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