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