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