r2379 - drop user_enabled column and all related stuff
[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 // This function returns an array of all port type pairs from PortCompat table.
1549 function getPortCompat ()
1550 {
1551 $query =
1552 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
1553 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
1554 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
1555 "inner join Chapter as c1 on d1.chapter_no = c1.chapter_no " .
1556 "inner join Chapter as c2 on d2.chapter_no = c2.chapter_no " .
1557 "where c1.chapter_name = 'PortType' and c2.chapter_name = 'PortType'";
1558 $result = useSelectBlade ($query, __FUNCTION__);
1559 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
1560 $result->closeCursor();
1561 return $ret;
1562 }
1563
1564 function removePortCompat ($type1 = 0, $type2 = 0)
1565 {
1566 global $dbxlink;
1567 if ($type1 == 0 or $type2 == 0)
1568 {
1569 showError ('Invalid arguments', __FUNCTION__);
1570 die;
1571 }
1572 $query = "delete from PortCompat where type1 = ${type1} and type2 = ${type2} limit 1";
1573 $result = $dbxlink->query ($query);
1574 if ($result == NULL)
1575 {
1576 showError ('SQL query failed', __FUNCTION__);
1577 die;
1578 }
1579 return TRUE;
1580 }
1581
1582 function addPortCompat ($type1 = 0, $type2 = 0)
1583 {
1584 if ($type1 <= 0 or $type2 <= 0)
1585 {
1586 showError ('Invalid arguments', __FUNCTION__);
1587 die;
1588 }
1589 return useInsertBlade
1590 (
1591 'PortCompat',
1592 array ('type1' => $type1, 'type2' => $type2)
1593 );
1594 }
1595
1596 // This function returns the dictionary as an array of trees, each tree
1597 // representing a single chapter. Each element has 'id', 'name', 'sticky'
1598 // and 'word' keys with the latter holding all the words within the chapter.
1599 function getDict ($parse_links = FALSE)
1600 {
1601 $query1 =
1602 "select chapter_name, Chapter.chapter_no, dict_key, dict_value, sticky from " .
1603 "Chapter natural left join Dictionary order by chapter_name, dict_value";
1604 $result = useSelectBlade ($query1, __FUNCTION__);
1605 $dict = array();
1606 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1607 {
1608 $chapter_no = $row['chapter_no'];
1609 if (!isset ($dict[$chapter_no]))
1610 {
1611 $dict[$chapter_no]['no'] = $chapter_no;
1612 $dict[$chapter_no]['name'] = $row['chapter_name'];
1613 $dict[$chapter_no]['sticky'] = $row['sticky'] == 'yes' ? TRUE : FALSE;
1614 $dict[$chapter_no]['word'] = array();
1615 }
1616 if ($row['dict_key'] != NULL)
1617 {
1618 $dict[$chapter_no]['word'][$row['dict_key']] = ($parse_links or $row['dict_key'] <= MAX_DICT_KEY) ?
1619 parseWikiLink ($row['dict_value'], 'a') : $row['dict_value'];
1620 $dict[$chapter_no]['refcnt'][$row['dict_key']] = 0;
1621 }
1622 }
1623 $result->closeCursor();
1624 unset ($result);
1625 // Find the list of all assigned values of dictionary-addressed attributes, each with
1626 // chapter/word keyed reference counters. Use the structure to adjust reference counters
1627 // of the returned disctionary words.
1628 $query2 = "select a.attr_id, am.chapter_no, uint_value, count(object_id) as refcnt " .
1629 "from Attribute as a inner join AttributeMap as am on a.attr_id = am.attr_id " .
1630 "inner join AttributeValue as av on a.attr_id = av.attr_id " .
1631 "inner join Dictionary as d on am.chapter_no = d.chapter_no and av.uint_value = d.dict_key " .
1632 "where attr_type = 'dict' group by a.attr_id, am.chapter_no, uint_value " .
1633 "order by a.attr_id, am.chapter_no, uint_value";
1634 $result = useSelectBlade ($query2, __FUNCTION__);
1635 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1636 $dict[$row['chapter_no']]['refcnt'][$row['uint_value']] = $row['refcnt'];
1637 $result->closeCursor();
1638 return $dict;
1639 }
1640
1641 function getDictStats ()
1642 {
1643 $stock_chapters = array (1, 2, 3, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23);
1644 $query =
1645 "select Chapter.chapter_no, chapter_name, count(dict_key) as wc from " .
1646 "Chapter natural left join Dictionary group by Chapter.chapter_no";
1647 $result = useSelectBlade ($query, __FUNCTION__);
1648 $tc = $tw = $uc = $uw = 0;
1649 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1650 {
1651 $tc++;
1652 $tw += $row['wc'];;
1653 if (in_array ($row['chapter_no'], $stock_chapters))
1654 continue;
1655 $uc++;
1656 $uw += $row['wc'];;
1657 }
1658 $result->closeCursor();
1659 unset ($result);
1660 $query = "select count(attr_id) as attrc from RackObject as ro left join " .
1661 "AttributeValue as av on ro.id = av.object_id group by ro.id";
1662 $result = useSelectBlade ($query, __FUNCTION__);
1663 $to = $ta = $so = 0;
1664 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1665 {
1666 $to++;
1667 if ($row['attrc'] != 0)
1668 {
1669 $so++;
1670 $ta += $row['attrc'];
1671 }
1672 }
1673 $result->closeCursor();
1674 $ret = array();
1675 $ret['Total chapters in dictionary'] = $tc;
1676 $ret['Total words in dictionary'] = $tw;
1677 $ret['User chapters'] = $uc;
1678 $ret['Words in user chapters'] = $uw;
1679 $ret['Total objects'] = $to;
1680 $ret['Objects with stickers'] = $so;
1681 $ret['Total stickers attached'] = $ta;
1682 return $ret;
1683 }
1684
1685 function getIPv4Stats ()
1686 {
1687 $ret = array();
1688 $subject = array();
1689 $subject[] = array ('q' => 'select count(id) from IPv4Network', 'txt' => 'Networks');
1690 $subject[] = array ('q' => 'select count(ip) from IPv4Address', 'txt' => 'Addresses commented/reserved');
1691 $subject[] = array ('q' => 'select count(ip) from IPv4Allocation', 'txt' => 'Addresses allocated');
1692 $subject[] = array ('q' => 'select count(*) from IPv4NAT', 'txt' => 'NAT rules');
1693 $subject[] = array ('q' => 'select count(id) from IPv4VS', 'txt' => 'Virtual services');
1694 $subject[] = array ('q' => 'select count(id) from IPv4RSPool', 'txt' => 'Real server pools');
1695 $subject[] = array ('q' => 'select count(id) from IPv4RS', 'txt' => 'Real servers');
1696 $subject[] = array ('q' => 'select count(distinct object_id) from IPv4LB', 'txt' => 'Load balancers');
1697
1698 foreach ($subject as $item)
1699 {
1700 $result = useSelectBlade ($item['q'], __FUNCTION__);
1701 $row = $result->fetch (PDO::FETCH_NUM);
1702 $ret[$item['txt']] = $row[0];
1703 $result->closeCursor();
1704 unset ($result);
1705 }
1706 return $ret;
1707 }
1708
1709 function getRackspaceStats ()
1710 {
1711 $ret = array();
1712 $subject = array();
1713 $subject[] = array ('q' => 'select count(*) from Dictionary where chapter_no = 3', 'txt' => 'Rack rows');
1714 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
1715 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
1716 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
1717
1718 foreach ($subject as $item)
1719 {
1720 $result = useSelectBlade ($item['q'], __FUNCTION__);
1721 $row = $result->fetch (PDO::FETCH_NUM);
1722 $ret[$item['txt']] = empty ($row[0]) ? 0 : $row[0];
1723 $result->closeCursor();
1724 unset ($result);
1725 }
1726 return $ret;
1727 }
1728
1729 function renderTagStats ()
1730 {
1731 global $taglist, $root;
1732 $query = "select id, tag, count(tag_id) as refcnt from " .
1733 "TagTree inner join TagStorage on TagTree.id = TagStorage.tag_id " .
1734 "group by tag_id order by refcnt desc limit 50";
1735 // The same data is already present in pre-loaded tag list, but not in
1736 // the form we need. So let's ask the DB server for cooked top list and
1737 // use the cooked tag list to break it down.
1738 $result = useSelectBlade ($query, __FUNCTION__);
1739 $refc = $result->fetchAll (PDO::FETCH_ASSOC);
1740 echo '<table border=1><tr><th>tag</th><th>total</th><th>objects</th><th>IPv4 nets</th><th>racks</th>';
1741 echo '<th>IPv4 VS</th><th>IPv4 RS pools</th><th>users</th><th>files</th></tr>';
1742 $pagebyrealm = array
1743 (
1744 'file' => 'filesbylink&entity_type=all',
1745 'ipv4net' => 'ipv4space&tab=default',
1746 'ipv4vs' => 'ipv4vslist&tab=default',
1747 'ipv4rspool' => 'ipv4rsplist&tab=default',
1748 'object' => 'objgroup&group_id=0',
1749 'rack' => 'rackspace&tab=default',
1750 'user' => 'userlist&tab=default'
1751 );
1752 foreach ($refc as $ref)
1753 {
1754 echo "<tr><td>${ref['tag']}</td><td>${ref['refcnt']}</td>";
1755 foreach (array ('object', 'ipv4net', 'rack', 'ipv4vs', 'ipv4rspool', 'user', 'file') as $realm)
1756 {
1757 echo '<td>';
1758 if (!isset ($taglist[$ref['id']]['refcnt'][$realm]))
1759 echo '&nbsp;';
1760 else
1761 {
1762 echo "<a href='${root}?page=" . $pagebyrealm[$realm] . "&tagfilter[]=${ref['id']}'>";
1763 echo $taglist[$ref['id']]['refcnt'][$realm] . '</a>';
1764 }
1765 echo '</td>';
1766 }
1767 echo '</tr>';
1768 }
1769 echo '</table>';
1770 }
1771
1772 /*
1773
1774 The following allows figuring out records in TagStorage, which refer to non-existing entities:
1775
1776 mysql> select entity_id from TagStorage left join Files on entity_id = id where entity_realm = 'file' and id is null;
1777 mysql> select entity_id from TagStorage left join IPv4Network on entity_id = id where entity_realm = 'ipv4net' and id is null;
1778 mysql> select entity_id from TagStorage left join RackObject on entity_id = id where entity_realm = 'object' and id is null;
1779 mysql> select entity_id from TagStorage left join Rack on entity_id = id where entity_realm = 'rack' and id is null;
1780 mysql> select entity_id from TagStorage left join IPv4VS on entity_id = id where entity_realm = 'ipv4vs' and id is null;
1781 mysql> select entity_id from TagStorage left join IPv4RSPool on entity_id = id where entity_realm = 'ipv4rspool' and id is null;
1782 mysql> select entity_id from TagStorage left join UserAccount on entity_id = user_id where entity_realm = 'user' and user_id is null;
1783
1784 Accordingly, these are the records, which refer to non-existent tags:
1785
1786 mysql> select tag_id from TagStorage left join TagTree on tag_id = id where id is null;
1787
1788 */
1789
1790 function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1791 {
1792 if ($chapter_no <= 0 or $dict_key <= 0 or empty ($dict_value))
1793 {
1794 showError ('Invalid args', __FUNCTION__);
1795 die;
1796 }
1797 global $dbxlink;
1798 $query =
1799 "update Dictionary set dict_value = '${dict_value}' where chapter_no=${chapter_no} " .
1800 "and dict_key=${dict_key} limit 1";
1801 $result = $dbxlink->query ($query);
1802 if ($result == NULL)
1803 {
1804 showError ('SQL query failed', __FUNCTION__);
1805 die;
1806 }
1807 return TRUE;
1808 }
1809
1810 function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1811 {
1812 if ($chapter_no <= 0 or empty ($dict_value))
1813 {
1814 showError ('Invalid args', __FUNCTION__);
1815 die;
1816 }
1817 return useInsertBlade
1818 (
1819 'Dictionary',
1820 array ('chapter_no' => $chapter_no, 'dict_value' => "'${dict_value}'")
1821 );
1822 }
1823
1824 function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1825 {
1826 if ($chapter_no <= 0 or $dict_key <= 0)
1827 {
1828 showError ('Invalid args', __FUNCTION__);
1829 die;
1830 }
1831 global $dbxlink;
1832 $query =
1833 "delete from Dictionary where chapter_no=${chapter_no} " .
1834 "and dict_key=${dict_key} limit 1";
1835 $result = $dbxlink->query ($query);
1836 if ($result == NULL)
1837 {
1838 showError ('SQL query failed', __FUNCTION__);
1839 die;
1840 }
1841 return TRUE;
1842 }
1843
1844 function commitAddChapter ($chapter_name = '')
1845 {
1846 if (empty ($chapter_name))
1847 {
1848 showError ('Invalid args', __FUNCTION__);
1849 die;
1850 }
1851 return useInsertBlade
1852 (
1853 'Chapter',
1854 array ('chapter_name' => "'${chapter_name}'")
1855 );
1856 }
1857
1858 function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
1859 {
1860 if ($chapter_no <= 0 or empty ($chapter_name))
1861 {
1862 showError ('Invalid args', __FUNCTION__);
1863 die;
1864 }
1865 global $dbxlink;
1866 $query =
1867 "update Chapter set chapter_name = '${chapter_name}' where chapter_no = ${chapter_no} " .
1868 "and sticky = 'no' limit 1";
1869 $result = $dbxlink->query ($query);
1870 if ($result == NULL)
1871 {
1872 showError ('SQL query failed', __FUNCTION__);
1873 die;
1874 }
1875 return TRUE;
1876 }
1877
1878 function commitDeleteChapter ($chapter_no = 0)
1879 {
1880 if ($chapter_no <= 0)
1881 {
1882 showError ('Invalid args', __FUNCTION__);
1883 die;
1884 }
1885 global $dbxlink;
1886 $query =
1887 "delete from Chapter where chapter_no = ${chapter_no} and sticky = 'no' limit 1";
1888 $result = $dbxlink->query ($query);
1889 if ($result == NULL)
1890 {
1891 showError ('SQL query failed', __FUNCTION__);
1892 die;
1893 }
1894 return TRUE;
1895 }
1896
1897 // This is a dictionary accessor. We perform link rendering, so the user sees
1898 // nice <select> drop-downs.
1899 function readChapter ($chapter_name = '')
1900 {
1901 if (empty ($chapter_name))
1902 {
1903 showError ('invalid argument', __FUNCTION__);
1904 return NULL;
1905 }
1906 $query =
1907 "select dict_key, dict_value from Dictionary natural join Chapter " .
1908 "where chapter_name = '${chapter_name}'";
1909 $result = useSelectBlade ($query, __FUNCTION__);
1910 $chapter = array();
1911 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1912 $chapter[$row['dict_key']] = parseWikiLink ($row['dict_value'], 'o');
1913 $result->closeCursor();
1914 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
1915 asort ($chapter);
1916 return $chapter;
1917 }
1918
1919 function getAttrMap ()
1920 {
1921 $query =
1922 "select a.attr_id, a.attr_type, a.attr_name, am.objtype_id, " .
1923 "d.dict_value as objtype_name, am.chapter_no, c2.chapter_name from " .
1924 "Attribute as a natural left join AttributeMap as am " .
1925 "left join Dictionary as d on am.objtype_id = d.dict_key " .
1926 "left join Chapter as c1 on d.chapter_no = c1.chapter_no " .
1927 "left join Chapter as c2 on am.chapter_no = c2.chapter_no " .
1928 "where c1.chapter_name = 'RackObjectType' or c1.chapter_name is null " .
1929 "order by attr_name";
1930 $result = useSelectBlade ($query, __FUNCTION__);
1931 $ret = array();
1932 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1933 {
1934 $attr_id = $row['attr_id'];
1935 if (!isset ($ret[$attr_id]))
1936 {
1937 $ret[$attr_id]['id'] = $attr_id;
1938 $ret[$attr_id]['type'] = $row['attr_type'];
1939 $ret[$attr_id]['name'] = $row['attr_name'];
1940 $ret[$attr_id]['application'] = array();
1941 }
1942 if ($row['objtype_id'] == '')
1943 continue;
1944 $application['objtype_id'] = $row['objtype_id'];
1945 $application['objtype_name'] = $row['objtype_name'];
1946 if ($row['attr_type'] == 'dict')
1947 {
1948 $application['chapter_no'] = $row['chapter_no'];
1949 $application['chapter_name'] = $row['chapter_name'];
1950 }
1951 $ret[$attr_id]['application'][] = $application;
1952 }
1953 $result->closeCursor();
1954 return $ret;
1955 }
1956
1957 function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
1958 {
1959 if ($attr_id <= 0 or empty ($attr_name))
1960 {
1961 showError ('Invalid args', __FUNCTION__);
1962 die;
1963 }
1964 global $dbxlink;
1965 $query =
1966 "update Attribute set attr_name = '${attr_name}' " .
1967 "where attr_id = ${attr_id} limit 1";
1968 $result = $dbxlink->query ($query);
1969 if ($result == NULL)
1970 {
1971 showError ("SQL query '${query}' failed", __FUNCTION__);
1972 die;
1973 }
1974 return TRUE;
1975 }
1976
1977 function commitAddAttribute ($attr_name = '', $attr_type = '')
1978 {
1979 if (empty ($attr_name))
1980 {
1981 showError ('Invalid args', __FUNCTION__);
1982 die;
1983 }
1984 switch ($attr_type)
1985 {
1986 case 'uint':
1987 case 'float':
1988 case 'string':
1989 case 'dict':
1990 break;
1991 default:
1992 showError ('Invalid args', __FUNCTION__);
1993 die;
1994 }
1995 return useInsertBlade
1996 (
1997 'Attribute',
1998 array ('attr_name' => "'${attr_name}'", 'attr_type' => "'${attr_type}'")
1999 );
2000 }
2001
2002 function commitDeleteAttribute ($attr_id = 0)
2003 {
2004 if ($attr_id <= 0)
2005 {
2006 showError ('Invalid args', __FUNCTION__);
2007 die;
2008 }
2009 return useDeleteBlade ('Attribute', 'attr_id', $attr_id);
2010 }
2011
2012 // FIXME: don't store garbage in chapter_no for non-dictionary types.
2013 function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
2014 {
2015 if ($attr_id <= 0 or $objtype_id <= 0 or $chapter_no <= 0)
2016 {
2017 showError ('Invalid args', __FUNCTION__);
2018 die;
2019 }
2020 return useInsertBlade
2021 (
2022 'AttributeMap',
2023 array
2024 (
2025 'attr_id' => $attr_id,
2026 'objtype_id' => $objtype_id,
2027 'chapter_no' => $chapter_no
2028 )
2029 );
2030 }
2031
2032 function commitReduceAttrMap ($attr_id = 0, $objtype_id)
2033 {
2034 if ($attr_id <= 0 or $objtype_id <= 0)
2035 {
2036 showError ('Invalid args', __FUNCTION__);
2037 die;
2038 }
2039 global $dbxlink;
2040 $query =
2041 "delete from AttributeMap where attr_id=${attr_id} " .
2042 "and objtype_id=${objtype_id} limit 1";
2043 $result = $dbxlink->query ($query);
2044 if ($result == NULL)
2045 {
2046 showError ('SQL query failed', __FUNCTION__);
2047 die;
2048 }
2049 return TRUE;
2050 }
2051
2052 // This function returns all optional attributes for requested object
2053 // as an array of records. NULL is returned on error and empty array
2054 // is returned, if there are no attributes found.
2055 function getAttrValues ($object_id, $strip_optgroup = FALSE)
2056 {
2057 if ($object_id <= 0)
2058 {
2059 showError ('Invalid argument', __FUNCTION__);
2060 return NULL;
2061 }
2062 $ret = array();
2063 $query =
2064 "select A.attr_id, A.attr_name, A.attr_type, C.chapter_name, " .
2065 "AV.uint_value, AV.float_value, AV.string_value, D.dict_value from " .
2066 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
2067 "inner join Attribute as A using (attr_id) " .
2068 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
2069 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_no = D.chapter_no " .
2070 "left join Chapter as C on AM.chapter_no = C.chapter_no " .
2071 "where RO.id = ${object_id} order by A.attr_type, A.attr_name";
2072 $result = useSelectBlade ($query, __FUNCTION__);
2073 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2074 {
2075 $record = array();
2076 $record['id'] = $row['attr_id'];
2077 $record['name'] = $row['attr_name'];
2078 $record['type'] = $row['attr_type'];
2079 switch ($row['attr_type'])
2080 {
2081 case 'uint':
2082 case 'float':
2083 case 'string':
2084 $record['value'] = $row[$row['attr_type'] . '_value'];
2085 $record['a_value'] = parseWikiLink ($record['value'], 'a');
2086 break;
2087 case 'dict':
2088 $record['value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'o', $strip_optgroup);
2089 $record['a_value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'a', $strip_optgroup);
2090 $record['chapter_name'] = $row['chapter_name'];
2091 $record['key'] = $row['uint_value'];
2092 break;
2093 default:
2094 $record['value'] = NULL;
2095 break;
2096 }
2097 $ret[$row['attr_id']] = $record;
2098 }
2099 $result->closeCursor();
2100 return $ret;
2101 }
2102
2103 function commitResetAttrValue ($object_id = 0, $attr_id = 0)
2104 {
2105 if ($object_id <= 0 or $attr_id <= 0)
2106 {
2107 showError ('Invalid arguments', __FUNCTION__);
2108 die;
2109 }
2110 global $dbxlink;
2111 $query = "delete from AttributeValue where object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2112 $result = $dbxlink->query ($query);
2113 if ($result == NULL)
2114 {
2115 showError ('SQL query failed', __FUNCTION__);
2116 die;
2117 }
2118 return TRUE;
2119 }
2120
2121 // FIXME: don't share common code with use commitResetAttrValue()
2122 function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
2123 {
2124 if ($object_id <= 0 or $attr_id <= 0)
2125 {
2126 showError ('Invalid arguments', __FUNCTION__);
2127 die;
2128 }
2129 if (empty ($value))
2130 return commitResetAttrValue ($object_id, $attr_id);
2131 global $dbxlink;
2132 $query1 = "select attr_type from Attribute where attr_id = ${attr_id}";
2133 $result = $dbxlink->query ($query1);
2134 if ($result == NULL)
2135 {
2136 showError ('SQL query #1 failed', __FUNCTION__);
2137 die;
2138 }
2139 $row = $result->fetch (PDO::FETCH_NUM);
2140 if ($row == NULL)
2141 {
2142 showError ('SQL query #1 returned no results', __FUNCTION__);
2143 die;
2144 }
2145 $attr_type = $row[0];
2146 $result->closeCursor();
2147 switch ($attr_type)
2148 {
2149 case 'uint':
2150 case 'float':
2151 case 'string':
2152 $column = $attr_type . '_value';
2153 break;
2154 case 'dict':
2155 $column = 'uint_value';
2156 break;
2157 default:
2158 showError ("Unknown attribute type '${attr_type}' met", __FUNCTION__);
2159 die;
2160 }
2161 $query2 =
2162 "delete from AttributeValue where " .
2163 "object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2164 $result = $dbxlink->query ($query2);
2165 if ($result == NULL)
2166 {
2167 showError ('SQL query #2 failed', __FUNCTION__);
2168 die;
2169 }
2170 // We know $value isn't empty here.
2171 $query3 =
2172 "insert into AttributeValue set ${column} = '${value}', " .
2173 "object_id = ${object_id}, attr_id = ${attr_id} ";
2174 $result = $dbxlink->query ($query3);
2175 if ($result == NULL)
2176 {
2177 showError ('SQL query #3 failed', __FUNCTION__);
2178 die;
2179 }
2180 return TRUE;
2181 }
2182
2183 function commitUseupPort ($port_id = 0)
2184 {
2185 if ($port_id <= 0)
2186 {
2187 showError ("Invalid argument", __FUNCTION__);
2188 die;
2189 }
2190 global $dbxlink;
2191 $query = "update Port set reservation_comment = NULL where id = ${port_id} limit 1";
2192 $result = $dbxlink->exec ($query);
2193 if ($result == NULL)
2194 {
2195 showError ("SQL query failed", __FUNCTION__);
2196 die;
2197 }
2198 return TRUE;
2199
2200 }
2201
2202 // This is a swiss-knife blade to insert a record into a table.
2203 // The first argument is table name.
2204 // The second argument is an array of "name" => "value" pairs.
2205 // The function returns either TRUE or FALSE (we expect one row
2206 // to be inserted).
2207 function useInsertBlade ($tablename, $values)
2208 {
2209 global $dbxlink;
2210 $namelist = $valuelist = '';
2211 foreach ($values as $name => $value)
2212 {
2213 $namelist = $namelist . ($namelist == '' ? "(${name}" : ", ${name}");
2214 $valuelist = $valuelist . ($valuelist == '' ? "(${value}" : ", ${value}");
2215 }
2216 $query = "insert into ${tablename} ${namelist}) values ${valuelist})";
2217 $result = $dbxlink->exec ($query);
2218 if ($result != 1)
2219 return FALSE;
2220 return TRUE;
2221 }
2222
2223 // This swiss-knife blade deletes one record from the specified table
2224 // using the specified key name and value.
2225 function useDeleteBlade ($tablename, $keyname, $keyvalue)
2226 {
2227 global $dbxlink;
2228 return 1 === $dbxlink->exec ("delete from ${tablename} where ${keyname}=${keyvalue} limit 1");
2229 }
2230
2231 function useSelectBlade ($query, $caller = 'N/A')
2232 {
2233 global $dbxlink;
2234 $result = $dbxlink->query ($query);
2235 if ($result == NULL)
2236 {
2237 $ei = $dbxlink->errorInfo();
2238 showError ("SQL query '${query}'\n failed in useSelectBlade with error ${ei[1]} (${ei[2]})", $caller);
2239 return NULL;
2240 }
2241 return $result;
2242 }
2243
2244 function loadConfigCache ()
2245 {
2246 $query = 'SELECT varname, varvalue, vartype, is_hidden, emptyok, description FROM Config ORDER BY varname';
2247 $result = useSelectBlade ($query, __FUNCTION__);
2248 $cache = array();
2249 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2250 $cache[$row['varname']] = $row;
2251 $result->closeCursor();
2252 return $cache;
2253 }
2254
2255 // setConfigVar() is expected to perform all necessary filtering
2256 function storeConfigVar ($varname = NULL, $varvalue = NULL)
2257 {
2258 global $dbxlink;
2259 if (empty ($varname) || $varvalue === NULL)
2260 {
2261 showError ('Invalid arguments', __FUNCTION__);
2262 return FALSE;
2263 }
2264 $query = "update Config set varvalue='${varvalue}' where varname='${varname}' limit 1";
2265 $result = $dbxlink->query ($query);
2266 if ($result == NULL)
2267 {
2268 showError ("SQL query '${query}' failed", __FUNCTION__);
2269 return FALSE;
2270 }
2271 $rc = $result->rowCount();
2272 $result->closeCursor();
2273 if ($rc == 0 or $rc == 1)
2274 return TRUE;
2275 showError ("Something went wrong for args '${varname}', '${varvalue}'", __FUNCTION__);
2276 return FALSE;
2277 }
2278
2279 // Database version detector. Should behave corretly on any
2280 // working dataset a user might have.
2281 function getDatabaseVersion ()
2282 {
2283 global $dbxlink;
2284 $query = "select varvalue from Config where varname = 'DB_VERSION' and vartype = 'string'";
2285 $result = $dbxlink->query ($query);
2286 if ($result == NULL)
2287 {
2288 $errorInfo = $dbxlink->errorInfo();
2289 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
2290 return '0.14.4';
2291 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
2292 }
2293 $rows = $result->fetchAll (PDO::FETCH_NUM);
2294 if (count ($rows) != 1 || empty ($rows[0][0]))
2295 {
2296 $result->closeCursor();
2297 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
2298 }
2299 $ret = $rows[0][0];
2300 $result->closeCursor();
2301 return $ret;
2302 }
2303
2304 // Return an array of virtual services. For each of them list real server pools
2305 // with their load balancers and other stats.
2306 function getSLBSummary ()
2307 {
2308 $query = 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
2309 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
2310 'from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id ' .
2311 'inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2312 'left join IPv4RS as rs on rs.rspool_id = lb.rspool_id ' .
2313 'group by vs.id, object_id order by vs.vip, object_id';
2314 $result = useSelectBlade ($query, __FUNCTION__);
2315 $ret = array();
2316 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2317 {
2318 $vsid = $row['vsid'];
2319 $object_id = $row['object_id'];
2320 if (!isset ($ret[$vsid]))
2321 {
2322 $ret[$vsid] = array();
2323 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
2324 $ret[$vsid][$cname] = $row[$cname];
2325 $ret[$vsid]['lblist'] = array();
2326 }
2327 // There's only one assigned RS pool possible for each LB-VS combination.
2328 $ret[$vsid]['lblist'][$row['object_id']] = array
2329 (
2330 'id' => $row['rspool_id'],
2331 'size' => $row['rscount'],
2332 'name' => $row['pool_name']
2333 );
2334 }
2335 $result->closeCursor();
2336 return $ret;
2337 }
2338
2339 // Get the detailed composition of a particular virtual service, namely the list
2340 // of all pools, each shown with the list of objects servicing it. VS/RS configs
2341 // will be returned as well.
2342 function getVServiceInfo ($vsid = 0)
2343 {
2344 $query1 = "select inet_ntoa(vip) as vip, vport, proto, name, vsconfig, rsconfig " .
2345 "from IPv4VS where id = ${vsid}";
2346 $result = useSelectBlade ($query1, __FUNCTION__);
2347 $vsinfo = array ();
2348 $row = $result->fetch (PDO::FETCH_ASSOC);
2349 if (!$row)
2350 return NULL;
2351 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig') as $cname)
2352 $vsinfo[$cname] = $row[$cname];
2353 $vsinfo['rspool'] = array();
2354 $result->closeCursor();
2355 unset ($result);
2356 $query2 = "select pool.id, name, pool.vsconfig, pool.rsconfig, object_id, " .
2357 "lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig from " .
2358 "IPv4RSPool as pool left join IPv4LB as lb on pool.id = lb.rspool_id " .
2359 "where vs_id = ${vsid} order by pool.name, object_id";
2360 $result = useSelectBlade ($query2, __FUNCTION__);
2361 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2362 {
2363 if (!isset ($vsinfo['rspool'][$row['id']]))
2364 {
2365 $vsinfo['rspool'][$row['id']]['name'] = $row['name'];
2366 $vsinfo['rspool'][$row['id']]['vsconfig'] = $row['vsconfig'];
2367 $vsinfo['rspool'][$row['id']]['rsconfig'] = $row['rsconfig'];
2368 $vsinfo['rspool'][$row['id']]['lblist'] = array();
2369 }
2370 if ($row['object_id'] == NULL)
2371 continue;
2372 $vsinfo['rspool'][$row['id']]['lblist'][$row['object_id']] = array
2373 (
2374 'vsconfig' => $row['lb_vsconfig'],
2375 'rsconfig' => $row['lb_rsconfig']
2376 );
2377 }
2378 $result->closeCursor();
2379 return $vsinfo;
2380 }
2381
2382 // Collect and return the following info about the given real server pool:
2383 // basic information
2384 // parent virtual service information
2385 // load balancers list (each with a list of VSes)
2386 // real servers list
2387
2388 function getRSPoolInfo ($id = 0)
2389 {
2390 $query1 = "select id, name, vsconfig, rsconfig from " .
2391 "IPv4RSPool where id = ${id}";
2392 $result = useSelectBlade ($query1, __FUNCTION__);
2393 $ret = array();
2394 $row = $result->fetch (PDO::FETCH_ASSOC);
2395 if (!$row)
2396 return NULL;
2397 foreach (array ('id', 'name', 'vsconfig', 'rsconfig') as $c)
2398 $ret[$c] = $row[$c];
2399 $result->closeCursor();
2400 unset ($result);
2401 $ret['lblist'] = array();
2402 $ret['rslist'] = array();
2403 $query2 = "select object_id, vs_id, lb.vsconfig, lb.rsconfig from " .
2404 "IPv4LB as lb inner join IPv4VS as vs on lb.vs_id = vs.id " .
2405 "where rspool_id = ${id} order by object_id, vip, vport";
2406 $result = useSelectBlade ($query2, __FUNCTION__);
2407 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2408 foreach (array ('vsconfig', 'rsconfig') as $c)
2409 $ret['lblist'][$row['object_id']][$row['vs_id']][$c] = $row[$c];
2410 $result->closeCursor();
2411 unset ($result);
2412 $query3 = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rsconfig from " .
2413 "IPv4RS where rspool_id = ${id} order by IPv4RS.rsip, rsport";
2414 $result = useSelectBlade ($query3, __FUNCTION__);
2415 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2416 foreach (array ('inservice', 'rsip', 'rsport', 'rsconfig') as $c)
2417 $ret['rslist'][$row['id']][$c] = $row[$c];
2418 $result->closeCursor();
2419 return $ret;
2420 }
2421
2422 function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
2423 {
2424 if ($pool_id <= 0)
2425 {
2426 showError ('Invalid arguments', __FUNCTION__);
2427 die;
2428 }
2429 if (empty ($rsport) or $rsport == 0)
2430 $rsport = 'NULL';
2431 return useInsertBlade
2432 (
2433 'IPv4RS',
2434 array
2435 (
2436 'rsip' => "inet_aton('${rsip}')",
2437 'rsport' => $rsport,
2438 'rspool_id' => $pool_id,
2439 'inservice' => ($inservice == 'yes' ? "'yes'" : "'no'"),
2440 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2441 )
2442 );
2443 }
2444
2445 function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig, $taglist = array())
2446 {
2447 if (empty ($vip) or $vport <= 0 or empty ($proto))
2448 return __FUNCTION__ . ': invalid arguments';
2449 if (!useInsertBlade
2450 (
2451 'IPv4VS',
2452 array
2453 (
2454 'vip' => "inet_aton('${vip}')",
2455 'vport' => $vport,
2456 'proto' => "'${proto}'",
2457 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2458 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2459 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2460 )
2461 ))
2462 return __FUNCTION__ . ': SQL insertion failed';
2463 return produceTagsForLastRecord ('ipv4vs', $taglist);
2464 }
2465
2466 function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
2467 {
2468 if ($pool_id <= 0 or $object_id <= 0 or $vs_id <= 0)
2469 {
2470 showError ('Invalid arguments', __FUNCTION__);
2471 die;
2472 }
2473 return useInsertBlade
2474 (
2475 'IPv4LB',
2476 array
2477 (
2478 'object_id' => $object_id,
2479 'rspool_id' => $pool_id,
2480 'vs_id' => $vs_id,
2481 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2482 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2483 )
2484 );
2485 }
2486
2487 function commitDeleteRS ($id = 0)
2488 {
2489 if ($id <= 0)
2490 return FALSE;
2491 return useDeleteBlade ('IPv4RS', 'id', $id);
2492 }
2493
2494 function commitDeleteVS ($id = 0)
2495 {
2496 if ($id <= 0)
2497 return FALSE;
2498 return useDeleteBlade ('IPv4VS', 'id', $id) && destroyTagsForEntity ('ipv4vs', $id);
2499 }
2500
2501 function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
2502 {
2503 global $dbxlink;
2504 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
2505 return FALSE;
2506 $query = "delete from IPv4LB where object_id = ${object_id} and " .
2507 "rspool_id = ${pool_id} and vs_id = ${vs_id} limit 1";
2508 $result = $dbxlink->exec ($query);
2509 if ($result === NULL)
2510 return FALSE;
2511 elseif ($result != 1)
2512 return FALSE;
2513 else
2514 return TRUE;
2515 }
2516
2517 function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2518 {
2519 if ($rsid <= 0)
2520 {
2521 showError ('Invalid args', __FUNCTION__);
2522 die;
2523 }
2524 if (long2ip (ip2long ($rsip)) !== $rsip)
2525 {
2526 showError ("Invalid IP address '${rsip}'", __FUNCTION__);
2527 die;
2528 }
2529 if (empty ($rsport) or $rsport == 0)
2530 $rsport = 'NULL';
2531 global $dbxlink;
2532 $query =
2533 "update IPv4RS set rsip = inet_aton('${rsip}'), rsport = ${rsport}, rsconfig = " .
2534 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2535 " where id = ${rsid} limit 1";
2536 $result = $dbxlink->query ($query);
2537 if ($result == NULL)
2538 {
2539 showError ("SQL query '${query}' failed", __FUNCTION__);
2540 die;
2541 }
2542 return TRUE;
2543 }
2544
2545 function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
2546 {
2547 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
2548 {
2549 showError ('Invalid args', __FUNCTION__);
2550 die;
2551 }
2552 global $dbxlink;
2553 $query =
2554 "update IPv4LB set vsconfig = " .
2555 (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'") .
2556 ', rsconfig = ' .
2557 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2558 " where object_id = ${object_id} and rspool_id = ${pool_id} " .
2559 "and vs_id = ${vs_id} limit 1";
2560 $result = $dbxlink->exec ($query);
2561 if ($result === NULL)
2562 return FALSE;
2563 else
2564 return TRUE;
2565 }
2566
2567 function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2568 {
2569 if ($vsid <= 0 or empty ($vip) or $vport <= 0 or empty ($proto))
2570 {
2571 showError ('Invalid args', __FUNCTION__);
2572 die;
2573 }
2574 global $dbxlink;
2575 $query = "update IPv4VS set " .
2576 "vip = inet_aton('${vip}'), " .
2577 "vport = ${vport}, " .
2578 "proto = '${proto}', " .
2579 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2580 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2581 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2582 " where id = ${vsid} limit 1";
2583 $result = $dbxlink->exec ($query);
2584 if ($result === NULL)
2585 return FALSE;
2586 else
2587 return TRUE;
2588 }
2589
2590 // Return the list of virtual services, indexed by vs_id.
2591 // Each record will be shown with its basic info plus RS pools counter.
2592 function getVSList ($tagfilter = array(), $tfmode = 'any')
2593 {
2594 $whereclause = getWhereClause ($tagfilter);
2595 $query = "select vs.id, inet_ntoa(vip) as vip, vport, proto, vs.name, vs.vsconfig, vs.rsconfig, count(rspool_id) as poolcount " .
2596 "from IPv4VS as vs left join IPv4LB as lb on vs.id = lb.vs_id " .
2597 "left join TagStorage on vs.id = TagStorage.entity_id and entity_realm = 'ipv4vs' " .
2598 "where true ${whereclause} group by vs.id order by vs.vip, proto, vport";
2599 $result = useSelectBlade ($query, __FUNCTION__);
2600 $ret = array ();
2601 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2602 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig', 'poolcount') as $cname)
2603 $ret[$row['id']][$cname] = $row[$cname];
2604 $result->closeCursor();
2605 return $ret;
2606 }
2607
2608 // Return the list of RS pool, indexed by pool id.
2609 function getRSPoolList ($tagfilter = array(), $tfmode = 'any')
2610 {
2611 $whereclause = getWhereClause ($tagfilter);
2612 $query = "select pool.id, pool.name, count(rspool_id) as refcnt, pool.vsconfig, pool.rsconfig " .
2613 "from IPv4RSPool as pool left join IPv4LB as lb on pool.id = lb.rspool_id " .
2614 "left join TagStorage on pool.id = TagStorage.entity_id and entity_realm = 'ipv4rspool' " .
2615 "where true ${whereclause} group by pool.id order by pool.name, pool.id";
2616 $result = useSelectBlade ($query, __FUNCTION__);
2617 $ret = array ();
2618 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2619 foreach (array ('name', 'refcnt', 'vsconfig', 'rsconfig') as $cname)
2620 $ret[$row['id']][$cname] = $row[$cname];
2621 $result->closeCursor();
2622 return $ret;
2623 }
2624
2625 function loadThumbCache ($rack_id = 0)
2626 {
2627 $ret = NULL;
2628 $query = "select thumb_data from Rack where id = ${rack_id} and thumb_data is not null limit 1";
2629 $result = useSelectBlade ($query, __FUNCTION__);
2630 $row = $result->fetch (PDO::FETCH_ASSOC);
2631 if ($row)
2632 $ret = base64_decode ($row['thumb_data']);
2633 $result->closeCursor();
2634 return $ret;
2635 }
2636
2637 function saveThumbCache ($rack_id = 0, $cache = NULL)
2638 {
2639 global $dbxlink;
2640 if ($rack_id == 0 or $cache == NULL)
2641 {
2642 showError ('Invalid arguments', __FUNCTION__);
2643 return;
2644 }
2645 $data = base64_encode ($cache);
2646 $query = "update Rack set thumb_data = '${data}' where id = ${rack_id} limit 1";
2647 $result = $dbxlink->exec ($query);
2648 }
2649
2650 function resetThumbCache ($rack_id = 0)
2651 {
2652 global $dbxlink;
2653 if ($rack_id == 0)
2654 {
2655 showError ('Invalid argument', __FUNCTION__);
2656 return;
2657 }
2658 $query = "update Rack set thumb_data = NULL where id = ${rack_id} limit 1";
2659 $result = $dbxlink->exec ($query);
2660 }
2661
2662 // Return the list of attached RS pools for the given object. As long as we have
2663 // the LB-VS UNIQUE in IPv4LB table, it is Ok to key returned records
2664 // by vs_id, because there will be only one RS pool listed for each VS of the
2665 // current object.
2666 function getRSPoolsForObject ($object_id = 0)
2667 {
2668 if ($object_id <= 0)
2669 {
2670 showError ('Invalid object_id', __FUNCTION__);
2671 return NULL;
2672 }
2673 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
2674 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
2675 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2676 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2677 'left join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
2678 "where lb.object_id = ${object_id} " .
2679 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name';
2680 $result = useSelectBlade ($query, __FUNCTION__);
2681 $ret = array ();
2682 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2683 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
2684 $ret[$row['vs_id']][$cname] = $row[$cname];
2685 $result->closeCursor();
2686 return $ret;
2687 }
2688
2689 function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
2690 {
2691 if (empty ($name))
2692 return __FUNCTION__ . ': invalid arguments';
2693 if (!useInsertBlade
2694 (
2695 'IPv4RSPool',
2696 array
2697 (
2698 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2699 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2700 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2701 )
2702 ))
2703 return __FUNCTION__ . ': SQL insertion failed';
2704 return produceTagsForLastRecord ('ipv4rspool', $taglist);
2705 }
2706
2707 function commitDeleteRSPool ($pool_id = 0)
2708 {
2709 global $dbxlink;
2710 if ($pool_id <= 0)
2711 return FALSE;
2712 return useDeleteBlade ('IPv4RSPool', 'id', $pool_id) && destroyTagsForEntity ('ipv4rspool', $pool_id);
2713 }
2714
2715 function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2716 {
2717 if ($pool_id <= 0)
2718 {
2719 showError ('Invalid arg', __FUNCTION__);
2720 die;
2721 }
2722 global $dbxlink;
2723 $query = "update IPv4RSPool set " .
2724 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2725 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2726 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2727 " where id = ${pool_id} limit 1";
2728 $result = $dbxlink->exec ($query);
2729 if ($result === NULL)
2730 return FALSE;
2731 elseif ($result != 1)
2732 return FALSE;
2733 else
2734 return TRUE;
2735 }
2736
2737 function getRSList ()
2738 {
2739 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
2740 "from IPv4RS order by rspool_id, IPv4RS.rsip, rsport";
2741 $result = useSelectBlade ($query, __FUNCTION__);
2742 $ret = array ();
2743 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2744 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
2745 $ret[$row['id']][$cname] = $row[$cname];
2746 $result->closeCursor();
2747 return $ret;
2748 }
2749
2750 // Return the list of all currently configured load balancers with their pool count.
2751 function getLBList ()
2752 {
2753 $query = "select object_id, count(rspool_id) as poolcount " .
2754 "from IPv4LB group by object_id order by object_id";
2755 $result = useSelectBlade ($query, __FUNCTION__);
2756 $ret = array ();
2757 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2758 $ret[$row['object_id']] = $row['poolcount'];
2759 $result->closeCursor();
2760 return $ret;
2761 }
2762
2763 // For the given object return: it vsconfig/rsconfig; the list of RS pools
2764 // attached (each with vsconfig/rsconfig in turn), each with the list of
2765 // virtual services terminating the pool. Each pool also lists all real
2766 // servers with rsconfig.
2767 function getSLBConfig ($object_id)
2768 {
2769 if ($object_id <= 0)
2770 {
2771 showError ('Invalid arg', __FUNCTION__);
2772 return NULL;
2773 }
2774 $ret = array();
2775 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2776 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2777 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
2778 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
2779 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
2780 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2781 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2782 'inner join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
2783 "where lb.object_id = ${object_id} and rs.inservice = 'yes' " .
2784 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport";
2785 $result = useSelectBlade ($query, __FUNCTION__);
2786 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2787 {
2788 $vs_id = $row['vs_id'];
2789 if (!isset ($ret[$vs_id]))
2790 {
2791 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)
2792 $ret[$vs_id][$c] = $row[$c];
2793 $ret[$vs_id]['rslist'] = array();
2794 }
2795 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2796 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
2797 }
2798 $result->closeCursor();
2799 return $ret;
2800 }
2801
2802 function commitSetInService ($rs_id = 0, $inservice = '')
2803 {
2804 if ($rs_id <= 0 or empty ($inservice))
2805 {
2806 showError ('Invalid args', __FUNCTION__);
2807 return NULL;
2808 }
2809 global $dbxlink;
2810 $query = "update IPv4RS set inservice = '${inservice}' where id = ${rs_id} limit 1";
2811 $result = $dbxlink->exec ($query);
2812 if ($result === NULL)
2813 return FALSE;
2814 elseif ($result != 1)
2815 return FALSE;
2816 else
2817 return TRUE;
2818 }
2819
2820 function executeAutoPorts ($object_id = 0, $type_id = 0)
2821 {
2822 if ($object_id == 0 or $type_id == 0)
2823 {
2824 showError ('Invalid arguments', __FUNCTION__);
2825 die;
2826 }
2827 $ret = TRUE;
2828 foreach (getAutoPorts ($type_id) as $autoport)
2829 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2830 return $ret;
2831 }
2832
2833 // Return only implicitly listed tags, the rest of the chain will be
2834 // generated/deducted later at higher levels.
2835 // Result is a chain: randomly indexed taginfo list.
2836 function loadEntityTags ($entity_realm = '', $entity_id = 0)
2837 {
2838 if ($entity_realm == '' or $entity_id <= 0)
2839 {
2840 showError ('Invalid or missing arguments', __FUNCTION__);
2841 return NULL;
2842 }
2843 $ret = array();
2844 $query = "select tt.id, tag from " .
2845 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
2846 "where entity_realm = '${entity_realm}' and entity_id = ${entity_id} " .
2847 "order by tt.tag";
2848 $result = useSelectBlade ($query, __FUNCTION__);
2849 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2850 $ret[$row['id']] = $row;
2851 $result->closeCursor();
2852 return getExplicitTagsOnly ($ret);
2853 }
2854
2855 function loadFileTags ($id)
2856 {
2857 return loadEntityTags ('file', $id);
2858 }
2859
2860 function loadRackObjectTags ($id)
2861 {
2862 return loadEntityTags ('object', $id);
2863 }
2864
2865 function loadIPv4PrefixTags ($id)
2866 {
2867 return loadEntityTags ('ipv4net', $id);
2868 }
2869
2870 function loadRackTags ($id)
2871 {
2872 return loadEntityTags ('rack', $id);
2873 }
2874
2875 function loadIPv4VSTags ($id)
2876 {
2877 return loadEntityTags ('ipv4vs', $id);
2878 }
2879
2880 function loadIPv4RSPoolTags ($id)
2881 {
2882 return loadEntityTags ('ipv4rspool', $id);
2883 }
2884
2885 function loadUserTags ($user_id)
2886 {
2887 return loadEntityTags ('user', $user_id);
2888 }
2889
2890 // Return a tag chain with all DB tags on it.
2891 function getTagList ()
2892 {
2893 $ret = array();
2894 $query = "select id, parent_id, tag, entity_realm as realm, count(entity_id) as refcnt " .
2895 "from TagTree left join TagStorage on id = tag_id " .
2896 "group by id, entity_realm order by tag";
2897 $result = useSelectBlade ($query, __FUNCTION__);
2898 $ci = 0; // Collation index. The resulting rows are ordered according to default collation,
2899 // which is utf8_general_ci for UTF-8.
2900 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2901 {
2902 if (!isset ($ret[$row['id']]))
2903 $ret[$row['id']] = array
2904 (
2905 'id' => $row['id'],
2906 'tag' => $row['tag'],
2907 'ci' => $ci++,
2908 'parent_id' => $row['parent_id'],
2909 'refcnt' => array()
2910 );
2911 if ($row['realm'])
2912 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
2913 }
2914 $result->closeCursor();
2915 return $ret;
2916 }
2917
2918 function commitCreateTag ($tagname = '', $parent_id = 0)
2919 {
2920 if ($tagname == '' or $parent_id === 0)
2921 return "Invalid args to " . __FUNCTION__;
2922 $result = useInsertBlade
2923 (
2924 'TagTree',
2925 array
2926 (
2927 'tag' => "'${tagname}'",
2928 'parent_id' => $parent_id
2929 )
2930 );
2931 if ($result)
2932 return '';
2933 else
2934 return "SQL query failed in " . __FUNCTION__;
2935 }
2936
2937 function commitDestroyTag ($tagid = 0)
2938 {
2939 if ($tagid == 0)
2940 return 'Invalid arg to ' . __FUNCTION__;
2941 if (useDeleteBlade ('TagTree', 'id', $tagid))
2942 return '';
2943 else
2944 return 'useDeleteBlade() failed in ' . __FUNCTION__;
2945 }
2946
2947 function commitUpdateTag ($tag_id, $tag_name, $parent_id)
2948 {
2949 if ($parent_id == 0)
2950 $parent_id = 'NULL';
2951 global $dbxlink;
2952 $query = "update TagTree set tag = '${tag_name}', parent_id = ${parent_id} " .
2953 "where id = ${tag_id} limit 1";
2954 $result = $dbxlink->exec ($query);
2955 if ($result === NULL)
2956 return 'SQL query failed in ' . __FUNCTION__;
2957 return '';
2958 }
2959
2960 // Drop the whole chain stored.
2961 function destroyTagsForEntity ($entity_realm, $entity_id)
2962 {
2963 global $dbxlink;
2964 $query = "delete from TagStorage where entity_realm = '${entity_realm}' and entity_id = ${entity_id}";
2965 $result = $dbxlink->exec ($query);
2966 if ($result === NULL)
2967 return FALSE;
2968 else
2969 return TRUE;
2970 }
2971
2972 // Drop only one record. This operation doesn't involve retossing other tags, unlike when adding.
2973 function deleteTagForEntity ($entity_realm, $entity_id, $tag_id)
2974 {
2975 global $dbxlink;
2976 $query = "delete from TagStorage where entity_realm = '${entity_realm}' and entity_id = ${entity_id} and tag_id = ${tag_id}";
2977 $result = $dbxlink->exec ($query);
2978 if ($result === NULL)
2979 return FALSE;
2980 else
2981 return TRUE;
2982 }
2983
2984 // Push a record into TagStorage unconditionally.
2985 function addTagForEntity ($realm = '', $entity_id, $tag_id)
2986 {
2987 if (empty ($realm))
2988 return FALSE;
2989 return useInsertBlade
2990 (
2991 'TagStorage',
2992 array
2993 (
2994 'entity_realm' => "'${realm}'",
2995 'entity_id' => $entity_id,
2996 'tag_id' => $tag_id,
2997 )
2998 );
2999 }
3000
3001 // Add records into TagStorage, if this makes sense (IOW, they don't appear
3002 // on the implicit list already). Then remove any other records, which
3003 // appear on the "implicit" side of the chain. This will make sure,
3004 // that both the tag base is still minimal and all requested tags appear on
3005 // the resulting tag chain.
3006 // Return TRUE, if any changes were committed.
3007 function rebuildTagChainForEntity ($realm, $entity_id, $extrachain = array())
3008 {
3009 // Put the current explicit sub-chain into a buffer and merge all tags from
3010 // the extra chain, which aren't there yet.
3011 $newchain = $oldchain = loadEntityTags ($realm, $entity_id);
3012 foreach ($extrachain as $extratag)
3013 if (!tagOnChain ($extratag, $newchain))
3014 $newchain[] = $extratag;
3015 // Then minimize the working buffer and check if it differs from the original
3016 // chain we started with. If it is so, save the work and signal the upper layer.
3017 $newchain = getExplicitTagsOnly ($newchain);
3018 if (tagChainCmp ($oldchain, $newchain))
3019 {
3020 destroyTagsForEntity ($realm, $entity_id);
3021 foreach ($newchain as $taginfo)
3022 addTagForEntity ($realm, $entity_id, $taginfo['id']);
3023 return TRUE;
3024 }
3025 return FALSE;
3026 }
3027
3028 // Presume, that the target record has no tags attached.
3029 function produceTagsForLastRecord ($realm, $tagidlist, $last_insert_id = 0)
3030 {
3031 if (!count ($tagidlist))
3032 return '';
3033 if (!$last_insert_id)
3034 $last_insert_id = lastInsertID();
3035 $errcount = 0;
3036 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagidlist)) as $taginfo)
3037 if (addTagForEntity ($realm, $last_insert_id, $taginfo['id']) == FALSE)
3038 $errcount++;
3039 if (!$errcount)
3040 return '';
3041 else
3042 return "Experienced ${errcount} errors adding tags in realm '${realm}' for entity ID == ${last_insert_id}";
3043 }
3044
3045 function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
3046 {
3047 // $range is in x.x.x.x/x format, split into ip/mask vars
3048 $rangeArray = explode('/', $range);
3049 if (count ($rangeArray) != 2)
3050 return "Invalid IPv4 prefix '${range}'";
3051 $ip = $rangeArray[0];
3052 $mask = $rangeArray[1];
3053
3054 if (empty ($ip) or empty ($mask))
3055 return "Invalid IPv4 prefix '${range}'";
3056 $ipL = ip2long($ip);
3057 $maskL = ip2long($mask);
3058 if ($ipL == -1 || $ipL === FALSE)
3059 return 'Bad IPv4 address';
3060 if ($mask < 32 && $mask > 0)
3061 $maskL = $mask;
3062 else
3063 {
3064 $maskB = decbin($maskL);
3065 if (strlen($maskB)!=32)
3066 return 'Invalid netmask';
3067 $ones=0;
3068 $zeroes=FALSE;
3069 foreach( str_split ($maskB) as $digit)
3070 {
3071 if ($digit == '0')
3072 $zeroes = TRUE;
3073 if ($digit == '1')
3074 {
3075 $ones++;
3076 if ($zeroes == TRUE)
3077 return 'Invalid netmask';
3078 }
3079 }
3080 $maskL = $ones;
3081 }
3082 $binmask = binMaskFromDec($maskL);
3083 $ipL = $ipL & $binmask;
3084 $result = useInsertBlade
3085 (
3086 'IPv4Network',
3087 array
3088 (
3089 'ip' => sprintf ('%u', $ipL),
3090 'mask' => "'${maskL}'",
3091 'name' => "'${name}'"
3092 )
3093 );
3094 if ($result != TRUE)
3095 return "Could not add ${range} (already exists?).";
3096
3097 if ($is_bcast and $maskL < 31)
3098 {
3099 $network_addr = long2ip ($ipL);
3100 $broadcast_addr = long2ip ($ipL | binInvMaskFromDec ($maskL));
3101 updateAddress ($network_addr, 'network', 'yes');
3102 updateAddress ($broadcast_addr, 'broadcast', 'yes');
3103 }
3104 return produceTagsForLastRecord ('ipv4net', $taglist);
3105 }
3106
3107 // FIXME: This function doesn't wipe relevant records from IPv4Address table.
3108 function destroyIPv4Prefix ($id = 0)
3109 {
3110 if ($id <= 0)
3111 return __FUNCTION__ . ': Invalid IPv4 prefix ID';
3112 if (!useDeleteBlade ('IPv4Network', 'id', $id))
3113 return __FUNCTION__ . ': SQL query #1 failed';
3114 if (!destroyTagsForEntity ('ipv4net', $id))
3115 return __FUNCTION__ . ': SQL query #2 failed';
3116 return '';
3117 }
3118
3119 function loadScript ($name)
3120 {
3121 $result = useSelectBlade ("select script_text from Script where script_name = '${name}'");
3122 $row = $result->fetch (PDO::FETCH_NUM);
3123 if ($row !== FALSE)
3124 return $row[0];
3125 else
3126 return NULL;
3127 }
3128
3129 function saveScript ($name, $text)
3130 {
3131 if (empty ($name))
3132 {
3133 showError ('Invalid argument');
3134 return FALSE;
3135 }
3136 // delete regardless of existence
3137 useDeleteBlade ('Script', 'script_name', "'${name}'");
3138 return useInsertBlade
3139 (
3140 'Script',
3141 array
3142 (
3143 'script_name' => "'${name}'",
3144 'script_text' => "'${text}'"
3145 )
3146 );
3147 }
3148
3149 function saveUserPassword ($user_id, $newp)
3150 {
3151 $newhash = hash (PASSWORD_HASH, $newp);
3152 $query = "update UserAccount set user_password_hash = ${newhash} where user_id = ${user_id} limit 1";
3153 }
3154
3155 function objectIsPortless ($id = 0)
3156 {
3157 if ($id <= 0)
3158 {
3159 showError ('Invalid argument', __FUNCTION__);
3160 return;
3161 }
3162 if (($result = useSelectBlade ("select count(id) from Port where object_id = ${id}", __FUNCTION__)) == NULL)
3163 {
3164 showError ('SQL query failed', __FUNCTION__);
3165 return;
3166 }
3167 $row = $result->fetch (PDO::FETCH_NUM);
3168 $count = $row[0];
3169 $result->closeCursor();
3170 unset ($result);
3171 return $count === '0';
3172 }
3173
3174 function recordExists ($id = 0, $realm = 'object')
3175 {
3176 if ($id <= 0)
3177 return FALSE;
3178 $table = array
3179 (
3180 'object' => 'RackObject',
3181 'ipv4net' => 'IPv4Network',
3182 'user' => 'UserAccount',
3183 );
3184 $idcol = array
3185 (
3186 'object' => 'id',
3187 'ipv4net' => 'id',
3188 'user' => 'user_id',
3189 );
3190 $query = 'select count(*) from ' . $table[$realm] . ' where ' . $idcol[$realm] . ' = ' . $id;
3191 if (($result = useSelectBlade ($query, __FUNCTION__)) == NULL)
3192 {
3193 showError ('SQL query failed', __FUNCTION__);
3194 return FALSE;
3195 }
3196 $row = $result->fetch (PDO::FETCH_NUM);
3197 $count = $row[0];
3198 $result->closeCursor();
3199 unset ($result);
3200 return $count === '1';
3201 }
3202
3203 function tagExistsInDatabase ($tname)
3204 {
3205 $result = useSelectBlade ("select count(*) from TagTree where lower(tag) = lower('${tname}')");
3206 $row = $result->fetch (PDO::FETCH_NUM);
3207 $count = $row[0];
3208 $result->closeCursor();
3209 unset ($result);
3210 return $count !== '0';
3211 }
3212
3213 function newPortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3214 {
3215 if (NULL === getIPv4AddressNetworkId ($localip))
3216 return "$localip: Non existant ip";
3217 if (NULL === getIPv4AddressNetworkId ($localip))
3218 return "$remoteip: Non existant ip";
3219 if ( ($localport <= 0) or ($localport >= 65536) )
3220 return "$localport: invaild port";
3221 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
3222 return "$remoteport: invaild port";
3223
3224 $result = useInsertBlade
3225 (
3226 'IPv4NAT',
3227 array
3228 (
3229 'object_id' => $object_id,
3230 'localip' => "INET_ATON('${localip}')",
3231 'remoteip' => "INET_ATON('$remoteip')",
3232 'localport' => $localport,
3233 'remoteport' => $remoteport,
3234 'proto' => "'${proto}'",
3235 'description' => "'${description}'",
3236 )
3237 );
3238 if ($result)
3239 return '';
3240 else
3241 return __FUNCTION__ . ': Failed to insert the rule.';
3242 }
3243
3244 function deletePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
3245 {
3246 global $dbxlink;
3247
3248 $query =
3249 "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'";
3250 $result = $dbxlink->exec ($query);
3251 return '';
3252 }
3253
3254 function updatePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3255 {
3256 global $dbxlink;
3257
3258 $query =
3259 "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'";
3260 $result = $dbxlink->exec ($query);
3261 return '';
3262 }
3263
3264 function getNATv4ForObject ($object_id)
3265 {
3266 $ret = array();
3267 $ret['out'] = array();
3268 $ret['in'] = array();
3269 $query =
3270 "select ".
3271 "proto, ".
3272 "INET_NTOA(localip) as localip, ".
3273 "localport, ".
3274 "INET_NTOA(remoteip) as remoteip, ".
3275 "remoteport, ".
3276 "ipa1.name as local_addr_name, " .
3277 "ipa2.name as remote_addr_name, " .
3278 "description ".
3279 "from IPv4NAT ".
3280 "left join IPv4Address as ipa1 on IPv4NAT.localip = ipa1.ip " .
3281 "left join IPv4Address as ipa2 on IPv4NAT.remoteip = ipa2.ip " .
3282 "where object_id='$object_id' ".
3283 "order by localip, localport, proto, remoteip, remoteport";
3284 $result = useSelectBlade ($query, __FUNCTION__);
3285 $count=0;
3286 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3287 {
3288 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
3289 $ret['out'][$count][$cname] = $row[$cname];
3290 $count++;
3291 }
3292 $result->closeCursor();
3293 unset ($result);
3294
3295 $query =
3296 "select ".
3297 "proto, ".
3298 "INET_NTOA(localip) as localip, ".
3299 "localport, ".
3300 "INET_NTOA(remoteip) as remoteip, ".
3301 "remoteport, ".
3302 "IPv4NAT.object_id as object_id, ".
3303 "RackObject.name as object_name, ".
3304 "description ".
3305 "from ((IPv4NAT join IPv4Allocation on remoteip=IPv4Allocation.ip) join RackObject on IPv4NAT.object_id=RackObject.id) ".
3306 "where IPv4Allocation.object_id='$object_id' ".
3307 "order by remoteip, remoteport, proto, localip, localport";
3308 $result = useSelectBlade ($query, __FUNCTION__);
3309 $count=0;
3310 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3311 {
3312 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
3313 $ret['in'][$count][$cname] = $row[$cname];
3314 $count++;
3315 }
3316 $result->closeCursor();
3317
3318 return $ret;
3319 }
3320
3321 // This function performs search and then calculates score for each result.
3322 // Given previous search results in $objects argument, it adds new results
3323 // to the array and updates score for existing results, if it is greater than
3324 // existing score.
3325 function mergeSearchResults (&$objects, $terms, $fieldname)
3326 {
3327 global $dbxlink;
3328 $query =
3329 "select name, label, asset_no, barcode, ro.id, dict_key as objtype_id, " .
3330 "dict_value as objtype_name, asset_no from RackObject as ro inner join Dictionary " .
3331 "on objtype_id = dict_key natural join Chapter where chapter_name = 'RackObjectType' and ";
3332 $count = 0;
3333 foreach (explode (' ', $terms) as $term)
3334 {
3335 if ($count) $query .= ' or ';
3336 $query .= "${fieldname} like '%$term%'";
3337 $count++;
3338 }
3339 $query .= " order by ${fieldname}";
3340 $result = useSelectBlade ($query, __FUNCTION__);
3341 // FIXME: this dead call was executed 4 times per 1 object search!
3342 // $typeList = getObjectTypeList();
3343 $clist = array ('id', 'name', 'label', 'asset_no', 'barcode', 'objtype_id', 'objtype_name');
3344 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3345 {
3346 foreach ($clist as $cname)
3347 $object[$cname] = $row[$cname];
3348 $object['score'] = 0;
3349 $object['dname'] = displayedName ($object);
3350 unset ($object['objtype_id']);
3351 foreach (explode (' ', $terms) as $term)
3352 if (strstr ($object['name'], $term))
3353 $object['score'] += 1;
3354 unset ($object['name']);
3355 if (!isset ($objects[$row['id']]))
3356 $objects[$row['id']] = $object;
3357 elseif ($objects[$row['id']]['score'] < $object['score'])
3358 $objects[$row['id']]['score'] = $object['score'];
3359 }
3360 return $objects;
3361 }
3362
3363 function getLostIPv4Addresses ()
3364 {
3365 dragon();
3366 }
3367
3368 // File-related functions
3369 function getAllFiles ()
3370 {
3371 $query = "SELECT id, name, type, size, ctime, mtime, atime, comment FROM File ORDER BY name";
3372 $result = useSelectBlade ($query, __FUNCTION__);
3373 $ret=array();
3374 $count=0;
3375 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3376 {
3377 $ret[$count]['id'] = $row['id'];
3378 $ret[$count]['name'] = $row['name'];
3379 $ret[$count]['type'] = $row['type'];
3380 $ret[$count]['size'] = $row['size'];
3381 $ret[$count]['ctime'] = $row['ctime'];
3382 $ret[$count]['mtime'] = $row['mtime'];
3383 $ret[$count]['atime'] = $row['atime'];
3384 $ret[$count]['comment'] = $row['comment'];
3385 $count++;
3386 }
3387 $result->closeCursor();
3388 return $ret;
3389 }
3390
3391 // Return a list of files which are not linked to the specified record. This list
3392 // will be used by printSelect().
3393 function getAllUnlinkedFiles ($entity_type = NULL, $entity_id = 0)
3394 {
3395 if ($entity_type == NULL || $entity_id == 0)
3396 {
3397 showError ('Invalid parameters', __FUNCTION__);
3398 return NULL;
3399 }
3400 global $dbxlink;
3401 $sql =
3402 'SELECT id, name FROM File ' .
3403 'WHERE id NOT IN (SELECT file_id FROM FileLink WHERE entity_type = ? AND entity_id = ?) ' .