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