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

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

/branches/sql-cleanup

First round of SQL cleanup and fixes - IPDB.pm

  • Property svn:keywords set to Date Rev Author
File size: 17.6 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-01 22:43:34 +0000 (Tue, 01 Feb 2005) $
6# SVN revision $Rev: 147 $
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 if ($type =~ /^.p$/) {
254 $msg = "Could not initialize IPs in new $disp_alloctypes{$type} pool $cidr";
255 initPool($dbh,$cidr,$type,$city,($type eq 'dp' ? "all" : "normal"));
256 }
257
258 } # routing vs non-routing netblock
259
260 $dbh->commit;
261 }; # end of eval
262 if ($@) {
263 $msg = $@;
264 eval { $dbh->rollback; };
265 return ('FAIL',$@);
266 } else {
267 return ('OK',"OK");
268 }
269
270 } else { # cidr != alloc_from
271
272 # Hard case. Allocation is smaller than free block.
273 my $wantmaskbits = $cidr->masklen;
274 my $maskbits = $alloc_from->masklen;
275
276 my @newfreeblocks; # Holds free blocks generated from splitting the source freeblock.
277
278 # This determines which blocks will be left "free" after allocation. We take the
279 # block we're allocating from, and split it in half. We see which half the wanted
280 # block is in, and repeat until the wanted block is equal to one of the halves.
281 my $i=0;
282 my $tmp_from = $alloc_from; # So we don't munge $alloc_from
283 while ($maskbits++ < $wantmaskbits) {
284 my @subblocks = $tmp_from->split($maskbits);
285 $newfreeblocks[$i++] = (($cidr->within($subblocks[0])) ? $subblocks[1] : $subblocks[0]);
286 $tmp_from = ( ($cidr->within($subblocks[0])) ? $subblocks[0] : $subblocks[1] );
287 } # while
288
289 # Begin SQL transaction block
290 eval {
291 $msg = "Unable to allocate $cidr as '$disp_alloctypes{$type}'";
292
293 # Delete old freeblocks entry
294 $sth = $dbh->prepare("delete from freeblocks where cidr='$alloc_from'");
295 $sth->execute();
296
297 # now we have to do some magic for routing blocks
298 if ($type eq 'rr') {
299
300 # Insert the new freeblocks entries
301 # Note that non-routed blocks are assigned to <NULL>
302 # and use the default value for the routed column ('n')
303 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city)".
304 " values (?, ?, '<NULL>')");
305 foreach my $block (@newfreeblocks) {
306 $sth->execute("$block", $block->masklen);
307 }
308
309 # Insert the entry in the routed table
310 $sth = $dbh->prepare("insert into routed (cidr,maskbits,city)".
311 " values ('$cidr',".$cidr->masklen.",'$city')");
312 $sth->execute;
313 # Insert the (almost) same entry in the freeblocks table
314 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
315 " values ('$cidr',".$cidr->masklen.",'$city','y')");
316 $sth->execute;
317
318 } else { # done with alloctype == rr
319
320 # Insert the new freeblocks entries
321 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
322 " values (?, ?, (select city from routed where cidr >>= '$cidr'),'y')");
323 foreach my $block (@newfreeblocks) {
324 $sth->execute("$block", $block->masklen);
325 }
326
327 # Insert the allocations entry
328 $sth = $dbh->prepare("insert into allocations (cidr,custid,type,city,".
329 "description,notes,maskbits,circuitid)".
330 " values ('$cidr','$custid','$type','$city','$desc','$notes',".
331 $cidr->masklen.",'$circid')");
332 $sth->execute;
333
334 # And initialize the pool, if necessary
335 if ($type =~ /^.p$/) {
336 $msg = "Could not initialize IPs in new $disp_alloctypes{$type} $cidr";
337 initPool($dbh,$cidr,$type,$city,($type eq 'dp' ? "all" : "normal"));
338 }
339
340 } # done with netblock alloctype != rr
341
342 $dbh->commit;
343 }; # end eval
344 if ($@) {
345 eval { $dbh->rollback; };
346 return ('FAIL',$msg);
347 } else {
348 return ('OK',"OK");
349 }
350
351 } # end fullcidr != alloc_from
352
353 } # end static-IP vs netblock allocation
354
355} # end allocateBlock()
356
357
358## IPDB::initPool()
359# Initializes a pool
360# Requires a database handle, the pool CIDR, type, city, and a parameter
361# indicating whether the pool should allow allocation of literally every
362# IP, or if it should reserve network/gateway/broadcast IPs
363# Note that this is NOT done in a transaction, that's why it's a private
364# function and should ONLY EVER get called from allocateBlock()
365sub initPool {
366 my ($dbh,undef,$type,$city,$class) = @_;
367 my $pool = new NetAddr::IP $_[1];
368
369 my ($pooltype) = ($type =~ /^(.)p$/);
370 my $sth;
371
372 # have to insert all pool IPs into poolips table as "unallocated".
373 $sth = $dbh->prepare("insert into poolips (pool,ip,custid,city,ptype)".
374 " values ('$pool', ?, '6750400', '$city', '$pooltype'");
375 my @poolip_list = $pool->hostenum;
376 if ($class eq 'all') { # (DSL-ish block - *all* IPs available
377 $sth->execute($pool->addr);
378 for (my $i=0; $i<=$#poolip_list; $i++) {
379 $sth->execute($poolip_list[$i]->addr);
380 }
381 $pool--;
382 $sth->execute($pool->addr);
383 } else { # (real netblock)
384 for (my $i=1; $i<=$#poolip_list; $i++) {
385 $sth->execute($poolip_list[$i]->addr);
386 }
387 }
388} # end initPool()
389
390
391## IPDB::deleteBlock()
392# Removes an allocation from the database, including deleting IPs
393# from poolips and recombining entries in freeblocks if possible
394# Also handles "deleting" a static IP allocation, and removal of a master
395# Requires a database handle, the block to delete, and the type of block
396sub deleteBlock {
397 my ($dbh,undef,$type) = @_;
398 my $cidr = new NetAddr::IP $_[1];
399
400 my $sth;
401
402 # To contain the error message, if any.
403 my $msg = "Unknown error deallocating $type $cidr";
404 # Enable transactions and exception-on-errors... but only for this sub
405 local $dbh->{AutoCommit} = 0;
406 local $dbh->{RaiseError} = 1;
407
408 # First case. The "block" is a static IP
409 # Note that we still need some additional code in the odd case
410 # of a netblock-aligned contiguous group of static IPs
411 if ($type =~ /^.i$/) {
412
413 eval {
414 $msg = "Unable to deallocate $type $cidr";
415 $sth = $dbh->prepare("update poolips set custid='6750400',available='y',".
416 "city=(select city from allocations where cidr >>= '$cidr'),".
417 "description='',notes='',circuitid='' where ip='$cidr'");
418 $sth->execute;
419 $dbh->commit;
420 };
421 if ($@) {
422 eval { $dbh->rollback; };
423 return ('FAIL',$msg);
424 } else {
425 return ('OK',"OK");
426 }
427
428 } elsif ($type eq 'mm') { # end alloctype =~ /.i/
429
430 $msg = "Unable to delete master block $cidr";
431 eval {
432 $sth = $dbh->prepare("delete from masterblocks where cidr='$cidr'");
433 $sth->execute;
434 $sth = $dbh->prepare("delete from freeblocks where cidr='$cidr'");
435 $sth->execute;
436 $dbh->commit;
437 };
438 if ($@) {
439 eval { $dbh->rollback; };
440 return ('FAIL', $msg);
441 } else {
442 return ('OK',"OK");
443 }
444
445 } else { # end alloctype master block case
446
447 ## This is a big block; but it HAS to be done in a chunk. Any removal
448 ## of a netblock allocation may result in a larger chunk of free
449 ## contiguous IP space - which may in turn be combined into a single
450 ## netblock rather than a number of smaller netblocks.
451
452 eval {
453
454 if ($type eq 'rr') {
455 $msg = "Unable to remove routing allocation $cidr";
456 $sth = $dbh->prepare("delete from routed where cidr='$cidr'");
457 $sth->execute;
458 # Make sure block getting deleted is properly accounted for.
459 $sth = $dbh->prepare("update freeblocks set routed='n',city='<NULL>'".
460 " where cidr='$cidr'");
461 $sth->execute;
462 # Set up query to start compacting free blocks.
463 $sth = $dbh->prepare("select cidr from freeblocks where ".
464 "maskbits<=".$cidr->masklen." and routed='n' order by maskbits desc");
465
466 } else { # end alloctype routing case
467
468 $sth = $dbh->prepare("delete from allocations where cidr='$cidr'");
469 $sth->execute;
470 # Special case - delete pool IPs
471 if ($type =~ /^.p$/) {
472 # We have to delete the IPs from the pool listing.
473 $sth = $dbh->prepare("delete from poolips where pool='$cidr'");
474 $sth->execute;
475 }
476
477 # Set up query for compacting free blocks.
478 $sth = $dbh->prepare("select cidr from freeblocks where cidr <<= ".
479 "(select cidr from routed where cidr >>= '$cidr') ".
480 " and maskbits<=".$cidr->masklen." and routed='y' order by maskbits desc");
481
482 } # end alloctype general case
483
484 # Now we look for larger-or-equal-sized free blocks in the same master (routed)
485 # (super)block. If there aren't any, we can't combine blocks anyway. If there
486 # are, we check to see if we can combine blocks.
487 # Execute the statement prepared in the if-else above.
488
489 $sth->execute;
490
491# NetAddr::IP->compact() attempts to produce the smallest inclusive block
492# from the caller and the passed terms.
493# EG: if you call $cidr->compact($ip1,$ip2,$ip3) when $cidr, $ip1, $ip2,
494# and $ip3 are consecutive /27's starting on .0 (.0-.31, .32-.63,
495# .64-.95, and .96-.128), you will get an array containing a single
496# /25 as element 0 (.0-.127). Order is not important; you could have
497# $cidr=.32/27, $ip1=.96/27, $ip2=.0/27, and $ip3=.64/27.
498
499 my (@together, @combinelist);
500 my $i=0;
501 while (my @data = $sth->fetchrow_array) {
502 my $testIP = new NetAddr::IP $data[0];
503 @together = $testIP->compact($cidr);
504 my $num = @together;
505 if ($num == 1) {
506 $cidr = $together[0];
507 $combinelist[$i++] = $testIP;
508 }
509 }
510
511 # Clear old freeblocks entries - if any. $i==0 if not.
512 if ($i>0) {
513 $sth = $dbh->prepare("delete from freeblocks where cidr=?");
514 foreach my $block (@combinelist) {
515 $sth->execute("$block");
516 }
517 }
518
519 # insert "new" freeblocks entry
520 if ($type eq 'rr') {
521 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city)".
522 " values ('$cidr',".$cidr->masklen.",'<NULL>')");
523 } else {
524 $sth = $dbh->prepare("insert into freeblocks (cidr,maskbits,city,routed)".
525 " values ('$cidr',".$cidr->masklen.
526 ",(select city from routed where cidr >>= '$cidr'),'y')");
527 }
528 $sth->execute;
529
530 # If we got here, we've succeeded. Whew!
531 $dbh->commit;
532 }; # end eval
533 if ($@) {
534 eval { $dbh->rollback; };
535 return ('FAIL', $msg);
536 } else {
537 return ('OK',"OK");
538 }
539
540 } # end alloctype != netblock
541
542} # end deleteBlock()
543
544
545## IPDB::mailNotify()
546# Sends notification mail to recipients regarding an IPDB operation
547sub mailNotify ($$$) {
548 my ($recip,$subj,$message) = @_;
549 my $mailer = Net::SMTP->new("smtp.example.com", Hello => "ipdb.example.com");
550
551 $mailer->mail('ipdb@example.com');
552 $mailer->to($recip);
553 $mailer->data("From: \"IP Database\" <ipdb\@example.com>\n",
554 "To: $recip\n",
555 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
556 "Subject: {IPDB} $subj\n",
557 "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
558 "Organization: Example Corp\n",
559 "\n$message\n");
560 $mailer->quit;
561}
562
563# Indicates module loaded OK. Required by Perl.
5641;
Note: See TracBrowser for help on using the repository browser.