4 * This file is a library of database access functions for RackTables.
8 function escapeString ($value, $do_db_escape = TRUE)
10 $ret = htmlspecialchars ($value, ENT_QUOTES
, 'UTF-8');
14 $ret = substr ($dbxlink->quote ($ret), 1, -1);
19 function getRackspace ($tagfilter = array(), $tfmode = 'any')
21 $whereclause = getWhereClause ($tagfilter);
23 "select dict_key as row_id, dict_value as row_name " .
24 "from Chapter natural join Dictionary left join Rack on Rack.row_id = dict_key " .
25 "left join TagStorage on Rack.id = TagStorage.target_id and target_realm = 'rack' " .
26 "where chapter_name = 'RackRow' " .
28 " order by dict_value";
29 $result = useSelectBlade ($query, __FUNCTION__
);
31 $clist = array ('row_id', 'row_name');
32 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
33 foreach ($clist as $cname)
34 $ret[$row['row_id']][$cname] = $row[$cname];
35 $result->closeCursor();
39 // Return detailed information about one rack row.
40 function getRackRowInfo ($rackrow_id)
43 "select dict_key as id, dict_value as name, count(Rack.id) as count, " .
44 "if(isnull(sum(Rack.height)),0,sum(Rack.height)) as sum " .
45 "from Chapter natural join Dictionary left join Rack on Rack.row_id = dict_key " .
46 "where chapter_name = 'RackRow' and dict_key = ${rackrow_id} " .
48 $result = useSelectBlade ($query, __FUNCTION__
);
49 if ($row = $result->fetch (PDO
::FETCH_ASSOC
))
55 // This function returns id->name map for all object types. The map is used
56 // to build <select> input for objects.
57 function getObjectTypeList ()
59 return readChapter ('RackObjectType');
62 // Return a part of SQL query suitable for embeding into a bigger text.
63 // The returned result should list all tag IDs shown in the tag filter.
64 function getWhereClause ($tagfilter = array())
67 if (count ($tagfilter))
69 $whereclause .= ' and (';
71 foreach ($tagfilter as $tag_id)
73 $whereclause .= $conj . 'tag_id = ' . $tag_id;
81 // Return a simple object list w/o related information.
82 function getNarrowObjectList ($type_id = 0)
87 showError ('Invalid argument', __FUNCTION__
);
90 // object type id is known and constant, but it's Ok to have this standard overhead
92 "select RackObject.id as id, RackObject.name as name, dict_value as objtype_name, " .
94 "RackObject inner join Dictionary on objtype_id=dict_key natural join Chapter " .
95 "where RackObject.deleted = 'no' and chapter_name = 'RackObjectType' " .
96 "and objtype_id = ${type_id} " .
98 $result = useSelectBlade ($query, __FUNCTION__
);
99 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
107 $ret[$row['id']][$cname] = $row[$cname];
108 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
113 // Return a filtered, detailed object list.
114 function getObjectList ($type_id = 0, $tagfilter = array(), $tfmode = 'any')
116 $whereclause = getWhereClause ($tagfilter);
118 $whereclause .= " and objtype_id = '${type_id}' ";
120 "select distinct RackObject.id as id , RackObject.name as name, dict_value as objtype_name, " .
121 "RackObject.label as label, RackObject.barcode as barcode, " .
122 "dict_key as objtype_id, asset_no, rack_id, Rack.name as Rack_name from " .
123 "((RackObject inner join Dictionary on objtype_id=dict_key natural join Chapter) " .
124 "left join RackSpace on RackObject.id = object_id) " .
125 "left join Rack on rack_id = Rack.id " .
126 "left join TagStorage on RackObject.id = TagStorage.target_id and target_realm = 'object' " .
127 "where RackObject.deleted = 'no' and chapter_name = 'RackObjectType' " .
130 $result = useSelectBlade ($query, __FUNCTION__
);
132 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
145 $ret[$row['id']][$cname] = $row[$cname];
146 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
148 $result->closeCursor();
152 function getRacksForRow ($row_id = 0, $tagfilter = array(), $tfmode = 'any')
155 "select Rack.id, Rack.name, height, Rack.comment, row_id, " .
156 "'yes' as left_is_front, 'yes' as bottom_is_unit1, dict_value as row_name " .
157 "from Rack left join Dictionary on row_id = dict_key natural join Chapter " .
158 "left join TagStorage on Rack.id = TagStorage.target_id and target_realm = 'rack' " .
159 "where chapter_name = 'RackRow' and Rack.deleted = 'no' " .
160 (($row_id == 0) ?
"" : "and row_id = ${row_id} ") .
161 getWhereClause ($tagfilter) .
162 " order by row_name, Rack.id";
163 $result = useSelectBlade ($query, __FUNCTION__
);
176 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
177 foreach ($clist as $cname)
178 $ret[$row['id']][$cname] = $row[$cname];
179 $result->closeCursor();
180 usort ($ret, 'sortRacks');
181 $ret = restoreRackIDs ($ret);
185 // This is a popular helper for getting information about
186 // a particular rack and its rackspace at once.
187 function getRackData ($rack_id = 0, $silent = FALSE)
191 if ($silent == FALSE)
192 showError ('Invalid rack_id', __FUNCTION__
);
196 "select Rack.id, Rack.name, row_id, height, Rack.comment, " .
197 "'yes' as left_is_front, 'yes' as bottom_is_unit1, dict_value as row_name from " .
198 "Rack left join Dictionary on Rack.row_id = dict_key natural join Chapter " .
199 "where chapter_name = 'RackRow' and Rack.id='${rack_id}' and Rack.deleted = 'no' limit 1";
200 $result = useSelectBlade ($query, __FUNCTION__
);
201 if (($row = $result->fetch (PDO
::FETCH_ASSOC
)) == NULL)
203 if ($silent == FALSE)
204 showError ('Query #1 succeded, but returned no data', __FUNCTION__
);
220 foreach ($clist as $cname)
221 $rack[$cname] = $row[$cname];
222 $result->closeCursor();
225 // start with default rackspace
226 for ($i = $rack['height']; $i > 0; $i--)
227 for ($locidx = 0; $locidx < 3; $locidx++
)
228 $rack[$i][$locidx]['state'] = 'F';
232 "select unit_no, atom, state, object_id " .
233 "from RackSpace where rack_id = ${rack_id} and " .
234 "unit_no between 1 and " . $rack['height'] . " order by unit_no";
235 $result = useSelectBlade ($query, __FUNCTION__
);
237 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
239 $rack[$row['unit_no']][$loclist[$row['atom']]]['state'] = $row['state'];
240 $rack[$row['unit_no']][$loclist[$row['atom']]]['object_id'] = $row['object_id'];
242 $result->closeCursor();
246 // This is a popular helper.
247 function getObjectInfo ($object_id = 0)
251 showError ('Invalid object_id', __FUNCTION__
);
255 "select id, name, label, barcode, dict_value as objtype_name, asset_no, dict_key as objtype_id, has_problems, comment from " .
256 "RackObject inner join Dictionary on objtype_id = dict_key natural join Chapter " .
257 "where id = '${object_id}' and deleted = 'no' and chapter_name = 'RackObjectType' limit 1";
258 $result = useSelectBlade ($query, __FUNCTION__
);
259 if (($row = $result->fetch (PDO
::FETCH_ASSOC
)) == NULL)
261 showError ('Query succeeded, but returned no data', __FUNCTION__
);
266 $ret['id'] = $row['id'];
267 $ret['name'] = $row['name'];
268 $ret['label'] = $row['label'];
269 $ret['barcode'] = $row['barcode'];
270 $ret['objtype_name'] = $row['objtype_name'];
271 $ret['objtype_id'] = $row['objtype_id'];
272 $ret['has_problems'] = $row['has_problems'];
273 $ret['asset_no'] = $row['asset_no'];
274 $ret['dname'] = displayedName ($ret);
275 $ret['comment'] = $row['comment'];
277 $result->closeCursor();
282 function getPortTypes ()
284 return readChapter ('PortType');
287 function getObjectPortsAndLinks ($object_id = 0)
291 showError ('Invalid object_id', __FUNCTION__
);
295 "select Port.id as Port_id, ".
296 "Port.name as Port_name, ".
297 "Port.label as Port_label, ".
298 "Port.l2address as Port_l2address, ".
299 "Port.type as Port_type, ".
300 "Port.reservation_comment as Port_reservation_comment, " .
301 "dict_value as PortType_name, ".
302 "RemotePort.id as RemotePort_id, ".
303 "RemotePort.name as RemotePort_name, ".
304 "RemotePort.object_id as RemotePort_object_id, ".
305 "RackObject.name as RackObject_name ".
309 "Port inner join Dictionary on Port.type = dict_key natural join Chapter".
311 "left join Link on Port.id=Link.porta or Port.id=Link.portb ".
313 "left join Port as RemotePort on Link.portb=RemotePort.id or Link.porta=RemotePort.id ".
315 "left join RackObject on RemotePort.object_id=RackObject.id ".
316 "where chapter_name = 'PortType' and Port.object_id=${object_id} ".
317 "and (Port.id != RemotePort.id or RemotePort.id is null) ".
318 "order by Port_name";
319 $result = useSelectBlade ($query, __FUNCTION__
);
322 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
324 $ret[$count]['id'] = $row['Port_id'];
325 $ret[$count]['name'] = $row['Port_name'];
326 $ret[$count]['l2address'] = l2addressFromDatabase ($row['Port_l2address']);
327 $ret[$count]['label'] = $row['Port_label'];
328 $ret[$count]['type_id'] = $row['Port_type'];
329 $ret[$count]['type'] = $row['PortType_name'];
330 $ret[$count]['reservation_comment'] = $row['Port_reservation_comment'];
331 $ret[$count]['remote_id'] = $row['RemotePort_id'];
332 $ret[$count]['remote_name'] = htmlentities ($row['RemotePort_name'], ENT_QUOTES
);
333 $ret[$count]['remote_object_id'] = $row['RemotePort_object_id'];
334 $ret[$count]['remote_object_name'] = $row['RackObject_name'];
335 // Save on displayedName() calls.
336 if (empty ($row['RackObject_name']) and !empty ($row['RemotePort_object_id']))
338 $oi = getObjectInfo ($row['RemotePort_object_id']);
339 $ret[$count]['remote_object_name'] = displayedName ($oi);
343 $result->closeCursor();
347 function commitAddRack ($name, $height = 0, $row_id = 0, $comment, $taglist)
349 if ($row_id <= 0 or $height <= 0 or empty ($name))
351 $result = useInsertBlade
357 'name' => "'${name}'",
359 'comment' => "'${comment}'"
364 showError ('useInsertBlade() failed', __FUNCTION__
);
367 $last_insert_id = lastInsertID();
368 return (produceTagsForLastRecord ('rack', $taglist, $last_insert_id) == '') and recordHistory ('Rack', "id = ${last_insert_id}");
371 function commitAddObject ($new_name, $new_label, $new_barcode, $new_type_id, $new_asset_no, $taglist = array())
374 // Maintain UNIQUE INDEX for common names and asset tags by
375 // filtering out empty strings (not NULLs).
376 $result1 = useInsertBlade
381 'name' => empty ($new_name) ?
'NULL' : "'${new_name}'",
382 'label' => "'${new_label}'",
383 'barcode' => empty ($new_barcode) ?
'NULL' : "'${new_barcode}'",
384 'objtype_id' => $new_type_id,
385 'asset_no' => empty ($new_asset_no) ?
'NULL' : "'${new_asset_no}'"
388 if ($result1 == NULL)
390 showError ("SQL query #1 failed", __FUNCTION__
);
393 $last_insert_id = lastInsertID();
394 // Do AutoPorts magic
395 executeAutoPorts ($last_insert_id, $new_type_id);
397 $error = produceTagsForLastRecord ('object', $taglist, $last_insert_id);
400 showError ("Error adding tags for the object: ${error}");
403 return recordHistory ('RackObject', "id = ${last_insert_id}");
406 function commitUpdateObject ($object_id = 0, $new_name = '', $new_label = '', $new_barcode = '', $new_type_id = 0, $new_has_problems = 'no', $new_asset_no = '', $new_comment = '')
408 if ($object_id == 0 ||
$new_type_id == 0)
410 showError ('Not all required args are present.', __FUNCTION__
);
414 $new_asset_no = empty ($new_asset_no) ?
'NULL' : "'${new_asset_no}'";
415 $new_barcode = empty ($new_barcode) ?
'NULL' : "'${new_barcode}'";
416 $new_name = empty ($new_name) ?
'NULL' : "'${new_name}'";
417 $query = "update RackObject set name=${new_name}, label='${new_label}', barcode=${new_barcode}, objtype_id='${new_type_id}', " .
418 "has_problems='${new_has_problems}', asset_no=${new_asset_no}, comment='${new_comment}' " .
419 "where id='${object_id}' limit 1";
420 $result = $dbxlink->query ($query);
423 showError ("SQL query '${query}' failed", __FUNCTION__
);
426 $result->closeCursor();
427 return recordHistory ('RackObject', "id = ${object_id}");
430 function commitUpdateRack ($rack_id, $new_name, $new_height, $new_row_id, $new_comment)
432 if (empty ($rack_id) ||
empty ($new_name) ||
empty ($new_height))
434 showError ('Not all required args are present.', __FUNCTION__
);
438 $query = "update Rack set name='${new_name}', height='${new_height}', comment='${new_comment}', row_id=${new_row_id} " .
439 "where id='${rack_id}' limit 1";
440 $result1 = $dbxlink->query ($query);
441 if ($result1->rowCount() != 1)
443 showError ('Error updating rack information', __FUNCTION__
);
446 return recordHistory ('Rack', "id = ${rack_id}");
449 // This function accepts rack data returned by getRackData(), validates and applies changes
450 // supplied in $_REQUEST and returns resulting array. Only those changes are examined, which
451 // correspond to current rack ID.
452 // 1st arg is rackdata, 2nd arg is unchecked state, 3rd arg is checked state.
453 // If 4th arg is present, object_id fields will be updated accordingly to the new state.
454 // The function returns the modified rack upon success.
455 function processGridForm (&$rackData, $unchecked_state, $checked_state, $object_id = 0)
457 global $loclist, $dbxlink;
458 $rack_id = $rackData['id'];
459 $rack_name = $rackData['name'];
460 $rackchanged = FALSE;
461 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
463 for ($locidx = 0; $locidx < 3; $locidx++
)
465 if ($rackData[$unit_no][$locidx]['enabled'] != TRUE)
468 $state = $rackData[$unit_no][$locidx]['state'];
469 if (isset ($_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"]) and $_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"] == 'on')
470 $newstate = $checked_state;
472 $newstate = $unchecked_state;
473 if ($state == $newstate)
477 $atom = $loclist[$locidx];
478 // The only changes allowed are those introduced by checkbox grid.
481 !($state == $checked_state && $newstate == $unchecked_state) &&
482 !($state == $unchecked_state && $newstate == $checked_state)
484 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, 'atom ${atom}', cannot change state from '${state}' to '${newstate}'");
485 // Here we avoid using ON DUPLICATE KEY UPDATE by first performing DELETE
486 // anyway and then looking for probable need of INSERT.
488 "delete from RackSpace where rack_id = ${rack_id} and " .
489 "unit_no = ${unit_no} and atom = '${atom}' limit 1";
490 $r = $dbxlink->query ($query);
492 return array ('code' => 500, 'message' => __FUNCTION__
. ": ${rack_name}: SQL DELETE query failed");
493 if ($newstate != 'F')
496 "insert into RackSpace(rack_id, unit_no, atom, state) " .
497 "values(${rack_id}, ${unit_no}, '${atom}', '${newstate}') ";
498 $r = $dbxlink->query ($query);
500 return array ('code' => 500, 'message' => __FUNCTION__
. ": ${rack_name}: SQL INSERT query failed");
502 if ($newstate == 'T' and $object_id != 0)
504 // At this point we already have a record in RackSpace.
506 "update RackSpace set object_id=${object_id} " .
507 "where rack_id=${rack_id} and unit_no=${unit_no} and atom='${atom}' limit 1";
508 $r = $dbxlink->query ($query);
509 if ($r->rowCount() == 1)
510 $rackData[$unit_no][$locidx]['object_id'] = $object_id;
512 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, atom '${atom}' failed to set object_id to '${object_id}'");
518 resetThumbCache ($rack_id);
519 return array ('code' => 200, 'message' => "${rack_name}: All changes were successfully saved.");
522 return array ('code' => 300, 'message' => "${rack_name}: No changes.");
525 // This function builds a list of rack-unit-atom records, which are assigned to
526 // the requested object.
527 function getMoleculeForObject ($object_id = 0)
531 showError ("object_id == 0", __FUNCTION__
);
535 "select rack_id, unit_no, atom from RackSpace " .
536 "where state = 'T' and object_id = ${object_id} order by rack_id, unit_no, atom";
537 $result = useSelectBlade ($query, __FUNCTION__
);
538 $ret = $result->fetchAll (PDO
::FETCH_ASSOC
);
539 $result->closeCursor();
543 // This function builds a list of rack-unit-atom records for requested molecule.
544 function getMolecule ($mid = 0)
548 showError ("mid == 0", __FUNCTION__
);
552 "select rack_id, unit_no, atom from Atom " .
553 "where molecule_id=${mid}";
554 $result = useSelectBlade ($query, __FUNCTION__
);
555 $ret = $result->fetchAll (PDO
::FETCH_ASSOC
);
556 $result->closeCursor();
560 // returns exactly what is's named after
561 function lastInsertID ()
563 if (NULL == ($result = useSelectBlade ('select last_insert_id()', __FUNCTION__
)))
565 showError ('SQL query failed!', __FUNCTION__
);
568 $row = $result->fetch (PDO
::FETCH_NUM
);
572 // This function creates a new record in Molecule and number of linked
573 // R-U-A records in Atom.
574 function createMolecule ($molData)
577 $query = "insert into Molecule values()";
578 $result1 = $dbxlink->query ($query);
579 if ($result1->rowCount() != 1)
581 showError ('Error inserting into Molecule', __FUNCTION__
);
584 $molecule_id = lastInsertID();
585 foreach ($molData as $rua)
587 $rack_id = $rua['rack_id'];
588 $unit_no = $rua['unit_no'];
589 $atom = $rua['atom'];
591 "insert into Atom(molecule_id, rack_id, unit_no, atom) " .
592 "values (${molecule_id}, ${rack_id}, ${unit_no}, '${atom}')";
593 $result3 = $dbxlink->query ($query);
594 if ($result3 == NULL or $result3->rowCount() != 1)
596 showError ('Error inserting into Atom', __FUNCTION__
);
603 // History logger. This function assumes certain table naming convention and
605 // 1. History table name equals to dictionary table name plus 'History'.
606 // 2. History table must have the same row set (w/o keys) plus one row named
607 // 'ctime' of type 'timestamp'.
608 function recordHistory ($tableName, $whereClause)
610 global $dbxlink, $remote_username;
611 $query = "insert into ${tableName}History select *, current_timestamp(), '${remote_username}' from ${tableName} where ${whereClause}";
612 $result = $dbxlink->query ($query);
613 if ($result == NULL or $result->rowCount() != 1)
615 showError ("SQL query '${query}' failed for table ${tableName}", __FUNCTION__
);
621 function getRackspaceHistory ()
624 "select mo.id as mo_id, ro.id as ro_id, ro.name, mo.ctime, mo.comment, dict_value as objtype_name, user_name from " .
625 "MountOperation as mo inner join RackObject as ro on mo.object_id = ro.id " .
626 "inner join Dictionary on objtype_id = dict_key natural join Chapter " .
627 "where chapter_name = 'RackObjectType' order by ctime desc";
628 $result = useSelectBlade ($query, __FUNCTION__
);
629 $ret = $result->fetchAll(PDO
::FETCH_ASSOC
);
630 $result->closeCursor();
634 // This function is used in renderRackspaceHistory()
635 function getOperationMolecules ($op_id = 0)
639 showError ("Missing argument", __FUNCTION__
);
642 $query = "select old_molecule_id, new_molecule_id from MountOperation where id = ${op_id}";
643 $result = useSelectBlade ($query, __FUNCTION__
);
644 // We expect one row.
645 $row = $result->fetch (PDO
::FETCH_ASSOC
);
648 showError ("SQL query succeded, but returned no results.", __FUNCTION__
);
651 $omid = $row['old_molecule_id'];
652 $nmid = $row['new_molecule_id'];
653 $result->closeCursor();
654 return array ($omid, $nmid);
657 function getResidentRacksData ($object_id = 0, $fetch_rackdata = TRUE)
661 showError ('Invalid object_id', __FUNCTION__
);
664 $query = "select distinct rack_id from RackSpace where object_id = ${object_id} order by rack_id";
665 $result = useSelectBlade ($query, __FUNCTION__
);
666 $rows = $result->fetchAll (PDO
::FETCH_NUM
);
667 $result->closeCursor();
669 foreach ($rows as $row)
671 if (!$fetch_rackdata)
673 $ret[$row[0]] = $row[0];
676 $rackData = getRackData ($row[0]);
677 if ($rackData == NULL)
679 showError ('getRackData() failed', __FUNCTION__
);
682 $ret[$row[0]] = $rackData;
684 $result->closeCursor();
688 function getObjectGroupInfo ()
691 'select dict_key as id, dict_value as name, count(id) as count from ' .
692 'Dictionary natural join Chapter left join RackObject on dict_key = objtype_id ' .
693 'where chapter_name = "RackObjectType" ' .
694 'group by dict_key order by dict_value';
695 $result = useSelectBlade ($query, __FUNCTION__
);
697 $ret[0] = array ('id' => 0, 'name' => 'ALL types');
698 $clist = array ('id', 'name', 'count');
700 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
701 if ($row['count'] > 0)
703 $total +
= $row['count'];
704 foreach ($clist as $cname)
705 $ret[$row['id']][$cname] = $row[$cname];
707 $result->closeCursor();
708 $ret[0]['count'] = $total;
712 // This function returns objects, which have no rackspace assigned to them.
713 // Additionally it keeps rack_id parameter, so we can silently pre-select
714 // the rack required.
715 function getUnmountedObjects ()
718 'select dict_value as objtype_name, dict_key as objtype_id, name, label, barcode, id, asset_no from ' .
719 'RackObject inner join Dictionary on objtype_id = dict_key natural join Chapter ' .
720 'left join RackSpace on id = object_id '.
721 'where rack_id is null and chapter_name = "RackObjectType" order by dict_value, name, label, asset_no, barcode';
722 $result = useSelectBlade ($query, __FUNCTION__
);
724 $clist = array ('id', 'name', 'label', 'barcode', 'objtype_name', 'objtype_id', 'asset_no');
725 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
727 foreach ($clist as $cname)
728 $ret[$row['id']][$cname] = $row[$cname];
729 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
731 $result->closeCursor();
735 function getProblematicObjects ()
738 'select dict_value as objtype_name, dict_key as objtype_id, name, id, asset_no from ' .
739 'RackObject inner join Dictionary on objtype_id = dict_key natural join Chapter '.
740 'where has_problems = "yes" and chapter_name = "RackObjectType" order by objtype_name, name';
741 $result = useSelectBlade ($query, __FUNCTION__
);
743 $clist = array ('id', 'name', 'objtype_name', 'objtype_id', 'asset_no');
744 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
746 foreach ($clist as $cname)
747 $ret[$row['id']][$cname] = $row[$cname];
748 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
750 $result->closeCursor();
754 function commitAddPort ($object_id = 0, $port_name, $port_type_id, $port_label, $port_l2address)
758 showError ('Invalid object_id', __FUNCTION__
);
761 $port_l2address = l2addressForDatabase ($port_l2address);
762 $result = useInsertBlade
767 'name' => "'${port_name}'",
768 'object_id' => "'${object_id}'",
769 'label' => "'${port_label}'",
770 'type' => "'${port_type_id}'",
771 'l2address' => "${port_l2address}"
777 return 'SQL query failed';
780 // The fifth argument may be either explicit 'NULL' or some (already quoted by the upper layer)
781 // string value. In case it is omitted, we just assign it its current value.
782 // It would be nice to simplify this semantics later.
783 function commitUpdatePort ($port_id, $port_name, $port_label, $port_l2address, $port_reservation_comment = 'reservation_comment')
786 $port_l2address = l2addressForDatabase ($port_l2address);
788 "update Port set name='$port_name', label='$port_label', " .
789 "reservation_comment = ${port_reservation_comment}, l2address=${port_l2address} " .
790 "where id='$port_id'";
791 $result = $dbxlink->exec ($query);
794 $errorInfo = $dbxlink->errorInfo();
795 // We could update nothing.
796 if ($errorInfo[0] == '00000')
798 return $errorInfo[2];
801 function delObjectPort ($port_id)
803 if (unlinkPort ($port_id) != '')
804 return __FUNCTION__
. ': unlinkPort() failed';
805 if (useDeleteBlade ('Port', 'id', $port_id) != TRUE)
806 return __FUNCTION__
. ': useDeleteBlade() failed';
810 function getAllIPv4Allocations ()
813 "select object_id as object_id, ".
814 "RackObject.name as object_name, ".
815 "IPBonds.name as name, ".
816 "INET_NTOA(ip) as ip ".
817 "from IPBonds join RackObject on id=object_id ";
818 $result = useSelectBlade ($query, __FUNCTION__
);
821 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
823 $ret[$count]['object_id']=$row['object_id'];
824 $ret[$count]['object_name']=$row['object_name'];
825 $ret[$count]['name']=$row['name'];
826 $ret[$count]['ip']=$row['ip'];
829 $result->closeCursor();
833 function getEmptyPortsOfType ($type_id)
836 "select distinct Port.id as Port_id, ".
837 "Port.object_id as Port_object_id, ".
838 "RackObject.name as Object_name, ".
839 "Port.name as Port_name, ".
840 "Port.type as Port_type_id, ".
841 "dict_value as Port_type_name ".
844 " Port inner join Dictionary on Port.type = dict_key natural join Chapter ".
846 " join RackObject on Port.object_id = RackObject.id ".
848 "left join Link on Port.id=Link.porta or Port.id=Link.portb ".
849 "inner join PortCompat on Port.type = PortCompat.type2 ".
850 "where chapter_name = 'PortType' and PortCompat.type1 = '$type_id' and Link.porta is NULL ".
851 "and Port.reservation_comment is null order by Object_name, Port_name";
852 $result = useSelectBlade ($query, __FUNCTION__
);
855 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
857 $ret[$count]['Port_id']=$row['Port_id'];
858 $ret[$count]['Port_object_id']=$row['Port_object_id'];
859 $ret[$count]['Object_name']=$row['Object_name'];
860 $ret[$count]['Port_name']=$row['Port_name'];
861 $ret[$count]['Port_type_id']=$row['Port_type_id'];
862 $ret[$count]['Port_type_name']=$row['Port_type_name'];
865 $result->closeCursor();
869 function linkPorts ($porta, $portb)
871 if ($porta == $portb)
872 return "Ports can't be the same";
880 $query1 = "insert into Link set porta='${porta}', portb='{$portb}'";
881 $query2 = "update Port set reservation_comment = NULL where id = ${porta} or id = ${portb} limit 2";
882 // FIXME: who cares about the return value?
883 $result = $dbxlink->exec ($query1);
884 $result = $dbxlink->exec ($query2);
888 function unlinkPort ($port)
892 "delete from Link where porta='$port' or portb='$port'";
893 $result = $dbxlink->exec ($query);
897 // Return all IPv4 addresses allocated to the objects. Attach detailed
898 // info about address to each alocation records. Index result by dotted-quad
900 function getObjectIPv4Allocations ($object_id = 0)
903 $query = 'select name as osif, type, inet_ntoa(ip) as dottedquad from IPBonds ' .
904 "where object_id = ${object_id} " .
906 $result = useSelectBlade ($query, __FUNCTION__
);
907 // don't spawn a sub-query with unfetched buffer, it may fail
908 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
909 $ret[$row['dottedquad']] = array ('osif' => $row['osif'], 'type' => $row['type']);
911 foreach (array_keys ($ret) as $dottedquad)
912 $ret[$dottedquad]['addrinfo'] = getIPv4Address ($dottedquad);
916 // Return minimal IPv4 address, optionally with "ip" key set, if requested.
917 function constructIPv4Address ($dottedquad = NULL)
929 if ($dottedquad != NULL)
930 $ret['ip'] = $dottedquad;
934 // Check the range requested for meaningful IPv4 records, build them
935 // into a list and return. Return an empty list if nothing matched.
936 // Both arguments are expected in signed int32 form. The resulting list
937 // is keyed by uint32 form of each IP address, items aren't sorted.
938 function scanIPv4Space ($i32_first, $i32_last)
941 $dnamechache = array();
943 $db_first = sprintf ('%u', 0x00000000 +
$i32_first);
944 $db_last = sprintf ('%u', 0x00000000 +
$i32_last);
945 // 1. collect labels and reservations
946 $query = "select INET_NTOA(ip) as ip, name, reserved from IPAddress ".
947 "where ip between ${db_first} and ${db_last} and (reserved = 'yes' or name != '')";
948 $result = useSelectBlade ($query, __FUNCTION__
);
949 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
951 $ip_bin = ip2long ($row['ip']);
952 if (!isset ($ret[$ip_bin]))
953 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
954 $ret[$ip_bin]['name'] = $row['name'];
955 $ret[$ip_bin]['reserved'] = $row['reserved'];
959 // 2. check for allocations
961 "select INET_NTOA(ipb.ip) as ip, ro.id as object_id, " .
962 "ro.name as object_name, ipb.name, ipb.type, objtype_id, " .
963 "dict_value as objtype_name from " .
964 "IPBonds as ipb inner join RackObject as ro on ipb.object_id = ro.id " .
965 "left join Dictionary on objtype_id=dict_key natural join Chapter " .
966 "where ip between ${db_first} and ${db_last} " .
967 "and chapter_name = 'RackObjectType'" .
968 "order by ipb.type, object_name";
969 $result = useSelectBlade ($query, __FUNCTION__
);
970 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
972 $ip_bin = ip2long ($row['ip']);
973 if (!isset ($ret[$ip_bin]))
974 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
975 if (!isset ($dnamecache[$row['object_id']]))
977 $quasiobject['name'] = $row['object_name'];
978 $quasiobject['objtype_id'] = $row['objtype_id'];
979 $quasiobject['objtype_name'] = $row['objtype_name'];
980 $dnamecache[$row['object_id']] = displayedName ($quasiobject);
983 foreach (array ('object_id', 'type', 'name') as $cname)
984 $tmp[$cname] = $row[$cname];
985 $tmp['object_name'] = $dnamecache[$row['object_id']];
986 $ret[$ip_bin]['allocs'][] = $tmp;
990 // 3. look for virtual services and related LB
991 $query = "select vs_id, inet_ntoa(vip) as ip, vport, proto, vs.name, " .
992 "object_id, objtype_id, ro.name as object_name, dict_value as objtype_name from " .
993 "IPVirtualService as vs inner join IPLoadBalancer as lb on vs.id = lb.vs_id " .
994 "inner join RackObject as ro on lb.object_id = ro.id " .
995 "left join Dictionary on objtype_id=dict_key " .
996 "natural join Chapter " .
997 "where vip between ${db_first} and ${db_last} " .
998 "and chapter_name = 'RackObjectType'" .
999 "order by vport, proto, ro.name, object_id";
1000 $result = useSelectBlade ($query, __FUNCTION__
);
1001 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1003 $ip_bin = ip2long ($row['ip']);
1004 if (!isset ($ret[$ip_bin]))
1005 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1006 if (!isset ($dnamecache[$row['object_id']]))
1008 $quasiobject['name'] = $row['object_name'];
1009 $quasiobject['objtype_id'] = $row['objtype_id'];
1010 $quasiobject['objtype_name'] = $row['objtype_name'];
1011 $dnamecache[$row['object_id']] = displayedName ($quasiobject);
1014 foreach (array ('object_id', 'vport', 'proto', 'vs_id', 'name') as $cname)
1015 $tmp[$cname] = $row[$cname];
1016 $tmp['object_name'] = $dnamecache[$row['object_id']];
1017 $tmp['vip'] = $row['ip'];
1018 $ret[$ip_bin]['lblist'][] = $tmp;
1022 // 4. don't forget about real servers along with pools
1023 $query = "select inet_ntoa(rsip) as ip, inservice, rsport, rspool_id, rsp.name as rspool_name from " .
1024 "IPRealServer as rs inner join IPRSPool as rsp on rs.rspool_id = rsp.id " .
1025 "where rsip between ${db_first} and ${db_last} " .
1026 "order by ip, rsport, rspool_id";
1027 $result = useSelectBlade ($query, __FUNCTION__
);
1028 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1030 $ip_bin = ip2long ($row['ip']);
1031 if (!isset ($ret[$ip_bin]))
1032 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1034 foreach (array ('rspool_id', 'rsport', 'rspool_name', 'inservice') as $cname)
1035 $tmp[$cname] = $row[$cname];
1036 $ret[$ip_bin]['rslist'][] = $tmp;
1040 // 5. add NAT rules, part 1
1044 "INET_NTOA(localip) as localip, " .
1046 "INET_NTOA(remoteip) as remoteip, " .
1049 "from PortForwarding " .
1050 "where remoteip between ${db_first} and ${db_last} or " .
1051 "localip between ${db_first} and ${db_last} " .
1052 "order by localip, localport, remoteip, remoteport, proto";
1053 $result = useSelectBlade ($query, __FUNCTION__
);
1054 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1056 $remoteip_bin = ip2long ($row['remoteip']);
1057 $localip_bin = ip2long ($row['localip']);
1058 if ($i32_first <= $remoteip_bin and $remoteip_bin <= $i32_last)
1060 if (!isset ($ret[$remoteip_bin]))
1061 $ret[$remoteip_bin] = constructIPv4Address ($row['remoteip']);
1062 $ret[$remoteip_bin]['inpf'][] = $row;
1064 if ($i32_first <= $localip_bin and $localip_bin <= $i32_last)
1066 if (!isset ($ret[$localip_bin]))
1067 $ret[$localip_bin] = constructIPv4Address ($row['localip']);
1068 $ret[$localip_bin]['outpf'][] = $row;
1074 // Return summary data about an IPv4 prefix, if it exists, or NULL otherwise.
1075 function getIPv4NetworkInfo ($id = 0)
1079 showError ('Invalid arg', __FUNCTION__
);
1082 $query = "select INET_NTOA(ip) as ip, mask, name ".
1083 "from IPRanges where id = $id";
1084 $result = useSelectBlade ($query, __FUNCTION__
);
1085 $ret = $result->fetch (PDO
::FETCH_ASSOC
);
1090 $ret['ip_bin'] = ip2long ($ret['ip']);
1091 $ret['mask_bin'] = binMaskFromDec ($ret['mask']);
1092 $ret['mask_bin_inv'] = binInvMaskFromDec ($ret['mask']);
1093 $ret['db_first'] = sprintf ('%u', 0x00000000 +
$ret['ip_bin'] & $ret['mask_bin']);
1094 $ret['db_last'] = sprintf ('%u', 0x00000000 +
$ret['ip_bin'] |
($ret['mask_bin_inv']));
1098 function getIPv4Network ($id = 0)
1100 $ret = getIPv4NetworkInfo ($id);
1103 showError ('Record not found', __FUNCTION__
);
1106 $ret['addrlist'] = scanIPv4Space ($ret['db_first'], $ret['db_last']);
1107 markupIPv4AddrList ($ret['addrlist']);
1111 function getIPv4Address ($dottedquad = '')
1113 if ($dottedquad == '')
1115 showError ('Invalid arg', __FUNCTION__
);
1118 $i32 = ip2long ($dottedquad); // signed 32 bit
1119 $scanres = scanIPv4Space ($i32, $i32);
1120 if (!isset ($scanres[$i32]))
1121 return constructIPv4Address ($dottedquad);
1122 markupIPv4AddrList ($scanres);
1123 return $scanres[$i32];
1126 function bindIpToObject ($ip = '', $object_id = 0, $name = '', $type = '')
1128 $result = useInsertBlade
1133 'ip' => "INET_ATON('$ip')",
1134 'object_id' => "'${object_id}'",
1135 'name' => "'${name}'",
1136 'type' => "'${type}'"
1139 return $result ?
'' : (__FUNCTION__
. '(): useInsertBlade() failed');
1142 function getAddressspaceList ($tagfilter = array(), $tfmode = 'any')
1144 $whereclause = getWhereClause ($tagfilter);
1147 "id as IPRanges_id, ".
1148 "INET_NTOA(ip) as IPRanges_ip, ".
1149 "mask as IPRanges_mask, ".
1150 "name as IPRanges_name ".
1151 "from IPRanges left join TagStorage on IPRanges.id = TagStorage.target_id and target_realm = 'ipv4net' " .
1152 "where true ${whereclause} " .
1154 $result = useSelectBlade ($query, __FUNCTION__
);
1157 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1159 $ret[$count]['id'] = $row['IPRanges_id'];
1160 $ret[$count]['ip'] = $row['IPRanges_ip'];
1161 $ret[$count]['ip_bin'] = ip2long($row['IPRanges_ip']);
1162 $ret[$count]['name'] = $row['IPRanges_name'];
1163 $ret[$count]['mask'] = $row['IPRanges_mask'];
1164 $ret[$count]['mask_bin'] = binMaskFromDec($row['IPRanges_mask']);
1165 $ret[$count]['mask_bin_inv'] = binInvMaskFromDec($row['IPRanges_mask']);
1168 $result->closeCursor();
1173 // Return the id of the smallest IPv4 network containing the given IPv4 address
1174 // or NULL, if nothing was found.
1175 function getIPv4AddressNetworkId ($dottedquad)
1177 $query = 'select id from IPRanges where ' .
1178 "inet_aton('${dottedquad}') & (4294967295 >> (32 - mask)) << (32 - mask) = ip " .
1179 'order by mask desc limit 1';
1180 $result = useSelectBlade ($query, __FUNCTION__
);
1181 if ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1186 function updateRange ($id=0, $name='')
1190 "update IPRanges set name='$name' where id='$id'";
1191 $result = $dbxlink->exec ($query);
1195 // This function is actually used not only to update, but also to create records,
1196 // that's why ON DUPLICATE KEY UPDATE was replaced by DELETE-INSERT pair
1197 // (MySQL 4.0 workaround).
1198 function updateAddress ($ip = 0, $name = '', $reserved = 'no')
1200 // DELETE may safely fail.
1201 $r = useDeleteBlade ('IPAddress', 'ip', "INET_ATON('${ip}')");
1202 // INSERT may appear not necessary.
1203 if ($name == '' and $reserved == 'no')
1205 if (useInsertBlade ('IPAddress', array ('name' => "'${name}'", 'reserved' => "'${reserved}'", 'ip' => "INET_ATON('${ip}')")))
1208 return __FUNCTION__
. '(): useInsertBlade() failed';
1211 function updateBond ($ip='', $object_id=0, $name='', $type='')
1216 "update IPBonds set name='$name', type='$type' where ip=INET_ATON('$ip') and object_id='$object_id'";
1217 $result = $dbxlink->exec ($query);
1221 function unbindIpFromObject ($ip='', $object_id=0)
1226 "delete from IPBonds where ip=INET_ATON('$ip') and object_id='$object_id'";
1227 $result = $dbxlink->exec ($query);
1231 // This function returns either all or one user account. Array key is user name.
1232 function getUserAccounts ($tagfilter = array(), $tfmode = 'any')
1234 $whereclause = getWhereClause ($tagfilter);
1236 'select user_id, user_name, user_password_hash, user_realname, user_enabled ' .
1237 'from UserAccount left join TagStorage ' .
1238 "on UserAccount.user_id = TagStorage.target_id and target_realm = 'user' " .
1239 "where true ${whereclause} " .
1240 'order by user_name';
1241 $result = useSelectBlade ($query, __FUNCTION__
);
1243 $clist = array ('user_id', 'user_name', 'user_realname', 'user_password_hash', 'user_enabled');
1244 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1245 foreach ($clist as $cname)
1246 $ret[$row['user_name']][$cname] = $row[$cname];
1247 $result->closeCursor();
1251 function searchByl2address ($l2addr)
1253 $l2addr = l2addressForDatabase ($l2addr);
1254 $query = "select object_id, Port.id as port_id from RackObject as ro inner join Port on ro.id = Port.object_id " .
1255 "where l2address = ${l2addr}";
1256 $result = useSelectBlade ($query, __FUNCTION__
);
1257 $rows = $result->fetchAll (PDO
::FETCH_ASSOC
);
1258 $result->closeCursor();
1259 if (count ($rows) == 0) // No results.
1261 if (count ($rows) == 1) // Target found.
1263 showError ('More than one results was found. This is probably a broken unique key.', __FUNCTION__
);
1267 function getIPv4PrefixSearchResult ($terms)
1269 $query = "select id, inet_ntoa(ip) as ip, mask, name from IPRanges where ";
1271 foreach (explode (' ', $terms) as $term)
1273 $query .= $or . "name like '%${term}%'";
1276 $result = useSelectBlade ($query, __FUNCTION__
);
1278 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1283 function getIPv4AddressSearchResult ($terms)
1285 $query = "select inet_ntoa(ip) as ip, name from IPAddress where ";
1287 foreach (explode (' ', $terms) as $term)
1289 $query .= $or . "name like '%${term}%'";
1292 $result = useSelectBlade ($query, __FUNCTION__
);
1294 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1299 function getIPv4RSPoolSearchResult ($terms)
1301 $query = "select id as pool_id, name from IPRSPool where ";
1303 foreach (explode (' ', $terms) as $term)
1305 $query .= $or . "name like '%${term}%'";
1308 $result = useSelectBlade ($query, __FUNCTION__
);
1310 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1315 function getIPv4VServiceSearchResult ($terms)
1317 $query = "select id, inet_ntoa(vip) as vip, vport, proto, name from IPVirtualService where ";
1319 foreach (explode (' ', $terms) as $term)
1321 $query .= $or . "name like '%${term}%'";
1324 $result = useSelectBlade ($query, __FUNCTION__
);
1326 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1331 function getAccountSearchResult ($terms)
1333 return getSearchResultByField
1336 array ('user_id', 'user_name', 'user_realname'),
1343 function getSearchResultByField ($tname, $rcolumns, $scolumn, $terms, $ocolumn = '')
1347 foreach ($rcolumns as $col)
1349 $query .= $pfx . $col;
1353 $query .= " from ${tname} where ";
1354 foreach (explode (' ', $terms) as $term)
1356 $query .= $pfx . "${scolumn} like '%${term}%'";
1360 $query .= " order by ${ocolumn}";
1361 $result = useSelectBlade ($query, __FUNCTION__
);
1363 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1368 // This function returns either port ID or NULL for specified arguments.
1369 function getPortID ($object_id, $port_name)
1371 $query = "select id from Port where object_id=${object_id} and name='${port_name}' limit 2";
1372 $result = useSelectBlade ($query, __FUNCTION__
);
1373 $rows = $result->fetchAll (PDO
::FETCH_NUM
);
1374 if (count ($rows) != 1)
1377 $result->closeCursor();
1381 function commitCreateUserAccount ($username, $realname, $password)
1383 return useInsertBlade
1388 'user_name' => "'${username}'",
1389 'user_realname' => "'${realname}'",
1390 'user_password_hash' => "'${password}'"
1395 function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
1399 "update UserAccount set user_name = '${new_username}', user_realname = '${new_realname}', " .
1400 "user_password_hash = '${new_password}' where user_id = ${id} limit 1";
1401 $result = $dbxlink->query ($query);
1402 if ($result == NULL)
1404 showError ('SQL query failed', __FUNCTION__
);
1410 function commitEnableUserAccount ($id, $new_enabled_value)
1414 "update UserAccount set user_enabled = '${new_enabled_value}' " .
1415 "where user_id = ${id} limit 1";
1416 $result = $dbxlink->query ($query);
1417 if ($result == NULL)
1419 showError ('SQL query failed', __FUNCTION__
);
1425 // This function returns an array of all port type pairs from PortCompat table.
1426 function getPortCompat ()
1429 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
1430 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
1431 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
1432 "inner join Chapter as c1 on d1.chapter_no = c1.chapter_no " .
1433 "inner join Chapter as c2 on d2.chapter_no = c2.chapter_no " .
1434 "where c1.chapter_name = 'PortType' and c2.chapter_name = 'PortType'";
1435 $result = useSelectBlade ($query, __FUNCTION__
);
1436 $ret = $result->fetchAll (PDO
::FETCH_ASSOC
);
1437 $result->closeCursor();
1441 function removePortCompat ($type1 = 0, $type2 = 0)
1444 if ($type1 == 0 or $type2 == 0)
1446 showError ('Invalid arguments', __FUNCTION__
);
1449 $query = "delete from PortCompat where type1 = ${type1} and type2 = ${type2} limit 1";
1450 $result = $dbxlink->query ($query);
1451 if ($result == NULL)
1453 showError ('SQL query failed', __FUNCTION__
);
1459 function addPortCompat ($type1 = 0, $type2 = 0)
1461 if ($type1 <= 0 or $type2 <= 0)
1463 showError ('Invalid arguments', __FUNCTION__
);
1466 return useInsertBlade
1469 array ('type1' => $type1, 'type2' => $type2)
1473 // This function returns the dictionary as an array of trees, each tree
1474 // representing a single chapter. Each element has 'id', 'name', 'sticky'
1475 // and 'word' keys with the latter holding all the words within the chapter.
1476 function getDict ($parse_links = FALSE)
1479 "select chapter_name, Chapter.chapter_no, dict_key, dict_value, sticky from " .
1480 "Chapter natural left join Dictionary order by chapter_name, dict_value";
1481 $result = useSelectBlade ($query1, __FUNCTION__
);
1483 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1485 $chapter_no = $row['chapter_no'];
1486 if (!isset ($dict[$chapter_no]))
1488 $dict[$chapter_no]['no'] = $chapter_no;
1489 $dict[$chapter_no]['name'] = $row['chapter_name'];
1490 $dict[$chapter_no]['sticky'] = $row['sticky'] == 'yes' ?
TRUE : FALSE;
1491 $dict[$chapter_no]['word'] = array();
1493 if ($row['dict_key'] != NULL)
1495 $dict[$chapter_no]['word'][$row['dict_key']] = $parse_links ?
1496 parseWikiLink ($row['dict_value'], 'a') : $row['dict_value'];
1497 $dict[$chapter_no]['refcnt'][$row['dict_key']] = 0;
1500 $result->closeCursor();
1502 // Find the list of all assigned values of dictionary-addressed attributes, each with
1503 // chapter/word keyed reference counters. Use the structure to adjust reference counters
1504 // of the returned disctionary words.
1505 $query2 = "select a.attr_id, am.chapter_no, uint_value, count(object_id) as refcnt " .
1506 "from Attribute as a inner join AttributeMap as am on a.attr_id = am.attr_id " .
1507 "inner join AttributeValue as av on a.attr_id = av.attr_id " .
1508 "inner join Dictionary as d on am.chapter_no = d.chapter_no and av.uint_value = d.dict_key " .
1509 "where attr_type = 'dict' group by a.attr_id, am.chapter_no, uint_value " .
1510 "order by a.attr_id, am.chapter_no, uint_value";
1511 $result = useSelectBlade ($query2, __FUNCTION__
);
1512 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1513 $dict[$row['chapter_no']]['refcnt'][$row['uint_value']] = $row['refcnt'];
1514 $result->closeCursor();
1518 function getDictStats ()
1520 $stock_chapters = array (1, 2, 3, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23);
1522 "select Chapter.chapter_no, chapter_name, count(dict_key) as wc from " .
1523 "Chapter natural left join Dictionary group by Chapter.chapter_no";
1524 $result = useSelectBlade ($query, __FUNCTION__
);
1525 $tc = $tw = $uc = $uw = 0;
1526 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1530 if (in_array ($row['chapter_no'], $stock_chapters))
1535 $result->closeCursor();
1537 $query = "select count(attr_id) as attrc from RackObject as ro left join " .
1538 "AttributeValue as av on ro.id = av.object_id group by ro.id";
1539 $result = useSelectBlade ($query, __FUNCTION__
);
1540 $to = $ta = $so = 0;
1541 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1544 if ($row['attrc'] != 0)
1547 $ta +
= $row['attrc'];
1550 $result->closeCursor();
1552 $ret['Total chapters in dictionary'] = $tc;
1553 $ret['Total words in dictionary'] = $tw;
1554 $ret['User chapters'] = $uc;
1555 $ret['Words in user chapters'] = $uw;
1556 $ret['Total objects'] = $to;
1557 $ret['Objects with stickers'] = $so;
1558 $ret['Total stickers attached'] = $ta;
1562 function getIPv4Stats()
1566 $subject[] = array ('q' => 'select count(id) from IPRanges', 'txt' => 'Networks');
1567 $subject[] = array ('q' => 'select count(ip) from IPAddress', 'txt' => 'Addresses commented/reserved');
1568 $subject[] = array ('q' => 'select count(ip) from IPBonds', 'txt' => 'Addresses allocated');
1569 $subject[] = array ('q' => 'select count(*) from PortForwarding', 'txt' => 'NAT rules');
1570 $subject[] = array ('q' => 'select count(id) from IPVirtualService', 'txt' => 'Virtual services');
1571 $subject[] = array ('q' => 'select count(id) from IPRSPool', 'txt' => 'Real server pools');
1572 $subject[] = array ('q' => 'select count(id) from IPRealServer', 'txt' => 'Real servers');
1573 $subject[] = array ('q' => 'select count(distinct object_id) from IPLoadBalancer', 'txt' => 'Load balancers');
1575 foreach ($subject as $item)
1577 $result = useSelectBlade ($item['q'], __FUNCTION__
);
1578 $row = $result->fetch (PDO
::FETCH_NUM
);
1579 $ret[$item['txt']] = $row[0];
1580 $result->closeCursor();
1586 function getRackspaceStats()
1590 $subject[] = array ('q' => 'select count(*) from Dictionary where chapter_no = 3', 'txt' => 'Rack rows');
1591 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
1592 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
1593 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
1595 foreach ($subject as $item)
1597 $result = useSelectBlade ($item['q'], __FUNCTION__
);
1598 $row = $result->fetch (PDO
::FETCH_NUM
);
1599 $ret[$item['txt']] = empty ($row[0]) ?
0 : $row[0];
1600 $result->closeCursor();
1606 function getTagStats ()
1609 $query = "select tag, count(tag_id) as refcnt from " .
1610 "TagTree inner join TagStorage on TagTree.id = TagStorage.tag_id " .
1611 "group by tag_id order by refcnt desc";
1612 $result = useSelectBlade ($query, __FUNCTION__
);
1613 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1614 $ret[$row['tag']] = $row['refcnt'];
1615 $result->closeCursor();
1619 function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1621 if ($chapter_no <= 0 or $dict_key <= 0 or empty ($dict_value))
1623 showError ('Invalid args', __FUNCTION__
);
1628 "update Dictionary set dict_value = '${dict_value}' where chapter_no=${chapter_no} " .
1629 "and dict_key=${dict_key} limit 1";
1630 $result = $dbxlink->query ($query);
1631 if ($result == NULL)
1633 showError ('SQL query failed', __FUNCTION__
);
1639 function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1641 if ($chapter_no <= 0 or empty ($dict_value))
1643 showError ('Invalid args', __FUNCTION__
);
1646 return useInsertBlade
1649 array ('chapter_no' => $chapter_no, 'dict_value' => "'${dict_value}'")
1653 function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1655 if ($chapter_no <= 0 or $dict_key <= 0)
1657 showError ('Invalid args', __FUNCTION__
);
1662 "delete from Dictionary where chapter_no=${chapter_no} " .
1663 "and dict_key=${dict_key} limit 1";
1664 $result = $dbxlink->query ($query);
1665 if ($result == NULL)
1667 showError ('SQL query failed', __FUNCTION__
);
1673 function commitAddChapter ($chapter_name = '')
1675 if (empty ($chapter_name))
1677 showError ('Invalid args', __FUNCTION__
);
1680 return useInsertBlade
1683 array ('chapter_name' => "'${chapter_name}'")
1687 function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
1689 if ($chapter_no <= 0 or empty ($chapter_name))
1691 showError ('Invalid args', __FUNCTION__
);
1696 "update Chapter set chapter_name = '${chapter_name}' where chapter_no = ${chapter_no} " .
1697 "and sticky = 'no' limit 1";
1698 $result = $dbxlink->query ($query);
1699 if ($result == NULL)
1701 showError ('SQL query failed', __FUNCTION__
);
1707 function commitDeleteChapter ($chapter_no = 0)
1709 if ($chapter_no <= 0)
1711 showError ('Invalid args', __FUNCTION__
);
1716 "delete from Chapter where chapter_no = ${chapter_no} and sticky = 'no' limit 1";
1717 $result = $dbxlink->query ($query);
1718 if ($result == NULL)
1720 showError ('SQL query failed', __FUNCTION__
);
1726 // This is a dictionary accessor. We perform link rendering, so the user sees
1727 // nice <select> drop-downs.
1728 function readChapter ($chapter_name = '')
1730 if (empty ($chapter_name))
1732 showError ('invalid argument', __FUNCTION__
);
1736 "select dict_key, dict_value from Dictionary natural join Chapter " .
1737 "where chapter_name = '${chapter_name}'";
1738 $result = useSelectBlade ($query, __FUNCTION__
);
1740 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1741 $chapter[$row['dict_key']] = parseWikiLink ($row['dict_value'], 'o');
1742 $result->closeCursor();
1743 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
1748 function getAttrMap ()
1751 "select a.attr_id, a.attr_type, a.attr_name, am.objtype_id, " .
1752 "d.dict_value as objtype_name, am.chapter_no, c2.chapter_name from " .
1753 "Attribute as a natural left join AttributeMap as am " .
1754 "left join Dictionary as d on am.objtype_id = d.dict_key " .
1755 "left join Chapter as c1 on d.chapter_no = c1.chapter_no " .
1756 "left join Chapter as c2 on am.chapter_no = c2.chapter_no " .
1757 "where c1.chapter_name = 'RackObjectType' or c1.chapter_name is null " .
1758 "order by attr_name";
1759 $result = useSelectBlade ($query, __FUNCTION__
);
1761 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1763 $attr_id = $row['attr_id'];
1764 if (!isset ($ret[$attr_id]))
1766 $ret[$attr_id]['id'] = $attr_id;
1767 $ret[$attr_id]['type'] = $row['attr_type'];
1768 $ret[$attr_id]['name'] = $row['attr_name'];
1769 $ret[$attr_id]['application'] = array();
1771 if ($row['objtype_id'] == '')
1773 $application['objtype_id'] = $row['objtype_id'];
1774 $application['objtype_name'] = $row['objtype_name'];
1775 if ($row['attr_type'] == 'dict')
1777 $application['chapter_no'] = $row['chapter_no'];
1778 $application['chapter_name'] = $row['chapter_name'];
1780 $ret[$attr_id]['application'][] = $application;
1782 $result->closeCursor();
1786 function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
1788 if ($attr_id <= 0 or empty ($attr_name))
1790 showError ('Invalid args', __FUNCTION__
);
1795 "update Attribute set attr_name = '${attr_name}' " .
1796 "where attr_id = ${attr_id} limit 1";
1797 $result = $dbxlink->query ($query);
1798 if ($result == NULL)
1800 showError ("SQL query '${query}' failed", __FUNCTION__
);
1806 function commitAddAttribute ($attr_name = '', $attr_type = '')
1808 if (empty ($attr_name))
1810 showError ('Invalid args', __FUNCTION__
);
1821 showError ('Invalid args', __FUNCTION__
);
1824 return useInsertBlade
1827 array ('attr_name' => "'${attr_name}'", 'attr_type' => "'${attr_type}'")
1831 function commitDeleteAttribute ($attr_id = 0)
1835 showError ('Invalid args', __FUNCTION__
);
1838 return useDeleteBlade ('Attribute', 'attr_id', $attr_id);
1841 // FIXME: don't store garbage in chapter_no for non-dictionary types.
1842 function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
1844 if ($attr_id <= 0 or $objtype_id <= 0 or $chapter_no <= 0)
1846 showError ('Invalid args', __FUNCTION__
);
1849 return useInsertBlade
1854 'attr_id' => $attr_id,
1855 'objtype_id' => $objtype_id,
1856 'chapter_no' => $chapter_no
1861 function commitReduceAttrMap ($attr_id = 0, $objtype_id)
1863 if ($attr_id <= 0 or $objtype_id <= 0)
1865 showError ('Invalid args', __FUNCTION__
);
1870 "delete from AttributeMap where attr_id=${attr_id} " .
1871 "and objtype_id=${objtype_id} limit 1";
1872 $result = $dbxlink->query ($query);
1873 if ($result == NULL)
1875 showError ('SQL query failed', __FUNCTION__
);
1881 // This function returns all optional attributes for requested object
1882 // as an array of records. NULL is returned on error and empty array
1883 // is returned, if there are no attributes found.
1884 function getAttrValues ($object_id, $strip_optgroup = FALSE)
1886 if ($object_id <= 0)
1888 showError ('Invalid argument', __FUNCTION__
);
1893 "select A.attr_id, A.attr_name, A.attr_type, C.chapter_name, " .
1894 "AV.uint_value, AV.float_value, AV.string_value, D.dict_value from " .
1895 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
1896 "inner join Attribute as A using (attr_id) " .
1897 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
1898 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_no = D.chapter_no " .
1899 "left join Chapter as C on AM.chapter_no = C.chapter_no " .
1900 "where RO.id = ${object_id} order by A.attr_type, A.attr_name";
1901 $result = useSelectBlade ($query, __FUNCTION__
);
1902 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
1905 $record['id'] = $row['attr_id'];
1906 $record['name'] = $row['attr_name'];
1907 $record['type'] = $row['attr_type'];
1908 switch ($row['attr_type'])
1913 $record['value'] = $row[$row['attr_type'] . '_value'];
1914 $record['a_value'] = parseWikiLink ($record['value'], 'a');
1917 $record['value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'o', $strip_optgroup);
1918 $record['a_value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'a', $strip_optgroup);
1919 $record['chapter_name'] = $row['chapter_name'];
1920 $record['key'] = $row['uint_value'];
1923 $record['value'] = NULL;
1926 $ret[$row['attr_id']] = $record;
1928 $result->closeCursor();
1932 function commitResetAttrValue ($object_id = 0, $attr_id = 0)
1934 if ($object_id <= 0 or $attr_id <= 0)
1936 showError ('Invalid arguments', __FUNCTION__
);
1940 $query = "delete from AttributeValue where object_id = ${object_id} and attr_id = ${attr_id} limit 1";
1941 $result = $dbxlink->query ($query);
1942 if ($result == NULL)
1944 showError ('SQL query failed', __FUNCTION__
);
1950 // FIXME: don't share common code with use commitResetAttrValue()
1951 function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
1953 if ($object_id <= 0 or $attr_id <= 0)
1955 showError ('Invalid arguments', __FUNCTION__
);
1959 return commitResetAttrValue ($object_id, $attr_id);
1961 $query1 = "select attr_type from Attribute where attr_id = ${attr_id}";
1962 $result = $dbxlink->query ($query1);
1963 if ($result == NULL)
1965 showError ('SQL query #1 failed', __FUNCTION__
);
1968 $row = $result->fetch (PDO
::FETCH_NUM
);
1971 showError ('SQL query #1 returned no results', __FUNCTION__
);
1974 $attr_type = $row[0];
1975 $result->closeCursor();
1981 $column = $attr_type . '_value';
1984 $column = 'uint_value';
1987 showError ("Unknown attribute type '${attr_type}' met", __FUNCTION__
);
1991 "delete from AttributeValue where " .
1992 "object_id = ${object_id} and attr_id = ${attr_id} limit 1";
1993 $result = $dbxlink->query ($query2);
1994 if ($result == NULL)
1996 showError ('SQL query #2 failed', __FUNCTION__
);
1999 // We know $value isn't empty here.
2001 "insert into AttributeValue set ${column} = '${value}', " .
2002 "object_id = ${object_id}, attr_id = ${attr_id} ";
2003 $result = $dbxlink->query ($query3);
2004 if ($result == NULL)
2006 showError ('SQL query #3 failed', __FUNCTION__
);
2012 function commitUseupPort ($port_id = 0)
2016 showError ("Invalid argument", __FUNCTION__
);
2020 $query = "update Port set reservation_comment = NULL where id = ${port_id} limit 1";
2021 $result = $dbxlink->exec ($query);
2022 if ($result == NULL)
2024 showError ("SQL query failed", __FUNCTION__
);
2031 // This is a swiss-knife blade to insert a record into a table.
2032 // The first argument is table name.
2033 // The second argument is an array of "name" => "value" pairs.
2034 // The function returns either TRUE or FALSE (we expect one row
2036 function useInsertBlade ($tablename, $values)
2039 $namelist = $valuelist = '';
2040 foreach ($values as $name => $value)
2042 $namelist = $namelist . ($namelist == '' ?
"(${name}" : ", ${name}");
2043 $valuelist = $valuelist . ($valuelist == '' ?
"(${value}" : ", ${value}");
2045 $query = "insert into ${tablename} ${namelist}) values ${valuelist})";
2046 $result = $dbxlink->exec ($query);
2052 // This swiss-knife blade deletes one record from the specified table
2053 // using the specified key name and value.
2054 function useDeleteBlade ($tablename, $keyname, $keyvalue)
2057 return 1 === $dbxlink->exec ("delete from ${tablename} where ${keyname}=${keyvalue} limit 1");
2060 function useSelectBlade ($query, $caller = 'N/A')
2063 $result = $dbxlink->query ($query);
2064 if ($result == NULL)
2066 $ei = $dbxlink->errorInfo();
2067 showError ("SQL query '${query}'\n failed in useSelectBlade with error ${ei[1]} (${ei[2]})", $caller);
2073 function loadConfigCache ()
2075 $query = 'SELECT varname, varvalue, vartype, is_hidden, emptyok, description FROM Config ORDER BY varname';
2076 $result = useSelectBlade ($query, __FUNCTION__
);
2078 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2079 $cache[$row['varname']] = $row;
2080 $result->closeCursor();
2084 // setConfigVar() is expected to perform all necessary filtering
2085 function storeConfigVar ($varname = NULL, $varvalue = NULL)
2088 if (empty ($varname) ||
$varvalue === NULL)
2090 showError ('Invalid arguments', __FUNCTION__
);
2093 $query = "update Config set varvalue='${varvalue}' where varname='${varname}' limit 1";
2094 $result = $dbxlink->query ($query);
2095 if ($result == NULL)
2097 showError ("SQL query '${query}' failed", __FUNCTION__
);
2100 $rc = $result->rowCount();
2101 $result->closeCursor();
2102 if ($rc == 0 or $rc == 1)
2104 showError ("Something went wrong for args '${varname}', '${varvalue}'", __FUNCTION__
);
2108 // Database version detector. Should behave corretly on any
2109 // working dataset a user might have.
2110 function getDatabaseVersion ()
2113 $query = "select varvalue from Config where varname = 'DB_VERSION' and vartype = 'string'";
2114 $result = $dbxlink->query ($query);
2115 if ($result == NULL)
2117 $errorInfo = $dbxlink->errorInfo();
2118 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
2120 die (__FUNCTION__
. ': SQL query #1 failed with error ' . $errorInfo[2]);
2122 $rows = $result->fetchAll (PDO
::FETCH_NUM
);
2123 if (count ($rows) != 1 ||
empty ($rows[0][0]))
2125 $result->closeCursor();
2126 die (__FUNCTION__
. ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
2129 $result->closeCursor();
2133 // Return an array of virtual services. For each of them list real server pools
2134 // with their load balancers and other stats.
2135 function getSLBSummary ()
2137 $query = 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
2138 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
2139 'from IPVirtualService as vs inner join IPLoadBalancer as lb on vs.id = lb.vs_id ' .
2140 'inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2141 'left join IPRealServer as rs on rs.rspool_id = lb.rspool_id ' .
2142 'group by vs.id, object_id order by vs.vip, object_id';
2143 $result = useSelectBlade ($query, __FUNCTION__
);
2145 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2147 $vsid = $row['vsid'];
2148 $object_id = $row['object_id'];
2149 if (!isset ($ret[$vsid]))
2151 $ret[$vsid] = array();
2152 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
2153 $ret[$vsid][$cname] = $row[$cname];
2154 $ret[$vsid]['lblist'] = array();
2156 // There's only one assigned RS pool possible for each LB-VS combination.
2157 $ret[$vsid]['lblist'][$row['object_id']] = array
2159 'id' => $row['rspool_id'],
2160 'size' => $row['rscount'],
2161 'name' => $row['pool_name']
2164 $result->closeCursor();
2168 // Get the detailed composition of a particular virtual service, namely the list
2169 // of all pools, each shown with the list of objects servicing it. VS/RS configs
2170 // will be returned as well.
2171 function getVServiceInfo ($vsid = 0)
2173 $query1 = "select inet_ntoa(vip) as vip, vport, proto, name, vsconfig, rsconfig " .
2174 "from IPVirtualService where id = ${vsid}";
2175 $result = useSelectBlade ($query1, __FUNCTION__
);
2177 $row = $result->fetch (PDO
::FETCH_ASSOC
);
2180 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig') as $cname)
2181 $vsinfo[$cname] = $row[$cname];
2182 $vsinfo['rspool'] = array();
2183 $result->closeCursor();
2185 $query2 = "select pool.id, name, pool.vsconfig, pool.rsconfig, object_id, " .
2186 "lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig from " .
2187 "IPRSPool as pool left join IPLoadBalancer as lb on pool.id = lb.rspool_id " .
2188 "where vs_id = ${vsid} order by pool.name, object_id";
2189 $result = useSelectBlade ($query2, __FUNCTION__
);
2190 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2192 if (!isset ($vsinfo['rspool'][$row['id']]))
2194 $vsinfo['rspool'][$row['id']]['name'] = $row['name'];
2195 $vsinfo['rspool'][$row['id']]['vsconfig'] = $row['vsconfig'];
2196 $vsinfo['rspool'][$row['id']]['rsconfig'] = $row['rsconfig'];
2197 $vsinfo['rspool'][$row['id']]['lblist'] = array();
2199 if ($row['object_id'] == NULL)
2201 $vsinfo['rspool'][$row['id']]['lblist'][$row['object_id']] = array
2203 'vsconfig' => $row['lb_vsconfig'],
2204 'rsconfig' => $row['lb_rsconfig']
2207 $result->closeCursor();
2211 // Collect and return the following info about the given real server pool:
2212 // basic information
2213 // parent virtual service information
2214 // load balancers list (each with a list of VSes)
2215 // real servers list
2217 function getRSPoolInfo ($id = 0)
2219 $query1 = "select id, name, vsconfig, rsconfig from " .
2220 "IPRSPool where id = ${id}";
2221 $result = useSelectBlade ($query1, __FUNCTION__
);
2223 $row = $result->fetch (PDO
::FETCH_ASSOC
);
2226 foreach (array ('id', 'name', 'vsconfig', 'rsconfig') as $c)
2227 $ret[$c] = $row[$c];
2228 $result->closeCursor();
2230 $ret['lblist'] = array();
2231 $ret['rslist'] = array();
2232 $query2 = "select object_id, vs_id, vsconfig, rsconfig from IPLoadBalancer " .
2233 "where rspool_id = ${id} order by object_id, vs_id";
2234 $result = useSelectBlade ($query2, __FUNCTION__
);
2235 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2236 foreach (array ('vsconfig', 'rsconfig') as $c)
2237 $ret['lblist'][$row['object_id']][$row['vs_id']][$c] = $row[$c];
2238 $result->closeCursor();
2240 $query3 = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rsconfig from " .
2241 "IPRealServer where rspool_id = ${id} order by IPRealServer.rsip, rsport";
2242 $result = useSelectBlade ($query3, __FUNCTION__
);
2243 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2244 foreach (array ('inservice', 'rsip', 'rsport', 'rsconfig') as $c)
2245 $ret['rslist'][$row['id']][$c] = $row[$c];
2246 $result->closeCursor();
2250 function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
2252 if ($pool_id <= 0 or $rsport <= 0)
2254 showError ('Invalid arguments', __FUNCTION__
);
2257 return useInsertBlade
2262 'rsip' => "inet_aton('${rsip}')",
2263 'rsport' => $rsport,
2264 'rspool_id' => $pool_id,
2265 'inservice' => ($inservice == 'yes' ?
"'yes'" : "'no'"),
2266 'rsconfig' => (empty ($rsconfig) ?
'NULL' : "'${rsconfig}'")
2271 function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig, $taglist = array())
2273 if (empty ($vip) or $vport <= 0 or empty ($proto))
2274 return __FUNCTION__
. ': invalid arguments';
2280 'vip' => "inet_aton('${vip}')",
2282 'proto' => "'${proto}'",
2283 'name' => (empty ($name) ?
'NULL' : "'${name}'"),
2284 'vsconfig' => (empty ($vsconfig) ?
'NULL' : "'${vsconfig}'"),
2285 'rsconfig' => (empty ($rsconfig) ?
'NULL' : "'${rsconfig}'")
2288 return __FUNCTION__
. ': SQL insertion failed';
2289 return produceTagsForLastRecord ('ipv4vs', $taglist);
2292 function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
2294 if ($pool_id <= 0 or $object_id <= 0 or $vs_id <= 0)
2296 showError ('Invalid arguments', __FUNCTION__
);
2299 return useInsertBlade
2304 'object_id' => $object_id,
2305 'rspool_id' => $pool_id,
2307 'vsconfig' => (empty ($vsconfig) ?
'NULL' : "'${vsconfig}'"),
2308 'rsconfig' => (empty ($rsconfig) ?
'NULL' : "'${rsconfig}'")
2313 function commitDeleteRS ($id = 0)
2317 return useDeleteBlade ('IPRealServer', 'id', $id);
2320 function commitDeleteVS ($id = 0)
2324 return useDeleteBlade ('IPVirtualService', 'id', $id) && destroyTagsForEntity ('ipv4vs', $id);
2327 function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
2330 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
2332 $query = "delete from IPLoadBalancer where object_id = ${object_id} and " .
2333 "rspool_id = ${pool_id} and vs_id = ${vs_id} limit 1";
2334 $result = $dbxlink->exec ($query);
2335 if ($result === NULL)
2337 elseif ($result != 1)
2343 function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2345 if ($rsid <= 0 or $rsport <= 0)
2347 showError ('Invalid args', __FUNCTION__
);
2350 if (long2ip (ip2long ($rsip)) !== $rsip)
2352 showError ("Invalid IP address '${rsip}'", __FUNCTION__
);
2357 "update IPRealServer set rsip = inet_aton('${rsip}'), rsport = ${rsport}, rsconfig = " .
2358 (empty ($rsconfig) ?
'NULL' : "'${rsconfig}'") .
2359 " where id = ${rsid} limit 1";
2360 $result = $dbxlink->query ($query);
2361 if ($result == NULL)
2363 showError ("SQL query '${query}' failed", __FUNCTION__
);
2369 function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
2371 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
2373 showError ('Invalid args', __FUNCTION__
);
2378 "update IPLoadBalancer set vsconfig = " .
2379 (empty ($vsconfig) ?
'NULL' : "'${vsconfig}'") .
2381 (empty ($rsconfig) ?
'NULL' : "'${rsconfig}'") .
2382 " where object_id = ${object_id} and rspool_id = ${pool_id} " .
2383 "and vs_id = ${vs_id} limit 1";
2384 $result = $dbxlink->exec ($query);
2385 if ($result === NULL)
2391 function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2393 if ($vsid <= 0 or empty ($vip) or $vport <= 0 or empty ($proto))
2395 showError ('Invalid args', __FUNCTION__
);
2399 $query = "update IPVirtualService set " .
2400 "vip = inet_aton('${vip}'), " .
2401 "vport = ${vport}, " .
2402 "proto = '${proto}', " .
2403 'name = ' . (empty ($name) ?
'NULL,' : "'${name}', ") .
2404 'vsconfig = ' . (empty ($vsconfig) ?
'NULL,' : "'${vsconfig}', ") .
2405 'rsconfig = ' . (empty ($rsconfig) ?
'NULL' : "'${rsconfig}'") .
2406 " where id = ${vsid} limit 1";
2407 $result = $dbxlink->exec ($query);
2408 if ($result === NULL)
2414 // Return the list of virtual services, indexed by vs_id.
2415 // Each record will be shown with its basic info plus RS pools counter.
2416 function getVSList ($tagfilter = array(), $tfmode = 'any')
2418 $whereclause = getWhereClause ($tagfilter);
2419 $query = "select vs.id, inet_ntoa(vip) as vip, vport, proto, vs.name, vs.vsconfig, vs.rsconfig, count(rspool_id) as poolcount " .
2420 "from IPVirtualService as vs left join IPLoadBalancer as lb on vs.id = lb.vs_id " .
2421 "left join TagStorage on vs.id = TagStorage.target_id and target_realm = 'ipv4vs' " .
2422 "where true ${whereclause} group by vs.id order by vs.vip, proto, vport";
2423 $result = useSelectBlade ($query, __FUNCTION__
);
2425 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2426 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig', 'poolcount') as $cname)
2427 $ret[$row['id']][$cname] = $row[$cname];
2428 $result->closeCursor();
2432 // Return the list of RS pool, indexed by pool id.
2433 function getRSPoolList ($tagfilter = array(), $tfmode = 'any')
2435 $whereclause = getWhereClause ($tagfilter);
2436 $query = "select pool.id, pool.name, count(rspool_id) as refcnt, pool.vsconfig, pool.rsconfig " .
2437 "from IPRSPool as pool left join IPLoadBalancer as lb on pool.id = lb.rspool_id " .
2438 "left join TagStorage on pool.id = TagStorage.target_id and target_realm = 'ipv4rspool' " .
2439 "where true ${whereclause} group by pool.id order by pool.name, pool.id";
2440 $result = useSelectBlade ($query, __FUNCTION__
);
2442 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2443 foreach (array ('name', 'refcnt', 'vsconfig', 'rsconfig') as $cname)
2444 $ret[$row['id']][$cname] = $row[$cname];
2445 $result->closeCursor();
2449 function loadThumbCache ($rack_id = 0)
2452 $query = "select thumb_data from Rack where id = ${rack_id} and thumb_data is not null limit 1";
2453 $result = useSelectBlade ($query, __FUNCTION__
);
2454 $row = $result->fetch (PDO
::FETCH_ASSOC
);
2456 $ret = base64_decode ($row['thumb_data']);
2457 $result->closeCursor();
2461 function saveThumbCache ($rack_id = 0, $cache = NULL)
2464 if ($rack_id == 0 or $cache == NULL)
2466 showError ('Invalid arguments', __FUNCTION__
);
2469 $data = base64_encode ($cache);
2470 $query = "update Rack set thumb_data = '${data}' where id = ${rack_id} limit 1";
2471 $result = $dbxlink->exec ($query);
2474 function resetThumbCache ($rack_id = 0)
2479 showError ('Invalid argument', __FUNCTION__
);
2482 $query = "update Rack set thumb_data = NULL where id = ${rack_id} limit 1";
2483 $result = $dbxlink->exec ($query);
2486 // Return the list of attached RS pools for the given object. As long as we have
2487 // the LB-VS UNIQUE in IPLoadBalancer table, it is Ok to key returned records
2488 // by vs_id, because there will be only one RS pool listed for each VS of the
2490 function getRSPoolsForObject ($object_id = 0)
2492 if ($object_id <= 0)
2494 showError ('Invalid object_id', __FUNCTION__
);
2497 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
2498 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
2499 'IPLoadBalancer as lb inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2500 'inner join IPVirtualService as vs on lb.vs_id = vs.id ' .
2501 'left join IPRealServer as rs on lb.rspool_id = rs.rspool_id ' .
2502 "where lb.object_id = ${object_id} " .
2503 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name';
2504 $result = useSelectBlade ($query, __FUNCTION__
);
2506 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2507 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
2508 $ret[$row['vs_id']][$cname] = $row[$cname];
2509 $result->closeCursor();
2513 function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
2516 return __FUNCTION__
. ': invalid arguments';
2522 'name' => (empty ($name) ?
'NULL' : "'${name}'"),
2523 'vsconfig' => (empty ($vsconfig) ?
'NULL' : "'${vsconfig}'"),
2524 'rsconfig' => (empty ($rsconfig) ?
'NULL' : "'${rsconfig}'")
2527 return __FUNCTION__
. ': SQL insertion failed';
2528 return produceTagsForLastRecord ('ipv4rspool', $taglist);
2531 function commitDeleteRSPool ($pool_id = 0)
2536 return useDeleteBlade ('IPRSPool', 'id', $pool_id) && destroyTagsForEntity ('ipv4rspool', $pool_id);
2539 function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2543 showError ('Invalid arg', __FUNCTION__
);
2547 $query = "update IPRSPool set " .
2548 'name = ' . (empty ($name) ?
'NULL,' : "'${name}', ") .
2549 'vsconfig = ' . (empty ($vsconfig) ?
'NULL,' : "'${vsconfig}', ") .
2550 'rsconfig = ' . (empty ($rsconfig) ?
'NULL' : "'${rsconfig}'") .
2551 " where id = ${pool_id} limit 1";
2552 $result = $dbxlink->exec ($query);
2553 if ($result === NULL)
2555 elseif ($result != 1)
2561 function getRSList ()
2563 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
2564 "from IPRealServer order by rspool_id, IPRealServer.rsip, rsport";
2565 $result = useSelectBlade ($query, __FUNCTION__
);
2567 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2568 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
2569 $ret[$row['id']][$cname] = $row[$cname];
2570 $result->closeCursor();
2574 // Return the list of all currently configured load balancers with their pool count.
2575 function getLBList ()
2577 $query = "select object_id, count(rspool_id) as poolcount " .
2578 "from IPLoadBalancer group by object_id order by object_id";
2579 $result = useSelectBlade ($query, __FUNCTION__
);
2581 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2582 $ret[$row['object_id']] = $row['poolcount'];
2583 $result->closeCursor();
2587 // For the given object return: it vsconfig/rsconfig; the list of RS pools
2588 // attached (each with vsconfig/rsconfig in turn), each with the list of
2589 // virtual services terminating the pool. Each pool also lists all real
2590 // servers with rsconfig.
2591 function getSLBConfig ($object_id)
2593 if ($object_id <= 0)
2595 showError ('Invalid arg', __FUNCTION__
);
2599 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2600 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2601 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
2602 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
2603 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
2604 'IPLoadBalancer as lb inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2605 'inner join IPVirtualService as vs on lb.vs_id = vs.id ' .
2606 'inner join IPRealServer as rs on lb.rspool_id = rs.rspool_id ' .
2607 "where lb.object_id = ${object_id} and rs.inservice = 'yes' " .
2608 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport";
2609 $result = useSelectBlade ($query, __FUNCTION__
);
2610 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2612 $vs_id = $row['vs_id'];
2613 if (!isset ($ret[$vs_id]))
2615 foreach (array ('vip', 'vport', 'proto', 'vs_name', 'vs_vsconfig', 'vs_rsconfig', 'lb_vsconfig', 'lb_rsconfig', 'pool_vsconfig', 'pool_rsconfig', 'pool_id', 'pool_name') as $c)
2616 $ret[$vs_id][$c] = $row[$c];
2617 $ret[$vs_id]['rslist'] = array();
2619 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2620 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
2622 $result->closeCursor();
2626 function commitSetInService ($rs_id = 0, $inservice = '')
2628 if ($rs_id <= 0 or empty ($inservice))
2630 showError ('Invalid args', __FUNCTION__
);
2634 $query = "update IPRealServer set inservice = '${inservice}' where id = ${rs_id} limit 1";
2635 $result = $dbxlink->exec ($query);
2636 if ($result === NULL)
2638 elseif ($result != 1)
2644 function executeAutoPorts ($object_id = 0, $type_id = 0)
2646 if ($object_id == 0 or $type_id == 0)
2648 showError ('Invalid arguments', __FUNCTION__
);
2652 foreach (getAutoPorts ($type_id) as $autoport)
2653 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2657 // Return only implicitly listed tags, the rest of the chain will be
2658 // generated/deducted later at higher levels.
2659 // Result is a chain: randomly indexed taginfo list.
2660 function loadEntityTags ($entity_realm = '', $entity_id = 0)
2662 if ($entity_realm == '' or $entity_id <= 0)
2664 showError ('Invalid or missing arguments', __FUNCTION__
);
2668 $query = "select tt.id, tag from " .
2669 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
2670 "where target_realm = '${entity_realm}' and target_id = ${entity_id} " .
2672 $result = useSelectBlade ($query, __FUNCTION__
);
2673 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2674 $ret[$row['id']] = $row;
2675 $result->closeCursor();
2676 return getExplicitTagsOnly ($ret);
2679 function loadRackObjectTags ($id)
2681 return loadEntityTags ('object', $id);
2684 function loadIPv4PrefixTags ($id)
2686 return loadEntityTags ('ipv4net', $id);
2689 function loadRackTags ($id)
2691 return loadEntityTags ('rack', $id);
2694 function loadIPv4VSTags ($id)
2696 return loadEntityTags ('ipv4vs', $id);
2699 function loadIPv4RSPoolTags ($id)
2701 return loadEntityTags ('ipv4rspool', $id);
2704 function loadUserTags ($user_id)
2706 return loadEntityTags ('user', $user_id);
2709 // Return a tag chain with all DB tags on it.
2710 function getTagList ()
2713 $query = "select id, parent_id, tag, target_realm as realm, count(target_id) as refcnt " .
2714 "from TagTree left join TagStorage on id = tag_id " .
2715 "group by id, target_realm order by tag";
2716 $result = useSelectBlade ($query, __FUNCTION__
);
2717 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2719 if (!isset ($ret[$row['id']]))
2720 $ret[$row['id']] = array
2723 'tag' => $row['tag'],
2724 'parent_id' => $row['parent_id'],
2728 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
2730 $result->closeCursor();
2734 function commitCreateTag ($tagname = '', $parent_id = 0)
2736 if ($tagname == '' or $parent_id === 0)
2737 return "Invalid args to " . __FUNCTION__
;
2738 $result = useInsertBlade
2743 'tag' => "'${tagname}'",
2744 'parent_id' => $parent_id
2750 return "SQL query failed in " . __FUNCTION__
;
2753 function commitDestroyTag ($tagid = 0)
2756 return 'Invalid arg to ' . __FUNCTION__
;
2757 if (useDeleteBlade ('TagTree', 'id', $tagid))
2760 return 'useDeleteBlade() failed in ' . __FUNCTION__
;
2763 function commitUpdateTag ($tag_id, $tag_name, $parent_id)
2765 if ($parent_id == 0)
2766 $parent_id = 'NULL';
2768 $query = "update TagTree set tag = '${tag_name}', parent_id = ${parent_id} " .
2769 "where id = ${tag_id} limit 1";
2770 $result = $dbxlink->exec ($query);
2771 if ($result === NULL)
2772 return 'SQL query failed in ' . __FUNCTION__
;
2776 // Drop the whole chain stored.
2777 function destroyTagsForEntity ($entity_realm, $entity_id)
2780 $query = "delete from TagStorage where target_realm = '${entity_realm}' and target_id = ${entity_id}";
2781 $result = $dbxlink->exec ($query);
2782 if ($result === NULL)
2788 // Drop only one record. This operation doesn't involve retossing other tags, unlike when adding.
2789 function deleteTagForEntity ($entity_realm, $entity_id, $tag_id)
2792 $query = "delete from TagStorage where target_realm = '${entity_realm}' and target_id = ${entity_id} and tag_id = ${tag_id}";
2793 $result = $dbxlink->exec ($query);
2794 if ($result === NULL)
2800 // Push a record into TagStorage unconditionally.
2801 function addTagForEntity ($realm, $entity_id, $tag_id)
2803 return useInsertBlade
2808 'target_realm' => "'${realm}'",
2809 'target_id' => $entity_id,
2810 'tag_id' => $tag_id,
2815 // Add records into TagStorage, if this makes sense (IOW, they don't appear
2816 // on the implicit list already). Then remove any other records, which
2817 // appear on the "implicit" side of the chain. This will make sure,
2818 // that both the tag base is still minimal and all requested tags appear on
2819 // the resulting tag chain.
2820 // Return TRUE, if any changes were committed.
2821 function rebuildTagChainForEntity ($realm, $entity_id, $extrachain = array())
2823 // Put the current explicit sub-chain into a buffer and merge all tags from
2824 // the extra chain, which aren't there yet.
2825 $newchain = $oldchain = loadEntityTags ($realm, $entity_id);
2826 foreach ($extrachain as $extratag)
2827 if (!tagOnChain ($extratag, $newchain))
2828 $newchain[] = $extratag;
2829 // Then minimize the working buffer and check if it differs from the original
2830 // chain we started with. If it is so, save the work and signal the upper layer.
2831 $newchain = getExplicitTagsOnly ($newchain);
2832 if (tagChainCmp ($oldchain, $newchain))
2834 destroyTagsForEntity ($realm, $entity_id);
2835 foreach ($newchain as $taginfo)
2836 addTagForEntity ($realm, $entity_id, $taginfo['id']);
2842 // Presume, that the target record has no tags attached.
2843 function produceTagsForLastRecord ($realm, $tagidlist, $last_insert_id = 0)
2845 if (!count ($tagidlist))
2847 if (!$last_insert_id)
2848 $last_insert_id = lastInsertID();
2850 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagidlist)) as $taginfo)
2851 if (addTagForEntity ($realm, $last_insert_id, $taginfo['id']) == FALSE)
2856 return "Experienced ${errcount} errors adding tags in realm '${realm}' for entity ID == ${last_insert_id}";
2859 function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
2861 // $range is in x.x.x.x/x format, split into ip/mask vars
2862 $rangeArray = explode('/', $range);
2863 if (count ($rangeArray) != 2)
2864 return "Invalid IPv4 prefix '${range}'";
2865 $ip = $rangeArray[0];
2866 $mask = $rangeArray[1];
2868 if (empty ($ip) or empty ($mask))
2869 return "Invalid IPv4 prefix '${range}'";
2870 $ipL = ip2long($ip);
2871 $maskL = ip2long($mask);
2872 if ($ipL == -1 ||
$ipL === FALSE)
2873 return 'Bad IPv4 address';
2874 if ($mask < 32 && $mask > 0)
2878 $maskB = decbin($maskL);
2879 if (strlen($maskB)!=32)
2880 return 'Invalid netmask';
2883 foreach( str_split ($maskB) as $digit)
2890 if ($zeroes == TRUE)
2891 return 'Invalid netmask';
2896 $binmask = binMaskFromDec($maskL);
2897 $ipL = $ipL & $binmask;
2901 "id, ip, mask, name ".
2904 $result = useSelectBlade ($query, __FUNCTION__
);
2906 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
2908 $otherip = $row['ip'];
2909 $othermask = binMaskFromDec($row['mask']);
2910 if (($otherip & $othermask) == ($ipL & $othermask))
2911 return "This subnet intersects with ".long2ip($row['ip'])."/${row['mask']}";
2912 if (($otherip & $binmask) == ($ipL & $binmask))
2913 return "This subnet intersects with ".long2ip($row['ip'])."/${row['mask']}";
2915 $result->closeCursor();
2917 $result = useInsertBlade
2922 'ip' => sprintf ('%u', $ipL),
2923 'mask' => "'${maskL}'",
2924 'name' => "'${name}'"
2928 if ($is_bcast and $maskL < 31)
2930 $network_addr = long2ip ($ipL);
2931 $broadcast_addr = long2ip ($ipL |
binInvMaskFromDec ($maskL));
2932 updateAddress ($network_addr, 'network', 'yes');
2933 updateAddress ($broadcast_addr, 'broadcast', 'yes');
2935 return produceTagsForLastRecord ('ipv4net', $taglist);
2938 // FIXME: This function doesn't wipe relevant records from IPAddress table.
2939 function destroyIPv4Prefix ($id = 0)
2942 return __FUNCTION__
. ': Invalid IPv4 prefix ID';
2943 if (!useDeleteBlade ('IPRanges', 'id', $id))
2944 return __FUNCTION__
. ': SQL query #1 failed';
2945 if (!destroyTagsForEntity ('ipv4net', $id))
2946 return __FUNCTION__
. ': SQL query #2 failed';
2950 function loadScript ($name)
2952 $result = useSelectBlade ("select script_text from Script where script_name = '${name}'");
2953 $row = $result->fetch (PDO
::FETCH_NUM
);
2960 function saveScript ($name, $text)
2964 showError ('Invalid argument');
2967 // delete regardless of existence
2968 useDeleteBlade ('Script', 'script_name', "'${name}'");
2969 return useInsertBlade
2974 'script_name' => "'${name}'",
2975 'script_text' => "'${text}'"
2980 function saveUserPassword ($user_id, $newp)
2982 $newhash = hash (PASSWORD_HASH
, $newp);
2983 $query = "update UserAccount set user_password_hash = ${newhash} where user_id = ${user_id} limit 1";
2986 function objectIsPortless ($id = 0)
2990 showError ('Invalid argument', __FUNCTION__
);
2993 if (($result = useSelectBlade ("select count(id) from Port where object_id = ${id}", __FUNCTION__
)) == NULL)
2995 showError ('SQL query failed', __FUNCTION__
);
2998 $row = $result->fetch (PDO
::FETCH_NUM
);
3000 $result->closeCursor();
3002 return $count === '0';
3005 function tagExistsInDatabase ($tname)
3007 $result = useSelectBlade ("select count(*) from TagTree where lower(tag) = lower('${tname}')");
3008 $row = $result->fetch (PDO
::FETCH_NUM
);
3010 $result->closeCursor();
3012 return $count !== '0';
3015 function newPortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3017 if (NULL === getIPv4AddressNetworkId ($localip))
3018 return "$localip: Non existant ip";
3019 if (NULL === getIPv4AddressNetworkId ($localip))
3020 return "$remoteip: Non existant ip";
3021 if ( ($localport <= 0) or ($localport >= 65536) )
3022 return "$localport: invaild port";
3023 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
3024 return "$remoteport: invaild port";
3026 $result = useInsertBlade
3031 'object_id' => $object_id,
3032 'localip' => "INET_ATON('${localip}')",
3033 'remoteip' => "INET_ATON('$remoteip')",
3034 'localport' => $localport,
3035 'remoteport' => $remoteport,
3036 'proto' => "'${proto}'",
3037 'description' => "'${description}'",
3043 return __FUNCTION__
. ': Failed to insert the rule.';
3046 function deletePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
3051 "delete from PortForwarding where object_id='$object_id' and localip=INET_ATON('$localip') and remoteip=INET_ATON('$remoteip') and localport='$localport' and remoteport='$remoteport' and proto='$proto'";
3052 $result = $dbxlink->exec ($query);
3056 function updatePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3061 "update PortForwarding set description='$description' where object_id='$object_id' and localip=INET_ATON('$localip') and remoteip=INET_ATON('$remoteip') and localport='$localport' and remoteport='$remoteport' and proto='$proto'";
3062 $result = $dbxlink->exec ($query);
3066 function getNATv4ForObject ($object_id)
3069 $ret['out'] = array();
3070 $ret['in'] = array();
3074 "INET_NTOA(localip) as localip, ".
3076 "INET_NTOA(remoteip) as remoteip, ".
3078 "ipa1.name as local_addr_name, " .
3079 "ipa2.name as remote_addr_name, " .
3081 "from PortForwarding ".
3082 "left join IPAddress as ipa1 on PortForwarding.localip = ipa1.ip " .
3083 "left join IPAddress as ipa2 on PortForwarding.remoteip = ipa2.ip " .
3084 "where object_id='$object_id' ".
3085 "order by localip, localport, proto, remoteip, remoteport";
3086 $result = useSelectBlade ($query, __FUNCTION__
);
3088 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
3090 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
3091 $ret['out'][$count][$cname] = $row[$cname];
3094 $result->closeCursor();
3100 "INET_NTOA(localip) as localip, ".
3102 "INET_NTOA(remoteip) as remoteip, ".
3104 "PortForwarding.object_id as object_id, ".
3105 "RackObject.name as object_name, ".
3107 "from ((PortForwarding join IPBonds on remoteip=IPBonds.ip) join RackObject on PortForwarding.object_id=RackObject.id) ".
3108 "where IPBonds.object_id='$object_id' ".
3109 "order by remoteip, remoteport, proto, localip, localport";
3110 $result = useSelectBlade ($query, __FUNCTION__
);
3112 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
3114 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
3115 $ret['in'][$count][$cname] = $row[$cname];
3118 $result->closeCursor();
3123 // This function performs search and then calculates score for each result.
3124 // Given previous search results in $objects argument, it adds new results
3125 // to the array and updates score for existing results, if it is greater than
3127 function mergeSearchResults (&$objects, $terms, $fieldname)
3131 "select name, label, asset_no, barcode, ro.id, dict_key as objtype_id, " .
3132 "dict_value as objtype_name, asset_no from RackObject as ro inner join Dictionary " .
3133 "on objtype_id = dict_key natural join Chapter where chapter_name = 'RackObjectType' and ";
3135 foreach (explode (' ', $terms) as $term)
3137 if ($count) $query .= ' or ';
3138 $query .= "${fieldname} like '%$term%'";
3141 $query .= " order by ${fieldname}";
3142 $result = useSelectBlade ($query, __FUNCTION__
);
3143 // FIXME: this dead call was executed 4 times per 1 object search!
3144 // $typeList = getObjectTypeList();
3145 $clist = array ('id', 'name', 'label', 'asset_no', 'barcode', 'objtype_id', 'objtype_name');
3146 while ($row = $result->fetch (PDO
::FETCH_ASSOC
))
3148 foreach ($clist as $cname)
3149 $object[$cname] = $row[$cname];
3150 $object['score'] = 0;
3151 $object['dname'] = displayedName ($object);
3152 unset ($object['objtype_id']);
3153 foreach (explode (' ', $terms) as $term)
3154 if (strstr ($object['name'], $term))
3155 $object['score'] +
= 1;
3156 unset ($object['name']);
3157 if (!isset ($objects[$row['id']]))
3158 $objects[$row['id']] = $object;
3159 elseif ($objects[$row['id']]['score'] < $object['score'])
3160 $objects[$row['id']]['score'] = $object['score'];