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