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

Last change on this file since 93 was 93, checked in by Kris Deugau, 20 years ago

/trunk

Add deleteBlock() sub

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