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