1 | # ipdb/cgi-bin/IPDB.pm
|
---|
2 | # Contains functions for IPDB - database access, subnet mangling, block allocation, etc
|
---|
3 | ##
|
---|
4 | # $Id: IPDB.pm 947 2024-07-31 20:09:57Z kdeugau $
|
---|
5 | # Copyright (C) 2004-2018,2022-2024 - Kris Deugau <kdeugau@deepnet.cx>
|
---|
6 | #
|
---|
7 | # This program is free software: you can redistribute it and/or modify
|
---|
8 | # it under the terms of the GNU General Public License as published by
|
---|
9 | # the Free Software Foundation, either version 3 of the License, or
|
---|
10 | # (at your option) any later version.
|
---|
11 | #
|
---|
12 | # This program is distributed in the hope that it will be useful,
|
---|
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
|
---|
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
---|
15 | # GNU General Public License for more details.
|
---|
16 | #
|
---|
17 | # You should have received a copy of the GNU General Public License
|
---|
18 | # along with this program. If not, see <http://www.gnu.org/licenses/>.
|
---|
19 | ##
|
---|
20 |
|
---|
21 | package IPDB;
|
---|
22 |
|
---|
23 | use strict;
|
---|
24 | use warnings;
|
---|
25 | use Exporter;
|
---|
26 | use DBI;
|
---|
27 | use Net::SMTP;
|
---|
28 | use NetAddr::IP qw(:lower Compact );
|
---|
29 | use Frontier::Client;
|
---|
30 | use POSIX;
|
---|
31 | use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
|
---|
32 |
|
---|
33 | $VERSION = 3; ##VERSION##
|
---|
34 | @ISA = qw(Exporter);
|
---|
35 | @EXPORT_OK = qw(
|
---|
36 | %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist
|
---|
37 | %IPDBacl %merge_display %aclmsg %rpcacl $maxfcgi
|
---|
38 | $errstr
|
---|
39 | &initIPDBGlobals &connectDB &finish &checkDBSanity
|
---|
40 | &addVRF &getVRF &deleteVRF &addMaster &touchMaster
|
---|
41 | &listVRF &listSummary &listSubs &listContainers &listAllocations &listForMerge &listFree &listPool
|
---|
42 | &getMasterList &getTypeList &getPoolSelect &findAllocateFrom
|
---|
43 | &ipParent &subParent &blockParent &getBreadCrumbs &getRoutedCity
|
---|
44 | &allocateBlock &updateBlock &splitBlock &shrinkBlock &mergeBlocks &deleteBlock &getBlockData
|
---|
45 | &getBlockRDNS &getRDNSbyIP &getRevID
|
---|
46 | &getNodeList &getNodeName &getNodeInfo
|
---|
47 | &getBlockNotices
|
---|
48 | &mailNotify
|
---|
49 | );
|
---|
50 |
|
---|
51 | @EXPORT = (); # Export nothing by default.
|
---|
52 | %EXPORT_TAGS = ( ALL => [qw(
|
---|
53 | %disp_alloctypes %list_alloctypes %def_custids @citylist @poplist
|
---|
54 | %IPDBacl %merge_display %aclmsg %rpcacl $maxfcgi
|
---|
55 | $errstr
|
---|
56 | &initIPDBGlobals &connectDB &finish &checkDBSanity
|
---|
57 | &addVRF &getVRF &deleteVRF &addMaster &touchMaster
|
---|
58 | &listVRF &listSummary &listSubs &listContainers &listAllocations &listForMerge &listFree &listPool
|
---|
59 | &getMasterList &getTypeList &getPoolSelect &findAllocateFrom
|
---|
60 | &ipParent &subParent &blockParent &getBreadCrumbs &getRoutedCity
|
---|
61 | &allocateBlock &updateBlock &splitBlock &shrinkBlock &mergeBlocks &deleteBlock &getBlockData
|
---|
62 | &getBlockRDNS &getRDNSbyIP &getRevID
|
---|
63 | &getNodeList &getNodeName &getNodeInfo
|
---|
64 | &getBlockNotices
|
---|
65 | &mailNotify
|
---|
66 | )]
|
---|
67 | );
|
---|
68 |
|
---|
69 | ##
|
---|
70 | ## Global variables
|
---|
71 | ##
|
---|
72 | our %disp_alloctypes;
|
---|
73 | our %list_alloctypes;
|
---|
74 | our %def_custids;
|
---|
75 | our @citylist;
|
---|
76 | our @poplist;
|
---|
77 | our %IPDBacl;
|
---|
78 |
|
---|
79 | # Mapping hash for pooltype -> poolip-as-netblock conversions
|
---|
80 | my %poolmap = (sd => 'en', cd => 'cn', dp => 'cn', mp => 'cn', wp => 'cn', ld => 'in', ad => 'in', bd => 'in');
|
---|
81 |
|
---|
82 | # Backup fields, since we iterate over the set regularly
|
---|
83 | our @backupfields = qw(brand model type src user vpass epass port ip);
|
---|
84 |
|
---|
85 | # Friendly display strings for merge scopes
|
---|
86 | our %merge_display = (
|
---|
87 | keepall => "Keep mergeable allocations as suballocations of new block",
|
---|
88 | mergepeer => "Keep suballocations of mergeable allocations",
|
---|
89 | clearpeer => "Keep only suballocations of the selected block",
|
---|
90 | clearall => "Clear all suballocations"
|
---|
91 | );
|
---|
92 |
|
---|
93 | # mapping table for functional-area => error message
|
---|
94 | our %aclmsg = (
|
---|
95 | addmaster => 'add a master block',
|
---|
96 | addblock => 'add an allocation',
|
---|
97 | updateblock => 'update a block',
|
---|
98 | delblock => 'delete an allocation',
|
---|
99 | mergeblock => 'merge allocations',
|
---|
100 | );
|
---|
101 |
|
---|
102 | our %rpcacl;
|
---|
103 | our $maxfcgi = 3;
|
---|
104 |
|
---|
105 | # error reporting
|
---|
106 | our $errstr = '';
|
---|
107 |
|
---|
108 | our $org_name = 'Example Corp';
|
---|
109 | our $smtphost = 'smtp.example.com';
|
---|
110 | our $domain = 'example.com';
|
---|
111 | our $defcustid = '5554242';
|
---|
112 | our $smtpsender = 'ipdb@example.com';
|
---|
113 | # mostly for rwhois
|
---|
114 | ##fixme: leave these blank by default?
|
---|
115 | our $rwhoisDataPath = '/usr/local/rwhoisd/etc/rwhoisd'; # to match ./configure defaults from rwhoisd-1.5.9.6
|
---|
116 | our $org_street = '123 4th Street';
|
---|
117 | our $org_city = 'Anytown';
|
---|
118 | our $org_prov_state = 'ON';
|
---|
119 | our $org_pocode = 'H0H 0H0';
|
---|
120 | our $org_country = 'CA';
|
---|
121 | our $org_phone = '000-555-1234';
|
---|
122 | our $org_techhandle = 'ISP-ARIN-HANDLE';
|
---|
123 | our $org_email = 'noc@example.com';
|
---|
124 | our $hostmaster = 'dns@example.com';
|
---|
125 |
|
---|
126 | our $syslog_facility = 'local2';
|
---|
127 |
|
---|
128 | our $rpc_url = '';
|
---|
129 | our $dnsadmin_url; # needs to be modified later
|
---|
130 | our $revgroup = 1; # should probably be configurable somewhere
|
---|
131 | our $rpccount = 0;
|
---|
132 |
|
---|
133 | # Largest inverse CIDR mask length to show per-IP rDNS list
|
---|
134 | # (eg, NetAddr::IP->bits - NetAddr::IP->masklen)
|
---|
135 | our $maxrevlist = 5; # /27
|
---|
136 |
|
---|
137 | # Display the per-IP rDNS list on all block types even when it might not
|
---|
138 | # make sense (typically for IP pools, where the per-IP entries are available
|
---|
139 | # from each IP's edit page)
|
---|
140 | our $revlistalltypes = 0;
|
---|
141 |
|
---|
142 | # UI layout for subblocks/containers
|
---|
143 | our $sublistlayout = 1;
|
---|
144 |
|
---|
145 | # UI layout for VRF/master blocks
|
---|
146 | our $masterswithvrfs = 2;
|
---|
147 |
|
---|
148 | # VLAN validation mode. Set to 0 to allow alphanumeric vlan names instead of using the vlan number.
|
---|
149 | our $numeric_vlan = 1;
|
---|
150 |
|
---|
151 | # Billing system return link
|
---|
152 | our $billinglink = 'https://billing.example.com/radius.pl';
|
---|
153 |
|
---|
154 | # Append the default domain on unqualified DNS names?
|
---|
155 | our $append_domain = 1;
|
---|
156 |
|
---|
157 | # Enable link publishing selected IP pool data as a CSV
|
---|
158 | # Not enabled by default due to webserver config required
|
---|
159 | our $enablecsv = 0;
|
---|
160 |
|
---|
161 | ##
|
---|
162 | ## Internal utility functions
|
---|
163 | ##
|
---|
164 |
|
---|
165 | ## IPDB::_rpc
|
---|
166 | # Make an RPC call for DNS changes
|
---|
167 | sub _rpc {
|
---|
168 | return if !$rpc_url; # Just In Case
|
---|
169 | my $rpcsub = shift;
|
---|
170 | my %args = @_;
|
---|
171 |
|
---|
172 | # Make an object to represent the XML-RPC server.
|
---|
173 | my $server = Frontier::Client->new(url => $rpc_url, debug => 0);
|
---|
174 | my $result;
|
---|
175 |
|
---|
176 | my %rpcargs = (
|
---|
177 | rpcsystem => 'ipdb',
|
---|
178 | # must be provided by caller's caller
|
---|
179 | # rpcuser => $args{user},
|
---|
180 | %args,
|
---|
181 | );
|
---|
182 |
|
---|
183 | eval {
|
---|
184 | $result = $server->call("dnsdb.$rpcsub", %rpcargs);
|
---|
185 | };
|
---|
186 | if ($@) {
|
---|
187 | $errstr = $@;
|
---|
188 | $errstr =~ s/\s*$//;
|
---|
189 | $errstr =~ s/Fault returned from XML RPC Server, fault code 4: error executing RPC `dnsdb.$rpcsub'\.\s//;
|
---|
190 | }
|
---|
191 | $rpccount++;
|
---|
192 |
|
---|
193 | return $result if $result;
|
---|
194 | } # end _rpc()
|
---|
195 |
|
---|
196 |
|
---|
197 | ## IPDB::_compactFree()
|
---|
198 | # Utility sub to compact a set of free block entries down to the minimum possible set of CIDR entries
|
---|
199 | # Not to be called outside of an eval{}!
|
---|
200 | sub _compactFree {
|
---|
201 | my $dbh = shift;
|
---|
202 | my $parent = shift;
|
---|
203 |
|
---|
204 | # Rather than having the caller provide all the details
|
---|
205 | my $pinfo = getBlockData($dbh, $parent);
|
---|
206 | my $ftype = (split //, $pinfo->{type})[0];
|
---|
207 |
|
---|
208 | # NetAddr::IP->compact() attempts to produce the smallest inclusive block
|
---|
209 | # from the caller and the passed terms.
|
---|
210 | # EG: if you call $cidr->compact($ip1,$ip2,$ip3) when $cidr, $ip1, $ip2,
|
---|
211 | # and $ip3 are consecutive /27's starting on .0 (.0-.31, .32-.63,
|
---|
212 | # .64-.95, and .96-.128), you will get an array containing a single
|
---|
213 | # /25 as element 0 (.0-.127). Order is not important; you could have
|
---|
214 | # $cidr=.32/27, $ip1=.96/27, $ip2=.0/27, and $ip3=.64/27.
|
---|
215 |
|
---|
216 | ##fixme: vrf
|
---|
217 | ##fixme: simplify since all containers now represent different "layers"/"levels"?
|
---|
218 |
|
---|
219 | # set up the query to get the list of blocks to try to merge.
|
---|
220 | my $sth = $dbh->prepare(q{
|
---|
221 | SELECT cidr,id FROM freeblocks
|
---|
222 | WHERE parent_id = ?
|
---|
223 | ORDER BY masklen(cidr) DESC
|
---|
224 | });
|
---|
225 | $sth->execute($parent);
|
---|
226 |
|
---|
227 | my (@rawfb, @combinelist, %rawid);
|
---|
228 | my $i=0;
|
---|
229 | # for each free block under $parent, push a NetAddr::IP object into one list, and
|
---|
230 | # continuously use NetAddr::IP->compact to automagically merge netblocks as possible.
|
---|
231 | while (my ($fcidr, $fid) = $sth->fetchrow_array) {
|
---|
232 | my $testIP = new NetAddr::IP $fcidr;
|
---|
233 | push @rawfb, $testIP;
|
---|
234 | $rawid{"$testIP"} = $fid; # $data[0] vs "$testIP" *does* make a difference for v6
|
---|
235 | @combinelist = $testIP->compact(@combinelist);
|
---|
236 | }
|
---|
237 |
|
---|
238 | # now that we have the full list of "compacted" freeblocks, go back over
|
---|
239 | # the list of raw freeblocks, and delete the ones that got merged.
|
---|
240 | $sth = $dbh->prepare("DELETE FROM freeblocks WHERE id = ?");
|
---|
241 | foreach my $rawfree (@rawfb) {
|
---|
242 | next if grep { $rawfree == $_ } @combinelist; # skip if the raw block is in the compacted list
|
---|
243 | $sth->execute($rawid{$rawfree});
|
---|
244 | }
|
---|
245 |
|
---|
246 | # now we walk the new list of compacted blocks, and see which ones we need to insert
|
---|
247 | $sth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id) VALUES (?,?,?,?,?,?)");
|
---|
248 | foreach my $cme (@combinelist) {
|
---|
249 | next if grep { $cme == $_ } @rawfb; # skip if the combined block was in the raw list
|
---|
250 | $sth->execute($cme, $pinfo->{city}, $ftype, $pinfo->{vrf}, $parent, $pinfo->{master_id});
|
---|
251 | }
|
---|
252 |
|
---|
253 | } # end _compactFree()
|
---|
254 |
|
---|
255 |
|
---|
256 | ## IPDB::_toPool()
|
---|
257 | # Convert an allocation or allocation tree to entries in an IP pool
|
---|
258 | # Assumes an incomplete/empty pool
|
---|
259 | # Takes a parent ID for the pool, CIDR range descriptor for the allocation(s) to convert, and the pool type
|
---|
260 | sub _toPool {
|
---|
261 | my $dbh = shift;
|
---|
262 | my $poolparent = shift;
|
---|
263 | my $convblock = shift; # May be smaller than the block referenced by $poolparent
|
---|
264 | my $pooltype = shift;
|
---|
265 | my $retall = shift || 0;
|
---|
266 |
|
---|
267 | # there is probably a way to avoid the temporary $foo here
|
---|
268 | my $foo = $dbh->selectall_arrayref("SELECT master_id,parent_id FROM allocations WHERE id = ?", undef, $poolparent);
|
---|
269 | my ($master,$mainparent) = @{$foo->[0]};
|
---|
270 |
|
---|
271 | my @retlist;
|
---|
272 |
|
---|
273 | my $iptype = $pooltype;
|
---|
274 | $iptype =~ s/[pd]$/i/;
|
---|
275 | my $poolclass = (split //, $iptype)[0];
|
---|
276 |
|
---|
277 | my $cidrpool = new NetAddr::IP $convblock;
|
---|
278 |
|
---|
279 | my $asth = $dbh->prepare(q{
|
---|
280 | SELECT id, cidr, type, parent_id, city, description, notes, circuitid,
|
---|
281 | createstamp, modifystamp, privdata, custid, vrf, vlan, rdns
|
---|
282 | FROM allocations
|
---|
283 | WHERE cidr <<= ? AND master_id = ?
|
---|
284 | ORDER BY masklen(cidr) DESC
|
---|
285 | });
|
---|
286 | my $inssth = $dbh->prepare(q{
|
---|
287 | INSERT INTO poolips (
|
---|
288 | ip,type,parent_id,master_id,available,
|
---|
289 | city,description,notes,circuitid,createstamp,modifystamp,privdata,custid,vrf,vlan,rdns
|
---|
290 | )
|
---|
291 | VALUES (?,?,?,?,'n',?,?,?,?,?,?,?,?,?,?,?)
|
---|
292 | });
|
---|
293 | my $updsth = $dbh->prepare("UPDATE poolips SET parent_id = ?, type = ? WHERE parent_id = ?");
|
---|
294 | my $delsth = $dbh->prepare("DELETE FROM allocations WHERE id = ?");
|
---|
295 | my $fbdelsth = $dbh->prepare("DELETE FROM freeblocks WHERE parent_id = ?");
|
---|
296 |
|
---|
297 | $asth->execute($convblock, $master);
|
---|
298 | my %poolcounter;
|
---|
299 | while (my ($oldid, $oldcidr, $oldtype, $oldparent, @oldalloc) = $asth->fetchrow_array) {
|
---|
300 | # don't merge the parent of the allocation selected for merge.
|
---|
301 | # if you really want to go there, start the merge *from* that parent.
|
---|
302 | next if $oldid == $mainparent;
|
---|
303 | if ($oldtype =~ /.[enr]/) {
|
---|
304 | # Convert leaf allocations to block of pool IP assignments
|
---|
305 | my $tmpcidr = new NetAddr::IP $oldcidr;
|
---|
306 | my $newtype = $poolclass.'i';
|
---|
307 | # set up the gateway IP in case we need it
|
---|
308 | my $gw = $cidrpool+1;
|
---|
309 | foreach my $newip ($tmpcidr->split(32)) {
|
---|
310 | my $baseip = $newip->addr;
|
---|
311 | # skip .0 and .255, they are prefectly legitimate but some systems behave
|
---|
312 | # poorly talking to a client using them.
|
---|
313 | next if $baseip =~ /\.(?:0|255)$/;
|
---|
314 | # skip the network, broadcast, and gateway IPs if we're creating a "normal netblock" pool
|
---|
315 | if ($pooltype =~ /d$/) {
|
---|
316 | next if $newip->addr eq $cidrpool->network->addr;
|
---|
317 | next if $newip->addr eq $cidrpool->broadcast->addr;
|
---|
318 | next if $newip->addr eq $gw->addr;
|
---|
319 | }
|
---|
320 | $inssth->execute($newip, $newtype, $poolparent, $master, @oldalloc) if !$poolcounter{"$newip"};
|
---|
321 | $poolcounter{"$newip"}++;
|
---|
322 | }
|
---|
323 | } elsif ($oldtype =~ /.[dp]/) {
|
---|
324 | # Reparent IPs in an existing pool, and rewrite their type
|
---|
325 | $updsth->execute($poolparent, $poolclass.'i', $oldid);
|
---|
326 | } else {
|
---|
327 | # Containers are mostly "not interesting" in this context since they're
|
---|
328 | # equivalent to the pool allocation on .[dp] types. Clean up the lingering free block(s).
|
---|
329 | $fbdelsth->execute($oldid);
|
---|
330 | }
|
---|
331 | # Clean up - remove the converted block unless it is the "primary"
|
---|
332 | $delsth->execute($oldid) unless $oldid == $poolparent;
|
---|
333 | # Return the converted blocks, but only the immediate peers, not the entire tree
|
---|
334 | push @retlist, { block => $oldcidr, mdisp => $disp_alloctypes{$oldtype}, mtype => $oldtype }
|
---|
335 | if (($oldparent == $mainparent) || $retall) && $oldid != $poolparent;
|
---|
336 | } # while $asth->fetch
|
---|
337 |
|
---|
338 | return \@retlist;
|
---|
339 | } # end _toPool()
|
---|
340 |
|
---|
341 |
|
---|
342 | ## IPDB::_poolToAllocations
|
---|
343 | # Convert pool IPs into allocations, and free IPs into free blocks
|
---|
344 | # Takes a pool ID, original pool CIDR (in case the allocation has been updated before the call here)
|
---|
345 | # and hashref to data for the new parent container for the IPs,
|
---|
346 | # and an optional hash with the new parent ID and allocation type
|
---|
347 | sub _poolToAllocations {
|
---|
348 | my $dbh = shift;
|
---|
349 | my $oldpool = shift;
|
---|
350 | my $parentinfo = shift;
|
---|
351 | my %args = @_;
|
---|
352 |
|
---|
353 | # Default to converting the pool to a container
|
---|
354 | $args{newparent} = $oldpool->{id} if !$args{newparent};
|
---|
355 |
|
---|
356 | my ($containerclass) = ($parentinfo->{type} =~ /(.)./);
|
---|
357 |
|
---|
358 | # Default type mapping
|
---|
359 | $args{newtype} = $poolmap{$oldpool->{type}} if !$args{newtype};
|
---|
360 |
|
---|
361 | # Convert a bunch of pool IP allocations into "normal" netblock allocations
|
---|
362 | my $pool2alloc = $dbh->prepare(q{
|
---|
363 | INSERT INTO allocations (
|
---|
364 | cidr,type,city, description, notes, circuitid, createstamp, modifystamp,
|
---|
365 | privdata, custid, vrf, vlan, rdns, parent_id, master_id, userid
|
---|
366 | )
|
---|
367 | SELECT
|
---|
368 | ip, ? AS type, city, description, notes, circuitid, createstamp, modifystamp,
|
---|
369 | privdata, custid, vrf, vlan, rdns, ? AS parent_id, master_id, userid
|
---|
370 | FROM poolips
|
---|
371 | WHERE parent_id = ? AND available = 'n'
|
---|
372 | });
|
---|
373 | $pool2alloc->execute($args{newtype}, $args{newparent}, $oldpool->{id});
|
---|
374 |
|
---|
375 | # Snag the whole list of pool IPs
|
---|
376 | my @freeips = @{$dbh->selectall_arrayref("SELECT ip,available FROM poolips WHERE parent_id = ?",
|
---|
377 | undef, $oldpool->{id})};
|
---|
378 | my @iplist;
|
---|
379 | my %usedips;
|
---|
380 | # Filter out the ones that were used...
|
---|
381 | foreach my $ip (@freeips) {
|
---|
382 | $$ip[0] =~ s{/32$}{};
|
---|
383 | push @iplist, NetAddr::IP->new($$ip[0]) if $$ip[1] eq 'y';
|
---|
384 | $usedips{$$ip[0]}++ if $$ip[1] eq 'n';
|
---|
385 | }
|
---|
386 | # ... so that we can properly decide whether the net, gw, and bcast IPs need to be added to the free list.
|
---|
387 | my $tmpblock = new NetAddr::IP $oldpool->{block};
|
---|
388 | push @iplist, NetAddr::IP->new($tmpblock->network->addr)
|
---|
389 | if !$usedips{$tmpblock->network->addr} || $tmpblock->network->addr =~ /\.0$/;
|
---|
390 | push @iplist, NetAddr::IP->new($tmpblock->broadcast->addr)
|
---|
391 | if !$usedips{$tmpblock->broadcast->addr} || $tmpblock->broadcast->addr =~ /\.255$/;
|
---|
392 | # only "DHCP"-ish pools have a gw ip removed from the pool
|
---|
393 | if ($oldpool->{type} =~ /.d/) {
|
---|
394 | $tmpblock++;
|
---|
395 | push @iplist, NetAddr::IP->new($tmpblock->addr);
|
---|
396 | }
|
---|
397 |
|
---|
398 | # take the list of /32 IPs, and see what CIDR ranges we get back as free, then insert them.
|
---|
399 | @iplist = Compact(@iplist);
|
---|
400 | my $insfbsth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id) VALUES (?,?,?,?,?,?)");
|
---|
401 | foreach (@iplist) {
|
---|
402 | $insfbsth->execute($_, $parentinfo->{city}, $containerclass, $parentinfo->{vrf},
|
---|
403 | $args{newparent}, $parentinfo->{master_id});
|
---|
404 | }
|
---|
405 |
|
---|
406 | # and finally delete the poolips entries
|
---|
407 | $dbh->do("DELETE FROM poolips WHERE parent_id = ?", undef, $oldpool->{id});
|
---|
408 |
|
---|
409 | } # end _poolToAllocations()
|
---|
410 |
|
---|
411 |
|
---|
412 | ## IPDB::_deleteCascade()
|
---|
413 | # Internal sub. Deletes an allocation and all subcomponents
|
---|
414 | sub _deleteCascade {
|
---|
415 | my $dbh = shift;
|
---|
416 | my $id = shift;
|
---|
417 | my $createfb = shift; # may be null at this point
|
---|
418 |
|
---|
419 | my $binfo = getBlockData($dbh, $id);
|
---|
420 |
|
---|
421 | # Decide if we're going to add a free block.
|
---|
422 |
|
---|
423 | # Caller is normal block delete -> add freeblock under $binfo->{parent_id} -> pass nothing
|
---|
424 | # Caller is delete for merge to leaf -> do not add freeblock -> pass 0
|
---|
425 | # Caller is normal master delete -> do not add freeblock -> pass nothing
|
---|
426 | # Caller is merge master -> add freeblock under alternate parent -> pass parent ID
|
---|
427 | if ($binfo->{type} ne 'mm') {
|
---|
428 | # Deleting a non-master block
|
---|
429 | if (!defined($createfb)) {
|
---|
430 | # No createfb flag passed; assuming normal block delete. Add the freeblock
|
---|
431 | # under the parent of the block we're deleting.
|
---|
432 | $createfb = $binfo->{parent_id};
|
---|
433 | #} else {
|
---|
434 | # Don't need to actually do anything here. The caller has given us an ID,
|
---|
435 | # which is either 0 (causing no free block) or (theoretically) a valid block
|
---|
436 | # ID to add the free block under.
|
---|
437 | }
|
---|
438 | #} else {
|
---|
439 | # Deleting a master block
|
---|
440 | # Don't need to actually do anything here. If the caller passed a parent ID,
|
---|
441 | # that parent will get the new free block. if the caller didn't pass anything,
|
---|
442 | # no free block will be added.
|
---|
443 | }
|
---|
444 |
|
---|
445 | ##fixme: special-case master blocks up here and quickly delete based on master_id,
|
---|
446 | # instead of wasting time tracing parent relations
|
---|
447 |
|
---|
448 | # grab all allocations in the master within the CIDR of the block to be deleted
|
---|
449 | my %parents;
|
---|
450 | my %cidrlist;
|
---|
451 | ##fixme: limit by VRF?
|
---|
452 | my $sth = $dbh->prepare("SELECT cidr,id,parent_id FROM allocations WHERE cidr <<= ? AND master_id = ?");
|
---|
453 | $sth->execute($binfo->{block}, $binfo->{master_id});
|
---|
454 | while (my ($cidr, $cid, $pid) = $sth->fetchrow_array) {
|
---|
455 | $parents{$cid} = $pid;
|
---|
456 | $cidrlist{$cid} = $cidr;
|
---|
457 | }
|
---|
458 |
|
---|
459 | # Trace the parent relations up the tree until we either hit parent ID 0 (we've found a master block
|
---|
460 | # but not the parent we're looking for - arguably this is already an error) or the parent ID matches
|
---|
461 | # the passed ID. If the latter, push the whole set into a second flag hash, so we can terminate
|
---|
462 | # further tree-tracing early.
|
---|
463 | my %found;
|
---|
464 | foreach my $cid (keys %parents) {
|
---|
465 | my @tmp;
|
---|
466 | if ($cid == $id) {
|
---|
467 | # "child" is the ID we've been asked to cascade-delete.
|
---|
468 | $found{$cid}++;
|
---|
469 | } elsif ($found{$cid}) {
|
---|
470 | # ID already seen and the chain terminates in our parent.
|
---|
471 | } elsif ($parents{$cid} == $id) {
|
---|
472 | # Immediate parent is the target parent
|
---|
473 | $found{$cid}++;
|
---|
474 | } else {
|
---|
475 | # Immediate parent isn't the one we're looking for. Walk the chain up until we hit our parent,
|
---|
476 | # the nonexistent parent id 0, or undefined (ID is not a child of the target ID at all)
|
---|
477 | # There are probably better ways to structure this loop.
|
---|
478 | while (1) {
|
---|
479 | # cache the ID
|
---|
480 | push @tmp, $cid;
|
---|
481 | # some very particularly defined loop ending conditions
|
---|
482 | if (!defined($parents{$cid}) || $parents{$cid} == $id || $parents{$cid} == 0) {
|
---|
483 | last;
|
---|
484 | } else {
|
---|
485 | # if we haven't found either the desired parent or another limiting condition,
|
---|
486 | # reset the ID to the parent next up the tree
|
---|
487 | $cid = $parents{$cid};
|
---|
488 | }
|
---|
489 | }
|
---|
490 | # if the current chain of relations ended with our target parent, shuffle the cached IDs into a flag hash
|
---|
491 | if (defined($parents{$cid}) && $parents{$cid} == $id) {
|
---|
492 | foreach (@tmp) { $found{$_}++; }
|
---|
493 | }
|
---|
494 | } # else
|
---|
495 | } # foreach my $cid
|
---|
496 |
|
---|
497 | # Use the keys in the flag hash to determine which allocations to actually delete.
|
---|
498 | # Delete matching freeblocks and pool IPs; their parents are going away so we want
|
---|
499 | # to make sure we don't leave orphaned records lying around loose.
|
---|
500 | my @dellist = keys %found;
|
---|
501 | push @dellist, $id; # Just In Case the target ID didn't make the list earlier.
|
---|
502 | my $b = '?'. (',?' x $#dellist);
|
---|
503 | $dbh->do("DELETE FROM allocations WHERE id IN ($b)", undef, (@dellist) );
|
---|
504 | $dbh->do("DELETE FROM freeblocks WHERE parent_id IN ($b)", undef, (@dellist) );
|
---|
505 | $dbh->do("DELETE FROM poolips WHERE parent_id IN ($b)", undef, (@dellist) );
|
---|
506 |
|
---|
507 | # Insert a new free block if needed
|
---|
508 | if ($createfb) {
|
---|
509 | my $pinfo = getBlockData($dbh, $createfb);
|
---|
510 | my $pt = (split //, $pinfo->{type})[1];
|
---|
511 | $dbh->do("INSERT INTO freeblocks (cidr,city,routed,parent_id,vrf,master_id) VALUES (?,?,?,?,?,?)", undef,
|
---|
512 | $binfo->{block}, $pinfo->{city}, $pt, $createfb, $pinfo->{vrf}, $binfo->{master_id});
|
---|
513 | }
|
---|
514 |
|
---|
515 | ##todo: and hey! bonus! we can return @dellist, or something (%cidrlist{@dellist})
|
---|
516 |
|
---|
517 | } # end _deleteCascade()
|
---|
518 |
|
---|
519 |
|
---|
520 | ## IPDB::_getChildren()
|
---|
521 | # Recursive sub to retrieve a flat list of suballocations
|
---|
522 | # Takes the root parent ID, master ID, reference to push results into, and the CIDR
|
---|
523 | # range to restrict results to
|
---|
524 | sub _getChildren {
|
---|
525 | my $dbh = shift;
|
---|
526 | my $id = shift;
|
---|
527 | my $master = shift;
|
---|
528 | my $retlist = shift; # better than trying to return complex structures recursively. Ow.
|
---|
529 | my $cidr = shift;
|
---|
530 |
|
---|
531 | if (!$cidr) {
|
---|
532 | my $bd = getBlockData($dbh, $id);
|
---|
533 | $cidr = $bd->{cidr};
|
---|
534 | }
|
---|
535 |
|
---|
536 | my $sth = $dbh->prepare(q(
|
---|
537 | SELECT id,cidr,type FROM allocations
|
---|
538 | WHERE parent_id = ? AND master_id = ? AND cidr <<= ?
|
---|
539 | ) );
|
---|
540 | $sth->execute($id, $master, $cidr);
|
---|
541 | while (my $row = $sth->fetchrow_hashref) {
|
---|
542 | push @$retlist, $row;
|
---|
543 | _getChildren($dbh, $row->{id}, $master, $retlist, $cidr);
|
---|
544 | }
|
---|
545 | } # end _getChildren()
|
---|
546 |
|
---|
547 |
|
---|
548 | ##
|
---|
549 | ## Public subs
|
---|
550 | ##
|
---|
551 |
|
---|
552 |
|
---|
553 | ## IPDB::initIPDBGlobals()
|
---|
554 | # Initialize all globals. Takes a database handle, returns a success or error code
|
---|
555 | sub initIPDBGlobals {
|
---|
556 | my $dbh = $_[0];
|
---|
557 | my $sth;
|
---|
558 |
|
---|
559 | # Initialize alloctypes hashes
|
---|
560 | $sth = $dbh->prepare("select type,listname,dispname,listorder,def_custid from alloctypes order by listorder");
|
---|
561 | $sth->execute;
|
---|
562 | while (my @data = $sth->fetchrow_array) {
|
---|
563 | $disp_alloctypes{$data[0]} = $data[2];
|
---|
564 | $def_custids{$data[0]} = $data[4];
|
---|
565 | if ($data[3] < 900) {
|
---|
566 | $list_alloctypes{$data[0]} = $data[1];
|
---|
567 | }
|
---|
568 | }
|
---|
569 |
|
---|
570 | # City and POP listings
|
---|
571 | $sth = $dbh->prepare("select city,routing from cities order by city");
|
---|
572 | $sth->execute;
|
---|
573 | return (undef,$sth->errstr) if $sth->err;
|
---|
574 | while (my @data = $sth->fetchrow_array) {
|
---|
575 | push @citylist, $data[0];
|
---|
576 | if ($data[1] eq 'y') {
|
---|
577 | push @poplist, $data[0];
|
---|
578 | }
|
---|
579 | }
|
---|
580 |
|
---|
581 | # Load ACL data. Specific username checks are done at a different level.
|
---|
582 | $sth = $dbh->prepare("select username,acl from users");
|
---|
583 | $sth->execute;
|
---|
584 | return (undef,$sth->errstr) if $sth->err;
|
---|
585 | while (my @data = $sth->fetchrow_array) {
|
---|
586 | $IPDBacl{$data[0]} = $data[1];
|
---|
587 | }
|
---|
588 |
|
---|
589 | ##fixme: initialize HTML::Template env var for template path
|
---|
590 | # something like $self->path().'/templates' ?
|
---|
591 | # $ENV{HTML_TEMPLATE_ROOT} = 'foo/bar';
|
---|
592 |
|
---|
593 | # fix up DNSAdmin remote link based on RPC URL
|
---|
594 | if ($rpc_url) {
|
---|
595 | ($dnsadmin_url = $rpc_url) =~ s{/dns-rpc\.f?cgi}{};
|
---|
596 | }
|
---|
597 |
|
---|
598 | return (1,"OK");
|
---|
599 | } # end initIPDBGlobals
|
---|
600 |
|
---|
601 |
|
---|
602 | ## IPDB::connectDB()
|
---|
603 | # Creates connection to IPDB.
|
---|
604 | # Requires the database name, username, and password.
|
---|
605 | # Returns a handle to the db.
|
---|
606 | # Set up for a PostgreSQL db; could be any transactional DBMS with the
|
---|
607 | # right changes.
|
---|
608 | sub connectDB {
|
---|
609 | my $dbname = shift;
|
---|
610 | my $user = shift;
|
---|
611 | my $pass = shift;
|
---|
612 | my $dbhost = shift;
|
---|
613 |
|
---|
614 | my $dbh;
|
---|
615 | my $DSN = "DBI:Pg:".($dbhost ? "host=$dbhost;" : '')."dbname=$dbname";
|
---|
616 |
|
---|
617 | # Note that we want to autocommit by default, and we will turn it off locally as necessary.
|
---|
618 | # We may not want to print gobbledygook errors; YMMV. Have to ponder that further.
|
---|
619 | $dbh = DBI->connect($DSN, $user, $pass, {
|
---|
620 | AutoCommit => 1,
|
---|
621 | PrintError => 0
|
---|
622 | })
|
---|
623 | or return (undef, $DBI::errstr) if(!$dbh);
|
---|
624 |
|
---|
625 | # Return here if we can't select. Note that this indicates a
|
---|
626 | # problem executing the select.
|
---|
627 | my $sth = $dbh->prepare("select type from alloctypes");
|
---|
628 | $sth->execute();
|
---|
629 | return (undef,$DBI::errstr) if ($sth->err);
|
---|
630 |
|
---|
631 | # See if the select returned anything (or null data). This should
|
---|
632 | # succeed if the select executed, but...
|
---|
633 | $sth->fetchrow();
|
---|
634 | return (undef,$DBI::errstr) if ($sth->err);
|
---|
635 |
|
---|
636 | # If we get here, we should be OK.
|
---|
637 | return ($dbh,"DB connection OK");
|
---|
638 | } # end connectDB
|
---|
639 |
|
---|
640 |
|
---|
641 | ## IPDB::finish()
|
---|
642 | # Cleans up after database handles and so on.
|
---|
643 | # Requires a database handle
|
---|
644 | sub finish {
|
---|
645 | my $dbh = $_[0];
|
---|
646 | $dbh->disconnect if $dbh;
|
---|
647 | } # end finish
|
---|
648 |
|
---|
649 |
|
---|
650 | ## IPDB::checkDBSanity()
|
---|
651 | # Quick check to see if the db is responding. A full integrity
|
---|
652 | # check will have to be a separate tool to walk the IP allocation trees.
|
---|
653 | sub checkDBSanity {
|
---|
654 | my ($dbh) = $_[0];
|
---|
655 |
|
---|
656 | if (!$dbh) {
|
---|
657 | print "No database handle, or connection has been closed.";
|
---|
658 | return -1;
|
---|
659 | } else {
|
---|
660 | # it connects, try a stmt.
|
---|
661 | my $sth = $dbh->prepare("select type from alloctypes");
|
---|
662 | my $err = $sth->execute();
|
---|
663 |
|
---|
664 | if ($sth->fetchrow()) {
|
---|
665 | # all is well.
|
---|
666 | return 1;
|
---|
667 | } else {
|
---|
668 | print "Connected to the database, but could not execute test statement. ".$sth->errstr();
|
---|
669 | return -1;
|
---|
670 | }
|
---|
671 | }
|
---|
672 | # Clean up after ourselves.
|
---|
673 | # $dbh->disconnect;
|
---|
674 | } # end checkDBSanity
|
---|
675 |
|
---|
676 |
|
---|
677 | ## IPDB::addVRF()
|
---|
678 | #
|
---|
679 | sub addVRF {
|
---|
680 | my $dbh = shift;
|
---|
681 | my $newvrf = shift;
|
---|
682 | my %args = @_;
|
---|
683 |
|
---|
684 | $args{comment} = '' if !$args{comment};
|
---|
685 | $args{location} = '' if !$args{location};
|
---|
686 |
|
---|
687 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
688 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
689 | local $dbh->{AutoCommit} = 0;
|
---|
690 | local $dbh->{RaiseError} = 1;
|
---|
691 |
|
---|
692 | eval {
|
---|
693 | # Check if the VRF exists. Arguably should check for "looks similar", but that gets ugly fast.
|
---|
694 | my $vrfex = $dbh->selectrow_array("SELECT vrf FROM vrfs WHERE vrf=?", undef, $newvrf);
|
---|
695 | die "VRF already exists!\n" if $vrfex;
|
---|
696 |
|
---|
697 | # Nothing there yet, so we can insert the new VRF
|
---|
698 | $dbh->do("INSERT INTO vrfs (vrf,comment,location) VALUES (?,?,?)", undef,
|
---|
699 | $newvrf, $args{comment}, $args{location});
|
---|
700 |
|
---|
701 | $dbh->commit;
|
---|
702 | };
|
---|
703 | if ($@) {
|
---|
704 | my $msg = $@;
|
---|
705 | eval { $dbh->rollback; };
|
---|
706 | return ('FAIL',$msg);
|
---|
707 | }
|
---|
708 | return ('OK',$newvrf);
|
---|
709 | } # end addVRF()
|
---|
710 |
|
---|
711 |
|
---|
712 | ## IPDB::getVRF()
|
---|
713 | # Retrieve additional fields from DB for a VRF
|
---|
714 | sub getVRF {
|
---|
715 | my $dbh = shift;
|
---|
716 | my $vrf = shift;
|
---|
717 |
|
---|
718 | return $dbh->selectrow_hashref("SELECT comment,location FROM vrfs WHERE vrf = ?", {Slice=>{}}, $vrf);
|
---|
719 | } # end getVRF()
|
---|
720 |
|
---|
721 |
|
---|
722 | ## IPDB::deleteVRF()
|
---|
723 | #
|
---|
724 | sub deleteVRF {
|
---|
725 | my $dbh = shift;
|
---|
726 | my $vrf = shift;
|
---|
727 |
|
---|
728 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
729 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
730 | local $dbh->{AutoCommit} = 0;
|
---|
731 | local $dbh->{RaiseError} = 1;
|
---|
732 |
|
---|
733 | eval {
|
---|
734 | $dbh->do("DELETE FROM vrfs WHERE vrf = ?", undef, $vrf);
|
---|
735 | $dbh->commit;
|
---|
736 | };
|
---|
737 | if ($@) {
|
---|
738 | my $msg = $@; # not much complexity here just yet.
|
---|
739 | return ('FAIL',$msg);
|
---|
740 | }
|
---|
741 |
|
---|
742 | return ('OK','OK');
|
---|
743 | } # end deleteVRF()
|
---|
744 |
|
---|
745 |
|
---|
746 | ## IPDB::addMaster()
|
---|
747 | # Does all the magic necessary to sucessfully add a master block
|
---|
748 | # Requires database handle, block to add
|
---|
749 | # Returns failure code and error message or success code and "message"
|
---|
750 | sub addMaster {
|
---|
751 | my $dbh = shift;
|
---|
752 | # warning! during testing, this somehow generated a "Bad file descriptor" error. O_o
|
---|
753 | my $ctext = shift;
|
---|
754 | my $cidr = new NetAddr::IP $ctext;
|
---|
755 |
|
---|
756 | return ('FAIL',"$ctext is not a valid CIDR address") if !$cidr;
|
---|
757 |
|
---|
758 | my %args = @_;
|
---|
759 |
|
---|
760 | $args{vrf} = '' if !$args{vrf};
|
---|
761 | $args{rdns} = '' if !$args{rdns};
|
---|
762 | $args{defloc} = '' if !$args{defloc};
|
---|
763 | $args{rwhois} = 'n' if !$args{rwhois}; # fail "safe", sort of.
|
---|
764 | $args{rwhois} = 'n' if $args{rwhois} ne 'n' and $args{rwhois} ne 'y';
|
---|
765 |
|
---|
766 | my $mid;
|
---|
767 |
|
---|
768 | # Allow transactions, and raise an exception on errors so we can catch it later.
|
---|
769 | # Use local to make sure these get "reset" properly on exiting this block
|
---|
770 | local $dbh->{AutoCommit} = 0;
|
---|
771 | local $dbh->{RaiseError} = 1;
|
---|
772 |
|
---|
773 | # Wrap all the SQL in a transaction
|
---|
774 | eval {
|
---|
775 | # First check - does the master exist in this VRF?
|
---|
776 | my ($mcontained) = $dbh->selectrow_array("SELECT cidr FROM allocations WHERE cidr >>= ? AND type = 'mm' AND vrf = ?",
|
---|
777 | undef, ($cidr, $args{vrf}) );
|
---|
778 | die "Master block $mcontained already exists and entirely contains $cidr\n"
|
---|
779 | if $mcontained;
|
---|
780 |
|
---|
781 | # Second check - does the new master contain an existing one or ones?
|
---|
782 | my ($mexist) = $dbh->selectrow_array("SELECT cidr FROM allocations WHERE cidr <<= ? AND type = 'mm' AND vrf = ?",
|
---|
783 | undef, ($cidr, $args{vrf}) );
|
---|
784 |
|
---|
785 | if (!$mexist) {
|
---|
786 | # First case - master is brand-spanking-new.
|
---|
787 | ##fixme: rwhois should be globally-flagable somewhere, much like a number of other things
|
---|
788 | ## maybe a db table called "config"?
|
---|
789 | $dbh->do("INSERT INTO allocations (cidr,type,swip,vrf,rdns) VALUES (?,?,?,?,?)", undef,
|
---|
790 | ($cidr, 'mm', 'y', $args{vrf}, $args{rdns}) );
|
---|
791 | ($mid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
|
---|
792 |
|
---|
793 | # Unrouted blocks aren't associated with a city (yet). We don't rely on this
|
---|
794 | # elsewhere though; legacy data may have traps and pitfalls in it to break this.
|
---|
795 | # Thus the "routed" flag.
|
---|
796 | $dbh->do("INSERT INTO freeblocks (cidr,city,routed,parent_id,vrf,master_id) VALUES (?,?,?,?,?,?)", undef,
|
---|
797 | ($cidr, '<NULL>', 'm', $mid, $args{vrf}, $mid) );
|
---|
798 |
|
---|
799 | # master should be its own master, so deletes directly at the master level work
|
---|
800 | $dbh->do("UPDATE allocations SET master_id = ? WHERE id = ?", undef, ($mid, $mid) );
|
---|
801 |
|
---|
802 | # If we get here, everything is happy. Commit changes.
|
---|
803 | $dbh->commit;
|
---|
804 |
|
---|
805 | } # done new master does not contain existing master(s)
|
---|
806 | else {
|
---|
807 |
|
---|
808 | # insert the new master
|
---|
809 | $dbh->do("INSERT INTO allocations (cidr,type,swip,vrf,rdns) VALUES (?,?,?,?,?)", undef,
|
---|
810 | ($cidr, 'mm', 'y', $args{vrf}, $args{rdns}) );
|
---|
811 | ($mid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
|
---|
812 |
|
---|
813 | # master should be its own master, so deletes directly at the master level work
|
---|
814 | $dbh->do("UPDATE allocations SET master_id = ? WHERE id = ?", undef, ($mid, $mid) );
|
---|
815 |
|
---|
816 | # collect the master(s) we're going to absorb, and snag the longest netmask while we're at it.
|
---|
817 | # note << is accurate and complete because our first check just into the eval is "is the new master
|
---|
818 | # entirely contained or equal to an existing one?" - so, by definition, if it's not contained, and
|
---|
819 | # it's not equal, it's larger. this also lets us insert the new master without picking it up again here.
|
---|
820 | my $smallmask = $cidr->masklen;
|
---|
821 | my $sth = $dbh->prepare("SELECT cidr,id FROM allocations WHERE cidr << ? AND type = 'mm' AND parent_id = 0 AND vrf = ? ");
|
---|
822 | $sth->execute($cidr, $args{vrf});
|
---|
823 | my @cmasters;
|
---|
824 | my @oldmids;
|
---|
825 | while (my @data = $sth->fetchrow_array) {
|
---|
826 | my $master = new NetAddr::IP $data[0];
|
---|
827 | push @cmasters, $master;
|
---|
828 | push @oldmids, $data[1];
|
---|
829 | $smallmask = $master->masklen if $master->masklen > $smallmask;
|
---|
830 | }
|
---|
831 |
|
---|
832 | # update existing DNS refs. do this unconditionally Just In Case
|
---|
833 | $dbh->do("UPDATE dnsavail SET parent_alloc = ? WHERE zone << ?".
|
---|
834 | " AND parent_alloc IN (".join(',', @oldmids).")",
|
---|
835 | undef, $mid, $cidr);
|
---|
836 |
|
---|
837 | # split the new master, and keep only those blocks not part of an existing master
|
---|
838 | my @blocklist;
|
---|
839 | foreach my $seg ($cidr->split($smallmask)) {
|
---|
840 | my $contained = 0;
|
---|
841 | foreach my $master (@cmasters) {
|
---|
842 | $contained = 1 if $master->contains($seg);
|
---|
843 | }
|
---|
844 | push @blocklist, $seg if !$contained;
|
---|
845 | }
|
---|
846 |
|
---|
847 | ##fixme: master_id
|
---|
848 | # collect the unrouted free blocks within the new master
|
---|
849 | $sth = $dbh->prepare("SELECT cidr FROM freeblocks WHERE masklen(cidr) <= ? AND cidr <<= ? AND routed = 'm' AND master_id IN (".join(',',@oldmids).")");
|
---|
850 | $sth->execute($smallmask, $cidr);
|
---|
851 | while (my @data = $sth->fetchrow_array) {
|
---|
852 | my $freeblock = new NetAddr::IP $data[0];
|
---|
853 | push @blocklist, $freeblock;
|
---|
854 | }
|
---|
855 |
|
---|
856 | # combine the set of free blocks we should have now.
|
---|
857 | @blocklist = Compact(@blocklist);
|
---|
858 |
|
---|
859 | # delete freeblocks that have been absorbed. this is probably rare.
|
---|
860 | $sth = $dbh->prepare("DELETE FROM freeblocks WHERE cidr <<= ? AND parent_id IN (".join(',', @oldmids).")");
|
---|
861 |
|
---|
862 | # insert new combined freeblocks.
|
---|
863 | my $sth2 = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,parent_id,vrf,master_id)".
|
---|
864 | " VALUES (?,'<NULL>','m',?,?,?)");
|
---|
865 | foreach my $newblock (@blocklist) {
|
---|
866 | $sth->execute($newblock);
|
---|
867 | $sth2->execute($newblock, $mid, $args{vrf}, $mid);
|
---|
868 | }
|
---|
869 |
|
---|
870 | # Update immediate allocations, and remove the old parents
|
---|
871 | $sth2 = $dbh->prepare("DELETE FROM allocations WHERE id = ?");
|
---|
872 | # sigh. going to have to churn things, since we need to do different updates to different sets of blocks.
|
---|
873 | my $fbfix = $dbh->prepare("UPDATE freeblocks SET master_id = ? WHERE master_id = ?");
|
---|
874 | my $fbfix2 = $dbh->prepare("UPDATE freeblocks SET parent_id = ? WHERE parent_id = ?");
|
---|
875 | my $allocfix = $dbh->prepare("UPDATE allocations SET master_id = ? WHERE master_id = ?");
|
---|
876 | my $allocfix2 = $dbh->prepare("UPDATE allocations SET parent_id = ? WHERE parent_id = ?");
|
---|
877 | foreach my $old (@oldmids) {
|
---|
878 | $sth2->execute($old);
|
---|
879 | $fbfix->execute($mid, $old);
|
---|
880 | $fbfix2->execute($mid, $old);
|
---|
881 | $allocfix->execute($mid, $old);
|
---|
882 | $allocfix2->execute($mid, $old);
|
---|
883 | }
|
---|
884 |
|
---|
885 | # *whew* If we got here, we likely suceeded.
|
---|
886 | $dbh->commit;
|
---|
887 |
|
---|
888 | } # new master contained existing master(s)
|
---|
889 | }; # end eval
|
---|
890 |
|
---|
891 | if ($@) {
|
---|
892 | my $msg = $@;
|
---|
893 | eval { $dbh->rollback; };
|
---|
894 | return ('FAIL',$msg);
|
---|
895 | } else {
|
---|
896 |
|
---|
897 | # Only attempt rDNS if the IPDB side succeeded
|
---|
898 | if ($rpc_url) {
|
---|
899 |
|
---|
900 | # Note *not* splitting reverse zones negates any benefit from caching the exported data.
|
---|
901 | # IPv6 address space is far too large to split usefully, and in any case (also due to
|
---|
902 | # the large address space) doesn't support the iterated template records v4 zones do
|
---|
903 | # that causes the bulk of the slowdown that needs the cache anyway.
|
---|
904 |
|
---|
905 | my @zonelist;
|
---|
906 | # allow splitting reverse zones to be disabled, maybe, someday
|
---|
907 | #if ($splitrevzones && !$cidr->{isv6}) {
|
---|
908 | if (1 && !$cidr->{isv6}) {
|
---|
909 | my $splitpoint = ($cidr->masklen <= 16 ? 16 : 24); # hack pthui
|
---|
910 | @zonelist = $cidr->split($splitpoint);
|
---|
911 | } else {
|
---|
912 | @zonelist = ($cidr);
|
---|
913 | }
|
---|
914 | my @fails;
|
---|
915 | ##fixme: remove hardcoding where possible
|
---|
916 | my $dasth = $dbh->prepare("INSERT INTO dnsavail (zone,location,parent_alloc) VALUES (?,?,?)");
|
---|
917 | foreach my $subzone (@zonelist) {
|
---|
918 | my %rpcargs = (
|
---|
919 | rpcuser => $args{user},
|
---|
920 | revzone => "$subzone",
|
---|
921 | revpatt => $args{rdns},
|
---|
922 | defloc => $args{defloc},
|
---|
923 | group => $revgroup, # not sure how these two could sanely be exposed, tbh...
|
---|
924 | state => 1, # could make them globally configurable maybe
|
---|
925 | );
|
---|
926 | if ($rpc_url) {
|
---|
927 | if (!_rpc('addRDNS', %rpcargs)) {
|
---|
928 | push @fails, ("$subzone" => $errstr);
|
---|
929 | } else {
|
---|
930 | $dasth->execute($subzone, $args{defloc}, $mid)
|
---|
931 | or push @fails, ("$subzone" => "rDNS added but failed to track locally: ".$dasth->errstr."\n");
|
---|
932 | }
|
---|
933 | }
|
---|
934 | }
|
---|
935 | if (@fails) {
|
---|
936 | $errstr = "Warning(s) adding $cidr to reverse DNS:\n".join("\n", @fails);
|
---|
937 | return ('WARN',$mid);
|
---|
938 | }
|
---|
939 | }
|
---|
940 | return ('OK',$mid);
|
---|
941 | }
|
---|
942 | } # end addMaster
|
---|
943 |
|
---|
944 |
|
---|
945 | ## IPDB::touchMaster()
|
---|
946 | # Update last-changed timestamp on a master block.
|
---|
947 | sub touchMaster {
|
---|
948 | my $dbh = shift;
|
---|
949 | my $master = shift;
|
---|
950 |
|
---|
951 | local $dbh->{AutoCommit} = 0;
|
---|
952 | local $dbh->{RaiseError} = 1;
|
---|
953 |
|
---|
954 | eval {
|
---|
955 | $dbh->do("UPDATE allocations SET modifystamp=now() WHERE id = ?", undef, ($master));
|
---|
956 | $dbh->commit;
|
---|
957 | };
|
---|
958 |
|
---|
959 | if ($@) {
|
---|
960 | my $msg = $@;
|
---|
961 | eval { $dbh->rollback; };
|
---|
962 | return ('FAIL',$msg);
|
---|
963 | }
|
---|
964 | return ('OK','OK');
|
---|
965 | } # end touchMaster()
|
---|
966 |
|
---|
967 |
|
---|
968 | ## IPDB::listVRF()
|
---|
969 | # Get summary list of all VRFs
|
---|
970 | # Returns an arrayref to a list of hashrefs with the VRF name, comment
|
---|
971 | sub listVRF {
|
---|
972 | my $dbh = shift;
|
---|
973 | my $vrflist = $dbh->selectall_arrayref("SELECT vrf,comment FROM vrfs ORDER BY vrf", { Slice => {} });
|
---|
974 | return $vrflist;
|
---|
975 | } # end listVRF()
|
---|
976 |
|
---|
977 |
|
---|
978 | ## IPDB::listSummary()
|
---|
979 | # Get summary list of all master blocks
|
---|
980 | # Returns an arrayref to a list of hashrefs containing the master block, routed count,
|
---|
981 | # allocated count, free count, and largest free block masklength
|
---|
982 | sub listSummary {
|
---|
983 | my $dbh = shift;
|
---|
984 | my $vrf = shift;
|
---|
985 |
|
---|
986 | my $mlist = $dbh->selectall_arrayref("SELECT cidr AS master,id FROM allocations ".
|
---|
987 | "WHERE type='mm' AND vrf = ? ORDER BY cidr",
|
---|
988 | { Slice => {} }, $vrf);
|
---|
989 |
|
---|
990 | foreach (@{$mlist}) {
|
---|
991 | my ($rcnt) = $dbh->selectrow_array("SELECT count(*) FROM allocations WHERE cidr <<= ? AND type='rm' AND master_id = ?",
|
---|
992 | undef, ($$_{master}, $$_{id}));
|
---|
993 | $$_{routed} = $rcnt;
|
---|
994 | my ($acnt) = $dbh->selectrow_array("SELECT count(*) FROM allocations WHERE cidr <<= ? ".
|
---|
995 | "AND NOT type='rm' AND NOT type='mm' AND master_id = ?",
|
---|
996 | undef, ($$_{master}, $$_{id}));
|
---|
997 | $$_{allocated} = $acnt;
|
---|
998 | my ($fcnt) = $dbh->selectrow_array("SELECT count(*) FROM freeblocks WHERE cidr <<= ? AND master_id = ?",
|
---|
999 | undef, ($$_{master}, $$_{id}));
|
---|
1000 | $$_{free} = $fcnt;
|
---|
1001 | my ($bigfree) = $dbh->selectrow_array("SELECT masklen(cidr) AS maskbits FROM freeblocks WHERE cidr <<= ?".
|
---|
1002 | " AND master_id = ? ORDER BY masklen(cidr) LIMIT 1", undef, ($$_{master}, $$_{id}));
|
---|
1003 | ##fixme: should find a way to do this without having to HTMLize the <>
|
---|
1004 | $bigfree = "/$bigfree" if $bigfree;
|
---|
1005 | $bigfree = '<NONE>' if !$bigfree;
|
---|
1006 | $$_{bigfree} = $bigfree;
|
---|
1007 | }
|
---|
1008 | return $mlist;
|
---|
1009 | } # end listSummary()
|
---|
1010 |
|
---|
1011 |
|
---|
1012 | ## IPDB::listSubs()
|
---|
1013 | # Get list of subnets within a specified CIDR block, on a specified VRF.
|
---|
1014 | # Returns an arrayref to a list of hashrefs containing the CIDR block, customer location or
|
---|
1015 | # city it's routed to, block type, SWIP status, and description
|
---|
1016 | sub listSubs {
|
---|
1017 | my $dbh = shift;
|
---|
1018 | my %args = @_;
|
---|
1019 |
|
---|
1020 | # Just In Case
|
---|
1021 | $args{vrf} = '' if !$args{vrf};
|
---|
1022 |
|
---|
1023 | # Snag the allocations for this block
|
---|
1024 | my $sth = $dbh->prepare("SELECT masklen(cidr),cidr,city,type,custid,swip,description,vrf,id,master_id".
|
---|
1025 | " FROM allocations WHERE parent_id = ? ORDER BY cidr");
|
---|
1026 | $sth->execute($args{parent});
|
---|
1027 |
|
---|
1028 | # hack hack hack
|
---|
1029 | # set up to flag swip=y records if they don't actually have supporting data in the customers table
|
---|
1030 | my $custsth = $dbh->prepare("SELECT count(*) FROM customers WHERE custid = ?");
|
---|
1031 |
|
---|
1032 | # snag some more details
|
---|
1033 | my $substh = $dbh->prepare("SELECT count(*) FROM allocations WHERE cidr <<= ? ".
|
---|
1034 | "AND type ~ '[mc]\$' AND master_id = ? AND NOT cidr = ? ");
|
---|
1035 | my $alsth = $dbh->prepare("SELECT count(*) FROM allocations WHERE cidr <<= ? ".
|
---|
1036 | "AND NOT type='rm' AND NOT type='mm' AND master_id = ? AND NOT id = ?");
|
---|
1037 | my $freesth = $dbh->prepare("SELECT count(*) FROM freeblocks WHERE cidr <<= ? AND master_id = ?");
|
---|
1038 | my $lfreesth = $dbh->prepare("SELECT masklen(cidr) AS maskbits FROM freeblocks WHERE cidr <<= ?".
|
---|
1039 | " AND master_id = ? ORDER BY masklen(cidr)");
|
---|
1040 |
|
---|
1041 | my @blocklist;
|
---|
1042 | while (my ($blockmask,$cidr,$city,$type,$custid,$swip,$desc,$vrf,$id,$mid) = $sth->fetchrow_array()) {
|
---|
1043 | $desc .= " - vrf:$vrf" if $desc && $vrf;
|
---|
1044 | $desc = "vrf:$vrf" if !$desc && $vrf;
|
---|
1045 | $custsth->execute($custid);
|
---|
1046 | my ($ncust) = $custsth->fetchrow_array();
|
---|
1047 | $substh->execute($cidr, $mid, $cidr);
|
---|
1048 | my ($cont) = $substh->fetchrow_array();
|
---|
1049 | $alsth->execute($cidr, $mid, $id);
|
---|
1050 | my ($alloc) = $alsth->fetchrow_array();
|
---|
1051 | $freesth->execute($cidr, $mid);
|
---|
1052 | my ($free) = $freesth->fetchrow_array();
|
---|
1053 | $lfreesth->execute($cidr, $mid);
|
---|
1054 |
|
---|
1055 | # make sure we capture the first one separately...
|
---|
1056 | my ($lfree) = $lfreesth->fetchrow_array();
|
---|
1057 | my $num_ipfree = ($lfree ? 2**(32-$lfree) : 0);
|
---|
1058 | # ... so this can proceed without accidentally whacking it
|
---|
1059 | while (my ($freemask) = $lfreesth->fetchrow_array) {
|
---|
1060 | $num_ipfree += 2**(32-$freemask);
|
---|
1061 | }
|
---|
1062 | if ($type =~ /^.[dp]$/) {
|
---|
1063 | ($num_ipfree) = $dbh->selectrow_array("SELECT count(*) FROM poolips WHERE parent_id = ? AND available = 'y'", undef, $id);
|
---|
1064 | }
|
---|
1065 | my $pctfree = sprintf "%0.1f", $num_ipfree / 2**(32-$blockmask) * 100;
|
---|
1066 | $lfree = "/$lfree" if $lfree;
|
---|
1067 | $lfree = '<NONE>' if !$lfree;
|
---|
1068 |
|
---|
1069 | my %row = (
|
---|
1070 | block => $cidr,
|
---|
1071 | subfree => $free,
|
---|
1072 | lfree => $lfree,
|
---|
1073 | city => $city,
|
---|
1074 | type => $disp_alloctypes{$type},
|
---|
1075 | custid => $custid,
|
---|
1076 | desc => $desc,
|
---|
1077 | hassubs => ($type eq 'rm' || $type eq 'mm' || $type =~ /.c/ ? 1 : 0),
|
---|
1078 | id => $id,
|
---|
1079 | );
|
---|
1080 | # $row{subblock} = ($type =~ /^.r$/); # hmf. wonder why these won't work in the hash declaration...
|
---|
1081 | $row{listpool} = ($type =~ /^.[pd]$/);
|
---|
1082 | # only set this on suitable types (pools, containers)
|
---|
1083 | $row{pctfree} = "$num_ipfree IPs, $pctfree" if $type =~ /^.[cpdm]/;
|
---|
1084 | push (@blocklist, \%row);
|
---|
1085 | }
|
---|
1086 | return \@blocklist;
|
---|
1087 | } # end listSubs()
|
---|
1088 |
|
---|
1089 |
|
---|
1090 | ## IPDB::listContainers()
|
---|
1091 | # List all container-type allocations in a given parent
|
---|
1092 | # Takes a database handle and a hash:
|
---|
1093 | # - parent is the ID of the parent block
|
---|
1094 | # Returns an arrayref to a list of hashrefs with the CIDR block, location, type,
|
---|
1095 | # description, block ID, and counts for the nmber uf suballocations (all types),
|
---|
1096 | # free blocks, and the CIDR size of the largest free block
|
---|
1097 | sub listContainers {
|
---|
1098 | my $dbh = shift;
|
---|
1099 | my %args = @_;
|
---|
1100 |
|
---|
1101 | # Just In Case
|
---|
1102 | $args{vrf} = '' if !$args{vrf};
|
---|
1103 |
|
---|
1104 | # Snag the allocations for this block
|
---|
1105 | my $sth = $dbh->prepare("SELECT cidr,city,type,custid,swip,description,vrf,id,master_id".
|
---|
1106 | " FROM allocations WHERE parent_id = ? AND type ~ '[mc]\$' ORDER BY cidr");
|
---|
1107 | $sth->execute($args{parent});
|
---|
1108 |
|
---|
1109 | my $alsth = $dbh->prepare("SELECT count(*) FROM allocations WHERE cidr <<= ? ".
|
---|
1110 | "AND NOT type='rm' AND NOT type='mm' AND master_id = ? AND NOT id = ?");
|
---|
1111 | my $freesth = $dbh->prepare("SELECT count(*) FROM freeblocks WHERE cidr <<= ? AND master_id = ?");
|
---|
1112 | my $lfreesth = $dbh->prepare("SELECT masklen(cidr) AS maskbits FROM freeblocks WHERE cidr <<= ?".
|
---|
1113 | " AND master_id = ? ORDER BY masklen(cidr) LIMIT 1");
|
---|
1114 |
|
---|
1115 | my @blocklist;
|
---|
1116 | while (my ($cidr,$city,$type,$custid,$swip,$desc,$vrf,$id,$mid) = $sth->fetchrow_array()) {
|
---|
1117 | $desc .= " - vrf:$vrf" if $desc && $vrf;
|
---|
1118 | $desc = "vrf:$vrf" if !$desc && $vrf;
|
---|
1119 | $alsth->execute($cidr, $mid, $id);
|
---|
1120 | my ($alloc) = $alsth->fetchrow_array();
|
---|
1121 | $freesth->execute($cidr, $mid);
|
---|
1122 | my ($free) = $freesth->fetchrow_array();
|
---|
1123 | $lfreesth->execute($cidr, $mid);
|
---|
1124 | my ($lfree) = $lfreesth->fetchrow_array();
|
---|
1125 | $lfree = "/$lfree" if $lfree;
|
---|
1126 | $lfree = '<NONE>' if !$lfree;
|
---|
1127 | my %row = (
|
---|
1128 | block => $cidr,
|
---|
1129 | suballocs => $alloc,
|
---|
1130 | subfree => $free,
|
---|
1131 | lfree => $lfree,
|
---|
1132 | city => $city,
|
---|
1133 | type => $disp_alloctypes{$type},
|
---|
1134 | desc => $desc,
|
---|
1135 | id => $id,
|
---|
1136 | );
|
---|
1137 | push (@blocklist, \%row);
|
---|
1138 | }
|
---|
1139 | return \@blocklist;
|
---|
1140 | } # end listContainers()
|
---|
1141 |
|
---|
1142 |
|
---|
1143 | ## IPDB::listAllocations()
|
---|
1144 | # List all end-use allocations in a given parent
|
---|
1145 | # Takes a database handle and a hash:
|
---|
1146 | # - parent is the ID of the parent block
|
---|
1147 | # Returns an arrayref to a list of hashrefs with the CIDR block, location, type,
|
---|
1148 | # custID, SWIP flag, description, block ID, and master ID
|
---|
1149 | sub listAllocations {
|
---|
1150 | my $dbh = shift;
|
---|
1151 | my %args = @_;
|
---|
1152 |
|
---|
1153 | # Snag the allocations for this block
|
---|
1154 | my $sth = $dbh->prepare("SELECT cidr,city,type,custid,swip,description,vrf,id,master_id".
|
---|
1155 | " FROM allocations WHERE parent_id = ? AND type !~ '[mc]\$' ORDER BY cidr");
|
---|
1156 | $sth->execute($args{parent});
|
---|
1157 |
|
---|
1158 | # hack hack hack
|
---|
1159 | # set up to flag swip=y records if they don't actually have supporting data in the customers table
|
---|
1160 | my $custsth = $dbh->prepare("SELECT count(*) FROM customers WHERE custid = ?");
|
---|
1161 |
|
---|
1162 | my @blocklist;
|
---|
1163 | while (my ($cidr,$city,$type,$custid,$swip,$desc,$vrf,$id,$mid) = $sth->fetchrow_array()) {
|
---|
1164 | $desc .= " - vrf:$vrf" if $desc && $vrf;
|
---|
1165 | $desc = "vrf:$vrf" if !$desc && $vrf;
|
---|
1166 | $custsth->execute($custid);
|
---|
1167 | my ($ncust) = $custsth->fetchrow_array();
|
---|
1168 | my %row = (
|
---|
1169 | block => $cidr,
|
---|
1170 | city => $city,
|
---|
1171 | type => $disp_alloctypes{$type},
|
---|
1172 | custid => $custid,
|
---|
1173 | swip => ($swip eq 'y' ? 'Yes' : 'No'),
|
---|
1174 | partswip => ($swip eq 'y' && $ncust == 0 ? 1 : 0),
|
---|
1175 | desc => $desc,
|
---|
1176 | id => $id,
|
---|
1177 | );
|
---|
1178 | # $row{subblock} = ($type =~ /^.r$/); # hmf. wonder why these won't work in the hash declaration...
|
---|
1179 | $row{listpool} = ($type =~ /^.[pd]$/);
|
---|
1180 | push (@blocklist, \%row);
|
---|
1181 | }
|
---|
1182 | return \@blocklist;
|
---|
1183 | } # end listAllocations()
|
---|
1184 |
|
---|
1185 |
|
---|
1186 | ## IPDB::listForMerge()
|
---|
1187 | # Get a list of blocks targetted in a proposed merge
|
---|
1188 | sub listForMerge {
|
---|
1189 | my $dbh = shift;
|
---|
1190 | my $parent = shift;
|
---|
1191 | my $newblock = shift;
|
---|
1192 | my $btype = shift || 'a';
|
---|
1193 | $btype = 'a' if $btype !~/^[af]$/;
|
---|
1194 | my $incsub = shift;
|
---|
1195 | $incsub = 1 if !defined($incsub);
|
---|
1196 |
|
---|
1197 | my $sql;
|
---|
1198 | if ($btype eq 'a') {
|
---|
1199 | my $ret = $dbh->selectall_arrayref(q(
|
---|
1200 | SELECT a.cidr,a.id,t.dispname FROM allocations a
|
---|
1201 | JOIN alloctypes t ON a.type=t.type
|
---|
1202 | WHERE a.parent_id = ? AND a.cidr <<= ?
|
---|
1203 | ORDER BY a.cidr
|
---|
1204 | ),
|
---|
1205 | { Slice => {} }, $parent, $newblock);
|
---|
1206 | return $ret;
|
---|
1207 | } else {
|
---|
1208 | ##fixme: Not sure about the casting hackery in "SELECT ?::integer AS id", but it works as intended
|
---|
1209 | my @dbargs = ($parent, "$newblock");
|
---|
1210 | push @dbargs, $parent, $newblock if $incsub;
|
---|
1211 | my $ret = $dbh->selectall_arrayref(q{
|
---|
1212 | SELECT cidr,id FROM freeblocks
|
---|
1213 | WHERE parent_id IN (
|
---|
1214 | }.($incsub ? "SELECT id FROM allocations WHERE parent_id = ? AND cidr <<= ? UNION " : '').q{
|
---|
1215 | SELECT ?::integer AS id
|
---|
1216 | ) AND cidr <<= ?
|
---|
1217 | ORDER BY cidr
|
---|
1218 | },
|
---|
1219 | { Slice => {} }, @dbargs);
|
---|
1220 | return $ret;
|
---|
1221 | }
|
---|
1222 | return;
|
---|
1223 | } # end listForMerge()
|
---|
1224 |
|
---|
1225 |
|
---|
1226 | ## IPDB::listFree()
|
---|
1227 | # Gets a list of free blocks in the requested parent/master and VRF instance in both CIDR and range notation
|
---|
1228 | # Takes a parent/master ID and an optional VRF specifier that defaults to empty.
|
---|
1229 | # Returns an arrayref to a list of hashrefs containing the CIDR and range-notation blocks
|
---|
1230 | # Returns some extra flags in the hashrefs for routed blocks, since those can have several subtypes
|
---|
1231 | sub listFree {
|
---|
1232 | my $dbh = shift;
|
---|
1233 |
|
---|
1234 | my %args = @_;
|
---|
1235 | # Just In Case
|
---|
1236 | $args{vrf} = '' if !$args{vrf};
|
---|
1237 |
|
---|
1238 | my $sth = $dbh->prepare(q(
|
---|
1239 | SELECT f.cidr,f.id,allocations.cidr
|
---|
1240 | FROM freeblocks f
|
---|
1241 | LEFT JOIN allocations ON f.reserve_for = allocations.id
|
---|
1242 | WHERE f.parent_id = ?
|
---|
1243 | ORDER BY f.cidr
|
---|
1244 | ) );
|
---|
1245 | # $sth->execute($args{parent}, $args{vrf});
|
---|
1246 | $sth->execute($args{parent});
|
---|
1247 | my @flist;
|
---|
1248 | while (my ($cidr,$id,$resv) = $sth->fetchrow_array()) {
|
---|
1249 | $cidr = new NetAddr::IP $cidr;
|
---|
1250 | my %row = (
|
---|
1251 | fblock => "$cidr",
|
---|
1252 | frange => $cidr->range,
|
---|
1253 | fbid => $id,
|
---|
1254 | fbparent => $args{parent},
|
---|
1255 | resv => $resv,
|
---|
1256 | );
|
---|
1257 | push @flist, \%row;
|
---|
1258 | }
|
---|
1259 | return \@flist;
|
---|
1260 | } # end listFree()
|
---|
1261 |
|
---|
1262 |
|
---|
1263 | ## IPDB::listPool()
|
---|
1264 | # List the IPs in an IP pool.
|
---|
1265 | # Takes a pool/parent ID
|
---|
1266 | # Returns an arrayref to a list of hashrefs containing the IP, customer ID, availability flag,
|
---|
1267 | # description, backreference to the pool/parent, and the IP ID in the pool.
|
---|
1268 | # Also includes a "may be deleted" metaflag mainly useful for allowing the return to be passed
|
---|
1269 | # directly to HTML::Template for UI display.
|
---|
1270 | sub listPool {
|
---|
1271 | my $dbh = shift;
|
---|
1272 | my $pool = shift;
|
---|
1273 | my $incdesc = shift;
|
---|
1274 | $incdesc = 1 if !defined($incdesc); # extra flag to include description and "deleteme" flag
|
---|
1275 |
|
---|
1276 | my $sth = $dbh->prepare("SELECT ip,custid,available,description,type,id".
|
---|
1277 | " FROM poolips WHERE parent_id = ? ORDER BY ip");
|
---|
1278 | $sth->execute($pool);
|
---|
1279 | my @poolips;
|
---|
1280 | while (my ($ip,$custid,$available,$desc,$type,$id) = $sth->fetchrow_array) {
|
---|
1281 | my %row = (
|
---|
1282 | ip => $ip,
|
---|
1283 | custid => $custid,
|
---|
1284 | available => $available,
|
---|
1285 | parent => $pool,
|
---|
1286 | id => $id,
|
---|
1287 | );
|
---|
1288 | if ($incdesc) {
|
---|
1289 | $row{desc} = $desc;
|
---|
1290 | $row{delme} = ($available eq 'n');
|
---|
1291 | }
|
---|
1292 | push @poolips, \%row;
|
---|
1293 | }
|
---|
1294 | return \@poolips;
|
---|
1295 | } # end listPool()
|
---|
1296 |
|
---|
1297 |
|
---|
1298 | ## IPDB::getMasterList()
|
---|
1299 | # Get a list of master blocks, optionally including last-modified timestamps
|
---|
1300 | # Takes an optional flag to indicate whether to include timestamps;
|
---|
1301 | # 'm' includes ctime, all others (suggest 'c') do not.
|
---|
1302 | # Returns an arrayref to a list of hashrefs
|
---|
1303 | sub getMasterList {
|
---|
1304 | my $dbh = shift;
|
---|
1305 | my $stampme = shift || 'm'; # optional but should be set by caller for clarity
|
---|
1306 |
|
---|
1307 | my $mlist = $dbh->selectall_arrayref("SELECT id,vrf,cidr AS master".($stampme eq 'm' ? ',modifystamp AS mtime' : '').
|
---|
1308 | " FROM allocations WHERE type='mm' ORDER BY cidr", { Slice => {} });
|
---|
1309 | return $mlist;
|
---|
1310 | } # end getMasterList()
|
---|
1311 |
|
---|
1312 |
|
---|
1313 | ## IPDB::getTypeList()
|
---|
1314 | # Get an alloctype/description pair list suitable for dropdowns
|
---|
1315 | # Takes a flag to determine which general groups of types are returned
|
---|
1316 | # Returns an reference to an array of hashrefs
|
---|
1317 | sub getTypeList {
|
---|
1318 | my $dbh = shift;
|
---|
1319 | my $tgroup = shift || 'a'; # technically optional, like this, but should
|
---|
1320 | # really be specified in the call for clarity
|
---|
1321 | my $seltype = shift || '';
|
---|
1322 |
|
---|
1323 | my $sql = "SELECT type,listname,type=? AS sel FROM alloctypes WHERE listorder <= 500";
|
---|
1324 | if ($tgroup eq 'n') {
|
---|
1325 | # grouping 'n' - all netblock types. These include routed blocks, containers (_c)
|
---|
1326 | # and contained (_r) types, dynamic-allocation ranges (_e), static IP pools (_d and _p),
|
---|
1327 | # and the "miscellaneous" cn, in, and en types.
|
---|
1328 | # Or in other words, everything but master and static IP types.
|
---|
1329 | $sql .= " AND type NOT LIKE '_i'";
|
---|
1330 | } elsif ($tgroup eq 'p') {
|
---|
1331 | # grouping 'p' - primary allocation types. As with 'n' above but without the _r contained types.
|
---|
1332 | $sql .= " AND type NOT LIKE '_i' AND type NOT LIKE '_r'";
|
---|
1333 | } elsif ($tgroup eq 'c') {
|
---|
1334 | # grouping 'c' - contained types. These include all static IPs and all _r types.
|
---|
1335 | $sql .= " AND (type LIKE '_i' OR type LIKE '_r')";
|
---|
1336 | } elsif ($tgroup eq 'i') {
|
---|
1337 | # grouping 'i' - static IP types.
|
---|
1338 | $sql .= " AND type LIKE '_i'";
|
---|
1339 | } else {
|
---|
1340 | # grouping 'a' - all standard allocation types. This includes everything
|
---|
1341 | # but mm (present only as a formality). Make this the default.
|
---|
1342 | # ... whee! no extra WHERE clauses
|
---|
1343 | }
|
---|
1344 | $sql .= " ORDER BY listorder";
|
---|
1345 | my $tlist = $dbh->selectall_arrayref($sql, { Slice => {} }, $seltype);
|
---|
1346 | return $tlist;
|
---|
1347 | }
|
---|
1348 |
|
---|
1349 |
|
---|
1350 | ## IPDB::getPoolSelect()
|
---|
1351 | # Get a list of pools matching the passed city and type that have 1 or more free IPs
|
---|
1352 | # Returns an arrayref to a list of hashrefs containing the number of available IPs, the CIDR pool,
|
---|
1353 | # and the city it's nominally in.
|
---|
1354 | sub getPoolSelect {
|
---|
1355 | my $dbh = shift;
|
---|
1356 | my $iptype = shift;
|
---|
1357 | my $pcity = shift;
|
---|
1358 |
|
---|
1359 | my $rangelimit = shift;
|
---|
1360 | if ($rangelimit) {
|
---|
1361 | if ($rangelimit !~ /^[\d\.\/]+$/) {
|
---|
1362 | # Just skip limiting on ridiculous range limits
|
---|
1363 | $rangelimit = '';
|
---|
1364 | } else {
|
---|
1365 | # now check for sanity
|
---|
1366 | $rangelimit = new NetAddr::IP $rangelimit;
|
---|
1367 | $rangelimit = '' if !$rangelimit;
|
---|
1368 | }
|
---|
1369 | }
|
---|
1370 |
|
---|
1371 | my ($ptype) = ($iptype =~ /^(.)i$/);
|
---|
1372 | return if !$ptype;
|
---|
1373 | $ptype .= '_';
|
---|
1374 |
|
---|
1375 | my @qargs = ($pcity, $ptype);
|
---|
1376 | push @qargs, "$rangelimit" if $rangelimit;
|
---|
1377 |
|
---|
1378 | my $plist = $dbh->selectall_arrayref( q(
|
---|
1379 | SELECT a.id as poolid,count(*) AS poolfree,a.cidr AS poolblock, a.city AS poolcit
|
---|
1380 | FROM poolips p
|
---|
1381 | JOIN allocations a ON p.parent_id=a.id
|
---|
1382 | WHERE p.available='y' AND a.city = ? AND p.type LIKE ?).
|
---|
1383 | ($rangelimit ? ' AND a.cidr << ?' : '').q(
|
---|
1384 | GROUP BY a.id,a.cidr,a.city
|
---|
1385 | ORDER BY a.cidr
|
---|
1386 | ),
|
---|
1387 | { Slice => {} }, @qargs );
|
---|
1388 | return $plist;
|
---|
1389 | } # end getPoolSelect()
|
---|
1390 |
|
---|
1391 |
|
---|
1392 | ## IPDB::findAllocateFrom()
|
---|
1393 | # Find free block to add a new allocation from. (CIDR block version of pool select above, more or less)
|
---|
1394 | # Takes
|
---|
1395 | # - mask length
|
---|
1396 | # - allocation type
|
---|
1397 | # - POP city "parent"
|
---|
1398 | # - optional master-block restriction
|
---|
1399 | # - optional flag to allow automatic pick-from-private-network-ranges
|
---|
1400 | # Returns a 3-element list with the free block ID, CIDR, and parent ID matching the criteria, if any
|
---|
1401 | sub findAllocateFrom {
|
---|
1402 | my $dbh = shift;
|
---|
1403 | my $maskbits = shift;
|
---|
1404 | my $type = shift;
|
---|
1405 | my $city = shift;
|
---|
1406 | my $pop = shift;
|
---|
1407 | my %optargs = @_;
|
---|
1408 |
|
---|
1409 | my $failmsg = "No suitable free block found\n";
|
---|
1410 |
|
---|
1411 | my @vallist;
|
---|
1412 | my $sql;
|
---|
1413 |
|
---|
1414 | # Free pool IPs should be easy.
|
---|
1415 | if ($type =~ /^.i$/) {
|
---|
1416 | # User may get an IP from the wrong VRF. User should not be using admin tools to allocate static IPs.
|
---|
1417 | $sql = "SELECT id, ip, parent_id FROM poolips WHERE ip = ?";
|
---|
1418 | @vallist = ($optargs{gimme});
|
---|
1419 | } else {
|
---|
1420 |
|
---|
1421 | ## Set up the SQL to find out what freeblock we can (probably) use for an allocation.
|
---|
1422 | ## Very large systems will require development of a reserve system (possibly an extension
|
---|
1423 | ## of the reserve-for-expansion concept in https://secure.deepnet.cx/trac/ipdb/ticket/24?)
|
---|
1424 | ## Also populate a value list for the DBI call.
|
---|
1425 |
|
---|
1426 | @vallist = ($maskbits);
|
---|
1427 | $sql = "SELECT id,cidr,parent_id FROM freeblocks WHERE masklen(cidr) <= ?";
|
---|
1428 |
|
---|
1429 | # cases, strict rules
|
---|
1430 | # .c -> container type
|
---|
1431 | # requires a routing container, fbtype r
|
---|
1432 | # .d -> DHCP/"normal-routing" static pool
|
---|
1433 | # requires a routing container, fbtype r
|
---|
1434 | # .e -> Dynamic-assignment connectivity
|
---|
1435 | # requires a routing container, fbtype r
|
---|
1436 | # .i -> error, can't allocate static IPs this way?
|
---|
1437 | # mm -> error, master block
|
---|
1438 | # rm -> routed block
|
---|
1439 | # requires master block, fbtype m
|
---|
1440 | # .n -> Miscellaneous usage
|
---|
1441 | # requires a routing container, fbtype r
|
---|
1442 | # .p -> PPP(oE) static pool
|
---|
1443 | # requires a routing container, fbtype r
|
---|
1444 | # .r -> contained type
|
---|
1445 | # requires a matching container, fbtype $1
|
---|
1446 | ##fixme: strict-or-not flag
|
---|
1447 |
|
---|
1448 | ##fixme: config or UI flag for "Strict" mode
|
---|
1449 | # if ($strictmode) {
|
---|
1450 | if (0) {
|
---|
1451 | if ($type =~ /^(.)r$/) {
|
---|
1452 | push @vallist, $1;
|
---|
1453 | $sql .= " AND routed = ?";
|
---|
1454 | } elsif ($type eq 'rm') {
|
---|
1455 | $sql .= " AND routed = 'm'";
|
---|
1456 | } else {
|
---|
1457 | $sql .= " AND routed = 'r'";
|
---|
1458 | }
|
---|
1459 | }
|
---|
1460 |
|
---|
1461 | # for PPP(oE) and container types, the POP city is the one attached to the pool.
|
---|
1462 | # individual allocations get listed with the customer city site.
|
---|
1463 | ##fixme: chain cities to align roughly with a full layer-2 node graph
|
---|
1464 | $city = $pop if $type !~ /^.[pc]$/;
|
---|
1465 | if ($type ne 'rm' && $city) {
|
---|
1466 | $sql .= " AND city = ?";
|
---|
1467 | push @vallist, $city;
|
---|
1468 | }
|
---|
1469 | # Allow specifying an arbitrary full block, instead of a master
|
---|
1470 | if ($optargs{gimme}) {
|
---|
1471 | $sql .= " AND cidr >>= ?";
|
---|
1472 | push @vallist, $optargs{gimme};
|
---|
1473 | }
|
---|
1474 | # if a specific master was requested, allow the requestor to self->shoot(foot)
|
---|
1475 | if ($optargs{master} && $optargs{master} ne '-') {
|
---|
1476 | $sql .= " AND master_id = ?";
|
---|
1477 | # if $optargs{master} ne '-';
|
---|
1478 | push @vallist, $optargs{master};
|
---|
1479 | } else {
|
---|
1480 | # if a specific master was NOT requested, filter out the RFC 1918 private networks
|
---|
1481 | if (!$optargs{allowpriv}) {
|
---|
1482 | $sql .= " AND NOT (cidr <<= '192.168.0.0/16' OR cidr <<= '10.0.0.0/8' OR cidr <<= '172.16.0.0/12')";
|
---|
1483 | }
|
---|
1484 | }
|
---|
1485 | # Keep "reserved" blocks out of automatic assignment.
|
---|
1486 | ##fixme: needs a UI flag or a config knob
|
---|
1487 | $sql .= " AND reserve_for = 0";
|
---|
1488 | # Sorting and limiting, since we don't (currently) care to provide a selection of
|
---|
1489 | # blocks to carve up. This preserves something resembling optimal usage of the IP
|
---|
1490 | # space by forcing contiguous allocations and free blocks as much as possible.
|
---|
1491 | $sql .= " ORDER BY masklen(cidr) DESC,cidr LIMIT 1";
|
---|
1492 | } # done setting up SQL for free CIDR block
|
---|
1493 |
|
---|
1494 | my ($fbid,$fbfound,$fbparent) = $dbh->selectrow_array($sql, undef, @vallist);
|
---|
1495 | return $fbid,$fbfound,$fbparent;
|
---|
1496 | } # end findAllocateFrom()
|
---|
1497 |
|
---|
1498 |
|
---|
1499 | ## IPDB::ipParent()
|
---|
1500 | # Get an IP's parent pool's details
|
---|
1501 | # Takes a database handle and IP
|
---|
1502 | # Returns a hashref to the parent pool block, if any
|
---|
1503 | sub ipParent {
|
---|
1504 | my $dbh = shift;
|
---|
1505 | my $block = shift;
|
---|
1506 |
|
---|
1507 | my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
|
---|
1508 | " WHERE cidr >>= ? AND (type LIKE '_p' OR type LIKE '_d')", undef, ($block) );
|
---|
1509 | return $pinfo;
|
---|
1510 | } # end ipParent()
|
---|
1511 |
|
---|
1512 |
|
---|
1513 | ## IPDB::subParent()
|
---|
1514 | # Get a block's parent's details
|
---|
1515 | # Takes a database handle and CIDR block
|
---|
1516 | # Returns a hashref to the parent container block, if any
|
---|
1517 | sub subParent {
|
---|
1518 | my $dbh = shift;
|
---|
1519 | my $block = shift;
|
---|
1520 |
|
---|
1521 | my $pinfo = $dbh->selectrow_hashref("SELECT cidr,custid,type,city,description FROM allocations".
|
---|
1522 | " WHERE cidr >>= ?", undef, ($block) );
|
---|
1523 | return $pinfo;
|
---|
1524 | } # end subParent()
|
---|
1525 |
|
---|
1526 |
|
---|
1527 | ## IPDB::blockParent()
|
---|
1528 | # Get a block's parent's details
|
---|
1529 | # Takes a database handle and CIDR block
|
---|
1530 | # Returns a hashref to the parent container block, if any
|
---|
1531 | sub blockParent {
|
---|
1532 | my $dbh = shift;
|
---|
1533 | my $block = shift;
|
---|
1534 |
|
---|
1535 | my $pinfo = $dbh->selectrow_hashref("SELECT cidr,city FROM routed".
|
---|
1536 | " WHERE cidr >>= ?", undef, ($block) );
|
---|
1537 | return $pinfo;
|
---|
1538 | } # end blockParent()
|
---|
1539 |
|
---|
1540 |
|
---|
1541 | ## IPDB::getBreadCrumbs()
|
---|
1542 | # Retrieve the ID and CIDR of a block's parent(s) up to the master block
|
---|
1543 | # Returns an arrayref to a list of hashrefs with CIDR and block ID
|
---|
1544 | sub getBreadCrumbs {
|
---|
1545 | my $dbh = shift;
|
---|
1546 | my $parent = shift || 0;
|
---|
1547 | my $vrf = shift; # if we're not browsing into netblocks yet, caller can pass the VRF for breadcrumbs
|
---|
1548 | my @result;
|
---|
1549 |
|
---|
1550 | my $sth = $dbh-> prepare("SELECT cidr,type,id,parent_id,vrf FROM allocations WHERE id=?");
|
---|
1551 |
|
---|
1552 | while ($parent != 0) {
|
---|
1553 | $sth->execute($parent);
|
---|
1554 | my ($cidr,$type,$id,$pid,$bvrf) = $sth->fetchrow_array;
|
---|
1555 | $vrf = $bvrf;
|
---|
1556 | push @result, { cidr => $cidr, link => $id, ispool => ($type =~ /^.[dp]$/ ? 1 : 0) };
|
---|
1557 | $parent = $pid;
|
---|
1558 | }
|
---|
1559 |
|
---|
1560 | push @result, { cidr => "vrf:$vrf", link => $vrf, isvrf => 1 }
|
---|
1561 | if $vrf;
|
---|
1562 |
|
---|
1563 | return \@result;
|
---|
1564 | } # end getBreadCrumbs()
|
---|
1565 |
|
---|
1566 |
|
---|
1567 | ## IPDB::getRoutedCity()
|
---|
1568 | # Get the city for a routed block.
|
---|
1569 | sub getRoutedCity {
|
---|
1570 | my $dbh = shift;
|
---|
1571 | my $block = shift;
|
---|
1572 |
|
---|
1573 | my ($rcity) = $dbh->selectrow_array("SELECT city FROM routed WHERE cidr = ?", undef, ($block) );
|
---|
1574 | return $rcity;
|
---|
1575 | } # end getRoutedCity()
|
---|
1576 |
|
---|
1577 |
|
---|
1578 | ## IPDB::allocateBlock()
|
---|
1579 | # Does all of the magic of actually allocating a netblock
|
---|
1580 | # Requires a database handle, and a hash containing the block to allocate, routing depth, custid,
|
---|
1581 | # type, city, block to allocate from, and optionally a description, notes, circuit ID,
|
---|
1582 | # and private data
|
---|
1583 | # Returns a success code and optional error message.
|
---|
1584 | sub allocateBlock {
|
---|
1585 | my $dbh = shift;
|
---|
1586 |
|
---|
1587 | my %args = @_;
|
---|
1588 |
|
---|
1589 | if ($args{cidr} eq 'Single static IP') {
|
---|
1590 | $args{cidr} = '';
|
---|
1591 | } else {
|
---|
1592 | $args{cidr} = new NetAddr::IP $args{cidr};
|
---|
1593 | }
|
---|
1594 |
|
---|
1595 | # Spaces don't show up well in lots of places. Make sure they don't get into the DB.
|
---|
1596 | $args{custid} =~ s/^\s+//;
|
---|
1597 | $args{custid} =~ s/\s+$//;
|
---|
1598 |
|
---|
1599 | $args{desc} = $args{description} if $args{description};
|
---|
1600 | $args{desc} = '' if !$args{desc};
|
---|
1601 | $args{notes} = '' if !$args{notes};
|
---|
1602 | $args{circid} = '' if !$args{circid};
|
---|
1603 | $args{privdata} = '' if !$args{privdata};
|
---|
1604 | ##fixme: VRF should trickle down like master_id
|
---|
1605 | $args{vrf} = '' if !$args{vrf};
|
---|
1606 | $args{vlan} = '' if !$args{vlan};
|
---|
1607 | $args{rdns} = '' if !$args{rdns};
|
---|
1608 | # customer accounts may have multiple allocations; tag the specific billing user for the allocation
|
---|
1609 | $args{billinguserid} = 0 if !$args{billinguserid};
|
---|
1610 |
|
---|
1611 | # munge the reverse name to include the default domain if there are no dots. Don't append if
|
---|
1612 | # there's no DNS argument though, that would likely cause Big Problems
|
---|
1613 | $args{rdns} .= ".$IPDB::domain" if $IPDB::append_domain && $args{rdns} && $args{rdns} !~ /\./;
|
---|
1614 |
|
---|
1615 | $args{user} = $args{rpcuser} if !$args{user};
|
---|
1616 |
|
---|
1617 | # Could arguably allow this for eg /120 allocations, but end users who get a single v4 IP are
|
---|
1618 | # usually given a v6 /64, and most v6 addressing schemes need at least half that address space
|
---|
1619 | if ($args{cidr} && $args{cidr}->{isv6} && $args{rdns} =~ /\%/) {
|
---|
1620 | return ('FAIL','Reverse DNS template patterns are not supported for IPv6 allocations');
|
---|
1621 | }
|
---|
1622 |
|
---|
1623 | my $sth;
|
---|
1624 |
|
---|
1625 | # Snag the "type" of the freeblock and its CIDR
|
---|
1626 | my ($alloc_from_type, $alloc_from, $fbparent, $fcity, $fbmaster) =
|
---|
1627 | $dbh->selectrow_array("SELECT routed,cidr,parent_id,city,master_id FROM freeblocks WHERE id = ?",
|
---|
1628 | undef, $args{fbid});
|
---|
1629 | $alloc_from = new NetAddr::IP $alloc_from;
|
---|
1630 | return ('FAIL',"Failed to allocate $args{cidr}; intended free block was used by another allocation.")
|
---|
1631 | if ($args{type} !~ /.i/ && !$fbparent);
|
---|
1632 | ##fixme: fail here if !$alloc_from
|
---|
1633 | # also consider "lock for allocation" due to multistep allocation process
|
---|
1634 |
|
---|
1635 | # To contain the error message, if any.
|
---|
1636 | my $msg = "Unknown error allocating $args{cidr} as '$disp_alloctypes{$args{type}}'";
|
---|
1637 |
|
---|
1638 | # Enable transactions and error handling
|
---|
1639 | local $dbh->{AutoCommit} = 0; # These need to be local so we don't
|
---|
1640 | local $dbh->{RaiseError} = 1; # step on our toes by accident.
|
---|
1641 |
|
---|
1642 | if ($args{type} =~ /^.i$/) {
|
---|
1643 | $msg = "Unable to assign static IP $args{cidr} to $args{custid}";
|
---|
1644 | eval {
|
---|
1645 | ##fixme: IP pools across VRFs, need to use the IP ID instead of the CIDR
|
---|
1646 | # ... or the VRF itself?
|
---|
1647 | if ($args{cidr}) {
|
---|
1648 | # IP specified
|
---|
1649 | my $availsql = "SELECT available FROM poolips WHERE ";
|
---|
1650 | my @availargs;
|
---|
1651 | if ($args{cidr} =~ /^\d+$/) {
|
---|
1652 | # IP passed as ID
|
---|
1653 | $availsql .= "id = ?";
|
---|
1654 | push @availargs, $args{cidr};
|
---|
1655 | } else {
|
---|
1656 | # IP passed as IP address
|
---|
1657 | $availsql .= "ip = ?";
|
---|
1658 | push @availargs, $args{cidr};
|
---|
1659 | }
|
---|
1660 | if ($args{parent}) {
|
---|
1661 | # Limit by parent ID
|
---|
1662 | $availsql .= " AND parent_id = ?";
|
---|
1663 | push @availargs, $args{parent};
|
---|
1664 | } elsif ($args{vfr}) {
|
---|
1665 | # Limit by VRF, but only if the parent ID isn't available
|
---|
1666 | $availsql .= " AND vrf = ?";
|
---|
1667 | push @availargs, $args{vrf};
|
---|
1668 | } else {
|
---|
1669 | # Fail if we don't have a handle for the pool
|
---|
1670 | die "Missing parent ID or VRF.\n";
|
---|
1671 | }
|
---|
1672 | my ($isavail) = $dbh->selectrow_array($availsql, undef, @availargs);
|
---|
1673 | die "IP is not in an IP pool.\n"
|
---|
1674 | if !$isavail;
|
---|
1675 | die "IP already allocated. Deallocate and reallocate, or update the entry\n"
|
---|
1676 | if $isavail eq 'n';
|
---|
1677 | } else { # IP not specified, take first available
|
---|
1678 | ($args{cidr}) = $dbh->selectrow_array("SELECT ip FROM poolips WHERE parent_id=? AND available='y' ORDER BY ip",
|
---|
1679 | undef, ($args{parent}) );
|
---|
1680 | }
|
---|
1681 |
|
---|
1682 | # backup
|
---|
1683 | my $backupid = 0;
|
---|
1684 | if ($args{backup}) {
|
---|
1685 | my $bksql = "INSERT INTO backuplist (";
|
---|
1686 | my @bkvals;
|
---|
1687 | my @bkfields;
|
---|
1688 | for my $bk (@backupfields) {
|
---|
1689 | if ($args{"bk$bk"}) {
|
---|
1690 | push @bkfields, "bk$bk";
|
---|
1691 | push @bkvals, $args{"bk$bk"};
|
---|
1692 | }
|
---|
1693 | }
|
---|
1694 | $bksql .= join(',',@bkfields).") VALUES (".join(',', map {'?'} @bkfields).")";
|
---|
1695 | $dbh->do($bksql, undef, @bkvals);
|
---|
1696 | ($backupid) = $dbh->selectrow_array("SELECT currval('backuplist_backup_id_seq')");
|
---|
1697 | }
|
---|
1698 |
|
---|
1699 | # finally assign the IP
|
---|
1700 | $dbh->do("UPDATE poolips SET custid = ?, city = ?, available='n', description = ?, notes = ?, vlan = ?, ".
|
---|
1701 | "circuitid = ?, privdata = ?, rdns = ?, backup_id = ?, userid = ? ".
|
---|
1702 | "WHERE ip = ? AND parent_id = ?", undef,
|
---|
1703 | ($args{custid}, $args{city}, $args{desc}, $args{notes}, $args{vlan},
|
---|
1704 | $args{circid}, $args{privdata}, $args{rdns}, $backupid, $args{billinguserid},
|
---|
1705 | $args{cidr}, $args{parent}) );
|
---|
1706 |
|
---|
1707 | # node hack
|
---|
1708 | if ($args{nodeid} && $args{nodeid} ne '') {
|
---|
1709 | $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
|
---|
1710 | }
|
---|
1711 | # end node hack
|
---|
1712 |
|
---|
1713 | $dbh->commit; # Allocate IP from pool
|
---|
1714 | };
|
---|
1715 | if ($@) {
|
---|
1716 | $msg .= ": $@";
|
---|
1717 | eval { $dbh->rollback; };
|
---|
1718 | return ('FAIL', $msg);
|
---|
1719 | } else {
|
---|
1720 | # Snag the pool info
|
---|
1721 | my $pinfo = getBlockData($dbh, $args{parent});
|
---|
1722 | # Only try to update rDNS when the pool is flagged as "rDNS available"
|
---|
1723 | if ($pinfo->{revavail} || $pinfo->{revpartial}) {
|
---|
1724 | _rpc('addOrUpdateRevRec', cidr => "$args{cidr}", name => $args{rdns}, rpcuser => $args{user},
|
---|
1725 | location => $pinfo->{location});
|
---|
1726 | }
|
---|
1727 | return ('OK', $args{cidr});
|
---|
1728 | }
|
---|
1729 |
|
---|
1730 | } else { # end IP-from-pool allocation
|
---|
1731 |
|
---|
1732 | if ($args{cidr} == $alloc_from) {
|
---|
1733 | # Easiest case- insert in one table, delete in the other, and go home. More or less.
|
---|
1734 |
|
---|
1735 | eval {
|
---|
1736 | $msg = "Unable to allocate $args{cidr} as '$disp_alloctypes{$args{type}}'";
|
---|
1737 |
|
---|
1738 | # backup
|
---|
1739 | my $backupid = 0;
|
---|
1740 | if ($args{backup}) {
|
---|
1741 | if (!$args{bkip}) {
|
---|
1742 | # check for /32-ness. no point in skipping /32 "netblocks", because they already single IPs
|
---|
1743 | die "Backup data set on a netblock requires a backup IP\n" unless $args{cidr} =~ m{/32$};
|
---|
1744 | $args{bkip} = $args{cidr};
|
---|
1745 | }
|
---|
1746 | my $bksql = "INSERT INTO backuplist (";
|
---|
1747 | my @bkfields;
|
---|
1748 | my @bkvals;
|
---|
1749 | for my $bk (@backupfields) {
|
---|
1750 | if ($args{"bk$bk"}) {
|
---|
1751 | push @bkfields, "bk$bk";
|
---|
1752 | push @bkvals, $args{"bk$bk"};
|
---|
1753 | }
|
---|
1754 | }
|
---|
1755 | $bksql .= join(',',@bkfields).") VALUES (".join(',',map {'?'} @bkfields).")";
|
---|
1756 | $dbh->do($bksql, undef, @bkvals);
|
---|
1757 | ($backupid) = $dbh->selectrow_array("SELECT currval('backuplist_backup_id_seq')");
|
---|
1758 | } # $args{backup}
|
---|
1759 |
|
---|
1760 | # Insert the allocations entry
|
---|
1761 | $dbh->do("INSERT INTO allocations ".
|
---|
1762 | "(cidr,parent_id,master_id,vrf,vlan,custid,type,city,description,notes,circuitid,privdata,rdns,backup_id,userid)".
|
---|
1763 | " VALUES (?,?,?,(SELECT vrf FROM allocations WHERE id=?),?,?,?,?,?,?,?,?,?,?,?)", undef,
|
---|
1764 | ($args{cidr}, $fbparent, $fbmaster, $fbmaster, $args{vlan}, $args{custid}, $args{type}, $args{city},
|
---|
1765 | $args{desc}, $args{notes}, $args{circid}, $args{privdata}, $args{rdns}, $backupid, $args{billinguserid}) );
|
---|
1766 | my ($bid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
|
---|
1767 |
|
---|
1768 | # Munge freeblocks
|
---|
1769 | if ($args{type} =~ /^(.)[mc]$/) {
|
---|
1770 | # special case - block is a routed or container/"reserve" block
|
---|
1771 | my $rtype = $1;
|
---|
1772 | $dbh->do("UPDATE freeblocks SET routed = ?,city = ?,parent_id = ? WHERE id = ?",
|
---|
1773 | undef, ($rtype, $args{city}, $bid, $args{fbid}) );
|
---|
1774 | } else {
|
---|
1775 | # "normal" case
|
---|
1776 | $dbh->do("DELETE FROM freeblocks WHERE id = ?", undef, ($args{fbid}) );
|
---|
1777 | }
|
---|
1778 |
|
---|
1779 | # And initialize the pool, if necessary
|
---|
1780 | # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
|
---|
1781 | # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
|
---|
1782 | if ($args{type} =~ /^.p$/) {
|
---|
1783 | $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
|
---|
1784 | my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "all", $bid);
|
---|
1785 | die $rmsg if $code eq 'FAIL';
|
---|
1786 | } elsif ($args{type} =~ /^.d$/) {
|
---|
1787 | $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
|
---|
1788 | my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "normal", $bid);
|
---|
1789 | die $rmsg if $code eq 'FAIL';
|
---|
1790 | }
|
---|
1791 |
|
---|
1792 | # node hack
|
---|
1793 | if ($args{nodeid} && $args{nodeid} ne '') {
|
---|
1794 | $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
|
---|
1795 | }
|
---|
1796 | # end node hack
|
---|
1797 |
|
---|
1798 | $dbh->commit; # Simple block allocation
|
---|
1799 | }; # end of eval
|
---|
1800 | if ($@) {
|
---|
1801 | $msg .= ": ".$@;
|
---|
1802 | eval { $dbh->rollback; };
|
---|
1803 | return ('FAIL',$msg);
|
---|
1804 | }
|
---|
1805 |
|
---|
1806 | } else { # cidr != alloc_from
|
---|
1807 |
|
---|
1808 | # Hard case. Allocation is smaller than free block.
|
---|
1809 |
|
---|
1810 | # make sure new allocation is in fact within freeblock. *sigh*
|
---|
1811 | return ('FAIL',"Requested allocation $args{cidr} is not within $alloc_from")
|
---|
1812 | if !$alloc_from->contains($args{cidr});
|
---|
1813 | my $wantmaskbits = $args{cidr}->masklen;
|
---|
1814 | my $maskbits = $alloc_from->masklen;
|
---|
1815 |
|
---|
1816 | my @newfreeblocks; # Holds free blocks generated from splitting the source freeblock.
|
---|
1817 |
|
---|
1818 | # This determines which blocks will be left "free" after allocation. We take the
|
---|
1819 | # block we're allocating from, and split it in half. We see which half the wanted
|
---|
1820 | # block is in, and repeat until the wanted block is equal to one of the halves.
|
---|
1821 | my $i=0;
|
---|
1822 | my $tmp_from = $alloc_from; # So we don't munge $args{alloc_from}
|
---|
1823 | while ($maskbits++ < $wantmaskbits) {
|
---|
1824 | my @subblocks = $tmp_from->split($maskbits);
|
---|
1825 | $newfreeblocks[$i++] = (($args{cidr}->within($subblocks[0])) ? $subblocks[1] : $subblocks[0]);
|
---|
1826 | $tmp_from = ( ($args{cidr}->within($subblocks[0])) ? $subblocks[0] : $subblocks[1] );
|
---|
1827 | } # while
|
---|
1828 |
|
---|
1829 | # Begin SQL transaction block
|
---|
1830 | eval {
|
---|
1831 | $msg = "Unable to allocate $args{cidr} as '$disp_alloctypes{$args{type}}'";
|
---|
1832 |
|
---|
1833 | # Delete old freeblocks entry
|
---|
1834 | $dbh->do("DELETE FROM freeblocks WHERE id = ?", undef, ($args{fbid}) );
|
---|
1835 |
|
---|
1836 | # Insert the allocations entry
|
---|
1837 | $dbh->do("INSERT INTO allocations ".
|
---|
1838 | "(cidr,parent_id,master_id,vrf,vlan,custid,type,city,description,notes,circuitid,privdata,rdns,userid)".
|
---|
1839 | " VALUES (?,?,?,(SELECT vrf FROM allocations WHERE id=?),?,?,?,?,?,?,?,?,?,?)", undef,
|
---|
1840 | ($args{cidr}, $fbparent, $fbmaster, $fbmaster, $args{vlan}, $args{custid}, $args{type}, $args{city},
|
---|
1841 | $args{desc}, $args{notes}, $args{circid}, $args{privdata}, $args{rdns}, $args{billinguserid}) );
|
---|
1842 | my ($bid) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
|
---|
1843 |
|
---|
1844 | # Insert new list of smaller free blocks left over. Flag the one that matches the
|
---|
1845 | # masklength of the new allocation, if a reserve block was requested.
|
---|
1846 | $sth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id,reserve_for) ".
|
---|
1847 | "VALUES (?,?,?,?,?,?,?)");
|
---|
1848 | foreach my $block (@newfreeblocks) {
|
---|
1849 | $sth->execute($block, $fcity, $alloc_from_type, $args{vrf}, $fbparent, $fbmaster,
|
---|
1850 | ($args{reserve} && $block->masklen == $wantmaskbits ? $bid : 0));
|
---|
1851 | }
|
---|
1852 |
|
---|
1853 | # For routed/container types, add a freeblock within the allocated block so we can subdivide it further
|
---|
1854 | if ($args{type} =~ /(.)[mc]/) { # rm and .c types - containers
|
---|
1855 | my $rtype = $1;
|
---|
1856 | $sth->execute($args{cidr}, $args{city}, $rtype, $args{vrf}, $bid, $fbmaster, 0);
|
---|
1857 | }
|
---|
1858 |
|
---|
1859 | # And initialize the pool, if necessary
|
---|
1860 | # PPPoE pools (currently dialup, DSL, and WiFi) get all IPs made available
|
---|
1861 | # "DHCP" or "real-subnet" pools have the net, gw, and bcast IPs removed.
|
---|
1862 | if ($args{type} =~ /^.p$/) {
|
---|
1863 | $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
|
---|
1864 | my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "all", $bid);
|
---|
1865 | die $rmsg if $code eq 'FAIL';
|
---|
1866 | } elsif ($args{type} =~ /^.d$/) {
|
---|
1867 | $msg = "Could not initialize IPs in new $disp_alloctypes{$args{type}} $args{cidr}";
|
---|
1868 | my ($code,$rmsg) = initPool($dbh, $args{cidr}, $args{type}, $args{city}, "normal", $bid);
|
---|
1869 | die $rmsg if $code eq 'FAIL';
|
---|
1870 | }
|
---|
1871 |
|
---|
1872 | # node hack
|
---|
1873 | if ($args{nodeid} && $args{nodeid} ne '') {
|
---|
1874 | $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($args{cidr}, $args{nodeid}) );
|
---|
1875 | }
|
---|
1876 | # end node hack
|
---|
1877 |
|
---|
1878 | $dbh->commit; # Complex block allocation
|
---|
1879 | }; # end eval
|
---|
1880 | if ($@) {
|
---|
1881 | $msg .= ": ".$@;
|
---|
1882 | eval { $dbh->rollback; };
|
---|
1883 | return ('FAIL',$msg);
|
---|
1884 | }
|
---|
1885 |
|
---|
1886 | } # end fullcidr != alloc_from
|
---|
1887 |
|
---|
1888 | # Snag the parent info
|
---|
1889 | my $pinfo = getBlockData($dbh, $fbparent);
|
---|
1890 | # Only try to update rDNS when the block is flagged as "rDNS available"
|
---|
1891 | if (($pinfo->{revavail} || $pinfo->{revpartial}) && ($args{rdns} || $args{iprev})) {
|
---|
1892 | # the netblock/allocation...
|
---|
1893 | _rpc('addOrUpdateRevRec', cidr => "$args{cidr}", name => $args{rdns}, rpcuser => $args{user},
|
---|
1894 | location => $pinfo->{location});
|
---|
1895 | # ...and the per-IP set, if there is one.
|
---|
1896 | _rpc('updateRevSet', %{$args{iprev}}, rpcuser => $args{user}, location => $pinfo->{location})
|
---|
1897 | if keys (%{$args{iprev}});
|
---|
1898 | }
|
---|
1899 |
|
---|
1900 | return ('OK', 'OK');
|
---|
1901 |
|
---|
1902 | } # end static-IP vs netblock allocation
|
---|
1903 |
|
---|
1904 | } # end allocateBlock()
|
---|
1905 |
|
---|
1906 |
|
---|
1907 | ## IPDB::initPool()
|
---|
1908 | # Initializes a pool
|
---|
1909 | # Requires a database handle, the pool CIDR, type, city, and a parameter
|
---|
1910 | # indicating whether the pool should allow allocation of literally every
|
---|
1911 | # IP, or if it should reserve network/gateway/broadcast IPs
|
---|
1912 | # Note that this is NOT done in a transaction, that's why it's a private
|
---|
1913 | # function and should ONLY EVER get called from allocateBlock()
|
---|
1914 | sub initPool {
|
---|
1915 | my ($dbh,undef,$type,$city,$class,$parent) = @_;
|
---|
1916 | my $pool = new NetAddr::IP $_[1];
|
---|
1917 |
|
---|
1918 | # IPv6 does not lend itself to IP pools as supported
|
---|
1919 | return ('FAIL',"Refusing to create IPv6 static IP pool\n") if $pool->{isv6};
|
---|
1920 | # IPv4 pools don't make much sense beyond even /24. Allow up to 4096-host footshooting anyway.
|
---|
1921 | # NetAddr::IP won't allow more than a /16 (65k hosts).
|
---|
1922 | return ('FAIL',"Refusing to create oversized static IP pool\n") if $pool->masklen <= 20;
|
---|
1923 |
|
---|
1924 | # Retrieve some odds and ends for defaults on the IPs
|
---|
1925 | my ($pcustid) = $dbh->selectrow_array("SELECT def_custid FROM alloctypes WHERE type=?", undef, ($type) );
|
---|
1926 | my ($vrf,$vlan,$master) = $dbh->selectrow_array("SELECT vrf,vlan,master_id FROM allocations WHERE id = ?",
|
---|
1927 | undef, ($parent) );
|
---|
1928 |
|
---|
1929 | $type =~ s/[pd]$/i/;
|
---|
1930 | my $sth;
|
---|
1931 | my $msg;
|
---|
1932 |
|
---|
1933 | eval {
|
---|
1934 | # have to insert all pool IPs into poolips table as "unallocated".
|
---|
1935 | $sth = $dbh->prepare("INSERT INTO poolips (ip,custid,city,type,parent_id,master_id,vrf) VALUES (?,?,?,?,?,?,?)");
|
---|
1936 |
|
---|
1937 | # in case of pool extension by some means, we need to see what IPs were already inserted
|
---|
1938 | my $tmp1 = $dbh->selectall_arrayref("SELECT ip FROM poolips WHERE parent_id = ?", undef, $parent);
|
---|
1939 | my %foundips;
|
---|
1940 | foreach (@{$tmp1}) {
|
---|
1941 | $foundips{$_->[0]} = 1;
|
---|
1942 | }
|
---|
1943 |
|
---|
1944 | # Dodge an edge case - pool where IPs have been "stolen" and turned into a netblock assignment.
|
---|
1945 | # We can't just "get all the current IPs, and add the missing ones", because some IPs are
|
---|
1946 | # legitimately missing (for stretchy values of "legitimately").
|
---|
1947 |
|
---|
1948 | my $pdata = getBlockData($dbh, $parent);
|
---|
1949 | my $pcidr = new NetAddr::IP $pdata->{block};
|
---|
1950 |
|
---|
1951 | if ($pcidr != $pool) {
|
---|
1952 | # enumerate the IPs from the *old* pool, flag them as "found", so we can iterate the entire
|
---|
1953 | # requested pool and still make sure we skip the IPs in the old pool - even if they've been
|
---|
1954 | # "stolen" by legacy netblocks.
|
---|
1955 | my @oldips = $pcidr->hostenum;
|
---|
1956 | # decide whether to start excluding existing IPs at the "gateway" or "gateway+1"
|
---|
1957 | my $ostart = ($pdata->{type} =~ /^.d$/ ? 1 : 0);
|
---|
1958 | for (my $i = $ostart; $i<= $#oldips; $i++) {
|
---|
1959 | $foundips{$oldips[$i]} = 1;
|
---|
1960 | }
|
---|
1961 | }
|
---|
1962 |
|
---|
1963 | # enumerate the hosts in the IP range - everything except the first (net) and last (bcast) IP
|
---|
1964 | my @poolip_list = $pool->hostenum;
|
---|
1965 |
|
---|
1966 | # always check/add IPs from gw+1 through bcast-1:
|
---|
1967 | # (but the set won't be in oooorderrrrr! <pout>)
|
---|
1968 | for (my $i=1; $i<=$#poolip_list; $i++) {
|
---|
1969 | my $baseip = $poolip_list[$i]->addr;
|
---|
1970 | if ($baseip !~ /\.(?:0|255)$/ && !$foundips{$poolip_list[$i]}) {
|
---|
1971 | $sth->execute($baseip, $pcustid, $city, $type, $parent, $master, $vrf);
|
---|
1972 | }
|
---|
1973 | }
|
---|
1974 |
|
---|
1975 | # now do the special case - DSL/PPP blocks can use the "net", "gw", and "bcast" IPs.
|
---|
1976 | # we exclude .0 and .255 anyway, since while they'll mostly work, they *will* behave badly here and there.
|
---|
1977 | if ($class eq 'all') { # (DSL-ish block - *all* IPs available
|
---|
1978 | if ($pool->addr !~ /\.0$/) { # .0 causes weirdness.
|
---|
1979 | $sth->execute($pool->addr, $pcustid, $city, $type, $parent, $master, $vrf)
|
---|
1980 | unless $foundips{$pool->addr."/32"};
|
---|
1981 | }
|
---|
1982 | $sth->execute($poolip_list[0]->addr, $pcustid, $city, $type, $parent, $master, $vrf)
|
---|
1983 | unless $foundips{$poolip_list[0]};
|
---|
1984 | $pool--;
|
---|
1985 | if ($pool->addr !~ /\.255$/) { # .255 can cause weirdness.
|
---|
1986 | $sth->execute($pool->addr, $pcustid, $city, $type, $parent, $master, $vrf)
|
---|
1987 | unless $foundips{$pool->addr."/32"};
|
---|
1988 | }
|
---|
1989 | }
|
---|
1990 | # don't commit here! the caller may not be done.
|
---|
1991 | # $dbh->commit;
|
---|
1992 | };
|
---|
1993 | if ($@) {
|
---|
1994 | $msg = $@;
|
---|
1995 | # Don't roll back! It's up to the caller to handle this.
|
---|
1996 | # eval { $dbh->rollback; };
|
---|
1997 | return ('FAIL',$msg);
|
---|
1998 | } else {
|
---|
1999 | return ('OK',"OK");
|
---|
2000 | }
|
---|
2001 | } # end initPool()
|
---|
2002 |
|
---|
2003 |
|
---|
2004 | ## IPDB::updateBlock()
|
---|
2005 | # Update an allocation
|
---|
2006 | # Takes all allocation fields in a hash
|
---|
2007 | sub updateBlock {
|
---|
2008 | my $dbh = shift;
|
---|
2009 | my %args = @_;
|
---|
2010 |
|
---|
2011 | return ('FAIL', 'Missing block to update') if !$args{block};
|
---|
2012 |
|
---|
2013 | # Spaces don't show up well in lots of places. Make sure they don't get into the DB.
|
---|
2014 | $args{custid} =~ s/^\s+//;
|
---|
2015 | $args{custid} =~ s/\s+$//;
|
---|
2016 |
|
---|
2017 | # do it all in a transaction
|
---|
2018 | local $dbh->{AutoCommit} = 0;
|
---|
2019 | local $dbh->{RaiseError} = 1;
|
---|
2020 |
|
---|
2021 | my @fieldlist;
|
---|
2022 | my @vallist;
|
---|
2023 | foreach ('custid', 'city', 'description', 'notes', 'circuitid', 'privdata', 'rdns', 'vrf', 'vlan') {
|
---|
2024 | if ($args{$_}) {
|
---|
2025 | push @fieldlist, $_;
|
---|
2026 | push @vallist, $args{$_};
|
---|
2027 | }
|
---|
2028 | }
|
---|
2029 |
|
---|
2030 | my $binfo;
|
---|
2031 | my $updtable = 'allocations';
|
---|
2032 | my $keyfield = 'id';
|
---|
2033 | if ($args{type} =~ /^(.)i$/) {
|
---|
2034 | $updtable = 'poolips';
|
---|
2035 | $binfo = getBlockData($dbh, $args{block}, 'i');
|
---|
2036 | # allow allocating an IP by update. mainly for RPC, may simplify matters for caller
|
---|
2037 | if ($args{assignIP_on_update}) {
|
---|
2038 | push @fieldlist, 'available';
|
---|
2039 | push @vallist, 'n';
|
---|
2040 | }
|
---|
2041 | } else {
|
---|
2042 | ## fixme: there's got to be a better way...
|
---|
2043 | $binfo = getBlockData($dbh, $args{block});
|
---|
2044 | if ($args{swip}) {
|
---|
2045 | if ($args{swip} eq 'on' || $args{swip} eq '1' || $args{swip} eq 'y') {
|
---|
2046 | $args{swip} = 'y';
|
---|
2047 | } else {
|
---|
2048 | $args{swip} = 'n';
|
---|
2049 | }
|
---|
2050 | }
|
---|
2051 | foreach ('type', 'swip') {
|
---|
2052 | if ($args{$_}) {
|
---|
2053 | push @fieldlist, $_;
|
---|
2054 | push @vallist, $args{$_};
|
---|
2055 | }
|
---|
2056 | }
|
---|
2057 | }
|
---|
2058 |
|
---|
2059 | return ('FAIL', 'No fields to update') if !@fieldlist;
|
---|
2060 |
|
---|
2061 | my $sql = "UPDATE $updtable SET ";
|
---|
2062 | $sql .= join " = ?, ", @fieldlist;
|
---|
2063 |
|
---|
2064 | # create these here so we can use the expanded CIDR in the rDNS update after the eval,
|
---|
2065 | # if we're expanding the block into a "reserved" freeblock
|
---|
2066 | my $cidr = NetAddr::IP->new($binfo->{block});
|
---|
2067 | my $newblock = NetAddr::IP->new($cidr->addr, $cidr->masklen - 1)->network;
|
---|
2068 |
|
---|
2069 | eval {
|
---|
2070 | # check for block merge first...
|
---|
2071 | if ($args{fbmerge}) {
|
---|
2072 | # safety net? make sure mergeable block passed in is really one or both of
|
---|
2073 | # a) reserved for expansion of the block and
|
---|
2074 | # b) confirmed CIDR-combinable
|
---|
2075 | # "safety? SELECT foo FROM freeblocks WHERE cidr << ? AND masklen(cidr) = ?, $newblock, ".$cidr->masklen."\n";
|
---|
2076 | $dbh->do("DELETE FROM freeblocks WHERE id=?", undef, $args{fbmerge});
|
---|
2077 | # ... so we can append the change in the stored CIDR field to extend the allocation.
|
---|
2078 | $sql .= " = ?, cidr";
|
---|
2079 | push @vallist, $newblock;
|
---|
2080 | # if we have an IP pool, call initPool to fill in any missing entries in the pool
|
---|
2081 | if ($binfo->{type} =~ /^.p$/) {
|
---|
2082 | my ($code,$rmsg) = initPool($dbh, "$newblock", $binfo->{type}, $binfo->{city}, 'all', $args{block});
|
---|
2083 | die $rmsg if $code eq 'FAIL';
|
---|
2084 | } elsif ($binfo->{type} =~ /^.d$/) {
|
---|
2085 | my ($code,$rmsg) = initPool($dbh, "$newblock", $binfo->{type}, $binfo->{city}, 'normal', $args{block});
|
---|
2086 | die $rmsg if $code eq 'FAIL';
|
---|
2087 | }
|
---|
2088 | }
|
---|
2089 |
|
---|
2090 | # backup
|
---|
2091 | if (!defined($args{ignorebk})) {
|
---|
2092 | # backup data considered "restricted"; caller should set this flag if user does not have 's' permission
|
---|
2093 |
|
---|
2094 | my $backupid = $binfo->{hasbk};
|
---|
2095 | if (!$binfo->{hasbk}) {
|
---|
2096 | if ($args{backup}) {
|
---|
2097 | # failure mode: backup data on netblock with no IP set
|
---|
2098 | if (!$args{bkip}) {
|
---|
2099 | # check for /32-ness. no point in skipping /32 "netblocks", because they already single IPs
|
---|
2100 | die "Backup data set on a netblock requires a backup IP\n" unless $binfo->{block} =~ m{/32$};
|
---|
2101 | $args{bkip} = $binfo->{block};
|
---|
2102 | }
|
---|
2103 | # insert new backup record since we don't have one
|
---|
2104 | my $bksql = "INSERT INTO backuplist (";
|
---|
2105 | my @bkfields;
|
---|
2106 | my @bkvals;
|
---|
2107 | for my $bk (@backupfields) {
|
---|
2108 | if ($args{"bk$bk"}) {
|
---|
2109 | push @bkfields, "bk$bk";
|
---|
2110 | push @bkvals, $args{"bk$bk"};
|
---|
2111 | }
|
---|
2112 | }
|
---|
2113 | $bksql .= join(',',@bkfields).") VALUES (".join(',', map {'?'} @bkfields).")";
|
---|
2114 | $dbh->do($bksql, undef, @bkvals);
|
---|
2115 | ($backupid) = $dbh->selectrow_array("SELECT currval('backuplist_backup_id_seq')");
|
---|
2116 | # add the backup ID to the update
|
---|
2117 | push @vallist, $backupid;
|
---|
2118 | $sql .= " = ?, backup_id";
|
---|
2119 | }
|
---|
2120 |
|
---|
2121 | } else { # !$binfo->{hasbk}
|
---|
2122 |
|
---|
2123 | # allocation already has backup data
|
---|
2124 | if ($args{backup}) {
|
---|
2125 | if (!$args{bkip}) {
|
---|
2126 | # check for /32-ness. no point in skipping /32 "netblocks", because they are already single IPs
|
---|
2127 | die "Backup data set on a netblock requires a backup IP\n" unless $binfo->{block} =~ m{/32$};
|
---|
2128 | $args{bkip} = $binfo->{block};
|
---|
2129 | }
|
---|
2130 | my @bkfields;
|
---|
2131 | my @bkvals;
|
---|
2132 | for my $bk (@backupfields) {
|
---|
2133 | no warnings qw( uninitialized );
|
---|
2134 | if ($binfo->{"bk$bk"} ne $args{"bk$bk"}) {
|
---|
2135 | push @bkfields, "bk$bk = ?";
|
---|
2136 | push @bkvals, $args{"bk$bk"};
|
---|
2137 | }
|
---|
2138 | }
|
---|
2139 |
|
---|
2140 | $dbh->do("UPDATE backuplist SET ".join(',', @bkfields)." WHERE backup_id = ?",
|
---|
2141 | undef, @bkvals, $binfo->{hasbk})
|
---|
2142 | if @bkfields;
|
---|
2143 | ##todo: keep historic changes for $timeperiod, by adding a backref ID field, and on updates adding a new backup
|
---|
2144 | # record instead of updating the existing one. should probably check if new==old so we don't do needless updates
|
---|
2145 | # in that case...
|
---|
2146 | } else {
|
---|
2147 | if ($binfo->{hasbk}) {
|
---|
2148 | # had backup data, no longer checked - delete backup entry
|
---|
2149 | $dbh->do("DELETE FROM backuplist WHERE backup_id = ?", undef, $binfo->{hasbk});
|
---|
2150 | $sql .= " = ?, backup_id";
|
---|
2151 | push @vallist, 0;
|
---|
2152 | }
|
---|
2153 | }
|
---|
2154 | } # $binfo->{hasbk} defined
|
---|
2155 | } # if !args{ignorebk}
|
---|
2156 |
|
---|
2157 | # append another SQL fragment
|
---|
2158 | push @vallist, $args{block};
|
---|
2159 | $sql .= " = ? WHERE $keyfield = ?";
|
---|
2160 |
|
---|
2161 | ##fixme: don't do the update on pool IPs if the IP is available and assignIP_on_update is not set
|
---|
2162 | # do the update
|
---|
2163 | $dbh->do($sql, undef, @vallist);
|
---|
2164 |
|
---|
2165 | if ($args{node}) {
|
---|
2166 | # done with delete/insert so we don't have to worry about funkyness updating a node ref that isn't there
|
---|
2167 | $dbh->do("DELETE FROM noderef WHERE block = ?", undef, ($binfo->{block}) );
|
---|
2168 | $dbh->do("INSERT INTO noderef (block,node_id) VALUES (?,?)", undef, ($binfo->{block}, $args{node}) )
|
---|
2169 | if $args{node} ne '--';
|
---|
2170 | }
|
---|
2171 |
|
---|
2172 | $dbh->commit;
|
---|
2173 | };
|
---|
2174 | if ($@) {
|
---|
2175 | my $msg = $@;
|
---|
2176 | $dbh->rollback;
|
---|
2177 | return ('FAIL', $msg);
|
---|
2178 | }
|
---|
2179 |
|
---|
2180 | # Do RPC rDNS call, if available.
|
---|
2181 | # Snag the parent info
|
---|
2182 | my $pinfo = getBlockData($dbh, $binfo->{parent_id});
|
---|
2183 | # Return early if rDNS flag(s) are not set
|
---|
2184 | return ('OK','OK') unless ($pinfo->{revavail} || $pinfo->{revpartial});
|
---|
2185 |
|
---|
2186 | # munge the reverse name to include the default domain if there are no dots. Don't append if
|
---|
2187 | # there's no DNS argument though, that would likely cause Big Problems
|
---|
2188 | $args{rdns} .= ".$IPDB::domain" if $IPDB::append_domain && $args{rdns} && $args{rdns} !~ /\./;
|
---|
2189 |
|
---|
2190 | # In case of any container (mainly master block), only update freeblocks so we don't stomp subs
|
---|
2191 | # (which would be the wrong thing in pretty much any case except "DELETE ALL EVARYTHING!!1!oneone!")
|
---|
2192 | if ($binfo->{type} =~ '.[mc]') {
|
---|
2193 | # Not using listFree() as it doesn't return quite all of the blocks wanted.
|
---|
2194 | # Retrieve the immediate free blocks
|
---|
2195 | my $sth = $dbh->prepare(q(
|
---|
2196 | SELECT cidr FROM freeblocks WHERE parent_id = ?
|
---|
2197 | UNION
|
---|
2198 | SELECT cidr FROM freeblocks f WHERE
|
---|
2199 | cidr = (SELECT cidr FROM allocations a WHERE f.cidr = a.cidr)
|
---|
2200 | AND master_id = ?
|
---|
2201 | ) );
|
---|
2202 | $sth->execute($args{block}, $binfo->{master_id});
|
---|
2203 | my %fbset;
|
---|
2204 | while (my ($fb) = $sth->fetchrow_array) {
|
---|
2205 | $fbset{"host_$fb"} = $args{rdns};
|
---|
2206 | }
|
---|
2207 | # We use this RPC call instead of multiple addOrUpdateRevRec calls, since we don't
|
---|
2208 | # know how many records we'll be updating and more than 3-4 is far too slow. This
|
---|
2209 | # should be safe to call unconditionally.
|
---|
2210 | # Requires dnsadmin >= r678
|
---|
2211 | _rpc('updateRevSet', %fbset, rpcuser => $args{user}, location => $pinfo->{location});
|
---|
2212 |
|
---|
2213 | } else {
|
---|
2214 | $binfo->{block} =~ s{/(?:32|128)$}{};
|
---|
2215 | # Only insert a record for IPv4, or actual single v6 IPs
|
---|
2216 | _rpc('addOrUpdateRevRec', cidr => $binfo->{block}, name => $args{rdns}, rpcuser => $args{user},
|
---|
2217 | location => $pinfo->{location})
|
---|
2218 | if !$cidr->{isv6} || ($cidr->{isv6} && $cidr->masklen == 128);
|
---|
2219 |
|
---|
2220 | # and the per-IP set, if there is one.
|
---|
2221 | _rpc('updateRevSet', cidr => $binfo->{block}, %{$args{iprev}}, rpcuser => $args{user},
|
---|
2222 | location => $pinfo->{location})
|
---|
2223 | if keys (%{$args{iprev}});
|
---|
2224 |
|
---|
2225 | # and fix up the template's CIDR if required
|
---|
2226 | _rpc('resizeTemplate', oldcidr => "$binfo->{block}", newcidr => $newblock->network.'',
|
---|
2227 | rpcuser => $args{user}, location => $pinfo->{location})
|
---|
2228 | if $args{fbmerge};
|
---|
2229 | }
|
---|
2230 |
|
---|
2231 | ##fixme: RPC failures?
|
---|
2232 | return ('OK','OK');
|
---|
2233 | } # end updateBlock()
|
---|
2234 |
|
---|
2235 |
|
---|
2236 | ## IPDB::splitBlock()
|
---|
2237 | # Splits an existing allocation into two or more smaller allocations based on a passed netmask
|
---|
2238 | # Duplicates all other data
|
---|
2239 | # Returns an arrayref to a list of hashrefs with ID and CIDR keys for the list of new allocations.
|
---|
2240 | # Should probably commit DNS magic to realign DNS data
|
---|
2241 | # Mostly works but may return Strange Things(TM) if used on a master block
|
---|
2242 | sub splitBlock {
|
---|
2243 | my $dbh = shift;
|
---|
2244 | my %args = @_;
|
---|
2245 |
|
---|
2246 | ##fixme: set errstr on errors so caller can suitably clue-by-four the user
|
---|
2247 | return if $args{basetype} ne 'b'; # only netblocks allowed!
|
---|
2248 |
|
---|
2249 | my $binfo = getBlockData($dbh, $args{id});
|
---|
2250 | return if !$binfo;
|
---|
2251 |
|
---|
2252 | return if $args{newmask} !~ /^\d+$/;
|
---|
2253 |
|
---|
2254 | my @ret;
|
---|
2255 | my $block = new NetAddr::IP $binfo->{block};
|
---|
2256 | my $oldmask = $block->masklen;
|
---|
2257 |
|
---|
2258 | # Fail if the block to split is "too small" - eg, can't split a v4 /32 at all
|
---|
2259 | # failure modes:
|
---|
2260 | # difference between $oldmask and $newmask is negative or 0
|
---|
2261 | if ($args{newmask} - $oldmask <= 0) {
|
---|
2262 | $errstr = "Can't split a /$oldmask allocation into /$args{newmask} pieces";
|
---|
2263 | return;
|
---|
2264 | }
|
---|
2265 | # # difference between $oldmask and $newmask is > n, for arbitrary n?
|
---|
2266 | # if ($newmask - $oldmask > 42) { # because 42
|
---|
2267 | # }
|
---|
2268 | # $oldmask > n, for arbitrary n? At least check limits of data type.
|
---|
2269 | if ($block->{isv6}) {
|
---|
2270 | if ($args{newmask} - $oldmask > 128) {
|
---|
2271 | $errstr = "Impossible IPv6 mask length /$args{newmask} requested";
|
---|
2272 | return;
|
---|
2273 | }
|
---|
2274 | } else {
|
---|
2275 | if ($args{newmask} - $oldmask > 32) {
|
---|
2276 | $errstr = "Impossible IPv4 mask length /$args{newmask} requested";
|
---|
2277 | return;
|
---|
2278 | }
|
---|
2279 | }
|
---|
2280 |
|
---|
2281 | my @newblocks = $block->split($args{newmask});
|
---|
2282 |
|
---|
2283 | local $dbh->{AutoCommit} = 0;
|
---|
2284 | local $dbh->{RaiseError} = 1;
|
---|
2285 |
|
---|
2286 | eval {
|
---|
2287 | # line up a list of fields and values. Be nice if there was a handy way to do,
|
---|
2288 | # direct in SQL, something like
|
---|
2289 | # "INSERT INTO foo (f1,f2,f3) VALUES (newf1,(SELECT oldf2,oldf3 FROM foo WHERE baz))"
|
---|
2290 | my @fieldlist = qw(type city description notes circuitid privdata custid swip vrf vlan rdns parent_id master_id userid);
|
---|
2291 | my $fields_sql = join(',', @fieldlist);
|
---|
2292 | my @vals;
|
---|
2293 | foreach (@fieldlist) {
|
---|
2294 | push @vals, $binfo->{$_};
|
---|
2295 | }
|
---|
2296 | # note the first block in the split for return
|
---|
2297 | push @ret, {nid => $args{id}, nblock => "$newblocks[0]"};
|
---|
2298 |
|
---|
2299 | # prepare
|
---|
2300 | my $idsth = $dbh->prepare("SELECT currval('allocations_id_seq')");
|
---|
2301 | my $allocsth = $dbh->prepare("INSERT INTO allocations (cidr, $fields_sql)".
|
---|
2302 | " VALUES (?".',?'x(scalar(@fieldlist)).")");
|
---|
2303 | my $allocsth2 = $dbh->prepare(qq(
|
---|
2304 | INSERT INTO allocations (cidr, $fields_sql)
|
---|
2305 | SELECT ? AS cidr, $fields_sql
|
---|
2306 | FROM allocations
|
---|
2307 | WHERE id = ?
|
---|
2308 | ) );
|
---|
2309 | my $nbsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip = ?");
|
---|
2310 | my $upd_psth = $dbh->prepare("UPDATE allocations SET parent_id = ? WHERE parent_id = ? AND cidr <<= ?");
|
---|
2311 | my $upd_msth = $dbh->prepare("UPDATE allocations SET master_id = ? WHERE master_id = ? AND cidr <<= ?");
|
---|
2312 | my $fb_psth = $dbh->prepare("UPDATE freeblocks SET parent_id = ? WHERE parent_id = ? AND cidr <<= ?");
|
---|
2313 | my $fb_msth = $dbh->prepare("UPDATE freeblocks SET master_id = ? WHERE master_id = ? AND cidr <<= ?");
|
---|
2314 | my $pool_psth = $dbh->prepare("UPDATE poolips SET parent_id = ? WHERE parent_id = ? AND ip << ?");
|
---|
2315 | my $pool_msth = $dbh->prepare("UPDATE poolips SET master_id = ? WHERE master_id = ? AND ip <<= ?");
|
---|
2316 |
|
---|
2317 | my @clist;
|
---|
2318 | _getChildren($dbh, $args{id}, $binfo->{master_id}, \@clist, $block);
|
---|
2319 |
|
---|
2320 | my @processlist;
|
---|
2321 | push @processlist, { id => $args{id}, cidr => $block, mask => $block->masklen, type => $binfo->{type} };
|
---|
2322 | foreach (@clist) {
|
---|
2323 | $_->{cidr} = new NetAddr::IP $_->{cidr};
|
---|
2324 | if ($_->{cidr}->masklen < $args{newmask}) {
|
---|
2325 | $_->{mask} = $_->{cidr}->masklen;
|
---|
2326 | push @processlist, $_;
|
---|
2327 | }
|
---|
2328 | }
|
---|
2329 |
|
---|
2330 | # Sort on masklen, crudely break ties by pushing container blocks down the stack. Multiple-nested containers
|
---|
2331 | # of the same size are virtually guaranteed to produce strange results, but should be rare enough to not matter
|
---|
2332 | @processlist = sort { $b->{cidr}->masklen <=> $a->{cidr}->masklen || $a->{type} =~ /^.m$/ } @processlist;
|
---|
2333 |
|
---|
2334 | foreach my $pr (@processlist) {
|
---|
2335 | my @nbset = $pr->{cidr}->split($args{newmask});
|
---|
2336 |
|
---|
2337 | # update existing block
|
---|
2338 | $dbh->do("UPDATE allocations SET cidr = ? WHERE id = ?", undef, ("$nbset[0]", $pr->{id}) );
|
---|
2339 |
|
---|
2340 | # axe the new bcast IP from the smaller pool at the "base" block, if it's a "normal" pool
|
---|
2341 | if ($pr->{type} =~ /.d/) {
|
---|
2342 | $nbset[0]--;
|
---|
2343 | $nbsth->execute($pr->{id}, $nbset[0]->addr);
|
---|
2344 | }
|
---|
2345 |
|
---|
2346 | # Holder for freeblocks-to-delete. Should be impossible to have more than one...
|
---|
2347 | my %fbdel;
|
---|
2348 |
|
---|
2349 | # Loop over the new blocks that are not the base block
|
---|
2350 | for (my $i = 1; $i <= $#nbset; $i++) {
|
---|
2351 | # add the new allocation
|
---|
2352 | $allocsth2->execute($nbset[$i], $pr->{id});
|
---|
2353 |
|
---|
2354 | # fetch the ID of the entry we just added...
|
---|
2355 | $idsth->execute();
|
---|
2356 | my ($nid) = $idsth->fetchrow_array();
|
---|
2357 | # ... so we can pass back the list of blocks and IDs...
|
---|
2358 | push @ret, {nid => $nid, nblock => "$nbset[$i]"};
|
---|
2359 | # axe the net, gw, and bcast IPs as necessary when splitting a "normal" pool
|
---|
2360 | if ($pr->{type} =~ /.d/) {
|
---|
2361 | # net
|
---|
2362 | $nbsth->execute($pr->{id}, $nbset[$i]->addr);
|
---|
2363 | $nbset[$i]++;
|
---|
2364 | # gw
|
---|
2365 | $nbsth->execute($pr->{id}, $nbset[$i]->addr);
|
---|
2366 | $nbset[$i]--;
|
---|
2367 | $nbset[$i]--;
|
---|
2368 | # bcast
|
---|
2369 | $nbsth->execute($pr->{id}, $nbset[$i]->addr);
|
---|
2370 | $nbset[$i]++;
|
---|
2371 | } # $binfo->{type} =~ /.d/
|
---|
2372 |
|
---|
2373 | # Check for free blocks larger than the new mask length, and split those as needed.
|
---|
2374 | if ($pr->{type} =~ /.[cm]/) {
|
---|
2375 | # get a "list" of freeblocks bigger than the allocation in the parent. there's only one, right?
|
---|
2376 | my $fblist = $dbh->selectall_arrayref("SELECT id FROM freeblocks WHERE cidr >> ? AND parent_id = ? ",
|
---|
2377 | {Slice=>{}}, $nbset[$i], $pr->{id});
|
---|
2378 | if (@$fblist) {
|
---|
2379 | # create a new freeblock for the new block we created earlier
|
---|
2380 | $dbh->do(q{
|
---|
2381 | INSERT INTO freeblocks (cidr, parent_id, master_id, city, routed,vrf)
|
---|
2382 | SELECT ? AS cidr, ? AS parent_id, master_id, city, routed, vrf FROM freeblocks
|
---|
2383 | WHERE id = ?
|
---|
2384 | }, undef, ($nbset[$i], $nid, $fblist->[0]->{id}) );
|
---|
2385 | $fbdel{$fblist->[0]->{id}}++;
|
---|
2386 | }
|
---|
2387 | } # $binfo->{type} =~ /.[cm]/
|
---|
2388 |
|
---|
2389 | # Reparent allocations, freeblocks, and pool IPs.
|
---|
2390 | $upd_psth->execute($nid, $pr->{id}, $nbset[$i]);
|
---|
2391 | $fb_psth->execute($nid, $pr->{id}, $nbset[$i]);
|
---|
2392 | $pool_psth->execute($nid, $pr->{id}, $nbset[$i]);
|
---|
2393 |
|
---|
2394 | # Update master if we've split a master block
|
---|
2395 | if ($pr->{type} eq 'mm') {
|
---|
2396 | $upd_msth->execute($nid, $pr->{id}, $nbset[$i]);
|
---|
2397 | $fb_msth->execute($nid, $pr->{id}, $nbset[$i]);
|
---|
2398 | $pool_msth->execute($nid, $pr->{id}, $nbset[$i]);
|
---|
2399 | }
|
---|
2400 |
|
---|
2401 | ##fixme:
|
---|
2402 | # 2015/09/09 not sure if the latest rewrite has covered this case complete or not
|
---|
2403 | # Still missing one edge case - megasplitting a large block such that "many" children also need to be split.
|
---|
2404 | # I'm going to call this "unsupported" because I really can't imagine a sane reason for doing this.
|
---|
2405 | # Should probably check and error out at least
|
---|
2406 |
|
---|
2407 | } # for (... @nbset)
|
---|
2408 |
|
---|
2409 | if (%fbdel) {
|
---|
2410 | # pretty sure this SELECT result isn't used...
|
---|
2411 | my $delfblist = $dbh->selectall_arrayref(q{
|
---|
2412 | SELECT cidr,parent_id,id FROM freeblocks
|
---|
2413 | WHERE id in (
|
---|
2414 | }.join(',', keys %fbdel).")", {Slice=>{}} );
|
---|
2415 | foreach my $fbd (keys %fbdel) {
|
---|
2416 | $dbh->do("UPDATE freeblocks SET cidr = set_masklen(cidr, ?) WHERE id = ?", undef, $args{newmask}, $fbd);
|
---|
2417 | }
|
---|
2418 | }
|
---|
2419 |
|
---|
2420 | } # foreach @processlist
|
---|
2421 |
|
---|
2422 | $dbh->commit;
|
---|
2423 | };
|
---|
2424 | if ($@) {
|
---|
2425 | $errstr = "Error splitting $binfo->{block}: $@";
|
---|
2426 | $dbh->rollback;
|
---|
2427 | return;
|
---|
2428 | }
|
---|
2429 |
|
---|
2430 | # Only try to update rDNS when the original block is flagged as "rDNS available"
|
---|
2431 | _rpc('splitTemplate', cidr => $binfo->{block}, newmask => $args{newmask}, rpcuser => $args{user},
|
---|
2432 | location => $binfo->{location})
|
---|
2433 | if ($binfo->{revavail} || $binfo->{revpartial});
|
---|
2434 |
|
---|
2435 | return \@ret;
|
---|
2436 | } # end splitBlock()
|
---|
2437 |
|
---|
2438 |
|
---|
2439 | ## IPDB::shrinkBlock()
|
---|
2440 | # Shrink an allocation to the passed CIDR block
|
---|
2441 | # Takes an allocation ID and a new CIDR
|
---|
2442 | # Returns an arrayref to a list of hashrefs with the ID and CIDR of the freed block(s)
|
---|
2443 | # Refuses to shrink "real netblock" pool types below /30
|
---|
2444 | sub shrinkBlock {
|
---|
2445 | my $dbh = shift;
|
---|
2446 | my $id = shift;
|
---|
2447 |
|
---|
2448 | # just take the new CIDR spec; this way we can shrink eg .16/28 to .20/30 without extra contortions
|
---|
2449 | my $newblock = new NetAddr::IP shift;
|
---|
2450 |
|
---|
2451 | my $user = shift;
|
---|
2452 |
|
---|
2453 | if (!$newblock) {
|
---|
2454 | $errstr = "Can't shrink something that's not a netblock";
|
---|
2455 | return;
|
---|
2456 | }
|
---|
2457 |
|
---|
2458 | my $binfo = getBlockData($dbh, $id);
|
---|
2459 | my $pinfo = getBlockData($dbh, $binfo->{parent_id});
|
---|
2460 |
|
---|
2461 | if ($binfo->{type} =~ /.d/ && $newblock->masklen > ($newblock->bits+2) ) {
|
---|
2462 | $errstr = "Can't shrink a non-PPP pool smaller than ".($newblock->{isv6} ? '/124' : '/30');
|
---|
2463 | return;
|
---|
2464 | }
|
---|
2465 |
|
---|
2466 | my $oldblock = new NetAddr::IP $binfo->{block};
|
---|
2467 |
|
---|
2468 | # Don't try to shrink the block outside of itself, Bad Things (probably) Happen.
|
---|
2469 | if (!$oldblock->contains($newblock)) {
|
---|
2470 | $errstr = "Can't shrink an allocation outside of itself";
|
---|
2471 | return;
|
---|
2472 | }
|
---|
2473 |
|
---|
2474 | local $dbh->{AutoCommit} = 0;
|
---|
2475 | local $dbh->{RaiseError} = 1;
|
---|
2476 |
|
---|
2477 | my $addfbsth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id) VALUES (?,?,?,?,?,?)");
|
---|
2478 | my $idsth = $dbh->prepare("SELECT currval('freeblocks_id_seq')");
|
---|
2479 | my $poolsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip << ?");
|
---|
2480 | my $netsth = $dbh->prepare("DELETE FROM poolips WHERE parent_id = ? AND ip = ?");
|
---|
2481 | my $allocsth = $dbh->prepare("DELETE FROM allocations WHERE parent_id = ? AND cidr <<= ?");
|
---|
2482 | my $delfbsth = $dbh->prepare("DELETE FROM freeblocks WHERE parent_id = ? AND cidr <<= ?");
|
---|
2483 |
|
---|
2484 | my @ret;
|
---|
2485 | my @newfreelist;
|
---|
2486 | eval {
|
---|
2487 | $dbh->do("UPDATE allocations SET cidr = ? WHERE id = ?", undef, $newblock, $id);
|
---|
2488 |
|
---|
2489 | # find the netblock(s) that are now free
|
---|
2490 | my @workingblocks = $oldblock->split($newblock->masklen);
|
---|
2491 | foreach my $newsub (@workingblocks) {
|
---|
2492 | next if $newsub == $newblock;
|
---|
2493 | push @newfreelist, $newsub;
|
---|
2494 | }
|
---|
2495 | @newfreelist = Compact(@newfreelist);
|
---|
2496 |
|
---|
2497 | # set new freeblocks, and clean up any IP pool entries if needed.
|
---|
2498 | foreach my $newfree (@newfreelist) {
|
---|
2499 | my @clist;
|
---|
2500 | # the block we're munging
|
---|
2501 | push @clist, { id => $id, type => $binfo->{type}, cidr => $binfo->{block} };
|
---|
2502 | _getChildren($dbh, $id, $binfo->{master_id}, \@clist, $newfree);
|
---|
2503 |
|
---|
2504 | foreach my $goner (@clist) {
|
---|
2505 | $poolsth->execute($goner->{id}, $newfree) if $goner->{type} =~ /.[dp]/;
|
---|
2506 | $allocsth->execute($goner->{id}, $newfree);
|
---|
2507 | $delfbsth->execute($goner->{id}, $newfree);
|
---|
2508 | }
|
---|
2509 |
|
---|
2510 | # No pinfo means we're shrinking a master block, which means the free space is returned outside of IPDB.
|
---|
2511 | if ($pinfo) {
|
---|
2512 | $addfbsth->execute($newfree, $pinfo->{city}, 'm', $pinfo->{vrf}, $binfo->{parent_id}, $pinfo->{master_id});
|
---|
2513 | $idsth->execute;
|
---|
2514 | my ($nid) = $idsth->fetchrow_array();
|
---|
2515 | # add to return list
|
---|
2516 | push @ret, {fbid => $nid, newfree => "$newfree", fbparent => $binfo->{parent_id} };
|
---|
2517 | }
|
---|
2518 |
|
---|
2519 | } # $newfree (@newfreelist)
|
---|
2520 |
|
---|
2521 | # additional cleanup on net/gw/bcast IPs in pool
|
---|
2522 | if ($binfo->{type} =~ /.d/) {
|
---|
2523 | $netsth->execute($id, $newblock->addr);
|
---|
2524 | $newblock++;
|
---|
2525 | $netsth->execute($id, $newblock->addr);
|
---|
2526 | $newblock--;
|
---|
2527 | $newblock--;
|
---|
2528 | $netsth->execute($id, $newblock->addr);
|
---|
2529 | }
|
---|
2530 |
|
---|
2531 | $dbh->commit;
|
---|
2532 | };
|
---|
2533 | if ($@) {
|
---|
2534 | $errstr = "Error splitting $binfo->{block}: $@";
|
---|
2535 | $dbh->rollback;
|
---|
2536 | return;
|
---|
2537 | }
|
---|
2538 |
|
---|
2539 | # Only try to update rDNS when the original block is flagged as "rDNS available"
|
---|
2540 | _rpc('resizeTemplate', oldcidr => $binfo->{block}, newcidr => $newblock->network, rpcuser => $user,
|
---|
2541 | location => $binfo->{location})
|
---|
2542 | if ($binfo->{revavail} || $binfo->{revpartial});
|
---|
2543 |
|
---|
2544 | return \@ret;
|
---|
2545 | } # end shrinkBlock()
|
---|
2546 |
|
---|
2547 |
|
---|
2548 | ## IPDB::mergeBlocks()
|
---|
2549 | # Merges two or more adjacent allocations, optionally including relevant
|
---|
2550 | # free space, into one allocation.
|
---|
2551 | # Takes a "base" block ID and a hash with a mask length and a scope argument to decide
|
---|
2552 | # how much existing allocation data to delete.
|
---|
2553 | # Returns a list starting with the new merged block, then the merged allocations with comment
|
---|
2554 | ## Merge scope:
|
---|
2555 | # Merge to container
|
---|
2556 | # keepall
|
---|
2557 | # Move all mergeable allocations into the new block
|
---|
2558 | # Move all mergeable free blocks into the new block
|
---|
2559 | # mergepeer
|
---|
2560 | # Move subs of mergeable containers into the updated primary.
|
---|
2561 | # Reparent free blocks in mergeable containers to the updated primary.
|
---|
2562 | # Convert assigned IPs from pools into subs.
|
---|
2563 | # Convert unused IPs from pools into free blocks.
|
---|
2564 | # Convert leaf allocations into free blocks.
|
---|
2565 | # clearpeer
|
---|
2566 | # Keep subs of the original (if it was a container).
|
---|
2567 | # Convert assigned IPs from the original pool into subs (if it was a pool).
|
---|
2568 | # Convert unused IPs from the original pool into free blocks (if it was a pool).
|
---|
2569 | # Delete all peers and their subs aside from the original.
|
---|
2570 | # clearall
|
---|
2571 | # Delete all peers, subs and IPs.
|
---|
2572 | # Add single free block for new container.
|
---|
2573 | # Merge to pool
|
---|
2574 | # keepall
|
---|
2575 | # Convert all leaf allocations in the merge range to groups of used IPs
|
---|
2576 | # mergepeer
|
---|
2577 | # Effectively equal to keepall
|
---|
2578 | # clearpeer
|
---|
2579 | # Only convert IPs from the original allocation to used IPs
|
---|
2580 | # clearall
|
---|
2581 | # Delete any existing IPs, and reinitialize the new pool entirely
|
---|
2582 | # Merge to leaf type
|
---|
2583 | # Remove all subs
|
---|
2584 | sub mergeBlocks {
|
---|
2585 | my $dbh = shift;
|
---|
2586 | my $prime = shift; # "base" block ID to use as a starting point
|
---|
2587 | if (!$prime) {
|
---|
2588 | $errstr = "Missing block ID to base merge on";
|
---|
2589 | return;
|
---|
2590 | }
|
---|
2591 |
|
---|
2592 | my %args = @_;
|
---|
2593 |
|
---|
2594 | # check key arguments.
|
---|
2595 | if (!$args{scope} || $args{scope} !~ /^(keepall|mergepeer|clearpeer|clearall)$/) {
|
---|
2596 | $errstr = "Bad or missing merge scope";
|
---|
2597 | return;
|
---|
2598 | }
|
---|
2599 | if (!$args{newmask} || $args{newmask} !~ /^\d+$/) {
|
---|
2600 | $errstr = "Bad or missing new netmask";
|
---|
2601 | return;
|
---|
2602 | }
|
---|
2603 |
|
---|
2604 | # Retrieve info about the base allocation we're munging
|
---|
2605 | my $binfo = getBlockData($dbh, $prime);
|
---|
2606 | my $block = new NetAddr::IP $binfo->{block};
|
---|
2607 | my ($basetype) = ($binfo->{type} =~ /^.(.)$/);
|
---|
2608 | $binfo->{id} = $prime; # preserve for later, just in case
|
---|
2609 |
|
---|
2610 | # proposed block
|
---|
2611 | my $newblock = new NetAddr::IP $block->addr."/$args{newmask}";
|
---|
2612 | $newblock = $newblock->network;
|
---|
2613 | $args{newtype} = $binfo->{type} if !$args{newtype};
|
---|
2614 | # if the "primary" block being changed is a master, it must remain one.
|
---|
2615 | # Also force the scope, since otherwise things get ugly.
|
---|
2616 | if ($binfo->{type} eq 'mm') {
|
---|
2617 | $args{newtype} = 'mm';
|
---|
2618 | # don't want to make a peer master a sub of the existing one; too many special cases go explodey,
|
---|
2619 | # but want to retain all other allocations
|
---|
2620 | $args{scope} = 'mergepeer';
|
---|
2621 | }
|
---|
2622 | my ($newcontainerclass) = ($args{newtype} =~ /^(.).$/);
|
---|
2623 |
|
---|
2624 | # build an info hash for the "new" allocation we're creating
|
---|
2625 | my $pinfo = {
|
---|
2626 | id => $prime,
|
---|
2627 | block => "$newblock",
|
---|
2628 | type => $args{newtype},
|
---|
2629 | parent_id =>
|
---|
2630 | $binfo->{parent_id},
|
---|
2631 | city => $binfo->{city},
|
---|
2632 | vrf => $binfo->{vrf},
|
---|
2633 | master_id => $binfo->{master_id}
|
---|
2634 | };
|
---|
2635 |
|
---|
2636 | my @retlist;
|
---|
2637 |
|
---|
2638 | local $dbh->{AutoCommit} = 0;
|
---|
2639 | local $dbh->{RaiseError} = 1;
|
---|
2640 |
|
---|
2641 | # Want to do all of the DB stuff in a transaction, to minimize data changing underfoot
|
---|
2642 | eval {
|
---|
2643 |
|
---|
2644 | # We always update the "prime" block passed in...
|
---|
2645 | my $updsth = $dbh->prepare("UPDATE allocations SET cidr = ?, type = ? WHERE id = ?");
|
---|
2646 |
|
---|
2647 | ##fixme: There's still an edge case in the return list where some branches accidentally include
|
---|
2648 | # the original block as "additional". Probably due to the ordering of when the prepared update
|
---|
2649 | # above gets executed.
|
---|
2650 |
|
---|
2651 | # For leaf blocks, we may need to create a new parent as the "primary" instead
|
---|
2652 | # of updating the existing block
|
---|
2653 | my $newparent = $dbh->prepare(q{
|
---|
2654 | INSERT INTO allocations (
|
---|
2655 | cidr, type, city, description, notes, circuitid, createstamp, modifystamp,
|
---|
2656 | privdata, custid, swip, vrf, vlan, rdns, parent_id, master_id
|
---|
2657 | )
|
---|
2658 | SELECT
|
---|
2659 | ? AS cidr, ? AS type, city, description, notes, circuitid, createstamp, modifystamp,
|
---|
2660 | privdata, custid, swip, vrf, vlan, rdns, parent_id, master_id
|
---|
2661 | FROM allocations
|
---|
2662 | WHERE id = ?
|
---|
2663 | });
|
---|
2664 |
|
---|
2665 | # Common actions
|
---|
2666 | my $peersth = $dbh->prepare("SELECT cidr,id,type,master_id FROM allocations WHERE parent_id = ? AND cidr <<= ?");
|
---|
2667 | $peersth->execute($binfo->{parent_id}, "$newblock");
|
---|
2668 | my $reparentsth = $dbh->prepare("UPDATE allocations SET parent_id = ?, master_id = ? WHERE id = ?");
|
---|
2669 | my $insfbsth = $dbh->prepare("INSERT INTO freeblocks (cidr,city,routed,vrf,parent_id,master_id) VALUES (?,?,?,?,?,?)");
|
---|
2670 | my $delsth = $dbh->prepare("DELETE FROM allocations WHERE id = ?");
|
---|
2671 |
|
---|
2672 | my $fbreparentsth = $dbh->prepare(q{
|
---|
2673 | UPDATE freeblocks
|
---|
2674 | SET parent_id = ?, master_id = ?, city = ?, routed = ?, vrf = ?
|
---|
2675 | WHERE parent_id = ? AND cidr <<= ?
|
---|
2676 | });
|
---|
2677 |
|
---|
2678 | if ($args{newtype} =~ /.[cm]/) {
|
---|
2679 | ## Container
|
---|
2680 |
|
---|
2681 | # In case of merging a master block. Somewhat redundant with calls to $fbreparentsth,
|
---|
2682 | # but not *quite* entirely.
|
---|
2683 | my $mfbsth = $dbh->prepare("UPDATE freeblocks SET master_id = ? WHERE master_id = ?");
|
---|
2684 |
|
---|
2685 | if ($args{scope} eq 'keepall') {
|
---|
2686 | # Create a new parent with the same info as the passed "primary".
|
---|
2687 | $newparent->execute($newblock, $args{newtype}, $prime);
|
---|
2688 | # and now retrieve the new parent ID
|
---|
2689 | ($prime) = $dbh->selectrow_array("SELECT currval('allocations_id_seq')");
|
---|
2690 | # snag the new parent info for the return list
|
---|
2691 | push @retlist, { block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime };
|
---|
2692 | # Reparent the free blocks in the new block
|
---|
2693 | $fbreparentsth->execute($prime, $binfo->{master_id}, $binfo->{city}, $newcontainerclass, $binfo->{vrf},
|
---|
2694 | $binfo->{parent_id}, $newblock);
|
---|
2695 | # keep existing allocations (including the original primary), just push them down a level
|
---|
2696 | while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
|
---|
2697 | $reparentsth->execute($prime, $binfo->{master_id}, $peer_id);
|
---|
2698 | # Fix up master_id on free blocks if we're merging a master block
|
---|
2699 | $mfbsth->execute($binfo->{master_id}, $m_id) if $peertype eq 'mm';
|
---|
2700 | # capture block for return
|
---|
2701 | push @retlist, { block => $peercidr, mdisp => $disp_alloctypes{$peertype}, mtype => $peertype };
|
---|
2702 | }
|
---|
2703 |
|
---|
2704 | } elsif ($args{scope} =~ /^clear/) {
|
---|
2705 | # clearpeer and clearall share a starting point
|
---|
2706 | # snag the new parent info for the return list
|
---|
2707 | push @retlist, { block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime };
|
---|
2708 | # update the primary allocation info
|
---|
2709 | $updsth->execute($newblock, $args{newtype}, $prime);
|
---|
2710 | # Reparent the free blocks in the new block
|
---|
2711 | $fbreparentsth->execute($prime, $binfo->{master_id}, $binfo->{city}, $newcontainerclass, $binfo->{vrf},
|
---|
2712 | $binfo->{parent_id}, $newblock);
|
---|
2713 | # Insert a free block if $prime is a leaf
|
---|
2714 | if ($binfo->{type} =~ /.[enr]/) {
|
---|
2715 | $insfbsth->execute($binfo->{block}, $binfo->{city}, $newcontainerclass, $binfo->{vrf}, $prime,
|
---|
2716 | $binfo->{master_id});
|
---|
2717 | }
|
---|
2718 | # delete the peers.
|
---|
2719 | while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
|
---|
2720 | next if $peer_id == $prime;
|
---|
2721 | # push existing allocations down a level before deleting,
|
---|
2722 | # so that when they're deleted the parent info is correct
|
---|
2723 | $reparentsth->execute($prime, $binfo->{master_id}, $peer_id);
|
---|
2724 | _deleteCascade($dbh, $peer_id);
|
---|
2725 | # insert the freeblock _deleteCascade() (deliberately) didn't when deleting a master block.
|
---|
2726 | # aren't special cases fun?
|
---|
2727 | $dbh->do("INSERT INTO freeblocks (cidr,routed,parent_id,master_id) values (?,?,?,?)",
|
---|
2728 | undef, ($peercidr, 'm', $prime, $prime) ) if $binfo->{type} eq 'mm';
|
---|
2729 | # capture block for return
|
---|
2730 | push @retlist, { block => $peercidr, mdisp => $disp_alloctypes{$peertype}, mtype => $peertype };
|
---|
2731 | }
|
---|
2732 | if ($args{scope} eq 'clearall') {
|
---|
2733 | # delete any subs of $prime as well
|
---|
2734 | my $substh = $dbh->prepare("SELECT cidr,id FROM allocations WHERE parent_id = ?");
|
---|
2735 | $substh->execute($prime);
|
---|
2736 | while (my ($scidr, $s_id) = $substh->fetchrow_array) {
|
---|
2737 | _deleteCascade($dbh, $s_id);
|
---|
2738 | }
|
---|
2739 | } else {
|
---|
2740 | # clearpeer
|
---|
2741 | if ($basetype =~ /[dp]/) {
|
---|
2742 | # Convert active IP pool entries to allocations if the original was an IP pool
|
---|
2743 | _poolToAllocations($dbh, $binfo, $pinfo, newtype => $poolmap{$binfo->{type}});
|
---|
2744 | }
|
---|
2745 | } # clearall or clearpeer
|
---|
2746 |
|
---|
2747 | } elsif ($args{scope} eq 'mergepeer') { # should this just be an else?
|
---|
2748 | # Default case. Merge "peer" blocks, but keep all suballocations
|
---|
2749 | # snag the new parent info for the return list
|
---|
2750 | push @retlist, {block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime};
|
---|
2751 | my $substh = $dbh->prepare("UPDATE allocations SET parent_id = ? WHERE parent_id = ?");
|
---|
2752 | my $delsth = $dbh->prepare("DELETE FROM allocations WHERE id = ?");
|
---|
2753 | # Reparent freeblocks in parent
|
---|
2754 | $fbreparentsth->execute($prime, $binfo->{master_id}, $binfo->{city}, $newcontainerclass, $binfo->{vrf},
|
---|
2755 | $binfo->{parent_id}, $newblock);
|
---|
2756 | # Loop over "peer" allocations to be merged
|
---|
2757 | while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
|
---|
2758 | # Snag existing peer data since we may need it
|
---|
2759 | my $peerfull = getBlockData($dbh, $peer_id);
|
---|
2760 | # Reparent free blocks from existing containers
|
---|
2761 | $fbreparentsth->execute($prime, $binfo->{master_id}, $binfo->{city}, $newcontainerclass,
|
---|
2762 | $binfo->{vrf}, $peer_id, $newblock);
|
---|
2763 | # Reparent any subblocks from existing containers
|
---|
2764 | $substh->execute($prime, $peer_id);
|
---|
2765 | # Delete the old container
|
---|
2766 | $delsth->execute($peer_id) unless $peer_id == $prime;
|
---|
2767 | # Add new freeblocks for merged leaf blocks
|
---|
2768 | $insfbsth->execute($peercidr, $binfo->{city}, $newcontainerclass, $binfo->{vrf}, $binfo->{id},
|
---|
2769 | $binfo->{master_id}) if $peertype =~ /.[enr]/;
|
---|
2770 | # Convert pool IPs into allocations or aggregated free blocks
|
---|
2771 | _poolToAllocations($dbh, $peerfull, $pinfo, newparent => $prime) if $peertype =~ /.[dp]/;
|
---|
2772 | # Fix up master_id on free blocks if we're merging a master block
|
---|
2773 | $mfbsth->execute($binfo->{master_id}, $m_id) if $peertype eq 'mm';
|
---|
2774 | # capture block for return
|
---|
2775 | push @retlist, { block => $peercidr, mdisp => $disp_alloctypes{$peertype}, mtype => $peertype };
|
---|
2776 | } # merge peers
|
---|
2777 | # update the primary allocation info. Do this last so we don't stomp extra data-retrieval in the loop above
|
---|
2778 | $updsth->execute($newblock, $args{newtype}, $prime);
|
---|
2779 |
|
---|
2780 | } # scope
|
---|
2781 |
|
---|
2782 | # Clean up free blocks
|
---|
2783 | _compactFree($dbh, $prime);
|
---|
2784 |
|
---|
2785 | } elsif ($args{newtype} =~ /.[dp]/) {
|
---|
2786 | ## Pool
|
---|
2787 | # Snag the new parent info for the return list
|
---|
2788 | push @retlist, { block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime };
|
---|
2789 |
|
---|
2790 | if ($args{scope} eq 'keepall') {
|
---|
2791 | # Convert all mergeable allocations and subs to chunks of pool IP assignments
|
---|
2792 | push @retlist, @{ _toPool($dbh, $prime, $newblock, $args{newtype}, 1) };
|
---|
2793 |
|
---|
2794 | } elsif ($args{scope} =~ /^clear/) {
|
---|
2795 | # Clear it all out for a fresh (mostly?) empty IP pool
|
---|
2796 | while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
|
---|
2797 | next if $peer_id == $prime;
|
---|
2798 | # Push existing allocations down a level before deleting,
|
---|
2799 | # so that when they're deleted the parent info is correct
|
---|
2800 | $reparentsth->execute($prime, $binfo->{master_id}, $peer_id);
|
---|
2801 | _deleteCascade($dbh, $peer_id, 0);
|
---|
2802 | # Capture block for return
|
---|
2803 | push @retlist, { block => $peercidr, mdisp => $disp_alloctypes{$peertype}, mtype => $peertype };
|
---|
2804 | }
|
---|
2805 | if ($args{scope} eq 'clearall') {
|
---|
2806 | # Delete any subs of $prime as well
|
---|
2807 | my $substh = $dbh->prepare("SELECT cidr,id FROM allocations WHERE parent_id = ?");
|
---|
2808 | $substh->execute($prime);
|
---|
2809 | while (my ($scidr, $s_id) = $substh->fetchrow_array) {
|
---|
2810 | _deleteCascade($dbh, $s_id);
|
---|
2811 | }
|
---|
2812 | } else {
|
---|
2813 | # Convert (subs of) self if not a leaf.
|
---|
2814 | push @retlist, @{ _toPool($dbh, $prime, $newblock, $args{newtype}, 1) }
|
---|
2815 | unless $binfo->{type} =~ /.[enr]/;
|
---|
2816 | } # scope ne 'clearall'
|
---|
2817 |
|
---|
2818 | } elsif ($args{scope} eq 'mergepeer') {
|
---|
2819 | # Try to match behaviour from (target type == container) by deleting immediate peer leaf allocations
|
---|
2820 | while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
|
---|
2821 | next if $peer_id == $prime; # don't delete the block we're turning into the pool allocation
|
---|
2822 | # Capture block for return
|
---|
2823 | push @retlist, { block => $peercidr, mdisp => $disp_alloctypes{$peertype}, mtype => $peertype };
|
---|
2824 | next unless $peertype =~ /.[enr]/;
|
---|
2825 | # Don't need _deleteCascade(), since we'll just be deleting the freshly
|
---|
2826 | # added free block a little later anyway
|
---|
2827 | $delsth->execute($peer_id);
|
---|
2828 | }
|
---|
2829 | # Convert self if not a leaf, to match behaviour with a container type as target
|
---|
2830 | _toPool($dbh, $prime, $newblock, $args{newtype}) unless $binfo->{type} =~ /.[enr]/;
|
---|
2831 | }
|
---|
2832 | # Update the primary allocation info.
|
---|
2833 | $updsth->execute($newblock, $args{newtype}, $prime);
|
---|
2834 | # Delete any lingering free blocks
|
---|
2835 | $dbh->do("DELETE FROM freeblocks WHERE parent_id = ? AND cidr <<= ?", undef, $binfo->{parent_id}, $newblock);
|
---|
2836 | # Fix up the rest of the pool IPs
|
---|
2837 | my ($code,$msg) = initPool($dbh, $newblock, $args{newtype}, $binfo->{city},
|
---|
2838 | ($args{newtype} =~ /.p/ ? 'all' : 'normal'), $prime);
|
---|
2839 |
|
---|
2840 | } elsif ($args{newtype} =~ /.[enr]/) {
|
---|
2841 | ## Leaf
|
---|
2842 | # Merging to a leaf type of any kind is, pretty much be definition, scope == 'clearall'.
|
---|
2843 | # keepall, mergepeer, and clearpeer all imply keeping suballocations, where leaf allocations
|
---|
2844 | # by definition do not have suballocations.
|
---|
2845 | # Update the old allocation
|
---|
2846 | $updsth->execute($newblock, $args{newtype}, $prime);
|
---|
2847 | # Snag the new parent info for the return list
|
---|
2848 | push @retlist, {block => "$newblock", type => $disp_alloctypes{$args{newtype}}, id => $prime};
|
---|
2849 | while (my ($peercidr, $peer_id, $peertype, $m_id) = $peersth->fetchrow_array) {
|
---|
2850 | next if $peer_id == $prime;
|
---|
2851 | # Push existing allocations down a level before deleting,
|
---|
2852 | # so that when they're deleted the parent info is correct
|
---|
2853 | $reparentsth->execute($prime, $binfo->{master_id}, $peer_id);
|
---|
2854 | _deleteCascade($dbh, $peer_id, 0);
|
---|
2855 | # Capture block for return
|
---|
2856 | push @retlist, { block => $peercidr, mdisp => $disp_alloctypes{$peertype}, mtype => $peertype };
|
---|
2857 | }
|
---|
2858 | # Delete any subs of $prime as well
|
---|
2859 | my $substh = $dbh->prepare("SELECT cidr,id FROM allocations WHERE parent_id = ?");
|
---|
2860 | $substh->execute($prime);
|
---|
2861 | while (my ($scidr, $s_id) = $substh->fetchrow_array) {
|
---|
2862 | _deleteCascade($dbh, $s_id);
|
---|
2863 | }
|
---|
2864 | # Clean up lingering free blocks and pool IPs
|
---|
2865 | $dbh->do("DELETE FROM freeblocks WHERE cidr <<= ? AND (parent_id = ? OR parent_id = ?)", undef,
|
---|
2866 | $newblock, $binfo->{parent_id}, $prime);
|
---|
2867 | $dbh->do("DELETE FROM poolips WHERE parent_id = ? AND ip <<= ? ", undef,
|
---|
2868 | $prime, $newblock);
|
---|
2869 |
|
---|
2870 | } # $args{newtype} if()
|
---|
2871 |
|
---|
2872 | $dbh->commit;
|
---|
2873 | };
|
---|
2874 | if ($@) {
|
---|
2875 | my $msg = $@;
|
---|
2876 | $errstr = $msg;
|
---|
2877 | $dbh->rollback;
|
---|
2878 | return ('FAIL',$msg);
|
---|
2879 | }
|
---|
2880 |
|
---|
2881 | # Make the assumption that any change crossing /24 or /16 boundaries will not come out right. Reverse DNS
|
---|
2882 | # updates for this operation are already complex enough without handling those edge cases.
|
---|
2883 | # ... er, how do we detect this?
|
---|
2884 |
|
---|
2885 | # Return early if the block wasn't flagged as rDNS-able
|
---|
2886 | return \@retlist unless $binfo->{revavail} || $binfo->{revpartial};
|
---|
2887 |
|
---|
2888 | if ($args{newtype} =~ /.[cm]/) {
|
---|
2889 |
|
---|
2890 | if ($args{scope} eq 'keepall') {
|
---|
2891 | # Add new rDNS for new container
|
---|
2892 | _rpc('addOrUpdateRevRec', cidr => $binfo->{block}, name => $binfo->{rdns}, rpcuser => $args{user},
|
---|
2893 | location => $binfo->{location});
|
---|
2894 |
|
---|
2895 | } else {
|
---|
2896 | # Resize rDNS template for $prime
|
---|
2897 | _rpc('resizeTemplate', oldcidr => "$binfo->{block}", newcidr => $newblock->network.'',
|
---|
2898 | rpcuser => $args{user}, location => $binfo->{location});
|
---|
2899 |
|
---|
2900 | # Assemble a list of blocks to delete...
|
---|
2901 | my $cidrlist;
|
---|
2902 | foreach my $mblock (@retlist) {
|
---|
2903 | $cidrlist .= $mblock->{block}."," unless $mblock->{block} =~ $newblock;
|
---|
2904 | }
|
---|
2905 |
|
---|
2906 | # ... then make slight variant batch delete calls depending on the merge scope
|
---|
2907 | if ($args{scope} eq 'mergepeer') {
|
---|
2908 | # Delete separate rDNS for other peers
|
---|
2909 | $cidrlist =~ s/,$//;
|
---|
2910 | _rpc('delRevSet', cidrlist => $cidrlist, rpcuser => $args{user}, delforward => 'y', delsubs => 'n',
|
---|
2911 | parpatt => $pinfo->{rdns}, location => $binfo->{location});
|
---|
2912 |
|
---|
2913 | } elsif ($args{scope} eq 'clearpeer') {
|
---|
2914 | # Delete all rDNS within other peers
|
---|
2915 | $cidrlist =~ s/,$//;
|
---|
2916 | _rpc('delRevSet', cidrlist => $cidrlist, rpcuser => $args{user}, delforward => 'y', delsubs => 'y',
|
---|
2917 | parpatt => $pinfo->{rdns}, location => $binfo->{location});
|
---|
2918 |
|
---|
2919 | } elsif ($args{scope} eq 'clearall') {
|
---|
2920 | # Delete all other records within the new block
|
---|
2921 | $cidrlist .= $binfo->{block};
|
---|
2922 | _rpc('delRevSet', cidrlist => $cidrlist, rpcuser => $args{user}, delforward => 'y', delsubs => 'y',
|
---|
2923 | parpatt => $pinfo->{rdns}, location => $binfo->{location});
|
---|
2924 |
|
---|
2925 | } # scope, second level
|
---|
2926 | } # scope, !keepall
|
---|
2927 |
|
---|
2928 | } elsif ($args{newtype} =~ /.[dp]/) {
|
---|
2929 | # Merge to pool
|
---|
2930 |
|
---|
2931 | # Resize rDNS template for $prime
|
---|
2932 | _rpc('resizeTemplate', oldcidr => "$binfo->{block}", newcidr => $newblock->network.'',
|
---|
2933 | rpcuser => $args{user}, location => $binfo->{location});
|
---|
2934 |
|
---|
2935 | if ($args{scope} eq 'keepall' || $args{scope} eq 'mergepeer') {
|
---|
2936 | # Assemble a list of blocks to convert from template to individual records...
|
---|
2937 | my @convlist;
|
---|
2938 | my @dellist;
|
---|
2939 | foreach my $mblock (@retlist) {
|
---|
2940 | next if $mblock->{block} =~ $newblock;
|
---|
2941 | if ($mblock->{mtype} =~ /.[cmdp]/) {
|
---|
2942 | # Container and pool templates get deleted
|
---|
2943 | push @dellist, $mblock->{block};
|
---|
2944 | } else {
|
---|
2945 | # Not-containers get converted to per-IP reverse records
|
---|
2946 | push @convlist, $mblock->{block};
|
---|
2947 | }
|
---|
2948 | }
|
---|
2949 | # And do the calls.
|
---|
2950 | _rpc('delRevSet', cidrlist => join(',', @dellist), rpcuser => $args{user}, delforward => 'y', delsubs => 'n',
|
---|
2951 | parpatt => $pinfo->{rdns}, location => $binfo->{location});
|
---|
2952 | _rpc('templatesToRecords', templates => \@convlist, rpcuser => $args{user}, location => $binfo->{location});
|
---|
2953 |
|
---|
2954 | } # scope eq 'keepall' || 'mergepeer'
|
---|
2955 | else {
|
---|
2956 |
|
---|
2957 | # Assemble a list of blocks to convert from template to individual records...
|
---|
2958 | my @convlist;
|
---|
2959 | my @dellist;
|
---|
2960 | my @fulldellist;
|
---|
2961 | # There may be an impossible edge case that can be optimized away in here...
|
---|
2962 | foreach my $mblock (@retlist) {
|
---|
2963 | my $checkcidr = new NetAddr::IP $mblock->{block};
|
---|
2964 | next if $mblock->{block} =~ $newblock;
|
---|
2965 | if (!$block->contains($checkcidr)) {
|
---|
2966 | # Blocks not within the original get deleted
|
---|
2967 | push @fulldellist, $mblock->{block};
|
---|
2968 | }
|
---|
2969 | elsif ($mblock->{mtype} =~ /.[cmdp]/) {
|
---|
2970 | # Containers and pools get deleted
|
---|
2971 | push @dellist, $mblock->{block};
|
---|
2972 | } else {
|
---|
2973 | # Whatever's left over gets converted
|
---|
2974 | push @convlist, $mblock->{block};
|
---|
2975 | }
|
---|
2976 | } # foreach @retlist
|
---|
2977 | # And do the calls.
|
---|
2978 | if ($args{scope} eq 'clearpeer') {
|
---|
2979 | # Not happy doing this many, but there isn't really a better way.
|
---|
2980 | # We delete ALL EVARYTHING in peer blocks...
|
---|
2981 | _rpc('delRevSet', cidrlist => join(',', @fulldellist), rpcuser => $args{user}, delforward => 'y',
|
---|
2982 | delsubs => 'y', parpatt => $pinfo->{rdns}, location => $binfo->{location})
|
---|
2983 | if @fulldellist;
|
---|
2984 | # ... and just the template for container or pool templates in $prime...
|
---|
2985 | _rpc('delRevSet', cidrlist => join(',', @dellist), rpcuser => $args{user}, delforward => 'y',
|
---|
2986 | delsubs => 'n', parpatt => $pinfo->{rdns}, location => $binfo->{location})
|
---|
2987 | if @dellist;
|
---|
2988 | # ... and convert a few to record groups
|
---|
2989 | _rpc('templatesToRecords', templates => \@convlist, rpcuser => $args{user},
|
---|
2990 | location => $binfo->{location})
|
---|
2991 | if @convlist;
|
---|
2992 | }
|
---|
2993 | if ($args{scope} eq 'clearall') {
|
---|
2994 | # consider just doing join(',',$newblock->split($newblock->masklen+1))?
|
---|
2995 | _rpc('delRevSet', cidrlist => join(',', @fulldellist, @dellist, @convlist, $binfo->{block}),
|
---|
2996 | rpcuser => $args{user}, delforward => 'y', delsubs => 'y', parpatt => $pinfo->{rdns},
|
---|
2997 | location => $binfo->{location});
|
---|
2998 | }
|
---|
2999 |
|
---|
3000 | } # scope eq 'clearpeer' || 'clearall'
|
---|
3001 |
|
---|
3002 | } elsif ($args{newtype} =~ /.[enr]/) {
|
---|
3003 | # Merge to leaf type
|
---|
3004 |
|
---|
3005 | # Resize rDNS template for $prime
|
---|
3006 | _rpc('resizeTemplate', oldcidr => "$binfo->{block}", newcidr => $newblock->network.'',
|
---|
3007 | rpcuser => $args{user}, location => $binfo->{location});
|
---|
3008 |
|
---|
3009 | # Assemble a list of blocks to delete...
|
---|
3010 | my $cidrlist;
|
---|
3011 | foreach my $mblock (@retlist) {
|
---|
3012 | $cidrlist .= $mblock->{block}."," unless $mblock->{block} =~ $newblock;
|
---|
3013 | }
|
---|
3014 | # Delete all other records within the new block
|
---|
3015 | $cidrlist .= $binfo->{block};
|
---|
3016 | _rpc('delRevSet', cidrlist => $cidrlist, rpcuser => $args{user}, delforward => 'y', delsubs => 'y',
|
---|
3017 | parpatt => $pinfo->{rdns}, location => $binfo->{location});
|
---|
3018 |
|
---|
3019 | } # type grouping for rDNS calls
|
---|
3020 |
|
---|
3021 | return \@retlist;
|
---|
3022 |
|
---|
3023 | } # end mergeBlocks()
|
---|
3024 |
|
---|
3025 |
|
---|
3026 | ## IPDB::deleteBlock()
|
---|
3027 | # Removes an allocation from the database, including deleting IPs
|
---|
3028 | # from poolips and recombining entries in freeblocks if possible
|
---|
3029 | # Also handles "deleting" a static IP allocation, and removal of a master
|
---|
3030 | # Requires a database handle, the block to delete, the routing depth (if applicable),
|
---|
3031 | # the VRF ID, and a flag to indicate whether to delete associated forward DNS entries
|
---|
3032 | # as well as the reverse entry
|
---|
3033 | sub deleteBlock {
|
---|
3034 | my ($dbh,$id,$basetype,$delfwd,$user) = @_;
|
---|
3035 |
|
---|
3036 | # reset $basetype so caller can just pass the complete allocation type
|
---|
3037 | if ($basetype =~ /^.?i$/) {
|
---|
3038 | $basetype = 'i';
|
---|
3039 | } else {
|
---|
3040 | $basetype = 'b';
|
---|
3041 | }
|
---|
3042 |
|
---|
3043 | # Collect info about the block we're going to delete
|
---|
3044 | my $binfo = getBlockData($dbh, $id, $basetype);
|
---|
3045 | my $cidr = new NetAddr::IP $binfo->{block};
|
---|
3046 |
|
---|
3047 | # For possible auto-VRF-ignoring (since public IPs shouldn't usually be present in more than one VRF)
|
---|
3048 | # is_rfc1918 requires NetAddr::IP >= 4.059
|
---|
3049 | # rather than doing this over and over and over.....
|
---|
3050 | my $tmpnum = $cidr->numeric;
|
---|
3051 | # 192.168.0.0/16 -> 192.168.255.255 => 3232235520 -> 3232301055
|
---|
3052 | # 172.16.0.0/12 -> 172.31.255.255 => 2886729728 -> 2887778303
|
---|
3053 | # 10.0.0.0/8 -> 10.255.255.255 => 167772160 -> 184549375
|
---|
3054 | my $isprivnet = (3232235520 <= $tmpnum && $tmpnum <= 3232301055) ||
|
---|
3055 | (2886729728 <= $tmpnum && $tmpnum <= 2887778303) ||
|
---|
3056 | (167772160 <= $tmpnum && $tmpnum <= 184549375);
|
---|
3057 |
|
---|
3058 | my $sth;
|
---|
3059 |
|
---|
3060 | # Magic variables used for odd allocation cases.
|
---|
3061 | my $container;
|
---|
3062 | my $con_type;
|
---|
3063 |
|
---|
3064 |
|
---|
3065 | # temporarily forced null, until a sane UI for VRF tracking can be found.
|
---|
3066 | # $vrf = '';# if !$vrf; # as with SQL, the null value is not equal to ''. *sigh*
|
---|
3067 |
|
---|
3068 | # To contain the error message, if any.
|
---|
3069 | my $msg = "Unknown error deallocating $binfo->{type} $cidr";
|
---|
3070 | my $goback; # to put the parent in so we can link back where the deallocate started
|
---|
3071 |
|
---|
3072 | # Enable transactions and exception-on-errors... but only for this sub
|
---|
3073 | local $dbh->{AutoCommit} = 0;
|
---|
3074 | local $dbh->{RaiseError} = 1;
|
---|
3075 |
|
---|
3076 | if ($binfo->{type} =~ /^.i$/) {
|
---|
3077 | # First case. The "block" is a static IP
|
---|
3078 | # Note that we still need some additional code in the odd case
|
---|
3079 | # of a netblock-aligned contiguous group of static IPs
|
---|
3080 | my $pinfo;
|
---|
3081 |
|
---|
3082 | eval {
|
---|
3083 | $msg = "Unable to deallocate $disp_alloctypes{$binfo->{type}} $cidr";
|
---|
3084 | $pinfo = getBlockData($dbh, $binfo->{parent_id}, 'b');
|
---|
3085 | $dbh->do("UPDATE poolips SET custid = ?, available = 'y',".
|
---|
3086 | "city = (SELECT city FROM allocations WHERE id = ?),".
|
---|
3087 | "description = '', notes = '', circuitid = '', vrf = ?, backup_id = 0".
|
---|
3088 | " WHERE id = ?", undef,
|
---|
3089 | ($pinfo->{custid}, $binfo->{parent_id}, $pinfo->{vrf}, $id) );
|
---|
3090 | $dbh->do("DELETE FROM backuplist WHERE backup_id = ?", undef, $binfo->{hasbk})
|
---|
3091 | if $binfo->{hasbk};
|
---|
3092 | $dbh->commit;
|
---|
3093 | };
|
---|
3094 | if ($@) {
|
---|
3095 | $msg .= ": $@";
|
---|
3096 | eval { $dbh->rollback; };
|
---|
3097 | return ('FAIL',$msg);
|
---|
3098 | }
|
---|
3099 |
|
---|
3100 | ##fixme: RPC return code?
|
---|
3101 | _rpc('delByCIDR', cidr => "$cidr", user => $user, delforward => $delfwd, rpcuser => $user,
|
---|
3102 | location => $binfo->{location})
|
---|
3103 | if ($pinfo->{revavail} || $pinfo->{revpartial});
|
---|
3104 |
|
---|
3105 | return ('OK',"OK");
|
---|
3106 |
|
---|
3107 | } elsif ($binfo->{type} eq 'mm') { # end alloctype =~ /.i/
|
---|
3108 | # Second case. The block is a full master block
|
---|
3109 |
|
---|
3110 | ##fixme: VRF limit
|
---|
3111 | $msg = "Unable to delete master block $cidr";
|
---|
3112 | eval {
|
---|
3113 | $dbh->do("DELETE FROM allocations WHERE cidr <<= ? AND master_id = ?", undef, ($cidr, $binfo->{master_id}) );
|
---|
3114 | $dbh->do("DELETE FROM freeblocks WHERE cidr <<= ? AND master_id = ?", undef, ($cidr, $binfo->{master_id}) );
|
---|
3115 | $dbh->do("DELETE FROM dnsavail WHERE location = ? AND parent_alloc = ?", undef,
|
---|
3116 | ($binfo->{location}, $binfo->{master_id}) );
|
---|
3117 | $dbh->do("DELETE FROM backuplist WHERE backup_id = ?", undef, $binfo->{hasbk})
|
---|
3118 | if $binfo->{hasbk};
|
---|
3119 | $dbh->commit;
|
---|
3120 | };
|
---|
3121 | if ($@) {
|
---|
3122 | $msg .= ": $@";
|
---|
3123 | eval { $dbh->rollback; };
|
---|
3124 | return ('FAIL', $msg);
|
---|
3125 | }
|
---|
3126 |
|
---|
3127 | # Have to handle potentially split reverse zones. Assume they *are* split,
|
---|
3128 | # since if we added them here, they would have been added split.
|
---|
3129 | # allow splitting reverse zones to be disabled, maybe, someday
|
---|
3130 | #if ($splitrevzones && !$cidr->{isv6}) {
|
---|
3131 | my @zonelist;
|
---|
3132 | if (1 && !$cidr->{isv6}) {
|
---|
3133 | my $splitpoint = ($cidr->masklen <= 16 ? 16 : 24); # hack pthui
|
---|
3134 | @zonelist = $cidr->split($splitpoint);
|
---|
3135 | } else {
|
---|
3136 | @zonelist = ($cidr);
|
---|
3137 | }
|
---|
3138 | my @fails;
|
---|
3139 | foreach my $subzone (@zonelist) {
|
---|
3140 | # We don't wrap this call tighter, since there isn't an inherent allocation to check for rDNS-ability.
|
---|
3141 | if ($rpc_url && !_rpc('delZone', zone => "$subzone", revrec => 'y', rpcuser => $user, delforward => $delfwd) ) {
|
---|
3142 | push @fails, ("$subzone" => $errstr);
|
---|
3143 | }
|
---|
3144 | }
|
---|
3145 | if (@fails) {
|
---|
3146 | return ('WARN',"Warning(s) deleting $cidr from reverse DNS:\n".join("\n", @fails));
|
---|
3147 | }
|
---|
3148 | return ('OK','OK');
|
---|
3149 |
|
---|
3150 | } else { # end alloctype master block case
|
---|
3151 |
|
---|
3152 | ## This is a big block; but it HAS to be done in a chunk. Any removal
|
---|
3153 | ## of a netblock allocation may result in a larger chunk of free
|
---|
3154 | ## contiguous IP space - which may in turn be combined into a single
|
---|
3155 | ## netblock rather than a number of smaller netblocks.
|
---|
3156 |
|
---|
3157 | my $retcode = 'OK';
|
---|
3158 | my ($ptype,$pcity,$ppatt,$p_id);
|
---|
3159 |
|
---|
3160 | eval {
|
---|
3161 |
|
---|
3162 | ##fixme: add recursive flag to allow "YES DAMMIT DELETE ALL EVARYTHING!!1!!" without
|
---|
3163 | # explicitly deleting any suballocations of the block to be deleted.
|
---|
3164 |
|
---|
3165 | # See if we have child allocations. Fail for now.
|
---|
3166 | my ($childcount) = $dbh->selectrow_array("SELECT count(*) from allocations where parent_id = ?", undef, $id);
|
---|
3167 | if ($childcount) {
|
---|
3168 | $msg = '';
|
---|
3169 | die "$binfo->{block} still has suballocations\n";
|
---|
3170 | }
|
---|
3171 |
|
---|
3172 | # get parent info of the block we're deleting
|
---|
3173 | my $pinfo = getBlockData($dbh, $binfo->{parent_id});
|
---|
3174 | $ptype = $pinfo->{type};
|
---|
3175 | $pcity = $pinfo->{city};
|
---|
3176 | $ppatt = $pinfo->{rdns};
|
---|
3177 | $p_id = $binfo->{parent_id};
|
---|
3178 |
|
---|
3179 | # Delete the block
|
---|
3180 | $dbh->do("DELETE FROM allocations WHERE id = ?", undef, ($id) );
|
---|
3181 |
|
---|
3182 | # munge the parent type a little
|
---|
3183 | $ptype = (split //, $ptype)[1];
|
---|
3184 |
|
---|
3185 | ##fixme: you can't... CAN NOT.... assign the same public IP to multiple things.
|
---|
3186 | # 'Net don't work like that, homey. Restrict VRF-uniqueness to private IPs?
|
---|
3187 | # -> $isprivnet flag from start of sub
|
---|
3188 |
|
---|
3189 | # check to see if any container allocations could be the "true" parent
|
---|
3190 | my ($tparent,$tpar_id,$trtype,$tcity);
|
---|
3191 | $tpar_id = 0;
|
---|
3192 |
|
---|
3193 | ##fixme: this is far simpler in the strict VRF case; we "know" that any allocation
|
---|
3194 | # contained by a container is a part of the same allocation tree when the VRF fields are equal.
|
---|
3195 |
|
---|
3196 | # logic:
|
---|
3197 | # For each possible container of $cidr
|
---|
3198 | # note the parent id
|
---|
3199 | # walk the chain up the parents
|
---|
3200 | # if we intersect $cidr's current parent, break
|
---|
3201 | # if we've intersected $cidr's current parent
|
---|
3202 | # set some variables to track that block
|
---|
3203 | # break
|
---|
3204 |
|
---|
3205 | # Set up part of "is it in the middle of a pool?" check
|
---|
3206 | my $wuzpool = $dbh->selectrow_hashref("SELECT cidr,parent_id,type,city,custid,id FROM allocations ".
|
---|
3207 | "WHERE (type LIKE '_d' OR type LIKE '_p') AND cidr >> ? AND master_id = ?", { Slice => {} },
|
---|
3208 | ($cidr, $binfo->{master_id}) );
|
---|
3209 |
|
---|
3210 | ##fixme?
|
---|
3211 | # edge cases not handled, or handled badly:
|
---|
3212 | # -> $cidr managed to get to be the entirety of an IP pool
|
---|
3213 |
|
---|
3214 | if ($wuzpool && $wuzpool->{id} != $id) {
|
---|
3215 | # we have legacy goo to be purified
|
---|
3216 | # going to ignore nested pools; not possible to create them via API and no current legacy data includes any.
|
---|
3217 |
|
---|
3218 | # for convenience
|
---|
3219 | my $poolid = $wuzpool->{id};
|
---|
3220 | my $pool = $wuzpool->{cidr};
|
---|
3221 | my $poolcity = $wuzpool->{city};
|
---|
3222 | my $pooltype = $wuzpool->{type};
|
---|
3223 | my $poolcustid = $wuzpool->{custid};
|
---|
3224 |
|
---|
3225 | $retcode = 'WARNPOOL';
|
---|
3226 | $goback = "$poolid,$pool";
|
---|
3227 | # We've already deleted the block, now we have to stuff its IPs into the pool.
|
---|
3228 | $pooltype =~ s/[dp]$/i/; # change type to static IP
|
---|
3229 | my $sth2 = $dbh->prepare("INSERT INTO poolips (ip,city,type,custid,parent_id) VALUES ".
|
---|
3230 | "(?,'$poolcity','$pooltype','$poolcustid',$poolid)");
|
---|
3231 |
|
---|
3232 | ##fixme: need to not insert net, gateway, and bcast on "real netblock" pools (DHCPish)
|
---|
3233 | # don't insert .0
|
---|
3234 | $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.0$|;
|
---|
3235 | $cidr++;
|
---|
3236 | my $bcast = $cidr->broadcast;
|
---|
3237 | while ($cidr != $bcast) {
|
---|
3238 | $sth2->execute($cidr->addr);
|
---|
3239 | $cidr++;
|
---|
3240 | }
|
---|
3241 | # don't insert .255
|
---|
3242 | $sth2->execute($cidr->addr) unless $cidr->addr =~ m|\.255$|;
|
---|
3243 |
|
---|
3244 | # Weirdness Happens. $cidr goes read-only somewhere (this is a thing?!?),
|
---|
3245 | # causing ->split, ->hostenum, and related methods to explode. O_o
|
---|
3246 | # foreach my $ip ($cidr->hostenum) {
|
---|
3247 | # $sth2->execute($ip);
|
---|
3248 | # }
|
---|
3249 |
|
---|
3250 | }
|
---|
3251 |
|
---|
3252 | ## important!
|
---|
3253 | # ... or IS IT?
|
---|
3254 | # we may have undef'ed $wuzpool above, if the allocation tree $cidr is in doesn't intersect the pool we found
|
---|
3255 | #if (!$wuzpool) {
|
---|
3256 |
|
---|
3257 | else {
|
---|
3258 |
|
---|
3259 | # Edge case: Block is the same size as more than one parent level. Should be rare.
|
---|
3260 | # - mainly master + first routing. Sorting on parent_id hides the problem pretty well,
|
---|
3261 | # but it's likely still possible to fail in particularly well-mangled databases.
|
---|
3262 | # The ultimate fix for this may be to resurrect the "routing depth" atrocity. :/
|
---|
3263 | # Get all possible (and probably a number of impossible) containers for $cidr
|
---|
3264 | $sth = $dbh->prepare("SELECT cidr,parent_id,type,city,id FROM allocations ".
|
---|
3265 | "WHERE (type LIKE '_m' OR type LIKE '_c') AND cidr >>= ? AND master_id = ? ".
|
---|
3266 | "ORDER BY masklen(cidr) DESC,parent_id DESC");
|
---|
3267 | $sth->execute($cidr, $binfo->{master_id});
|
---|
3268 |
|
---|
3269 | # Quickly get certain fields (simpler than getBlockData()
|
---|
3270 | my $sth2 = $dbh->prepare("SELECT cidr,parent_id,type,city FROM allocations ".
|
---|
3271 | "WHERE (type LIKE '_m' OR type LIKE '_c') AND id = ? AND master_id = ?");
|
---|
3272 |
|
---|
3273 | # For each possible container of $cidr...
|
---|
3274 | while (my @data = $sth->fetchrow_array) {
|
---|
3275 | my $i = 0;
|
---|
3276 | # Save some state and set a start point - parent ID of container we're checking
|
---|
3277 | $tparent = $data[0];
|
---|
3278 | my $ppid = $data[1];
|
---|
3279 | $trtype = $data[2];
|
---|
3280 | $tcity = $data[3];
|
---|
3281 | $tpar_id = $data[4];
|
---|
3282 | last if $data[4] == $binfo->{parent_id}; # Preemptively break if we're already in the right place
|
---|
3283 | last if $ppid == $binfo->{parent_id}; # ... or if the parent of the container is the block's parent
|
---|
3284 | while (1) {
|
---|
3285 | # Retrieve bits on that parent ID
|
---|
3286 | $sth2->execute($ppid, $binfo->{master_id});
|
---|
3287 | my @container = $sth2->fetchrow_array;
|
---|
3288 | $ppid = $container[1];
|
---|
3289 | last if $container[1] == 0; # Break if we've hit a master block
|
---|
3290 | last if $ppid == $binfo->{parent_id}; # Break if we've reached the block $cidr is currently in
|
---|
3291 | }
|
---|
3292 | last if $ppid == $binfo->{parent_id};
|
---|
3293 | }
|
---|
3294 |
|
---|
3295 | # found an alternate parent; reset some parent-info bits
|
---|
3296 | if ($tpar_id != $binfo->{parent_id}) {
|
---|
3297 | $ptype = (split //, $trtype)[1];
|
---|
3298 | $pcity = $tcity;
|
---|
3299 | $retcode = 'WARNMERGE'; # may be redundant
|
---|
3300 | $p_id = $tpar_id;
|
---|
3301 | }
|
---|
3302 |
|
---|
3303 | $goback = "$p_id,$tparent"; # breadcrumb, currently only used in case of live-parent-is-not-true-parent
|
---|
3304 |
|
---|
3305 | # Special case - delete pool IPs
|
---|
3306 | if ($binfo->{type} =~ /^.[pd]$/) {
|
---|
3307 | # We have to delete the IPs from the pool listing.
|
---|
3308 | ##fixme: rdepth? vrf?
|
---|
3309 | $dbh->do("DELETE FROM poolips WHERE parent_id = ?", undef, ($id) );
|
---|
3310 | }
|
---|
3311 |
|
---|
3312 | $pinfo = getBlockData($dbh, $p_id);
|
---|
3313 |
|
---|
3314 | # If the block wasn't legacy goo embedded in a static pool, we check the
|
---|
3315 | # freeblocks in the identified parent to see if we can combine any of them.
|
---|
3316 |
|
---|
3317 | # if the block to be deleted is a container, move its freeblock(s) up a level, and reset their parenting info
|
---|
3318 | if ($binfo->{type} =~ /^.[mc]/) {
|
---|
3319 | # move the freeblocks into the parent
|
---|
3320 | # we don't insert a new freeblock because there could be a live reparented sub.
|
---|
3321 | $dbh->do("UPDATE freeblocks SET parent_id = ?, routed = ?, city = ? WHERE parent_id = ?", undef,
|
---|
3322 | ($p_id, $ptype, $pcity, $id) );
|
---|
3323 | } else {
|
---|
3324 | # ... otherwise, add the freeblock
|
---|
3325 | $dbh->do("INSERT INTO freeblocks (cidr, city, routed, parent_id, master_id) VALUES (?,?,?,?,?)", undef,
|
---|
3326 | ($cidr, $pcity, $ptype, $p_id, $binfo->{master_id}) );
|
---|
3327 | }
|
---|
3328 |
|
---|
3329 | # Walk the free blocks in the parent and reduce them to the minimal set of CIDR ranges necessary
|
---|
3330 | _compactFree($dbh, $p_id);
|
---|
3331 |
|
---|
3332 | } # done returning IPs to the appropriate place
|
---|
3333 |
|
---|
3334 | # node hack
|
---|
3335 | # note we want to delete the ref from the original block, not any aggregated blocks we've pulled together
|
---|
3336 | $dbh->do("DELETE FROM noderef WHERE block = ?", undef, ($binfo->{block}) );
|
---|
3337 | # node hack
|
---|
3338 |
|
---|
3339 | # If we got here, we've succeeded. Whew!
|
---|
3340 | $dbh->commit;
|
---|
3341 | }; # end eval
|
---|
3342 | if ($@) {
|
---|
3343 | if ($msg) { $msg .= ": $@"; } else { $msg = $@; }
|
---|
3344 | eval { $dbh->rollback; };
|
---|
3345 | return ('FAIL', $msg);
|
---|
3346 | }
|
---|
3347 |
|
---|
3348 | ##fixme: RPC return code?
|
---|
3349 | _rpc('delByCIDR', cidr => "$cidr", rpcuser => $user, delforward => $delfwd, delsubs => 'y',
|
---|
3350 | parpatt => $ppatt, location => $binfo->{location})
|
---|
3351 | if ($binfo->{revavail} || $binfo->{revpartial});
|
---|
3352 |
|
---|
3353 | return ($retcode, $goback);
|
---|
3354 |
|
---|
3355 | } # end alloctype != netblock
|
---|
3356 |
|
---|
3357 | } # end deleteBlock()
|
---|
3358 |
|
---|
3359 |
|
---|
3360 | ## IPDB::getBlockData()
|
---|
3361 | # Get CIDR or IP, custid, type, city, circuit ID, description, notes, modification time,
|
---|
3362 | # private/restricted data, and backup fields, for a CIDR block or pool IP
|
---|
3363 | # Also returns SWIP status flag for CIDR blocks or pool netblock for IPs
|
---|
3364 | # Takes the block ID or IP to look up and an optional flag to indicate a pool IP lookup
|
---|
3365 | # instead of a netblock.
|
---|
3366 | # Returns a hashref to the block data
|
---|
3367 | sub getBlockData {
|
---|
3368 | my $dbh = shift;
|
---|
3369 | my $id = shift;
|
---|
3370 | my $type = shift || 'b'; # default to netblock for lazy callers
|
---|
3371 |
|
---|
3372 | # reset $type so caller can just pass the complete allocation type
|
---|
3373 | if ($type =~ /^.?i$/) {
|
---|
3374 | $type = 'i';
|
---|
3375 | } else {
|
---|
3376 | $type = 'b';
|
---|
3377 | }
|
---|
3378 |
|
---|
3379 | # catch some errors, someday
|
---|
3380 | # if (!$id || $id !~ /^\d+$/) {
|
---|
3381 | # $errstr = "Allocation ID must be numeric
|
---|
3382 | # }
|
---|
3383 |
|
---|
3384 | # Note city, vrf, parent_id and master_id removed due to JOIN uncertainty for block allocations
|
---|
3385 | my $commonfields = q(a.custid, a.type, a.circuitid, a.description, a.notes, a.modifystamp AS lastmod,
|
---|
3386 | a.privdata, a.vlan, a.rdns, a.userid);
|
---|
3387 | my $bkfields = q(b.backup_id AS hasbk, b.bkbrand, b.bkmodel, b.bktype, b.bkport, b.bksrc,
|
---|
3388 | b.bkuser, b.bkvpass, b.bkepass, b.bkip);
|
---|
3389 |
|
---|
3390 | if ($type eq 'i') {
|
---|
3391 | my $binfo = $dbh->selectrow_hashref(qq(
|
---|
3392 | SELECT a.id, a.ip AS block, a.city, a.vrf, a.parent_id, a.master_id, $commonfields,
|
---|
3393 | d.zone >> a.ip AS revavail, d.location,
|
---|
3394 | $bkfields,
|
---|
3395 | v.location AS vrfloc
|
---|
3396 | FROM poolips a
|
---|
3397 | LEFT JOIN dnsavail d ON a.master_id = d.parent_alloc AND a.ip << d.zone
|
---|
3398 | LEFT JOIN backuplist b ON a.backup_id = b.backup_id
|
---|
3399 | JOIN allocations m ON a.master_id = m.id JOIN vrfs v ON m.vrf = v.vrf
|
---|
3400 | WHERE a.id = ?
|
---|
3401 | ), undef, ($id) );
|
---|
3402 | return $binfo;
|
---|
3403 | } else {
|
---|
3404 | my $binfo = $dbh->selectrow_hashref(qq(
|
---|
3405 | SELECT a.id, masklen(a.cidr), a.cidr AS block, a.city, a.vrf, a.parent_id, a.master_id, a.swip, $commonfields,
|
---|
3406 | f.cidr AS reserve, f.id as reserve_id,
|
---|
3407 | d.zone >>= a.cidr AS revavail, d.zone << a.cidr AS revpartial, d.location,
|
---|
3408 | $bkfields,
|
---|
3409 | v.location AS vrfloc
|
---|
3410 | FROM allocations a
|
---|
3411 | LEFT JOIN freeblocks f ON a.id=f.reserve_for
|
---|
3412 | LEFT JOIN dnsavail d ON a.master_id = d.parent_alloc AND (a.cidr <<= d.zone OR a.cidr >> d.zone)
|
---|
3413 | LEFT JOIN backuplist b ON a.backup_id = b.backup_id
|
---|
3414 | JOIN allocations m ON a.master_id = m.id JOIN vrfs v ON m.vrf = v.vrf
|
---|
3415 | WHERE a.id = ?
|
---|
3416 | ), undef, ($id) );
|
---|
3417 |
|
---|
3418 | if ($binfo->{type} =~ /^.[dp]$/) {
|
---|
3419 | ($binfo->{nfree}) = $dbh->selectrow_array("SELECT count(*) FROM poolips WHERE parent_id = ? AND available = 'y'", undef, $id);
|
---|
3420 | } else {
|
---|
3421 | # assemble free IP count
|
---|
3422 | my $tmp = $dbh->prepare("SELECT 2^(32-masklen(cidr)) AS fc FROM freeblocks WHERE parent_id = ?");
|
---|
3423 | $tmp->execute($id);
|
---|
3424 | my $nfree = 0;
|
---|
3425 | while (my ($fc) = $tmp->fetchrow_array) {
|
---|
3426 | $nfree += $fc;
|
---|
3427 | }
|
---|
3428 | $binfo->{nfree} = $nfree;
|
---|
3429 | }
|
---|
3430 |
|
---|
3431 | return $binfo;
|
---|
3432 | }
|
---|
3433 | } # end getBlockData()
|
---|
3434 |
|
---|
3435 |
|
---|
3436 | ## IPDB::getBlockRDNS()
|
---|
3437 | # Gets reverse DNS pattern for a block or IP. Note that this will also
|
---|
3438 | # retrieve any default pattern following the parent chain up, and check via
|
---|
3439 | # RPC (if available) to see what the narrowest pattern for the requested block is
|
---|
3440 | # Returns the current pattern for the block or IP.
|
---|
3441 | sub getBlockRDNS {
|
---|
3442 | my $dbh = shift;
|
---|
3443 | my %args = @_;
|
---|
3444 |
|
---|
3445 | $args{type} = 'b' if !$args{type};
|
---|
3446 | my $cached = 1;
|
---|
3447 |
|
---|
3448 | # snag entry from database
|
---|
3449 | my ($rdns,$rfrom,$pid,$mid);
|
---|
3450 | if ($args{type} =~ /.i/) {
|
---|
3451 | ($rdns, $rfrom, $pid, $mid) = $dbh->selectrow_array("SELECT rdns,ip,parent_id,master_id FROM poolips WHERE id = ?",
|
---|
3452 | undef, ($args{id}) );
|
---|
3453 | } else {
|
---|
3454 | ($rdns, $rfrom, $pid, $mid) = $dbh->selectrow_array("SELECT rdns,cidr,parent_id,master_id FROM allocations WHERE id = ?",
|
---|
3455 | undef, ($args{id}) );
|
---|
3456 | }
|
---|
3457 |
|
---|
3458 | # Can't see a way this could end up empty, for any case I care about. If the caller
|
---|
3459 | # doesn't know an allocation ID to request, then they don't know anything else anyway.
|
---|
3460 | my $selfblock = $rfrom;
|
---|
3461 |
|
---|
3462 | my $type;
|
---|
3463 | while (!$rdns && $pid) {
|
---|
3464 | ($rdns, $rfrom, $pid, $type) = $dbh->selectrow_array(
|
---|
3465 | "SELECT rdns,cidr,parent_id,type FROM allocations WHERE id = ?",
|
---|
3466 | undef, ($pid) );
|
---|
3467 | last if $type eq 'mm'; # break loops in unfortunate legacy data
|
---|
3468 | }
|
---|
3469 |
|
---|
3470 | # use the actual allocation to check against the DNS utility; we don't want
|
---|
3471 | # to always go chasing up the chain to the master... which may (usually won't)
|
---|
3472 | # be present directly in DNS anyway
|
---|
3473 | my $cidr = new NetAddr::IP $selfblock;
|
---|
3474 |
|
---|
3475 | if ($rpc_url) {
|
---|
3476 | # Use the first /16 or /24, rather than dithering over which sub-/14 /16
|
---|
3477 | # or sub-/19 /24 to retrieve - it's the least-wrong way to do things.
|
---|
3478 |
|
---|
3479 | my ($rpcblock) = ($cidr->masklen <= 24 ? $cidr->split( ($cidr->masklen <= 16 ? 16 : 24) ) : $cidr);
|
---|
3480 | my %rpcargs = (
|
---|
3481 | rpcuser => $args{user},
|
---|
3482 | group => $revgroup, # not sure how this could sanely be exposed, tbh...
|
---|
3483 | cidr => "$rpcblock",
|
---|
3484 | );
|
---|
3485 |
|
---|
3486 | # # Retrieve the VRF's location by way of the master block
|
---|
3487 | # ($rpcargs{location}) = $dbh->selectrow_array("SELECT v.location FROM vrfs v".
|
---|
3488 | # " JOIN allocations a ON a.vrf = v.vrf".
|
---|
3489 | # " WHERE a.id = ?", undef, $mid);
|
---|
3490 |
|
---|
3491 | ## ... is there something more needed here?
|
---|
3492 | # order by so that we get the narrowest entry
|
---|
3493 | ($rpcargs{location}) = $dbh->selectrow_array("SELECT d.location FROM dnsavail d".
|
---|
3494 | " WHERE d.parent_alloc = ? ORDER BY zone DESC", undef, $mid);
|
---|
3495 |
|
---|
3496 | $errstr = '';
|
---|
3497 | my $remote_rdns = _rpc('getRevPattern', %rpcargs);
|
---|
3498 | if ($remote_rdns) {
|
---|
3499 | $rdns = $remote_rdns;
|
---|
3500 | $cached = 0;
|
---|
3501 | } else {
|
---|
3502 | if (!$errstr) {
|
---|
3503 | # no error, but no data
|
---|
3504 | $cached = 0;
|
---|
3505 | }
|
---|
3506 | }
|
---|
3507 | }
|
---|
3508 |
|
---|
3509 | # hmm. do we care about where it actually came from?
|
---|
3510 | return $rdns, $cached;
|
---|
3511 | } # end getBlockRDNS()
|
---|
3512 |
|
---|
3513 |
|
---|
3514 | ## IPDB::getRDNSbyIP()
|
---|
3515 | # Get individual reverse entries for the IP or CIDR IP range passed. Sort of looking the
|
---|
3516 | # opposite direction down the netblock tree compared to getBlockRDNS() above.
|
---|
3517 | sub getRDNSbyIP {
|
---|
3518 | my $dbh = shift;
|
---|
3519 | my %args = @_; # We want to accept a variety of call types
|
---|
3520 |
|
---|
3521 | # key arguments: allocation ID, type
|
---|
3522 | unless ($args{id} || $args{type}) {
|
---|
3523 | $errstr = 'Missing allocation ID or type';
|
---|
3524 | return;
|
---|
3525 | }
|
---|
3526 |
|
---|
3527 | my $binfo = getBlockData($dbh, $args{id}, $args{type});
|
---|
3528 |
|
---|
3529 | my @ret = ();
|
---|
3530 | # special case: single IP. Check if it's an allocation or in a pool, then do the RPC call for fresh data.
|
---|
3531 | if ($args{type} =~ /^.i$/) {
|
---|
3532 | my ($ip, $localrev) = $dbh->selectrow_array("SELECT ip, rdns FROM poolips WHERE id = ?", undef, ($args{id}) );
|
---|
3533 | push @ret, { 'r_ip' => $ip, 'iphost' => $localrev };
|
---|
3534 | ##fixme: rpc call?
|
---|
3535 | } else {
|
---|
3536 | if ($rpc_url) {
|
---|
3537 | my %rpcargs = (
|
---|
3538 | rpcuser => $args{user},
|
---|
3539 | group => $revgroup, # not sure how this could sanely be exposed, tbh...
|
---|
3540 | cidr => $args{range},
|
---|
3541 | );
|
---|
3542 |
|
---|
3543 | # # Retrieve the VRF's DNS location by way of the master block
|
---|
3544 | # ($rpcargs{location}) = $dbh->selectrow_array("SELECT v.location FROM vrfs v".
|
---|
3545 | # " JOIN allocations a ON a.vrf = v.vrf JOIN allocations b ON a.id = b.master_id".
|
---|
3546 | # " WHERE b.id = ?", undef, $args{id});
|
---|
3547 |
|
---|
3548 | ## ... is there something more needed here?
|
---|
3549 | # order by so that we get the narrowest entry
|
---|
3550 | ($rpcargs{location}) = $dbh->selectrow_array("SELECT d.location FROM dnsavail d".
|
---|
3551 | " WHERE d.parent_alloc = ? ORDER BY zone DESC", undef, $binfo->{master_id});
|
---|
3552 |
|
---|
3553 | my $remote_rdns = _rpc('getRevSet', %rpcargs);
|
---|
3554 | return $remote_rdns;
|
---|
3555 | # $rdns = $remote_rdns if $remote_rdns;
|
---|
3556 | # $cached = 0;
|
---|
3557 | }
|
---|
3558 | }
|
---|
3559 | return \@ret;
|
---|
3560 | } # end getRDNSbyIP()
|
---|
3561 |
|
---|
3562 |
|
---|
3563 | ## IPDB::getRevID()
|
---|
3564 | # Get the reverse zone ID(s) for an allocation
|
---|
3565 | # Takes a hash with cidr, location and user elements
|
---|
3566 | # Returns a hashref to a list of zones and zone IDs (in case of large
|
---|
3567 | # allocations effectively split across multiple DNS zones)
|
---|
3568 | ##fixme: arguably should be integrated in some other related sub that
|
---|
3569 | # does RPC to minimize the number of RPC calls somehow
|
---|
3570 | sub getRevID {
|
---|
3571 | my $dbh = shift;
|
---|
3572 | my %args = @_;
|
---|
3573 |
|
---|
3574 | ##fixme: build a local cache for mapping allocations to DNS zone IDs
|
---|
3575 | # my ($revlocal) = $dbh->selectrow_array("SELECT revzones[0] AS zone,revzones[1] AS revid FROM dnsavail WHERE
|
---|
3576 | #zone >>= ? AND location = ?", undef, $args{cidr}, $args{location});
|
---|
3577 | #use Data::Dumper;
|
---|
3578 | #print "rezone array?<pre>".Dumper($revlocal)."</pre>\n";
|
---|
3579 |
|
---|
3580 | my $revzones = _rpc('getZonesByCIDR', rpcuser => $args{user},
|
---|
3581 | cidr => $args{cidr},
|
---|
3582 | return_location => 0,
|
---|
3583 | location => $args{location},
|
---|
3584 | );
|
---|
3585 | return $revzones;
|
---|
3586 | } # end getRevID()
|
---|
3587 |
|
---|
3588 |
|
---|
3589 | ## IPDB::getNodeList()
|
---|
3590 | # Gets a list of node ID+name pairs as an arrayref to a list of hashrefs
|
---|
3591 | # Takes an optional argument to flag a selected node for dropdown lists
|
---|
3592 | sub getNodeList {
|
---|
3593 | my $dbh = shift;
|
---|
3594 | my $sel = shift || 0;
|
---|
3595 |
|
---|
3596 | my $ret = $dbh->selectall_arrayref("SELECT node_id, node_name, node_id=? AS selected FROM nodes".
|
---|
3597 | " ORDER BY node_name,node_type,node_id",
|
---|
3598 | { Slice => {} }, ($sel) );
|
---|
3599 | return $ret;
|
---|
3600 | } # end getNodeList()
|
---|
3601 |
|
---|
3602 |
|
---|
3603 | ## IPDB::getNodeName()
|
---|
3604 | # Get node name from the ID
|
---|
3605 | sub getNodeName {
|
---|
3606 | my $dbh = shift;
|
---|
3607 | my $nid = shift;
|
---|
3608 |
|
---|
3609 | my ($nname) = $dbh->selectrow_array("SELECT node_name FROM nodes WHERE node_id = ?", undef, ($nid) );
|
---|
3610 | return $nname;
|
---|
3611 | } # end getNodeName()
|
---|
3612 |
|
---|
3613 |
|
---|
3614 | ## IPDB::getNodeInfo()
|
---|
3615 | # Get node name and ID associated with a block
|
---|
3616 | sub getNodeInfo {
|
---|
3617 | my $dbh = shift;
|
---|
3618 | my $block = shift;
|
---|
3619 |
|
---|
3620 | my ($nid, $nname) = $dbh->selectrow_array("SELECT nodes.node_id,node_name FROM nodes INNER JOIN noderef".
|
---|
3621 | " ON nodes.node_id=noderef.node_id WHERE noderef.block = ?", undef, ($block) );
|
---|
3622 | return ($nid, $nname);
|
---|
3623 | } # end getNodeInfo()
|
---|
3624 |
|
---|
3625 |
|
---|
3626 | ## IPDB::getBlockNotices()
|
---|
3627 | # Retrieve any infonotes for a block and all of its parents
|
---|
3628 | # Takes the block ID to trace down the stack
|
---|
3629 | # Returns an arrayref to the block and all of its parents, containing the CIDR,
|
---|
3630 | # description, and notice (if any) associated to each block.
|
---|
3631 | sub getBlockNotices {
|
---|
3632 | my $dbh = shift;
|
---|
3633 | my $bid = shift;
|
---|
3634 | my $nlist = $dbh->selectall_arrayref(q(
|
---|
3635 | WITH RECURSIVE blockparents (id, cidr, description, parent_id, notice, depth) AS (
|
---|
3636 | SELECT a.id, a.cidr, a.description, a.parent_id, bn.notice, 1 AS depth FROM allocations a
|
---|
3637 | LEFT JOIN blocknotices bn ON a.id = bn.alloc_id
|
---|
3638 | WHERE a.id = ?
|
---|
3639 | UNION
|
---|
3640 | SELECT b.id, b.cidr, b.description, b.parent_id, bn2.notice, t.depth AS depth FROM allocations b
|
---|
3641 | JOIN blockparents t ON t.parent_id = b.id
|
---|
3642 | LEFT JOIN blocknotices bn2 ON b.id = bn2.alloc_id
|
---|
3643 | ) SELECT id, cidr, description, parent_id, notice FROM blockparents ORDER BY depth DESC;
|
---|
3644 | ), {Slice=>{}}, $bid);
|
---|
3645 |
|
---|
3646 | return $nlist;
|
---|
3647 | } # end getBlockNotices()
|
---|
3648 |
|
---|
3649 |
|
---|
3650 | ## IPDB::mailNotify()
|
---|
3651 | # Sends notification mail to recipients regarding an IPDB operation
|
---|
3652 | sub mailNotify {
|
---|
3653 | my $dbh = shift;
|
---|
3654 | my ($action,$subj,$message) = @_;
|
---|
3655 |
|
---|
3656 | return if $smtphost eq 'smtp.example.com'; # do nothing if still using default SMTP host.
|
---|
3657 |
|
---|
3658 | ##fixme: need to redesign the breakdown/processing for $action for proper handling of all cases
|
---|
3659 |
|
---|
3660 | # split action into parts for fiddlement. nb: there are almost certainly better ways to do this.
|
---|
3661 | my @actionbits = split //, $action;
|
---|
3662 |
|
---|
3663 | # want to notify anyone who has specifically requested notify on *this* type ($action as passed),
|
---|
3664 | # on "all static IP types" or "all pool types" (and other last-char-in-type groupings), on eg "all DSL types",
|
---|
3665 | # and "all events with this action"
|
---|
3666 | my @actionsets = ($action);
|
---|
3667 | ##fixme: ick, eww. really gotta find a better way to handle this...
|
---|
3668 | push @actionsets, ($actionbits[0].'.'.$actionbits[2],
|
---|
3669 | $actionbits[0].$actionbits[1].'.', $actionbits[0].'a') if $action =~ /^.{3}$/;
|
---|
3670 |
|
---|
3671 | my $mailer = Net::SMTP->new($smtphost, Hello => "ipdb.$domain");
|
---|
3672 |
|
---|
3673 | # get recip list from db
|
---|
3674 | my $sth = $dbh->prepare("SELECT reciplist FROM notify WHERE action=?");
|
---|
3675 |
|
---|
3676 | my %reciplist;
|
---|
3677 | foreach (@actionsets) {
|
---|
3678 | $sth->execute($_);
|
---|
3679 | ##fixme - need to handle db errors
|
---|
3680 | my ($recipsub) = $sth->fetchrow_array;
|
---|
3681 | next if !$recipsub;
|
---|
3682 | foreach (split(/,/, $recipsub)) {
|
---|
3683 | $reciplist{$_}++;
|
---|
3684 | }
|
---|
3685 | }
|
---|
3686 |
|
---|
3687 | return if !%reciplist;
|
---|
3688 |
|
---|
3689 | # dodge a bullet with module version "numbers"
|
---|
3690 | my ($ver) = ($IPDB::VERSION =~ /^(\d+(?:\.\d+)?)/);
|
---|
3691 |
|
---|
3692 | foreach my $recip (keys %reciplist) {
|
---|
3693 | $mailer->mail($smtpsender);
|
---|
3694 | $mailer->to($recip);
|
---|
3695 | $mailer->data("From: \"$org_name IP Database\" <$smtpsender>\n",
|
---|
3696 | "To: $recip\n",
|
---|
3697 | "Date: ".strftime("%a, %d %b %Y %H:%M:%S %z",localtime)."\n",
|
---|
3698 | "Subject: {IPDB} $subj\n",
|
---|
3699 | "X-Mailer: IPDB Notify v".sprintf("%.1d",$ver)."\n",
|
---|
3700 | "Organization: $org_name\n",
|
---|
3701 | "\n$message\n");
|
---|
3702 | }
|
---|
3703 | $mailer->quit;
|
---|
3704 | }
|
---|
3705 |
|
---|
3706 | # Indicates module loaded OK. Required by Perl.
|
---|
3707 | 1;
|
---|