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