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

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

/trunk

Redesigned error handling in allocateBlock() to return more useful
error messages than DBI provides

File size: 10.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$
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 &mailNotify);
25
26@EXPORT = (); # Export nothing by default.
27%EXPORT_TAGS = ( ALL => [qw( &initIPDBGlocals &connectDB &finish &checkDBSanity
28 &allocateBlock &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,0);
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,0);
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::mailNotify()
340# Sends notification mail to recipients regarding an IPDB operation
341sub mailNotify ($$$) {
342 my ($recip,$subj,$message) = @_;
343 my $mailer = Net::SMTP->new("smtp.example.com", Hello => "ipdb.example.com");
344
345 $mailer->mail('ipdb@example.com');
346 $mailer->to($recip);
347 $mailer->data("From: \"IP Database\" <ipdb\@example.com>\n",
348 "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
349 "Subject: {IPDB} $subj\n",
350 "X-Mailer: IPDB Notify v".sprintf("%.1d",$IPDB::VERSION)."\n",
351 "Organization: Example Corp\n",
352 "\n$message\n");
353 $mailer->quit;
354}
355
356# Indicates module loaded OK. Required by Perl.
3571;
Note: See TracBrowser for help on using the repository browser.