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