r2320 added ability to delete objects
[racktables] / inc / database.php
1 <?php
2 /*
3 *
4 * This file is a library of database access functions for RackTables.
5 *
6 */
7
8 function isInnoDBSupported ($dbh = FALSE) {
9 global $dbxlink;
10
11 // sometimes db handle isn't available globally, must be passed
12 if (!$dbxlink)
13 $dbxlink = $dbh;
14
15 // create a temp table
16 $dbxlink->query("CREATE TABLE `innodb_test` (`id` int) ENGINE=InnoDB");
17 $row = $dbxlink->query("SHOW TABLE STATUS LIKE 'innodb_test'")->fetch(PDO::FETCH_ASSOC);
18 $dbxlink->query("DROP TABLE `innodb_test`");
19 if ($row['Engine'] == 'InnoDB')
20 return TRUE;
21
22 return FALSE;
23 }
24
25 function escapeString ($value, $do_db_escape = TRUE)
26 {
27 $ret = htmlspecialchars ($value, ENT_QUOTES, 'UTF-8');
28 if ($do_db_escape)
29 {
30 global $dbxlink;
31 $ret = substr ($dbxlink->quote ($ret), 1, -1);
32 }
33 return $ret;
34 }
35
36 function getRackspace ($tagfilter = array(), $tfmode = 'any')
37 {
38 $whereclause = getWhereClause ($tagfilter);
39 $query =
40 "select dict_key as row_id, dict_value as row_name " .
41 "from Chapter natural join Dictionary left join Rack on Rack.row_id = dict_key " .
42 "left join TagStorage on Rack.id = TagStorage.target_id and target_realm = 'rack' " .
43 "where chapter_name = 'RackRow' " .
44 $whereclause .
45 " order by dict_value";
46 $result = useSelectBlade ($query, __FUNCTION__);
47 $ret = array();
48 $clist = array ('row_id', 'row_name');
49 while ($row = $result->fetch (PDO::FETCH_ASSOC))
50 foreach ($clist as $cname)
51 $ret[$row['row_id']][$cname] = $row[$cname];
52 $result->closeCursor();
53 return $ret;
54 }
55
56 // Return detailed information about one rack row.
57 function getRackRowInfo ($rackrow_id)
58 {
59 $query =
60 "select dict_key as id, dict_value as name, count(Rack.id) as count, " .
61 "if(isnull(sum(Rack.height)),0,sum(Rack.height)) as sum " .
62 "from Chapter natural join Dictionary left join Rack on Rack.row_id = dict_key " .
63 "where chapter_name = 'RackRow' and dict_key = ${rackrow_id} " .
64 "group by dict_key";
65 $result = useSelectBlade ($query, __FUNCTION__);
66 if ($row = $result->fetch (PDO::FETCH_ASSOC))
67 return $row;
68 else
69 return NULL;
70 }
71
72 // This function returns id->name map for all object types. The map is used
73 // to build <select> input for objects.
74 function getObjectTypeList ()
75 {
76 return readChapter ('RackObjectType');
77 }
78
79 // Return a part of SQL query suitable for embeding into a bigger text.
80 // The returned result should list all tag IDs shown in the tag filter.
81 function getWhereClause ($tagfilter = array())
82 {
83 $whereclause = '';
84 if (count ($tagfilter))
85 {
86 $whereclause .= ' and (';
87 $conj = '';
88 foreach ($tagfilter as $tag_id)
89 {
90 $whereclause .= $conj . 'tag_id = ' . $tag_id;
91 $conj = ' or ';
92 }
93 $whereclause .= ') ';
94 }
95 return $whereclause;
96 }
97
98 // Return a simple object list w/o related information.
99 function getNarrowObjectList ($type_id = 0)
100 {
101 $ret = array();
102 if (!$type_id)
103 {
104 showError ('Invalid argument', __FUNCTION__);
105 return $ret;
106 }
107 // object type id is known and constant, but it's Ok to have this standard overhead
108 $query =
109 "select RackObject.id as id, RackObject.name as name, dict_value as objtype_name, " .
110 "objtype_id from " .
111 "RackObject inner join Dictionary on objtype_id=dict_key natural join Chapter " .
112 "where RackObject.deleted = 'no' and chapter_name = 'RackObjectType' " .
113 "and objtype_id = ${type_id} " .
114 "order by name";
115 $result = useSelectBlade ($query, __FUNCTION__);
116 while ($row = $result->fetch (PDO::FETCH_ASSOC))
117 {
118 foreach (array (
119 'id',
120 'name',
121 'objtype_name',
122 'objtype_id'
123 ) as $cname)
124 $ret[$row['id']][$cname] = $row[$cname];
125 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
126 }
127 return $ret;
128 }
129
130 // Return a filtered, detailed object list.
131 function getObjectList ($type_id = 0, $tagfilter = array(), $tfmode = 'any')
132 {
133 $whereclause = getWhereClause ($tagfilter);
134 if ($type_id != 0)
135 $whereclause .= " and objtype_id = '${type_id}' ";
136 $query =
137 "select distinct RackObject.id as id , RackObject.name as name, dict_value as objtype_name, " .
138 "RackObject.label as label, RackObject.barcode as barcode, " .
139 "dict_key as objtype_id, asset_no, rack_id, Rack.name as Rack_name, Rack.row_id, " .
140 "(SELECT dict_value FROM Dictionary WHERE dict_key = Rack.row_id) AS Row_name " .
141 "from ((RackObject inner join Dictionary on objtype_id=dict_key natural join Chapter) " .
142 "left join RackSpace on RackObject.id = object_id) " .
143 "left join Rack on rack_id = Rack.id " .
144 "left join TagStorage on RackObject.id = TagStorage.target_id and target_realm = 'object' " .
145 "where RackObject.deleted = 'no' and chapter_name = 'RackObjectType' " .
146 $whereclause .
147 "order by name";
148 $result = useSelectBlade ($query, __FUNCTION__);
149 $ret = array();
150 while ($row = $result->fetch (PDO::FETCH_ASSOC))
151 {
152 foreach (array (
153 'id',
154 'name',
155 'label',
156 'barcode',
157 'objtype_name',
158 'objtype_id',
159 'asset_no',
160 'rack_id',
161 'Rack_name',
162 'row_id',
163 'Row_name'
164 ) as $cname)
165 $ret[$row['id']][$cname] = $row[$cname];
166 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
167 }
168 $result->closeCursor();
169 return $ret;
170 }
171
172 function getRacksForRow ($row_id = 0, $tagfilter = array(), $tfmode = 'any')
173 {
174 $query =
175 "select Rack.id, Rack.name, height, Rack.comment, row_id, " .
176 "'yes' as left_is_front, 'yes' as bottom_is_unit1, dict_value as row_name " .
177 "from Rack left join Dictionary on row_id = dict_key natural join Chapter " .
178 "left join TagStorage on Rack.id = TagStorage.target_id and target_realm = 'rack' " .
179 "where chapter_name = 'RackRow' and Rack.deleted = 'no' " .
180 (($row_id == 0) ? "" : "and row_id = ${row_id} ") .
181 getWhereClause ($tagfilter) .
182 " order by row_name, Rack.id";
183 $result = useSelectBlade ($query, __FUNCTION__);
184 $ret = array();
185 $clist = array
186 (
187 'id',
188 'name',
189 'height',
190 'comment',
191 'row_id',
192 'left_is_front',
193 'bottom_is_unit1',
194 'row_name'
195 );
196 while ($row = $result->fetch (PDO::FETCH_ASSOC))
197 foreach ($clist as $cname)
198 $ret[$row['id']][$cname] = $row[$cname];
199 $result->closeCursor();
200 usort ($ret, 'sortRacks');
201 $ret = restoreRackIDs ($ret);
202 return $ret;
203 }
204
205 // This is a popular helper for getting information about
206 // a particular rack and its rackspace at once.
207 function getRackData ($rack_id = 0, $silent = FALSE)
208 {
209 if ($rack_id == 0)
210 {
211 if ($silent == FALSE)
212 showError ('Invalid rack_id', __FUNCTION__);
213 return NULL;
214 }
215 $query =
216 "select Rack.id, Rack.name, row_id, height, Rack.comment, " .
217 "'yes' as left_is_front, 'yes' as bottom_is_unit1, dict_value as row_name from " .
218 "Rack left join Dictionary on Rack.row_id = dict_key natural join Chapter " .
219 "where chapter_name = 'RackRow' and Rack.id='${rack_id}' and Rack.deleted = 'no' limit 1";
220 $result = useSelectBlade ($query, __FUNCTION__);
221 if (($row = $result->fetch (PDO::FETCH_ASSOC)) == NULL)
222 {
223 if ($silent == FALSE)
224 showError ('Query #1 succeded, but returned no data', __FUNCTION__);
225 return NULL;
226 }
227
228 // load metadata
229 $clist = array
230 (
231 'id',
232 'name',
233 'height',
234 'comment',
235 'row_id',
236 'left_is_front',
237 'bottom_is_unit1',
238 'row_name'
239 );
240 foreach ($clist as $cname)
241 $rack[$cname] = $row[$cname];
242 $result->closeCursor();
243 unset ($result);
244
245 // start with default rackspace
246 for ($i = $rack['height']; $i > 0; $i--)
247 for ($locidx = 0; $locidx < 3; $locidx++)
248 $rack[$i][$locidx]['state'] = 'F';
249
250 // load difference
251 $query =
252 "select unit_no, atom, state, object_id " .
253 "from RackSpace where rack_id = ${rack_id} and " .
254 "unit_no between 1 and " . $rack['height'] . " order by unit_no";
255 $result = useSelectBlade ($query, __FUNCTION__);
256 global $loclist;
257 while ($row = $result->fetch (PDO::FETCH_ASSOC))
258 {
259 $rack[$row['unit_no']][$loclist[$row['atom']]]['state'] = $row['state'];
260 $rack[$row['unit_no']][$loclist[$row['atom']]]['object_id'] = $row['object_id'];
261 }
262 $result->closeCursor();
263 return $rack;
264 }
265
266 // This is a popular helper.
267 function getObjectInfo ($object_id = 0)
268 {
269 if ($object_id == 0)
270 {
271 showError ('Invalid object_id', __FUNCTION__);
272 return;
273 }
274 $query =
275 "select id, name, label, barcode, dict_value as objtype_name, asset_no, dict_key as objtype_id, has_problems, comment from " .
276 "RackObject inner join Dictionary on objtype_id = dict_key natural join Chapter " .
277 "where id = '${object_id}' and deleted = 'no' and chapter_name = 'RackObjectType' limit 1";
278 $result = useSelectBlade ($query, __FUNCTION__);
279 if (($row = $result->fetch (PDO::FETCH_ASSOC)) == NULL)
280 {
281 showError ('Query succeeded, but returned no data', __FUNCTION__);
282 $ret = NULL;
283 }
284 else
285 {
286 $ret['id'] = $row['id'];
287 $ret['name'] = $row['name'];
288 $ret['label'] = $row['label'];
289 $ret['barcode'] = $row['barcode'];
290 $ret['objtype_name'] = $row['objtype_name'];
291 $ret['objtype_id'] = $row['objtype_id'];
292 $ret['has_problems'] = $row['has_problems'];
293 $ret['asset_no'] = $row['asset_no'];
294 $ret['dname'] = displayedName ($ret);
295 $ret['comment'] = $row['comment'];
296 }
297 $result->closeCursor();
298 unset ($result);
299 return $ret;
300 }
301
302 function getPortTypes ()
303 {
304 return readChapter ('PortType');
305 }
306
307 function getObjectPortsAndLinks ($object_id = 0)
308 {
309 if ($object_id == 0)
310 {
311 showError ('Invalid object_id', __FUNCTION__);
312 return;
313 }
314 // prepare decoder
315 $ptd = readChapter ('PortType');
316 $query = "select id, name, label, l2address, type as type_id, reservation_comment from Port where object_id = ${object_id}";
317 // list and decode all ports of the current object
318 $result = useSelectBlade ($query, __FUNCTION__);
319 $ret=array();
320 while ($row = $result->fetch (PDO::FETCH_ASSOC))
321 {
322 $row['type'] = $ptd[$row['type_id']];
323 $row['l2address'] = l2addressFromDatabase ($row['l2address']);
324 $row['remote_id'] = NULL;
325 $row['remote_name'] = NULL;
326 $row['remote_object_id'] = NULL;
327 $row['remote_object_name'] = NULL;
328 $ret[] = $row;
329 }
330 unset ($result);
331 // now find and decode remote ends for all locally terminated connections
332 foreach (array_keys ($ret) as $tmpkey)
333 {
334 $portid = $ret[$tmpkey]['id'];
335 $remote_id = NULL;
336 $query = "select porta, portb from Link where porta = {$portid} or portb = ${portid}";
337 $result = useSelectBlade ($query, __FUNCTION__);
338 if ($row = $result->fetch (PDO::FETCH_ASSOC))
339 {
340 if ($portid != $row['porta'])
341 $remote_id = $row['porta'];
342 elseif ($portid != $row['portb'])
343 $remote_id = $row['portb'];
344 }
345 unset ($result);
346 if ($remote_id) // there's a remote end here
347 {
348 $query = "select Port.name as port_name, Port.type as port_type, object_id, RackObject.name as object_name " .
349 "from Port left join RackObject on Port.object_id = RackObject.id " .
350 "where Port.id = ${remote_id}";
351 $result = useSelectBlade ($query, __FUNCTION__);
352 if ($row = $result->fetch (PDO::FETCH_ASSOC))
353 {
354 $ret[$tmpkey]['remote_name'] = $row['port_name'];
355 $ret[$tmpkey]['remote_object_id'] = $row['object_id'];
356 $ret[$tmpkey]['remote_object_name'] = $row['object_name'];
357 }
358 $ret[$tmpkey]['remote_id'] = $remote_id;
359 unset ($result);
360 // only call displayedName() when necessary
361 if (empty ($ret[$tmpkey]['remote_object_name']) and !empty ($ret[$tmpkey]['remote_object_id']))
362 {
363 $oi = getObjectInfo ($ret[$tmpkey]['remote_object_id']);
364 $ret[$tmpkey]['remote_object_name'] = displayedName ($oi);
365 }
366 }
367 }
368 return $ret;
369 }
370
371 function commitAddRack ($name, $height = 0, $row_id = 0, $comment, $taglist)
372 {
373 if ($row_id <= 0 or $height <= 0 or empty ($name))
374 return FALSE;
375 $result = useInsertBlade
376 (
377 'Rack',
378 array
379 (
380 'row_id' => $row_id,
381 'name' => "'${name}'",
382 'height' => $height,
383 'comment' => "'${comment}'"
384 )
385 );
386 if ($result == NULL)
387 {
388 showError ('useInsertBlade() failed', __FUNCTION__);
389 return FALSE;
390 }
391 $last_insert_id = lastInsertID();
392 return (produceTagsForLastRecord ('rack', $taglist, $last_insert_id) == '') and recordHistory ('Rack', "id = ${last_insert_id}");
393 }
394
395 function commitAddObject ($new_name, $new_label, $new_barcode, $new_type_id, $new_asset_no, $taglist = array())
396 {
397 global $dbxlink;
398 // Maintain UNIQUE INDEX for common names and asset tags by
399 // filtering out empty strings (not NULLs).
400 $result1 = useInsertBlade
401 (
402 'RackObject',
403 array
404 (
405 'name' => empty ($new_name) ? 'NULL' : "'${new_name}'",
406 'label' => "'${new_label}'",
407 'barcode' => empty ($new_barcode) ? 'NULL' : "'${new_barcode}'",
408 'objtype_id' => $new_type_id,
409 'asset_no' => empty ($new_asset_no) ? 'NULL' : "'${new_asset_no}'"
410 )
411 );
412 if ($result1 == NULL)
413 {
414 showError ("SQL query #1 failed", __FUNCTION__);
415 return FALSE;
416 }
417 $last_insert_id = lastInsertID();
418 // Do AutoPorts magic
419 executeAutoPorts ($last_insert_id, $new_type_id);
420 // Now tags...
421 $error = produceTagsForLastRecord ('object', $taglist, $last_insert_id);
422 if ($error != '')
423 {
424 showError ("Error adding tags for the object: ${error}");
425 return FALSE;
426 }
427 return recordHistory ('RackObject', "id = ${last_insert_id}");
428 }
429
430 function commitUpdateObject ($object_id = 0, $new_name = '', $new_label = '', $new_barcode = '', $new_type_id = 0, $new_has_problems = 'no', $new_asset_no = '', $new_comment = '')
431 {
432 if ($object_id == 0 || $new_type_id == 0)
433 {
434 showError ('Not all required args are present.', __FUNCTION__);
435 return FALSE;
436 }
437 global $dbxlink;
438 $new_asset_no = empty ($new_asset_no) ? 'NULL' : "'${new_asset_no}'";
439 $new_barcode = empty ($new_barcode) ? 'NULL' : "'${new_barcode}'";
440 $new_name = empty ($new_name) ? 'NULL' : "'${new_name}'";
441 $query = "update RackObject set name=${new_name}, label='${new_label}', barcode=${new_barcode}, objtype_id='${new_type_id}', " .
442 "has_problems='${new_has_problems}', asset_no=${new_asset_no}, comment='${new_comment}' " .
443 "where id='${object_id}' limit 1";
444 $result = $dbxlink->query ($query);
445 if ($result == NULL)
446 {
447 showError ("SQL query '${query}' failed", __FUNCTION__);
448 return FALSE;
449 }
450 $result->closeCursor();
451 return recordHistory ('RackObject', "id = ${object_id}");
452 }
453
454 // There are times when you want to delete all traces of an object
455 function commitDeleteObject ($object_id = 0)
456 {
457 if ($object_id <= 0)
458 {
459 showError ('Invalid args', __FUNCTION__);
460 die;
461 }
462 global $dbxlink;
463 $dbxlink->query("DELETE FROM AttributeValue WHERE object_id = {$object_id}");
464 $dbxlink->query("DELETE FROM File WHERE id IN (SELECT file_id FROM FileLink WHERE entity_id = 'object' AND entity_id = {$object_id})");
465 $dbxlink->query("DELETE FROM IPLoadBalancer WHERE object_id = {$object_id}");
466 $dbxlink->query("DELETE FROM IPBonds WHERE object_id = {$object_id}");
467 $dbxlink->query("DELETE FROM Port WHERE object_id = {$object_id}");
468 $dbxlink->query("DELETE FROM PortForwarding WHERE object_id = {$object_id}");
469 $dbxlink->query("DELETE FROM RackSpace WHERE object_id = {$object_id}");
470 $dbxlink->query("DELETE FROM TagStorage WHERE target_realm = 'object' and target_id = {$object_id}");
471 $dbxlink->query("DELETE FROM Atom WHERE molecule_id IN (SELECT new_molecule_id FROM MountOperation WHERE object_id = {$object_id})");
472 $dbxlink->query("DELETE FROM Molecule WHERE id IN (SELECT new_molecule_id FROM MountOperation WHERE object_id = {$object_id})");
473 $dbxlink->query("DELETE FROM MountOperation WHERE object_id = {$object_id}");
474 $dbxlink->query("DELETE FROM RackObjectHistory WHERE id = {$object_id}");
475 $dbxlink->query("DELETE FROM RackObject WHERE id = {$object_id}");
476
477 return '';
478 }
479
480 function commitUpdateRack ($rack_id, $new_name, $new_height, $new_row_id, $new_comment)
481 {
482 if (empty ($rack_id) || empty ($new_name) || empty ($new_height))
483 {
484 showError ('Not all required args are present.', __FUNCTION__);
485 return FALSE;
486 }
487 global $dbxlink;
488 $query = "update Rack set name='${new_name}', height='${new_height}', comment='${new_comment}', row_id=${new_row_id} " .
489 "where id='${rack_id}' limit 1";
490 $result1 = $dbxlink->query ($query);
491 if ($result1->rowCount() != 1)
492 {
493 showError ('Error updating rack information', __FUNCTION__);
494 return FALSE;
495 }
496 return recordHistory ('Rack', "id = ${rack_id}");
497 }
498
499 // This function accepts rack data returned by getRackData(), validates and applies changes
500 // supplied in $_REQUEST and returns resulting array. Only those changes are examined, which
501 // correspond to current rack ID.
502 // 1st arg is rackdata, 2nd arg is unchecked state, 3rd arg is checked state.
503 // If 4th arg is present, object_id fields will be updated accordingly to the new state.
504 // The function returns the modified rack upon success.
505 function processGridForm (&$rackData, $unchecked_state, $checked_state, $object_id = 0)
506 {
507 global $loclist, $dbxlink;
508 $rack_id = $rackData['id'];
509 $rack_name = $rackData['name'];
510 $rackchanged = FALSE;
511 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
512 {
513 for ($locidx = 0; $locidx < 3; $locidx++)
514 {
515 if ($rackData[$unit_no][$locidx]['enabled'] != TRUE)
516 continue;
517 // detect a change
518 $state = $rackData[$unit_no][$locidx]['state'];
519 if (isset ($_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"]) and $_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"] == 'on')
520 $newstate = $checked_state;
521 else
522 $newstate = $unchecked_state;
523 if ($state == $newstate)
524 continue;
525 $rackchanged = TRUE;
526 // and validate
527 $atom = $loclist[$locidx];
528 // The only changes allowed are those introduced by checkbox grid.
529 if
530 (
531 !($state == $checked_state && $newstate == $unchecked_state) &&
532 !($state == $unchecked_state && $newstate == $checked_state)
533 )
534 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, 'atom ${atom}', cannot change state from '${state}' to '${newstate}'");
535 // Here we avoid using ON DUPLICATE KEY UPDATE by first performing DELETE
536 // anyway and then looking for probable need of INSERT.
537 $query =
538 "delete from RackSpace where rack_id = ${rack_id} and " .
539 "unit_no = ${unit_no} and atom = '${atom}' limit 1";
540 $r = $dbxlink->query ($query);
541 if ($r == NULL)
542 return array ('code' => 500, 'message' => __FUNCTION__ . ": ${rack_name}: SQL DELETE query failed");
543 if ($newstate != 'F')
544 {
545 $query =
546 "insert into RackSpace(rack_id, unit_no, atom, state) " .
547 "values(${rack_id}, ${unit_no}, '${atom}', '${newstate}') ";
548 $r = $dbxlink->query ($query);
549 if ($r == NULL)
550 return array ('code' => 500, 'message' => __FUNCTION__ . ": ${rack_name}: SQL INSERT query failed");
551 }
552 if ($newstate == 'T' and $object_id != 0)
553 {
554 // At this point we already have a record in RackSpace.
555 $query =
556 "update RackSpace set object_id=${object_id} " .
557 "where rack_id=${rack_id} and unit_no=${unit_no} and atom='${atom}' limit 1";
558 $r = $dbxlink->query ($query);
559 if ($r->rowCount() == 1)
560 $rackData[$unit_no][$locidx]['object_id'] = $object_id;
561 else
562 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, atom '${atom}' failed to set object_id to '${object_id}'");
563 }
564 }
565 }
566 if ($rackchanged)
567 {
568 resetThumbCache ($rack_id);
569 return array ('code' => 200, 'message' => "${rack_name}: All changes were successfully saved.");
570 }
571 else
572 return array ('code' => 300, 'message' => "${rack_name}: No changes.");
573 }
574
575 // This function builds a list of rack-unit-atom records, which are assigned to
576 // the requested object.
577 function getMoleculeForObject ($object_id = 0)
578 {
579 if ($object_id == 0)
580 {
581 showError ("object_id == 0", __FUNCTION__);
582 return NULL;
583 }
584 $query =
585 "select rack_id, unit_no, atom from RackSpace " .
586 "where state = 'T' and object_id = ${object_id} order by rack_id, unit_no, atom";
587 $result = useSelectBlade ($query, __FUNCTION__);
588 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
589 $result->closeCursor();
590 return $ret;
591 }
592
593 // This function builds a list of rack-unit-atom records for requested molecule.
594 function getMolecule ($mid = 0)
595 {
596 if ($mid == 0)
597 {
598 showError ("mid == 0", __FUNCTION__);
599 return NULL;
600 }
601 $query =
602 "select rack_id, unit_no, atom from Atom " .
603 "where molecule_id=${mid}";
604 $result = useSelectBlade ($query, __FUNCTION__);
605 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
606 $result->closeCursor();
607 return $ret;
608 }
609
610 // returns exactly what is's named after
611 function lastInsertID ()
612 {
613 if (NULL == ($result = useSelectBlade ('select last_insert_id()', __FUNCTION__)))
614 {
615 showError ('SQL query failed!', __FUNCTION__);
616 die;
617 }
618 $row = $result->fetch (PDO::FETCH_NUM);
619 return $row[0];
620 }
621
622 // This function creates a new record in Molecule and number of linked
623 // R-U-A records in Atom.
624 function createMolecule ($molData)
625 {
626 global $dbxlink;
627 $query = "insert into Molecule values()";
628 $result1 = $dbxlink->query ($query);
629 if ($result1->rowCount() != 1)
630 {
631 showError ('Error inserting into Molecule', __FUNCTION__);
632 return NULL;
633 }
634 $molecule_id = lastInsertID();
635 foreach ($molData as $rua)
636 {
637 $rack_id = $rua['rack_id'];
638 $unit_no = $rua['unit_no'];
639 $atom = $rua['atom'];
640 $query =
641 "insert into Atom(molecule_id, rack_id, unit_no, atom) " .
642 "values (${molecule_id}, ${rack_id}, ${unit_no}, '${atom}')";
643 $result3 = $dbxlink->query ($query);
644 if ($result3 == NULL or $result3->rowCount() != 1)
645 {
646 showError ('Error inserting into Atom', __FUNCTION__);
647 return NULL;
648 }
649 }
650 return $molecule_id;
651 }
652
653 // History logger. This function assumes certain table naming convention and
654 // column design:
655 // 1. History table name equals to dictionary table name plus 'History'.
656 // 2. History table must have the same row set (w/o keys) plus one row named
657 // 'ctime' of type 'timestamp'.
658 function recordHistory ($tableName, $whereClause)
659 {
660 global $dbxlink, $remote_username;
661 $query = "insert into ${tableName}History select *, current_timestamp(), '${remote_username}' from ${tableName} where ${whereClause}";
662 $result = $dbxlink->query ($query);
663 if ($result == NULL or $result->rowCount() != 1)
664 {
665 showError ("SQL query '${query}' failed for table ${tableName}", __FUNCTION__);
666 return FALSE;
667 }
668 return TRUE;
669 }
670
671 function getRackspaceHistory ()
672 {
673 $query =
674 "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 " .
675 "MountOperation as mo inner join RackObject as ro on mo.object_id = ro.id " .
676 "inner join Dictionary on objtype_id = dict_key natural join Chapter " .
677 "where chapter_name = 'RackObjectType' order by ctime desc";
678 $result = useSelectBlade ($query, __FUNCTION__);
679 $ret = $result->fetchAll(PDO::FETCH_ASSOC);
680 $result->closeCursor();
681 return $ret;
682 }
683
684 // This function is used in renderRackspaceHistory()
685 function getOperationMolecules ($op_id = 0)
686 {
687 if ($op_id <= 0)
688 {
689 showError ("Missing argument", __FUNCTION__);
690 return;
691 }
692 $query = "select old_molecule_id, new_molecule_id from MountOperation where id = ${op_id}";
693 $result = useSelectBlade ($query, __FUNCTION__);
694 // We expect one row.
695 $row = $result->fetch (PDO::FETCH_ASSOC);
696 if ($row == NULL)
697 {
698 showError ("SQL query succeded, but returned no results.", __FUNCTION__);
699 return;
700 }
701 $omid = $row['old_molecule_id'];
702 $nmid = $row['new_molecule_id'];
703 $result->closeCursor();
704 return array ($omid, $nmid);
705 }
706
707 function getResidentRacksData ($object_id = 0, $fetch_rackdata = TRUE)
708 {
709 if ($object_id <= 0)
710 {
711 showError ('Invalid object_id', __FUNCTION__);
712 return;
713 }
714 $query = "select distinct rack_id from RackSpace where object_id = ${object_id} order by rack_id";
715 $result = useSelectBlade ($query, __FUNCTION__);
716 $rows = $result->fetchAll (PDO::FETCH_NUM);
717 $result->closeCursor();
718 $ret = array();
719 foreach ($rows as $row)
720 {
721 if (!$fetch_rackdata)
722 {
723 $ret[$row[0]] = $row[0];
724 continue;
725 }
726 $rackData = getRackData ($row[0]);
727 if ($rackData == NULL)
728 {
729 showError ('getRackData() failed', __FUNCTION__);
730 return NULL;
731 }
732 $ret[$row[0]] = $rackData;
733 }
734 $result->closeCursor();
735 return $ret;
736 }
737
738 function getObjectGroupInfo ()
739 {
740 $query =
741 'select dict_key as id, dict_value as name, count(id) as count from ' .
742 'Dictionary natural join Chapter left join RackObject on dict_key = objtype_id ' .
743 'where chapter_name = "RackObjectType" ' .
744 'group by dict_key order by dict_value';
745 $result = useSelectBlade ($query, __FUNCTION__);
746 $ret = array();
747 $ret[0] = array ('id' => 0, 'name' => 'ALL types');
748 $clist = array ('id', 'name', 'count');
749 $total = 0;
750 while ($row = $result->fetch (PDO::FETCH_ASSOC))
751 if ($row['count'] > 0)
752 {
753 $total += $row['count'];
754 foreach ($clist as $cname)
755 $ret[$row['id']][$cname] = $row[$cname];
756 }
757 $result->closeCursor();
758 $ret[0]['count'] = $total;
759 return $ret;
760 }
761
762 // This function returns objects, which have no rackspace assigned to them.
763 // Additionally it keeps rack_id parameter, so we can silently pre-select
764 // the rack required.
765 function getUnmountedObjects ()
766 {
767 $query =
768 'select dict_value as objtype_name, dict_key as objtype_id, name, label, barcode, id, asset_no from ' .
769 'RackObject inner join Dictionary on objtype_id = dict_key natural join Chapter ' .
770 'left join RackSpace on id = object_id '.
771 'where rack_id is null and chapter_name = "RackObjectType" order by dict_value, name, label, asset_no, barcode';
772 $result = useSelectBlade ($query, __FUNCTION__);
773 $ret = array();
774 $clist = array ('id', 'name', 'label', 'barcode', 'objtype_name', 'objtype_id', 'asset_no');
775 while ($row = $result->fetch (PDO::FETCH_ASSOC))
776 {
777 foreach ($clist as $cname)
778 $ret[$row['id']][$cname] = $row[$cname];
779 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
780 }
781 $result->closeCursor();
782 return $ret;
783 }
784
785 function getProblematicObjects ()
786 {
787 $query =
788 'select dict_value as objtype_name, dict_key as objtype_id, name, id, asset_no from ' .
789 'RackObject inner join Dictionary on objtype_id = dict_key natural join Chapter '.
790 'where has_problems = "yes" and chapter_name = "RackObjectType" order by objtype_name, name';
791 $result = useSelectBlade ($query, __FUNCTION__);
792 $ret = array();
793 $clist = array ('id', 'name', 'objtype_name', 'objtype_id', 'asset_no');
794 while ($row = $result->fetch (PDO::FETCH_ASSOC))
795 {
796 foreach ($clist as $cname)
797 $ret[$row['id']][$cname] = $row[$cname];
798 $ret[$row['id']]['dname'] = displayedName ($ret[$row['id']]);
799 }
800 $result->closeCursor();
801 return $ret;
802 }
803
804 function commitAddPort ($object_id = 0, $port_name, $port_type_id, $port_label, $port_l2address)
805 {
806 if ($object_id <= 0)
807 {
808 showError ('Invalid object_id', __FUNCTION__);
809 return;
810 }
811 $port_l2address = l2addressForDatabase ($port_l2address);
812 $result = useInsertBlade
813 (
814 'Port',
815 array
816 (
817 'name' => "'${port_name}'",
818 'object_id' => "'${object_id}'",
819 'label' => "'${port_label}'",
820 'type' => "'${port_type_id}'",
821 'l2address' => "${port_l2address}"
822 )
823 );
824 if ($result)
825 return '';
826 else
827 return 'SQL query failed';
828 }
829
830 // The fifth argument may be either explicit 'NULL' or some (already quoted by the upper layer)
831 // string value. In case it is omitted, we just assign it its current value.
832 // It would be nice to simplify this semantics later.
833 function commitUpdatePort ($port_id, $port_name, $port_type_id, $port_label, $port_l2address, $port_reservation_comment = 'reservation_comment')
834 {
835 global $dbxlink;
836 $port_l2address = l2addressForDatabase ($port_l2address);
837 $query =
838 "update Port set name='$port_name', type=$port_type_id, label='$port_label', " .
839 "reservation_comment = ${port_reservation_comment}, l2address=${port_l2address} " .
840 "where id='$port_id'";
841 $result = $dbxlink->exec ($query);
842 if ($result == 1)
843 return '';
844 $errorInfo = $dbxlink->errorInfo();
845 // We could update nothing.
846 if ($errorInfo[0] == '00000')
847 return '';
848 return $errorInfo[2];
849 }
850
851 function delObjectPort ($port_id)
852 {
853 if (unlinkPort ($port_id) != '')
854 return __FUNCTION__ . ': unlinkPort() failed';
855 if (useDeleteBlade ('Port', 'id', $port_id) != TRUE)
856 return __FUNCTION__ . ': useDeleteBlade() failed';
857 return '';
858 }
859
860 function getAllIPv4Allocations ()
861 {
862 $query =
863 "select object_id as object_id, ".
864 "RackObject.name as object_name, ".
865 "IPBonds.name as name, ".
866 "INET_NTOA(ip) as ip ".
867 "from IPBonds join RackObject on id=object_id ";
868 $result = useSelectBlade ($query, __FUNCTION__);
869 $ret = array();
870 $count=0;
871 while ($row = $result->fetch (PDO::FETCH_ASSOC))
872 {
873 $ret[$count]['object_id']=$row['object_id'];
874 $ret[$count]['object_name']=$row['object_name'];
875 $ret[$count]['name']=$row['name'];
876 $ret[$count]['ip']=$row['ip'];
877 $count++;
878 }
879 $result->closeCursor();
880 return $ret;
881 }
882
883 function getEmptyPortsOfType ($type_id)
884 {
885 $query =
886 "select distinct Port.id as Port_id, ".
887 "Port.object_id as Port_object_id, ".
888 "RackObject.name as Object_name, ".
889 "Port.name as Port_name, ".
890 "Port.type as Port_type_id, ".
891 "dict_value as Port_type_name ".
892 "from ( ".
893 " ( ".
894 " Port inner join Dictionary on Port.type = dict_key natural join Chapter ".
895 " ) ".
896 " join RackObject on Port.object_id = RackObject.id ".
897 ") ".
898 "left join Link on Port.id=Link.porta or Port.id=Link.portb ".
899 "inner join PortCompat on Port.type = PortCompat.type2 ".
900 "where chapter_name = 'PortType' and PortCompat.type1 = '$type_id' and Link.porta is NULL ".
901 "and Port.reservation_comment is null order by Object_name, Port_name";
902 $result = useSelectBlade ($query, __FUNCTION__);
903 $ret = array();
904 $count=0;
905 while ($row = $result->fetch (PDO::FETCH_ASSOC))
906 {
907 $ret[$count]['Port_id']=$row['Port_id'];
908 $ret[$count]['Port_object_id']=$row['Port_object_id'];
909 $ret[$count]['Object_name']=$row['Object_name'];
910 $ret[$count]['Port_name']=$row['Port_name'];
911 $ret[$count]['Port_type_id']=$row['Port_type_id'];
912 $ret[$count]['Port_type_name']=$row['Port_type_name'];
913 $count++;
914 }
915 $result->closeCursor();
916 return $ret;
917 }
918
919 function linkPorts ($porta, $portb)
920 {
921 if ($porta == $portb)
922 return "Ports can't be the same";
923 if ($porta > $portb)
924 {
925 $tmp = $porta;
926 $porta = $portb;
927 $portb = $tmp;
928 }
929 global $dbxlink;
930 $query1 = "insert into Link set porta='${porta}', portb='{$portb}'";
931 $query2 = "update Port set reservation_comment = NULL where id = ${porta} or id = ${portb} limit 2";
932 // FIXME: who cares about the return value?
933 $result = $dbxlink->exec ($query1);
934 $result = $dbxlink->exec ($query2);
935 return '';
936 }
937
938 function unlinkPort ($port)
939 {
940 global $dbxlink;
941 $query =
942 "delete from Link where porta='$port' or portb='$port'";
943 $result = $dbxlink->exec ($query);
944 return '';
945 }
946
947 // Return all IPv4 addresses allocated to the objects. Attach detailed
948 // info about address to each alocation records. Index result by dotted-quad
949 // address.
950 function getObjectIPv4Allocations ($object_id = 0)
951 {
952 $ret = array();
953 $query = 'select name as osif, type, inet_ntoa(ip) as dottedquad from IPBonds ' .
954 "where object_id = ${object_id} " .
955 'order by ip';
956 $result = useSelectBlade ($query, __FUNCTION__);
957 // don't spawn a sub-query with unfetched buffer, it may fail
958 while ($row = $result->fetch (PDO::FETCH_ASSOC))
959 $ret[$row['dottedquad']] = array ('osif' => $row['osif'], 'type' => $row['type']);
960 unset ($result);
961 foreach (array_keys ($ret) as $dottedquad)
962 $ret[$dottedquad]['addrinfo'] = getIPv4Address ($dottedquad);
963 return $ret;
964 }
965
966 // Return minimal IPv4 address, optionally with "ip" key set, if requested.
967 function constructIPv4Address ($dottedquad = NULL)
968 {
969 $ret = array
970 (
971 'name' => '',
972 'reserved' => 'no',
973 'outpf' => array(),
974 'inpf' => array(),
975 'rslist' => array(),
976 'allocs' => array(),
977 'lblist' => array()
978 );
979 if ($dottedquad != NULL)
980 $ret['ip'] = $dottedquad;
981 return $ret;
982 }
983
984 // Check the range requested for meaningful IPv4 records, build them
985 // into a list and return. Return an empty list if nothing matched.
986 // Both arguments are expected in signed int32 form. The resulting list
987 // is keyed by uint32 form of each IP address, items aren't sorted.
988 // LATER: accept a list of pairs and build WHERE sub-expression accordingly
989 function scanIPv4Space ($pairlist)
990 {
991 $ret = array();
992 if (!count ($pairlist)) // this is normal for a network completely divided into smaller parts
993 return $ret;;
994 $dnamechache = array();
995 // FIXME: this is a copy-and-paste prototype
996 $or = '';
997 $whereexpr1 = '(';
998 $whereexpr2 = '(';
999 $whereexpr3 = '(';
1000 $whereexpr4 = '(';
1001 $whereexpr5a = '(';
1002 $whereexpr5b = '(';
1003 foreach ($pairlist as $tmp)
1004 {
1005 $db_first = sprintf ('%u', 0x00000000 + $tmp['i32_first']);
1006 $db_last = sprintf ('%u', 0x00000000 + $tmp['i32_last']);
1007 $whereexpr1 .= $or . "ip between ${db_first} and ${db_last}";
1008 $whereexpr2 .= $or . "ip between ${db_first} and ${db_last}";
1009 $whereexpr3 .= $or . "vip between ${db_first} and ${db_last}";
1010 $whereexpr4 .= $or . "rsip between ${db_first} and ${db_last}";
1011 $whereexpr5a .= $or . "remoteip between ${db_first} and ${db_last}";
1012 $whereexpr5b .= $or . "localip between ${db_first} and ${db_last}";
1013 $or = ' or ';
1014 }
1015 $whereexpr1 .= ')';
1016 $whereexpr2 .= ')';
1017 $whereexpr3 .= ')';
1018 $whereexpr4 .= ')';
1019 $whereexpr5a .= ')';
1020 $whereexpr5b .= ')';
1021
1022 // 1. collect labels and reservations
1023 $query = "select INET_NTOA(ip) as ip, name, reserved from IPAddress ".
1024 "where ${whereexpr1} and (reserved = 'yes' or name != '')";
1025 $result = useSelectBlade ($query, __FUNCTION__);
1026 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1027 {
1028 $ip_bin = ip2long ($row['ip']);
1029 if (!isset ($ret[$ip_bin]))
1030 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1031 $ret[$ip_bin]['name'] = $row['name'];
1032 $ret[$ip_bin]['reserved'] = $row['reserved'];
1033 }
1034 unset ($result);
1035
1036 // 2. check for allocations
1037 $query =
1038 "select INET_NTOA(ipb.ip) as ip, ro.id as object_id, " .
1039 "ro.name as object_name, ipb.name, ipb.type, objtype_id, " .
1040 "dict_value as objtype_name from " .
1041 "IPBonds as ipb inner join RackObject as ro on ipb.object_id = ro.id " .
1042 "left join Dictionary on objtype_id=dict_key natural join Chapter " .
1043 "where ${whereexpr2} " .
1044 "and chapter_name = 'RackObjectType'" .
1045 "order by ipb.type, object_name";
1046 $result = useSelectBlade ($query, __FUNCTION__);
1047 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1048 {
1049 $ip_bin = ip2long ($row['ip']);
1050 if (!isset ($ret[$ip_bin]))
1051 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1052 if (!isset ($dnamecache[$row['object_id']]))
1053 {
1054 $quasiobject['name'] = $row['object_name'];
1055 $quasiobject['objtype_id'] = $row['objtype_id'];
1056 $quasiobject['objtype_name'] = $row['objtype_name'];
1057 $dnamecache[$row['object_id']] = displayedName ($quasiobject);
1058 }
1059 $tmp = array();
1060 foreach (array ('object_id', 'type', 'name') as $cname)
1061 $tmp[$cname] = $row[$cname];
1062 $tmp['object_name'] = $dnamecache[$row['object_id']];
1063 $ret[$ip_bin]['allocs'][] = $tmp;
1064 }
1065 unset ($result);
1066
1067 // 3. look for virtual services and related LB
1068 $query = "select vs_id, inet_ntoa(vip) as ip, vport, proto, vs.name, " .
1069 "object_id, objtype_id, ro.name as object_name, dict_value as objtype_name from " .
1070 "IPVirtualService as vs inner join IPLoadBalancer as lb on vs.id = lb.vs_id " .
1071 "inner join RackObject as ro on lb.object_id = ro.id " .
1072 "left join Dictionary on objtype_id=dict_key " .
1073 "natural join Chapter " .
1074 "where ${whereexpr3} " .
1075 "and chapter_name = 'RackObjectType'" .
1076 "order by vport, proto, ro.name, object_id";
1077 $result = useSelectBlade ($query, __FUNCTION__);
1078 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1079 {
1080 $ip_bin = ip2long ($row['ip']);
1081 if (!isset ($ret[$ip_bin]))
1082 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1083 if (!isset ($dnamecache[$row['object_id']]))
1084 {
1085 $quasiobject['name'] = $row['object_name'];
1086 $quasiobject['objtype_id'] = $row['objtype_id'];
1087 $quasiobject['objtype_name'] = $row['objtype_name'];
1088 $dnamecache[$row['object_id']] = displayedName ($quasiobject);
1089 }
1090 $tmp = array();
1091 foreach (array ('object_id', 'vport', 'proto', 'vs_id', 'name') as $cname)
1092 $tmp[$cname] = $row[$cname];
1093 $tmp['object_name'] = $dnamecache[$row['object_id']];
1094 $tmp['vip'] = $row['ip'];
1095 $ret[$ip_bin]['lblist'][] = $tmp;
1096 }
1097 unset ($result);
1098
1099 // 4. don't forget about real servers along with pools
1100 $query = "select inet_ntoa(rsip) as ip, inservice, rsport, rspool_id, rsp.name as rspool_name from " .
1101 "IPRealServer as rs inner join IPRSPool as rsp on rs.rspool_id = rsp.id " .
1102 "where ${whereexpr4} " .
1103 "order by ip, rsport, rspool_id";
1104 $result = useSelectBlade ($query, __FUNCTION__);
1105 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1106 {
1107 $ip_bin = ip2long ($row['ip']);
1108 if (!isset ($ret[$ip_bin]))
1109 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1110 $tmp = array();
1111 foreach (array ('rspool_id', 'rsport', 'rspool_name', 'inservice') as $cname)
1112 $tmp[$cname] = $row[$cname];
1113 $ret[$ip_bin]['rslist'][] = $tmp;
1114 }
1115 unset ($result);
1116
1117 // 5. add NAT rules, part 1
1118 $query =
1119 "select " .
1120 "proto, " .
1121 "INET_NTOA(localip) as localip, " .
1122 "localport, " .
1123 "INET_NTOA(remoteip) as remoteip, " .
1124 "remoteport, " .
1125 "description " .
1126 "from PortForwarding " .
1127 "where ${whereexpr5a} " .
1128 "order by localip, localport, remoteip, remoteport, proto";
1129 $result = useSelectBlade ($query, __FUNCTION__);
1130 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1131 {
1132 $remoteip_bin = ip2long ($row['remoteip']);
1133 if (!isset ($ret[$remoteip_bin]))
1134 $ret[$remoteip_bin] = constructIPv4Address ($row['remoteip']);
1135 $ret[$remoteip_bin]['inpf'][] = $row;
1136 }
1137 unset ($result);
1138 // 5. add NAT rules, part 2
1139 $query =
1140 "select " .
1141 "proto, " .
1142 "INET_NTOA(localip) as localip, " .
1143 "localport, " .
1144 "INET_NTOA(remoteip) as remoteip, " .
1145 "remoteport, " .
1146 "description " .
1147 "from PortForwarding " .
1148 "where ${whereexpr5b} " .
1149 "order by localip, localport, remoteip, remoteport, proto";
1150 $result = useSelectBlade ($query, __FUNCTION__);
1151 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1152 {
1153 $localip_bin = ip2long ($row['localip']);
1154 if (!isset ($ret[$localip_bin]))
1155 $ret[$localip_bin] = constructIPv4Address ($row['localip']);
1156 $ret[$localip_bin]['outpf'][] = $row;
1157 }
1158 unset ($result);
1159 return $ret;
1160 }
1161
1162 // Return summary data about an IPv4 prefix, if it exists, or NULL otherwise.
1163 function getIPv4NetworkInfo ($id = 0)
1164 {
1165 if ($id <= 0)
1166 {
1167 showError ('Invalid arg', __FUNCTION__);
1168 return NULL;
1169 }
1170 $query = "select INET_NTOA(ip) as ip, mask, name ".
1171 "from IPRanges where id = $id";
1172 $result = useSelectBlade ($query, __FUNCTION__);
1173 $ret = $result->fetch (PDO::FETCH_ASSOC);
1174 if ($ret == NULL)
1175 return NULL;
1176 unset ($result);
1177 $ret['id'] = $id;
1178 $ret['ip_bin'] = ip2long ($ret['ip']);
1179 $ret['mask_bin'] = binMaskFromDec ($ret['mask']);
1180 $ret['mask_bin_inv'] = binInvMaskFromDec ($ret['mask']);
1181 $ret['db_first'] = sprintf ('%u', 0x00000000 + $ret['ip_bin'] & $ret['mask_bin']);
1182 $ret['db_last'] = sprintf ('%u', 0x00000000 + $ret['ip_bin'] | ($ret['mask_bin_inv']));
1183 return $ret;
1184 }
1185
1186 function getIPv4Address ($dottedquad = '')
1187 {
1188 if ($dottedquad == '')
1189 {
1190 showError ('Invalid arg', __FUNCTION__);
1191 return NULL;
1192 }
1193 $i32 = ip2long ($dottedquad); // signed 32 bit
1194 $scanres = scanIPv4Space (array (array ('i32_first' => $i32, 'i32_last' => $i32)));
1195 if (!isset ($scanres[$i32]))
1196 //$scanres[$i32] = constructIPv4Address ($dottedquad); // XXX: this should be verified to not break things
1197 return constructIPv4Address ($dottedquad);
1198 markupIPv4AddrList ($scanres);
1199 return $scanres[$i32];
1200 }
1201
1202 function bindIpToObject ($ip = '', $object_id = 0, $name = '', $type = '')
1203 {
1204 $result = useInsertBlade
1205 (
1206 'IPBonds',
1207 array
1208 (
1209 'ip' => "INET_ATON('$ip')",
1210 'object_id' => "'${object_id}'",
1211 'name' => "'${name}'",
1212 'type' => "'${type}'"
1213 )
1214 );
1215 return $result ? '' : (__FUNCTION__ . '(): useInsertBlade() failed');
1216 }
1217
1218 // Collect data necessary to build a tree. Calling functions should care about
1219 // setting the rest of data.
1220 function getIPv4NetworkList ($tagfilter = array(), $tfmode = 'any')
1221 {
1222 $whereclause = getWhereClause ($tagfilter);
1223 $query =
1224 "select distinct id, INET_NTOA(ip) as ip, mask, name " .
1225 "from IPRanges left join TagStorage on id = target_id and target_realm = 'ipv4net' " .
1226 "where true ${whereclause} order by IPRanges.ip";
1227 $result = useSelectBlade ($query, __FUNCTION__);
1228 $ret = array();
1229 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1230 {
1231 // ip_bin and mask are used by iptree_fill()
1232 $row['ip_bin'] = ip2long ($row['ip']);
1233 $ret[$row['id']] = $row;
1234 }
1235 // After all the keys are known we can update parent_id appropriately. Also we don't
1236 // run two queries in parallel this way.
1237 $keys = array_keys ($ret);
1238 foreach ($keys as $netid)
1239 {
1240 // parent_id is for treeFromList()
1241 $ret[$netid]['parent_id'] = getIPv4AddressNetworkId ($ret[$netid]['ip'], $ret[$netid]['mask']);
1242 if ($ret[$netid]['parent_id'] and !in_array ($ret[$netid]['parent_id'], $keys))
1243 {
1244 $ret[$netid]['real_parent_id'] = $ret[$netid]['parent_id'];
1245 $ret[$netid]['parent_id'] = NULL;
1246 }
1247 }
1248 return $ret;
1249 }
1250
1251 // Return the id of the smallest IPv4 network containing the given IPv4 address
1252 // or NULL, if nothing was found. When finding the covering network for
1253 // another network, it is important to filter out matched records with longer
1254 // masks (they aren't going to be the right pick).
1255 function getIPv4AddressNetworkId ($dottedquad, $masklen = 32)
1256 {
1257 // N.B. To perform the same for IPv6 address and networks, some pre-requisites
1258 // are necessary and a different query. IPv6 addresses are 128 bit long, which
1259 // is too much for both PHP and MySQL data types. These values must be split
1260 // into 4 32-byte long parts (b_u32_0, b_u32_1, b_u32_2, b_u32_3).
1261 // Then each network must have its 128-bit netmask split same way and either
1262 // stored right in its record or JOINed from decoder and accessible as m_u32_0,
1263 // m_u32_1, m_u32_2, m_u32_3. After that the query to pick the smallest network
1264 // covering the given address would look as follows:
1265 // $query = 'select id from IPv6Network as n where ' .
1266 // "(${b_u32_0} & n.m_u32_0 = n.b_u32_0) and " .
1267 // "(${b_u32_1} & n.m_u32_1 = n.b_u32_1) and " .
1268 // "(${b_u32_2} & n.m_u32_2 = n.b_u32_2) and " .
1269 // "(${b_u32_3} & n.m_u32_3 = n.b_u32_3) and " .
1270 // "mask < ${masklen} " .
1271 // 'order by mask desc limit 1';
1272
1273 $query = 'select id from IPRanges where ' .
1274 "inet_aton('${dottedquad}') & (4294967295 >> (32 - mask)) << (32 - mask) = ip " .
1275 "and mask < ${masklen} " .
1276 'order by mask desc limit 1';
1277 $result = useSelectBlade ($query, __FUNCTION__);
1278 if ($row = $result->fetch (PDO::FETCH_ASSOC))
1279 return $row['id'];
1280 return NULL;
1281 }
1282
1283 function updateRange ($id=0, $name='')
1284 {
1285 global $dbxlink;
1286 $query =
1287 "update IPRanges set name='$name' where id='$id'";
1288 $result = $dbxlink->exec ($query);
1289 return '';
1290 }
1291
1292 // This function is actually used not only to update, but also to create records,
1293 // that's why ON DUPLICATE KEY UPDATE was replaced by DELETE-INSERT pair
1294 // (MySQL 4.0 workaround).
1295 function updateAddress ($ip = 0, $name = '', $reserved = 'no')
1296 {
1297 // DELETE may safely fail.
1298 $r = useDeleteBlade ('IPAddress', 'ip', "INET_ATON('${ip}')");
1299 // INSERT may appear not necessary.
1300 if ($name == '' and $reserved == 'no')
1301 return '';
1302 if (useInsertBlade ('IPAddress', array ('name' => "'${name}'", 'reserved' => "'${reserved}'", 'ip' => "INET_ATON('${ip}')")))
1303 return '';
1304 else
1305 return __FUNCTION__ . '(): useInsertBlade() failed';
1306 }
1307
1308 function updateBond ($ip='', $object_id=0, $name='', $type='')
1309 {
1310 global $dbxlink;
1311
1312 $query =
1313 "update IPBonds set name='$name', type='$type' where ip=INET_ATON('$ip') and object_id='$object_id'";
1314 $result = $dbxlink->exec ($query);
1315 return '';
1316 }
1317
1318 function unbindIpFromObject ($ip='', $object_id=0)
1319 {
1320 global $dbxlink;
1321
1322 $query =
1323 "delete from IPBonds where ip=INET_ATON('$ip') and object_id='$object_id'";
1324 $result = $dbxlink->exec ($query);
1325 return '';
1326 }
1327
1328 // This function returns either all or one user account. Array key is user name.
1329 function getUserAccounts ($tagfilter = array(), $tfmode = 'any')
1330 {
1331 $whereclause = getWhereClause ($tagfilter);
1332 $query =
1333 'select user_id, user_name, user_password_hash, user_realname, user_enabled ' .
1334 'from UserAccount left join TagStorage ' .
1335 "on UserAccount.user_id = TagStorage.target_id and target_realm = 'user' " .
1336 "where true ${whereclause} " .
1337 'order by user_name';
1338 $result = useSelectBlade ($query, __FUNCTION__);
1339 $ret = array();
1340 $clist = array ('user_id', 'user_name', 'user_realname', 'user_password_hash', 'user_enabled');
1341 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1342 foreach ($clist as $cname)
1343 $ret[$row['user_name']][$cname] = $row[$cname];
1344 $result->closeCursor();
1345 return $ret;
1346 }
1347
1348 function searchByl2address ($l2addr)
1349 {
1350 $l2addr = l2addressForDatabase ($l2addr);
1351 $query = "select object_id, Port.id as port_id from RackObject as ro inner join Port on ro.id = Port.object_id " .
1352 "where l2address = ${l2addr}";
1353 $result = useSelectBlade ($query, __FUNCTION__);
1354 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
1355 $result->closeCursor();
1356 if (count ($rows) == 0) // No results.
1357 return NULL;
1358 if (count ($rows) == 1) // Target found.
1359 return $rows[0];
1360 showError ('More than one results was found. This is probably a broken unique key.', __FUNCTION__);
1361 return NULL;
1362 }
1363
1364 function getIPv4PrefixSearchResult ($terms)
1365 {
1366 $query = "select id, inet_ntoa(ip) as ip, mask, name from IPRanges where ";
1367 $or = '';
1368 foreach (explode (' ', $terms) as $term)
1369 {
1370 $query .= $or . "name like '%${term}%'";
1371 $or = ' or ';
1372 }
1373 $result = useSelectBlade ($query, __FUNCTION__);
1374 $ret = array();
1375 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1376 $ret[] = $row;
1377 return $ret;
1378 }
1379
1380 function getIPv4AddressSearchResult ($terms)
1381 {
1382 $query = "select inet_ntoa(ip) as ip, name from IPAddress where ";
1383 $or = '';
1384 foreach (explode (' ', $terms) as $term)
1385 {
1386 $query .= $or . "name like '%${term}%'";
1387 $or = ' or ';
1388 }
1389 $result = useSelectBlade ($query, __FUNCTION__);
1390 $ret = array();
1391 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1392 $ret[] = $row;
1393 return $ret;
1394 }
1395
1396 function getIPv4RSPoolSearchResult ($terms)
1397 {
1398 $query = "select id as pool_id, name from IPRSPool where ";
1399 $or = '';
1400 foreach (explode (' ', $terms) as $term)
1401 {
1402 $query .= $or . "name like '%${term}%'";
1403 $or = ' or ';
1404 }
1405 $result = useSelectBlade ($query, __FUNCTION__);
1406 $ret = array();
1407 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1408 $ret[] = $row;
1409 return $ret;
1410 }
1411
1412 function getIPv4VServiceSearchResult ($terms)
1413 {
1414 $query = "select id, inet_ntoa(vip) as vip, vport, proto, name from IPVirtualService where ";
1415 $or = '';
1416 foreach (explode (' ', $terms) as $term)
1417 {
1418 $query .= $or . "name like '%${term}%'";
1419 $or = ' or ';
1420 }
1421 $result = useSelectBlade ($query, __FUNCTION__);
1422 $ret = array();
1423 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1424 $ret[] = $row;
1425 return $ret;
1426 }
1427
1428 function getAccountSearchResult ($terms)
1429 {
1430 $byUsername = getSearchResultByField
1431 (
1432 'UserAccount',
1433 array ('user_id', 'user_name', 'user_realname'),
1434 'user_name',
1435 $terms,
1436 'user_name'
1437 );
1438 $byRealname = getSearchResultByField
1439 (
1440 'UserAccount',
1441 array ('user_id', 'user_name', 'user_realname'),
1442 'user_realname',
1443 $terms,
1444 'user_name'
1445 );
1446 // Filter out dupes.
1447 foreach ($byUsername as $res1)
1448 foreach (array_keys ($byRealname) as $key2)
1449 if ($res1['user_id'] == $byRealname[$key2]['user_id'])
1450 {
1451 unset ($byRealname[$key2]);
1452 continue 2;
1453 }
1454 return array_merge ($byUsername, $byRealname);
1455 }
1456
1457 function getFileSearchResult ($terms)
1458 {
1459 $byFilename = getSearchResultByField
1460 (
1461 'File',
1462 array ('id', 'name', 'comment'),
1463 'name',
1464 $terms,
1465 'name'
1466 );
1467 $byComment = getSearchResultByField
1468 (
1469 'File',
1470 array ('id', 'name', 'comment'),
1471 'comment',
1472 $terms,
1473 'name'
1474 );
1475 // Filter out dupes.
1476 foreach ($byFilename as $res1)
1477 foreach (array_keys ($byComment) as $key2)
1478 if ($res1['id'] == $byComment[$key2]['id'])
1479 {
1480 unset ($byComment[$key2]);
1481 continue 2;
1482 }
1483 return array_merge ($byFilename, $byComment);
1484 }
1485
1486 function getSearchResultByField ($tname, $rcolumns, $scolumn, $terms, $ocolumn = '')
1487 {
1488 $pfx = '';
1489 $query = 'select ';
1490 foreach ($rcolumns as $col)
1491 {
1492 $query .= $pfx . $col;
1493 $pfx = ', ';
1494 }
1495 $pfx = '';
1496 $query .= " from ${tname} where ";
1497 foreach (explode (' ', $terms) as $term)
1498 {
1499 $query .= $pfx . "${scolumn} like '%${term}%'";
1500 $pfx = ' or ';
1501 }
1502 if ($ocolumn != '')
1503 $query .= " order by ${ocolumn}";
1504 $result = useSelectBlade ($query, __FUNCTION__);
1505 $ret = array();
1506 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1507 $ret[] = $row;
1508 return $ret;
1509 }
1510
1511 // This function returns either port ID or NULL for specified arguments.
1512 function getPortID ($object_id, $port_name)
1513 {
1514 $query = "select id from Port where object_id=${object_id} and name='${port_name}' limit 2";
1515 $result = useSelectBlade ($query, __FUNCTION__);
1516 $rows = $result->fetchAll (PDO::FETCH_NUM);
1517 if (count ($rows) != 1)
1518 return NULL;
1519 $ret = $rows[0][0];
1520 $result->closeCursor();
1521 return $ret;
1522 }
1523
1524 function commitCreateUserAccount ($username, $realname, $password)
1525 {
1526 return useInsertBlade
1527 (
1528 'UserAccount',
1529 array
1530 (
1531 'user_name' => "'${username}'",
1532 'user_realname' => "'${realname}'",
1533 'user_password_hash' => "'${password}'"
1534 )
1535 );
1536 }
1537
1538 function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
1539 {
1540 global $dbxlink;
1541 $query =
1542 "update UserAccount set user_name = '${new_username}', user_realname = '${new_realname}', " .
1543 "user_password_hash = '${new_password}' where user_id = ${id} limit 1";
1544 $result = $dbxlink->query ($query);
1545 if ($result == NULL)
1546 {
1547 showError ('SQL query failed', __FUNCTION__);
1548 die;
1549 }
1550 return TRUE;
1551 }
1552
1553 function commitEnableUserAccount ($id, $new_enabled_value)
1554 {
1555 global $dbxlink;
1556 $query =
1557 "update UserAccount set user_enabled = '${new_enabled_value}' " .
1558 "where user_id = ${id} limit 1";
1559 $result = $dbxlink->query ($query);
1560 if ($result == NULL)
1561 {
1562 showError ('SQL query failed', __FUNCTION__);
1563 die;
1564 }
1565 return TRUE;
1566 }
1567
1568 // This function returns an array of all port type pairs from PortCompat table.
1569 function getPortCompat ()
1570 {
1571 $query =
1572 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
1573 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
1574 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
1575 "inner join Chapter as c1 on d1.chapter_no = c1.chapter_no " .
1576 "inner join Chapter as c2 on d2.chapter_no = c2.chapter_no " .
1577 "where c1.chapter_name = 'PortType' and c2.chapter_name = 'PortType'";
1578 $result = useSelectBlade ($query, __FUNCTION__);
1579 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
1580 $result->closeCursor();
1581 return $ret;
1582 }
1583
1584 function removePortCompat ($type1 = 0, $type2 = 0)
1585 {
1586 global $dbxlink;
1587 if ($type1 == 0 or $type2 == 0)
1588 {
1589 showError ('Invalid arguments', __FUNCTION__);
1590 die;
1591 }
1592 $query = "delete from PortCompat where type1 = ${type1} and type2 = ${type2} limit 1";
1593 $result = $dbxlink->query ($query);
1594 if ($result == NULL)
1595 {
1596 showError ('SQL query failed', __FUNCTION__);
1597 die;
1598 }
1599 return TRUE;
1600 }
1601
1602 function addPortCompat ($type1 = 0, $type2 = 0)
1603 {
1604 if ($type1 <= 0 or $type2 <= 0)
1605 {
1606 showError ('Invalid arguments', __FUNCTION__);
1607 die;
1608 }
1609 return useInsertBlade
1610 (
1611 'PortCompat',
1612 array ('type1' => $type1, 'type2' => $type2)
1613 );
1614 }
1615
1616 // This function returns the dictionary as an array of trees, each tree
1617 // representing a single chapter. Each element has 'id', 'name', 'sticky'
1618 // and 'word' keys with the latter holding all the words within the chapter.
1619 function getDict ($parse_links = FALSE)
1620 {
1621 $query1 =
1622 "select chapter_name, Chapter.chapter_no, dict_key, dict_value, sticky from " .
1623 "Chapter natural left join Dictionary order by chapter_name, dict_value";
1624 $result = useSelectBlade ($query1, __FUNCTION__);
1625 $dict = array();
1626 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1627 {
1628 $chapter_no = $row['chapter_no'];
1629 if (!isset ($dict[$chapter_no]))
1630 {
1631 $dict[$chapter_no]['no'] = $chapter_no;
1632 $dict[$chapter_no]['name'] = $row['chapter_name'];
1633 $dict[$chapter_no]['sticky'] = $row['sticky'] == 'yes' ? TRUE : FALSE;
1634 $dict[$chapter_no]['word'] = array();
1635 }
1636 if ($row['dict_key'] != NULL)
1637 {
1638 $dict[$chapter_no]['word'][$row['dict_key']] = $parse_links ?
1639 parseWikiLink ($row['dict_value'], 'a') : $row['dict_value'];
1640 $dict[$chapter_no]['refcnt'][$row['dict_key']] = 0;
1641 }
1642 }
1643 $result->closeCursor();
1644 unset ($result);
1645 // Find the list of all assigned values of dictionary-addressed attributes, each with
1646 // chapter/word keyed reference counters. Use the structure to adjust reference counters
1647 // of the returned disctionary words.
1648 $query2 = "select a.attr_id, am.chapter_no, uint_value, count(object_id) as refcnt " .
1649 "from Attribute as a inner join AttributeMap as am on a.attr_id = am.attr_id " .
1650 "inner join AttributeValue as av on a.attr_id = av.attr_id " .
1651 "inner join Dictionary as d on am.chapter_no = d.chapter_no and av.uint_value = d.dict_key " .
1652 "where attr_type = 'dict' group by a.attr_id, am.chapter_no, uint_value " .
1653 "order by a.attr_id, am.chapter_no, uint_value";
1654 $result = useSelectBlade ($query2, __FUNCTION__);
1655 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1656 $dict[$row['chapter_no']]['refcnt'][$row['uint_value']] = $row['refcnt'];
1657 $result->closeCursor();
1658 return $dict;
1659 }
1660
1661 function getDictStats ()
1662 {
1663 $stock_chapters = array (1, 2, 3, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23);
1664 $query =
1665 "select Chapter.chapter_no, chapter_name, count(dict_key) as wc from " .
1666 "Chapter natural left join Dictionary group by Chapter.chapter_no";
1667 $result = useSelectBlade ($query, __FUNCTION__);
1668 $tc = $tw = $uc = $uw = 0;
1669 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1670 {
1671 $tc++;
1672 $tw += $row['wc'];;
1673 if (in_array ($row['chapter_no'], $stock_chapters))
1674 continue;
1675 $uc++;
1676 $uw += $row['wc'];;
1677 }
1678 $result->closeCursor();
1679 unset ($result);
1680 $query = "select count(attr_id) as attrc from RackObject as ro left join " .
1681 "AttributeValue as av on ro.id = av.object_id group by ro.id";
1682 $result = useSelectBlade ($query, __FUNCTION__);
1683 $to = $ta = $so = 0;
1684 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1685 {
1686 $to++;
1687 if ($row['attrc'] != 0)
1688 {
1689 $so++;
1690 $ta += $row['attrc'];
1691 }
1692 }
1693 $result->closeCursor();
1694 $ret = array();
1695 $ret['Total chapters in dictionary'] = $tc;
1696 $ret['Total words in dictionary'] = $tw;
1697 $ret['User chapters'] = $uc;
1698 $ret['Words in user chapters'] = $uw;
1699 $ret['Total objects'] = $to;
1700 $ret['Objects with stickers'] = $so;
1701 $ret['Total stickers attached'] = $ta;
1702 return $ret;
1703 }
1704
1705 function getIPv4Stats ()
1706 {
1707 $ret = array();
1708 $subject = array();
1709 $subject[] = array ('q' => 'select count(id) from IPRanges', 'txt' => 'Networks');
1710 $subject[] = array ('q' => 'select count(ip) from IPAddress', 'txt' => 'Addresses commented/reserved');
1711 $subject[] = array ('q' => 'select count(ip) from IPBonds', 'txt' => 'Addresses allocated');
1712 $subject[] = array ('q' => 'select count(*) from PortForwarding', 'txt' => 'NAT rules');
1713 $subject[] = array ('q' => 'select count(id) from IPVirtualService', 'txt' => 'Virtual services');
1714 $subject[] = array ('q' => 'select count(id) from IPRSPool', 'txt' => 'Real server pools');
1715 $subject[] = array ('q' => 'select count(id) from IPRealServer', 'txt' => 'Real servers');
1716 $subject[] = array ('q' => 'select count(distinct object_id) from IPLoadBalancer', 'txt' => 'Load balancers');
1717
1718 foreach ($subject as $item)
1719 {
1720 $result = useSelectBlade ($item['q'], __FUNCTION__);
1721 $row = $result->fetch (PDO::FETCH_NUM);
1722 $ret[$item['txt']] = $row[0];
1723 $result->closeCursor();
1724 unset ($result);
1725 }
1726 return $ret;
1727 }
1728
1729 function getRackspaceStats ()
1730 {
1731 $ret = array();
1732 $subject = array();
1733 $subject[] = array ('q' => 'select count(*) from Dictionary where chapter_no = 3', 'txt' => 'Rack rows');
1734 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
1735 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
1736 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
1737
1738 foreach ($subject as $item)
1739 {
1740 $result = useSelectBlade ($item['q'], __FUNCTION__);
1741 $row = $result->fetch (PDO::FETCH_NUM);
1742 $ret[$item['txt']] = empty ($row[0]) ? 0 : $row[0];
1743 $result->closeCursor();
1744 unset ($result);
1745 }
1746 return $ret;
1747 }
1748
1749 function renderTagStats ()
1750 {
1751 global $taglist, $root;
1752 $query = "select id, tag, count(tag_id) as refcnt from " .
1753 "TagTree inner join TagStorage on TagTree.id = TagStorage.tag_id " .
1754 "group by tag_id order by refcnt desc limit 50";
1755 // The same data is already present in pre-loaded tag list, but not in
1756 // the form we need. So let's ask the DB server for cooked top list and
1757 // use the cooked tag list to break it down.
1758 $result = useSelectBlade ($query, __FUNCTION__);
1759 $refc = $result->fetchAll (PDO::FETCH_ASSOC);
1760 echo '<table border=1><tr><th>tag</th><th>total</th><th>objects</th><th>IPv4 nets</th><th>racks</th>';
1761 echo '<th>IPv4 VS</th><th>IPv4 RS pools</th><th>users</th><th>files</th></tr>';
1762 $pagebyrealm = array
1763 (
1764 'file' => 'filesbylink&entity_type=all',
1765 'ipv4net' => 'ipv4space&tab=default',
1766 'ipv4vs' => 'ipv4vslist&tab=default',
1767 'ipv4rspool' => 'ipv4rsplist&tab=default',
1768 'object' => 'objgroup&group_id=0',
1769 'rack' => 'rackspace&tab=default',
1770 'user' => 'userlist&tab=default'
1771 );
1772 foreach ($refc as $ref)
1773 {
1774 echo "<tr><td>${ref['tag']}</td><td>${ref['refcnt']}</td>";
1775 foreach (array ('object', 'ipv4net', 'rack', 'ipv4vs', 'ipv4rspool', 'user', 'file') as $realm)
1776 {
1777 echo '<td>';
1778 if (!isset ($taglist[$ref['id']]['refcnt'][$realm]))
1779 echo '&nbsp;';
1780 else
1781 {
1782 echo "<a href='${root}?page=" . $pagebyrealm[$realm] . "&tagfilter[]=${ref['id']}'>";
1783 echo $taglist[$ref['id']]['refcnt'][$realm] . '</a>';
1784 }
1785 echo '</td>';
1786 }
1787 echo '</tr>';
1788 }
1789 echo '</table>';
1790 }
1791
1792 /*
1793
1794 The following allows figuring out records in TagStorage, which refer to non-existing entities:
1795
1796 mysql> select target_id from TagStorage left join Files on target_id = id where target_realm = 'file' and id is null;
1797 mysql> select target_id from TagStorage left join IPRanges on target_id = id where target_realm = 'ipv4net' and id is null;
1798 mysql> select target_id from TagStorage left join RackObject on target_id = id where target_realm = 'object' and id is null;
1799 mysql> select target_id from TagStorage left join Rack on target_id = id where target_realm = 'rack' and id is null;
1800 mysql> select target_id from TagStorage left join IPVirtualService on target_id = id where target_realm = 'ipv4vs' and id is null;
1801 mysql> select target_id from TagStorage left join IPRSPool on target_id = id where target_realm = 'ipv4rspool' and id is null;
1802 mysql> select target_id from TagStorage left join UserAccount on target_id = user_id where target_realm = 'user' and user_id is null;
1803
1804 Accordingly, these are the records, which refer to non-existent tags:
1805
1806 mysql> select tag_id from TagStorage left join TagTree on tag_id = id where id is null;
1807
1808 */
1809
1810 function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1811 {
1812 if ($chapter_no <= 0 or $dict_key <= 0 or empty ($dict_value))
1813 {
1814 showError ('Invalid args', __FUNCTION__);
1815 die;
1816 }
1817 global $dbxlink;
1818 $query =
1819 "update Dictionary set dict_value = '${dict_value}' where chapter_no=${chapter_no} " .
1820 "and dict_key=${dict_key} limit 1";
1821 $result = $dbxlink->query ($query);
1822 if ($result == NULL)
1823 {
1824 showError ('SQL query failed', __FUNCTION__);
1825 die;
1826 }
1827 return TRUE;
1828 }
1829
1830 function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1831 {
1832 if ($chapter_no <= 0 or empty ($dict_value))
1833 {
1834 showError ('Invalid args', __FUNCTION__);
1835 die;
1836 }
1837 return useInsertBlade
1838 (
1839 'Dictionary',
1840 array ('chapter_no' => $chapter_no, 'dict_value' => "'${dict_value}'")
1841 );
1842 }
1843
1844 function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1845 {
1846 if ($chapter_no <= 0 or $dict_key <= 0)
1847 {
1848 showError ('Invalid args', __FUNCTION__);
1849 die;
1850 }
1851 global $dbxlink;
1852 $query =
1853 "delete from Dictionary where chapter_no=${chapter_no} " .
1854 "and dict_key=${dict_key} limit 1";
1855 $result = $dbxlink->query ($query);
1856 if ($result == NULL)
1857 {
1858 showError ('SQL query failed', __FUNCTION__);
1859 die;
1860 }
1861 return TRUE;
1862 }
1863
1864 function commitAddChapter ($chapter_name = '')
1865 {
1866 if (empty ($chapter_name))
1867 {
1868 showError ('Invalid args', __FUNCTION__);
1869 die;
1870 }
1871 return useInsertBlade
1872 (
1873 'Chapter',
1874 array ('chapter_name' => "'${chapter_name}'")
1875 );
1876 }
1877
1878 function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
1879 {
1880 if ($chapter_no <= 0 or empty ($chapter_name))
1881 {
1882 showError ('Invalid args', __FUNCTION__);
1883 die;
1884 }
1885 global $dbxlink;
1886 $query =
1887 "update Chapter set chapter_name = '${chapter_name}' where chapter_no = ${chapter_no} " .
1888 "and sticky = 'no' limit 1";
1889 $result = $dbxlink->query ($query);
1890 if ($result == NULL)
1891 {
1892 showError ('SQL query failed', __FUNCTION__);
1893 die;
1894 }
1895 return TRUE;
1896 }
1897
1898 function commitDeleteChapter ($chapter_no = 0)
1899 {
1900 if ($chapter_no <= 0)
1901 {
1902 showError ('Invalid args', __FUNCTION__);
1903 die;
1904 }
1905 global $dbxlink;
1906 $query =
1907 "delete from Chapter where chapter_no = ${chapter_no} and sticky = 'no' limit 1";
1908 $result = $dbxlink->query ($query);
1909 if ($result == NULL)
1910 {
1911 showError ('SQL query failed', __FUNCTION__);
1912 die;
1913 }
1914 return TRUE;
1915 }
1916
1917 // This is a dictionary accessor. We perform link rendering, so the user sees
1918 // nice <select> drop-downs.
1919 function readChapter ($chapter_name = '')
1920 {
1921 if (empty ($chapter_name))
1922 {
1923 showError ('invalid argument', __FUNCTION__);
1924 return NULL;
1925 }
1926 $query =
1927 "select dict_key, dict_value from Dictionary natural join Chapter " .
1928 "where chapter_name = '${chapter_name}'";
1929 $result = useSelectBlade ($query, __FUNCTION__);
1930 $chapter = array();
1931 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1932 $chapter[$row['dict_key']] = parseWikiLink ($row['dict_value'], 'o');
1933 $result->closeCursor();
1934 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
1935 asort ($chapter);
1936 return $chapter;
1937 }
1938
1939 function getAttrMap ()
1940 {
1941 $query =
1942 "select a.attr_id, a.attr_type, a.attr_name, am.objtype_id, " .
1943 "d.dict_value as objtype_name, am.chapter_no, c2.chapter_name from " .
1944 "Attribute as a natural left join AttributeMap as am " .
1945 "left join Dictionary as d on am.objtype_id = d.dict_key " .
1946 "left join Chapter as c1 on d.chapter_no = c1.chapter_no " .
1947 "left join Chapter as c2 on am.chapter_no = c2.chapter_no " .
1948 "where c1.chapter_name = 'RackObjectType' or c1.chapter_name is null " .
1949 "order by attr_name";
1950 $result = useSelectBlade ($query, __FUNCTION__);
1951 $ret = array();
1952 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1953 {
1954 $attr_id = $row['attr_id'];
1955 if (!isset ($ret[$attr_id]))
1956 {
1957 $ret[$attr_id]['id'] = $attr_id;
1958 $ret[$attr_id]['type'] = $row['attr_type'];
1959 $ret[$attr_id]['name'] = $row['attr_name'];
1960 $ret[$attr_id]['application'] = array();
1961 }
1962 if ($row['objtype_id'] == '')
1963 continue;
1964 $application['objtype_id'] = $row['objtype_id'];
1965 $application['objtype_name'] = $row['objtype_name'];
1966 if ($row['attr_type'] == 'dict')
1967 {
1968 $application['chapter_no'] = $row['chapter_no'];
1969 $application['chapter_name'] = $row['chapter_name'];
1970 }
1971 $ret[$attr_id]['application'][] = $application;
1972 }
1973 $result->closeCursor();
1974 return $ret;
1975 }
1976
1977 function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
1978 {
1979 if ($attr_id <= 0 or empty ($attr_name))
1980 {
1981 showError ('Invalid args', __FUNCTION__);
1982 die;
1983 }
1984 global $dbxlink;
1985 $query =
1986 "update Attribute set attr_name = '${attr_name}' " .
1987 "where attr_id = ${attr_id} limit 1";
1988 $result = $dbxlink->query ($query);
1989 if ($result == NULL)
1990 {
1991 showError ("SQL query '${query}' failed", __FUNCTION__);
1992 die;
1993 }
1994 return TRUE;
1995 }
1996
1997 function commitAddAttribute ($attr_name = '', $attr_type = '')
1998 {
1999 if (empty ($attr_name))
2000 {
2001 showError ('Invalid args', __FUNCTION__);
2002 die;
2003 }
2004 switch ($attr_type)
2005 {
2006 case 'uint':
2007 case 'float':
2008 case 'string':
2009 case 'dict':
2010 break;
2011 default:
2012 showError ('Invalid args', __FUNCTION__);
2013 die;
2014 }
2015 return useInsertBlade
2016 (
2017 'Attribute',
2018 array ('attr_name' => "'${attr_name}'", 'attr_type' => "'${attr_type}'")
2019 );
2020 }
2021
2022 function commitDeleteAttribute ($attr_id = 0)
2023 {
2024 if ($attr_id <= 0)
2025 {
2026 showError ('Invalid args', __FUNCTION__);
2027 die;
2028 }
2029 return useDeleteBlade ('Attribute', 'attr_id', $attr_id);
2030 }
2031
2032 // FIXME: don't store garbage in chapter_no for non-dictionary types.
2033 function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
2034 {
2035 if ($attr_id <= 0 or $objtype_id <= 0 or $chapter_no <= 0)
2036 {
2037 showError ('Invalid args', __FUNCTION__);
2038 die;
2039 }
2040 return useInsertBlade
2041 (
2042 'AttributeMap',
2043 array
2044 (
2045 'attr_id' => $attr_id,
2046 'objtype_id' => $objtype_id,
2047 'chapter_no' => $chapter_no
2048 )
2049 );
2050 }
2051
2052 function commitReduceAttrMap ($attr_id = 0, $objtype_id)
2053 {
2054 if ($attr_id <= 0 or $objtype_id <= 0)
2055 {
2056 showError ('Invalid args', __FUNCTION__);
2057 die;
2058 }
2059 global $dbxlink;
2060 $query =
2061 "delete from AttributeMap where attr_id=${attr_id} " .
2062 "and objtype_id=${objtype_id} limit 1";
2063 $result = $dbxlink->query ($query);
2064 if ($result == NULL)
2065 {
2066 showError ('SQL query failed', __FUNCTION__);
2067 die;
2068 }
2069 return TRUE;
2070 }
2071
2072 // This function returns all optional attributes for requested object
2073 // as an array of records. NULL is returned on error and empty array
2074 // is returned, if there are no attributes found.
2075 function getAttrValues ($object_id, $strip_optgroup = FALSE)
2076 {
2077 if ($object_id <= 0)
2078 {
2079 showError ('Invalid argument', __FUNCTION__);
2080 return NULL;
2081 }
2082 $ret = array();
2083 $query =
2084 "select A.attr_id, A.attr_name, A.attr_type, C.chapter_name, " .
2085 "AV.uint_value, AV.float_value, AV.string_value, D.dict_value from " .
2086 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
2087 "inner join Attribute as A using (attr_id) " .
2088 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
2089 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_no = D.chapter_no " .
2090 "left join Chapter as C on AM.chapter_no = C.chapter_no " .
2091 "where RO.id = ${object_id} order by A.attr_type, A.attr_name";
2092 $result = useSelectBlade ($query, __FUNCTION__);
2093 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2094 {
2095 $record = array();
2096 $record['id'] = $row['attr_id'];
2097 $record['name'] = $row['attr_name'];
2098 $record['type'] = $row['attr_type'];
2099 switch ($row['attr_type'])
2100 {
2101 case 'uint':
2102 case 'float':
2103 case 'string':
2104 $record['value'] = $row[$row['attr_type'] . '_value'];
2105 $record['a_value'] = parseWikiLink ($record['value'], 'a');
2106 break;
2107 case 'dict':
2108 $record['value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'o', $strip_optgroup);
2109 $record['a_value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'a', $strip_optgroup);
2110 $record['chapter_name'] = $row['chapter_name'];
2111 $record['key'] = $row['uint_value'];
2112 break;
2113 default:
2114 $record['value'] = NULL;
2115 break;
2116 }
2117 $ret[$row['attr_id']] = $record;
2118 }
2119 $result->closeCursor();
2120 return $ret;
2121 }
2122
2123 function commitResetAttrValue ($object_id = 0, $attr_id = 0)
2124 {
2125 if ($object_id <= 0 or $attr_id <= 0)
2126 {
2127 showError ('Invalid arguments', __FUNCTION__);
2128 die;
2129 }
2130 global $dbxlink;
2131 $query = "delete from AttributeValue where object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2132 $result = $dbxlink->query ($query);
2133 if ($result == NULL)
2134 {
2135 showError ('SQL query failed', __FUNCTION__);
2136 die;
2137 }
2138 return TRUE;
2139 }
2140
2141 // FIXME: don't share common code with use commitResetAttrValue()
2142 function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
2143 {
2144 if ($object_id <= 0 or $attr_id <= 0)
2145 {
2146 showError ('Invalid arguments', __FUNCTION__);
2147 die;
2148 }
2149 if (empty ($value))
2150 return commitResetAttrValue ($object_id, $attr_id);
2151 global $dbxlink;
2152 $query1 = "select attr_type from Attribute where attr_id = ${attr_id}";
2153 $result = $dbxlink->query ($query1);
2154 if ($result == NULL)
2155 {
2156 showError ('SQL query #1 failed', __FUNCTION__);
2157 die;
2158 }
2159 $row = $result->fetch (PDO::FETCH_NUM);
2160 if ($row == NULL)
2161 {
2162 showError ('SQL query #1 returned no results', __FUNCTION__);
2163 die;
2164 }
2165 $attr_type = $row[0];
2166 $result->closeCursor();
2167 switch ($attr_type)
2168 {
2169 case 'uint':
2170 case 'float':
2171 case 'string':
2172 $column = $attr_type . '_value';
2173 break;
2174 case 'dict':
2175 $column = 'uint_value';
2176 break;
2177 default:
2178 showError ("Unknown attribute type '${attr_type}' met", __FUNCTION__);
2179 die;
2180 }
2181 $query2 =
2182 "delete from AttributeValue where " .
2183 "object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2184 $result = $dbxlink->query ($query2);
2185 if ($result == NULL)
2186 {
2187 showError ('SQL query #2 failed', __FUNCTION__);
2188 die;
2189 }
2190 // We know $value isn't empty here.
2191 $query3 =
2192 "insert into AttributeValue set ${column} = '${value}', " .
2193 "object_id = ${object_id}, attr_id = ${attr_id} ";
2194 $result = $dbxlink->query ($query3);
2195 if ($result == NULL)
2196 {
2197 showError ('SQL query #3 failed', __FUNCTION__);
2198 die;
2199 }
2200 return TRUE;
2201 }
2202
2203 function commitUseupPort ($port_id = 0)
2204 {
2205 if ($port_id <= 0)
2206 {
2207 showError ("Invalid argument", __FUNCTION__);
2208 die;
2209 }
2210 global $dbxlink;
2211 $query = "update Port set reservation_comment = NULL where id = ${port_id} limit 1";
2212 $result = $dbxlink->exec ($query);
2213 if ($result == NULL)
2214 {
2215 showError ("SQL query failed", __FUNCTION__);
2216 die;
2217 }
2218 return TRUE;
2219
2220 }
2221
2222 // This is a swiss-knife blade to insert a record into a table.
2223 // The first argument is table name.
2224 // The second argument is an array of "name" => "value" pairs.
2225 // The function returns either TRUE or FALSE (we expect one row
2226 // to be inserted).
2227 function useInsertBlade ($tablename, $values)
2228 {
2229 global $dbxlink;
2230 $namelist = $valuelist = '';
2231 foreach ($values as $name => $value)
2232 {
2233 $namelist = $namelist . ($namelist == '' ? "(${name}" : ", ${name}");
2234 $valuelist = $valuelist . ($valuelist == '' ? "(${value}" : ", ${value}");
2235 }
2236 $query = "insert into ${tablename} ${namelist}) values ${valuelist})";
2237 $result = $dbxlink->exec ($query);
2238 if ($result != 1)
2239 return FALSE;
2240 return TRUE;
2241 }
2242
2243 // This swiss-knife blade deletes one record from the specified table
2244 // using the specified key name and value.
2245 function useDeleteBlade ($tablename, $keyname, $keyvalue)
2246 {
2247 global $dbxlink;
2248 return 1 === $dbxlink->exec ("delete from ${tablename} where ${keyname}=${keyvalue} limit 1");
2249 }
2250
2251 function useSelectBlade ($query, $caller = 'N/A')
2252 {
2253 global $dbxlink;
2254 $result = $dbxlink->query ($query);
2255 if ($result == NULL)
2256 {
2257 $ei = $dbxlink->errorInfo();
2258 showError ("SQL query '${query}'\n failed in useSelectBlade with error ${ei[1]} (${ei[2]})", $caller);
2259 return NULL;
2260 }
2261 return $result;
2262 }
2263
2264 function loadConfigCache ()
2265 {
2266 $query = 'SELECT varname, varvalue, vartype, is_hidden, emptyok, description FROM Config ORDER BY varname';
2267 $result = useSelectBlade ($query, __FUNCTION__);
2268 $cache = array();
2269 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2270 $cache[$row['varname']] = $row;
2271 $result->closeCursor();
2272 return $cache;
2273 }
2274
2275 // setConfigVar() is expected to perform all necessary filtering
2276 function storeConfigVar ($varname = NULL, $varvalue = NULL)
2277 {
2278 global $dbxlink;
2279 if (empty ($varname) || $varvalue === NULL)
2280 {
2281 showError ('Invalid arguments', __FUNCTION__);
2282 return FALSE;
2283 }
2284 $query = "update Config set varvalue='${varvalue}' where varname='${varname}' limit 1";
2285 $result = $dbxlink->query ($query);
2286 if ($result == NULL)
2287 {
2288 showError ("SQL query '${query}' failed", __FUNCTION__);
2289 return FALSE;
2290 }
2291 $rc = $result->rowCount();
2292 $result->closeCursor();
2293 if ($rc == 0 or $rc == 1)
2294 return TRUE;
2295 showError ("Something went wrong for args '${varname}', '${varvalue}'", __FUNCTION__);
2296 return FALSE;
2297 }
2298
2299 // Database version detector. Should behave corretly on any
2300 // working dataset a user might have.
2301 function getDatabaseVersion ()
2302 {
2303 global $dbxlink;
2304 $query = "select varvalue from Config where varname = 'DB_VERSION' and vartype = 'string'";
2305 $result = $dbxlink->query ($query);
2306 if ($result == NULL)
2307 {
2308 $errorInfo = $dbxlink->errorInfo();
2309 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
2310 return '0.14.4';
2311 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
2312 }
2313 $rows = $result->fetchAll (PDO::FETCH_NUM);
2314 if (count ($rows) != 1 || empty ($rows[0][0]))
2315 {
2316 $result->closeCursor();
2317 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
2318 }
2319 $ret = $rows[0][0];
2320 $result->closeCursor();
2321 return $ret;
2322 }
2323
2324 // Return an array of virtual services. For each of them list real server pools
2325 // with their load balancers and other stats.
2326 function getSLBSummary ()
2327 {
2328 $query = 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
2329 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
2330 'from IPVirtualService as vs inner join IPLoadBalancer as lb on vs.id = lb.vs_id ' .
2331 'inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2332 'left join IPRealServer as rs on rs.rspool_id = lb.rspool_id ' .
2333 'group by vs.id, object_id order by vs.vip, object_id';
2334 $result = useSelectBlade ($query, __FUNCTION__);
2335 $ret = array();
2336 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2337 {
2338 $vsid = $row['vsid'];
2339 $object_id = $row['object_id'];
2340 if (!isset ($ret[$vsid]))
2341 {
2342 $ret[$vsid] = array();
2343 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
2344 $ret[$vsid][$cname] = $row[$cname];
2345 $ret[$vsid]['lblist'] = array();
2346 }
2347 // There's only one assigned RS pool possible for each LB-VS combination.
2348 $ret[$vsid]['lblist'][$row['object_id']] = array
2349 (
2350 'id' => $row['rspool_id'],
2351 'size' => $row['rscount'],
2352 'name' => $row['pool_name']
2353 );
2354 }
2355 $result->closeCursor();
2356 return $ret;
2357 }
2358
2359 // Get the detailed composition of a particular virtual service, namely the list
2360 // of all pools, each shown with the list of objects servicing it. VS/RS configs
2361 // will be returned as well.
2362 function getVServiceInfo ($vsid = 0)
2363 {
2364 $query1 = "select inet_ntoa(vip) as vip, vport, proto, name, vsconfig, rsconfig " .
2365 "from IPVirtualService where id = ${vsid}";
2366 $result = useSelectBlade ($query1, __FUNCTION__);
2367 $vsinfo = array ();
2368 $row = $result->fetch (PDO::FETCH_ASSOC);
2369 if (!$row)
2370 return NULL;
2371 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig') as $cname)
2372 $vsinfo[$cname] = $row[$cname];
2373 $vsinfo['rspool'] = array();
2374 $result->closeCursor();
2375 unset ($result);
2376 $query2 = "select pool.id, name, pool.vsconfig, pool.rsconfig, object_id, " .
2377 "lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig from " .
2378 "IPRSPool as pool left join IPLoadBalancer as lb on pool.id = lb.rspool_id " .
2379 "where vs_id = ${vsid} order by pool.name, object_id";
2380 $result = useSelectBlade ($query2, __FUNCTION__);
2381 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2382 {
2383 if (!isset ($vsinfo['rspool'][$row['id']]))
2384 {
2385 $vsinfo['rspool'][$row['id']]['name'] = $row['name'];
2386 $vsinfo['rspool'][$row['id']]['vsconfig'] = $row['vsconfig'];
2387 $vsinfo['rspool'][$row['id']]['rsconfig'] = $row['rsconfig'];
2388 $vsinfo['rspool'][$row['id']]['lblist'] = array();
2389 }
2390 if ($row['object_id'] == NULL)
2391 continue;
2392 $vsinfo['rspool'][$row['id']]['lblist'][$row['object_id']] = array
2393 (
2394 'vsconfig' => $row['lb_vsconfig'],
2395 'rsconfig' => $row['lb_rsconfig']
2396 );
2397 }
2398 $result->closeCursor();
2399 return $vsinfo;
2400 }
2401
2402 // Collect and return the following info about the given real server pool:
2403 // basic information
2404 // parent virtual service information
2405 // load balancers list (each with a list of VSes)
2406 // real servers list
2407
2408 function getRSPoolInfo ($id = 0)
2409 {
2410 $query1 = "select id, name, vsconfig, rsconfig from " .
2411 "IPRSPool where id = ${id}";
2412 $result = useSelectBlade ($query1, __FUNCTION__);
2413 $ret = array();
2414 $row = $result->fetch (PDO::FETCH_ASSOC);
2415 if (!$row)
2416 return NULL;
2417 foreach (array ('id', 'name', 'vsconfig', 'rsconfig') as $c)
2418 $ret[$c] = $row[$c];
2419 $result->closeCursor();
2420 unset ($result);
2421 $ret['lblist'] = array();
2422 $ret['rslist'] = array();
2423 $query2 = "select object_id, vs_id, lb.vsconfig, lb.rsconfig from " .
2424 "IPLoadBalancer as lb inner join IPVirtualService as vs on lb.vs_id = vs.id " .
2425 "where rspool_id = ${id} order by object_id, vip, vport";
2426 $result = useSelectBlade ($query2, __FUNCTION__);
2427 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2428 foreach (array ('vsconfig', 'rsconfig') as $c)
2429 $ret['lblist'][$row['object_id']][$row['vs_id']][$c] = $row[$c];
2430 $result->closeCursor();
2431 unset ($result);
2432 $query3 = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rsconfig from " .
2433 "IPRealServer where rspool_id = ${id} order by IPRealServer.rsip, rsport";
2434 $result = useSelectBlade ($query3, __FUNCTION__);
2435 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2436 foreach (array ('inservice', 'rsip', 'rsport', 'rsconfig') as $c)
2437 $ret['rslist'][$row['id']][$c] = $row[$c];
2438 $result->closeCursor();
2439 return $ret;
2440 }
2441
2442 function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
2443 {
2444 if ($pool_id <= 0)
2445 {
2446 showError ('Invalid arguments', __FUNCTION__);
2447 die;
2448 }
2449 if (empty ($rsport) or $rsport == 0)
2450 $rsport = 'NULL';
2451 return useInsertBlade
2452 (
2453 'IPRealServer',
2454 array
2455 (
2456 'rsip' => "inet_aton('${rsip}')",
2457 'rsport' => $rsport,
2458 'rspool_id' => $pool_id,
2459 'inservice' => ($inservice == 'yes' ? "'yes'" : "'no'"),
2460 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2461 )
2462 );
2463 }
2464
2465 function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig, $taglist = array())
2466 {
2467 if (empty ($vip) or $vport <= 0 or empty ($proto))
2468 return __FUNCTION__ . ': invalid arguments';
2469 if (!useInsertBlade
2470 (
2471 'IPVirtualService',
2472 array
2473 (
2474 'vip' => "inet_aton('${vip}')",
2475 'vport' => $vport,
2476 'proto' => "'${proto}'",
2477 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2478 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2479 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2480 )
2481 ))
2482 return __FUNCTION__ . ': SQL insertion failed';
2483 return produceTagsForLastRecord ('ipv4vs', $taglist);
2484 }
2485
2486 function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
2487 {
2488 if ($pool_id <= 0 or $object_id <= 0 or $vs_id <= 0)
2489 {
2490 showError ('Invalid arguments', __FUNCTION__);
2491 die;
2492 }
2493 return useInsertBlade
2494 (
2495 'IPLoadBalancer',
2496 array
2497 (
2498 'object_id' => $object_id,
2499 'rspool_id' => $pool_id,
2500 'vs_id' => $vs_id,
2501 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2502 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2503 )
2504 );
2505 }
2506
2507 function commitDeleteRS ($id = 0)
2508 {
2509 if ($id <= 0)
2510 return FALSE;
2511 return useDeleteBlade ('IPRealServer', 'id', $id);
2512 }
2513
2514 function commitDeleteVS ($id = 0)
2515 {
2516 if ($id <= 0)
2517 return FALSE;
2518 return useDeleteBlade ('IPVirtualService', 'id', $id) && destroyTagsForEntity ('ipv4vs', $id);
2519 }
2520
2521 function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
2522 {
2523 global $dbxlink;
2524 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
2525 return FALSE;
2526 $query = "delete from IPLoadBalancer where object_id = ${object_id} and " .
2527 "rspool_id = ${pool_id} and vs_id = ${vs_id} limit 1";
2528 $result = $dbxlink->exec ($query);
2529 if ($result === NULL)
2530 return FALSE;
2531 elseif ($result != 1)
2532 return FALSE;
2533 else
2534 return TRUE;
2535 }
2536
2537 function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2538 {
2539 if ($rsid <= 0)
2540 {
2541 showError ('Invalid args', __FUNCTION__);
2542 die;
2543 }
2544 if (long2ip (ip2long ($rsip)) !== $rsip)
2545 {
2546 showError ("Invalid IP address '${rsip}'", __FUNCTION__);
2547 die;
2548 }
2549 if (empty ($rsport) or $rsport == 0)
2550 $rsport = 'NULL';
2551 global $dbxlink;
2552 $query =
2553 "update IPRealServer set rsip = inet_aton('${rsip}'), rsport = ${rsport}, rsconfig = " .
2554 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2555 " where id = ${rsid} limit 1";
2556 $result = $dbxlink->query ($query);
2557 if ($result == NULL)
2558 {
2559 showError ("SQL query '${query}' failed", __FUNCTION__);
2560 die;
2561 }
2562 return TRUE;
2563 }
2564
2565 function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
2566 {
2567 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
2568 {
2569 showError ('Invalid args', __FUNCTION__);
2570 die;
2571 }
2572 global $dbxlink;
2573 $query =
2574 "update IPLoadBalancer set vsconfig = " .
2575 (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'") .
2576 ', rsconfig = ' .
2577 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2578 " where object_id = ${object_id} and rspool_id = ${pool_id} " .
2579 "and vs_id = ${vs_id} limit 1";
2580 $result = $dbxlink->exec ($query);
2581 if ($result === NULL)
2582 return FALSE;
2583 else
2584 return TRUE;
2585 }
2586
2587 function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2588 {
2589 if ($vsid <= 0 or empty ($vip) or $vport <= 0 or empty ($proto))
2590 {
2591 showError ('Invalid args', __FUNCTION__);
2592 die;
2593 }
2594 global $dbxlink;
2595 $query = "update IPVirtualService set " .
2596 "vip = inet_aton('${vip}'), " .
2597 "vport = ${vport}, " .
2598 "proto = '${proto}', " .
2599 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2600 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2601 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2602 " where id = ${vsid} limit 1";
2603 $result = $dbxlink->exec ($query);
2604 if ($result === NULL)
2605 return FALSE;
2606 else
2607 return TRUE;
2608 }
2609
2610 // Return the list of virtual services, indexed by vs_id.
2611 // Each record will be shown with its basic info plus RS pools counter.
2612 function getVSList ($tagfilter = array(), $tfmode = 'any')
2613 {
2614 $whereclause = getWhereClause ($tagfilter);
2615 $query = "select vs.id, inet_ntoa(vip) as vip, vport, proto, vs.name, vs.vsconfig, vs.rsconfig, count(rspool_id) as poolcount " .
2616 "from IPVirtualService as vs left join IPLoadBalancer as lb on vs.id = lb.vs_id " .
2617 "left join TagStorage on vs.id = TagStorage.target_id and target_realm = 'ipv4vs' " .
2618 "where true ${whereclause} group by vs.id order by vs.vip, proto, vport";
2619 $result = useSelectBlade ($query, __FUNCTION__);
2620 $ret = array ();
2621 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2622 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig', 'poolcount') as $cname)
2623 $ret[$row['id']][$cname] = $row[$cname];
2624 $result->closeCursor();
2625 return $ret;
2626 }
2627
2628 // Return the list of RS pool, indexed by pool id.
2629 function getRSPoolList ($tagfilter = array(), $tfmode = 'any')
2630 {
2631 $whereclause = getWhereClause ($tagfilter);
2632 $query = "select pool.id, pool.name, count(rspool_id) as refcnt, pool.vsconfig, pool.rsconfig " .
2633 "from IPRSPool as pool left join IPLoadBalancer as lb on pool.id = lb.rspool_id " .
2634 "left join TagStorage on pool.id = TagStorage.target_id and target_realm = 'ipv4rspool' " .
2635 "where true ${whereclause} group by pool.id order by pool.name, pool.id";
2636 $result = useSelectBlade ($query, __FUNCTION__);
2637 $ret = array ();
2638 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2639 foreach (array ('name', 'refcnt', 'vsconfig', 'rsconfig') as $cname)
2640 $ret[$row['id']][$cname] = $row[$cname];
2641 $result->closeCursor();
2642 return $ret;
2643 }
2644
2645 function loadThumbCache ($rack_id = 0)
2646 {
2647 $ret = NULL;
2648 $query = "select thumb_data from Rack where id = ${rack_id} and thumb_data is not null limit 1";
2649 $result = useSelectBlade ($query, __FUNCTION__);
2650 $row = $result->fetch (PDO::FETCH_ASSOC);
2651 if ($row)
2652 $ret = base64_decode ($row['thumb_data']);
2653 $result->closeCursor();
2654 return $ret;
2655 }
2656
2657 function saveThumbCache ($rack_id = 0, $cache = NULL)
2658 {
2659 global $dbxlink;
2660 if ($rack_id == 0 or $cache == NULL)
2661 {
2662 showError ('Invalid arguments', __FUNCTION__);
2663 return;
2664 }
2665 $data = base64_encode ($cache);
2666 $query = "update Rack set thumb_data = '${data}' where id = ${rack_id} limit 1";
2667 $result = $dbxlink->exec ($query);
2668 }
2669
2670 function resetThumbCache ($rack_id = 0)
2671 {
2672 global $dbxlink;
2673 if ($rack_id == 0)
2674 {
2675 showError ('Invalid argument', __FUNCTION__);
2676 return;
2677 }
2678 $query = "update Rack set thumb_data = NULL where id = ${rack_id} limit 1";
2679 $result = $dbxlink->exec ($query);
2680 }
2681
2682 // Return the list of attached RS pools for the given object. As long as we have
2683 // the LB-VS UNIQUE in IPLoadBalancer table, it is Ok to key returned records
2684 // by vs_id, because there will be only one RS pool listed for each VS of the
2685 // current object.
2686 function getRSPoolsForObject ($object_id = 0)
2687 {
2688 if ($object_id <= 0)
2689 {
2690 showError ('Invalid object_id', __FUNCTION__);
2691 return NULL;
2692 }
2693 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
2694 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
2695 'IPLoadBalancer as lb inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2696 'inner join IPVirtualService as vs on lb.vs_id = vs.id ' .
2697 'left join IPRealServer as rs on lb.rspool_id = rs.rspool_id ' .
2698 "where lb.object_id = ${object_id} " .
2699 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name';
2700 $result = useSelectBlade ($query, __FUNCTION__);
2701 $ret = array ();
2702 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2703 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
2704 $ret[$row['vs_id']][$cname] = $row[$cname];
2705 $result->closeCursor();
2706 return $ret;
2707 }
2708
2709 function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
2710 {
2711 if (empty ($name))
2712 return __FUNCTION__ . ': invalid arguments';
2713 if (!useInsertBlade
2714 (
2715 'IPRSPool',
2716 array
2717 (
2718 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2719 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2720 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2721 )
2722 ))
2723 return __FUNCTION__ . ': SQL insertion failed';
2724 return produceTagsForLastRecord ('ipv4rspool', $taglist);
2725 }
2726
2727 function commitDeleteRSPool ($pool_id = 0)
2728 {
2729 global $dbxlink;
2730 if ($pool_id <= 0)
2731 return FALSE;
2732 return useDeleteBlade ('IPRSPool', 'id', $pool_id) && destroyTagsForEntity ('ipv4rspool', $pool_id);
2733 }
2734
2735 function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2736 {
2737 if ($pool_id <= 0)
2738 {
2739 showError ('Invalid arg', __FUNCTION__);
2740 die;
2741 }
2742 global $dbxlink;
2743 $query = "update IPRSPool set " .
2744 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2745 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2746 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2747 " where id = ${pool_id} limit 1";
2748 $result = $dbxlink->exec ($query);
2749 if ($result === NULL)
2750 return FALSE;
2751 elseif ($result != 1)
2752 return FALSE;
2753 else
2754 return TRUE;
2755 }
2756
2757 function getRSList ()
2758 {
2759 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
2760 "from IPRealServer order by rspool_id, IPRealServer.rsip, rsport";
2761 $result = useSelectBlade ($query, __FUNCTION__);
2762 $ret = array ();
2763 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2764 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
2765 $ret[$row['id']][$cname] = $row[$cname];
2766 $result->closeCursor();
2767 return $ret;
2768 }
2769
2770 // Return the list of all currently configured load balancers with their pool count.
2771 function getLBList ()
2772 {
2773 $query = "select object_id, count(rspool_id) as poolcount " .
2774 "from IPLoadBalancer group by object_id order by object_id";
2775 $result = useSelectBlade ($query, __FUNCTION__);
2776 $ret = array ();
2777 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2778 $ret[$row['object_id']] = $row['poolcount'];
2779 $result->closeCursor();
2780 return $ret;
2781 }
2782
2783 // For the given object return: it vsconfig/rsconfig; the list of RS pools
2784 // attached (each with vsconfig/rsconfig in turn), each with the list of
2785 // virtual services terminating the pool. Each pool also lists all real
2786 // servers with rsconfig.
2787 function getSLBConfig ($object_id)
2788 {
2789 if ($object_id <= 0)
2790 {
2791 showError ('Invalid arg', __FUNCTION__);
2792 return NULL;
2793 }
2794 $ret = array();
2795 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2796 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2797 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
2798 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
2799 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
2800 'IPLoadBalancer as lb inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2801 'inner join IPVirtualService as vs on lb.vs_id = vs.id ' .
2802 'inner join IPRealServer as rs on lb.rspool_id = rs.rspool_id ' .
2803 "where lb.object_id = ${object_id} and rs.inservice = 'yes' " .
2804 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport";
2805 $result = useSelectBlade ($query, __FUNCTION__);
2806 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2807 {
2808 $vs_id = $row['vs_id'];
2809 if (!isset ($ret[$vs_id]))
2810 {
2811 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)
2812 $ret[$vs_id][$c] = $row[$c];
2813 $ret[$vs_id]['rslist'] = array();
2814 }
2815 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2816 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
2817 }
2818 $result->closeCursor();
2819 return $ret;
2820 }
2821
2822 function commitSetInService ($rs_id = 0, $inservice = '')
2823 {
2824 if ($rs_id <= 0 or empty ($inservice))
2825 {
2826 showError ('Invalid args', __FUNCTION__);
2827 return NULL;
2828 }
2829 global $dbxlink;
2830 $query = "update IPRealServer set inservice = '${inservice}' where id = ${rs_id} limit 1";
2831 $result = $dbxlink->exec ($query);
2832 if ($result === NULL)
2833 return FALSE;
2834 elseif ($result != 1)
2835 return FALSE;
2836 else
2837 return TRUE;
2838 }
2839
2840 function executeAutoPorts ($object_id = 0, $type_id = 0)
2841 {
2842 if ($object_id == 0 or $type_id == 0)
2843 {
2844 showError ('Invalid arguments', __FUNCTION__);
2845 die;
2846 }
2847 $ret = TRUE;
2848 foreach (getAutoPorts ($type_id) as $autoport)
2849 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2850 return $ret;
2851 }
2852
2853 // Return only implicitly listed tags, the rest of the chain will be
2854 // generated/deducted later at higher levels.
2855 // Result is a chain: randomly indexed taginfo list.
2856 function loadEntityTags ($entity_realm = '', $entity_id = 0)
2857 {
2858 if ($entity_realm == '' or $entity_id <= 0)
2859 {
2860 showError ('Invalid or missing arguments', __FUNCTION__);
2861 return NULL;
2862 }
2863 $ret = array();
2864 $query = "select tt.id, tag from " .
2865 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
2866 "where target_realm = '${entity_realm}' and target_id = ${entity_id} " .
2867 "order by tt.tag";
2868 $result = useSelectBlade ($query, __FUNCTION__);
2869 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2870 $ret[$row['id']] = $row;
2871 $result->closeCursor();
2872 return getExplicitTagsOnly ($ret);
2873 }
2874
2875 function loadFileTags ($id)
2876 {
2877 return loadEntityTags ('file', $id);
2878 }
2879
2880 function loadRackObjectTags ($id)
2881 {
2882 return loadEntityTags ('object', $id);
2883 }
2884
2885 function loadIPv4PrefixTags ($id)
2886 {
2887 return loadEntityTags ('ipv4net', $id);
2888 }
2889
2890 function loadRackTags ($id)
2891 {
2892 return loadEntityTags ('rack', $id);
2893 }
2894
2895 function loadIPv4VSTags ($id)
2896 {
2897 return loadEntityTags ('ipv4vs', $id);
2898 }
2899
2900 function loadIPv4RSPoolTags ($id)
2901 {
2902 return loadEntityTags ('ipv4rspool', $id);
2903 }
2904
2905 function loadUserTags ($user_id)
2906 {
2907 return loadEntityTags ('user', $user_id);
2908 }
2909
2910 // Return a tag chain with all DB tags on it.
2911 function getTagList ()
2912 {
2913 $ret = array();
2914 $query = "select id, parent_id, tag, target_realm as realm, count(target_id) as refcnt " .
2915 "from TagTree left join TagStorage on id = tag_id " .
2916 "group by id, target_realm order by tag";
2917 $result = useSelectBlade ($query, __FUNCTION__);
2918 $ci = 0; // Collation index. The resulting rows are ordered according to default collation,
2919 // which is utf8_general_ci for UTF-8.
2920 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2921 {
2922 if (!isset ($ret[$row['id']]))
2923 $ret[$row['id']] = array
2924 (
2925 'id' => $row['id'],
2926 'tag' => $row['tag'],
2927 'ci' => $ci++,
2928 'parent_id' => $row['parent_id'],
2929 'refcnt' => array()
2930 );
2931 if ($row['realm'])
2932 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
2933 }
2934 $result->closeCursor();
2935 return $ret;
2936 }
2937
2938 function commitCreateTag ($tagname = '', $parent_id = 0)
2939 {
2940 if ($tagname == '' or $parent_id === 0)
2941 return "Invalid args to " . __FUNCTION__;
2942 $result = useInsertBlade
2943 (
2944 'TagTree',
2945 array
2946 (
2947 'tag' => "'${tagname}'",
2948 'parent_id' => $parent_id
2949 )
2950 );
2951 if ($result)
2952 return '';
2953 else
2954 return "SQL query failed in " . __FUNCTION__;
2955 }
2956
2957 function commitDestroyTag ($tagid = 0)
2958 {
2959 if ($tagid == 0)
2960 return 'Invalid arg to ' . __FUNCTION__;
2961 if (useDeleteBlade ('TagTree', 'id', $tagid))
2962 return '';
2963 else
2964 return 'useDeleteBlade() failed in ' . __FUNCTION__;
2965 }
2966
2967 function commitUpdateTag ($tag_id, $tag_name, $parent_id)
2968 {
2969 if ($parent_id == 0)
2970 $parent_id = 'NULL';
2971 global $dbxlink;
2972 $query = "update TagTree set tag = '${tag_name}', parent_id = ${parent_id} " .
2973 "where id = ${tag_id} limit 1";
2974 $result = $dbxlink->exec ($query);
2975 if ($result === NULL)
2976 return 'SQL query failed in ' . __FUNCTION__;
2977 return '';
2978 }
2979
2980 // Drop the whole chain stored.
2981 function destroyTagsForEntity ($entity_realm, $entity_id)
2982 {
2983 global $dbxlink;
2984 $query = "delete from TagStorage where target_realm = '${entity_realm}' and target_id = ${entity_id}";
2985 $result = $dbxlink->exec ($query);
2986 if ($result === NULL)
2987 return FALSE;
2988 else
2989 return TRUE;
2990 }
2991
2992 // Drop only one record. This operation doesn't involve retossing other tags, unlike when adding.
2993 function deleteTagForEntity ($entity_realm, $entity_id, $tag_id)
2994 {
2995 global $dbxlink;
2996 $query = "delete from TagStorage where target_realm = '${entity_realm}' and target_id = ${entity_id} and tag_id = ${tag_id}";
2997 $result = $dbxlink->exec ($query);
2998 if ($result === NULL)
2999 return FALSE;
3000 else
3001 return TRUE;
3002 }
3003
3004 // Push a record into TagStorage unconditionally.
3005 function addTagForEntity ($realm = '', $entity_id, $tag_id)
3006 {
3007 if (empty ($realm))
3008 return FALSE;
3009 return useInsertBlade
3010 (
3011 'TagStorage',
3012 array
3013 (
3014 'target_realm' => "'${realm}'",
3015 'target_id' => $entity_id,
3016 'tag_id' => $tag_id,
3017 )
3018 );
3019 }
3020
3021 // Add records into TagStorage, if this makes sense (IOW, they don't appear
3022 // on the implicit list already). Then remove any other records, which
3023 // appear on the "implicit" side of the chain. This will make sure,
3024 // that both the tag base is still minimal and all requested tags appear on
3025 // the resulting tag chain.
3026 // Return TRUE, if any changes were committed.
3027 function rebuildTagChainForEntity ($realm, $entity_id, $extrachain = array())
3028 {
3029 // Put the current explicit sub-chain into a buffer and merge all tags from
3030 // the extra chain, which aren't there yet.
3031 $newchain = $oldchain = loadEntityTags ($realm, $entity_id);
3032 foreach ($extrachain as $extratag)
3033 if (!tagOnChain ($extratag, $newchain))
3034 $newchain[] = $extratag;
3035 // Then minimize the working buffer and check if it differs from the original
3036 // chain we started with. If it is so, save the work and signal the upper layer.
3037 $newchain = getExplicitTagsOnly ($newchain);
3038 if (tagChainCmp ($oldchain, $newchain))
3039 {
3040 destroyTagsForEntity ($realm, $entity_id);
3041 foreach ($newchain as $taginfo)
3042 addTagForEntity ($realm, $entity_id, $taginfo['id']);
3043 return TRUE;
3044 }
3045 return FALSE;
3046 }
3047
3048 // Presume, that the target record has no tags attached.
3049 function produceTagsForLastRecord ($realm, $tagidlist, $last_insert_id = 0)
3050 {
3051 if (!count ($tagidlist))
3052 return '';
3053 if (!$last_insert_id)
3054 $last_insert_id = lastInsertID();
3055 $errcount = 0;
3056 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagidlist)) as $taginfo)
3057 if (addTagForEntity ($realm, $last_insert_id, $taginfo['id']) == FALSE)
3058 $errcount++;
3059 if (!$errcount)
3060 return '';
3061 else
3062 return "Experienced ${errcount} errors adding tags in realm '${realm}' for entity ID == ${last_insert_id}";
3063 }
3064
3065 function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
3066 {
3067 // $range is in x.x.x.x/x format, split into ip/mask vars
3068 $rangeArray = explode('/', $range);
3069 if (count ($rangeArray) != 2)
3070 return "Invalid IPv4 prefix '${range}'";
3071 $ip = $rangeArray[0];
3072 $mask = $rangeArray[1];
3073
3074 if (empty ($ip) or empty ($mask))
3075 return "Invalid IPv4 prefix '${range}'";
3076 $ipL = ip2long($ip);
3077 $maskL = ip2long($mask);
3078 if ($ipL == -1 || $ipL === FALSE)
3079 return 'Bad IPv4 address';
3080 if ($mask < 32 && $mask > 0)
3081 $maskL = $mask;
3082 else
3083 {
3084 $maskB = decbin($maskL);
3085 if (strlen($maskB)!=32)
3086 return 'Invalid netmask';
3087 $ones=0;
3088 $zeroes=FALSE;
3089 foreach( str_split ($maskB) as $digit)
3090 {
3091 if ($digit == '0')
3092 $zeroes = TRUE;
3093 if ($digit == '1')
3094 {
3095 $ones++;
3096 if ($zeroes == TRUE)
3097 return 'Invalid netmask';
3098 }
3099 }
3100 $maskL = $ones;
3101 }
3102 $binmask = binMaskFromDec($maskL);
3103 $ipL = $ipL & $binmask;
3104 $result = useInsertBlade
3105 (
3106 'IPRanges',
3107 array
3108 (
3109 'ip' => sprintf ('%u', $ipL),
3110 'mask' => "'${maskL}'",
3111 'name' => "'${name}'"
3112 )
3113 );
3114 if ($result != TRUE)
3115 return "Could not add ${range} (already exists?).";
3116
3117 if ($is_bcast and $maskL < 31)
3118 {
3119 $network_addr = long2ip ($ipL);
3120 $broadcast_addr = long2ip ($ipL | binInvMaskFromDec ($maskL));
3121 updateAddress ($network_addr, 'network', 'yes');
3122 updateAddress ($broadcast_addr, 'broadcast', 'yes');
3123 }
3124 return produceTagsForLastRecord ('ipv4net', $taglist);
3125 }
3126
3127 // FIXME: This function doesn't wipe relevant records from IPAddress table.
3128 function destroyIPv4Prefix ($id = 0)
3129 {
3130 if ($id <= 0)
3131 return __FUNCTION__ . ': Invalid IPv4 prefix ID';
3132 if (!useDeleteBlade ('IPRanges', 'id', $id))
3133 return __FUNCTION__ . ': SQL query #1 failed';
3134 if (!destroyTagsForEntity ('ipv4net', $id))
3135 return __FUNCTION__ . ': SQL query #2 failed';
3136 return '';
3137 }
3138
3139 function loadScript ($name)
3140 {
3141 $result = useSelectBlade ("select script_text from Script where script_name = '${name}'");
3142 $row = $result->fetch (PDO::FETCH_NUM);
3143 if ($row !== FALSE)
3144 return $row[0];
3145 else
3146 return NULL;
3147 }
3148
3149 function saveScript ($name, $text)
3150 {
3151 if (empty ($name))
3152 {
3153 showError ('Invalid argument');
3154 return FALSE;
3155 }
3156 // delete regardless of existence
3157 useDeleteBlade ('Script', 'script_name', "'${name}'");
3158 return useInsertBlade
3159 (
3160 'Script',
3161 array
3162 (
3163 'script_name' => "'${name}'",
3164 'script_text' => "'${text}'"
3165 )
3166 );
3167 }
3168
3169 function saveUserPassword ($user_id, $newp)
3170 {
3171 $newhash = hash (PASSWORD_HASH, $newp);
3172 $query = "update UserAccount set user_password_hash = ${newhash} where user_id = ${user_id} limit 1";
3173 }
3174
3175 function objectIsPortless ($id = 0)
3176 {
3177 if ($id <= 0)
3178 {
3179 showError ('Invalid argument', __FUNCTION__);
3180 return;
3181 }
3182 if (($result = useSelectBlade ("select count(id) from Port where object_id = ${id}", __FUNCTION__)) == NULL)
3183 {
3184 showError ('SQL query failed', __FUNCTION__);
3185 return;
3186 }
3187 $row = $result->fetch (PDO::FETCH_NUM);
3188 $count = $row[0];
3189 $result->closeCursor();
3190 unset ($result);
3191 return $count === '0';
3192 }
3193
3194 function recordExists ($id = 0, $realm = 'object')
3195 {
3196 if ($id <= 0)
3197 return FALSE;
3198 $table = array
3199 (
3200 'object' => 'RackObject',
3201 'ipv4net' => 'IPRanges',
3202 'user' => 'UserAccount',
3203 );
3204 $idcol = array
3205 (
3206 'object' => 'id',
3207 'ipv4net' => 'id',
3208 'user' => 'user_id',
3209 );
3210 $query = 'select count(*) from ' . $table[$realm] . ' where ' . $idcol[$realm] . ' = ' . $id;
3211 if (($result = useSelectBlade ($query, __FUNCTION__)) == NULL)
3212 {
3213 showError ('SQL query failed', __FUNCTION__);
3214 return FALSE;
3215 }
3216 $row = $result->fetch (PDO::FETCH_NUM);
3217 $count = $row[0];
3218 $result->closeCursor();
3219 unset ($result);
3220 return $count === '1';
3221 }
3222
3223 function tagExistsInDatabase ($tname)
3224 {
3225 $result = useSelectBlade ("select count(*) from TagTree where lower(tag) = lower('${tname}')");
3226 $row = $result->fetch (PDO::FETCH_NUM);
3227 $count = $row[0];
3228 $result->closeCursor();
3229 unset ($result);
3230 return $count !== '0';
3231 }
3232
3233 function newPortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3234 {
3235 if (NULL === getIPv4AddressNetworkId ($localip))
3236 return "$localip: Non existant ip";
3237 if (NULL === getIPv4AddressNetworkId ($localip))
3238 return "$remoteip: Non existant ip";
3239 if ( ($localport <= 0) or ($localport >= 65536) )
3240 return "$localport: invaild port";
3241 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
3242 return "$remoteport: invaild port";
3243
3244 $result = useInsertBlade
3245 (
3246 'PortForwarding',
3247 array
3248 (
3249 'object_id' => $object_id,
3250 'localip' => "INET_ATON('${localip}')",
3251 'remoteip' => "INET_ATON('$remoteip')",
3252 'localport' => $localport,
3253 'remoteport' => $remoteport,
3254 'proto' => "'${proto}'",
3255 'description' => "'${description}'",
3256 )
3257 );
3258 if ($result)
3259 return '';
3260 else
3261 return __FUNCTION__ . ': Failed to insert the rule.';
3262 }
3263
3264 function deletePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
3265 {
3266 global $dbxlink;
3267
3268 $query =
3269 "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'";
3270 $result = $dbxlink->exec ($query);
3271 return '';
3272 }
3273
3274 function updatePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3275 {
3276 global $dbxlink;
3277
3278 $query =
3279 "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'";
3280 $result = $dbxlink->exec ($query);
3281 return '';
3282 }
3283
3284 function getNATv4ForObject ($object_id)
3285 {
3286 $ret = array();
3287 $ret['out'] = array();
3288 $ret['in'] = array();
3289 $query =
3290 "select ".
3291 "proto, ".
3292 "INET_NTOA(localip) as localip, ".
3293 "localport, ".
3294 "INET_NTOA(remoteip) as remoteip, ".
3295 "remoteport, ".
3296 "ipa1.name as local_addr_name, " .
3297 "ipa2.name as remote_addr_name, " .
3298 "description ".
3299 "from PortForwarding ".
3300 "left join IPAddress as ipa1 on PortForwarding.localip = ipa1.ip " .
3301 "left join IPAddress as ipa2 on PortForwarding.remoteip = ipa2.ip " .
3302 "where object_id='$object_id' ".
3303 "order by localip, localport, proto, remoteip, remoteport";
3304 $result = useSelectBlade ($query, __FUNCTION__);
3305 $count=0;
3306 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3307 {
3308 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
3309 $ret['out'][$count][$cname] = $row[$cname];
3310 $count++;
3311 }
3312 $result->closeCursor();
3313 unset ($result);
3314
3315 $query =
3316 "select ".
3317 "proto, ".
3318 "INET_NTOA(localip) as localip, ".
3319 "localport, ".
3320 "INET_NTOA(remoteip) as remoteip, ".
3321 "remoteport, ".
3322 "PortForwarding.object_id as object_id, ".
3323 "RackObject.name as object_name, ".
3324 "description ".
3325 "from ((PortForwarding join IPBonds on remoteip=IPBonds.ip) join RackObject on PortForwarding.object_id=RackObject.id) ".
3326 "where IPBonds.object_id='$object_id' ".
3327 "order by remoteip, remoteport, proto, localip, localport";
3328 $result = useSelectBlade ($query, __FUNCTION__);
3329 $count=0;
3330 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3331 {
3332 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
3333 $ret['in'][$count][$cname] = $row[$cname];
3334 $count++;
3335 }
3336 $result->closeCursor();
3337
3338 return $ret;
3339 }
3340
3341 // This function performs search and then calculates score for each result.
3342 // Given previous search results in $objects argument, it adds new results
3343 // to the array and updates score for existing results, if it is greater than
3344 // existing score.
3345 function mergeSearchResults (&$objects, $terms, $fieldname)
3346 {
3347 global $dbxlink;
3348 $query =
3349 "select name, label, asset_no, barcode, ro.id, dict_key as objtype_id, " .
3350 "dict_value as objtype_name, asset_no from RackObject as ro inner join Dictionary " .
3351 "on objtype_id = dict_key natural join Chapter where chapter_name = 'RackObjectType' and ";
3352 $count = 0;
3353 foreach (explode (' ', $terms) as $term)
3354 {
3355 if ($count) $query .= ' or ';
3356 $query .= "${fieldname} like '%$term%'";
3357 $count++;
3358 }
3359 $query .= " order by ${fieldname}";
3360 $result = useSelectBlade ($query, __FUNCTION__);
3361 // FIXME: this dead call was executed 4 times per 1 object search!
3362 // $typeList = getObjectTypeList();
3363 $clist = array ('id', 'name', 'label', 'asset_no', 'barcode', 'objtype_id', 'objtype_name');
3364 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3365 {
3366 foreach ($clist as $cname)
3367 $object[$cname] = $row[$cname];
3368 $object['score'] = 0;
3369 $object['dname'] = displayedName ($object);
3370 unset ($object['objtype_id']);
3371 foreach (explode (' ', $terms) as $term)
3372 if (strstr ($object['name'], $term))
3373 $object['score'] += 1;
3374 unset ($object['name']);
3375 if (!isset ($objects[$row['id']]))
3376 $objects[$row['id']] = $object;
3377 elseif ($objects[$row['id']]['score'] < $object['score'])
3378 $objects[$row['id']]['score'] = $object['score'];
3379 }
3380 return $objects;
3381 }
3382
3383 function getLostIPv4Addresses ()
3384 {
3385 dragon();
3386 }
3387
3388 // File-related functions
3389 function getAllFiles ()
3390 {
3391 $query = "SELECT id, name, type, size, ctime, mtime, atime, comment FROM File ORDER BY name";
3392 $result = useSelectBlade ($query, __FUNCTION__);
3393 $ret=array();
3394 $count=0;
3395 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3396 {
3397 $ret[$count]['id'] = $row['id'];
3398 $ret[$count]['name'] = $row['name'];
3399 $ret[$count]['type'] = $row['type'];
3400 $ret[$count]['size'] = $row['size'];
3401 $ret[$count]['ctime'] = $row['ctime'];
3402 $ret[$count]['mtime'] = $row['mtime'];
3403 $ret[$count]['atime'] = $row[