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