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