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