r2190 - initial unified tree hacks
[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 (produceTagsForLastRecord ('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 = produceTagsForLastRecord ('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 all IPv4 addresses allocated to the objects. Attach detailed
898 // info about address to each alocation records. Index result by dotted-quad
899 // address.
900 function getObjectIPv4Allocations ($object_id = 0)
901 {
902 $ret = array();
903 $query = 'select name as osif, type, inet_ntoa(ip) as dottedquad from IPBonds ' .
904 "where object_id = ${object_id} " .
905 'order by ip';
906 $result = useSelectBlade ($query, __FUNCTION__);
907 // don't spawn a sub-query with unfetched buffer, it may fail
908 while ($row = $result->fetch (PDO::FETCH_ASSOC))
909 $ret[$row['dottedquad']] = array ('osif' => $row['osif'], 'type' => $row['type']);
910 unset ($result);
911 foreach (array_keys ($ret) as $dottedquad)
912 $ret[$dottedquad]['addrinfo'] = getIPv4Address ($dottedquad);
913 return $ret;
914 }
915
916 // Return minimal IPv4 address, optionally with "ip" key set, if requested.
917 function constructIPv4Address ($dottedquad = NULL)
918 {
919 $ret = array
920 (
921 'name' => '',
922 'reserved' => 'no',
923 'outpf' => array(),
924 'inpf' => array(),
925 'rslist' => array(),
926 'allocs' => array(),
927 'lblist' => array()
928 );
929 if ($dottedquad != NULL)
930 $ret['ip'] = $dottedquad;
931 return $ret;
932 }
933
934 // Check the range requested for meaningful IPv4 records, build them
935 // into a list and return. Return an empty list if nothing matched.
936 // Both arguments are expected in signed int32 form. The resulting list
937 // is keyed by uint32 form of each IP address, items aren't sorted.
938 function scanIPv4Space ($i32_first, $i32_last)
939 {
940 $ret = array();
941 $dnamechache = array();
942
943 $db_first = sprintf ('%u', 0x00000000 + $i32_first);
944 $db_last = sprintf ('%u', 0x00000000 + $i32_last);
945 // 1. collect labels and reservations
946 $query = "select INET_NTOA(ip) as ip, name, reserved from IPAddress ".
947 "where ip between ${db_first} and ${db_last} and (reserved = 'yes' or name != '')";
948 $result = useSelectBlade ($query, __FUNCTION__);
949 while ($row = $result->fetch (PDO::FETCH_ASSOC))
950 {
951 $ip_bin = ip2long ($row['ip']);
952 if (!isset ($ret[$ip_bin]))
953 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
954 $ret[$ip_bin]['name'] = $row['name'];
955 $ret[$ip_bin]['reserved'] = $row['reserved'];
956 }
957 unset ($result);
958
959 // 2. check for allocations
960 $query =
961 "select INET_NTOA(ipb.ip) as ip, ro.id as object_id, " .
962 "ro.name as object_name, ipb.name, ipb.type, objtype_id, " .
963 "dict_value as objtype_name from " .
964 "IPBonds as ipb inner join RackObject as ro on ipb.object_id = ro.id " .
965 "left join Dictionary on objtype_id=dict_key natural join Chapter " .
966 "where ip between ${db_first} and ${db_last} " .
967 "and chapter_name = 'RackObjectType'" .
968 "order by ipb.type, object_name";
969 $result = useSelectBlade ($query, __FUNCTION__);
970 while ($row = $result->fetch (PDO::FETCH_ASSOC))
971 {
972 $ip_bin = ip2long ($row['ip']);
973 if (!isset ($ret[$ip_bin]))
974 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
975 if (!isset ($dnamecache[$row['object_id']]))
976 {
977 $quasiobject['name'] = $row['object_name'];
978 $quasiobject['objtype_id'] = $row['objtype_id'];
979 $quasiobject['objtype_name'] = $row['objtype_name'];
980 $dnamecache[$row['object_id']] = displayedName ($quasiobject);
981 }
982 $tmp = array();
983 foreach (array ('object_id', 'type', 'name') as $cname)
984 $tmp[$cname] = $row[$cname];
985 $tmp['object_name'] = $dnamecache[$row['object_id']];
986 $ret[$ip_bin]['allocs'][] = $tmp;
987 }
988 unset ($result);
989
990 // 3. look for virtual services and related LB
991 $query = "select vs_id, inet_ntoa(vip) as ip, vport, proto, vs.name, " .
992 "object_id, objtype_id, ro.name as object_name, dict_value as objtype_name from " .
993 "IPVirtualService as vs inner join IPLoadBalancer as lb on vs.id = lb.vs_id " .
994 "inner join RackObject as ro on lb.object_id = ro.id " .
995 "left join Dictionary on objtype_id=dict_key " .
996 "natural join Chapter " .
997 "where vip between ${db_first} and ${db_last} " .
998 "and chapter_name = 'RackObjectType'" .
999 "order by vport, proto, ro.name, object_id";
1000 $result = useSelectBlade ($query, __FUNCTION__);
1001 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1002 {
1003 $ip_bin = ip2long ($row['ip']);
1004 if (!isset ($ret[$ip_bin]))
1005 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1006 if (!isset ($dnamecache[$row['object_id']]))
1007 {
1008 $quasiobject['name'] = $row['object_name'];
1009 $quasiobject['objtype_id'] = $row['objtype_id'];
1010 $quasiobject['objtype_name'] = $row['objtype_name'];
1011 $dnamecache[$row['object_id']] = displayedName ($quasiobject);
1012 }
1013 $tmp = array();
1014 foreach (array ('object_id', 'vport', 'proto', 'vs_id', 'name') as $cname)
1015 $tmp[$cname] = $row[$cname];
1016 $tmp['object_name'] = $dnamecache[$row['object_id']];
1017 $tmp['vip'] = $row['ip'];
1018 $ret[$ip_bin]['lblist'][] = $tmp;
1019 }
1020 unset ($result);
1021
1022 // 4. don't forget about real servers along with pools
1023 $query = "select inet_ntoa(rsip) as ip, inservice, rsport, rspool_id, rsp.name as rspool_name from " .
1024 "IPRealServer as rs inner join IPRSPool as rsp on rs.rspool_id = rsp.id " .
1025 "where rsip between ${db_first} and ${db_last} " .
1026 "order by ip, rsport, rspool_id";
1027 $result = useSelectBlade ($query, __FUNCTION__);
1028 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1029 {
1030 $ip_bin = ip2long ($row['ip']);
1031 if (!isset ($ret[$ip_bin]))
1032 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1033 $tmp = array();
1034 foreach (array ('rspool_id', 'rsport', 'rspool_name', 'inservice') as $cname)
1035 $tmp[$cname] = $row[$cname];
1036 $ret[$ip_bin]['rslist'][] = $tmp;
1037 }
1038 unset ($result);
1039
1040 // 5. add NAT rules, part 1
1041 $query =
1042 "select " .
1043 "proto, " .
1044 "INET_NTOA(localip) as localip, " .
1045 "localport, " .
1046 "INET_NTOA(remoteip) as remoteip, " .
1047 "remoteport, " .
1048 "description " .
1049 "from PortForwarding " .
1050 "where remoteip between ${db_first} and ${db_last} or " .
1051 "localip between ${db_first} and ${db_last} " .
1052 "order by localip, localport, remoteip, remoteport, proto";
1053 $result = useSelectBlade ($query, __FUNCTION__);
1054 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1055 {
1056 $remoteip_bin = ip2long ($row['remoteip']);
1057 $localip_bin = ip2long ($row['localip']);
1058 if ($i32_first <= $remoteip_bin and $remoteip_bin <= $i32_last)
1059 {
1060 if (!isset ($ret[$remoteip_bin]))
1061 $ret[$remoteip_bin] = constructIPv4Address ($row['remoteip']);
1062 $ret[$remoteip_bin]['inpf'][] = $row;
1063 }
1064 if ($i32_first <= $localip_bin and $localip_bin <= $i32_last)
1065 {
1066 if (!isset ($ret[$localip_bin]))
1067 $ret[$localip_bin] = constructIPv4Address ($row['localip']);
1068 $ret[$localip_bin]['outpf'][] = $row;
1069 }
1070 }
1071 return $ret;
1072 }
1073
1074 // Return summary data about an IPv4 prefix, if it exists, or NULL otherwise.
1075 function getIPv4NetworkInfo ($id = 0)
1076 {
1077 if ($id <= 0)
1078 {
1079 showError ('Invalid arg', __FUNCTION__);
1080 return NULL;
1081 }
1082 $query = "select INET_NTOA(ip) as ip, mask, name ".
1083 "from IPRanges where id = $id";
1084 $result = useSelectBlade ($query, __FUNCTION__);
1085 $ret = $result->fetch (PDO::FETCH_ASSOC);
1086 if ($ret == NULL)
1087 return NULL;
1088 unset ($result);
1089 $ret['id'] = $id;
1090 $ret['ip_bin'] = ip2long ($ret['ip']);
1091 $ret['mask_bin'] = binMaskFromDec ($ret['mask']);
1092 $ret['mask_bin_inv'] = binInvMaskFromDec ($ret['mask']);
1093 $ret['db_first'] = sprintf ('%u', 0x00000000 + $ret['ip_bin'] & $ret['mask_bin']);
1094 $ret['db_last'] = sprintf ('%u', 0x00000000 + $ret['ip_bin'] | ($ret['mask_bin_inv']));
1095 $ret['parent_id'] = getIPv4AddressNetworkId ($ret['ip'], $ret['mask']);
1096 return $ret;
1097 }
1098
1099 function getIPv4Network ($id = 0)
1100 {
1101 $ret = getIPv4NetworkInfo ($id);
1102 if (!$ret)
1103 {
1104 showError ('Record not found', __FUNCTION__);
1105 return NULL;
1106 }
1107 $ret['addrlist'] = scanIPv4Space ($ret['db_first'], $ret['db_last']);
1108 markupIPv4AddrList ($ret['addrlist']);
1109 return $ret;
1110 }
1111
1112 function getIPv4Address ($dottedquad = '')
1113 {
1114 if ($dottedquad == '')
1115 {
1116 showError ('Invalid arg', __FUNCTION__);
1117 return NULL;
1118 }
1119 $i32 = ip2long ($dottedquad); // signed 32 bit
1120 $scanres = scanIPv4Space ($i32, $i32);
1121 if (!isset ($scanres[$i32]))
1122 return constructIPv4Address ($dottedquad);
1123 markupIPv4AddrList ($scanres);
1124 return $scanres[$i32];
1125 }
1126
1127 function bindIpToObject ($ip = '', $object_id = 0, $name = '', $type = '')
1128 {
1129 $result = useInsertBlade
1130 (
1131 'IPBonds',
1132 array
1133 (
1134 'ip' => "INET_ATON('$ip')",
1135 'object_id' => "'${object_id}'",
1136 'name' => "'${name}'",
1137 'type' => "'${type}'"
1138 )
1139 );
1140 return $result ? '' : (__FUNCTION__ . '(): useInsertBlade() failed');
1141 }
1142
1143 function getIPv4NetworkList ($tagfilter = array(), $tfmode = 'any')
1144 {
1145 $whereclause = getWhereClause ($tagfilter);
1146 $query =
1147 "select distinct id ".
1148 "from IPRanges left join TagStorage on id = target_id and target_realm = 'ipv4net' " .
1149 "where true ${whereclause} order by ip";
1150 $result = useSelectBlade ($query, __FUNCTION__);
1151 $ret = array();
1152 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1153 $ret[$row['id']] = NULL;
1154 unset ($result);
1155 $keys = array_keys ($ret);
1156 foreach ($keys as $netid)
1157 {
1158 $ret[$netid] = getIPv4NetworkInfo ($netid);
1159 if ($ret[$netid]['parent_id'] and !in_array ($ret[$netid]['parent_id'], $keys))
1160 {
1161 $ret[$netid]['real_parent_id'] = $ret[$netid]['parent_id'];
1162 $ret[$netid]['parent_id'] = NULL;
1163 }
1164 }
1165 return $ret;
1166 }
1167
1168 function getAddressspaceList ($tagfilter = array(), $tfmode = 'any')
1169 {
1170 $whereclause = getWhereClause ($tagfilter);
1171 $query =
1172 "select distinct ".
1173 "id as IPRanges_id, ".
1174 "INET_NTOA(ip) as IPRanges_ip, ".
1175 "mask as IPRanges_mask, ".
1176 "name as IPRanges_name ".
1177 "from IPRanges left join TagStorage on IPRanges.id = TagStorage.target_id and target_realm = 'ipv4net' " .
1178 "where true ${whereclause} " .
1179 " order by ip";
1180 $result = useSelectBlade ($query, __FUNCTION__);
1181 $ret=array();
1182 $count=0;
1183 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1184 {
1185 $ret[$count]['id'] = $row['IPRanges_id'];
1186 $ret[$count]['ip'] = $row['IPRanges_ip'];
1187 $ret[$count]['ip_bin'] = ip2long($row['IPRanges_ip']);
1188 $ret[$count]['name'] = $row['IPRanges_name'];
1189 $ret[$count]['mask'] = $row['IPRanges_mask'];
1190 $ret[$count]['mask_bin'] = binMaskFromDec($row['IPRanges_mask']);
1191 $ret[$count]['mask_bin_inv'] = binInvMaskFromDec($row['IPRanges_mask']);
1192 $count++;
1193 }
1194 $result->closeCursor();
1195 return $ret;
1196
1197 }
1198
1199 // Return the id of the smallest IPv4 network containing the given IPv4 address
1200 // or NULL, if nothing was found. When finding the covering network for
1201 // another network, it is important to filter out matched records with longer
1202 // masks (they aren't going to be the right pick).
1203 function getIPv4AddressNetworkId ($dottedquad, $masklen = 32)
1204 {
1205 $query = 'select id from IPRanges where ' .
1206 "inet_aton('${dottedquad}') & (4294967295 >> (32 - mask)) << (32 - mask) = ip " .
1207 "and mask < ${masklen} " .
1208 'order by mask desc limit 1';
1209 $result = useSelectBlade ($query, __FUNCTION__);
1210 if ($row = $result->fetch (PDO::FETCH_ASSOC))
1211 return $row['id'];
1212 return NULL;
1213 }
1214
1215 function updateRange ($id=0, $name='')
1216 {
1217 global $dbxlink;
1218 $query =
1219 "update IPRanges set name='$name' where id='$id'";
1220 $result = $dbxlink->exec ($query);
1221 return '';
1222 }
1223
1224 // This function is actually used not only to update, but also to create records,
1225 // that's why ON DUPLICATE KEY UPDATE was replaced by DELETE-INSERT pair
1226 // (MySQL 4.0 workaround).
1227 function updateAddress ($ip = 0, $name = '', $reserved = 'no')
1228 {
1229 // DELETE may safely fail.
1230 $r = useDeleteBlade ('IPAddress', 'ip', "INET_ATON('${ip}')");
1231 // INSERT may appear not necessary.
1232 if ($name == '' and $reserved == 'no')
1233 return '';
1234 if (useInsertBlade ('IPAddress', array ('name' => "'${name}'", 'reserved' => "'${reserved}'", 'ip' => "INET_ATON('${ip}')")))
1235 return '';
1236 else
1237 return __FUNCTION__ . '(): useInsertBlade() failed';
1238 }
1239
1240 function updateBond ($ip='', $object_id=0, $name='', $type='')
1241 {
1242 global $dbxlink;
1243
1244 $query =
1245 "update IPBonds set name='$name', type='$type' where ip=INET_ATON('$ip') and object_id='$object_id'";
1246 $result = $dbxlink->exec ($query);
1247 return '';
1248 }
1249
1250 function unbindIpFromObject ($ip='', $object_id=0)
1251 {
1252 global $dbxlink;
1253
1254 $query =
1255 "delete from IPBonds where ip=INET_ATON('$ip') and object_id='$object_id'";
1256 $result = $dbxlink->exec ($query);
1257 return '';
1258 }
1259
1260 // This function returns either all or one user account. Array key is user name.
1261 function getUserAccounts ($tagfilter = array(), $tfmode = 'any')
1262 {
1263 $whereclause = getWhereClause ($tagfilter);
1264 $query =
1265 'select user_id, user_name, user_password_hash, user_realname, user_enabled ' .
1266 'from UserAccount left join TagStorage ' .
1267 "on UserAccount.user_id = TagStorage.target_id and target_realm = 'user' " .
1268 "where true ${whereclause} " .
1269 'order by user_name';
1270 $result = useSelectBlade ($query, __FUNCTION__);
1271 $ret = array();
1272 $clist = array ('user_id', 'user_name', 'user_realname', 'user_password_hash', 'user_enabled');
1273 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1274 foreach ($clist as $cname)
1275 $ret[$row['user_name']][$cname] = $row[$cname];
1276 $result->closeCursor();
1277 return $ret;
1278 }
1279
1280 function searchByl2address ($l2addr)
1281 {
1282 $l2addr = l2addressForDatabase ($l2addr);
1283 $query = "select object_id, Port.id as port_id from RackObject as ro inner join Port on ro.id = Port.object_id " .
1284 "where l2address = ${l2addr}";
1285 $result = useSelectBlade ($query, __FUNCTION__);
1286 $rows = $result->fetchAll (PDO::FETCH_ASSOC);
1287 $result->closeCursor();
1288 if (count ($rows) == 0) // No results.
1289 return NULL;
1290 if (count ($rows) == 1) // Target found.
1291 return $rows[0];
1292 showError ('More than one results was found. This is probably a broken unique key.', __FUNCTION__);
1293 return NULL;
1294 }
1295
1296 function getIPv4PrefixSearchResult ($terms)
1297 {
1298 $query = "select id, inet_ntoa(ip) as ip, mask, name from IPRanges where ";
1299 $or = '';
1300 foreach (explode (' ', $terms) as $term)
1301 {
1302 $query .= $or . "name like '%${term}%'";
1303 $or = ' or ';
1304 }
1305 $result = useSelectBlade ($query, __FUNCTION__);
1306 $ret = array();
1307 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1308 $ret[] = $row;
1309 return $ret;
1310 }
1311
1312 function getIPv4AddressSearchResult ($terms)
1313 {
1314 $query = "select inet_ntoa(ip) as ip, name from IPAddress where ";
1315 $or = '';
1316 foreach (explode (' ', $terms) as $term)
1317 {
1318 $query .= $or . "name like '%${term}%'";
1319 $or = ' or ';
1320 }
1321 $result = useSelectBlade ($query, __FUNCTION__);
1322 $ret = array();
1323 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1324 $ret[] = $row;
1325 return $ret;
1326 }
1327
1328 function getIPv4RSPoolSearchResult ($terms)
1329 {
1330 $query = "select id as pool_id, name from IPRSPool where ";
1331 $or = '';
1332 foreach (explode (' ', $terms) as $term)
1333 {
1334 $query .= $or . "name like '%${term}%'";
1335 $or = ' or ';
1336 }
1337 $result = useSelectBlade ($query, __FUNCTION__);
1338 $ret = array();
1339 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1340 $ret[] = $row;
1341 return $ret;
1342 }
1343
1344 function getIPv4VServiceSearchResult ($terms)
1345 {
1346 $query = "select id, inet_ntoa(vip) as vip, vport, proto, name from IPVirtualService where ";
1347 $or = '';
1348 foreach (explode (' ', $terms) as $term)
1349 {
1350 $query .= $or . "name like '%${term}%'";
1351 $or = ' or ';
1352 }
1353 $result = useSelectBlade ($query, __FUNCTION__);
1354 $ret = array();
1355 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1356 $ret[] = $row;
1357 return $ret;
1358 }
1359
1360 function getAccountSearchResult ($terms)
1361 {
1362 return getSearchResultByField
1363 (
1364 'UserAccount',
1365 array ('user_id', 'user_name', 'user_realname'),
1366 'user_name',
1367 $terms,
1368 'user_name'
1369 );
1370 }
1371
1372 function getSearchResultByField ($tname, $rcolumns, $scolumn, $terms, $ocolumn = '')
1373 {
1374 $pfx = '';
1375 $query = 'select ';
1376 foreach ($rcolumns as $col)
1377 {
1378 $query .= $pfx . $col;
1379 $pfx = ', ';
1380 }
1381 $pfx = '';
1382 $query .= " from ${tname} where ";
1383 foreach (explode (' ', $terms) as $term)
1384 {
1385 $query .= $pfx . "${scolumn} like '%${term}%'";
1386 $pfx = ' or ';
1387 }
1388 if ($ocolumn != '')
1389 $query .= " order by ${ocolumn}";
1390 $result = useSelectBlade ($query, __FUNCTION__);
1391 $ret = array();
1392 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1393 $ret[] = $row;
1394 return $ret;
1395 }
1396
1397 // This function returns either port ID or NULL for specified arguments.
1398 function getPortID ($object_id, $port_name)
1399 {
1400 $query = "select id from Port where object_id=${object_id} and name='${port_name}' limit 2";
1401 $result = useSelectBlade ($query, __FUNCTION__);
1402 $rows = $result->fetchAll (PDO::FETCH_NUM);
1403 if (count ($rows) != 1)
1404 return NULL;
1405 $ret = $rows[0][0];
1406 $result->closeCursor();
1407 return $ret;
1408 }
1409
1410 function commitCreateUserAccount ($username, $realname, $password)
1411 {
1412 return useInsertBlade
1413 (
1414 'UserAccount',
1415 array
1416 (
1417 'user_name' => "'${username}'",
1418 'user_realname' => "'${realname}'",
1419 'user_password_hash' => "'${password}'"
1420 )
1421 );
1422 }
1423
1424 function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
1425 {
1426 global $dbxlink;
1427 $query =
1428 "update UserAccount set user_name = '${new_username}', user_realname = '${new_realname}', " .
1429 "user_password_hash = '${new_password}' where user_id = ${id} limit 1";
1430 $result = $dbxlink->query ($query);
1431 if ($result == NULL)
1432 {
1433 showError ('SQL query failed', __FUNCTION__);
1434 die;
1435 }
1436 return TRUE;
1437 }
1438
1439 function commitEnableUserAccount ($id, $new_enabled_value)
1440 {
1441 global $dbxlink;
1442 $query =
1443 "update UserAccount set user_enabled = '${new_enabled_value}' " .
1444 "where user_id = ${id} limit 1";
1445 $result = $dbxlink->query ($query);
1446 if ($result == NULL)
1447 {
1448 showError ('SQL query failed', __FUNCTION__);
1449 die;
1450 }
1451 return TRUE;
1452 }
1453
1454 // This function returns an array of all port type pairs from PortCompat table.
1455 function getPortCompat ()
1456 {
1457 $query =
1458 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
1459 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
1460 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
1461 "inner join Chapter as c1 on d1.chapter_no = c1.chapter_no " .
1462 "inner join Chapter as c2 on d2.chapter_no = c2.chapter_no " .
1463 "where c1.chapter_name = 'PortType' and c2.chapter_name = 'PortType'";
1464 $result = useSelectBlade ($query, __FUNCTION__);
1465 $ret = $result->fetchAll (PDO::FETCH_ASSOC);
1466 $result->closeCursor();
1467 return $ret;
1468 }
1469
1470 function removePortCompat ($type1 = 0, $type2 = 0)
1471 {
1472 global $dbxlink;
1473 if ($type1 == 0 or $type2 == 0)
1474 {
1475 showError ('Invalid arguments', __FUNCTION__);
1476 die;
1477 }
1478 $query = "delete from PortCompat where type1 = ${type1} and type2 = ${type2} limit 1";
1479 $result = $dbxlink->query ($query);
1480 if ($result == NULL)
1481 {
1482 showError ('SQL query failed', __FUNCTION__);
1483 die;
1484 }
1485 return TRUE;
1486 }
1487
1488 function addPortCompat ($type1 = 0, $type2 = 0)
1489 {
1490 if ($type1 <= 0 or $type2 <= 0)
1491 {
1492 showError ('Invalid arguments', __FUNCTION__);
1493 die;
1494 }
1495 return useInsertBlade
1496 (
1497 'PortCompat',
1498 array ('type1' => $type1, 'type2' => $type2)
1499 );
1500 }
1501
1502 // This function returns the dictionary as an array of trees, each tree
1503 // representing a single chapter. Each element has 'id', 'name', 'sticky'
1504 // and 'word' keys with the latter holding all the words within the chapter.
1505 function getDict ($parse_links = FALSE)
1506 {
1507 $query1 =
1508 "select chapter_name, Chapter.chapter_no, dict_key, dict_value, sticky from " .
1509 "Chapter natural left join Dictionary order by chapter_name, dict_value";
1510 $result = useSelectBlade ($query1, __FUNCTION__);
1511 $dict = array();
1512 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1513 {
1514 $chapter_no = $row['chapter_no'];
1515 if (!isset ($dict[$chapter_no]))
1516 {
1517 $dict[$chapter_no]['no'] = $chapter_no;
1518 $dict[$chapter_no]['name'] = $row['chapter_name'];
1519 $dict[$chapter_no]['sticky'] = $row['sticky'] == 'yes' ? TRUE : FALSE;
1520 $dict[$chapter_no]['word'] = array();
1521 }
1522 if ($row['dict_key'] != NULL)
1523 {
1524 $dict[$chapter_no]['word'][$row['dict_key']] = $parse_links ?
1525 parseWikiLink ($row['dict_value'], 'a') : $row['dict_value'];
1526 $dict[$chapter_no]['refcnt'][$row['dict_key']] = 0;
1527 }
1528 }
1529 $result->closeCursor();
1530 unset ($result);
1531 // Find the list of all assigned values of dictionary-addressed attributes, each with
1532 // chapter/word keyed reference counters. Use the structure to adjust reference counters
1533 // of the returned disctionary words.
1534 $query2 = "select a.attr_id, am.chapter_no, uint_value, count(object_id) as refcnt " .
1535 "from Attribute as a inner join AttributeMap as am on a.attr_id = am.attr_id " .
1536 "inner join AttributeValue as av on a.attr_id = av.attr_id " .
1537 "inner join Dictionary as d on am.chapter_no = d.chapter_no and av.uint_value = d.dict_key " .
1538 "where attr_type = 'dict' group by a.attr_id, am.chapter_no, uint_value " .
1539 "order by a.attr_id, am.chapter_no, uint_value";
1540 $result = useSelectBlade ($query2, __FUNCTION__);
1541 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1542 $dict[$row['chapter_no']]['refcnt'][$row['uint_value']] = $row['refcnt'];
1543 $result->closeCursor();
1544 return $dict;
1545 }
1546
1547 function getDictStats ()
1548 {
1549 $stock_chapters = array (1, 2, 3, 11, 12, 13, 14, 16, 17, 18, 19, 20, 21, 22, 23);
1550 $query =
1551 "select Chapter.chapter_no, chapter_name, count(dict_key) as wc from " .
1552 "Chapter natural left join Dictionary group by Chapter.chapter_no";
1553 $result = useSelectBlade ($query, __FUNCTION__);
1554 $tc = $tw = $uc = $uw = 0;
1555 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1556 {
1557 $tc++;
1558 $tw += $row['wc'];;
1559 if (in_array ($row['chapter_no'], $stock_chapters))
1560 continue;
1561 $uc++;
1562 $uw += $row['wc'];;
1563 }
1564 $result->closeCursor();
1565 unset ($result);
1566 $query = "select count(attr_id) as attrc from RackObject as ro left join " .
1567 "AttributeValue as av on ro.id = av.object_id group by ro.id";
1568 $result = useSelectBlade ($query, __FUNCTION__);
1569 $to = $ta = $so = 0;
1570 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1571 {
1572 $to++;
1573 if ($row['attrc'] != 0)
1574 {
1575 $so++;
1576 $ta += $row['attrc'];
1577 }
1578 }
1579 $result->closeCursor();
1580 $ret = array();
1581 $ret['Total chapters in dictionary'] = $tc;
1582 $ret['Total words in dictionary'] = $tw;
1583 $ret['User chapters'] = $uc;
1584 $ret['Words in user chapters'] = $uw;
1585 $ret['Total objects'] = $to;
1586 $ret['Objects with stickers'] = $so;
1587 $ret['Total stickers attached'] = $ta;
1588 return $ret;
1589 }
1590
1591 function getIPv4Stats ()
1592 {
1593 $ret = array();
1594 $subject = array();
1595 $subject[] = array ('q' => 'select count(id) from IPRanges', 'txt' => 'Networks');
1596 $subject[] = array ('q' => 'select count(ip) from IPAddress', 'txt' => 'Addresses commented/reserved');
1597 $subject[] = array ('q' => 'select count(ip) from IPBonds', 'txt' => 'Addresses allocated');
1598 $subject[] = array ('q' => 'select count(*) from PortForwarding', 'txt' => 'NAT rules');
1599 $subject[] = array ('q' => 'select count(id) from IPVirtualService', 'txt' => 'Virtual services');
1600 $subject[] = array ('q' => 'select count(id) from IPRSPool', 'txt' => 'Real server pools');
1601 $subject[] = array ('q' => 'select count(id) from IPRealServer', 'txt' => 'Real servers');
1602 $subject[] = array ('q' => 'select count(distinct object_id) from IPLoadBalancer', 'txt' => 'Load balancers');
1603
1604 foreach ($subject as $item)
1605 {
1606 $result = useSelectBlade ($item['q'], __FUNCTION__);
1607 $row = $result->fetch (PDO::FETCH_NUM);
1608 $ret[$item['txt']] = $row[0];
1609 $result->closeCursor();
1610 unset ($result);
1611 }
1612 return $ret;
1613 }
1614
1615 function getRackspaceStats ()
1616 {
1617 $ret = array();
1618 $subject = array();
1619 $subject[] = array ('q' => 'select count(*) from Dictionary where chapter_no = 3', 'txt' => 'Rack rows');
1620 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
1621 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
1622 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
1623
1624 foreach ($subject as $item)
1625 {
1626 $result = useSelectBlade ($item['q'], __FUNCTION__);
1627 $row = $result->fetch (PDO::FETCH_NUM);
1628 $ret[$item['txt']] = empty ($row[0]) ? 0 : $row[0];
1629 $result->closeCursor();
1630 unset ($result);
1631 }
1632 return $ret;
1633 }
1634
1635 function renderTagStats ()
1636 {
1637 global $taglist, $root;
1638 $query = "select id, tag, count(tag_id) as refcnt from " .
1639 "TagTree inner join TagStorage on TagTree.id = TagStorage.tag_id " .
1640 "group by tag_id order by refcnt desc limit 50";
1641 // The same data is already present in pre-loaded tag list, but not in
1642 // the form we need. So let's ask the DB server for cooked top list and
1643 // use the cooked tag list to break it down.
1644 $result = useSelectBlade ($query, __FUNCTION__);
1645 $refc = $result->fetchAll (PDO::FETCH_ASSOC);
1646 echo '<table border=1><tr><th>tag</th><th>total</th><th>objects</th><th>IPv4 nets</th><th>racks</th>';
1647 echo '<th>IPv4 VS</th><th>IPv4 RS pools</th><th>users</th></tr>';
1648 $pagebyrealm = array
1649 (
1650 'object' => 'objgroup&group_id=0',
1651 'ipv4net' => 'ipv4space&tab=default',
1652 'rack' => 'rackspace&tab=default',
1653 'ipv4vs' => 'ipv4vslist&tab=default',
1654 'ipv4rspool' => 'ipv4rsplist&tab=default',
1655 'user' => 'userlist&tab=default'
1656 );
1657 foreach ($refc as $ref)
1658 {
1659 echo "<tr><td>${ref['tag']}</td><td>${ref['refcnt']}</td>";
1660 foreach (array ('object', 'ipv4net', 'rack', 'ipv4vs', 'ipv4rspool', 'user') as $realm)
1661 {
1662 echo '<td>';
1663 if (!isset ($taglist[$ref['id']]['refcnt'][$realm]))
1664 echo '&nbsp;';
1665 else
1666 {
1667 echo "<a href='${root}?page=" . $pagebyrealm[$realm] . "&tagfilter[]=${ref['id']}'>";
1668 echo $taglist[$ref['id']]['refcnt'][$realm] . '</a>';
1669 }
1670 echo '</td>';
1671 }
1672 echo '</tr>';
1673 }
1674 echo '</table>';
1675 }
1676
1677 /*
1678
1679 The following allows figuring out records in TagStorage, which refer to non-existing entities:
1680
1681 mysql> select target_id from TagStorage left join IPRanges on target_id = id where target_realm = 'ipv4net' and id is null;
1682 mysql> select target_id from TagStorage left join RackObject on target_id = id where target_realm = 'object' and id is null;
1683 mysql> select target_id from TagStorage left join Rack on target_id = id where target_realm = 'rack' and id is null;
1684 mysql> select target_id from TagStorage left join IPVirtualService on target_id = id where target_realm = 'ipv4vs' and id is null;
1685 mysql> select target_id from TagStorage left join IPRSPool on target_id = id where target_realm = 'ipv4rspool' and id is null;
1686 mysql> select target_id from TagStorage left join UserAccount on target_id = user_id where target_realm = 'user' and user_id is null;
1687
1688 Accordingly, these are the records, which refer to non-existent tags:
1689
1690 mysql> select tag_id from TagStorage left join TagTree on tag_id = id where id is null;
1691
1692 */
1693
1694 function commitUpdateDictionary ($chapter_no = 0, $dict_key = 0, $dict_value = '')
1695 {
1696 if ($chapter_no <= 0 or $dict_key <= 0 or empty ($dict_value))
1697 {
1698 showError ('Invalid args', __FUNCTION__);
1699 die;
1700 }
1701 global $dbxlink;
1702 $query =
1703 "update Dictionary set dict_value = '${dict_value}' where chapter_no=${chapter_no} " .
1704 "and dict_key=${dict_key} limit 1";
1705 $result = $dbxlink->query ($query);
1706 if ($result == NULL)
1707 {
1708 showError ('SQL query failed', __FUNCTION__);
1709 die;
1710 }
1711 return TRUE;
1712 }
1713
1714 function commitSupplementDictionary ($chapter_no = 0, $dict_value = '')
1715 {
1716 if ($chapter_no <= 0 or empty ($dict_value))
1717 {
1718 showError ('Invalid args', __FUNCTION__);
1719 die;
1720 }
1721 return useInsertBlade
1722 (
1723 'Dictionary',
1724 array ('chapter_no' => $chapter_no, 'dict_value' => "'${dict_value}'")
1725 );
1726 }
1727
1728 function commitReduceDictionary ($chapter_no = 0, $dict_key = 0)
1729 {
1730 if ($chapter_no <= 0 or $dict_key <= 0)
1731 {
1732 showError ('Invalid args', __FUNCTION__);
1733 die;
1734 }
1735 global $dbxlink;
1736 $query =
1737 "delete from Dictionary where chapter_no=${chapter_no} " .
1738 "and dict_key=${dict_key} limit 1";
1739 $result = $dbxlink->query ($query);
1740 if ($result == NULL)
1741 {
1742 showError ('SQL query failed', __FUNCTION__);
1743 die;
1744 }
1745 return TRUE;
1746 }
1747
1748 function commitAddChapter ($chapter_name = '')
1749 {
1750 if (empty ($chapter_name))
1751 {
1752 showError ('Invalid args', __FUNCTION__);
1753 die;
1754 }
1755 return useInsertBlade
1756 (
1757 'Chapter',
1758 array ('chapter_name' => "'${chapter_name}'")
1759 );
1760 }
1761
1762 function commitUpdateChapter ($chapter_no = 0, $chapter_name = '')
1763 {
1764 if ($chapter_no <= 0 or empty ($chapter_name))
1765 {
1766 showError ('Invalid args', __FUNCTION__);
1767 die;
1768 }
1769 global $dbxlink;
1770 $query =
1771 "update Chapter set chapter_name = '${chapter_name}' where chapter_no = ${chapter_no} " .
1772 "and sticky = 'no' limit 1";
1773 $result = $dbxlink->query ($query);
1774 if ($result == NULL)
1775 {
1776 showError ('SQL query failed', __FUNCTION__);
1777 die;
1778 }
1779 return TRUE;
1780 }
1781
1782 function commitDeleteChapter ($chapter_no = 0)
1783 {
1784 if ($chapter_no <= 0)
1785 {
1786 showError ('Invalid args', __FUNCTION__);
1787 die;
1788 }
1789 global $dbxlink;
1790 $query =
1791 "delete from Chapter where chapter_no = ${chapter_no} and sticky = 'no' limit 1";
1792 $result = $dbxlink->query ($query);
1793 if ($result == NULL)
1794 {
1795 showError ('SQL query failed', __FUNCTION__);
1796 die;
1797 }
1798 return TRUE;
1799 }
1800
1801 // This is a dictionary accessor. We perform link rendering, so the user sees
1802 // nice <select> drop-downs.
1803 function readChapter ($chapter_name = '')
1804 {
1805 if (empty ($chapter_name))
1806 {
1807 showError ('invalid argument', __FUNCTION__);
1808 return NULL;
1809 }
1810 $query =
1811 "select dict_key, dict_value from Dictionary natural join Chapter " .
1812 "where chapter_name = '${chapter_name}'";
1813 $result = useSelectBlade ($query, __FUNCTION__);
1814 $chapter = array();
1815 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1816 $chapter[$row['dict_key']] = parseWikiLink ($row['dict_value'], 'o');
1817 $result->closeCursor();
1818 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
1819 asort ($chapter);
1820 return $chapter;
1821 }
1822
1823 function getAttrMap ()
1824 {
1825 $query =
1826 "select a.attr_id, a.attr_type, a.attr_name, am.objtype_id, " .
1827 "d.dict_value as objtype_name, am.chapter_no, c2.chapter_name from " .
1828 "Attribute as a natural left join AttributeMap as am " .
1829 "left join Dictionary as d on am.objtype_id = d.dict_key " .
1830 "left join Chapter as c1 on d.chapter_no = c1.chapter_no " .
1831 "left join Chapter as c2 on am.chapter_no = c2.chapter_no " .
1832 "where c1.chapter_name = 'RackObjectType' or c1.chapter_name is null " .
1833 "order by attr_name";
1834 $result = useSelectBlade ($query, __FUNCTION__);
1835 $ret = array();
1836 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1837 {
1838 $attr_id = $row['attr_id'];
1839 if (!isset ($ret[$attr_id]))
1840 {
1841 $ret[$attr_id]['id'] = $attr_id;
1842 $ret[$attr_id]['type'] = $row['attr_type'];
1843 $ret[$attr_id]['name'] = $row['attr_name'];
1844 $ret[$attr_id]['application'] = array();
1845 }
1846 if ($row['objtype_id'] == '')
1847 continue;
1848 $application['objtype_id'] = $row['objtype_id'];
1849 $application['objtype_name'] = $row['objtype_name'];
1850 if ($row['attr_type'] == 'dict')
1851 {
1852 $application['chapter_no'] = $row['chapter_no'];
1853 $application['chapter_name'] = $row['chapter_name'];
1854 }
1855 $ret[$attr_id]['application'][] = $application;
1856 }
1857 $result->closeCursor();
1858 return $ret;
1859 }
1860
1861 function commitUpdateAttribute ($attr_id = 0, $attr_name = '')
1862 {
1863 if ($attr_id <= 0 or empty ($attr_name))
1864 {
1865 showError ('Invalid args', __FUNCTION__);
1866 die;
1867 }
1868 global $dbxlink;
1869 $query =
1870 "update Attribute set attr_name = '${attr_name}' " .
1871 "where attr_id = ${attr_id} limit 1";
1872 $result = $dbxlink->query ($query);
1873 if ($result == NULL)
1874 {
1875 showError ("SQL query '${query}' failed", __FUNCTION__);
1876 die;
1877 }
1878 return TRUE;
1879 }
1880
1881 function commitAddAttribute ($attr_name = '', $attr_type = '')
1882 {
1883 if (empty ($attr_name))
1884 {
1885 showError ('Invalid args', __FUNCTION__);
1886 die;
1887 }
1888 switch ($attr_type)
1889 {
1890 case 'uint':
1891 case 'float':
1892 case 'string':
1893 case 'dict':
1894 break;
1895 default:
1896 showError ('Invalid args', __FUNCTION__);
1897 die;
1898 }
1899 return useInsertBlade
1900 (
1901 'Attribute',
1902 array ('attr_name' => "'${attr_name}'", 'attr_type' => "'${attr_type}'")
1903 );
1904 }
1905
1906 function commitDeleteAttribute ($attr_id = 0)
1907 {
1908 if ($attr_id <= 0)
1909 {
1910 showError ('Invalid args', __FUNCTION__);
1911 die;
1912 }
1913 return useDeleteBlade ('Attribute', 'attr_id', $attr_id);
1914 }
1915
1916 // FIXME: don't store garbage in chapter_no for non-dictionary types.
1917 function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
1918 {
1919 if ($attr_id <= 0 or $objtype_id <= 0 or $chapter_no <= 0)
1920 {
1921 showError ('Invalid args', __FUNCTION__);
1922 die;
1923 }
1924 return useInsertBlade
1925 (
1926 'AttributeMap',
1927 array
1928 (
1929 'attr_id' => $attr_id,
1930 'objtype_id' => $objtype_id,
1931 'chapter_no' => $chapter_no
1932 )
1933 );
1934 }
1935
1936 function commitReduceAttrMap ($attr_id = 0, $objtype_id)
1937 {
1938 if ($attr_id <= 0 or $objtype_id <= 0)
1939 {
1940 showError ('Invalid args', __FUNCTION__);
1941 die;
1942 }
1943 global $dbxlink;
1944 $query =
1945 "delete from AttributeMap where attr_id=${attr_id} " .
1946 "and objtype_id=${objtype_id} limit 1";
1947 $result = $dbxlink->query ($query);
1948 if ($result == NULL)
1949 {
1950 showError ('SQL query failed', __FUNCTION__);
1951 die;
1952 }
1953 return TRUE;
1954 }
1955
1956 // This function returns all optional attributes for requested object
1957 // as an array of records. NULL is returned on error and empty array
1958 // is returned, if there are no attributes found.
1959 function getAttrValues ($object_id, $strip_optgroup = FALSE)
1960 {
1961 if ($object_id <= 0)
1962 {
1963 showError ('Invalid argument', __FUNCTION__);
1964 return NULL;
1965 }
1966 $ret = array();
1967 $query =
1968 "select A.attr_id, A.attr_name, A.attr_type, C.chapter_name, " .
1969 "AV.uint_value, AV.float_value, AV.string_value, D.dict_value from " .
1970 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
1971 "inner join Attribute as A using (attr_id) " .
1972 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
1973 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_no = D.chapter_no " .
1974 "left join Chapter as C on AM.chapter_no = C.chapter_no " .
1975 "where RO.id = ${object_id} order by A.attr_type, A.attr_name";
1976 $result = useSelectBlade ($query, __FUNCTION__);
1977 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1978 {
1979 $record = array();
1980 $record['id'] = $row['attr_id'];
1981 $record['name'] = $row['attr_name'];
1982 $record['type'] = $row['attr_type'];
1983 switch ($row['attr_type'])
1984 {
1985 case 'uint':
1986 case 'float':
1987 case 'string':
1988 $record['value'] = $row[$row['attr_type'] . '_value'];
1989 $record['a_value'] = parseWikiLink ($record['value'], 'a');
1990 break;
1991 case 'dict':
1992 $record['value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'o', $strip_optgroup);
1993 $record['a_value'] = parseWikiLink ($row[$row['attr_type'] . '_value'], 'a', $strip_optgroup);
1994 $record['chapter_name'] = $row['chapter_name'];
1995 $record['key'] = $row['uint_value'];
1996 break;
1997 default:
1998 $record['value'] = NULL;
1999 break;
2000 }
2001 $ret[$row['attr_id']] = $record;
2002 }
2003 $result->closeCursor();
2004 return $ret;
2005 }
2006
2007 function commitResetAttrValue ($object_id = 0, $attr_id = 0)
2008 {
2009 if ($object_id <= 0 or $attr_id <= 0)
2010 {
2011 showError ('Invalid arguments', __FUNCTION__);
2012 die;
2013 }
2014 global $dbxlink;
2015 $query = "delete from AttributeValue where object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2016 $result = $dbxlink->query ($query);
2017 if ($result == NULL)
2018 {
2019 showError ('SQL query failed', __FUNCTION__);
2020 die;
2021 }
2022 return TRUE;
2023 }
2024
2025 // FIXME: don't share common code with use commitResetAttrValue()
2026 function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
2027 {
2028 if ($object_id <= 0 or $attr_id <= 0)
2029 {
2030 showError ('Invalid arguments', __FUNCTION__);
2031 die;
2032 }
2033 if (empty ($value))
2034 return commitResetAttrValue ($object_id, $attr_id);
2035 global $dbxlink;
2036 $query1 = "select attr_type from Attribute where attr_id = ${attr_id}";
2037 $result = $dbxlink->query ($query1);
2038 if ($result == NULL)
2039 {
2040 showError ('SQL query #1 failed', __FUNCTION__);
2041 die;
2042 }
2043 $row = $result->fetch (PDO::FETCH_NUM);
2044 if ($row == NULL)
2045 {
2046 showError ('SQL query #1 returned no results', __FUNCTION__);
2047 die;
2048 }
2049 $attr_type = $row[0];
2050 $result->closeCursor();
2051 switch ($attr_type)
2052 {
2053 case 'uint':
2054 case 'float':
2055 case 'string':
2056 $column = $attr_type . '_value';
2057 break;
2058 case 'dict':
2059 $column = 'uint_value';
2060 break;
2061 default:
2062 showError ("Unknown attribute type '${attr_type}' met", __FUNCTION__);
2063 die;
2064 }
2065 $query2 =
2066 "delete from AttributeValue where " .
2067 "object_id = ${object_id} and attr_id = ${attr_id} limit 1";
2068 $result = $dbxlink->query ($query2);
2069 if ($result == NULL)
2070 {
2071 showError ('SQL query #2 failed', __FUNCTION__);
2072 die;
2073 }
2074 // We know $value isn't empty here.
2075 $query3 =
2076 "insert into AttributeValue set ${column} = '${value}', " .
2077 "object_id = ${object_id}, attr_id = ${attr_id} ";
2078 $result = $dbxlink->query ($query3);
2079 if ($result == NULL)
2080 {
2081 showError ('SQL query #3 failed', __FUNCTION__);
2082 die;
2083 }
2084 return TRUE;
2085 }
2086
2087 function commitUseupPort ($port_id = 0)
2088 {
2089 if ($port_id <= 0)
2090 {
2091 showError ("Invalid argument", __FUNCTION__);
2092 die;
2093 }
2094 global $dbxlink;
2095 $query = "update Port set reservation_comment = NULL where id = ${port_id} limit 1";
2096 $result = $dbxlink->exec ($query);
2097 if ($result == NULL)
2098 {
2099 showError ("SQL query failed", __FUNCTION__);
2100 die;
2101 }
2102 return TRUE;
2103
2104 }
2105
2106 // This is a swiss-knife blade to insert a record into a table.
2107 // The first argument is table name.
2108 // The second argument is an array of "name" => "value" pairs.
2109 // The function returns either TRUE or FALSE (we expect one row
2110 // to be inserted).
2111 function useInsertBlade ($tablename, $values)
2112 {
2113 global $dbxlink;
2114 $namelist = $valuelist = '';
2115 foreach ($values as $name => $value)
2116 {
2117 $namelist = $namelist . ($namelist == '' ? "(${name}" : ", ${name}");
2118 $valuelist = $valuelist . ($valuelist == '' ? "(${value}" : ", ${value}");
2119 }
2120 $query = "insert into ${tablename} ${namelist}) values ${valuelist})";
2121 $result = $dbxlink->exec ($query);
2122 if ($result != 1)
2123 return FALSE;
2124 return TRUE;
2125 }
2126
2127 // This swiss-knife blade deletes one record from the specified table
2128 // using the specified key name and value.
2129 function useDeleteBlade ($tablename, $keyname, $keyvalue)
2130 {
2131 global $dbxlink;
2132 return 1 === $dbxlink->exec ("delete from ${tablename} where ${keyname}=${keyvalue} limit 1");
2133 }
2134
2135 function useSelectBlade ($query, $caller = 'N/A')
2136 {
2137 global $dbxlink;
2138 $result = $dbxlink->query ($query);
2139 if ($result == NULL)
2140 {
2141 $ei = $dbxlink->errorInfo();
2142 showError ("SQL query '${query}'\n failed in useSelectBlade with error ${ei[1]} (${ei[2]})", $caller);
2143 return NULL;
2144 }
2145 return $result;
2146 }
2147
2148 function loadConfigCache ()
2149 {
2150 $query = 'SELECT varname, varvalue, vartype, is_hidden, emptyok, description FROM Config ORDER BY varname';
2151 $result = useSelectBlade ($query, __FUNCTION__);
2152 $cache = array();
2153 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2154 $cache[$row['varname']] = $row;
2155 $result->closeCursor();
2156 return $cache;
2157 }
2158
2159 // setConfigVar() is expected to perform all necessary filtering
2160 function storeConfigVar ($varname = NULL, $varvalue = NULL)
2161 {
2162 global $dbxlink;
2163 if (empty ($varname) || $varvalue === NULL)
2164 {
2165 showError ('Invalid arguments', __FUNCTION__);
2166 return FALSE;
2167 }
2168 $query = "update Config set varvalue='${varvalue}' where varname='${varname}' limit 1";
2169 $result = $dbxlink->query ($query);
2170 if ($result == NULL)
2171 {
2172 showError ("SQL query '${query}' failed", __FUNCTION__);
2173 return FALSE;
2174 }
2175 $rc = $result->rowCount();
2176 $result->closeCursor();
2177 if ($rc == 0 or $rc == 1)
2178 return TRUE;
2179 showError ("Something went wrong for args '${varname}', '${varvalue}'", __FUNCTION__);
2180 return FALSE;
2181 }
2182
2183 // Database version detector. Should behave corretly on any
2184 // working dataset a user might have.
2185 function getDatabaseVersion ()
2186 {
2187 global $dbxlink;
2188 $query = "select varvalue from Config where varname = 'DB_VERSION' and vartype = 'string'";
2189 $result = $dbxlink->query ($query);
2190 if ($result == NULL)
2191 {
2192 $errorInfo = $dbxlink->errorInfo();
2193 if ($errorInfo[0] == '42S02') // ER_NO_SUCH_TABLE
2194 return '0.14.4';
2195 die (__FUNCTION__ . ': SQL query #1 failed with error ' . $errorInfo[2]);
2196 }
2197 $rows = $result->fetchAll (PDO::FETCH_NUM);
2198 if (count ($rows) != 1 || empty ($rows[0][0]))
2199 {
2200 $result->closeCursor();
2201 die (__FUNCTION__ . ': Cannot guess database version. Config table is present, but DB_VERSION is missing or invalid. Giving up.');
2202 }
2203 $ret = $rows[0][0];
2204 $result->closeCursor();
2205 return $ret;
2206 }
2207
2208 // Return an array of virtual services. For each of them list real server pools
2209 // with their load balancers and other stats.
2210 function getSLBSummary ()
2211 {
2212 $query = 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
2213 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
2214 'from IPVirtualService as vs inner join IPLoadBalancer as lb on vs.id = lb.vs_id ' .
2215 'inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2216 'left join IPRealServer as rs on rs.rspool_id = lb.rspool_id ' .
2217 'group by vs.id, object_id order by vs.vip, object_id';
2218 $result = useSelectBlade ($query, __FUNCTION__);
2219 $ret = array();
2220 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2221 {
2222 $vsid = $row['vsid'];
2223 $object_id = $row['object_id'];
2224 if (!isset ($ret[$vsid]))
2225 {
2226 $ret[$vsid] = array();
2227 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
2228 $ret[$vsid][$cname] = $row[$cname];
2229 $ret[$vsid]['lblist'] = array();
2230 }
2231 // There's only one assigned RS pool possible for each LB-VS combination.
2232 $ret[$vsid]['lblist'][$row['object_id']] = array
2233 (
2234 'id' => $row['rspool_id'],
2235 'size' => $row['rscount'],
2236 'name' => $row['pool_name']
2237 );
2238 }
2239 $result->closeCursor();
2240 return $ret;
2241 }
2242
2243 // Get the detailed composition of a particular virtual service, namely the list
2244 // of all pools, each shown with the list of objects servicing it. VS/RS configs
2245 // will be returned as well.
2246 function getVServiceInfo ($vsid = 0)
2247 {
2248 $query1 = "select inet_ntoa(vip) as vip, vport, proto, name, vsconfig, rsconfig " .
2249 "from IPVirtualService where id = ${vsid}";
2250 $result = useSelectBlade ($query1, __FUNCTION__);
2251 $vsinfo = array ();
2252 $row = $result->fetch (PDO::FETCH_ASSOC);
2253 if (!$row)
2254 return NULL;
2255 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig') as $cname)
2256 $vsinfo[$cname] = $row[$cname];
2257 $vsinfo['rspool'] = array();
2258 $result->closeCursor();
2259 unset ($result);
2260 $query2 = "select pool.id, name, pool.vsconfig, pool.rsconfig, object_id, " .
2261 "lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig from " .
2262 "IPRSPool as pool left join IPLoadBalancer as lb on pool.id = lb.rspool_id " .
2263 "where vs_id = ${vsid} order by pool.name, object_id";
2264 $result = useSelectBlade ($query2, __FUNCTION__);
2265 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2266 {
2267 if (!isset ($vsinfo['rspool'][$row['id']]))
2268 {
2269 $vsinfo['rspool'][$row['id']]['name'] = $row['name'];
2270 $vsinfo['rspool'][$row['id']]['vsconfig'] = $row['vsconfig'];
2271 $vsinfo['rspool'][$row['id']]['rsconfig'] = $row['rsconfig'];
2272 $vsinfo['rspool'][$row['id']]['lblist'] = array();
2273 }
2274 if ($row['object_id'] == NULL)
2275 continue;
2276 $vsinfo['rspool'][$row['id']]['lblist'][$row['object_id']] = array
2277 (
2278 'vsconfig' => $row['lb_vsconfig'],
2279 'rsconfig' => $row['lb_rsconfig']
2280 );
2281 }
2282 $result->closeCursor();
2283 return $vsinfo;
2284 }
2285
2286 // Collect and return the following info about the given real server pool:
2287 // basic information
2288 // parent virtual service information
2289 // load balancers list (each with a list of VSes)
2290 // real servers list
2291
2292 function getRSPoolInfo ($id = 0)
2293 {
2294 $query1 = "select id, name, vsconfig, rsconfig from " .
2295 "IPRSPool where id = ${id}";
2296 $result = useSelectBlade ($query1, __FUNCTION__);
2297 $ret = array();
2298 $row = $result->fetch (PDO::FETCH_ASSOC);
2299 if (!$row)
2300 return NULL;
2301 foreach (array ('id', 'name', 'vsconfig', 'rsconfig') as $c)
2302 $ret[$c] = $row[$c];
2303 $result->closeCursor();
2304 unset ($result);
2305 $ret['lblist'] = array();
2306 $ret['rslist'] = array();
2307 $query2 = "select object_id, vs_id, vsconfig, rsconfig from IPLoadBalancer " .
2308 "where rspool_id = ${id} order by object_id, vs_id";
2309 $result = useSelectBlade ($query2, __FUNCTION__);
2310 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2311 foreach (array ('vsconfig', 'rsconfig') as $c)
2312 $ret['lblist'][$row['object_id']][$row['vs_id']][$c] = $row[$c];
2313 $result->closeCursor();
2314 unset ($result);
2315 $query3 = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rsconfig from " .
2316 "IPRealServer where rspool_id = ${id} order by IPRealServer.rsip, rsport";
2317 $result = useSelectBlade ($query3, __FUNCTION__);
2318 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2319 foreach (array ('inservice', 'rsip', 'rsport', 'rsconfig') as $c)
2320 $ret['rslist'][$row['id']][$c] = $row[$c];
2321 $result->closeCursor();
2322 return $ret;
2323 }
2324
2325 function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
2326 {
2327 if ($pool_id <= 0)
2328 {
2329 showError ('Invalid arguments', __FUNCTION__);
2330 die;
2331 }
2332 if (empty ($rsport) or $rsport == 0)
2333 $rsport = 'NULL';
2334 return useInsertBlade
2335 (
2336 'IPRealServer',
2337 array
2338 (
2339 'rsip' => "inet_aton('${rsip}')",
2340 'rsport' => $rsport,
2341 'rspool_id' => $pool_id,
2342 'inservice' => ($inservice == 'yes' ? "'yes'" : "'no'"),
2343 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2344 )
2345 );
2346 }
2347
2348 function commitCreateVS ($vip = '', $vport = 0, $proto = '', $name = '', $vsconfig, $rsconfig, $taglist = array())
2349 {
2350 if (empty ($vip) or $vport <= 0 or empty ($proto))
2351 return __FUNCTION__ . ': invalid arguments';
2352 if (!useInsertBlade
2353 (
2354 'IPVirtualService',
2355 array
2356 (
2357 'vip' => "inet_aton('${vip}')",
2358 'vport' => $vport,
2359 'proto' => "'${proto}'",
2360 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2361 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2362 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2363 )
2364 ))
2365 return __FUNCTION__ . ': SQL insertion failed';
2366 return produceTagsForLastRecord ('ipv4vs', $taglist);
2367 }
2368
2369 function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
2370 {
2371 if ($pool_id <= 0 or $object_id <= 0 or $vs_id <= 0)
2372 {
2373 showError ('Invalid arguments', __FUNCTION__);
2374 die;
2375 }
2376 return useInsertBlade
2377 (
2378 'IPLoadBalancer',
2379 array
2380 (
2381 'object_id' => $object_id,
2382 'rspool_id' => $pool_id,
2383 'vs_id' => $vs_id,
2384 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2385 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2386 )
2387 );
2388 }
2389
2390 function commitDeleteRS ($id = 0)
2391 {
2392 if ($id <= 0)
2393 return FALSE;
2394 return useDeleteBlade ('IPRealServer', 'id', $id);
2395 }
2396
2397 function commitDeleteVS ($id = 0)
2398 {
2399 if ($id <= 0)
2400 return FALSE;
2401 return useDeleteBlade ('IPVirtualService', 'id', $id) && destroyTagsForEntity ('ipv4vs', $id);
2402 }
2403
2404 function commitDeleteLB ($object_id = 0, $pool_id = 0, $vs_id = 0)
2405 {
2406 global $dbxlink;
2407 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
2408 return FALSE;
2409 $query = "delete from IPLoadBalancer where object_id = ${object_id} and " .
2410 "rspool_id = ${pool_id} and vs_id = ${vs_id} limit 1";
2411 $result = $dbxlink->exec ($query);
2412 if ($result === NULL)
2413 return FALSE;
2414 elseif ($result != 1)
2415 return FALSE;
2416 else
2417 return TRUE;
2418 }
2419
2420 function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2421 {
2422 if ($rsid <= 0)
2423 {
2424 showError ('Invalid args', __FUNCTION__);
2425 die;
2426 }
2427 if (long2ip (ip2long ($rsip)) !== $rsip)
2428 {
2429 showError ("Invalid IP address '${rsip}'", __FUNCTION__);
2430 die;
2431 }
2432 if (empty ($rsport) or $rsport == 0)
2433 $rsport = 'NULL';
2434 global $dbxlink;
2435 $query =
2436 "update IPRealServer set rsip = inet_aton('${rsip}'), rsport = ${rsport}, rsconfig = " .
2437 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2438 " where id = ${rsid} limit 1";
2439 $result = $dbxlink->query ($query);
2440 if ($result == NULL)
2441 {
2442 showError ("SQL query '${query}' failed", __FUNCTION__);
2443 die;
2444 }
2445 return TRUE;
2446 }
2447
2448 function commitUpdateLB ($object_id = 0, $pool_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '')
2449 {
2450 if ($object_id <= 0 or $pool_id <= 0 or $vs_id <= 0)
2451 {
2452 showError ('Invalid args', __FUNCTION__);
2453 die;
2454 }
2455 global $dbxlink;
2456 $query =
2457 "update IPLoadBalancer set vsconfig = " .
2458 (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'") .
2459 ', rsconfig = ' .
2460 (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2461 " where object_id = ${object_id} and rspool_id = ${pool_id} " .
2462 "and vs_id = ${vs_id} limit 1";
2463 $result = $dbxlink->exec ($query);
2464 if ($result === NULL)
2465 return FALSE;
2466 else
2467 return TRUE;
2468 }
2469
2470 function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2471 {
2472 if ($vsid <= 0 or empty ($vip) or $vport <= 0 or empty ($proto))
2473 {
2474 showError ('Invalid args', __FUNCTION__);
2475 die;
2476 }
2477 global $dbxlink;
2478 $query = "update IPVirtualService set " .
2479 "vip = inet_aton('${vip}'), " .
2480 "vport = ${vport}, " .
2481 "proto = '${proto}', " .
2482 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2483 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2484 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2485 " where id = ${vsid} limit 1";
2486 $result = $dbxlink->exec ($query);
2487 if ($result === NULL)
2488 return FALSE;
2489 else
2490 return TRUE;
2491 }
2492
2493 // Return the list of virtual services, indexed by vs_id.
2494 // Each record will be shown with its basic info plus RS pools counter.
2495 function getVSList ($tagfilter = array(), $tfmode = 'any')
2496 {
2497 $whereclause = getWhereClause ($tagfilter);
2498 $query = "select vs.id, inet_ntoa(vip) as vip, vport, proto, vs.name, vs.vsconfig, vs.rsconfig, count(rspool_id) as poolcount " .
2499 "from IPVirtualService as vs left join IPLoadBalancer as lb on vs.id = lb.vs_id " .
2500 "left join TagStorage on vs.id = TagStorage.target_id and target_realm = 'ipv4vs' " .
2501 "where true ${whereclause} group by vs.id order by vs.vip, proto, vport";
2502 $result = useSelectBlade ($query, __FUNCTION__);
2503 $ret = array ();
2504 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2505 foreach (array ('vip', 'vport', 'proto', 'name', 'vsconfig', 'rsconfig', 'poolcount') as $cname)
2506 $ret[$row['id']][$cname] = $row[$cname];
2507 $result->closeCursor();
2508 return $ret;
2509 }
2510
2511 // Return the list of RS pool, indexed by pool id.
2512 function getRSPoolList ($tagfilter = array(), $tfmode = 'any')
2513 {
2514 $whereclause = getWhereClause ($tagfilter);
2515 $query = "select pool.id, pool.name, count(rspool_id) as refcnt, pool.vsconfig, pool.rsconfig " .
2516 "from IPRSPool as pool left join IPLoadBalancer as lb on pool.id = lb.rspool_id " .
2517 "left join TagStorage on pool.id = TagStorage.target_id and target_realm = 'ipv4rspool' " .
2518 "where true ${whereclause} group by pool.id order by pool.name, pool.id";
2519 $result = useSelectBlade ($query, __FUNCTION__);
2520 $ret = array ();
2521 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2522 foreach (array ('name', 'refcnt', 'vsconfig', 'rsconfig') as $cname)
2523 $ret[$row['id']][$cname] = $row[$cname];
2524 $result->closeCursor();
2525 return $ret;
2526 }
2527
2528 function loadThumbCache ($rack_id = 0)
2529 {
2530 $ret = NULL;
2531 $query = "select thumb_data from Rack where id = ${rack_id} and thumb_data is not null limit 1";
2532 $result = useSelectBlade ($query, __FUNCTION__);
2533 $row = $result->fetch (PDO::FETCH_ASSOC);
2534 if ($row)
2535 $ret = base64_decode ($row['thumb_data']);
2536 $result->closeCursor();
2537 return $ret;
2538 }
2539
2540 function saveThumbCache ($rack_id = 0, $cache = NULL)
2541 {
2542 global $dbxlink;
2543 if ($rack_id == 0 or $cache == NULL)
2544 {
2545 showError ('Invalid arguments', __FUNCTION__);
2546 return;
2547 }
2548 $data = base64_encode ($cache);
2549 $query = "update Rack set thumb_data = '${data}' where id = ${rack_id} limit 1";
2550 $result = $dbxlink->exec ($query);
2551 }
2552
2553 function resetThumbCache ($rack_id = 0)
2554 {
2555 global $dbxlink;
2556 if ($rack_id == 0)
2557 {
2558 showError ('Invalid argument', __FUNCTION__);
2559 return;
2560 }
2561 $query = "update Rack set thumb_data = NULL where id = ${rack_id} limit 1";
2562 $result = $dbxlink->exec ($query);
2563 }
2564
2565 // Return the list of attached RS pools for the given object. As long as we have
2566 // the LB-VS UNIQUE in IPLoadBalancer table, it is Ok to key returned records
2567 // by vs_id, because there will be only one RS pool listed for each VS of the
2568 // current object.
2569 function getRSPoolsForObject ($object_id = 0)
2570 {
2571 if ($object_id <= 0)
2572 {
2573 showError ('Invalid object_id', __FUNCTION__);
2574 return NULL;
2575 }
2576 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
2577 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig from ' .
2578 'IPLoadBalancer as lb inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2579 'inner join IPVirtualService as vs on lb.vs_id = vs.id ' .
2580 'left join IPRealServer as rs on lb.rspool_id = rs.rspool_id ' .
2581 "where lb.object_id = ${object_id} " .
2582 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name';
2583 $result = useSelectBlade ($query, __FUNCTION__);
2584 $ret = array ();
2585 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2586 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig') as $cname)
2587 $ret[$row['vs_id']][$cname] = $row[$cname];
2588 $result->closeCursor();
2589 return $ret;
2590 }
2591
2592 function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
2593 {
2594 if (empty ($name))
2595 return __FUNCTION__ . ': invalid arguments';
2596 if (!useInsertBlade
2597 (
2598 'IPRSPool',
2599 array
2600 (
2601 'name' => (empty ($name) ? 'NULL' : "'${name}'"),
2602 'vsconfig' => (empty ($vsconfig) ? 'NULL' : "'${vsconfig}'"),
2603 'rsconfig' => (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'")
2604 )
2605 ))
2606 return __FUNCTION__ . ': SQL insertion failed';
2607 return produceTagsForLastRecord ('ipv4rspool', $taglist);
2608 }
2609
2610 function commitDeleteRSPool ($pool_id = 0)
2611 {
2612 global $dbxlink;
2613 if ($pool_id <= 0)
2614 return FALSE;
2615 return useDeleteBlade ('IPRSPool', 'id', $pool_id) && destroyTagsForEntity ('ipv4rspool', $pool_id);
2616 }
2617
2618 function commitUpdateRSPool ($pool_id = 0, $name = '', $vsconfig = '', $rsconfig = '')
2619 {
2620 if ($pool_id <= 0)
2621 {
2622 showError ('Invalid arg', __FUNCTION__);
2623 die;
2624 }
2625 global $dbxlink;
2626 $query = "update IPRSPool set " .
2627 'name = ' . (empty ($name) ? 'NULL,' : "'${name}', ") .
2628 'vsconfig = ' . (empty ($vsconfig) ? 'NULL,' : "'${vsconfig}', ") .
2629 'rsconfig = ' . (empty ($rsconfig) ? 'NULL' : "'${rsconfig}'") .
2630 " where id = ${pool_id} limit 1";
2631 $result = $dbxlink->exec ($query);
2632 if ($result === NULL)
2633 return FALSE;
2634 elseif ($result != 1)
2635 return FALSE;
2636 else
2637 return TRUE;
2638 }
2639
2640 function getRSList ()
2641 {
2642 $query = "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
2643 "from IPRealServer order by rspool_id, IPRealServer.rsip, rsport";
2644 $result = useSelectBlade ($query, __FUNCTION__);
2645 $ret = array ();
2646 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2647 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
2648 $ret[$row['id']][$cname] = $row[$cname];
2649 $result->closeCursor();
2650 return $ret;
2651 }
2652
2653 // Return the list of all currently configured load balancers with their pool count.
2654 function getLBList ()
2655 {
2656 $query = "select object_id, count(rspool_id) as poolcount " .
2657 "from IPLoadBalancer group by object_id order by object_id";
2658 $result = useSelectBlade ($query, __FUNCTION__);
2659 $ret = array ();
2660 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2661 $ret[$row['object_id']] = $row['poolcount'];
2662 $result->closeCursor();
2663 return $ret;
2664 }
2665
2666 // For the given object return: it vsconfig/rsconfig; the list of RS pools
2667 // attached (each with vsconfig/rsconfig in turn), each with the list of
2668 // virtual services terminating the pool. Each pool also lists all real
2669 // servers with rsconfig.
2670 function getSLBConfig ($object_id)
2671 {
2672 if ($object_id <= 0)
2673 {
2674 showError ('Invalid arg', __FUNCTION__);
2675 return NULL;
2676 }
2677 $ret = array();
2678 $query = 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2679 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2680 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, pool.id as pool_id, pool.name as pool_name, ' .
2681 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
2682 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
2683 'IPLoadBalancer as lb inner join IPRSPool as pool on lb.rspool_id = pool.id ' .
2684 'inner join IPVirtualService as vs on lb.vs_id = vs.id ' .
2685 'inner join IPRealServer as rs on lb.rspool_id = rs.rspool_id ' .
2686 "where lb.object_id = ${object_id} and rs.inservice = 'yes' " .
2687 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport";
2688 $result = useSelectBlade ($query, __FUNCTION__);
2689 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2690 {
2691 $vs_id = $row['vs_id'];
2692 if (!isset ($ret[$vs_id]))
2693 {
2694 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)
2695 $ret[$vs_id][$c] = $row[$c];
2696 $ret[$vs_id]['rslist'] = array();
2697 }
2698 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2699 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
2700 }
2701 $result->closeCursor();
2702 return $ret;
2703 }
2704
2705 function commitSetInService ($rs_id = 0, $inservice = '')
2706 {
2707 if ($rs_id <= 0 or empty ($inservice))
2708 {
2709 showError ('Invalid args', __FUNCTION__);
2710 return NULL;
2711 }
2712 global $dbxlink;
2713 $query = "update IPRealServer set inservice = '${inservice}' where id = ${rs_id} limit 1";
2714 $result = $dbxlink->exec ($query);
2715 if ($result === NULL)
2716 return FALSE;
2717 elseif ($result != 1)
2718 return FALSE;
2719 else
2720 return TRUE;
2721 }
2722
2723 function executeAutoPorts ($object_id = 0, $type_id = 0)
2724 {
2725 if ($object_id == 0 or $type_id == 0)
2726 {
2727 showError ('Invalid arguments', __FUNCTION__);
2728 die;
2729 }
2730 $ret = TRUE;
2731 foreach (getAutoPorts ($type_id) as $autoport)
2732 $ret = $ret and '' == commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
2733 return $ret;
2734 }
2735
2736 // Return only implicitly listed tags, the rest of the chain will be
2737 // generated/deducted later at higher levels.
2738 // Result is a chain: randomly indexed taginfo list.
2739 function loadEntityTags ($entity_realm = '', $entity_id = 0)
2740 {
2741 if ($entity_realm == '' or $entity_id <= 0)
2742 {
2743 showError ('Invalid or missing arguments', __FUNCTION__);
2744 return NULL;
2745 }
2746 $ret = array();
2747 $query = "select tt.id, tag from " .
2748 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
2749 "where target_realm = '${entity_realm}' and target_id = ${entity_id} " .
2750 "order by tt.tag";
2751 $result = useSelectBlade ($query, __FUNCTION__);
2752 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2753 $ret[$row['id']] = $row;
2754 $result->closeCursor();
2755 return getExplicitTagsOnly ($ret);
2756 }
2757
2758 function loadRackObjectTags ($id)
2759 {
2760 return loadEntityTags ('object', $id);
2761 }
2762
2763 function loadIPv4PrefixTags ($id)
2764 {
2765 return loadEntityTags ('ipv4net', $id);
2766 }
2767
2768 function loadRackTags ($id)
2769 {
2770 return loadEntityTags ('rack', $id);
2771 }
2772
2773 function loadIPv4VSTags ($id)
2774 {
2775 return loadEntityTags ('ipv4vs', $id);
2776 }
2777
2778 function loadIPv4RSPoolTags ($id)
2779 {
2780 return loadEntityTags ('ipv4rspool', $id);
2781 }
2782
2783 function loadUserTags ($user_id)
2784 {
2785 return loadEntityTags ('user', $user_id);
2786 }
2787
2788 // Return a tag chain with all DB tags on it.
2789 function getTagList ()
2790 {
2791 $ret = array();
2792 $query = "select id, parent_id, tag, target_realm as realm, count(target_id) as refcnt " .
2793 "from TagTree left join TagStorage on id = tag_id " .
2794 "group by id, target_realm order by tag";
2795 $result = useSelectBlade ($query, __FUNCTION__);
2796 $ci = 0; // Collation index. The resulting rows are ordered according to default collation,
2797 // which is utf8_general_ci for UTF-8.
2798 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2799 {
2800 if (!isset ($ret[$row['id']]))
2801 $ret[$row['id']] = array
2802 (
2803 'id' => $row['id'],
2804 'tag' => $row['tag'],
2805 'ci' => $ci++,
2806 'parent_id' => $row['parent_id'],
2807 'refcnt' => array()
2808 );
2809 if ($row['realm'])
2810 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
2811 }
2812 $result->closeCursor();
2813 return $ret;
2814 }
2815
2816 function commitCreateTag ($tagname = '', $parent_id = 0)
2817 {
2818 if ($tagname == '' or $parent_id === 0)
2819 return "Invalid args to " . __FUNCTION__;
2820 $result = useInsertBlade
2821 (
2822 'TagTree',
2823 array
2824 (
2825 'tag' => "'${tagname}'",
2826 'parent_id' => $parent_id
2827 )
2828 );
2829 if ($result)
2830 return '';
2831 else
2832 return "SQL query failed in " . __FUNCTION__;
2833 }
2834
2835 function commitDestroyTag ($tagid = 0)
2836 {
2837 if ($tagid == 0)
2838 return 'Invalid arg to ' . __FUNCTION__;
2839 if (useDeleteBlade ('TagTree', 'id', $tagid))
2840 return '';
2841 else
2842 return 'useDeleteBlade() failed in ' . __FUNCTION__;
2843 }
2844
2845 function commitUpdateTag ($tag_id, $tag_name, $parent_id)
2846 {
2847 if ($parent_id == 0)
2848 $parent_id = 'NULL';
2849 global $dbxlink;
2850 $query = "update TagTree set tag = '${tag_name}', parent_id = ${parent_id} " .
2851 "where id = ${tag_id} limit 1";
2852 $result = $dbxlink->exec ($query);
2853 if ($result === NULL)
2854 return 'SQL query failed in ' . __FUNCTION__;
2855 return '';
2856 }
2857
2858 // Drop the whole chain stored.
2859 function destroyTagsForEntity ($entity_realm, $entity_id)
2860 {
2861 global $dbxlink;
2862 $query = "delete from TagStorage where target_realm = '${entity_realm}' and target_id = ${entity_id}";
2863 $result = $dbxlink->exec ($query);
2864 if ($result === NULL)
2865 return FALSE;
2866 else
2867 return TRUE;
2868 }
2869
2870 // Drop only one record. This operation doesn't involve retossing other tags, unlike when adding.
2871 function deleteTagForEntity ($entity_realm, $entity_id, $tag_id)
2872 {
2873 global $dbxlink;
2874 $query = "delete from TagStorage where target_realm = '${entity_realm}' and target_id = ${entity_id} and tag_id = ${tag_id}";
2875 $result = $dbxlink->exec ($query);
2876 if ($result === NULL)
2877 return FALSE;
2878 else
2879 return TRUE;
2880 }
2881
2882 // Push a record into TagStorage unconditionally.
2883 function addTagForEntity ($realm = '', $entity_id, $tag_id)
2884 {
2885 if (empty ($realm))
2886 return FALSE;
2887 return useInsertBlade
2888 (
2889 'TagStorage',
2890 array
2891 (
2892 'target_realm' => "'${realm}'",
2893 'target_id' => $entity_id,
2894 'tag_id' => $tag_id,
2895 )
2896 );
2897 }
2898
2899 // Add records into TagStorage, if this makes sense (IOW, they don't appear
2900 // on the implicit list already). Then remove any other records, which
2901 // appear on the "implicit" side of the chain. This will make sure,
2902 // that both the tag base is still minimal and all requested tags appear on
2903 // the resulting tag chain.
2904 // Return TRUE, if any changes were committed.
2905 function rebuildTagChainForEntity ($realm, $entity_id, $extrachain = array())
2906 {
2907 // Put the current explicit sub-chain into a buffer and merge all tags from
2908 // the extra chain, which aren't there yet.
2909 $newchain = $oldchain = loadEntityTags ($realm, $entity_id);
2910 foreach ($extrachain as $extratag)
2911 if (!tagOnChain ($extratag, $newchain))
2912 $newchain[] = $extratag;
2913 // Then minimize the working buffer and check if it differs from the original
2914 // chain we started with. If it is so, save the work and signal the upper layer.
2915 $newchain = getExplicitTagsOnly ($newchain);
2916 if (tagChainCmp ($oldchain, $newchain))
2917 {
2918 destroyTagsForEntity ($realm, $entity_id);
2919 foreach ($newchain as $taginfo)
2920 addTagForEntity ($realm, $entity_id, $taginfo['id']);
2921 return TRUE;
2922 }
2923 return FALSE;
2924 }
2925
2926 // Presume, that the target record has no tags attached.
2927 function produceTagsForLastRecord ($realm, $tagidlist, $last_insert_id = 0)
2928 {
2929 if (!count ($tagidlist))
2930 return '';
2931 if (!$last_insert_id)
2932 $last_insert_id = lastInsertID();
2933 $errcount = 0;
2934 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagidlist)) as $taginfo)
2935 if (addTagForEntity ($realm, $last_insert_id, $taginfo['id']) == FALSE)
2936 $errcount++;
2937 if (!$errcount)
2938 return '';
2939 else
2940 return "Experienced ${errcount} errors adding tags in realm '${realm}' for entity ID == ${last_insert_id}";
2941 }
2942
2943 function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
2944 {
2945 // $range is in x.x.x.x/x format, split into ip/mask vars
2946 $rangeArray = explode('/', $range);
2947 if (count ($rangeArray) != 2)
2948 return "Invalid IPv4 prefix '${range}'";
2949 $ip = $rangeArray[0];
2950 $mask = $rangeArray[1];
2951
2952 if (empty ($ip) or empty ($mask))
2953 return "Invalid IPv4 prefix '${range}'";
2954 $ipL = ip2long($ip);
2955 $maskL = ip2long($mask);
2956 if ($ipL == -1 || $ipL === FALSE)
2957 return 'Bad IPv4 address';
2958 if ($mask < 32 && $mask > 0)
2959 $maskL = $mask;
2960 else
2961 {
2962 $maskB = decbin($maskL);
2963 if (strlen($maskB)!=32)
2964 return 'Invalid netmask';
2965 $ones=0;
2966 $zeroes=FALSE;
2967 foreach( str_split ($maskB) as $digit)
2968 {
2969 if ($digit == '0')
2970 $zeroes = TRUE;
2971 if ($digit == '1')
2972 {
2973 $ones++;
2974 if ($zeroes == TRUE)
2975 return 'Invalid netmask';
2976 }
2977 }
2978 $maskL = $ones;
2979 }
2980 $binmask = binMaskFromDec($maskL);
2981 $ipL = $ipL & $binmask;
2982 /*
2983 $query =
2984 "select ".
2985 "id, INET_NTOA(ip) as dottedquad, mask, name ".
2986 "from IPRanges";
2987
2988 $result = useSelectBlade ($query, __FUNCTION__);
2989
2990 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2991 {
2992 $otherip = ip2long ($row['dottedquad']);
2993 $othermask = binMaskFromDec ($row['mask']);
2994 if (($otherip & $othermask) == ($ipL & $othermask) or ($otherip & $binmask) == ($ipL & $binmask))
2995 return "This subnet intersects with ${row['dottedquad']}/${row['mask']}";
2996 }
2997 $result->closeCursor();
2998 unset ($result);
2999 */
3000 $result = useInsertBlade
3001 (
3002 'IPRanges',
3003 array
3004 (
3005 'ip' => sprintf ('%u', $ipL),
3006 'mask' => "'${maskL}'",
3007 'name' => "'${name}'"
3008 )
3009 );
3010
3011 if ($is_bcast and $maskL < 31)
3012 {
3013 $network_addr = long2ip ($ipL);
3014 $broadcast_addr = long2ip ($ipL | binInvMaskFromDec ($maskL));
3015 updateAddress ($network_addr, 'network', 'yes');
3016 updateAddress ($broadcast_addr, 'broadcast', 'yes');
3017 }
3018 return produceTagsForLastRecord ('ipv4net', $taglist);
3019 }
3020
3021 // FIXME: This function doesn't wipe relevant records from IPAddress table.
3022 function destroyIPv4Prefix ($id = 0)
3023 {
3024 if ($id <= 0)
3025 return __FUNCTION__ . ': Invalid IPv4 prefix ID';
3026 if (!useDeleteBlade ('IPRanges', 'id', $id))
3027 return __FUNCTION__ . ': SQL query #1 failed';
3028 if (!destroyTagsForEntity ('ipv4net', $id))
3029 return __FUNCTION__ . ': SQL query #2 failed';
3030 return '';
3031 }
3032
3033 function loadScript ($name)
3034 {
3035 $result = useSelectBlade ("select script_text from Script where script_name = '${name}'");
3036 $row = $result->fetch (PDO::FETCH_NUM);
3037 if ($row !== FALSE)
3038 return $row[0];
3039 else
3040 return NULL;
3041 }
3042
3043 function saveScript ($name, $text)
3044 {
3045 if (empty ($name))
3046 {
3047 showError ('Invalid argument');
3048 return FALSE;
3049 }
3050 // delete regardless of existence
3051 useDeleteBlade ('Script', 'script_name', "'${name}'");
3052 return useInsertBlade
3053 (
3054 'Script',
3055 array
3056 (
3057 'script_name' => "'${name}'",
3058 'script_text' => "'${text}'"
3059 )
3060 );
3061 }
3062
3063 function saveUserPassword ($user_id, $newp)
3064 {
3065 $newhash = hash (PASSWORD_HASH, $newp);
3066 $query = "update UserAccount set user_password_hash = ${newhash} where user_id = ${user_id} limit 1";
3067 }
3068
3069 function objectIsPortless ($id = 0)
3070 {
3071 if ($id <= 0)
3072 {
3073 showError ('Invalid argument', __FUNCTION__);
3074 return;
3075 }
3076 if (($result = useSelectBlade ("select count(id) from Port where object_id = ${id}", __FUNCTION__)) == NULL)
3077 {
3078 showError ('SQL query failed', __FUNCTION__);
3079 return;
3080 }
3081 $row = $result->fetch (PDO::FETCH_NUM);
3082 $count = $row[0];
3083 $result->closeCursor();
3084 unset ($result);
3085 return $count === '0';
3086 }
3087
3088 function recordExists ($id = 0, $realm = 'object')
3089 {
3090 if ($id <= 0)
3091 return FALSE;
3092 $table = array
3093 (
3094 'object' => 'RackObject',
3095 'ipv4net' => 'IPRanges',
3096 'user' => 'UserAccount',
3097 );
3098 $idcol = array
3099 (
3100 'object' => 'id',
3101 'ipv4net' => 'id',
3102 'user' => 'user_id',
3103 );
3104 $query = 'select count(*) from ' . $table[$realm] . ' where ' . $idcol[$realm] . ' = ' . $id;
3105 if (($result = useSelectBlade ($query, __FUNCTION__)) == NULL)
3106 {
3107 showError ('SQL query failed', __FUNCTION__);
3108 return FALSE;
3109 }
3110 $row = $result->fetch (PDO::FETCH_NUM);
3111 $count = $row[0];
3112 $result->closeCursor();
3113 unset ($result);
3114 return $count === '1';
3115 }
3116
3117 function tagExistsInDatabase ($tname)
3118 {
3119 $result = useSelectBlade ("select count(*) from TagTree where lower(tag) = lower('${tname}')");
3120 $row = $result->fetch (PDO::FETCH_NUM);
3121 $count = $row[0];
3122 $result->closeCursor();
3123 unset ($result);
3124 return $count !== '0';
3125 }
3126
3127 function newPortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3128 {
3129 if (NULL === getIPv4AddressNetworkId ($localip))
3130 return "$localip: Non existant ip";
3131 if (NULL === getIPv4AddressNetworkId ($localip))
3132 return "$remoteip: Non existant ip";
3133 if ( ($localport <= 0) or ($localport >= 65536) )
3134 return "$localport: invaild port";
3135 if ( ($remoteport <= 0) or ($remoteport >= 65536) )
3136 return "$remoteport: invaild port";
3137
3138 $result = useInsertBlade
3139 (
3140 'PortForwarding',
3141 array
3142 (
3143 'object_id' => $object_id,
3144 'localip' => "INET_ATON('${localip}')",
3145 'remoteip' => "INET_ATON('$remoteip')",
3146 'localport' => $localport,
3147 'remoteport' => $remoteport,
3148 'proto' => "'${proto}'",
3149 'description' => "'${description}'",
3150 )
3151 );
3152 if ($result)
3153 return '';
3154 else
3155 return __FUNCTION__ . ': Failed to insert the rule.';
3156 }
3157
3158 function deletePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto)
3159 {
3160 global $dbxlink;
3161
3162 $query =
3163 "delete from PortForwarding where object_id='$object_id' and localip=INET_ATON('$localip') and remoteip=INET_ATON('$remoteip') and localport='$localport' and remoteport='$remoteport' and proto='$proto'";
3164 $result = $dbxlink->exec ($query);
3165 return '';
3166 }
3167
3168 function updatePortForwarding ($object_id, $localip, $localport, $remoteip, $remoteport, $proto, $description)
3169 {
3170 global $dbxlink;
3171
3172 $query =
3173 "update PortForwarding set description='$description' where object_id='$object_id' and localip=INET_ATON('$localip') and remoteip=INET_ATON('$remoteip') and localport='$localport' and remoteport='$remoteport' and proto='$proto'";
3174 $result = $dbxlink->exec ($query);
3175 return '';
3176 }
3177
3178 function getNATv4ForObject ($object_id)
3179 {
3180 $ret = array();
3181 $ret['out'] = array();
3182 $ret['in'] = array();
3183 $query =
3184 "select ".
3185 "proto, ".
3186 "INET_NTOA(localip) as localip, ".
3187 "localport, ".
3188 "INET_NTOA(remoteip) as remoteip, ".
3189 "remoteport, ".
3190 "ipa1.name as local_addr_name, " .
3191 "ipa2.name as remote_addr_name, " .
3192 "description ".
3193 "from PortForwarding ".
3194 "left join IPAddress as ipa1 on PortForwarding.localip = ipa1.ip " .
3195 "left join IPAddress as ipa2 on PortForwarding.remoteip = ipa2.ip " .
3196 "where object_id='$object_id' ".
3197 "order by localip, localport, proto, remoteip, remoteport";
3198 $result = useSelectBlade ($query, __FUNCTION__);
3199 $count=0;
3200 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3201 {
3202 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'description', 'local_addr_name', 'remote_addr_name') as $cname)
3203 $ret['out'][$count][$cname] = $row[$cname];
3204 $count++;
3205 }
3206 $result->closeCursor();
3207 unset ($result);
3208
3209 $query =
3210 "select ".
3211 "proto, ".
3212 "INET_NTOA(localip) as localip, ".
3213 "localport, ".
3214 "INET_NTOA(remoteip) as remoteip, ".
3215 "remoteport, ".
3216 "PortForwarding.object_id as object_id, ".
3217 "RackObject.name as object_name, ".
3218 "description ".
3219 "from ((PortForwarding join IPBonds on remoteip=IPBonds.ip) join RackObject on PortForwarding.object_id=RackObject.id) ".
3220 "where IPBonds.object_id='$object_id' ".
3221 "order by remoteip, remoteport, proto, localip, localport";
3222 $result = useSelectBlade ($query, __FUNCTION__);
3223 $count=0;
3224 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3225 {
3226 foreach (array ('proto', 'localport', 'localip', 'remoteport', 'remoteip', 'object_id', 'object_name', 'description') as $cname)
3227 $ret['in'][$count][$cname] = $row[$cname];
3228 $count++;
3229 }
3230 $result->closeCursor();
3231
3232 return $ret;
3233 }
3234
3235 // This function performs search and then calculates score for each result.
3236 // Given previous search results in $objects argument, it adds new results
3237 // to the array and updates score for existing results, if it is greater than
3238 // existing score.
3239 function mergeSearchResults (&$objects, $terms, $fieldname)
3240 {
3241 global $dbxlink;
3242 $query =
3243 "select name, label, asset_no, barcode, ro.id, dict_key as objtype_id, " .
3244 "dict_value as objtype_name, asset_no from RackObject as ro inner join Dictionary " .
3245 "on objtype_id = dict_key natural join Chapter where chapter_name = 'RackObjectType' and ";
3246 $count = 0;
3247 foreach (explode (' ', $terms) as $term)
3248 {
3249 if ($count) $query .= ' or ';
3250 $query .= "${fieldname} like '%$term%'";
3251 $count++;
3252 }
3253 $query .= " order by ${fieldname}";
3254 $result = useSelectBlade ($query, __FUNCTION__);
3255 // FIXME: this dead call was executed 4 times per 1 object search!
3256 // $typeList = getObjectTypeList();
3257 $clist = array ('id', 'name', 'label', 'asset_no', 'barcode', 'objtype_id', 'objtype_name');
3258 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3259 {
3260 foreach ($clist as $cname)
3261 $object[$cname] = $row[$cname];
3262 $object['score'] = 0;
3263 $object['dname'] = displayedName ($object);
3264 unset ($object['objtype_id']);
3265 foreach (explode (' ', $terms) as $term)
3266 if (strstr ($object['name'], $term))
3267 $object['score'] += 1;
3268 unset ($object['name']);
3269 if (!isset ($objects[$row['id']]))
3270 $objects[$row['id']] = $object;
3271 elseif ($objects[$row['id']]['score'] < $object['score'])
3272 $objects[$row['id']]['score'] = $object['score'];
3273 }
3274 return $objects;
3275 }
3276
3277 ?>