4 * This file is a library of database access functions for RackTables.
12 'table' => 'RackObject',
18 'asset_no' => 'asset_no',
19 'objtype_id' => 'objtype_id',
20 'rack_id' => '(select rack_id from RackSpace where object_id = id order by rack_id asc limit 1)',
21 'Rack_name' => '(select name from Rack where id = rack_id)',
22 'row_id' => '(select row_id from Rack where id = rack_id)',
23 'Row_name' => '(select name from RackRow where id = row_id)',
24 'has_problems' => 'has_problems',
25 'comment' => 'comment',
26 'nports' => '(SELECT COUNT(*) FROM Port WHERE object_id = RackObject.id)',
27 'runs8021Q' => '(SELECT 1 FROM VLANSwitch WHERE object_id = id LIMIT 1)',
30 'ordcolumns' => array ('RackObject.name'),
34 'table' => 'UserAccount',
37 'user_id' => 'user_id',
38 'user_name' => 'user_name',
39 'user_password_hash' => 'user_password_hash',
40 'user_realname' => 'user_realname',
42 'keycolumn' => 'user_id',
43 'ordcolumns' => array ('UserAccount.user_name'),
47 'table' => 'IPv4Network',
51 'ip' => 'INET_NTOA(IPv4Network.ip)',
54 'comment' => 'comment',
55 'parent_id' => '(SELECT id FROM IPv4Network AS subt WHERE IPv4Network.ip & (4294967295 >> (32 - subt.mask)) << (32 - subt.mask) = subt.ip and subt.mask < IPv4Network.mask ORDER BY subt.mask DESC limit 1)',
56 'vlanc' => '(SELECT COUNT(*) FROM VLANIPv4 WHERE ipv4net_id = id)',
59 'ordcolumns' => array ('IPv4Network.ip', 'IPv4Network.mask'),
63 'table' => 'IPv6Network',
70 'comment' => 'comment',
71 'parent_id' => '(SELECT id FROM IPv6Network AS subt WHERE IPv6Network.ip >= subt.ip AND IPv6Network.last_ip <= subt.last_ip AND IPv6Network.mask > subt.mask ORDER BY subt.mask DESC limit 1)',
72 'vlanc' => '(SELECT COUNT(*) FROM VLANIPv6 WHERE ipv6net_id = id)',
75 'ordcolumns' => array ('IPv6Network.ip', 'IPv6Network.mask'),
89 'comment' => 'comment',
92 'ordcolumns' => array ('File.name'),
100 'vip' => 'INET_NTOA(vip)',
104 'vsconfig' => 'vsconfig',
105 'rsconfig' => 'rsconfig',
106 'poolcount' => '(select count(vs_id) from IPv4LB where vs_id = id)',
107 'dname' => 'CONCAT_WS("/", CONCAT_WS(":", INET_NTOA(vip), vport), proto)',
110 'ordcolumns' => array ('IPv4VS.vip', 'IPv4VS.proto', 'IPv4VS.vport'),
112 'ipv4rspool' => array
114 'table' => 'IPv4RSPool',
119 'refcnt' => '(select count(rspool_id) from IPv4LB where rspool_id = id)',
120 'rscount' => '(select count(rspool_id) from IPv4RS where rspool_id = IPv4RSPool.id)',
121 'vsconfig' => 'vsconfig',
122 'rsconfig' => 'rsconfig',
125 'ordcolumns' => array ('IPv4RSPool.name', 'IPv4RSPool.id'),
134 'height' => 'height',
135 'comment' => 'comment',
136 'row_id' => 'row_id',
137 'row_name' => '(select name from RackRow where RackRow.id = row_id)',
140 'ordcolumns' => array ('row_name', 'Rack.name'),
141 'pidcolumn' => 'row_id',
149 'by_sticker' => 'getStickerSearchResults',
150 'by_port' => 'getPortSearchResults',
151 'by_attr' => 'getObjectAttrsSearchResults',
152 'by_iface' => 'getObjectIfacesSearchResults',
153 'by_nat' => 'getObjectNATSearchResults',
157 $tablemap_8021q = array
161 'pvm' => 'PortVLANMode',
162 'pav' => 'PortAllowedVLAN',
163 'pnv' => 'PortNativeVLAN',
167 'pvm' => 'CachedPVM',
168 'pav' => 'CachedPAV',
169 'pnv' => 'CachedPNV',
174 $port_role_options = array
177 'access' => 'user: access only',
178 'trunk' => 'user: trunk only',
179 'anymode' => 'user: any mode',
180 'uplink' => 'system: uplink trunk',
181 'downlink' => 'system: downlink trunk',
184 $object_attribute_cache = array();
186 function escapeString ($value, $do_db_escape = FALSE)
188 $ret = htmlspecialchars ($value, ENT_QUOTES
, 'UTF-8');
192 $ret = substr ($dbxlink->quote ($ret), 1, -1);
197 // Return detailed information about one rack row.
198 function getRackRowInfo ($rackrow_id)
201 "select RackRow.id as id, RackRow.name as name, count(Rack.id) as count, " .
202 "if(isnull(sum(Rack.height)),0,sum(Rack.height)) as sum " .
203 "from RackRow left join Rack on Rack.row_id = RackRow.id " .
204 "where RackRow.id = ? " .
205 "group by RackRow.id";
206 $result = usePreparedSelectBlade ($query, array ($rackrow_id));
207 if ($row = $result->fetch (PDO
::FETCH_ASSOC
))
210 throw new EntityNotFoundException ('rackrow', $rackrow_id);
213 function getRackRows ()
215 $result = usePreparedSelectBlade ('SELECT id, name FROM RackRow ORDER BY name');
217 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
218 $rows[$row['id']] = $row['name'];
222 // Return a simple object list w/o related information, so that the returned value
223 // can be directly used by printSelect(). An optional argument is the name of config
224 // option with constraint in RackCode.
225 function getNarrowObjectList ($varname = '')
227 $wideList = listCells ('object');
228 if (strlen ($varname) and strlen (getConfigVar ($varname)))
231 if (!isset ($parseCache[$varname]))
232 $parseCache[$varname] = spotPayload (getConfigVar ($varname), 'SYNT_EXPR');
233 if ($parseCache[$varname]['result'] != 'ACK')
235 $wideList = filterCellList ($wideList, $parseCache[$varname]['load']);
238 foreach ($wideList as $cell)
239 $ret[$cell['id']] = $cell['dname'];
243 // For a given realm return a list of entity records, each with
244 // enough information for judgeCell() to execute.
245 function listCells ($realm, $parent_id = 0)
250 if (isset ($entityCache['complete'][$realm]))
251 return $entityCache['complete'][$realm];
254 if (!isset ($SQLSchema[$realm]))
255 throw new InvalidArgException ('realm', $realm);
256 $SQLinfo = $SQLSchema[$realm];
259 foreach ($SQLinfo['columns'] as $alias => $expression)
260 // Automatically prepend table name to each single column, but leave all others intact.
261 $query .= ($alias == $expression ?
"${SQLinfo['table']}.${alias}" : "${expression} as ${alias}") . ', ';
262 $query = trim($query, ', ');
263 $query .= " FROM ${SQLinfo['table']}";
264 if (isset ($SQLinfo['pidcolumn']) and $parent_id)
266 $query .= " WHERE ${SQLinfo['table']}.${SQLinfo['pidcolumn']} = ?";
267 $qparams[] = $parent_id;
269 $query .= " ORDER BY ";
270 foreach ($SQLinfo['ordcolumns'] as $oc)
272 $query = trim($query, ', ');
273 $result = usePreparedSelectBlade ($query, $qparams);
275 // Index returned result by the value of key column.
276 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
278 $entity_id = $row[$SQLinfo['keycolumn']];
279 $ret[$entity_id] = array ('realm' => $realm);
280 $ret[$entity_id]['etags'] = array();
281 foreach (array_keys ($SQLinfo['columns']) as $alias)
282 $ret[$entity_id][$alias] = $row[$alias];
286 // select tags and link them to previosly fetched entities
287 $query = 'SELECT entity_id, tag_id FROM TagStorage WHERE entity_realm = ?';
288 $result = usePreparedSelectBlade ($query, array($realm));
290 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
292 if (array_key_exists($row['entity_id'], $ret))
293 $ret[$row['entity_id']]['etags'][] = array
295 'id' => $row['tag_id'],
296 'tag' => $taglist[$row['tag_id']]['tag'],
297 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
301 // Add necessary finish to the list before returning it. Maintain caches.
303 unset ($entityCache['partial'][$realm]);
304 if ($realm == 'object') // cache all attributes of all objects to speed up autotags calculation
305 cacheAllObjectsAttributes();
306 foreach (array_keys ($ret) as $entity_id)
308 $ret[$entity_id]['etags'] = getExplicitTagsOnly ($ret[$entity_id]['etags']);
309 $ret[$entity_id]['itags'] = getImplicitTags ($ret[$entity_id]['etags']);
310 $ret[$entity_id]['atags'] = generateEntityAutoTags ($ret[$entity_id]);
314 setDisplayedName ($ret[$entity_id]);
317 $ret[$entity_id]['ip_bin'] = ip2long ($ret[$entity_id]['ip']);
318 $ret[$entity_id]['mask_bin'] = binMaskFromDec ($ret[$entity_id]['mask']);
319 $ret[$entity_id]['mask_bin_inv'] = binInvMaskFromDec ($ret[$entity_id]['mask']);
320 $ret[$entity_id]['db_first'] = sprintf ('%u', 0x00000000 +
$ret[$entity_id]['ip_bin'] & $ret[$entity_id]['mask_bin']);
321 $ret[$entity_id]['db_last'] = sprintf ('%u', 0x00000000 +
$ret[$entity_id]['ip_bin'] |
($ret[$entity_id]['mask_bin_inv']));
324 $ret[$entity_id]['ip_bin'] = new IPv6Address ($ret[$entity_id]['ip_bin']);
325 $ret[$entity_id]['ip'] = $ret[$entity_id]['ip_bin']->format();
326 $ret[$entity_id]['db_first'] = $ret[$entity_id]['ip_bin']->get_first_subnet_address($ret[$entity_id]['mask']);
327 $ret[$entity_id]['db_last'] = $ret[$entity_id]['ip_bin']->get_last_subnet_address($ret[$entity_id]['mask']);
333 $entityCache['complete'][$realm][$entity_id] = $ret[$entity_id];
335 $entityCache['partial'][$realm][$entity_id] = $ret[$entity_id];
340 // Very much like listCells(), but return only one record requested (or NULL,
341 // if it does not exist).
342 function spotEntity ($realm, $id)
345 if (isset ($entityCache['complete'][$realm]))
346 // Emphasize the absence of record, if listCells() has already been called.
347 if (isset ($entityCache['complete'][$realm][$id]))
348 return $entityCache['complete'][$realm][$id];
350 throw new EntityNotFoundException ($realm, $id);
351 elseif (isset ($entityCache['partial'][$realm][$id]))
352 return $entityCache['partial'][$realm][$id];
354 if (!isset ($SQLSchema[$realm]))
355 throw new InvalidArgException ('realm', $realm);
356 $SQLinfo = $SQLSchema[$realm];
357 $query = 'SELECT tag_id';
358 foreach ($SQLinfo['columns'] as $alias => $expression)
359 // Automatically prepend table name to each single column, but leave all others intact.
360 $query .= ', ' . ($alias == $expression ?
"${SQLinfo['table']}.${alias}" : "${expression} as ${alias}");
361 $query .= " FROM ${SQLinfo['table']} LEFT JOIN TagStorage on entity_realm = ? and entity_id = ${SQLinfo['table']}.${SQLinfo['keycolumn']}";
362 $query .= " WHERE ${SQLinfo['table']}.${SQLinfo['keycolumn']} = ?";
363 $query .= " ORDER BY tag_id";
364 $result = usePreparedSelectBlade ($query, array ($realm, $id));
367 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
368 if (!isset ($ret['realm']))
370 $ret = array ('realm' => $realm);
371 foreach (array_keys ($SQLinfo['columns']) as $alias)
372 $ret[$alias] = $row[$alias];
373 $ret['etags'] = array();
374 if ($row['tag_id'] != NULL && isset ($taglist[$row['tag_id']]))
375 $ret['etags'][] = array
377 'id' => $row['tag_id'],
378 'tag' => $taglist[$row['tag_id']]['tag'],
379 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
382 elseif (isset ($taglist[$row['tag_id']]))
383 $ret['etags'][] = array
385 'id' => $row['tag_id'],
386 'tag' => $taglist[$row['tag_id']]['tag'],
387 'parent_id' => $taglist[$row['tag_id']]['parent_id'],
390 if (!isset ($ret['realm'])) // no rows were returned
391 throw new EntityNotFoundException ($realm, $id);
392 $ret['etags'] = getExplicitTagsOnly ($ret['etags']);
393 $ret['itags'] = getImplicitTags ($ret['etags']);
394 $ret['atags'] = generateEntityAutoTags ($ret);
398 setDisplayedName ($ret);
401 $ret['ip_bin'] = ip2long ($ret['ip']);
402 $ret['mask_bin'] = binMaskFromDec ($ret['mask']);
403 $ret['mask_bin_inv'] = binInvMaskFromDec ($ret['mask']);
404 $ret['db_first'] = sprintf ('%u', 0x00000000 +
$ret['ip_bin'] & $ret['mask_bin']);
405 $ret['db_last'] = sprintf ('%u', 0x00000000 +
$ret['ip_bin'] |
($ret['mask_bin_inv']));
408 $ret['ip_bin'] = new IPv6Address ($ret['ip_bin']);
409 $ret['ip'] = $ret['ip_bin']->format();
410 $ret['db_first'] = $ret['ip_bin']->get_first_subnet_address($ret['mask']);
411 $ret['db_last'] = $ret['ip_bin']->get_last_subnet_address($ret['mask']);
416 $entityCache['partial'][$realm][$id] = $ret;
420 // This function can be used with array_walk().
421 function amplifyCell (&$record, $dummy = NULL)
423 switch ($record['realm'])
426 $record['ports'] = getObjectPortsAndLinks ($record['id']);
427 $record['ipv4'] = getObjectIPv4Allocations ($record['id']);
428 $record['ipv6'] = getObjectIPv6Allocations ($record['id']);
429 $record['nat4'] = getNATv4ForObject ($record['id']);
430 $record['ipv4rspools'] = getRSPoolsForObject ($record['id']);
431 $record['files'] = getFilesOfEntity ($record['realm'], $record['id']);
434 $record['links'] = getFileLinks ($record['id']);
437 $record['lblist'] = array();
438 $query = "select object_id, vs_id, lb.vsconfig, lb.rsconfig, lb.prio from " .
439 "IPv4LB as lb inner join IPv4VS as vs on lb.vs_id = vs.id " .
440 "where rspool_id = ? order by object_id, vip, vport";
441 $result = usePreparedSelectBlade ($query, array ($record['id']));
442 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
443 $record['lblist'][$row['object_id']][$row['vs_id']] = array
445 'rsconfig' => $row['rsconfig'],
446 'vsconfig' => $row['vsconfig'],
447 'prio' => $row['prio'],
450 $record['rslist'] = array();
451 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rsconfig from " .
452 "IPv4RS where rspool_id = ? order by IPv4RS.rsip, rsport";
453 $result = usePreparedSelectBlade ($query, array ($record['id']));
454 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
455 $record['rslist'][$row['id']] = array
457 'inservice' => $row['inservice'],
458 'rsip' => $row['rsip'],
459 'rsport' => $row['rsport'],
460 'rsconfig' => $row['rsconfig'],
465 // Get the detailed composition of a particular virtual service, namely the list
466 // of all pools, each shown with the list of objects servicing it. VS/RS configs
467 // will be returned as well.
468 $record['rspool'] = array();
469 $query = "select pool.id, name, pool.vsconfig, pool.rsconfig, object_id, " .
470 "lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, lb.prio from " .
471 "IPv4RSPool as pool left join IPv4LB as lb on pool.id = lb.rspool_id " .
472 "where vs_id = ? order by pool.name, object_id";
473 $result = usePreparedSelectBlade ($query, array ($record['id']));
474 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
476 if (!isset ($record['rspool'][$row['id']]))
477 $record['rspool'][$row['id']] = array
479 'name' => $row['name'],
480 'vsconfig' => $row['vsconfig'],
481 'rsconfig' => $row['rsconfig'],
484 if ($row['object_id'] == NULL)
486 $record['rspool'][$row['id']]['lblist'][$row['object_id']] = array
488 'vsconfig' => $row['lb_vsconfig'],
489 'rsconfig' => $row['lb_rsconfig'],
490 'prio' => $row['prio'],
496 $record['mountedObjects'] = array();
497 // start with default rackspace
498 for ($i = $record['height']; $i > 0; $i--)
499 for ($locidx = 0; $locidx < 3; $locidx++
)
500 $record[$i][$locidx]['state'] = 'F';
503 "select unit_no, atom, state, object_id " .
504 "from RackSpace where rack_id = ? and " .
505 "unit_no between 1 and ? order by unit_no";
506 $result = usePreparedSelectBlade ($query, array ($record['id'], $record['height']));
508 $mounted_objects = array();
509 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
511 $record[$row['unit_no']][$loclist[$row['atom']]]['state'] = $row['state'];
512 $record[$row['unit_no']][$loclist[$row['atom']]]['object_id'] = $row['object_id'];
513 if ($row['state'] == 'T' and $row['object_id'] != NULL)
514 $mounted_objects[$row['object_id']] = TRUE;
516 $record['mountedObjects'] = array_keys ($mounted_objects);
520 $record['8021q'] = getIPv4Network8021QBindings ($record['id']);
523 $record['8021q'] = getIPv6Network8021QBindings ($record['id']);
529 function getObjectPortsAndLinks ($object_id)
531 $query = "SELECT id, name, label, l2address, iif_id, (SELECT iif_name FROM PortInnerInterface WHERE id = iif_id) AS iif_name, " .
532 "type AS oif_id, (SELECT dict_value FROM Dictionary WHERE dict_key = type) AS oif_name, reservation_comment " .
533 "FROM Port WHERE object_id = ?";
534 // list and decode all ports of the current object
535 $result = usePreparedSelectBlade ($query, array ($object_id));
537 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
539 $row['l2address'] = l2addressFromDatabase ($row['l2address']);
540 $row['remote_id'] = NULL;
541 $row['remote_name'] = NULL;
542 $row['remote_object_id'] = NULL;
546 // now find and decode remote ends for all locally terminated connections
547 // FIXME: can't this data be extracted in one pass with sub-queries?
548 foreach (array_keys ($ret) as $tmpkey)
550 $portid = $ret[$tmpkey]['id'];
552 $query = "select porta, portb, cable from Link where porta = ? or portb = ?";
553 $result = usePreparedSelectBlade ($query, array ($portid, $portid));
554 $cable = "CableID n/a";
555 if ($row = $result->fetch (PDO
::FETCH_ASSOC
))
557 if ($portid != $row['porta'])
558 $remote_id = $row['porta'];
559 elseif ($portid != $row['portb'])
560 $remote_id = $row['portb'];
561 $cable = $row['cable'];
564 if ($remote_id) // there's a remote end here
566 $query = "SELECT name, object_id FROM Port WHERE id = ?";
567 $result = usePreparedSelectBlade ($query, array ($remote_id));
568 if ($row = $result->fetch (PDO
::FETCH_ASSOC
))
570 $ret[$tmpkey]['remote_name'] = $row['name'];
571 $ret[$tmpkey]['remote_object_id'] = $row['object_id'];
572 $ret[$tmpkey]['cableid'] = $cable;
574 $ret[$tmpkey]['remote_id'] = $remote_id;
578 return sortPortList ($ret, TRUE);
581 function commitAddRack ($name, $height, $row_id, $comment, $taglist)
583 usePreparedInsertBlade
591 'comment' => $comment
594 $last_insert_id = lastInsertID();
595 produceTagsForLastRecord ('rack', $taglist, $last_insert_id);
596 recordHistory ('Rack', $last_insert_id);
599 function commitAddObject ($new_name, $new_label, $new_type_id, $new_asset_no, $taglist = array())
601 // Maintain UNIQUE INDEX for common names and asset tags by
602 // filtering out empty strings (not NULLs).
603 $result1 = usePreparedInsertBlade
608 'name' => !strlen ($new_name) ?
NULL : $new_name,
609 'label' => $new_label,
610 'objtype_id' => $new_type_id,
611 'asset_no' => !strlen ($new_asset_no) ?
NULL : $new_asset_no,
614 $last_insert_id = lastInsertID();
615 // Do AutoPorts magic
616 executeAutoPorts ($last_insert_id, $new_type_id);
618 produceTagsForLastRecord ('object', $taglist, $last_insert_id);
620 recordHistory ('RackObject', $last_insert_id);
622 return $last_insert_id;
625 function commitUpdateObject ($object_id, $new_name, $new_label, $new_has_problems, $new_asset_no, $new_comment)
627 usePreparedUpdateBlade
632 'name' => !mb_strlen ($new_name) ?
NULL : $new_name,
633 'label' => !mb_strlen ($new_label) ?
NULL : $new_label,
634 'has_problems' => $new_has_problems,
635 'asset_no' => !mb_strlen ($new_asset_no) ?
NULL : $new_asset_no,
636 'comment' => $new_comment,
643 return recordHistory ('RackObject', $object_id);
646 // used by getEntityRelatives for sorting
647 function compare_name ($a, $b)
649 return strnatcmp($a['name'], $b['name']);
652 // find either parents or children of a record
653 function getEntityRelatives ($type, $entity_type, $entity_id)
655 if ($type == 'parents')
657 // searching for parents
659 'SELECT id, parent_entity_type AS entity_type, parent_entity_id AS entity_id FROM EntityLink ' .
660 'WHERE child_entity_type = ? AND child_entity_id = ?';
664 // searching for children
666 'SELECT id, child_entity_type AS entity_type, child_entity_id AS entity_id FROM EntityLink ' .
667 'WHERE parent_entity_type = ? AND parent_entity_id = ?';
669 $query = usePreparedSelectBlade ($sql, array ($entity_type, $entity_id));
670 $rows = $query->fetchAll (PDO
::FETCH_ASSOC
);
672 foreach ($rows as $row)
674 // get info of the relative (only objects supported now, others may be added later)
675 switch ($row['entity_type'])
679 $id_name = 'object_id';
680 $relative = spotEntity ($row['entity_type'], $row['entity_id']);
681 $name = $relative['dname'];
685 // name needs to have some value for hrefs to work
687 $name = sprintf("[Unnamed %s]", formatEntityName($row['entity_type']));
689 $ret[$row['id']] = array(
691 'id_name' => $id_name,
692 'entity_type' => $row['entity_type'],
693 'entity_id' => $row['entity_id'],
698 uasort($ret, 'compare_name');
702 function commitUnlinkEntities ($link_id)
704 return usePreparedDeleteBlade ('EntityLink', array ('id' => $link_id));
707 // The following functions return stats about VM-related info.
708 // TODO: simplify the queries
709 function getVMClusterSummary ()
711 $result = usePreparedSelectBlade
713 "SELECT RO.id, RO.name, " .
714 "(SELECT COUNT(*) FROM EntityLink EL " .
715 "LEFT JOIN RackObject RO_H ON EL.child_entity_id = RO_H.id " .
716 "LEFT JOIN AttributeValue AV ON RO_H.id = AV.object_id " .
717 "WHERE EL.parent_entity_type = 'object' " .
718 "AND EL.child_entity_type = 'object' " .
719 "AND EL.parent_entity_id = RO.id " .
720 "AND RO_H.objtype_id = 4 " .
721 "AND AV.attr_id = 26 " .
722 "AND AV.uint_value = 1501) AS hypervisors, " .
723 "(SELECT COUNT(*) FROM EntityLink EL " .
724 "LEFT JOIN RackObject RO_VM ON EL.child_entity_id = RO_VM.id " .
725 "WHERE EL.parent_entity_type = 'object' " .
726 "AND EL.child_entity_type = 'object' " .
727 "AND EL.parent_entity_id = RO.id " .
728 "AND RO_VM.objtype_id = 1504) AS VMs " .
729 "FROM RackObject RO " .
730 "WHERE RO.objtype_id = 1505 " .
733 return $result->fetchAll (PDO
::FETCH_ASSOC
);
736 function getVMResourcePoolSummary ()
738 $result = usePreparedSelectBlade
740 "SELECT RO.id, RO.name, " .
742 "FROM EntityLink EL " .
743 "LEFT JOIN RackObject RO_C ON EL.parent_entity_id = RO_C.id " .
744 "WHERE EL.child_entity_id = RO.id " .
745 "AND EL.parent_entity_type = 'object' " .
746 "AND EL.child_entity_type = 'object' " .
747 "AND RO_C.objtype_id = 1505) AS cluster_id, " .
748 "(SELECT RO_C.name " .
749 "FROM EntityLink EL " .
750 "LEFT JOIN RackObject RO_C ON EL.parent_entity_id = RO_C.id " .
751 "WHERE EL.child_entity_id = RO.id " .
752 "AND EL.parent_entity_type = 'object' " .
753 "AND EL.child_entity_type = 'object' " .
754 "AND RO_C.objtype_id = 1505) AS cluster_name, " .
755 "(SELECT COUNT(*) FROM EntityLink EL " .
756 "LEFT JOIN RackObject RO_VM ON EL.child_entity_id = RO_VM.id " .
757 "WHERE EL.parent_entity_type = 'object' " .
758 "AND EL.child_entity_type = 'object' " .
759 "AND EL.parent_entity_id = RO.id " .
760 "AND RO_VM.objtype_id = 1504) AS VMs " .
761 "FROM RackObject RO " .
762 "WHERE RO.objtype_id = 1506 " .
765 return $result->fetchAll (PDO
::FETCH_ASSOC
);
768 function getVMHypervisorSummary ()
770 $result = usePreparedSelectBlade
772 "SELECT RO.id, RO.name, " .
774 "FROM EntityLink EL " .
775 "LEFT JOIN RackObject RO_C ON EL.parent_entity_id = RO_C.id " .
776 "WHERE EL.child_entity_id = RO.id " .
777 "AND EL.parent_entity_type = 'object' " .
778 "AND EL.child_entity_type = 'object' " .
779 "AND RO_C.objtype_id = 1505) AS cluster_id, " .
780 "(SELECT RO_C.name " .
781 "FROM EntityLink EL " .
782 "LEFT JOIN RackObject RO_C ON EL.parent_entity_id = RO_C.id " .
783 "WHERE EL.child_entity_id = RO.id " .
784 "AND EL.parent_entity_type = 'object' " .
785 "AND EL.child_entity_type = 'object' " .
786 "AND RO_C.objtype_id = 1505) AS cluster_name, " .
787 "(SELECT COUNT(*) FROM EntityLink EL " .
788 "LEFT JOIN RackObject RO_VM ON EL.child_entity_id = RO_VM.id " .
789 "WHERE EL.parent_entity_type = 'object' " .
790 "AND EL.child_entity_type = 'object' " .
791 "AND EL.parent_entity_id = RO.id " .
792 "AND RO_VM.objtype_id = 1504) AS VMs " .
793 "FROM RackObject RO " .
794 "LEFT JOIN AttributeValue AV ON RO.id = AV.object_id " .
795 "WHERE RO.objtype_id = 4 " .
796 "AND AV.attr_id = 26 " .
797 "AND AV.uint_value = 1501 " .
800 return $result->fetchAll (PDO
::FETCH_ASSOC
);
803 function getVMSwitchSummary ()
805 $result = usePreparedSelectBlade
807 "SELECT RO.id, RO.name " .
808 "FROM RackObject RO " .
809 "WHERE RO.objtype_id = 1507 " .
812 return $result->fetchAll (PDO
::FETCH_ASSOC
);
815 // Remove file links related to the entity, but leave the entity and file(s) intact.
816 function releaseFiles ($entity_realm, $entity_id)
818 usePreparedDeleteBlade ('FileLink', array ('entity_type' => $entity_realm, 'entity_id' => $entity_id));
821 // There are times when you want to delete all traces of an object
822 function commitDeleteObject ($object_id = 0)
824 // Reset most of stuff
825 commitResetObject ($object_id);
827 usePreparedDeleteBlade ('RackObject', array ('id' => $object_id));
830 function commitResetObject ($object_id = 0)
832 releaseFiles ('object', $object_id);
833 destroyTagsForEntity ('object', $object_id);
834 usePreparedDeleteBlade ('IPv4LB', array ('object_id' => $object_id));
835 usePreparedDeleteBlade ('IPv4Allocation', array ('object_id' => $object_id));
836 usePreparedDeleteBlade ('IPv6Allocation', array ('object_id' => $object_id));
837 usePreparedDeleteBlade ('IPv4NAT', array ('object_id' => $object_id));
838 // Parent-child relationships
839 usePreparedExecuteBlade
841 'DELETE FROM EntityLink WHERE ' .
842 "(parent_entity_type = 'object' AND parent_entity_id = ?) OR (child_entity_type = 'object' AND child_entity_id = ?)",
843 array ($object_id, $object_id)
846 usePreparedExecuteBlade ('DELETE FROM Atom WHERE molecule_id IN (SELECT new_molecule_id FROM MountOperation WHERE object_id = ?)', array ($object_id));
847 usePreparedExecuteBlade ('DELETE FROM Molecule WHERE id IN (SELECT new_molecule_id FROM MountOperation WHERE object_id = ?)', array ($object_id));
848 usePreparedDeleteBlade ('MountOperation', array ('object_id' => $object_id));
849 usePreparedDeleteBlade ('RackSpace', array ('object_id' => $object_id));
851 usePreparedDeleteBlade ('PortVLANMode', array ('object_id' => $object_id));
852 usePreparedDeleteBlade ('PortNativeVLAN', array ('object_id' => $object_id));
853 usePreparedDeleteBlade ('PortAllowedVLAN', array ('object_id' => $object_id));
854 usePreparedDeleteBlade ('CachedPVM', array ('object_id' => $object_id));
855 usePreparedDeleteBlade ('VLANSwitch', array ('object_id' => $object_id));
857 usePreparedDeleteBlade ('Port', array ('object_id' => $object_id));
859 usePreparedUpdateBlade ('RackObject', array ('name' => NULL, 'label' => ''), array ('id' => $object_id));
861 commitUpdateAttrValue ($object_id, 3, "");
863 recordHistory ('RackObject', $object_id);
866 function commitDeleteRack($rack_id)
868 releaseFiles ('rack', $rack_id);
869 destroyTagsForEntity ('rack', $rack_id);
870 usePreparedDeleteBlade ('RackSpace', array ('rack_id' => $rack_id));
871 usePreparedDeleteBlade ('RackHistory', array ('id' => $rack_id));
872 usePreparedDeleteBlade ('Rack', array ('id' => $rack_id));
876 function commitUpdateRack ($rack_id, $new_name, $new_height, $new_row_id, $new_comment)
878 // Can't shrink a rack if rows being deleted contain mounted objects
879 $check_result = usePreparedSelectBlade ('SELECT COUNT(*) AS count FROM RackSpace WHERE rack_id = ? AND unit_no > ?', array ($rack_id, $new_height));
880 $check_row = $check_result->fetch (PDO
::FETCH_ASSOC
);
881 unset ($check_result);
882 if ($check_row['count'] > 0)
883 throw new InvalidArgException ('new_height', $new_height, 'Cannot shrink rack, objects are still mounted there');
884 usePreparedUpdateBlade
890 'height' => $new_height,
891 'comment' => $new_comment,
892 'row_id' => $new_row_id,
899 return recordHistory ('Rack', $rack_id);
902 // This function accepts rack data returned by amplifyCell(), validates and applies changes
903 // supplied in $_REQUEST and returns resulting array. Only those changes are examined, which
904 // correspond to current rack ID.
905 // 1st arg is rackdata, 2nd arg is unchecked state, 3rd arg is checked state.
906 // If 4th arg is present, object_id fields will be updated accordingly to the new state.
907 // The function returns the modified rack upon success.
908 function processGridForm (&$rackData, $unchecked_state, $checked_state, $object_id = 0)
911 $rack_id = $rackData['id'];
912 $rack_name = $rackData['name'];
913 $rackchanged = FALSE;
914 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
916 for ($locidx = 0; $locidx < 3; $locidx++
)
918 if ($rackData[$unit_no][$locidx]['enabled'] != TRUE)
921 $state = $rackData[$unit_no][$locidx]['state'];
922 if (isset ($_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"]) and $_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"] == 'on')
923 $newstate = $checked_state;
925 $newstate = $unchecked_state;
926 if ($state == $newstate)
930 $atom = $loclist[$locidx];
931 // The only changes allowed are those introduced by checkbox grid.
934 !($state == $checked_state && $newstate == $unchecked_state) &&
935 !($state == $unchecked_state && $newstate == $checked_state)
937 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, 'atom ${atom}', cannot change state from '${state}' to '${newstate}'");
938 // Here we avoid using ON DUPLICATE KEY UPDATE by first performing DELETE
939 // anyway and then looking for probable need of INSERT.
940 usePreparedDeleteBlade ('RackSpace', array ('rack_id' => $rack_id, 'unit_no' => $unit_no, 'atom' => $atom));
941 if ($newstate != 'F')
942 usePreparedInsertBlade ('RackSpace', array ('rack_id' => $rack_id, 'unit_no' => $unit_no, 'atom' => $atom, 'state' => $newstate));
943 if ($newstate == 'T' and $object_id != 0)
945 // At this point we already have a record in RackSpace.
946 $r = usePreparedUpdateBlade
949 array ('object_id' => $object_id),
952 'rack_id' => $rack_id,
953 'unit_no' => $unit_no,
958 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, atom '${atom}' failed to set object_id to '${object_id}'");
959 $rackData[$unit_no][$locidx]['object_id'] = $object_id;
965 usePreparedUpdateBlade ('Rack', array ('thumb_data' => NULL), array ('id' => $rack_id));
966 return array ('code' => 200, 'message' => "${rack_name}: All changes were successfully saved.");
969 return array ('code' => 300, 'message' => "${rack_name}: No changes.");
972 // This function builds a list of rack-unit-atom records, which are assigned to
973 // the requested object.
974 function getMoleculeForObject ($object_id)
976 $result = usePreparedSelectBlade
978 'SELECT rack_id, unit_no, atom FROM RackSpace ' .
979 'WHERE state = "T" AND object_id = ? ORDER BY rack_id, unit_no, atom',
982 return $result->fetchAll (PDO
::FETCH_ASSOC
);
985 // This function builds a list of rack-unit-atom records for requested molecule.
986 function getMolecule ($mid = 0)
988 $result = usePreparedSelectBlade ('SELECT rack_id, unit_no, atom FROM Atom WHERE molecule_id = ?', array ($mid));
989 return $result->fetchAll (PDO
::FETCH_ASSOC
);
992 // returns exactly what is's named after
993 function lastInsertID ()
995 $result = usePreparedSelectBlade ('select last_insert_id()');
996 $row = $result->fetch (PDO
::FETCH_NUM
);
1000 // This function creates a new record in Molecule and number of linked
1001 // R-U-A records in Atom.
1002 function createMolecule ($molData)
1004 usePreparedExecuteBlade ('INSERT INTO Molecule VALUES()');
1005 $molecule_id = lastInsertID();
1006 foreach ($molData as $rua)
1007 usePreparedInsertBlade
1012 'molecule_id' => $molecule_id,
1013 'rack_id' => $rua['rack_id'],
1014 'unit_no' => $rua['unit_no'],
1015 'atom' => $rua['atom'],
1018 return $molecule_id;
1021 // History logger. This function assumes certain table naming convention and
1023 // 1. History table name equals to dictionary table name plus 'History'.
1024 // 2. History table must have the same row set (w/o keys) plus one row named
1025 // 'ctime' of type 'timestamp'.
1026 function recordHistory ($tableName, $orig_id)
1028 global $remote_username;
1029 return FALSE !== usePreparedExecuteBlade
1031 "INSERT INTO ${tableName}History SELECT *, CURRENT_TIMESTAMP(), ? " .
1032 "FROM ${tableName} WHERE id=?",
1033 array ($remote_username, $orig_id)
1037 function getRackspaceHistory ()
1039 $result = usePreparedSelectBlade
1041 "SELECT id as mo_id, object_id as ro_id, ctime, comment, user_name FROM " .
1042 "MountOperation ORDER BY ctime DESC"
1044 return $result->fetchAll (PDO
::FETCH_ASSOC
);
1047 // This function is used in renderRackspaceHistory()
1048 function getOperationMolecules ($op_id = 0)
1050 $result = usePreparedSelectBlade ('SELECT old_molecule_id, new_molecule_id FROM MountOperation WHERE id = ?', array ($op_id));
1051 // We expect one row.
1052 $row = $result->fetch (PDO
::FETCH_ASSOC
);
1053 return array ($row['old_molecule_id'], $row['new_molecule_id']);
1056 function getResidentRacksData ($object_id = 0, $fetch_rackdata = TRUE)
1058 $result = usePreparedSelectBlade ('SELECT DISTINCT rack_id FROM RackSpace WHERE object_id = ? ORDER BY rack_id', array ($object_id));
1059 $rows = $result->fetchAll (PDO
::FETCH_NUM
);
1062 foreach ($rows as $row)
1064 if (!$fetch_rackdata)
1066 $ret[$row[0]] = $row[0];
1069 $rackData = spotEntity ('rack', $row[0]);
1070 amplifyCell ($rackData);
1071 $ret[$row[0]] = $rackData;
1076 function commitAddPort ($object_id = 0, $port_name, $port_type_id, $port_label, $port_l2address)
1078 $db_l2address = l2addressForDatabase ($port_l2address);
1080 $dbxlink->exec ('LOCK TABLES Port WRITE');
1081 if (alreadyUsedL2Address ($db_l2address, $object_id))
1083 $dbxlink->exec ('UNLOCK TABLES');
1084 throw new InvalidRequestArgException ('port_l2address', $port_l2address, 'address belongs to another object');
1089 case preg_match ('/^([[:digit:]]+)-([[:digit:]]+)$/', $port_type_id, $matches):
1090 $iif_id = $matches[1];
1091 $oif_id = $matches[2];
1093 case preg_match ('/^([[:digit:]]+)$/', $port_type_id, $matches):
1095 $oif_id = $matches[1];
1098 $dbxlink->exec ('UNLOCK TABLES');
1099 throw new InvalidArgException ('port_type_id', $port_type_id, 'format error');
1101 $result = usePreparedInsertBlade
1106 'name' => $port_name,
1107 'object_id' => $object_id,
1108 'label' => $port_label,
1109 'iif_id' => $iif_id,
1111 'l2address' => ($db_l2address === '') ?
NULL : $db_l2address,
1114 $dbxlink->exec ('UNLOCK TABLES');
1117 // The fifth argument may be either explicit 'NULL' or some (already quoted by the upper layer)
1118 // string value. In case it is omitted, we just assign it its current value.
1119 // It would be nice to simplify this semantics later.
1120 function commitUpdatePort ($object_id, $port_id, $port_name, $port_type_id, $port_label, $port_l2address, $port_reservation_comment)
1122 $db_l2address = l2addressForDatabase ($port_l2address);
1124 $dbxlink->exec ('LOCK TABLES Port WRITE');
1125 if (alreadyUsedL2Address ($db_l2address, $object_id))
1127 $dbxlink->exec ('UNLOCK TABLES');
1128 // FIXME: it is more correct to throw InvalidArgException here
1129 // and convert it to InvalidRequestArgException at upper level,
1130 // when there is a mean to do that.
1131 throw new InvalidRequestArgException ('port_l2address', $db_l2address, 'address belongs to another object');
1133 usePreparedUpdateBlade
1138 'name' => $port_name,
1139 'type' => $port_type_id,
1140 'label' => $port_label,
1141 'reservation_comment' => mb_strlen ($port_reservation_comment) ?
$port_reservation_comment : NULL,
1142 'l2address' => ($db_l2address === '') ?
NULL : $db_l2address,
1147 'object_id' => $object_id
1150 $dbxlink->exec ('UNLOCK TABLES');
1153 function getAllIPv4Allocations ()
1155 $result = usePreparedSelectBlade
1157 "select object_id as object_id, ".
1158 "RackObject.name as object_name, ".
1159 "IPv4Allocation.name as name, ".
1160 "INET_NTOA(ip) as ip ".
1161 "from IPv4Allocation join RackObject on id=object_id "
1164 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1169 function linkPorts ($porta, $portb, $cable = NULL)
1171 if ($porta == $portb)
1172 throw new InvalidArgException ('porta/portb', $porta, "Ports can't be the same");
1175 $dbxlink->exec ('LOCK TABLES Link WRITE');
1176 $result = usePreparedSelectBlade
1178 'SELECT COUNT(*) FROM Link WHERE porta IN (?,?) OR portb IN (?,?)',
1179 array ($porta, $portb, $porta, $portb)
1181 if ($result->fetchColumn () != 0)
1183 $dbxlink->exec ('UNLOCK TABLES');
1184 return "Port ${porta} or ${portb} is already linked";
1186 $result->closeCursor ();
1187 if ($porta > $portb)
1193 $ret = FALSE !== usePreparedInsertBlade ('Link', array ('porta' => $porta, 'portb' => $portb, 'cable' => $cable));
1194 $dbxlink->exec ('UNLOCK TABLES');
1195 $ret = $ret and FALSE !== usePreparedExecuteBlade
1197 'UPDATE Port SET reservation_comment=NULL WHERE id IN(?, ?)',
1198 array ($porta, $portb)
1200 return $ret ?
'' : 'query failed';
1203 // Returns all IPv4 addresses allocated to object, but does not attach detailed info about address
1204 // Used instead of getObjectIPv4Allocations if you need perfomance but 'addrinfo' value
1205 function getObjectIPv4AllocationList ($object_id)
1208 $result = usePreparedSelectBlade
1210 'SELECT name AS osif, type, inet_ntoa(ip) AS dottedquad FROM IPv4Allocation ' .
1211 'WHERE object_id = ? ORDER BY ip',
1214 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1215 $ret[$row['dottedquad']] = array ('osif' => $row['osif'], 'type' => $row['type']);
1219 // Return all IPv4 addresses allocated to the objects. Attach detailed
1220 // info about address to each alocation records. Index result by dotted-quad
1222 function getObjectIPv4Allocations ($object_id = 0)
1224 $ret = getObjectIPv4AllocationList ($object_id);
1225 foreach (array_keys ($ret) as $dottedquad)
1226 $ret[$dottedquad]['addrinfo'] = getIPv4Address ($dottedquad);
1230 // Returns all IPv4 addresses allocated to object, but does not attach detailed info about address
1231 // Used instead of getObjectIPv6Allocations if you need perfomance but 'addrinfo' value
1232 function getObjectIPv6AllocationList ($object_id)
1235 $result = usePreparedSelectBlade
1237 'SELECT name AS osif, type, ip AS ip FROM IPv6Allocation ' .
1238 'WHERE object_id = ? ORDER BY ip',
1241 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1242 $ret[$row['ip']] = array ('osif' => $row['osif'], 'type' => $row['type']);
1246 // Return all IPv6 addresses allocated to the objects. Attach detailed
1247 // info about address to each alocation records. Index result by binary string of IPv6
1248 function getObjectIPv6Allocations ($object_id = 0)
1250 $ret = getObjectIPv6AllocationList ($object_id);
1251 foreach (array_keys ($ret) as $ip_bin)
1252 $ret[$ip_bin]['addrinfo'] = getIPv6Address (new IPv6Address ($ip_bin));
1256 // Return minimal IPv4 address, optionally with "ip" key set, if requested.
1257 function constructIPv4Address ($dottedquad = NULL)
1266 'rslist' => array(),
1267 'allocs' => array(),
1270 if ($dottedquad != NULL)
1271 $ret['ip'] = $dottedquad;
1275 // Return minimal IPv6 address, optionally with "ip" key set, if requested.
1276 function constructIPv6Address ($bin_ip = NULL)
1283 'allocs' => array(),
1285 if ($bin_ip != NULL)
1286 $ret['ip'] = $bin_ip->format();
1290 // Check the range requested for meaningful IPv4 records, build them
1291 // into a list and return. Return an empty list if nothing matched.
1292 // Both arguments are expected in signed int32 form. The resulting list
1293 // is keyed by uint32 form of each IP address, items aren't sorted.
1294 // LATER: accept a list of pairs and build WHERE sub-expression accordingly
1295 function scanIPv4Space ($pairlist)
1298 if (!count ($pairlist)) // this is normal for a network completely divided into smaller parts
1300 // FIXME: this is a copy-and-paste prototype
1309 foreach ($pairlist as $tmp)
1311 $db_first = sprintf ('%u', 0x00000000 +
$tmp['i32_first']);
1312 $db_last = sprintf ('%u', 0x00000000 +
$tmp['i32_last']);
1313 $whereexpr1 .= $or . "ip between ? and ?";
1314 $whereexpr2 .= $or . "ip between ? and ?";
1315 $whereexpr3 .= $or . "vip between ? and ?";
1316 $whereexpr4 .= $or . "rsip between ? and ?";
1317 $whereexpr5a .= $or . "remoteip between ? and ?";
1318 $whereexpr5b .= $or . "localip between ? and ?";
1320 $qparams[] = $db_first;
1321 $qparams[] = $db_last;
1327 $whereexpr5a .= ')';
1328 $whereexpr5b .= ')';
1330 // 1. collect labels and reservations
1331 $query = "select INET_NTOA(ip) as ip, name, reserved from IPv4Address ".
1332 "where ${whereexpr1} and (reserved = 'yes' or name != '')";
1333 $result = usePreparedSelectBlade ($query, $qparams);
1334 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1336 $ip_bin = ip2long ($row['ip']);
1337 if (!isset ($ret[$ip_bin]))
1338 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1339 $ret[$ip_bin]['name'] = $row['name'];
1340 $ret[$ip_bin]['reserved'] = $row['reserved'];
1344 // 2. check for allocations
1346 "select INET_NTOA(ip) as ip, object_id, name, type " .
1347 "from IPv4Allocation where ${whereexpr2} order by type";
1348 $result = usePreparedSelectBlade ($query, $qparams);
1349 // release DBX early to avoid issues with nested spotEntity() calls
1350 $allRows = $result->fetchAll (PDO
::FETCH_ASSOC
);
1352 foreach ($allRows as $row)
1354 $ip_bin = ip2long ($row['ip']);
1355 if (!isset ($ret[$ip_bin]))
1356 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1357 $oinfo = spotEntity ('object', $row['object_id']);
1358 $ret[$ip_bin]['allocs'][] = array
1360 'type' => $row['type'],
1361 'name' => $row['name'],
1362 'object_id' => $row['object_id'],
1363 'object_name' => $oinfo['dname'],
1367 // 3. look for virtual services and related LB
1368 $query = "select vs_id, inet_ntoa(vip) as ip, vport, proto, vs.name, object_id " .
1369 "from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id " .
1370 "where ${whereexpr3} order by vport, proto, object_id";
1371 $result = usePreparedSelectBlade ($query, $qparams);
1372 $allRows = $result->fetchAll (PDO
::FETCH_ASSOC
);
1374 foreach ($allRows as $row)
1376 $ip_bin = ip2long ($row['ip']);
1377 if (!isset ($ret[$ip_bin]))
1378 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1379 $oinfo = spotEntity ('object', $row['object_id']);
1380 $ret[$ip_bin]['lblist'][] = array
1382 'vport' => $row['vport'],
1383 'proto' => $row['proto'],
1384 'vs_id' => $row['vs_id'],
1385 'name' => $row['name'],
1386 'vip' => $row['ip'],
1387 'object_id' => $row['object_id'],
1388 'object_name' => $oinfo['dname'],
1392 // 4. don't forget about real servers along with pools
1393 $query = "select inet_ntoa(rsip) as ip, inservice, rsport, rspool_id, rsp.name as rspool_name from " .
1394 "IPv4RS as rs inner join IPv4RSPool as rsp on rs.rspool_id = rsp.id " .
1395 "where ${whereexpr4} " .
1396 "order by ip, rsport, rspool_id";
1397 $result = usePreparedSelectBlade ($query, $qparams);
1398 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1400 $ip_bin = ip2long ($row['ip']);
1401 if (!isset ($ret[$ip_bin]))
1402 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1404 foreach (array ('rspool_id', 'rsport', 'rspool_name', 'inservice') as $cname)
1405 $tmp[$cname] = $row[$cname];
1406 $ret[$ip_bin]['rslist'][] = $tmp;
1410 // 5. add NAT rules, part 1
1414 "INET_NTOA(localip) as localip, " .
1416 "INET_NTOA(remoteip) as remoteip, " .
1420 "where ${whereexpr5a} " .
1421 "order by localip, localport, remoteip, remoteport, proto";
1422 $result = usePreparedSelectBlade ($query, $qparams);
1423 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1425 $remoteip_bin = ip2long ($row['remoteip']);
1426 if (!isset ($ret[$remoteip_bin]))
1427 $ret[$remoteip_bin] = constructIPv4Address ($row['remoteip']);
1428 $ret[$remoteip_bin]['inpf'][] = $row;
1431 // 5. add NAT rules, part 2
1435 "INET_NTOA(localip) as localip, " .
1437 "INET_NTOA(remoteip) as remoteip, " .
1441 "where ${whereexpr5b} " .
1442 "order by localip, localport, remoteip, remoteport, proto";
1443 $result = usePreparedSelectBlade ($query, $qparams);
1444 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1446 $localip_bin = ip2long ($row['localip']);
1447 if (!isset ($ret[$localip_bin]))
1448 $ret[$localip_bin] = constructIPv4Address ($row['localip']);
1449 $ret[$localip_bin]['outpf'][] = $row;
1455 // Check the range requested for meaningful IPv6 records, build them
1456 // into a list and return. Return an empty list if nothing matched.
1457 // Both arguments are expected as instances of IPv6Address class. The resulting list
1458 // is keyed by uint32 form of each IP address, items aren't sorted.
1459 function scanIPv6Space ($pairlist)
1463 foreach ($pairlist as $pair)
1465 $wheres[] = "ip >= ? AND ip <= ?";
1466 $qparams[] = $pair['first']->getBin();
1467 $qparams[] = $pair['last']->getBin();
1469 if (! count ($wheres)) // this is normal for a network completely divided into smaller parts
1471 $whereexpr = '(' .implode (' OR ', $wheres) . ')';
1473 // 1. collect labels and reservations
1474 $query = "select ip, name, reserved from IPv6Address ".
1475 "where ${whereexpr} and (reserved = 'yes' or name != '')";
1476 $result = usePreparedSelectBlade ($query, $qparams);
1477 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1479 $ip_bin = new IPv6Address ($row['ip']);
1480 $key = $ip_bin->getBin();
1481 if (!isset ($ret[$key]))
1482 $ret[$key] = constructIPv6Address ($ip_bin);
1483 $ret[$key]['name'] = $row['name'];
1484 $ret[$key]['reserved'] = $row['reserved'];
1488 // 2. check for allocations
1490 "select ip, object_id, name, type " .
1491 "from IPv6Allocation where ${whereexpr} order by type";
1492 $result = usePreparedSelectBlade ($query, $qparams);
1493 // release DBX early to avoid issues with nested spotEntity() calls
1494 $allRows = $result->fetchAll (PDO
::FETCH_ASSOC
);
1496 foreach ($allRows as $row)
1498 $ip_bin = new IPv6Address ($row['ip']);
1499 $key = $ip_bin->getBin();
1500 if (!isset ($ret[$key]))
1501 $ret[$key] = constructIPv6Address ($ip_bin);
1502 $oinfo = spotEntity ('object', $row['object_id']);
1503 $ret[$key]['allocs'][] = array
1505 'type' => $row['type'],
1506 'name' => $row['name'],
1507 'object_id' => $row['object_id'],
1508 'object_name' => $oinfo['dname'],
1514 // this is a wrapper around getIPv4Address and getIPv6Address
1515 // You can pass dotted IPv4, human representation of IPv6, or instance of IPv6Address
1516 function getIPAddress ($ip)
1518 if (is_a ($ip, 'IPv6Address'))
1519 return getIPv6Address ($ip);
1520 $ipv6 = new IPv6Address
;
1521 if ($ipv6->parse ($ip))
1522 return getIPv6Address ($ipv6);
1523 return getIPv4Address ($ip);
1526 function getIPv4Address ($dottedquad = '')
1528 if ($dottedquad == '')
1529 throw new InvalidArgException ('$dottedquad', $dottedquad);
1530 $i32 = ip2long ($dottedquad); // signed 32 bit
1531 $scanres = scanIPv4Space (array (array ('i32_first' => $i32, 'i32_last' => $i32)));
1532 if (empty ($scanres))
1533 //$scanres[$i32] = constructIPv4Address ($dottedquad); // XXX: this should be verified to not break things
1534 return constructIPv4Address ($dottedquad);
1535 markupIPAddrList ($scanres);
1536 return $scanres[$i32];
1539 // returns the array of structure described by constructIPv6Address
1540 function getIPv6Address ($v6addr)
1542 if (! is_object ($v6addr))
1543 throw new InvalidArgException ('$v6addr', $v6addr);
1544 $scanres = scanIPv6Space (array (array ('first' => $v6addr, 'last' => $v6addr)));
1545 if (empty ($scanres))
1546 return constructIPv6Address ($v6addr);
1547 markupIPAddrList ($scanres);
1548 return array_shift ($scanres);
1551 function bindIpToObject ($ip = '', $object_id = 0, $name = '', $type = '')
1553 return usePreparedExecuteBlade
1555 'INSERT INTO IPv4Allocation (ip, object_id, name, type) VALUES (INET_ATON(?), ?, ?, ?)',
1556 array ($ip, $object_id, $name, $type)
1560 function bindIPv6ToObject ($ip, $object_id = 0, $name = '', $type = '')
1562 return usePreparedInsertBlade
1565 array ('ip' => $ip->getBin(), 'object_id' => $object_id, 'name' => $name, 'type' => $type)
1569 // Return the id of the smallest IPv4 network containing the given IPv4 address
1570 // or NULL, if nothing was found. When finding the covering network for
1571 // another network, it is important to filter out matched records with longer
1572 // masks (they aren't going to be the right pick).
1573 function getIPv4AddressNetworkId ($dottedquad, $masklen = 32)
1575 $query = 'select id from IPv4Network where ' .
1576 "inet_aton(?) & (4294967295 >> (32 - mask)) << (32 - mask) = ip " .
1578 'order by mask desc limit 1';
1579 $result = usePreparedSelectBlade ($query, array ($dottedquad, $masklen));
1580 if ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1585 // Return the id of the smallest IPv6 network containing the given IPv6 address
1586 // ($ip is an instance of IPv4Address class) or NULL, if nothing was found.
1587 function getIPv6AddressNetworkId ($ip, $masklen = 128)
1589 $query = 'select id from IPv6Network where ip <= ? AND last_ip >= ? and mask < ? order by mask desc limit 1';
1590 $result = usePreparedSelectBlade ($query, array ($ip->getBin(), $ip->getBin(), $masklen));
1591 if ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1596 // It is a wrapper around updateV4Address and updateV6Address.
1597 // You can pass dotted IPv4, human representation of IPv6, or instance of IPv6Address
1598 function updateAddress ($ip = 0, $name = '', $reserved = 'no')
1600 if (is_a ($ip, 'IPv6Address'))
1601 return updateV6Address ($ip, $name, $reserved);
1602 $ipv6 = new IPv6Address
;
1603 if ($ipv6->parse ($ip))
1604 return updateV6Address ($ipv6, $name, $reserved);
1605 return updateV4Address ($ip, $name, $reserved);
1608 // This function is actually used not only to update, but also to create records,
1609 // that's why ON DUPLICATE KEY UPDATE was replaced by DELETE-INSERT pair
1610 // (MySQL 4.0 workaround).
1611 function updateV4Address ($ip = 0, $name = '', $reserved = 'no')
1613 usePreparedExecuteBlade ('DELETE FROM IPv4Address WHERE ip = INET_ATON(?)', array ($ip));
1614 // INSERT may appear not necessary.
1615 if ($name == '' and $reserved == 'no')
1617 $ret = usePreparedExecuteBlade
1619 'INSERT INTO IPv4Address (name, reserved, ip) VALUES (?, ?, INET_ATON(?))',
1620 array ($name, $reserved, $ip)
1622 return $ret !== FALSE ?
'' : (__FUNCTION__
. 'query failed');
1625 function updateV6Address ($ip, $name = '', $reserved = 'no')
1627 usePreparedDeleteBlade ('IPv6Address', array ('ip' => $ip->getBin()));
1628 // INSERT may appear not necessary.
1629 if ($name == '' and $reserved == 'no')
1631 $ret = usePreparedInsertBlade
1634 array ('name' => $name, 'reserved' => $reserved, 'ip' => $ip->getBin())
1636 return $ret !== FALSE ?
'' : (__FUNCTION__
. 'query failed');
1639 function updateBond ($ip='', $object_id=0, $name='', $type='')
1641 return usePreparedExecuteBlade
1643 'UPDATE IPv4Allocation SET name=?, type=? WHERE ip=INET_ATON(?) AND object_id=?',
1644 array ($name, $type, $ip, $object_id)
1648 function updateIPv6Bond ($ip, $object_id=0, $name='', $type='')
1650 return usePreparedUpdateBlade
1660 'ip' => $ip->getBin(),
1661 'object_id' => $object_id,
1666 function unbindIpFromObject ($ip, $object_id)
1668 return usePreparedExecuteBlade
1670 'DELETE FROM IPv4Allocation WHERE ip=INET_ATON(?) AND object_id=?',
1671 array ($ip, $object_id)
1675 function unbindIPv6FromObject ($ip, $object_id)
1677 return usePreparedDeleteBlade
1680 array ('ip' => $ip->getBin(), 'object_id' => $object_id)
1684 function getIPv4PrefixSearchResult ($terms)
1686 $byname = getSearchResultByField
1695 foreach ($byname as $row)
1696 $ret[$row['id']] = spotEntity ('ipv4net', $row['id']);
1700 function getIPv6PrefixSearchResult ($terms)
1702 $byname = getSearchResultByField
1711 foreach ($byname as $row)
1712 $ret[$row['id']] = spotEntity ('ipv6net', $row['id']);
1716 function getIPv4AddressSearchResult ($terms)
1718 $query = "select inet_ntoa(ip) as ip, name from IPv4Address where ";
1721 foreach (explode (' ', $terms) as $term)
1723 $query .= $or . "name like ?";
1725 $qparams[] = "%${term}%";
1727 $result = usePreparedSelectBlade ($query, $qparams);
1729 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1730 $ret[$row['ip']] = $row;
1734 function getIPv6AddressSearchResult ($terms)
1736 $query = "select ip, name from IPv6Address where ";
1739 foreach (explode (' ', $terms) as $term)
1741 $query .= $or . "name like ?";
1743 $qparams[] = "%${term}%";
1745 $result = usePreparedSelectBlade ($query, $qparams);
1747 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1748 $ret[$row['ip']] = $row;
1752 function getIPv4RSPoolSearchResult ($terms)
1754 $byname = getSearchResultByField
1763 foreach ($byname as $row)
1764 $ret[$row['id']] = spotEntity ('ipv4rspool', $row['id']);
1768 function getIPv4VServiceSearchResult ($terms)
1770 $byname = getSearchResultByField
1779 foreach ($byname as $row)
1780 $ret[$row['id']] = spotEntity ('ipv4vs', $row['id']);
1784 function getAccountSearchResult ($terms)
1786 $byUsername = getSearchResultByField
1789 array ('user_id', 'user_name', 'user_realname'),
1794 $byRealname = getSearchResultByField
1797 array ('user_id', 'user_name', 'user_realname'),
1802 // Merge it together, if duplicates persist, byUsername wins
1804 foreach (array ($byRealname, $byUsername) as $array)
1805 foreach ($array as $user)
1807 $user['realm'] = 'user';
1808 $ret[$user['user_id']] = $user;
1813 function getFileSearchResult ($terms)
1815 $byName = getSearchResultByField
1823 $byComment = getSearchResultByField
1831 // Filter out dupes.
1832 foreach ($byName as $res1)
1833 foreach (array_keys ($byComment) as $key2)
1834 if ($res1['id'] == $byComment[$key2]['id'])
1836 unset ($byComment[$key2]);
1840 foreach (array_merge ($byName, $byComment) as $row)
1841 $ret[$row['id']] = spotEntity ('file', $row['id']);
1845 function getRackSearchResult ($terms)
1847 $byName = getSearchResultByField
1855 $byComment = getSearchResultByField
1863 // Filter out dupes.
1864 foreach ($byName as $res1)
1865 foreach (array_keys ($byComment) as $key2)
1866 if ($res1['id'] == $byComment[$key2]['id'])
1868 unset ($byComment[$key2]);
1872 foreach (array_merge ($byName, $byComment) as $row)
1873 $ret[$row['id']] = spotEntity ('rack', $row['id']);
1877 function getVLANSearchResult ($terms)
1881 if (preg_match ('/^vlan\s*(\d+)$/i', $terms, $matches))
1883 $byID = getSearchResultByField
1886 array ('domain_id', 'vlan_id'),
1892 foreach ($byID as $row)
1894 $vlan_ck = $row['domain_id'] . '-' . $row['vlan_id'];
1895 $ret[$vlan_ck] = $vlan_ck;
1900 $byDescr = getSearchResultByField
1903 array ('domain_id', 'vlan_id'),
1907 foreach ($byDescr as $row)
1909 $vlan_ck = $row['domain_id'] . '-' . $row['vlan_id'];
1910 $ret[$vlan_ck] = $vlan_ck;
1916 function getSearchResultByField ($tname, $rcolumns, $scolumn, $terms, $ocolumn = '', $exactness = 0)
1921 foreach ($rcolumns as $col)
1923 $query .= $pfx . $col;
1927 $query .= " from ${tname} where ";
1928 foreach (explode (' ', $terms) as $term)
1932 case 2: // does this work as expected?
1933 $query .= $pfx . "binary ${scolumn} = ?";
1937 $query .= $pfx . "${scolumn} = ?";
1941 $query .= $pfx . "${scolumn} like ?";
1942 $qparams[] = "%${term}%";
1948 $query .= " order by ${ocolumn}";
1949 $result = usePreparedSelectBlade ($query, $qparams);
1951 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1956 function getObjectSearchResults ($what)
1960 foreach ($searchfunc['object'] as $method => $func)
1961 foreach ($func ($what) as $objRecord)
1963 $ret[$objRecord['id']]['id'] = $objRecord['id'];
1964 $ret[$objRecord['id']][$method] = $objRecord[$method];
1969 function getObjectAttrsSearchResults ($what)
1972 foreach (array ('name', 'label', 'asset_no') as $column)
1974 $tmp = getSearchResultByField
1982 foreach ($tmp as $row)
1984 $ret[$row['id']]['id'] = $row['id'];
1985 $ret[$row['id']]['by_attr'][] = $column;
1991 // Look for EXACT value in stickers and return a list of pairs "object_id-attribute_id",
1992 // which matched. A partilar object_id could be returned more, than once, if it has
1993 // multiple matching stickers. Search is only performed on "string" attributes.
1994 function getStickerSearchResults ($what, $exactness = 0)
1996 $stickers = getSearchResultByField
1999 array ('object_id', 'attr_id'),
2005 $map = getAttrMap();
2007 foreach ($stickers as $sticker)
2008 if ($map[$sticker['attr_id']]['type'] == 'string')
2010 $ret[$sticker['object_id']]['id'] = $sticker['object_id'];
2011 $ret[$sticker['object_id']]['by_sticker'][] = $sticker['attr_id'];
2016 // search in port "reservation comment", "label" and "L2 address" columns
2017 function getPortSearchResults ($what)
2020 $ports = getSearchResultByField
2023 array ('object_id', 'id', 'reservation_comment'),
2024 'reservation_comment',
2029 foreach ($ports as $port)
2031 $ret[$port['object_id']]['id'] = $port['object_id'];
2032 $ret[$port['object_id']]['by_port'][$port['id']] = $port['reservation_comment'];
2034 $ports = getSearchResultByField
2037 array ('object_id', 'id', 'label'),
2043 foreach ($ports as $port)
2045 $ret[$port['object_id']]['id'] = $port['object_id'];
2046 $ret[$port['object_id']]['by_port'][$port['id']] = $port['label'];
2050 $db_l2address = l2addressForDatabase ($what);
2052 catch (InvalidArgException
$e)
2056 $ports = getSearchResultByField
2059 array ('object_id', 'id', 'l2address'),
2065 foreach ($ports as $port)
2067 $ret[$port['object_id']]['id'] = $port['object_id'];
2068 $ret[$port['object_id']]['by_port'][$port['id']] = $port['l2address'];
2073 // search in IPv4 allocations
2074 function getObjectIfacesSearchResults ($what)
2077 $ifaces4 = getSearchResultByField
2080 array ('object_id', 'name'),
2085 $ifaces6 = getSearchResultByField
2088 array ('object_id', 'name'),
2093 foreach (array_merge ($ifaces4, $ifaces6) as $row)
2095 $ret[$row['object_id']]['id'] = $row['object_id'];
2096 $ret[$row['object_id']]['by_iface'][] = $row['name'];
2101 function getObjectNATSearchResults ($what)
2104 $ifaces = getSearchResultByField
2107 array ('object_id', 'description'),
2112 foreach ($ifaces as $row)
2114 $ret[$row['object_id']]['id'] = $row['object_id'];
2115 $ret[$row['object_id']]['by_nat'][] = $row['description'];
2120 // This function returns either port ID or NULL for specified arguments.
2121 function getPortIDs ($object_id, $port_name)
2124 $result = usePreparedSelectBlade ('SELECT id FROM Port WHERE object_id = ? AND name = ?', array ($object_id, $port_name));
2125 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2126 $ret[] = $row['id'];
2130 // Search in "FQDN" attribute only, and return object ID, when there is exactly
2131 // one result found (and NULL in any other case).
2132 function searchByMgmtHostname ($string)
2134 $result = usePreparedSelectBlade ('SELECT object_id FROM AttributeValue WHERE attr_id = 3 AND string_value = ? LIMIT 2', array ($string));
2135 $rows = $result->fetchAll (PDO
::FETCH_NUM
);
2136 if (count ($rows) != 1)
2141 function commitCreateUserAccount ($username, $realname, $password)
2143 return usePreparedInsertBlade
2148 'user_name' => $username,
2149 'user_realname' => $realname,
2150 'user_password_hash' => $password,
2155 function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
2157 return usePreparedUpdateBlade
2162 'user_name' => $new_username,
2163 'user_realname' => $new_realname,
2164 'user_password_hash' => $new_password,
2166 array ('user_id' => $id)
2170 // This function returns an array of all port type pairs from PortCompat table.
2171 function getPortOIFCompat ()
2174 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
2175 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
2176 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
2177 'ORDER BY type1name, type2name';
2178 $result = usePreparedSelectBlade ($query);
2179 return $result->fetchAll (PDO
::FETCH_ASSOC
);
2182 // Returns an array of all object type pairs from the ObjectParentCompat table.
2183 function getObjectParentCompat ()
2186 'SELECT parent_objtype_id, child_objtype_id, d1.dict_value AS parent_name, d2.dict_value AS child_name FROM ' .
2187 'ObjectParentCompat AS pc INNER JOIN Dictionary AS d1 ON pc.parent_objtype_id = d1.dict_key ' .
2188 'INNER JOIN Dictionary AS d2 ON pc.child_objtype_id = d2.dict_key ' .
2189 'ORDER BY parent_name, child_name';
2190 $result = usePreparedSelectBlade ($query);
2191 return $result->fetchAll (PDO
::FETCH_ASSOC
);
2194 // Used to determine if a type of object may have a parent or not
2195 function rackObjectTypeMayHaveParent ($objtype_id)
2197 $result = usePreparedSelectBlade ('SELECT COUNT(*) FROM ObjectParentCompat WHERE child_objtype_id = ?', array ($objtype_id));
2198 $row = $result->fetch (PDO
::FETCH_NUM
);
2204 // Add a pair to the ObjectParentCompat table.
2205 function commitSupplementOPC ($parent_objtype_id, $child_objtype_id)
2207 if ($parent_objtype_id <= 0)
2208 throw new InvalidArgException ('parent_objtype_id', $parent_objtype_id);
2209 if ($child_objtype_id <= 0)
2210 throw new InvalidArgException ('child_objtype_id', $child_objtype_id);
2211 return usePreparedInsertBlade
2213 'ObjectParentCompat',
2214 array ('parent_objtype_id' => $parent_objtype_id, 'child_objtype_id' => $child_objtype_id)
2218 // Remove a pair from the ObjectParentCompat table.
2219 function commitReduceOPC ($parent_objtype_id, $child_objtype_id)
2221 return usePreparedDeleteBlade ('ObjectParentCompat', array ('parent_objtype_id' => $parent_objtype_id, 'child_objtype_id' => $child_objtype_id));
2224 function getDictStats ()
2226 $stock_chapters = array (1, 2, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33);
2227 $result = usePreparedSelectBlade
2229 "select Chapter.id as chapter_no, Chapter.name as chapter_name, count(dict_key) as wc from " .
2230 "Chapter left join Dictionary on Chapter.id = Dictionary.chapter_id group by Chapter.id"
2232 $tc = $tw = $uc = $uw = 0;
2233 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2237 if (in_array ($row['chapter_no'], $stock_chapters))
2243 $result = usePreparedSelectBlade
2245 "select count(object_id) as attrc from RackObject as ro left join " .
2246 "AttributeValue as av on ro.id = av.object_id group by ro.id"
2248 $to = $ta = $so = 0;
2249 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2252 if ($row['attrc'] != 0)
2255 $ta +
= $row['attrc'];
2260 $ret['Total chapters in dictionary'] = $tc;
2261 $ret['Total words in dictionary'] = $tw;
2262 $ret['User chapters'] = $uc;
2263 $ret['Words in user chapters'] = $uw;
2264 $ret['Total objects'] = $to;
2265 $ret['Objects with stickers'] = $so;
2266 $ret['Total stickers attached'] = $ta;
2270 function getIPv4Stats ()
2274 $subject[] = array ('q' => 'select count(id) from IPv4Network', 'txt' => 'Networks');
2275 $subject[] = array ('q' => 'select count(ip) from IPv4Address', 'txt' => 'Addresses commented/reserved');
2276 $subject[] = array ('q' => 'select count(ip) from IPv4Allocation', 'txt' => 'Addresses allocated');
2277 $subject[] = array ('q' => 'select count(*) from IPv4NAT', 'txt' => 'NAT rules');
2278 $subject[] = array ('q' => 'select count(id) from IPv4VS', 'txt' => 'Virtual services');
2279 $subject[] = array ('q' => 'select count(id) from IPv4RSPool', 'txt' => 'Real server pools');
2280 $subject[] = array ('q' => 'select count(id) from IPv4RS', 'txt' => 'Real servers');
2281 $subject[] = array ('q' => 'select count(distinct object_id) from IPv4LB', 'txt' => 'Load balancers');
2283 foreach ($subject as $item)
2285 $result = usePreparedSelectBlade ($item['q']);
2286 $row = $result->fetch (PDO
::FETCH_NUM
);
2287 $ret[$item['txt']] = $row[0];
2293 function getIPv6Stats ()
2297 $subject[] = array ('q' => 'select count(id) from IPv6Network', 'txt' => 'Networks');
2298 $subject[] = array ('q' => 'select count(ip) from IPv6Address', 'txt' => 'Addresses commented/reserved');
2299 $subject[] = array ('q' => 'select count(ip) from IPv6Allocation', 'txt' => 'Addresses allocated');
2301 foreach ($subject as $item)
2303 $result = usePreparedSelectBlade ($item['q']);
2304 $row = $result->fetch (PDO
::FETCH_NUM
);
2305 $ret[$item['txt']] = $row[0];
2311 function getRackspaceStats ()
2315 $subject[] = array ('q' => 'select count(*) from RackRow', 'txt' => 'Rack rows');
2316 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
2317 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
2318 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
2320 foreach ($subject as $item)
2322 $result = usePreparedSelectBlade ($item['q']);
2323 $row = $result->fetch (PDO
::FETCH_NUM
);
2324 $ret[$item['txt']] = !strlen ($row[0]) ?
0 : $row[0];
2332 The following allows figuring out records in TagStorage, which refer to non-existing entities:
2334 mysql> select entity_id from TagStorage left join Files on entity_id = id where entity_realm = 'file' and id is null;
2335 mysql> select entity_id from TagStorage left join IPv4Network on entity_id = id where entity_realm = 'ipv4net' and id is null;
2336 mysql> select entity_id from TagStorage left join RackObject on entity_id = id where entity_realm = 'object' and id is null;
2337 mysql> select entity_id from TagStorage left join Rack on entity_id = id where entity_realm = 'rack' and id is null;
2338 mysql> select entity_id from TagStorage left join IPv4VS on entity_id = id where entity_realm = 'ipv4vs' and id is null;
2339 mysql> select entity_id from TagStorage left join IPv4RSPool on entity_id = id where entity_realm = 'ipv4rspool' and id is null;
2340 mysql> select entity_id from TagStorage left join UserAccount on entity_id = user_id where entity_realm = 'user' and user_id is null;
2342 Accordingly, these are the records, which refer to non-existent tags:
2344 mysql> select tag_id from TagStorage left join TagTree on tag_id = id where id is null;
2348 function commitDeleteChapter ($chapter_no = 0)
2350 return usePreparedDeleteBlade ('Chapter', array ('id' => $chapter_no, 'sticky' => 'no'));
2353 // This is a dictionary accessor. We perform link rendering, so the user sees
2354 // nice <select> drop-downs.
2355 function readChapter ($chapter_id = 0, $style = '')
2357 $result = usePreparedSelectBlade
2359 "select dict_key, dict_value as value from Dictionary " .
2360 "where chapter_id = ?",
2364 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2366 parseWikiLink ($row);
2367 $chapter[$row['dict_key']] = ($style == 'a' ?
$row['a_value'] : $row['o_value']);
2369 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
2374 // Return refcounters for all given keys of the given chapter.
2375 function getChapterRefc ($chapter_id, $keylist)
2378 foreach ($keylist as $key)
2380 switch ($chapter_id)
2383 // RackObjectType chapter is referenced by AttributeMap and RackObject tables
2384 $query = 'select dict_key as uint_value, (select count(*) from AttributeMap where objtype_id = dict_key) + ' .
2385 "(select count(*) from RackObject where objtype_id = dict_key) as refcnt from Dictionary where chapter_id = ?";
2388 // PortOuterInterface chapter is referenced by PortCompat, PortInterfaceCompat and Port tables
2389 $query = 'select dict_key as uint_value, (select count(*) from PortCompat where type1 = dict_key or type2 = dict_key) + ' .
2390 '(select count(*) from Port where type = dict_key) + (SELECT COUNT(*) FROM PortInterfaceCompat WHERE oif_id = dict_key) as refcnt ' .
2391 "from Dictionary where chapter_id = ?";
2394 // Find the list of all assigned values of dictionary-addressed attributes, each with
2395 // chapter/word keyed reference counters.
2396 $query = "select uint_value, count(object_id) as refcnt
2397 from AttributeMap am
2398 inner join AttributeValue av on am.attr_id = av.attr_id
2399 inner join RackObject ro on ro.id = av.object_id
2400 where am.chapter_id = ? and ro.objtype_id = am.objtype_id
2401 group by uint_value";
2404 $result = usePreparedSelectBlade ($query, array ($chapter_id));
2405 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2406 $ret[$row['uint_value']] = $row['refcnt'];
2410 // Return a list of all stickers with sticker map applied. Each sticker records will
2411 // list all its ways on the map with refcnt set.
2412 function getAttrMap ()
2414 $result = usePreparedSelectBlade
2416 'SELECT id, type, name, chapter_id, (SELECT dict_value FROM Dictionary WHERE dict_key = objtype_id) '.
2417 'AS objtype_name, (SELECT name FROM Chapter WHERE id = chapter_id) ' .
2418 'AS chapter_name, objtype_id, (SELECT COUNT(object_id) FROM AttributeValue AS av INNER JOIN RackObject AS ro ' .
2419 'ON av.object_id = ro.id WHERE av.attr_id = Attribute.id AND ro.objtype_id = AttributeMap.objtype_id) ' .
2420 'AS refcnt FROM Attribute LEFT JOIN AttributeMap ON id = attr_id ORDER BY Attribute.name, objtype_name'
2423 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2425 if (!isset ($ret[$row['id']]))
2426 $ret[$row['id']] = array
2429 'type' => $row['type'],
2430 'name' => $row['name'],
2431 'application' => array(),
2433 if ($row['objtype_id'] == '')
2435 $application = array
2437 'objtype_id' => $row['objtype_id'],
2438 'refcnt' => $row['refcnt'],
2440 if ($row['type'] == 'dict')
2442 $application['chapter_no'] = $row['chapter_id'];
2443 $application['chapter_name'] = $row['chapter_name'];
2445 $ret[$row['id']]['application'][] = $application;
2450 // FIXME: don't store garbage in chapter_no for non-dictionary types.
2451 function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
2454 throw new InvalidArgException ('$attr_id', $attr_id);
2455 if ($objtype_id <= 0)
2456 throw new InvalidArgException ('$objtype_id', $objtype_id);
2458 return usePreparedInsertBlade
2463 'attr_id' => $attr_id,
2464 'objtype_id' => $objtype_id,
2465 'chapter_id' => $chapter_no
2470 function cacheAllObjectsAttributes()
2472 global $object_attribute_cache;
2473 $object_attribute_cache = fetchAttrsForObjects(NULL);
2476 // Fetches a list of attributes for each object in $object_set array.
2477 // If $object_set is not set, returns attributes for all objects in DB
2478 // Returns an array with object_id keys
2479 function fetchAttrsForObjects($object_set)
2483 "select A.id as attr_id, A.name as attr_name, A.type as attr_type, C.name as chapter_name, " .
2484 "C.id as chapter_id, AV.uint_value, AV.float_value, AV.string_value, D.dict_value, RO.id as object_id from " .
2485 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
2486 "inner join Attribute as A on AM.attr_id = A.id " .
2487 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
2488 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_id = D.chapter_id " .
2489 "left join Chapter as C on AM.chapter_id = C.id";
2490 if (is_array ($object_set) && !empty ($object_set))
2492 $query .= ' WHERE RO.id IN (';
2493 foreach ($object_set as $object_id)
2494 $query .= intval ($object_id) . ', ';
2495 $query = trim ($query, ', ') . ')';
2497 $query .= " order by A.name, A.type";
2499 $result = usePreparedSelectBlade ($query);
2500 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2502 $object_id = $row['object_id'];
2503 $attr_id = $row['attr_id'];
2504 if (!array_key_exists ($object_id, $ret))
2505 $ret[$object_id] = array();
2508 $record['id'] = $row['attr_id'];
2509 $record['name'] = $row['attr_name'];
2510 $record['type'] = $row['attr_type'];
2511 switch ($row['attr_type'])
2514 $record['chapter_id'] = $row['chapter_id'];
2515 $record['chapter_name'] = $row['chapter_name'];
2516 $record['key'] = $row['uint_value'];
2521 $record['value'] = $row[$row['attr_type'] . '_value'];
2522 parseWikiLink ($record);
2525 $record['value'] = NULL;
2528 $ret[$object_id][$attr_id] = $record;
2533 // This function returns all optional attributes for requested object
2534 // as an array of records.
2535 // Empty array is returned, if there are no attributes found.
2536 function getAttrValues ($object_id)
2538 global $object_attribute_cache;
2539 if (isset ($object_attribute_cache[$object_id]))
2540 return $object_attribute_cache[$object_id];
2542 $ret = fetchAttrsForObjects(array($object_id));
2544 if (isset ($ret[$object_id]))
2546 $attrs = $ret[$object_id];
2547 $object_attribute_cache[$object_id] = $attrs;
2552 function commitResetAttrValue ($object_id = 0, $attr_id = 0)
2554 return usePreparedDeleteBlade ('AttributeValue', array ('object_id' => $object_id, 'attr_id' => $attr_id));
2557 function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
2559 if ($object_id <= 0)
2560 throw new InvalidArgException ('$objtype_id', $objtype_id);
2562 throw new InvalidArgException ('$attr_id', $attr_id);
2563 if (!strlen ($value))
2564 return commitResetAttrValue ($object_id, $attr_id);
2565 $result = usePreparedSelectBlade ('select type as attr_type from Attribute where id = ?', array ($attr_id));
2566 $row = $result->fetch (PDO
::FETCH_NUM
);
2567 $attr_type = $row[0];
2574 $column = $attr_type . '_value';
2577 $column = 'uint_value';
2580 throw new InvalidArgException ('$attr_type', $attr_type, 'Unknown attribute type found in object #'.$object_id.', attribute #'.$attr_id);
2582 usePreparedDeleteBlade ('AttributeValue', array ('object_id' => $object_id, 'attr_id' => $attr_id));
2583 // We know $value isn't empty here.
2584 usePreparedInsertBlade
2590 'object_id' => $object_id,
2591 'attr_id' => $attr_id,
2597 function convertPDOException ($e)
2599 switch ($e->getCode() . '-' . $e->errorInfo
[1])
2602 $text = 'such record already exists';
2605 $text = 'such record already exists';
2609 $text = 'foreign key violation';
2612 $text = 'lock wait timeout';
2617 return new RTDatabaseError ($text);
2620 // This is a swiss-knife blade to insert a record into a table.
2621 // The first argument is table name.
2622 // The second argument is an array of "name" => "value" pairs.
2623 function usePreparedInsertBlade ($tablename, $columns)
2626 $query = "INSERT INTO ${tablename} (" . implode (', ', array_keys ($columns));
2627 $query .= ') VALUES (' . questionMarks (count ($columns)) . ')';
2628 // Now the query should be as follows:
2629 // INSERT INTO table (c1, c2, c3) VALUES (?, ?, ?)
2632 $prepared = $dbxlink->prepare ($query);
2633 if (!$prepared->execute (array_values ($columns)))
2635 return $prepared->rowCount() == 1;
2637 catch (PDOException
$e)
2639 throw convertPDOException ($e);
2643 // This swiss-knife blade deletes any number of records from the specified table
2644 // using the specified key names and values.
2645 function usePreparedDeleteBlade ($tablename, $columns, $conjunction = 'AND')
2649 $query = "DELETE FROM ${tablename} WHERE ";
2650 foreach ($columns as $colname => $colvalue)
2652 $query .= " ${conj} ${colname}=?";
2653 $conj = $conjunction;
2657 $prepared = $dbxlink->prepare ($query);
2658 if (!$prepared->execute (array_values ($columns)))
2660 return $prepared->rowCount(); // FALSE !== 0
2662 catch (PDOException
$e)
2664 throw convertPDOException ($e);
2668 function usePreparedSelectBlade ($query, $args = array())
2671 $prepared = $dbxlink->prepare ($query);
2674 if (!$prepared->execute ($args))
2678 catch (PDOException
$e)
2680 throw convertPDOException ($e);
2684 function usePreparedUpdateBlade ($tablename, $set_columns, $where_columns, $conjunction = 'AND')
2688 $query = "UPDATE ${tablename} SET ";
2689 foreach (array_keys ($set_columns) as $colname)
2691 $query .= "${conj}${colname}=?";
2695 $query .= ' WHERE ';
2696 foreach (array_keys ($where_columns) as $colname)
2698 $query .= " ${conj} ${colname}=?";
2699 $conj = $conjunction;
2703 $prepared = $dbxlink->prepare ($query);
2704 $prepared->execute (array_merge (array_values ($set_columns), array_values ($where_columns)));
2706 catch (PDOException
$e)
2708 throw convertPDOException ($e);
2712 // Prepare and execute the statement with parameters, then return number of
2713 // rows affected (or FALSE in case of an error).
2714 function usePreparedExecuteBlade ($query, $args = array())
2719 if (!$prepared = $dbxlink->prepare ($query))
2721 if (!$prepared->execute ($args))
2723 return $prepared->rowCount();
2725 catch (PDOException
$e)
2727 throw convertPDOException ($e);
2731 function loadConfigCache ()
2733 $result = usePreparedSelectBlade ('SELECT varname, varvalue, vartype, is_hidden, emptyok, description, is_userdefined FROM Config ORDER BY varname');
2735 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2736 $cache[$row['varname']] = $row;
2740 function loadUserConfigCache ($username = NULL)
2742 if (!strlen ($username))
2743 throw new InvalidArgException ('$username', $username);
2744 $result = usePreparedSelectBlade ('SELECT varname, varvalue FROM UserConfig WHERE user = ?', array ($username));
2746 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2747 $cache[$row['varname']] = $row;
2751 // Return an array of virtual services. For each of them list real server pools
2752 // with their load balancers and other stats.
2753 function getSLBSummary ()
2755 $result = usePreparedSelectBlade
2757 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
2758 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
2759 'from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id ' .
2760 'inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2761 'left join IPv4RS as rs on rs.rspool_id = lb.rspool_id ' .
2762 'group by vs.id, object_id order by vs.vip, object_id'
2765 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2767 $vsid = $row['vsid'];
2768 $object_id = $row['object_id'];
2769 if (!isset ($ret[$vsid]))
2771 $ret[$vsid] = array();
2772 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
2773 $ret[$vsid][$cname] = $row[$cname];
2774 $ret[$vsid]['lblist'] = array();
2776 // There's only one assigned RS pool possible for each LB-VS combination.
2777 $ret[$vsid]['lblist'][$row['object_id']] = array
2779 'id' => $row['rspool_id'],
2780 'size' => $row['rscount'],
2781 'name' => $row['pool_name']
2787 function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
2789 return usePreparedExecuteBlade
2791 'INSERT INTO IPv4RS (rsip, rsport, rspool_id, inservice, rsconfig) VALUES (INET_ATON(?), ?, ?, ?, ?)',
2795 (!strlen ($rsport) or $rsport === 0) ?
NULL : $rsport,
2797 $inservice == 'yes' ?
'yes' : 'no',
2798 !strlen ($rsconfig) ?
NULL : $rsconfig
2803 function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '', $prio = '')
2805 return usePreparedInsertBlade
2810 'object_id' => $object_id,
2811 'rspool_id' => $pool_id,
2813 'vsconfig' => (!strlen ($vsconfig) ?
NULL : $vsconfig),
2814 'rsconfig' => (!strlen ($rsconfig) ?
NULL : $rsconfig),
2815 'prio' => (!strlen ($prio) ?
NULL : $prio),
2820 function commitDeleteVS ($id = 0)
2822 releaseFiles ('ipv4vs', $id);
2823 return FALSE !== usePreparedDeleteBlade ('IPv4VS', array ('id' => $id)) && FALSE !== destroyTagsForEntity ('ipv4vs', $id);
2826 function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2828 if (long2ip (ip2long ($rsip)) !== $rsip)
2829 throw new InvalidArgException ('$rsip', $rsip);
2830 return usePreparedExecuteBlade
2832 'UPDATE IPv4RS SET rsip=INET_ATON(?), rsport=?, rsconfig=? WHERE id=?',
2836 (!strlen ($rsport) or $rsport === 0) ?
NULL : $rsport,
2837 !strlen ($rsconfig) ?
NULL : $rsconfig,
2843 function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2846 throw new InvalidArgException ('$vip', $vip);
2848 throw new InvalidArgException ('$vport', $vport);
2849 if (!strlen ($proto))
2850 throw new InvalidArgException ('$proto', $proto);
2851 return usePreparedExecuteBlade
2853 'UPDATE IPv4VS SET vip=INET_ATON(?), vport=?, proto=?, name=?, vsconfig=?, rsconfig=? WHERE id=?',
2859 !strlen ($name) ?
NULL : $name,
2860 !strlen ($vsconfig) ?
NULL : $vsconfig,
2861 !strlen ($rsconfig) ?
NULL : $rsconfig,
2867 function loadThumbCache ($rack_id = 0)
2870 $result = usePreparedSelectBlade ("SELECT thumb_data FROM Rack WHERE id = ? AND thumb_data IS NOT NULL", array ($rack_id));
2871 $row = $result->fetch (PDO
::FETCH_ASSOC
);
2873 $ret = base64_decode ($row['thumb_data']);
2877 // Return the list of attached RS pools for the given object. As long as we have
2878 // the LB-VS UNIQUE in IPv4LB table, it is Ok to key returned records
2879 // by vs_id, because there will be only one RS pool listed for each VS of the
2881 function getRSPoolsForObject ($object_id = 0)
2883 $result = usePreparedSelectBlade
2885 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
2886 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig, lb.prio from ' .
2887 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2888 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2889 'left join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
2890 'where lb.object_id = ? ' .
2891 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name',
2895 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2896 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig', 'prio') as $cname)
2897 $ret[$row['vs_id']][$cname] = $row[$cname];
2901 function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
2903 usePreparedInsertBlade
2908 'name' => (!strlen ($name) ?
NULL : $name),
2909 'vsconfig' => (!strlen ($vsconfig) ?
NULL : $vsconfig),
2910 'rsconfig' => (!strlen ($rsconfig) ?
NULL : $rsconfig)
2913 produceTagsForLastRecord ('ipv4rspool', $taglist);
2916 function commitDeleteRSPool ($pool_id = 0)
2918 releaseFiles ('ipv4rspool', $pool_id);
2919 return usePreparedDeleteBlade ('IPv4RSPool', array ('id' => $pool_id)) && destroyTagsForEntity ('ipv4rspool', $pool_id);
2922 function getRSList ()
2924 $result = usePreparedSelectBlade
2926 "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
2927 "from IPv4RS order by rspool_id, IPv4RS.rsip, rsport"
2930 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2931 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
2932 $ret[$row['id']][$cname] = $row[$cname];
2936 // Return the list of all currently configured load balancers with their pool count.
2937 function getLBList ()
2939 $result = usePreparedSelectBlade
2941 "select object_id, count(rspool_id) as poolcount " .
2942 "from IPv4LB group by object_id order by object_id"
2945 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2946 $ret[$row['object_id']] = $row['poolcount'];
2950 // For the given object return: its vsconfig/rsconfig; the list of RS pools
2951 // attached (each with vsconfig/rsconfig in turn), each with the list of
2952 // virtual services terminating the pool. Each pool also lists all real
2953 // servers with rsconfig.
2954 function getSLBConfig ($object_id)
2957 $result = usePreparedSelectBlade
2959 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2960 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2961 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, lb.prio as prio, pool.id as pool_id, pool.name as pool_name, ' .
2962 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
2963 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
2964 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2965 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2966 'inner join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
2967 "where lb.object_id = ? and rs.inservice = 'yes' " .
2968 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport",
2971 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2973 $vs_id = $row['vs_id'];
2974 if (!isset ($ret[$vs_id]))
2976 foreach (array ('vip', 'vport', 'proto', 'vs_name', 'vs_vsconfig', 'vs_rsconfig', 'lb_vsconfig', 'lb_rsconfig', 'pool_vsconfig', 'pool_rsconfig', 'pool_id', 'pool_name', 'prio') as $c)
2977 $ret[$vs_id][$c] = $row[$c];
2978 $ret[$vs_id]['rslist'] = array();
2980 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2981 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
2986 function commitUpdateSLBDefConf ($data)
2988 return saveScript('DefaultVSConfig', $data['vs']) &&
2989 saveScript('DefaultRSConfig', $data['rs']);
2992 function getSLBDefaults ($do_cache_result = FALSE) {
2993 static $ret = array();
2995 if (! $do_cache_result)
2997 elseif (! empty ($ret))
3000 $ret['vs'] = loadScript('DefaultVSConfig');
3001 $ret['rs'] = loadScript('DefaultRSConfig');
3005 function commitSetInService ($rs_id = 0, $inservice = '')
3007 if (! in_array ($inservice, array ('yes', 'no')))
3008 throw new InvalidArgException ('$inservice', $inservice);
3009 return usePreparedUpdateBlade ('IPv4RS', array ('inservice' => $inservice), array ('id' => $rs_id));
3012 function executeAutoPorts ($object_id = 0, $type_id = 0)
3014 if ($object_id == 0)
3015 throw new InvalidArgException ('$object_id', $object_id);
3017 throw new InvalidArgException ('$type_id', $type_id);
3018 foreach (getAutoPorts ($type_id) as $autoport)
3019 commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
3022 // Return only implicitly listed tags, the rest of the chain will be
3023 // generated/deducted later at higher levels.
3024 // Result is a chain: randomly indexed taginfo list.
3025 function loadEntityTags ($entity_realm = '', $entity_id = 0)
3028 $result = usePreparedSelectBlade
3030 "select tt.id, tag from " .
3031 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
3032 "where entity_realm = ? and entity_id = ? " .
3034 array ($entity_realm, $entity_id)
3036 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
3037 $ret[$row['id']] = $row;
3038 return getExplicitTagsOnly ($ret);
3041 // Return a tag chain with all DB tags on it.
3042 function getTagList ()
3045 $result = usePreparedSelectBlade
3047 "select id, parent_id, tag, entity_realm as realm, count(entity_id) as refcnt " .
3048 "from TagTree left join TagStorage on id = tag_id " .
3049 "group by id, entity_realm order by tag"
3051 // Collation index. The resulting rows are ordered according to default collation,
3052 // which is utf8_general_ci for UTF-8.
3054 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
3056 if (!isset ($ret[$row['id']]))
3057 $ret[$row['id']] = array
3060 'tag' => $row['tag'],
3062 'parent_id' => $row['parent_id'],
3063 'refcnt' => array ('total' => 0)
3067 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
3068 $ret[$row['id']]['refcnt']['total'] +
= $row['refcnt'];
3069 // introduce the 'pseudo'-ream 'ipnet' which combines 'ipv4net' and 'ipv6net' realms.
3070 if ($row['realm'] == 'ipv4net' ||
$row['realm'] == 'ipv6net')
3071 if (isset ($ret[$row['id']]['refcnt']['ipnet']))
3072 $ret[$row['id']]['refcnt']['ipnet'] +
= $row['refcnt'];
3074 $ret[$row['id']]['refcnt']['ipnet'] = $row['refcnt'];
3080 // Drop the whole chain stored.
3081 function destroyTagsForEntity ($entity_realm, $entity_id)
3083 return usePreparedDeleteBlade ('TagStorage', array ('entity_realm' => $entity_realm, 'entity_id' => $entity_id));
3086 // Drop only one record. This operation doesn't involve retossing other tags, unlike when adding.
3087 // FIXME: this function could be used by 3rd-party scripts, dismiss it at some later point,
3089 function deleteTagForEntity ($entity_realm, $entity_id, $tag_id)
3091 return usePreparedDeleteBlade ('TagStorage', array ('entity_realm' => $entity_realm, 'entity_id' => $entity_id, 'tag_id' => $tag_id));
3094 // Push a record into TagStorage unconditionally.
3095 function addTagForEntity ($realm, $entity_id, $tag_id)
3098 if (! array_key_exists ($realm, $SQLSchema))
3099 throw new InvalidArgException ('realm', $realm);
3100 // spotEntity ($realm, $entity_id) would be a more expensive way
3101 // to validate two parameters
3102 return usePreparedInsertBlade
3107 'entity_realm' => $realm,
3108 'entity_id' => $entity_id,
3109 'tag_id' => $tag_id,
3114 // Add records into TagStorage, if this makes sense (IOW, they don't appear
3115 // on the implicit list already). Then remove any other records, which
3116 // appear on the "implicit" side of the chain. This will make sure,
3117 // that both the tag base is still minimal and all requested tags appear on
3118 // the resulting tag chain.
3119 // Return TRUE, if any changes were committed.
3120 function rebuildTagChainForEntity ($realm, $entity_id, $extrachain = array())
3122 // Put the current explicit sub-chain into a buffer and merge all tags from
3123 // the extra chain, which aren't there yet.
3124 $newchain = $oldchain = loadEntityTags ($realm, $entity_id);
3125 foreach ($extrachain as $extratag)
3126 if (!tagOnChain ($extratag, $newchain))
3127 $newchain[] = $extratag;
3128 // Then minimize the working buffer and check if it differs from the original
3129 // chain we started with. If it is so, save the work and signal the upper layer.
3130 $newchain = getExplicitTagsOnly ($newchain);
3131 if (tagChainCmp ($oldchain, $newchain))
3133 destroyTagsForEntity ($realm, $entity_id);
3134 foreach ($newchain as $taginfo)
3135 addTagForEntity ($realm, $entity_id, $taginfo['id']);
3141 // Presume, that the target record has no tags attached.
3142 function produceTagsForLastRecord ($realm, $tagidlist, $last_insert_id = 0)
3144 if (!$last_insert_id)
3145 $last_insert_id = lastInsertID();
3146 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagidlist)) as $taginfo)
3147 addTagForEntity ($realm, $last_insert_id, $taginfo['id']);
3150 function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
3152 // $range is in x.x.x.x/x format, split into ip/mask vars
3153 $rangeArray = explode('/', $range);
3154 if (count ($rangeArray) != 2)
3155 throw new InvalidRequestArgException ('range', $range, 'Invalid IPv4 prefix');
3156 $ip = $rangeArray[0];
3157 $mask = $rangeArray[1];
3159 if (!strlen ($ip) or !strlen ($mask))
3160 throw new InvalidRequestArgException ('range', $range, 'Invalid IPv4 prefix');
3161 $ipL = ip2long($ip);
3162 $maskL = ip2long($mask);
3163 if ($ipL == -1 ||
$ipL === FALSE)
3164 throw new InvalidRequestArgException ('range', $range, 'Invalid IPv4 address');
3165 if ($mask < 32 && $mask > 0)
3169 $maskB = decbin($maskL);
3170 if (strlen($maskB)!=32)
3171 throw new InvalidRequestArgException ('range', $range, 'Invalid netmask');
3174 foreach( str_split ($maskB) as $digit)
3181 if ($zeroes == TRUE)
3182 throw new InvalidRequestArgException ('range', $range, 'Invalid netmask');
3187 $binmask = binMaskFromDec($maskL);
3188 $ipL = $ipL & $binmask;
3189 usePreparedInsertBlade
3194 'ip' => sprintf ('%u', $ipL),
3200 if ($is_bcast and $maskL < 31)
3202 $network_addr = long2ip ($ipL);
3203 $broadcast_addr = long2ip ($ipL |
binInvMaskFromDec ($maskL));
3204 updateV4Address ($network_addr, 'network', 'yes');
3205 updateV4Address ($broadcast_addr, 'broadcast', 'yes');
3207 produceTagsForLastRecord ('ipv4net', $taglist);
3210 function createIPv6Prefix ($range = '', $name = '', $taglist = array())
3212 // $range is in aaa0:b::c:d/x format, split into ip/mask vars
3213 $rangeArray = explode ('/', $range);
3214 if (count ($rangeArray) != 2)
3215 throw new InvalidRequestArgException ('range', $range, 'Invalid IPv6 prefix');
3216 $ip = $rangeArray[0];
3217 $mask = $rangeArray[1];
3218 $address = new IPv6Address
;
3219 if (!strlen ($ip) or !strlen ($mask) or ! $address->parse ($ip))
3220 throw new InvalidRequestArgException ('range', $range, 'Invalid IPv4 prefix');
3221 $network_addr = $address->get_first_subnet_address ($mask);
3222 $broadcast_addr = $address->get_last_subnet_address ($mask);
3223 if (! $network_addr ||
! $broadcast_addr)
3224 throw new InvalidRequestArgException ('range', $range, 'Invalid netmask');
3225 usePreparedInsertBlade
3230 'ip' => $network_addr->getBin(),
3231 'last_ip' => $broadcast_addr->getBin(),
3236 produceTagsForLastRecord ('ipv6net', $taglist);
3239 // FIXME: This function doesn't wipe relevant records from IPv4Address table.
3240 function destroyIPv4Prefix ($id)
3242 releaseFiles ('ipv4net', $id);
3243 usePreparedDeleteBlade ('IPv4Network', array ('id' => $id));
3244 destroyTagsForEntity ('ipv4net', $id);
3247 // FIXME: This function doesn't wipe relevant records from IPv6Address table.
3248 function destroyIPv6Prefix ($id)
3250 releaseFiles ('ipv6net', $id);
3251 usePreparedDeleteBlade ('IPv6Network', array ('id' => $id));
3252 destroyTagsForEntity ('ipv6net', $id);
3255 function loadScript ($name)
3257 $result = usePreparedSelectBlade ("select script_text from Script where script_name = ?", array ($name));
3258 $row = $result->fetch (PDO
::FETCH_NUM
);
3265 function saveScript ($name = '', $text)
3267 if (!strlen ($name))
3268 throw new InvalidArgException ('$name', $name);
3269 return usePreparedExecuteBlade
3271 'INSERT INTO Script (script_name, script_text) VALUES (?, ?) ' .
3272 'ON DUPLICATE KEY UPDATE script_text=?',
3273 array ($name, $text, $text)
3277 function newPortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3279 if (NULL === getIPv4AddressNetworkId ($localip))
3280 return "$localip: Non existant ip";
3281 if (NULL === getIPv4AddressNetworkId ($remoteip))
3282 return "$remoteip: Non existant ip";
3283 if ( ($localport <= 0) or ($localport >= 65536) )
3284 return "$localport: invaild port";
3285 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
3286 return "$remoteport: invaild port";
3288 $result = usePreparedExecuteBlade
3290 'INSERT INTO IPv4NAT (object_id, localip, remoteip, localport, remoteport, proto, description) ' .
3291 'VALUES (?, INET_ATON(?), INET_ATON(?), ?, ?, ?, ?)',
3303 return $result !== FALSE ?
'' : (__FUNCTION__
. '(): failed to insert the rule');
3306 function deletePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
3308 return usePreparedExecuteBlade
3310 'DELETE FROM IPv4NAT WHERE object_id=? AND localip=INET_ATON(?) AND ' .
3311 'remoteip=INET_ATON(?) AND localport=? AND remoteport=? AND proto=?',