source: trunk/cgi-bin/IPDB.pm@ 96

Last change on this file since 96 was 96, checked in by Kris Deugau, 19 years ago

/trunk

Added city and POP list initialization

  • Property svn:keywords set to Date Rev Author
File size: 16.2 KB
Line 
1# ipdb/cgi-bin/IPDB.pm
2# Contains functions for IPDB - database access, subnet mangling, block allocation, etc
3###
4# SVN revision info
5# $Date: 2004-12-01 20:53:28 +0000 (Wed, 01 Dec 2004) $
6# SVN revision $Rev: 96 $
7# Last update by $Author: kdeugau $
8###
9# Copyright (C) 2004 - Kris Deugau
10
11package IPDB;
12
13use strict;
14use warnings;
15use Exporter;
16use DBI;
17use Net::SMTP;
18use POSIX;
19use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
20
21$VERSION = 2.0;
22@ISA = qw(Exporter);
23@EXPORT_OK = qw(&initIPDBGlocals &connectDB &finish &checkDBSanity &allocateBlock
24 &deleteBlock &mailNotify);
25
26@EXPORT = (); # Export nothing by default.
27%EXPORT_TAGS = ( ALL => [qw( &initIPDBGlocals &connectDB &finish &checkDBSanity
28 &allocateBlock &deleteBlock &mailNotify)]
29 );
30
31##
32## Global variables
33##
34our %disp_alloctypes;
35our %list_alloctypes;
36our @citylist;
37our @poplist;
38
39# Let's initialize the globals.
40## IPDB::initIPDBGlobals()
41# Initialize all globals. Takes a database handle, returns a success or error code
42sub initIPDBGlobals {
43 my $dbh = $_[0];
44 my $sth;
45
46 # Initialize alloctypes list
47 $sth = $dbh->prepare("select type,dispname from alloctypes");
48 $sth->execute;
49 return (undef,$sth->errstr) if $sth->err;
50 while (my @data = $sth->fetchrow_array) {
51 $disp_alloctypes{$data[0]} = $data[1];
52 }
53
54 # City and POP listings
55 $sth = $dbh->prepare("select * from cities");
56 $sth->execute;
57 return (undef,$sth->errstr) if $sth->err;
58 my $i = 0;
59 my $j = 0;
60 while (my @data = $sth->fetchrow_array) {
61 $citylist[$i++] = $data[0];
62 if ($data[1] eq 'y') {
63 $poplist[$j++] = $data[0];
64 }
65 }
66
67 return (1,"OK");
68} # end initIPDBGlobals
69
70
71## IPDB::connectDB()
72# Creates connection to IPDB.
73# Requires the database name, username, and password.
74# Returns a handle to the db.
75# Set up for a PostgreSQL db; could be any transactional DBMS with the
76# right changes.
77# This definition should be sub connectDB($$$) to be technically correct,
78# but this breaks. GRR.
79sub connectDB {
80 my ($dbname,$user,$pass) = @_;
81 my $dbh;
82 my $DSN = "DBI:Pg:dbname=$dbname";
83# my $user = 'ipdb';
84# my $pw = 'ipdbpwd';
85
86# Note that we want to autocommit by default, and we will turn it off locally as necessary.
87# We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
88 $dbh = DBI->connect($DSN, $user, $pass, {
89 AutoCommit => 1,
90 PrintError => 0
91 })
92 or return (undef, $DBI::errstr) if(!$dbh);
93
94# Return here if we can't select. Note that this indicates a
95# problem executing the select.
96 my $sth = $dbh->prepare('select cidr from masterblocks');
97 $sth->execute();
98 return (undef,$DBI::errstr) if ($sth->err);
99
100# See if the select returned anything (or null data). This should
101# succeed if the select executed, but...
102 $sth->fetchrow();
103 return (undef,$DBI::errstr) if ($sth->err);
104
105# If we get here, we should be OK.
106 return ($dbh,"DB connection OK");
107} # end connectDB
108
109
110## IPDB::finish()
111# Cleans up after database handles and so on.
112# Requires a database handle
113sub finish {
114 my $dbh = $_[0];
115 $dbh->disconnect;
116} # end finish
117
118
119# Quick check to see if the db is responding. A full integrity
120# check will have to be a separate tool to walk the IP allocation trees.
121sub checkDBSanity {
122 my $dbh = connectDB();
123
124 if (!$dbh) {
125 print "Cannot connect to the database!";
126 } else {
127 # it connects, try a stmt.
128 my $sth = $dbh->prepare('select cidr from masterblocks');
129 my $err = $sth->execute();
130
131 if ($sth->fetchrow()) {
132 # all is well.
133 return 1;
134 } else {
135 print "Connected to the database, but could not execute test statement. ".$sth->errstr();
136 }
137 }
138 # Clean up after ourselves.
139 $dbh->disconnect;
140} # end checkDBSanity
141
142
143## IPDB::allocateBlock()
144# Does all of the magic of actually allocating a netblock
145# Requires database handle, block to allocate, custid, type, city,
146# description, notes, circuit ID, block to allocate from,
147# Returns a success code and optional error message.
148sub allocateBlock {
149 my ($dbh,undef,undef,$custid,$type,$city,$desc,$notes,$circid) = @_;
150
151 my $cidr = new NetAddr::IP $_[1];
152 my $alloc_from = new NetAddr::IP $_[2];
153 my $sth;
154
155 # To contain the error message, if any.
156 my $msg = "Unknown error allocating $cidr as '$type'";
157
158 # Enable transactions and error handling
159 local $dbh->{AutoCommit} = 0; # These need to be local so we don't
160 local $dbh->{RaiseError} = 1; # step on our toes by accident.
161
162 if ($type =~ /^[cdsmw]i$/) {
163 $msg = "Unable to assign static IP $cidr to $custid";
164 eval {
165 # We'll just have to put up with the oddities caused by SQL (un)sort order
166 $sth = $dbh->prepare("select * from poolips where pool='$alloc_from'".
167 " and available='y' order by ip");
168 $sth->execute;
169
170# update poolips set custid='$custid',city='$city',available='n',
171# description='$desc',notes='$notes',circuitid='$circid'
172# where ip=(select ip from poolips where pool='$alloc_from'
173# and available='y' order by ip limit 1);
174##err Need better handling here; what if there's no free IPs when this sub gets called?
175 my @data = $sth->fetchrow_array;
176 my $cidr = $data[1];
177
178 $sth = $dbh->prepare("update poolips set custid='$custid',".
179 "city='$city',available='n',description='$desc',notes='$notes'".
180 "circuitid='$circid'".
181 " where ip='$cidr'");
182 $sth->execute;
183 $dbh->commit;
184 };
185 if ($@) {
186 eval { $dbh->rollback; };
187 return ('FAIL',$msg);
188 } else {
189 return ('OK',"OK");
190 }
191
192 } else { # end IP-from-pool allocation
193
194 if ($cidr == $alloc_from) {
195 # Easiest case- insert in one table, delete in the other, and go home. More or less.
196 # insert into allocations values (cidr,custid,type,city,desc) and
197 # delete from freeblocks where cidr='cidr'
198 # For data safety on non-transaction DBs, we delete first.
199
200 eval {
201 $msg = "Unable to allocate $cidr as '$disp_alloctypes{$type}'";
202 if ($type eq 'rr') {
203 $sth = $dbh->prepare("update freeblocks set routed='y',city='$city'".
204 " where cidr='$cidr'");
205 $sth->execute;
206 $sth = $dbh->prepare("insert into routed values ('$cidr',".
207 $cidr->masklen.",'$city')");
208 $sth->execute;
209 } else {
210 # common stuff for end-use, dialup, dynDSL, pools, etc, etc.
211 $sth = $dbh->prepare("delete from freeblocks where cidr='$cidr'");
212 $sth->execute;
213
214 $sth = $dbh->prepare("insert into allocations values ('$cidr',".
215 "'$custid','$type','$city','$desc','$notes',".
216 $cidr->masklen.",'$circid')");
217 $sth->execute;
218
219 # And initialize the pool, if necessary
220 if ($type =~ /^.p$/) {
221 $msg = "Could not initialize IPs in new $disp_alloctypes{$type} pool $cidr";
222 initPool($dbh,$cidr,$type,$city,($type eq 'dp' ? "all" : "normal"));
223 }
224
225 } # routing vs non-routing netblock
226
227 $dbh->commit;
228 }; # end of eval
229 if ($@) {
230 $msg = $@;
231 eval { $dbh->rollback; };
232 return ('FAIL',$@);
233 } else {
234 return ('OK',"OK");
235 }
236
237 } else { # cidr != alloc_from
238
239 # Hard case. Allocation is smaller than free block.
240 my $wantmaskbits = $cidr->masklen;
241 my $maskbits = $alloc_from->masklen;
242
243 my @newfreeblocks; # Holds free blocks generated from splitting the source freeblock.
244
245 # This determines which blocks will be left "free" after allocation. We take the
246 # block we're allocating from, and split it in half. We see which half the wanted
247 # block is in, and repeat until the wanted block is equal to one of the halves.
248 my $i=0;
249 my $tmp_from = $alloc_from; # So we don't munge $alloc_from
250 while ($maskbits++ < $wantmaskbits) {
251 my @subblocks = $tmp_from->split($maskbits);
252 $newfreeblocks[$i++] = (($cidr->within($subblocks[0])) ? $subblocks[1] : $subblocks[0]);
253 $tmp_from = ( ($cidr->within($subblocks[0])) ? $subblocks[0] : $subblocks[1] );
254 } # while
255
256 # Begin SQL transaction block
257 eval {
258 $msg = "Unable to allocate $cidr as '$disp_alloctypes{$type}'";
259
260 # Delete old freeblocks entry
261 $sth = $dbh->prepare("delete from freeblocks where cidr='$alloc_from'");
262 $sth->execute();
263
264 # now we have to do some magic for routing blocks
265 if ($type eq 'rr') {
266
267 # Insert the new freeblocks entries
268 # Note that non-routed blocks are assigned to <NULL>
269 $sth = $dbh->prepare("insert into freeblocks values (?, ?, '<NULL>','n')");
270 foreach my $block (@newfreeblocks) {
271 $sth->execute("$block", $block->masklen);
272 }
273
274 # Insert the entry in the routed table
275 $sth = $dbh->prepare("insert into routed values ('$cidr',".
276 $cidr->masklen.",'$city')");
277 $sth->execute;
278 # Insert the (almost) same entry in the freeblocks table
279 $sth = $dbh->prepare("insert into freeblocks values ('$cidr',".
280 $cidr->masklen.",'$city','y')");
281 $sth->execute;
282
283 } else { # done with alloctype == rr
284
285 # Insert the new freeblocks entries
286 $sth = $dbh->prepare("insert into freeblocks values (?, ?, ".
287 "(select city from routed where cidr >>= '$cidr'),'y')");
288 foreach my $block (@newfreeblocks) {
289 $sth->execute("$block", $block->masklen);
290 }
291
292 # Insert the allocations entry
293 $sth = $dbh->prepare("insert into allocations values ('$cidr',".
294 "'$custid','$type','$city','$desc','$notes',".$cidr->masklen.
295 ",'$circid')");
296 $sth->execute;
297
298 # And initialize the pool, if necessary
299 if ($type =~ /^.p$/) {
300 $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
301 initPool($dbh,$cidr,$type,$city,($type eq 'dp' ? "all" : "normal"));
302 }
303
304 } # done with netblock alloctype != rr
305
306 $dbh->commit;
307 }; # end eval
308 if ($@) {
309 eval { $dbh->rollback; };
310 return ('FAIL',$msg);
311 } else {
312 return ('OK',"OK");
313 }
314
315 } # end fullcidr != alloc_from
316
317 } # end static-IP vs netblock allocation
318
319} # end allocateBlock()
320
321
322## IPDB::initPool()
323# Initializes a pool
324# Requires a database handle, the pool CIDR, type, city, and a parameter
325# indicating whether the pool should allow allocation of literally every
326# IP, or if it should reserve network/gateway/broadcast IPs
327# Note that this is NOT done in a transaction, that's why it's a private
328# function and should ONLY EVER get called from allocateBlock()
329sub initPool {
330 my ($dbh,undef,$type,$city,$class) = @_;
331 my $pool = new NetAddr::IP $_[1];
332
333 my ($pooltype) = ($type =~ /^(.)p$/);
334 my $sth;
335
336 # have to insert all pool IPs into poolips table as "unallocated".
337 $sth = $dbh->prepare("insert into poolips values ('$pool',".
338 " ?, '6750400', '$city', '$pooltype', 'y', '', '', '')");
339 my @poolip_list = $pool->hostenum;
340 if ($class eq 'all') { # (DSL-ish block - *all* IPs available
341 $sth->execute($pool->addr);
342 for (my $i=0; $i<=$#poolip_list; $i++) {
343 $sth->execute($poolip_list[$i]->addr);
344 }
345 $pool--;
346 $sth->execute($pool->addr);
347 } else { # (real netblock)
348 for (my $i=1; $i<=$#poolip_list; $i++) {
349 $sth->execute($poolip_list[$i]->addr);
350 }
351 }
352} # end initPool()
353
354
355## IPDB::deleteBlock()
356# Removes an allocation from the database, including deleting IPs
357# from poolips and recombining entries in freeblocks if possible
358# Also handles "deleting" a static IP allocation, and removal of a master
359# Requires a database handle, the block to delete, and the type of block
360sub deleteBlock {
361 my ($dbh,undef,$type) = @_;
362 my $cidr = new NetAddr::IP $_[1];
363
364 my $sth;
365
366 # To contain the error message, if any.
367 my $msg = "Unknown error deallocating $type $cidr";
368 # Enable transactions and exception-on-errors... but only for this sub
369 local $dbh->{AutoCommit} = 0;
370 local $dbh->{RaiseError} = 1;
371
372 # First case. The "block" is a static IP
373 # Note that we still need some additional code in the odd case
374 # of a netblock-aligned contiguous group of static IPs
375 if ($type =~ /^.i$/) {
376
377 eval {
378 $msg = "Unable to deallocate $type $cidr";
379 $sth = $dbh->prepare("update poolips set custid='6750400',available='y',".
380 "city=(select city from allocations ".
381 "where cidr=(select pool from poolips where ip='$cidr')),".
382 "description='',notes='',circuitid='' where ip='$cidr'");
383 $sth->execute;
384 $dbh->commit;
385 };
386 if ($@) {
387 eval { $dbh->rollback; };
388 return ('FAIL',$msg);
389 } else {
390 return ('OK',"OK");
391 }
392
393 } elsif ($type eq 'mm') { # end alloctype =~ /.i/
394
395 $msg = "Unable to delete master block $cidr";
396 eval {
397 $sth = $dbh->prepare("delete from masterblocks where cidr='$cidr'");
398 $sth->execute;
399 $sth = $dbh->prepare("delete from freeblocks where cidr='$cidr'");
400 $sth->execute;
401 $dbh->commit;
402 };
403 if ($@) {
404 eval { $dbh->rollback; };
405 return ('FAIL', $msg);
406 } else {
407 return ('OK',"OK");
408 }
409
410 } else { # end alloctype master block case
411
412 ## This is a big block; but it HAS to be done in a chunk. Any removal
413 ## of a netblock allocation may result in a larger chunk of free
414 ## contiguous IP space - which may in turn be combined into a single
415 ## netblock rather than a number of smaller netblocks.
416
417 eval {
418
419 if ($type eq 'rr') {
420 $msg = "Unable to remove routing allocation $cidr";
421 $sth = $dbh->prepare("delete from routed where cidr='$cidr'");
422 $sth->execute;
423 # Make sure block getting deleted is properly accounted for.
424 $sth = $dbh->prepare("update freeblocks set routed='n',city='<NULL>'".
425 " where cidr='$cidr'");
426 $sth->execute;
427 # Set up query to start compacting free blocks.
428 $sth = $dbh->prepare("select * from freeblocks where ".
429 "maskbits<=".$cidr->masklen." and routed='n' order by maskbits desc");
430
431 } else { # end alloctype routing case
432
433 $sth = $dbh->prepare("delete from allocations where cidr='$cidr'");
434 $sth->execute;
435 # Special case - delete pool IPs
436 if ($type =~ /^.p$/) {
437 # We have to delete the IPs from the pool listing.
438 $sth = $dbh->prepare("delete from poolips where pool='$cidr'");
439 $sth->execute;
440 }
441
442 # Set up query for compacting free blocks.
443 $sth = $dbh->prepare("select * from freeblocks where cidr << ".
444 "(select cidr from routed where cidr >> '$cidr') ".
445 " and maskbits<=".$cidr->masklen." and routed='y' order by maskbits desc");
446
447 } # end alloctype general case
448
449 # Now we look for larger-or-equal-sized free blocks in the same master (routed)
450 # (super)block. If there aren't any, we can't combine blocks anyway. If there
451 # are, we check to see if we can combine blocks.
452 # Execute the statement prepared in the if-else above.
453
454 $sth->execute;
455
456# NetAddr::IP->compact() attempts to produce the smallest inclusive block
457# from the caller and the passed terms.
458# EG: if you call $cidr->compact($ip1,$ip2,$ip3) when $cidr, $ip1, $ip2,
459# and $ip3 are consecutive /27's starting on .0 (.0-.31, .32-.63,
460# .64-.95, and .96-.128), you will get an array containing a single
461# /25 as element 0 (.0-.127). Order is not important; you could have
462# $cidr=.32/27, $ip1=.96/27, $ip2=.0/27, and $ip3=.64/27.
463
464 my (@together, @combinelist);
465 my $i=0;
466 while (my @data = $sth->fetchrow_array) {
467 my $testIP = new NetAddr::IP $data[0];
468 @together = $testIP->compact($cidr);
469 my $num = @together;
470 if ($num == 1) {
471 $cidr = $together[0];
472 $combinelist[$i++] = $testIP;
473 }
474 }
475
476 # Clear old freeblocks entries - if any. $i==0 if not.
477 if ($i>0) {
478 $sth = $dbh->prepare("delete from freeblocks where cidr=?");
479 foreach my $block (@combinelist) {
480 $sth->execute("$block");
481 }
482 }
483
484 # insert "new" freeblocks entry
485 if ($type eq 'rr') {
486 $sth = $dbh->prepare("insert into freeblocks values ('$cidr',".$cidr->masklen.
487 ",'<NULL>','n')");
488 } else {
489 $sth = $dbh->prepare("insert into freeblocks values ('$cidr',".$cidr->masklen.
490 ",(select city from routed where cidr >>= '$cidr'),'y')");
491 }
492 $sth->execute;
493
494 # If we got here, we've succeeded. Whew!
495 $dbh->commit;
496 }; # end eval
497 if ($@) {
498 eval { $dbh->rollback; };
499 return ('FAIL', $msg);
500 } else {
501 return ('OK',"OK");
502 }
503
504 } # end alloctype != netblock
505
506} # end deleteBlock()
507
508
509## IPDB::mailNotify()
510# Sends notification mail to recipients regarding an IPDB operation
511sub mailNotify ($$$) {
512 my ($recip,$subj,$message) = @_;
513 my $mailer = Net::SMTP->new("smtp.example.com", Hello => "ipdb.example.com");
514
515 $mailer->mail('ipdb@example.com');
516 $mailer->to($recip);
517 $mailer->data("From: \"IP Database\" <ipdb\@example.com>\n",
518 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
519 "Subject: {IPDB} $subj\n",
520 "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
521 "Organization: Example Corp\n",
522 "\n$message\n");
523 $mailer->quit;
524}
525
526# Indicates module loaded OK. Required by Perl.
5271;
Note: See TracBrowser for help on using the repository browser.