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