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