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