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