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

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

/trunk

Fix error reporting in allocateBlock() to return the SQL error
string as well as the "Can't do that" message on static IP allocations

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