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