source: branches/sql-cleanup/cgi-bin/IPDB.pm@ 149

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

/branches/sql-cleanup

Fixed a bunch of general problems with pool allocations, and
rearranged some code, alloctypes, and the poolips table (ugh)
to more cleanly support different types of IP pool.

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