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