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