r4393 processGridForm(): employ transaction to make sure, that the changes either
[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, $dbxlink;
900 $rack_id = $rackData['id'];
901 $rack_name = $rackData['name'];
902 $rackchanged = FALSE;
903 $dbxlink->beginTransaction();
904 for ($unit_no = $rackData['height']; $unit_no > 0; $unit_no--)
905 {
906 for ($locidx = 0; $locidx < 3; $locidx++)
907 {
908 if ($rackData[$unit_no][$locidx]['enabled'] != TRUE)
909 continue;
910 // detect a change
911 $state = $rackData[$unit_no][$locidx]['state'];
912 if (isset ($_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"]) and $_REQUEST["atom_${rack_id}_${unit_no}_${locidx}"] == 'on')
913 $newstate = $checked_state;
914 else
915 $newstate = $unchecked_state;
916 if ($state == $newstate)
917 continue;
918 $rackchanged = TRUE;
919 // and validate
920 $atom = $loclist[$locidx];
921 // The only changes allowed are those introduced by checkbox grid.
922 if
923 (
924 !($state == $checked_state && $newstate == $unchecked_state) &&
925 !($state == $unchecked_state && $newstate == $checked_state)
926 )
927 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, 'atom ${atom}', cannot change state from '${state}' to '${newstate}'");
928 // Here we avoid using ON DUPLICATE KEY UPDATE by first performing DELETE
929 // anyway and then looking for probable need of INSERT.
930 usePreparedDeleteBlade ('RackSpace', array ('rack_id' => $rack_id, 'unit_no' => $unit_no, 'atom' => $atom));
931 if ($newstate != 'F')
932 usePreparedInsertBlade ('RackSpace', array ('rack_id' => $rack_id, 'unit_no' => $unit_no, 'atom' => $atom, 'state' => $newstate));
933 if ($newstate == 'T' and $object_id != 0)
934 {
935 // At this point we already have a record in RackSpace.
936 $r = usePreparedUpdateBlade
937 (
938 'RackSpace',
939 array ('object_id' => $object_id),
940 array
941 (
942 'rack_id' => $rack_id,
943 'unit_no' => $unit_no,
944 'atom' => $atom,
945 )
946 );
947 if ($r === FALSE)
948 return array ('code' => 500, 'message' => "${rack_name}: Rack ID ${rack_id}, unit ${unit_no}, atom '${atom}' failed to set object_id to '${object_id}'");
949 $rackData[$unit_no][$locidx]['object_id'] = $object_id;
950 }
951 }
952 }
953 if ($rackchanged)
954 {
955 usePreparedUpdateBlade ('Rack', array ('thumb_data' => NULL), array ('id' => $rack_id));
956 $dbxlink->commit();
957 return array ('code' => 200, 'message' => "${rack_name}: All changes were successfully saved.");
958 }
959 $dbxlink->rollBack();
960 return array ('code' => 300, 'message' => "${rack_name}: No changes.");
961 }
962
963 // This function builds a list of rack-unit-atom records, which are assigned to
964 // the requested object.
965 function getMoleculeForObject ($object_id)
966 {
967 $result = usePreparedSelectBlade
968 (
969 'SELECT rack_id, unit_no, atom FROM RackSpace ' .
970 'WHERE state = "T" AND object_id = ? ORDER BY rack_id, unit_no, atom',
971 array ($object_id)
972 );
973 return $result->fetchAll (PDO::FETCH_ASSOC);
974 }
975
976 // This function builds a list of rack-unit-atom records for requested molecule.
977 function getMolecule ($mid = 0)
978 {
979 $result = usePreparedSelectBlade ('SELECT rack_id, unit_no, atom FROM Atom WHERE molecule_id = ?', array ($mid));
980 return $result->fetchAll (PDO::FETCH_ASSOC);
981 }
982
983 // returns exactly what is's named after
984 function lastInsertID ()
985 {
986 $result = usePreparedSelectBlade ('select last_insert_id()');
987 $row = $result->fetch (PDO::FETCH_NUM);
988 return $row[0];
989 }
990
991 // This function creates a new record in Molecule and number of linked
992 // R-U-A records in Atom.
993 function createMolecule ($molData)
994 {
995 usePreparedExecuteBlade ('INSERT INTO Molecule VALUES()');
996 $molecule_id = lastInsertID();
997 foreach ($molData as $rua)
998 usePreparedInsertBlade
999 (
1000 'Atom',
1001 array
1002 (
1003 'molecule_id' => $molecule_id,
1004 'rack_id' => $rua['rack_id'],
1005 'unit_no' => $rua['unit_no'],
1006 'atom' => $rua['atom'],
1007 )
1008 );
1009 return $molecule_id;
1010 }
1011
1012 // History logger. This function assumes certain table naming convention and
1013 // column design:
1014 // 1. History table name equals to dictionary table name plus 'History'.
1015 // 2. History table must have the same row set (w/o keys) plus one row named
1016 // 'ctime' of type 'timestamp'.
1017 function recordHistory ($tableName, $orig_id)
1018 {
1019 global $remote_username;
1020 return FALSE !== usePreparedExecuteBlade
1021 (
1022 "INSERT INTO ${tableName}History SELECT *, CURRENT_TIMESTAMP(), ? " .
1023 "FROM ${tableName} WHERE id=?",
1024 array ($remote_username, $orig_id)
1025 );
1026 }
1027
1028 function getRackspaceHistory ()
1029 {
1030 $result = usePreparedSelectBlade
1031 (
1032 "SELECT id as mo_id, object_id as ro_id, ctime, comment, user_name FROM " .
1033 "MountOperation ORDER BY ctime DESC"
1034 );
1035 return $result->fetchAll (PDO::FETCH_ASSOC);
1036 }
1037
1038 // This function is used in renderRackspaceHistory()
1039 function getOperationMolecules ($op_id = 0)
1040 {
1041 $result = usePreparedSelectBlade ('SELECT old_molecule_id, new_molecule_id FROM MountOperation WHERE id = ?', array ($op_id));
1042 // We expect one row.
1043 $row = $result->fetch (PDO::FETCH_ASSOC);
1044 return array ($row['old_molecule_id'], $row['new_molecule_id']);
1045 }
1046
1047 function getResidentRacksData ($object_id = 0, $fetch_rackdata = TRUE)
1048 {
1049 $result = usePreparedSelectBlade ('SELECT DISTINCT rack_id FROM RackSpace WHERE object_id = ? ORDER BY rack_id', array ($object_id));
1050 $rows = $result->fetchAll (PDO::FETCH_NUM);
1051 unset ($result);
1052 $ret = array();
1053 foreach ($rows as $row)
1054 {
1055 if (!$fetch_rackdata)
1056 {
1057 $ret[$row[0]] = $row[0];
1058 continue;
1059 }
1060 $rackData = spotEntity ('rack', $row[0]);
1061 amplifyCell ($rackData);
1062 $ret[$row[0]] = $rackData;
1063 }
1064 return $ret;
1065 }
1066
1067 function commitAddPort ($object_id = 0, $port_name, $port_type_id, $port_label, $port_l2address)
1068 {
1069 $db_l2address = l2addressForDatabase ($port_l2address);
1070 global $dbxlink;
1071 $dbxlink->exec ('LOCK TABLES Port WRITE');
1072 if (alreadyUsedL2Address ($db_l2address, $object_id))
1073 {
1074 $dbxlink->exec ('UNLOCK TABLES');
1075 throw new InvalidRequestArgException ('port_l2address', $port_l2address, 'address belongs to another object');
1076 }
1077 $matches = array();
1078 switch (1)
1079 {
1080 case preg_match ('/^([[:digit:]]+)-([[:digit:]]+)$/', $port_type_id, $matches):
1081 $iif_id = $matches[1];
1082 $oif_id = $matches[2];
1083 break;
1084 case preg_match ('/^([[:digit:]]+)$/', $port_type_id, $matches):
1085 $iif_id = 1;
1086 $oif_id = $matches[1];
1087 break;
1088 default:
1089 $dbxlink->exec ('UNLOCK TABLES');
1090 throw new InvalidArgException ('port_type_id', $port_type_id, 'format error');
1091 }
1092 $result = usePreparedInsertBlade
1093 (
1094 'Port',
1095 array
1096 (
1097 'name' => $port_name,
1098 'object_id' => $object_id,
1099 'label' => $port_label,
1100 'iif_id' => $iif_id,
1101 'type' => $oif_id,
1102 'l2address' => ($db_l2address === '') ? NULL : $db_l2address,
1103 )
1104 );
1105 $dbxlink->exec ('UNLOCK TABLES');
1106 }
1107
1108 // The fifth argument may be either explicit 'NULL' or some (already quoted by the upper layer)
1109 // string value. In case it is omitted, we just assign it its current value.
1110 // It would be nice to simplify this semantics later.
1111 function commitUpdatePort ($object_id, $port_id, $port_name, $port_type_id, $port_label, $port_l2address, $port_reservation_comment)
1112 {
1113 $db_l2address = l2addressForDatabase ($port_l2address);
1114 global $dbxlink;
1115 $dbxlink->exec ('LOCK TABLES Port WRITE');
1116 if (alreadyUsedL2Address ($db_l2address, $object_id))
1117 {
1118 $dbxlink->exec ('UNLOCK TABLES');
1119 // FIXME: it is more correct to throw InvalidArgException here
1120 // and convert it to InvalidRequestArgException at upper level,
1121 // when there is a mean to do that.
1122 throw new InvalidRequestArgException ('port_l2address', $db_l2address, 'address belongs to another object');
1123 }
1124 usePreparedUpdateBlade
1125 (
1126 'Port',
1127 array
1128 (
1129 'name' => $port_name,
1130 'type' => $port_type_id,
1131 'label' => $port_label,
1132 'reservation_comment' => mb_strlen ($port_reservation_comment) ? $port_reservation_comment : NULL,
1133 'l2address' => ($db_l2address === '') ? NULL : $db_l2address,
1134 ),
1135 array
1136 (
1137 'id' => $port_id,
1138 'object_id' => $object_id
1139 )
1140 );
1141 $dbxlink->exec ('UNLOCK TABLES');
1142 }
1143
1144 function commitUpdatePortOIF ($port_id, $port_type_id)
1145 {
1146 return usePreparedUpdateBlade
1147 (
1148 'Port',
1149 array ('type' => $port_type_id),
1150 array ('id' => $port_id)
1151 );
1152 }
1153
1154 function getAllIPv4Allocations ()
1155 {
1156 $result = usePreparedSelectBlade
1157 (
1158 "select object_id as object_id, ".
1159 "RackObject.name as object_name, ".
1160 "IPv4Allocation.name as name, ".
1161 "INET_NTOA(ip) as ip ".
1162 "from IPv4Allocation join RackObject on id=object_id "
1163 );
1164 $ret = array();
1165 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1166 $ret[] = $row;
1167 return $ret;
1168 }
1169
1170 function linkPorts ($porta, $portb, $cable = NULL)
1171 {
1172 if ($porta == $portb)
1173 throw new InvalidArgException ('porta/portb', $porta, "Ports can't be the same");
1174
1175 global $dbxlink;
1176 $dbxlink->exec ('LOCK TABLES Link WRITE');
1177 $result = usePreparedSelectBlade
1178 (
1179 'SELECT COUNT(*) FROM Link WHERE porta IN (?,?) OR portb IN (?,?)',
1180 array ($porta, $portb, $porta, $portb)
1181 );
1182 if ($result->fetchColumn () != 0)
1183 {
1184 $dbxlink->exec ('UNLOCK TABLES');
1185 return "Port ${porta} or ${portb} is already linked";
1186 }
1187 $result->closeCursor ();
1188 if ($porta > $portb)
1189 {
1190 $tmp = $porta;
1191 $porta = $portb;
1192 $portb = $tmp;
1193 }
1194 $ret = FALSE !== usePreparedInsertBlade ('Link', array ('porta' => $porta, 'portb' => $portb, 'cable' => $cable));
1195 $dbxlink->exec ('UNLOCK TABLES');
1196 $ret = $ret and FALSE !== usePreparedExecuteBlade
1197 (
1198 'UPDATE Port SET reservation_comment=NULL WHERE id IN(?, ?)',
1199 array ($porta, $portb)
1200 );
1201 return $ret ? '' : 'query failed';
1202 }
1203
1204 // Returns all IPv4 addresses allocated to object, but does not attach detailed info about address
1205 // Used instead of getObjectIPv4Allocations if you need perfomance but 'addrinfo' value
1206 function getObjectIPv4AllocationList ($object_id)
1207 {
1208 $ret = array();
1209 $result = usePreparedSelectBlade
1210 (
1211 'SELECT name AS osif, type, inet_ntoa(ip) AS dottedquad FROM IPv4Allocation ' .
1212 'WHERE object_id = ? ORDER BY ip',
1213 array ($object_id)
1214 );
1215 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1216 $ret[$row['dottedquad']] = array ('osif' => $row['osif'], 'type' => $row['type']);
1217 return $ret;
1218 }
1219
1220 // Return all IPv4 addresses allocated to the objects. Attach detailed
1221 // info about address to each alocation records. Index result by dotted-quad
1222 // address.
1223 function getObjectIPv4Allocations ($object_id = 0)
1224 {
1225 $ret = getObjectIPv4AllocationList ($object_id);
1226 foreach (array_keys ($ret) as $dottedquad)
1227 $ret[$dottedquad]['addrinfo'] = getIPv4Address ($dottedquad);
1228 return $ret;
1229 }
1230
1231 // Returns all IPv4 addresses allocated to object, but does not attach detailed info about address
1232 // Used instead of getObjectIPv6Allocations if you need perfomance but 'addrinfo' value
1233 function getObjectIPv6AllocationList ($object_id)
1234 {
1235 $ret = array();
1236 $result = usePreparedSelectBlade
1237 (
1238 'SELECT name AS osif, type, ip AS ip FROM IPv6Allocation ' .
1239 'WHERE object_id = ? ORDER BY ip',
1240 array ($object_id)
1241 );
1242 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1243 $ret[$row['ip']] = array ('osif' => $row['osif'], 'type' => $row['type']);
1244 return $ret;
1245 }
1246
1247 // Return all IPv6 addresses allocated to the objects. Attach detailed
1248 // info about address to each alocation records. Index result by binary string of IPv6
1249 function getObjectIPv6Allocations ($object_id = 0)
1250 {
1251 $ret = getObjectIPv6AllocationList ($object_id);
1252 foreach (array_keys ($ret) as $ip_bin)
1253 $ret[$ip_bin]['addrinfo'] = getIPv6Address (new IPv6Address ($ip_bin));
1254 return $ret;
1255 }
1256
1257 // Return minimal IPv4 address, optionally with "ip" key set, if requested.
1258 function constructIPv4Address ($dottedquad = NULL)
1259 {
1260 $ret = array
1261 (
1262 'version' => 4,
1263 'name' => '',
1264 'reserved' => 'no',
1265 'outpf' => array(),
1266 'inpf' => array(),
1267 'rslist' => array(),
1268 'allocs' => array(),
1269 'lblist' => array()
1270 );
1271 if ($dottedquad != NULL)
1272 $ret['ip'] = $dottedquad;
1273 return $ret;
1274 }
1275
1276 // Return minimal IPv6 address, optionally with "ip" key set, if requested.
1277 function constructIPv6Address ($bin_ip = NULL)
1278 {
1279 $ret = array
1280 (
1281 'version' => 6,
1282 'name' => '',
1283 'reserved' => 'no',
1284 'allocs' => array(),
1285 );
1286 if ($bin_ip != NULL)
1287 $ret['ip'] = $bin_ip->format();
1288 return $ret;
1289 }
1290
1291 // Check the range requested for meaningful IPv4 records, build them
1292 // into a list and return. Return an empty list if nothing matched.
1293 // Both arguments are expected in signed int32 form. The resulting list
1294 // is keyed by uint32 form of each IP address, items aren't sorted.
1295 // LATER: accept a list of pairs and build WHERE sub-expression accordingly
1296 function scanIPv4Space ($pairlist)
1297 {
1298 $ret = array();
1299 if (!count ($pairlist)) // this is normal for a network completely divided into smaller parts
1300 return $ret;
1301 // FIXME: this is a copy-and-paste prototype
1302 $or = '';
1303 $whereexpr1 = '(';
1304 $whereexpr2 = '(';
1305 $whereexpr3 = '(';
1306 $whereexpr4 = '(';
1307 $whereexpr5a = '(';
1308 $whereexpr5b = '(';
1309 $qparams = array();
1310 foreach ($pairlist as $tmp)
1311 {
1312 $db_first = sprintf ('%u', 0x00000000 + $tmp['i32_first']);
1313 $db_last = sprintf ('%u', 0x00000000 + $tmp['i32_last']);
1314 $whereexpr1 .= $or . "ip between ? and ?";
1315 $whereexpr2 .= $or . "ip between ? and ?";
1316 $whereexpr3 .= $or . "vip between ? and ?";
1317 $whereexpr4 .= $or . "rsip between ? and ?";
1318 $whereexpr5a .= $or . "remoteip between ? and ?";
1319 $whereexpr5b .= $or . "localip between ? and ?";
1320 $or = ' or ';
1321 $qparams[] = $db_first;
1322 $qparams[] = $db_last;
1323 }
1324 $whereexpr1 .= ')';
1325 $whereexpr2 .= ')';
1326 $whereexpr3 .= ')';
1327 $whereexpr4 .= ')';
1328 $whereexpr5a .= ')';
1329 $whereexpr5b .= ')';
1330
1331 // 1. collect labels and reservations
1332 $query = "select INET_NTOA(ip) as ip, name, reserved from IPv4Address ".
1333 "where ${whereexpr1} and (reserved = 'yes' or name != '')";
1334 $result = usePreparedSelectBlade ($query, $qparams);
1335 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1336 {
1337 $ip_bin = ip2long ($row['ip']);
1338 if (!isset ($ret[$ip_bin]))
1339 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1340 $ret[$ip_bin]['name'] = $row['name'];
1341 $ret[$ip_bin]['reserved'] = $row['reserved'];
1342 }
1343 unset ($result);
1344
1345 // 2. check for allocations
1346 $query =
1347 "select INET_NTOA(ip) as ip, object_id, name, type " .
1348 "from IPv4Allocation where ${whereexpr2} order by type";
1349 $result = usePreparedSelectBlade ($query, $qparams);
1350 // release DBX early to avoid issues with nested spotEntity() calls
1351 $allRows = $result->fetchAll (PDO::FETCH_ASSOC);
1352 unset ($result);
1353 foreach ($allRows as $row)
1354 {
1355 $ip_bin = ip2long ($row['ip']);
1356 if (!isset ($ret[$ip_bin]))
1357 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1358 $oinfo = spotEntity ('object', $row['object_id']);
1359 $ret[$ip_bin]['allocs'][] = array
1360 (
1361 'type' => $row['type'],
1362 'name' => $row['name'],
1363 'object_id' => $row['object_id'],
1364 'object_name' => $oinfo['dname'],
1365 );
1366 }
1367
1368 // 3. look for virtual services and related LB
1369 $query = "select vs_id, inet_ntoa(vip) as ip, vport, proto, vs.name, object_id " .
1370 "from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id " .
1371 "where ${whereexpr3} order by vport, proto, object_id";
1372 $result = usePreparedSelectBlade ($query, $qparams);
1373 $allRows = $result->fetchAll (PDO::FETCH_ASSOC);
1374 unset ($result);
1375 foreach ($allRows as $row)
1376 {
1377 $ip_bin = ip2long ($row['ip']);
1378 if (!isset ($ret[$ip_bin]))
1379 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1380 $oinfo = spotEntity ('object', $row['object_id']);
1381 $ret[$ip_bin]['lblist'][] = array
1382 (
1383 'vport' => $row['vport'],
1384 'proto' => $row['proto'],
1385 'vs_id' => $row['vs_id'],
1386 'name' => $row['name'],
1387 'vip' => $row['ip'],
1388 'object_id' => $row['object_id'],
1389 'object_name' => $oinfo['dname'],
1390 );
1391 }
1392
1393 // 4. don't forget about real servers along with pools
1394 $query = "select inet_ntoa(rsip) as ip, inservice, rsport, rspool_id, rsp.name as rspool_name from " .
1395 "IPv4RS as rs inner join IPv4RSPool as rsp on rs.rspool_id = rsp.id " .
1396 "where ${whereexpr4} " .
1397 "order by ip, rsport, rspool_id";
1398 $result = usePreparedSelectBlade ($query, $qparams);
1399 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1400 {
1401 $ip_bin = ip2long ($row['ip']);
1402 if (!isset ($ret[$ip_bin]))
1403 $ret[$ip_bin] = constructIPv4Address ($row['ip']);
1404 $tmp = array();
1405 foreach (array ('rspool_id', 'rsport', 'rspool_name', 'inservice') as $cname)
1406 $tmp[$cname] = $row[$cname];
1407 $ret[$ip_bin]['rslist'][] = $tmp;
1408 }
1409 unset ($result);
1410
1411 // 5. add NAT rules, part 1
1412 $query =
1413 "select " .
1414 "proto, " .
1415 "INET_NTOA(localip) as localip, " .
1416 "localport, " .
1417 "INET_NTOA(remoteip) as remoteip, " .
1418 "remoteport, " .
1419 "description " .
1420 "from IPv4NAT " .
1421 "where ${whereexpr5a} " .
1422 "order by localip, localport, remoteip, remoteport, proto";
1423 $result = usePreparedSelectBlade ($query, $qparams);
1424 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1425 {
1426 $remoteip_bin = ip2long ($row['remoteip']);
1427 if (!isset ($ret[$remoteip_bin]))
1428 $ret[$remoteip_bin] = constructIPv4Address ($row['remoteip']);
1429 $ret[$remoteip_bin]['inpf'][] = $row;
1430 }
1431 unset ($result);
1432 // 5. add NAT rules, part 2
1433 $query =
1434 "select " .
1435 "proto, " .
1436 "INET_NTOA(localip) as localip, " .
1437 "localport, " .
1438 "INET_NTOA(remoteip) as remoteip, " .
1439 "remoteport, " .
1440 "description " .
1441 "from IPv4NAT " .
1442 "where ${whereexpr5b} " .
1443 "order by localip, localport, remoteip, remoteport, proto";
1444 $result = usePreparedSelectBlade ($query, $qparams);
1445 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1446 {
1447 $localip_bin = ip2long ($row['localip']);
1448 if (!isset ($ret[$localip_bin]))
1449 $ret[$localip_bin] = constructIPv4Address ($row['localip']);
1450 $ret[$localip_bin]['outpf'][] = $row;
1451 }
1452 unset ($result);
1453 return $ret;
1454 }
1455
1456 // Check the range requested for meaningful IPv6 records, build them
1457 // into a list and return. Return an empty list if nothing matched.
1458 // Both arguments are expected as instances of IPv6Address class. The resulting list
1459 // is keyed by uint32 form of each IP address, items aren't sorted.
1460 function scanIPv6Space ($pairlist)
1461 {
1462 $ret = array();
1463 $wheres = array();
1464 foreach ($pairlist as $pair)
1465 {
1466 $wheres[] = "ip >= ? AND ip <= ?";
1467 $qparams[] = $pair['first']->getBin();
1468 $qparams[] = $pair['last']->getBin();
1469 }
1470 if (! count ($wheres)) // this is normal for a network completely divided into smaller parts
1471 return $ret;
1472 $whereexpr = '(' .implode (' OR ', $wheres) . ')';
1473
1474 // 1. collect labels and reservations
1475 $query = "select ip, name, reserved from IPv6Address ".
1476 "where ${whereexpr} and (reserved = 'yes' or name != '')";
1477 $result = usePreparedSelectBlade ($query, $qparams);
1478 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1479 {
1480 $ip_bin = new IPv6Address ($row['ip']);
1481 $key = $ip_bin->getBin();
1482 if (!isset ($ret[$key]))
1483 $ret[$key] = constructIPv6Address ($ip_bin);
1484 $ret[$key]['name'] = $row['name'];
1485 $ret[$key]['reserved'] = $row['reserved'];
1486 }
1487 unset ($result);
1488
1489 // 2. check for allocations
1490 $query =
1491 "select ip, object_id, name, type " .
1492 "from IPv6Allocation where ${whereexpr} order by type";
1493 $result = usePreparedSelectBlade ($query, $qparams);
1494 // release DBX early to avoid issues with nested spotEntity() calls
1495 $allRows = $result->fetchAll (PDO::FETCH_ASSOC);
1496 unset ($result);
1497 foreach ($allRows as $row)
1498 {
1499 $ip_bin = new IPv6Address ($row['ip']);
1500 $key = $ip_bin->getBin();
1501 if (!isset ($ret[$key]))
1502 $ret[$key] = constructIPv6Address ($ip_bin);
1503 $oinfo = spotEntity ('object', $row['object_id']);
1504 $ret[$key]['allocs'][] = array
1505 (
1506 'type' => $row['type'],
1507 'name' => $row['name'],
1508 'object_id' => $row['object_id'],
1509 'object_name' => $oinfo['dname'],
1510 );
1511 }
1512 return $ret;
1513 }
1514
1515 // this is a wrapper around getIPv4Address and getIPv6Address
1516 // You can pass dotted IPv4, human representation of IPv6, or instance of IPv6Address
1517 function getIPAddress ($ip)
1518 {
1519 if (is_a ($ip, 'IPv6Address'))
1520 return getIPv6Address ($ip);
1521 $ipv6 = new IPv6Address;
1522 if ($ipv6->parse ($ip))
1523 return getIPv6Address ($ipv6);
1524 return getIPv4Address ($ip);
1525 }
1526
1527 function getIPv4Address ($dottedquad = '')
1528 {
1529 if ($dottedquad == '')
1530 throw new InvalidArgException ('$dottedquad', $dottedquad);
1531 $i32 = ip2long ($dottedquad); // signed 32 bit
1532 $scanres = scanIPv4Space (array (array ('i32_first' => $i32, 'i32_last' => $i32)));
1533 if (empty ($scanres))
1534 //$scanres[$i32] = constructIPv4Address ($dottedquad); // XXX: this should be verified to not break things
1535 return constructIPv4Address ($dottedquad);
1536 markupIPAddrList ($scanres);
1537 return $scanres[$i32];
1538 }
1539
1540 // returns the array of structure described by constructIPv6Address
1541 function getIPv6Address ($v6addr)
1542 {
1543 if (! is_object ($v6addr))
1544 throw new InvalidArgException ('$v6addr', $v6addr);
1545 $scanres = scanIPv6Space (array (array ('first' => $v6addr, 'last' => $v6addr)));
1546 if (empty ($scanres))
1547 return constructIPv6Address ($v6addr);
1548 markupIPAddrList ($scanres);
1549 return array_shift ($scanres);
1550 }
1551
1552 function bindIpToObject ($ip = '', $object_id = 0, $name = '', $type = '')
1553 {
1554 return usePreparedExecuteBlade
1555 (
1556 'INSERT INTO IPv4Allocation (ip, object_id, name, type) VALUES (INET_ATON(?), ?, ?, ?)',
1557 array ($ip, $object_id, $name, $type)
1558 );
1559 }
1560
1561 function bindIPv6ToObject ($ip, $object_id = 0, $name = '', $type = '')
1562 {
1563 return usePreparedInsertBlade
1564 (
1565 'IPv6Allocation',
1566 array ('ip' => $ip->getBin(), 'object_id' => $object_id, 'name' => $name, 'type' => $type)
1567 );
1568 }
1569
1570 // Return the id of the smallest IPv4 network containing the given IPv4 address
1571 // or NULL, if nothing was found. When finding the covering network for
1572 // another network, it is important to filter out matched records with longer
1573 // masks (they aren't going to be the right pick).
1574 function getIPv4AddressNetworkId ($dottedquad, $masklen = 32)
1575 {
1576 $query = 'select id from IPv4Network where ' .
1577 "inet_aton(?) & (4294967295 >> (32 - mask)) << (32 - mask) = ip " .
1578 "and mask < ? " .
1579 'order by mask desc limit 1';
1580 $result = usePreparedSelectBlade ($query, array ($dottedquad, $masklen));
1581 if ($row = $result->fetch (PDO::FETCH_ASSOC))
1582 return $row['id'];
1583 return NULL;
1584 }
1585
1586 // Return the id of the smallest IPv6 network containing the given IPv6 address
1587 // ($ip is an instance of IPv4Address class) or NULL, if nothing was found.
1588 function getIPv6AddressNetworkId ($ip, $masklen = 128)
1589 {
1590 $query = 'select id from IPv6Network where ip <= ? AND last_ip >= ? and mask < ? order by mask desc limit 1';
1591 $result = usePreparedSelectBlade ($query, array ($ip->getBin(), $ip->getBin(), $masklen));
1592 if ($row = $result->fetch (PDO::FETCH_ASSOC))
1593 return $row['id'];
1594 return NULL;
1595 }
1596
1597 // It is a wrapper around updateV4Address and updateV6Address.
1598 // You can pass dotted IPv4, human representation of IPv6, or instance of IPv6Address
1599 function updateAddress ($ip = 0, $name = '', $reserved = 'no')
1600 {
1601 if (is_a ($ip, 'IPv6Address'))
1602 return updateV6Address ($ip, $name, $reserved);
1603 $ipv6 = new IPv6Address;
1604 if ($ipv6->parse ($ip))
1605 return updateV6Address ($ipv6, $name, $reserved);
1606 return updateV4Address ($ip, $name, $reserved);
1607 }
1608
1609 // This function is actually used not only to update, but also to create records,
1610 // that's why ON DUPLICATE KEY UPDATE was replaced by DELETE-INSERT pair
1611 // (MySQL 4.0 workaround).
1612 function updateV4Address ($ip = 0, $name = '', $reserved = 'no')
1613 {
1614 usePreparedExecuteBlade ('DELETE FROM IPv4Address WHERE ip = INET_ATON(?)', array ($ip));
1615 // INSERT may appear not necessary.
1616 if ($name == '' and $reserved == 'no')
1617 return '';
1618 $ret = usePreparedExecuteBlade
1619 (
1620 'INSERT INTO IPv4Address (name, reserved, ip) VALUES (?, ?, INET_ATON(?))',
1621 array ($name, $reserved, $ip)
1622 );
1623 return $ret !== FALSE ? '' : (__FUNCTION__ . 'query failed');
1624 }
1625
1626 function updateV6Address ($ip, $name = '', $reserved = 'no')
1627 {
1628 usePreparedDeleteBlade ('IPv6Address', array ('ip' => $ip->getBin()));
1629 // INSERT may appear not necessary.
1630 if ($name == '' and $reserved == 'no')
1631 return '';
1632 $ret = usePreparedInsertBlade
1633 (
1634 'IPv6Address',
1635 array ('name' => $name, 'reserved' => $reserved, 'ip' => $ip->getBin())
1636 );
1637 return $ret !== FALSE ? '' : (__FUNCTION__ . 'query failed');
1638 }
1639
1640 function updateBond ($ip='', $object_id=0, $name='', $type='')
1641 {
1642 return usePreparedExecuteBlade
1643 (
1644 'UPDATE IPv4Allocation SET name=?, type=? WHERE ip=INET_ATON(?) AND object_id=?',
1645 array ($name, $type, $ip, $object_id)
1646 );
1647 }
1648
1649 function updateIPv6Bond ($ip, $object_id=0, $name='', $type='')
1650 {
1651 return usePreparedUpdateBlade
1652 (
1653 'IPv6Allocation',
1654 array
1655 (
1656 'name' => $name,
1657 'type' => $type,
1658 ),
1659 array
1660 (
1661 'ip' => $ip->getBin(),
1662 'object_id' => $object_id,
1663 )
1664 );
1665 }
1666
1667 function unbindIpFromObject ($ip, $object_id)
1668 {
1669 return usePreparedExecuteBlade
1670 (
1671 'DELETE FROM IPv4Allocation WHERE ip=INET_ATON(?) AND object_id=?',
1672 array ($ip, $object_id)
1673 );
1674 }
1675
1676 function unbindIPv6FromObject ($ip, $object_id)
1677 {
1678 return usePreparedDeleteBlade
1679 (
1680 'IPv6Allocation',
1681 array ('ip' => $ip->getBin(), 'object_id' => $object_id)
1682 );
1683 }
1684
1685 function getIPv4PrefixSearchResult ($terms)
1686 {
1687 $byname = getSearchResultByField
1688 (
1689 'IPv4Network',
1690 array ('id'),
1691 'name',
1692 $terms,
1693 'ip'
1694 );
1695 $ret = array();
1696 foreach ($byname as $row)
1697 $ret[$row['id']] = spotEntity ('ipv4net', $row['id']);
1698 return $ret;
1699 }
1700
1701 function getIPv6PrefixSearchResult ($terms)
1702 {
1703 $byname = getSearchResultByField
1704 (
1705 'IPv6Network',
1706 array ('id'),
1707 'name',
1708 $terms,
1709 'ip'
1710 );
1711 $ret = array();
1712 foreach ($byname as $row)
1713 $ret[$row['id']] = spotEntity ('ipv6net', $row['id']);
1714 return $ret;
1715 }
1716
1717 function getIPv4AddressSearchResult ($terms)
1718 {
1719 $query = "select inet_ntoa(ip) as ip, name from IPv4Address where ";
1720 $or = '';
1721 $qparams = array();
1722 foreach (explode (' ', $terms) as $term)
1723 {
1724 $query .= $or . "name like ?";
1725 $or = ' or ';
1726 $qparams[] = "%${term}%";
1727 }
1728 $result = usePreparedSelectBlade ($query, $qparams);
1729 $ret = array();
1730 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1731 $ret[$row['ip']] = $row;
1732 return $ret;
1733 }
1734
1735 function getIPv6AddressSearchResult ($terms)
1736 {
1737 $query = "select ip, name from IPv6Address where ";
1738 $or = '';
1739 $qparams = array();
1740 foreach (explode (' ', $terms) as $term)
1741 {
1742 $query .= $or . "name like ?";
1743 $or = ' or ';
1744 $qparams[] = "%${term}%";
1745 }
1746 $result = usePreparedSelectBlade ($query, $qparams);
1747 $ret = array();
1748 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1749 $ret[$row['ip']] = $row;
1750 return $ret;
1751 }
1752
1753 function getIPv4RSPoolSearchResult ($terms)
1754 {
1755 $byname = getSearchResultByField
1756 (
1757 'IPv4RSPool',
1758 array ('id'),
1759 'name',
1760 $terms,
1761 'name'
1762 );
1763 $ret = array();
1764 foreach ($byname as $row)
1765 $ret[$row['id']] = spotEntity ('ipv4rspool', $row['id']);
1766 return $ret;
1767 }
1768
1769 function getIPv4VServiceSearchResult ($terms)
1770 {
1771 $byname = getSearchResultByField
1772 (
1773 'IPv4VS',
1774 array ('id'),
1775 'name',
1776 $terms,
1777 'vip'
1778 );
1779 $ret = array();
1780 foreach ($byname as $row)
1781 $ret[$row['id']] = spotEntity ('ipv4vs', $row['id']);
1782 return $ret;
1783 }
1784
1785 function getAccountSearchResult ($terms)
1786 {
1787 $byUsername = getSearchResultByField
1788 (
1789 'UserAccount',
1790 array ('user_id', 'user_name', 'user_realname'),
1791 'user_name',
1792 $terms,
1793 'user_name'
1794 );
1795 $byRealname = getSearchResultByField
1796 (
1797 'UserAccount',
1798 array ('user_id', 'user_name', 'user_realname'),
1799 'user_realname',
1800 $terms,
1801 'user_name'
1802 );
1803 // Merge it together, if duplicates persist, byUsername wins
1804 $ret = array();
1805 foreach (array ($byRealname, $byUsername) as $array)
1806 foreach ($array as $user)
1807 {
1808 $user['realm'] = 'user';
1809 $ret[$user['user_id']] = $user;
1810 }
1811 return $ret;
1812 }
1813
1814 function getFileSearchResult ($terms)
1815 {
1816 $byName = getSearchResultByField
1817 (
1818 'File',
1819 array ('id'),
1820 'name',
1821 $terms,
1822 'name'
1823 );
1824 $byComment = getSearchResultByField
1825 (
1826 'File',
1827 array ('id'),
1828 'comment',
1829 $terms,
1830 'name'
1831 );
1832 // Filter out dupes.
1833 foreach ($byName as $res1)
1834 foreach (array_keys ($byComment) as $key2)
1835 if ($res1['id'] == $byComment[$key2]['id'])
1836 {
1837 unset ($byComment[$key2]);
1838 continue 2;
1839 }
1840 $ret = array();
1841 foreach (array_merge ($byName, $byComment) as $row)
1842 $ret[$row['id']] = spotEntity ('file', $row['id']);
1843 return $ret;
1844 }
1845
1846 function getRackSearchResult ($terms)
1847 {
1848 $byName = getSearchResultByField
1849 (
1850 'Rack',
1851 array ('id'),
1852 'name',
1853 $terms,
1854 'name'
1855 );
1856 $byComment = getSearchResultByField
1857 (
1858 'Rack',
1859 array ('id'),
1860 'comment',
1861 $terms,
1862 'name'
1863 );
1864 // Filter out dupes.
1865 foreach ($byName as $res1)
1866 foreach (array_keys ($byComment) as $key2)
1867 if ($res1['id'] == $byComment[$key2]['id'])
1868 {
1869 unset ($byComment[$key2]);
1870 continue 2;
1871 }
1872 $ret = array();
1873 foreach (array_merge ($byName, $byComment) as $row)
1874 $ret[$row['id']] = spotEntity ('rack', $row['id']);
1875 return $ret;
1876 }
1877
1878 function getVLANSearchResult ($terms)
1879 {
1880 $ret = array();
1881 $matches = array();
1882 if (preg_match ('/^vlan\s*(\d+)$/i', $terms, $matches))
1883 {
1884 $byID = getSearchResultByField
1885 (
1886 'VLANDescription',
1887 array ('domain_id', 'vlan_id'),
1888 'vlan_id',
1889 $matches[1],
1890 'domain_id',
1891 1
1892 );
1893 foreach ($byID as $row)
1894 {
1895 $vlan_ck = $row['domain_id'] . '-' . $row['vlan_id'];
1896 $ret[$vlan_ck] = $vlan_ck;
1897 }
1898 }
1899 else
1900 {
1901 $byDescr = getSearchResultByField
1902 (
1903 'VLANDescription',
1904 array ('domain_id', 'vlan_id'),
1905 'vlan_descr',
1906 $terms
1907 );
1908 foreach ($byDescr as $row)
1909 {
1910 $vlan_ck = $row['domain_id'] . '-' . $row['vlan_id'];
1911 $ret[$vlan_ck] = $vlan_ck;
1912 }
1913 }
1914 return $ret;
1915 }
1916
1917 function getSearchResultByField ($tname, $rcolumns, $scolumn, $terms, $ocolumn = '', $exactness = 0)
1918 {
1919 $pfx = '';
1920 $query = 'select ';
1921 $qparams = array();
1922 foreach ($rcolumns as $col)
1923 {
1924 $query .= $pfx . $col;
1925 $pfx = ', ';
1926 }
1927 $pfx = '';
1928 $query .= " from ${tname} where ";
1929 foreach (explode (' ', $terms) as $term)
1930 {
1931 switch ($exactness)
1932 {
1933 case 2: // does this work as expected?
1934 $query .= $pfx . "binary ${scolumn} = ?";
1935 $qparams[] = $term;
1936 break;
1937 case 1:
1938 $query .= $pfx . "${scolumn} = ?";
1939 $qparams[] = $term;
1940 break;
1941 default:
1942 $query .= $pfx . "${scolumn} like ?";
1943 $qparams[] = "%${term}%";
1944 break;
1945 }
1946 $pfx = ' or ';
1947 }
1948 if ($ocolumn != '')
1949 $query .= " order by ${ocolumn}";
1950 $result = usePreparedSelectBlade ($query, $qparams);
1951 $ret = array();
1952 while ($row = $result->fetch (PDO::FETCH_ASSOC))
1953 $ret[] = $row;
1954 return $ret;
1955 }
1956
1957 function getObjectSearchResults ($what)
1958 {
1959 $ret = array();
1960 global $searchfunc;
1961 foreach ($searchfunc['object'] as $method => $func)
1962 foreach ($func ($what) as $objRecord)
1963 {
1964 $ret[$objRecord['id']]['id'] = $objRecord['id'];
1965 $ret[$objRecord['id']][$method] = $objRecord[$method];
1966 }
1967 return $ret;
1968 }
1969
1970 function getObjectAttrsSearchResults ($what)
1971 {
1972 $ret = array();
1973 foreach (array ('name', 'label', 'asset_no') as $column)
1974 {
1975 $tmp = getSearchResultByField
1976 (
1977 'RackObject',
1978 array ('id'),
1979 $column,
1980 $what,
1981 $column
1982 );
1983 foreach ($tmp as $row)
1984 {
1985 $ret[$row['id']]['id'] = $row['id'];
1986 $ret[$row['id']]['by_attr'][] = $column;
1987 }
1988 }
1989 return $ret;
1990 }
1991
1992 // Look for EXACT value in stickers and return a list of pairs "object_id-attribute_id",
1993 // which matched. A partilar object_id could be returned more, than once, if it has
1994 // multiple matching stickers. Search is only performed on "string" attributes.
1995 function getStickerSearchResults ($what, $exactness = 0)
1996 {
1997 $stickers = getSearchResultByField
1998 (
1999 'AttributeValue',
2000 array ('object_id', 'attr_id'),
2001 'string_value',
2002 $what,
2003 'object_id',
2004 $exactness
2005 );
2006 $map = getAttrMap();
2007 $ret = array();
2008 foreach ($stickers as $sticker)
2009 if ($map[$sticker['attr_id']]['type'] == 'string')
2010 {
2011 $ret[$sticker['object_id']]['id'] = $sticker['object_id'];
2012 $ret[$sticker['object_id']]['by_sticker'][] = $sticker['attr_id'];
2013 }
2014 return $ret;
2015 }
2016
2017 // search in port "reservation comment", "label" and "L2 address" columns
2018 function getPortSearchResults ($what)
2019 {
2020 $ret = array();
2021 $ports = getSearchResultByField
2022 (
2023 'Port',
2024 array ('object_id', 'id', 'reservation_comment'),
2025 'reservation_comment',
2026 $what,
2027 'object_id',
2028 0
2029 );
2030 foreach ($ports as $port)
2031 {
2032 $ret[$port['object_id']]['id'] = $port['object_id'];
2033 $ret[$port['object_id']]['by_port'][$port['id']] = $port['reservation_comment'];
2034 }
2035 $ports = getSearchResultByField
2036 (
2037 'Port',
2038 array ('object_id', 'id', 'label'),
2039 'label',
2040 $what,
2041 'object_id',
2042 0
2043 );
2044 foreach ($ports as $port)
2045 {
2046 $ret[$port['object_id']]['id'] = $port['object_id'];
2047 $ret[$port['object_id']]['by_port'][$port['id']] = $port['label'];
2048 }
2049 try
2050 {
2051 $db_l2address = l2addressForDatabase ($what);
2052 }
2053 catch (InvalidArgException $e)
2054 {
2055 return $ret;
2056 }
2057 $ports = getSearchResultByField
2058 (
2059 'Port',
2060 array ('object_id', 'id', 'l2address'),
2061 'l2address',
2062 $db_l2address,
2063 'object_id',
2064 2
2065 );
2066 foreach ($ports as $port)
2067 {
2068 $ret[$port['object_id']]['id'] = $port['object_id'];
2069 $ret[$port['object_id']]['by_port'][$port['id']] = $port['l2address'];
2070 }
2071 return $ret;
2072 }
2073
2074 // search in IPv4 allocations
2075 function getObjectIfacesSearchResults ($what)
2076 {
2077 $ret = array();
2078 $ifaces4 = getSearchResultByField
2079 (
2080 'IPv4Allocation',
2081 array ('object_id', 'name'),
2082 'name',
2083 $what,
2084 'object_id'
2085 );
2086 $ifaces6 = getSearchResultByField
2087 (
2088 'IPv6Allocation',
2089 array ('object_id', 'name'),
2090 'name',
2091 $what,
2092 'object_id'
2093 );
2094 foreach (array_merge ($ifaces4, $ifaces6) as $row)
2095 {
2096 $ret[$row['object_id']]['id'] = $row['object_id'];
2097 $ret[$row['object_id']]['by_iface'][] = $row['name'];
2098 }
2099 return $ret;
2100 }
2101
2102 function getObjectNATSearchResults ($what)
2103 {
2104 $ret = array();
2105 $ifaces = getSearchResultByField
2106 (
2107 'IPv4NAT',
2108 array ('object_id', 'description'),
2109 'description',
2110 $what,
2111 'object_id'
2112 );
2113 foreach ($ifaces as $row)
2114 {
2115 $ret[$row['object_id']]['id'] = $row['object_id'];
2116 $ret[$row['object_id']]['by_nat'][] = $row['description'];
2117 }
2118 return $ret;
2119 }
2120
2121 // This function returns either port ID or NULL for specified arguments.
2122 function getPortIDs ($object_id, $port_name)
2123 {
2124 $ret = array();
2125 $result = usePreparedSelectBlade ('SELECT id FROM Port WHERE object_id = ? AND name = ?', array ($object_id, $port_name));
2126 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2127 $ret[] = $row['id'];
2128 return $ret;
2129 }
2130
2131 // Search in "FQDN" attribute only, and return object ID, when there is exactly
2132 // one result found (and NULL in any other case).
2133 function searchByMgmtHostname ($string)
2134 {
2135 $result = usePreparedSelectBlade ('SELECT object_id FROM AttributeValue WHERE attr_id = 3 AND string_value = ? LIMIT 2', array ($string));
2136 $rows = $result->fetchAll (PDO::FETCH_NUM);
2137 if (count ($rows) == 1)
2138 return $rows[0][0];
2139 unset ($result);
2140
2141 // second attempt: search for FQDN part, separated by dot.
2142 $result = usePreparedSelectBlade ('SELECT object_id FROM AttributeValue WHERE attr_id = 3 AND string_value LIKE ? LIMIT 2', array ("$string.%"));
2143 $rows = $result->fetchAll (PDO::FETCH_NUM);
2144 if (count ($rows) != 1)
2145 return NULL;
2146 return $rows[0][0];
2147 }
2148
2149 function commitCreateUserAccount ($username, $realname, $password)
2150 {
2151 return usePreparedInsertBlade
2152 (
2153 'UserAccount',
2154 array
2155 (
2156 'user_name' => $username,
2157 'user_realname' => $realname,
2158 'user_password_hash' => $password,
2159 )
2160 );
2161 }
2162
2163 function commitUpdateUserAccount ($id, $new_username, $new_realname, $new_password)
2164 {
2165 return usePreparedUpdateBlade
2166 (
2167 'UserAccount',
2168 array
2169 (
2170 'user_name' => $new_username,
2171 'user_realname' => $new_realname,
2172 'user_password_hash' => $new_password,
2173 ),
2174 array ('user_id' => $id)
2175 );
2176 }
2177
2178 // This function returns an array of all port type pairs from PortCompat table.
2179 function getPortOIFCompat ()
2180 {
2181 $query =
2182 "select type1, type2, d1.dict_value as type1name, d2.dict_value as type2name from " .
2183 "PortCompat as pc inner join Dictionary as d1 on pc.type1 = d1.dict_key " .
2184 "inner join Dictionary as d2 on pc.type2 = d2.dict_key " .
2185 'ORDER BY type1name, type2name';
2186 $result = usePreparedSelectBlade ($query);
2187 return $result->fetchAll (PDO::FETCH_ASSOC);
2188 }
2189
2190 // Returns an array of all object type pairs from the ObjectParentCompat table.
2191 function getObjectParentCompat ()
2192 {
2193 $query =
2194 'SELECT parent_objtype_id, child_objtype_id, d1.dict_value AS parent_name, d2.dict_value AS child_name FROM ' .
2195 'ObjectParentCompat AS pc INNER JOIN Dictionary AS d1 ON pc.parent_objtype_id = d1.dict_key ' .
2196 'INNER JOIN Dictionary AS d2 ON pc.child_objtype_id = d2.dict_key ' .
2197 'ORDER BY parent_name, child_name';
2198 $result = usePreparedSelectBlade ($query);
2199 return $result->fetchAll (PDO::FETCH_ASSOC);
2200 }
2201
2202 // Used to determine if a type of object may have a parent or not
2203 function rackObjectTypeMayHaveParent ($objtype_id)
2204 {
2205 $result = usePreparedSelectBlade ('SELECT COUNT(*) FROM ObjectParentCompat WHERE child_objtype_id = ?', array ($objtype_id));
2206 $row = $result->fetch (PDO::FETCH_NUM);
2207 if ($row[0] > 0)
2208 return TRUE;
2209 return FALSE;
2210 }
2211
2212 // Add a pair to the ObjectParentCompat table.
2213 function commitSupplementOPC ($parent_objtype_id, $child_objtype_id)
2214 {
2215 if ($parent_objtype_id <= 0)
2216 throw new InvalidArgException ('parent_objtype_id', $parent_objtype_id);
2217 if ($child_objtype_id <= 0)
2218 throw new InvalidArgException ('child_objtype_id', $child_objtype_id);
2219 return usePreparedInsertBlade
2220 (
2221 'ObjectParentCompat',
2222 array ('parent_objtype_id' => $parent_objtype_id, 'child_objtype_id' => $child_objtype_id)
2223 );
2224 }
2225
2226 // Remove a pair from the ObjectParentCompat table.
2227 function commitReduceOPC ($parent_objtype_id, $child_objtype_id)
2228 {
2229 return usePreparedDeleteBlade ('ObjectParentCompat', array ('parent_objtype_id' => $parent_objtype_id, 'child_objtype_id' => $child_objtype_id));
2230 }
2231
2232 function getDictStats ()
2233 {
2234 $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);
2235 $result = usePreparedSelectBlade
2236 (
2237 "select Chapter.id as chapter_no, Chapter.name as chapter_name, count(dict_key) as wc from " .
2238 "Chapter left join Dictionary on Chapter.id = Dictionary.chapter_id group by Chapter.id"
2239 );
2240 $tc = $tw = $uc = $uw = 0;
2241 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2242 {
2243 $tc++;
2244 $tw += $row['wc'];;
2245 if (in_array ($row['chapter_no'], $stock_chapters))
2246 continue;
2247 $uc++;
2248 $uw += $row['wc'];;
2249 }
2250 unset ($result);
2251 $result = usePreparedSelectBlade
2252 (
2253 "select count(object_id) as attrc from RackObject as ro left join " .
2254 "AttributeValue as av on ro.id = av.object_id group by ro.id"
2255 );
2256 $to = $ta = $so = 0;
2257 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2258 {
2259 $to++;
2260 if ($row['attrc'] != 0)
2261 {
2262 $so++;
2263 $ta += $row['attrc'];
2264 }
2265 }
2266 unset ($result);
2267 $ret = array();
2268 $ret['Total chapters in dictionary'] = $tc;
2269 $ret['Total words in dictionary'] = $tw;
2270 $ret['User chapters'] = $uc;
2271 $ret['Words in user chapters'] = $uw;
2272 $ret['Total objects'] = $to;
2273 $ret['Objects with stickers'] = $so;
2274 $ret['Total stickers attached'] = $ta;
2275 return $ret;
2276 }
2277
2278 function getIPv4Stats ()
2279 {
2280 $ret = array();
2281 $subject = array();
2282 $subject[] = array ('q' => 'select count(id) from IPv4Network', 'txt' => 'Networks');
2283 $subject[] = array ('q' => 'select count(ip) from IPv4Address', 'txt' => 'Addresses commented/reserved');
2284 $subject[] = array ('q' => 'select count(ip) from IPv4Allocation', 'txt' => 'Addresses allocated');
2285 $subject[] = array ('q' => 'select count(*) from IPv4NAT', 'txt' => 'NAT rules');
2286 $subject[] = array ('q' => 'select count(id) from IPv4VS', 'txt' => 'Virtual services');
2287 $subject[] = array ('q' => 'select count(id) from IPv4RSPool', 'txt' => 'Real server pools');
2288 $subject[] = array ('q' => 'select count(id) from IPv4RS', 'txt' => 'Real servers');
2289 $subject[] = array ('q' => 'select count(distinct object_id) from IPv4LB', 'txt' => 'Load balancers');
2290
2291 foreach ($subject as $item)
2292 {
2293 $result = usePreparedSelectBlade ($item['q']);
2294 $row = $result->fetch (PDO::FETCH_NUM);
2295 $ret[$item['txt']] = $row[0];
2296 unset ($result);
2297 }
2298 return $ret;
2299 }
2300
2301 function getIPv6Stats ()
2302 {
2303 $ret = array();
2304 $subject = array();
2305 $subject[] = array ('q' => 'select count(id) from IPv6Network', 'txt' => 'Networks');
2306 $subject[] = array ('q' => 'select count(ip) from IPv6Address', 'txt' => 'Addresses commented/reserved');
2307 $subject[] = array ('q' => 'select count(ip) from IPv6Allocation', 'txt' => 'Addresses allocated');
2308
2309 foreach ($subject as $item)
2310 {
2311 $result = usePreparedSelectBlade ($item['q']);
2312 $row = $result->fetch (PDO::FETCH_NUM);
2313 $ret[$item['txt']] = $row[0];
2314 unset ($result);
2315 }
2316 return $ret;
2317 }
2318
2319 function getRackspaceStats ()
2320 {
2321 $ret = array();
2322 $subject = array();
2323 $subject[] = array ('q' => 'select count(*) from RackRow', 'txt' => 'Rack rows');
2324 $subject[] = array ('q' => 'select count(*) from Rack', 'txt' => 'Racks');
2325 $subject[] = array ('q' => 'select avg(height) from Rack', 'txt' => 'Average rack height');
2326 $subject[] = array ('q' => 'select sum(height) from Rack', 'txt' => 'Total rack units in field');
2327
2328 foreach ($subject as $item)
2329 {
2330 $result = usePreparedSelectBlade ($item['q']);
2331 $row = $result->fetch (PDO::FETCH_NUM);
2332 $ret[$item['txt']] = !strlen ($row[0]) ? 0 : $row[0];
2333 unset ($result);
2334 }
2335 return $ret;
2336 }
2337
2338 /*
2339
2340 The following allows figuring out records in TagStorage, which refer to non-existing entities:
2341
2342 mysql> select entity_id from TagStorage left join Files on entity_id = id where entity_realm = 'file' and id is null;
2343 mysql> select entity_id from TagStorage left join IPv4Network on entity_id = id where entity_realm = 'ipv4net' and id is null;
2344 mysql> select entity_id from TagStorage left join RackObject on entity_id = id where entity_realm = 'object' and id is null;
2345 mysql> select entity_id from TagStorage left join Rack on entity_id = id where entity_realm = 'rack' and id is null;
2346 mysql> select entity_id from TagStorage left join IPv4VS on entity_id = id where entity_realm = 'ipv4vs' and id is null;
2347 mysql> select entity_id from TagStorage left join IPv4RSPool on entity_id = id where entity_realm = 'ipv4rspool' and id is null;
2348 mysql> select entity_id from TagStorage left join UserAccount on entity_id = user_id where entity_realm = 'user' and user_id is null;
2349
2350 Accordingly, these are the records, which refer to non-existent tags:
2351
2352 mysql> select tag_id from TagStorage left join TagTree on tag_id = id where id is null;
2353
2354 */
2355
2356 function commitDeleteChapter ($chapter_no = 0)
2357 {
2358 return usePreparedDeleteBlade ('Chapter', array ('id' => $chapter_no, 'sticky' => 'no'));
2359 }
2360
2361 // This is a dictionary accessor. We perform link rendering, so the user sees
2362 // nice <select> drop-downs.
2363 function readChapter ($chapter_id = 0, $style = '')
2364 {
2365 $result = usePreparedSelectBlade
2366 (
2367 "select dict_key, dict_value as value from Dictionary " .
2368 "where chapter_id = ?",
2369 array ($chapter_id)
2370 );
2371 $chapter = array();
2372 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2373 {
2374 parseWikiLink ($row);
2375 $chapter[$row['dict_key']] = ($style == 'a' ? $row['a_value'] : $row['o_value']);
2376 }
2377 // SQL ORDER BY had no sense, because we need to sort after link rendering, not before.
2378 asort ($chapter);
2379 return $chapter;
2380 }
2381
2382 // Return refcounters for all given keys of the given chapter.
2383 function getChapterRefc ($chapter_id, $keylist)
2384 {
2385 $ret = array();
2386 foreach ($keylist as $key)
2387 $ret[$key] = 0;
2388 switch ($chapter_id)
2389 {
2390 case CHAP_OBJTYPE:
2391 // RackObjectType chapter is referenced by AttributeMap and RackObject tables
2392 $query = 'select dict_key as uint_value, (select count(*) from AttributeMap where objtype_id = dict_key) + ' .
2393 "(select count(*) from RackObject where objtype_id = dict_key) as refcnt from Dictionary where chapter_id = ?";
2394 break;
2395 case CHAP_PORTTYPE:
2396 // PortOuterInterface chapter is referenced by PortCompat, PortInterfaceCompat and Port tables
2397 $query = 'select dict_key as uint_value, (select count(*) from PortCompat where type1 = dict_key or type2 = dict_key) + ' .
2398 '(select count(*) from Port where type = dict_key) + (SELECT COUNT(*) FROM PortInterfaceCompat WHERE oif_id = dict_key) as refcnt ' .
2399 "from Dictionary where chapter_id = ?";
2400 break;
2401 default:
2402 // Find the list of all assigned values of dictionary-addressed attributes, each with
2403 // chapter/word keyed reference counters.
2404 $query = "select uint_value, count(object_id) as refcnt
2405 from AttributeMap am
2406 inner join AttributeValue av on am.attr_id = av.attr_id
2407 inner join RackObject ro on ro.id = av.object_id
2408 where am.chapter_id = ? and ro.objtype_id = am.objtype_id
2409 group by uint_value";
2410 break;
2411 }
2412 $result = usePreparedSelectBlade ($query, array ($chapter_id));
2413 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2414 $ret[$row['uint_value']] = $row['refcnt'];
2415 return $ret;
2416 }
2417
2418 // Return a list of all stickers with sticker map applied. Each sticker records will
2419 // list all its ways on the map with refcnt set.
2420 function getAttrMap ()
2421 {
2422 $result = usePreparedSelectBlade
2423 (
2424 'SELECT id, type, name, chapter_id, (SELECT dict_value FROM Dictionary WHERE dict_key = objtype_id) '.
2425 'AS objtype_name, (SELECT name FROM Chapter WHERE id = chapter_id) ' .
2426 'AS chapter_name, objtype_id, (SELECT COUNT(object_id) FROM AttributeValue AS av INNER JOIN RackObject AS ro ' .
2427 'ON av.object_id = ro.id WHERE av.attr_id = Attribute.id AND ro.objtype_id = AttributeMap.objtype_id) ' .
2428 'AS refcnt FROM Attribute LEFT JOIN AttributeMap ON id = attr_id ORDER BY Attribute.name, objtype_name'
2429 );
2430 $ret = array();
2431 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2432 {
2433 if (!isset ($ret[$row['id']]))
2434 $ret[$row['id']] = array
2435 (
2436 'id' => $row['id'],
2437 'type' => $row['type'],
2438 'name' => $row['name'],
2439 'application' => array(),
2440 );
2441 if ($row['objtype_id'] == '')
2442 continue;
2443 $application = array
2444 (
2445 'objtype_id' => $row['objtype_id'],
2446 'refcnt' => $row['refcnt'],
2447 );
2448 if ($row['type'] == 'dict')
2449 {
2450 $application['chapter_no'] = $row['chapter_id'];
2451 $application['chapter_name'] = $row['chapter_name'];
2452 }
2453 $ret[$row['id']]['application'][] = $application;
2454 }
2455 return $ret;
2456 }
2457
2458 // FIXME: don't store garbage in chapter_no for non-dictionary types.
2459 function commitSupplementAttrMap ($attr_id = 0, $objtype_id = 0, $chapter_no = 0)
2460 {
2461 if ($attr_id <= 0)
2462 throw new InvalidArgException ('$attr_id', $attr_id);
2463 if ($objtype_id <= 0)
2464 throw new InvalidArgException ('$objtype_id', $objtype_id);
2465
2466 return usePreparedInsertBlade
2467 (
2468 'AttributeMap',
2469 array
2470 (
2471 'attr_id' => $attr_id,
2472 'objtype_id' => $objtype_id,
2473 'chapter_id' => $chapter_no
2474 )
2475 );
2476 }
2477
2478 function cacheAllObjectsAttributes()
2479 {
2480 global $object_attribute_cache;
2481 $object_attribute_cache = fetchAttrsForObjects(NULL);
2482 }
2483
2484 // Fetches a list of attributes for each object in $object_set array.
2485 // If $object_set is not set, returns attributes for all objects in DB
2486 // Returns an array with object_id keys
2487 function fetchAttrsForObjects($object_set)
2488 {
2489 $ret = array();
2490 $query =
2491 "select A.id as attr_id, A.name as attr_name, A.type as attr_type, C.name as chapter_name, " .
2492 "C.id as chapter_id, AV.uint_value, AV.float_value, AV.string_value, D.dict_value, RO.id as object_id from " .
2493 "RackObject as RO inner join AttributeMap as AM on RO.objtype_id = AM.objtype_id " .
2494 "inner join Attribute as A on AM.attr_id = A.id " .
2495 "left join AttributeValue as AV on AV.attr_id = AM.attr_id and AV.object_id = RO.id " .
2496 "left join Dictionary as D on D.dict_key = AV.uint_value and AM.chapter_id = D.chapter_id " .
2497 "left join Chapter as C on AM.chapter_id = C.id";
2498 if (is_array ($object_set) && !empty ($object_set))
2499 {
2500 $query .= ' WHERE RO.id IN (';
2501 foreach ($object_set as $object_id)
2502 $query .= intval ($object_id) . ', ';
2503 $query = trim ($query, ', ') . ')';
2504 }
2505 $query .= " order by A.name, A.type";
2506
2507 $result = usePreparedSelectBlade ($query);
2508 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2509 {
2510 $object_id = $row['object_id'];
2511 $attr_id = $row['attr_id'];
2512 if (!array_key_exists ($object_id, $ret))
2513 $ret[$object_id] = array();
2514
2515 $record = array();
2516 $record['id'] = $row['attr_id'];
2517 $record['name'] = $row['attr_name'];
2518 $record['type'] = $row['attr_type'];
2519 switch ($row['attr_type'])
2520 {
2521 case 'dict':
2522 $record['chapter_id'] = $row['chapter_id'];
2523 $record['chapter_name'] = $row['chapter_name'];
2524 $record['key'] = $row['uint_value'];
2525 // fall through
2526 case 'uint':
2527 case 'float':
2528 case 'string':
2529 $record['value'] = $row[$row['attr_type'] . '_value'];
2530 parseWikiLink ($record);
2531 break;
2532 default:
2533 $record['value'] = NULL;
2534 break;
2535 }
2536 $ret[$object_id][$attr_id] = $record;
2537 }
2538 return $ret;
2539 }
2540
2541 // This function returns all optional attributes for requested object
2542 // as an array of records.
2543 // Empty array is returned, if there are no attributes found.
2544 function getAttrValues ($object_id)
2545 {
2546 global $object_attribute_cache;
2547 if (isset ($object_attribute_cache[$object_id]))
2548 return $object_attribute_cache[$object_id];
2549
2550 $ret = fetchAttrsForObjects(array($object_id));
2551 $attrs = array();
2552 if (isset ($ret[$object_id]))
2553 {
2554 $attrs = $ret[$object_id];
2555 $object_attribute_cache[$object_id] = $attrs;
2556 }
2557 return $attrs;
2558 }
2559
2560 function commitResetAttrValue ($object_id = 0, $attr_id = 0)
2561 {
2562 return usePreparedDeleteBlade ('AttributeValue', array ('object_id' => $object_id, 'attr_id' => $attr_id));
2563 }
2564
2565 function commitUpdateAttrValue ($object_id = 0, $attr_id = 0, $value = '')
2566 {
2567 if ($object_id <= 0)
2568 throw new InvalidArgException ('$objtype_id', $objtype_id);
2569 if ($attr_id <= 0)
2570 throw new InvalidArgException ('$attr_id', $attr_id);
2571 if (!strlen ($value))
2572 return commitResetAttrValue ($object_id, $attr_id);
2573 $result = usePreparedSelectBlade ('select type as attr_type from Attribute where id = ?', array ($attr_id));
2574 $row = $result->fetch (PDO::FETCH_NUM);
2575 $attr_type = $row[0];
2576 unset ($result);
2577 switch ($attr_type)
2578 {
2579 case 'uint':
2580 case 'float':
2581 case 'string':
2582 $column = $attr_type . '_value';
2583 break;
2584 case 'dict':
2585 $column = 'uint_value';
2586 break;
2587 default:
2588 throw new InvalidArgException ('$attr_type', $attr_type, 'Unknown attribute type found in object #'.$object_id.', attribute #'.$attr_id);
2589 }
2590 usePreparedDeleteBlade ('AttributeValue', array ('object_id' => $object_id, 'attr_id' => $attr_id));
2591 // We know $value isn't empty here.
2592 usePreparedInsertBlade
2593 (
2594 'AttributeValue',
2595 array
2596 (
2597 $column => $value,
2598 'object_id' => $object_id,
2599 'attr_id' => $attr_id,
2600 )
2601 );
2602 return TRUE;
2603 }
2604
2605 function convertPDOException ($e)
2606 {
2607 switch ($e->getCode() . '-' . $e->errorInfo[1])
2608 {
2609 case '23000-1062':
2610 $text = 'such record already exists';
2611 break;
2612 case '23000-1205':
2613 $text = 'such record already exists';
2614 break;
2615 case '23000-1451':
2616 case '23000-1452':
2617 $text = 'foreign key violation';
2618 break;
2619 case 'HY000-1205':
2620 $text = 'lock wait timeout';
2621 break;
2622 default:
2623 return $e;
2624 }
2625 return new RTDatabaseError ($text);
2626 }
2627
2628 // This is a swiss-knife blade to insert a record into a table.
2629 // The first argument is table name.
2630 // The second argument is an array of "name" => "value" pairs.
2631 function usePreparedInsertBlade ($tablename, $columns)
2632 {
2633 global $dbxlink;
2634 $query = "INSERT INTO ${tablename} (" . implode (', ', array_keys ($columns));
2635 $query .= ') VALUES (' . questionMarks (count ($columns)) . ')';
2636 // Now the query should be as follows:
2637 // INSERT INTO table (c1, c2, c3) VALUES (?, ?, ?)
2638 try
2639 {
2640 $prepared = $dbxlink->prepare ($query);
2641 if (!$prepared->execute (array_values ($columns)))
2642 return FALSE;
2643 return $prepared->rowCount() == 1;
2644 }
2645 catch (PDOException $e)
2646 {
2647 throw convertPDOException ($e);
2648 }
2649 }
2650
2651 // This swiss-knife blade deletes any number of records from the specified table
2652 // using the specified key names and values.
2653 function usePreparedDeleteBlade ($tablename, $columns, $conjunction = 'AND')
2654 {
2655 global $dbxlink;
2656 $conj = '';
2657 $query = "DELETE FROM ${tablename} WHERE ";
2658 foreach ($columns as $colname => $colvalue)
2659 {
2660 $query .= " ${conj} ${colname}=?";
2661 $conj = $conjunction;
2662 }
2663 try
2664 {
2665 $prepared = $dbxlink->prepare ($query);
2666 if (!$prepared->execute (array_values ($columns)))
2667 return FALSE;
2668 return $prepared->rowCount(); // FALSE !== 0
2669 }
2670 catch (PDOException $e)
2671 {
2672 throw convertPDOException ($e);
2673 }
2674 }
2675
2676 function usePreparedSelectBlade ($query, $args = array())
2677 {
2678 global $dbxlink;
2679 $prepared = $dbxlink->prepare ($query);
2680 try
2681 {
2682 if (!$prepared->execute ($args))
2683 return FALSE;
2684 return $prepared;
2685 }
2686 catch (PDOException $e)
2687 {
2688 throw convertPDOException ($e);
2689 }
2690 }
2691
2692 function usePreparedUpdateBlade ($tablename, $set_columns, $where_columns, $conjunction = 'AND')
2693 {
2694 global $dbxlink;
2695 $conj = '';
2696 $query = "UPDATE ${tablename} SET ";
2697 foreach (array_keys ($set_columns) as $colname)
2698 {
2699 $query .= "${conj}${colname}=?";
2700 $conj = ', ';
2701 }
2702 $conj = '';
2703 $query .= ' WHERE ';
2704 foreach (array_keys ($where_columns) as $colname)
2705 {
2706 $query .= " ${conj} ${colname}=?";
2707 $conj = $conjunction;
2708 }
2709 try
2710 {
2711 $prepared = $dbxlink->prepare ($query);
2712 if (! $prepared->execute (array_merge (array_values ($set_columns), array_values ($where_columns))))
2713 return FALSE;
2714 return $prepared->rowCount();
2715 }
2716 catch (PDOException $e)
2717 {
2718 throw convertPDOException ($e);
2719 }
2720 }
2721
2722 // Prepare and execute the statement with parameters, then return number of
2723 // rows affected (or FALSE in case of an error).
2724 function usePreparedExecuteBlade ($query, $args = array())
2725 {
2726 global $dbxlink;
2727 try
2728 {
2729 if (!$prepared = $dbxlink->prepare ($query))
2730 return FALSE;
2731 if (!$prepared->execute ($args))
2732 return FALSE;
2733 return $prepared->rowCount();
2734 }
2735 catch (PDOException $e)
2736 {
2737 throw convertPDOException ($e);
2738 }
2739 }
2740
2741 function loadConfigCache ()
2742 {
2743 $result = usePreparedSelectBlade ('SELECT varname, varvalue, vartype, is_hidden, emptyok, description, is_userdefined FROM Config ORDER BY varname');
2744 $cache = array();
2745 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2746 $cache[$row['varname']] = $row;
2747 return $cache;
2748 }
2749
2750 function loadUserConfigCache ($username = NULL)
2751 {
2752 if (!strlen ($username))
2753 throw new InvalidArgException ('$username', $username);
2754 $result = usePreparedSelectBlade ('SELECT varname, varvalue FROM UserConfig WHERE user = ?', array ($username));
2755 $cache = array();
2756 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2757 $cache[$row['varname']] = $row;
2758 return $cache;
2759 }
2760
2761 // Return an array of virtual services. For each of them list real server pools
2762 // with their load balancers and other stats.
2763 function getSLBSummary ()
2764 {
2765 $result = usePreparedSelectBlade
2766 (
2767 'select vs.id as vsid, inet_ntoa(vip) as vip, vport, proto, vs.name, object_id, ' .
2768 'lb.rspool_id, pool.name as pool_name, count(rs.id) as rscount ' .
2769 'from IPv4VS as vs inner join IPv4LB as lb on vs.id = lb.vs_id ' .
2770 'inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2771 'left join IPv4RS as rs on rs.rspool_id = lb.rspool_id ' .
2772 'group by vs.id, object_id order by vs.vip, object_id'
2773 );
2774 $ret = array();
2775 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2776 {
2777 $vsid = $row['vsid'];
2778 $object_id = $row['object_id'];
2779 if (!isset ($ret[$vsid]))
2780 {
2781 $ret[$vsid] = array();
2782 foreach (array ('vip', 'vport', 'proto', 'name') as $cname)
2783 $ret[$vsid][$cname] = $row[$cname];
2784 $ret[$vsid]['lblist'] = array();
2785 }
2786 // There's only one assigned RS pool possible for each LB-VS combination.
2787 $ret[$vsid]['lblist'][$row['object_id']] = array
2788 (
2789 'id' => $row['rspool_id'],
2790 'size' => $row['rscount'],
2791 'name' => $row['pool_name']
2792 );
2793 }
2794 return $ret;
2795 }
2796
2797 function addRStoRSPool ($pool_id = 0, $rsip = '', $rsport = 0, $inservice = 'no', $rsconfig = '')
2798 {
2799 return usePreparedExecuteBlade
2800 (
2801 'INSERT INTO IPv4RS (rsip, rsport, rspool_id, inservice, rsconfig) VALUES (INET_ATON(?), ?, ?, ?, ?)',
2802 array
2803 (
2804 $rsip,
2805 (!strlen ($rsport) or $rsport === 0) ? NULL : $rsport,
2806 $pool_id,
2807 $inservice == 'yes' ? 'yes' : 'no',
2808 !strlen ($rsconfig) ? NULL : $rsconfig
2809 )
2810 );
2811 }
2812
2813 function addLBtoRSPool ($pool_id = 0, $object_id = 0, $vs_id = 0, $vsconfig = '', $rsconfig = '', $prio = '')
2814 {
2815 return usePreparedInsertBlade
2816 (
2817 'IPv4LB',
2818 array
2819 (
2820 'object_id' => $object_id,
2821 'rspool_id' => $pool_id,
2822 'vs_id' => $vs_id,
2823 'vsconfig' => (!strlen ($vsconfig) ? NULL : $vsconfig),
2824 'rsconfig' => (!strlen ($rsconfig) ? NULL : $rsconfig),
2825 'prio' => (!strlen ($prio) ? NULL : $prio),
2826 )
2827 );
2828 }
2829
2830 function commitDeleteVS ($id = 0)
2831 {
2832 releaseFiles ('ipv4vs', $id);
2833 return FALSE !== usePreparedDeleteBlade ('IPv4VS', array ('id' => $id)) && FALSE !== destroyTagsForEntity ('ipv4vs', $id);
2834 }
2835
2836 function commitUpdateRS ($rsid = 0, $rsip = '', $rsport = 0, $rsconfig = '')
2837 {
2838 if (long2ip (ip2long ($rsip)) !== $rsip)
2839 throw new InvalidArgException ('$rsip', $rsip);
2840 return usePreparedExecuteBlade
2841 (
2842 'UPDATE IPv4RS SET rsip=INET_ATON(?), rsport=?, rsconfig=? WHERE id=?',
2843 array
2844 (
2845 $rsip,
2846 (!strlen ($rsport) or $rsport === 0) ? NULL : $rsport,
2847 !strlen ($rsconfig) ? NULL : $rsconfig,
2848 $rsid,
2849 )
2850 );
2851 }
2852
2853 function commitUpdateVS ($vsid = 0, $vip = '', $vport = 0, $proto = '', $name = '', $vsconfig = '', $rsconfig = '')
2854 {
2855 if (!strlen ($vip))
2856 throw new InvalidArgException ('$vip', $vip);
2857 if ($vport <= 0)
2858 throw new InvalidArgException ('$vport', $vport);
2859 if (!strlen ($proto))
2860 throw new InvalidArgException ('$proto', $proto);
2861 return usePreparedExecuteBlade
2862 (
2863 'UPDATE IPv4VS SET vip=INET_ATON(?), vport=?, proto=?, name=?, vsconfig=?, rsconfig=? WHERE id=?',
2864 array
2865 (
2866 $vip,
2867 $vport,
2868 $proto,
2869 !strlen ($name) ? NULL : $name,
2870 !strlen ($vsconfig) ? NULL : $vsconfig,
2871 !strlen ($rsconfig) ? NULL : $rsconfig,
2872 $vsid,
2873 )
2874 );
2875 }
2876
2877 function loadThumbCache ($rack_id = 0)
2878 {
2879 $ret = NULL;
2880 $result = usePreparedSelectBlade ("SELECT thumb_data FROM Rack WHERE id = ? AND thumb_data IS NOT NULL", array ($rack_id));
2881 $row = $result->fetch (PDO::FETCH_ASSOC);
2882 if ($row)
2883 $ret = base64_decode ($row['thumb_data']);
2884 return $ret;
2885 }
2886
2887 // Return the list of attached RS pools for the given object. As long as we have
2888 // the LB-VS UNIQUE in IPv4LB table, it is Ok to key returned records
2889 // by vs_id, because there will be only one RS pool listed for each VS of the
2890 // current object.
2891 function getRSPoolsForObject ($object_id = 0)
2892 {
2893 $result = usePreparedSelectBlade
2894 (
2895 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name, pool.id as pool_id, ' .
2896 'pool.name as pool_name, count(rsip) as rscount, lb.vsconfig, lb.rsconfig, lb.prio from ' .
2897 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2898 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2899 'left join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
2900 'where lb.object_id = ? ' .
2901 'group by lb.rspool_id, lb.vs_id order by vs.vip, vport, proto, pool.name',
2902 array ($object_id)
2903 );
2904 $ret = array ();
2905 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2906 foreach (array ('vip', 'vport', 'proto', 'name', 'pool_id', 'pool_name', 'rscount', 'vsconfig', 'rsconfig', 'prio') as $cname)
2907 $ret[$row['vs_id']][$cname] = $row[$cname];
2908 return $ret;
2909 }
2910
2911 function commitCreateRSPool ($name = '', $vsconfig = '', $rsconfig = '', $taglist = array())
2912 {
2913 usePreparedInsertBlade
2914 (
2915 'IPv4RSPool',
2916 array
2917 (
2918 'name' => (!strlen ($name) ? NULL : $name),
2919 'vsconfig' => (!strlen ($vsconfig) ? NULL : $vsconfig),
2920 'rsconfig' => (!strlen ($rsconfig) ? NULL : $rsconfig)
2921 )
2922 );
2923 produceTagsForLastRecord ('ipv4rspool', $taglist);
2924 }
2925
2926 function commitDeleteRSPool ($pool_id = 0)
2927 {
2928 releaseFiles ('ipv4rspool', $pool_id);
2929 return usePreparedDeleteBlade ('IPv4RSPool', array ('id' => $pool_id)) && destroyTagsForEntity ('ipv4rspool', $pool_id);
2930 }
2931
2932 function getRSList ()
2933 {
2934 $result = usePreparedSelectBlade
2935 (
2936 "select id, inservice, inet_ntoa(rsip) as rsip, rsport, rspool_id, rsconfig " .
2937 "from IPv4RS order by rspool_id, IPv4RS.rsip, rsport"
2938 );
2939 $ret = array ();
2940 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2941 foreach (array ('inservice', 'rsip', 'rsport', 'rspool_id', 'rsconfig') as $cname)
2942 $ret[$row['id']][$cname] = $row[$cname];
2943 return $ret;
2944 }
2945
2946 // Return the list of all currently configured load balancers with their pool count.
2947 function getLBList ()
2948 {
2949 $result = usePreparedSelectBlade
2950 (
2951 "select object_id, count(rspool_id) as poolcount " .
2952 "from IPv4LB group by object_id order by object_id"
2953 );
2954 $ret = array ();
2955 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2956 $ret[$row['object_id']] = $row['poolcount'];
2957 return $ret;
2958 }
2959
2960 // For the given object return: its vsconfig/rsconfig; the list of RS pools
2961 // attached (each with vsconfig/rsconfig in turn), each with the list of
2962 // virtual services terminating the pool. Each pool also lists all real
2963 // servers with rsconfig.
2964 function getSLBConfig ($object_id)
2965 {
2966 $ret = array();
2967 $result = usePreparedSelectBlade
2968 (
2969 'select vs_id, inet_ntoa(vip) as vip, vport, proto, vs.name as vs_name, ' .
2970 'vs.vsconfig as vs_vsconfig, vs.rsconfig as vs_rsconfig, ' .
2971 'lb.vsconfig as lb_vsconfig, lb.rsconfig as lb_rsconfig, lb.prio as prio, pool.id as pool_id, pool.name as pool_name, ' .
2972 'pool.vsconfig as pool_vsconfig, pool.rsconfig as pool_rsconfig, ' .
2973 'rs.id as rs_id, inet_ntoa(rsip) as rsip, rsport, rs.rsconfig as rs_rsconfig from ' .
2974 'IPv4LB as lb inner join IPv4RSPool as pool on lb.rspool_id = pool.id ' .
2975 'inner join IPv4VS as vs on lb.vs_id = vs.id ' .
2976 'inner join IPv4RS as rs on lb.rspool_id = rs.rspool_id ' .
2977 "where lb.object_id = ? and rs.inservice = 'yes' " .
2978 "order by vs.vip, vport, proto, pool.name, rs.rsip, rs.rsport",
2979 array ($object_id)
2980 );
2981 while ($row = $result->fetch (PDO::FETCH_ASSOC))
2982 {
2983 $vs_id = $row['vs_id'];
2984 if (!isset ($ret[$vs_id]))
2985 {
2986 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)
2987 $ret[$vs_id][$c] = $row[$c];
2988 $ret[$vs_id]['rslist'] = array();
2989 }
2990 foreach (array ('rsip', 'rsport', 'rs_rsconfig') as $c)
2991 $ret[$vs_id]['rslist'][$row['rs_id']][$c] = $row[$c];
2992 }
2993 return $ret;
2994 }
2995
2996 function commitUpdateSLBDefConf ($data)
2997 {
2998 return saveScript('DefaultVSConfig', $data['vs']) &&
2999 saveScript('DefaultRSConfig', $data['rs']);
3000 }
3001
3002 function getSLBDefaults ($do_cache_result = FALSE) {
3003 static $ret = array();
3004
3005 if (! $do_cache_result)
3006 $ret = array();
3007 elseif (! empty ($ret))
3008 return $ret;
3009
3010 $ret['vs'] = loadScript('DefaultVSConfig');
3011 $ret['rs'] = loadScript('DefaultRSConfig');
3012 return $ret;
3013 }
3014
3015 function commitSetInService ($rs_id = 0, $inservice = '')
3016 {
3017 if (! in_array ($inservice, array ('yes', 'no')))
3018 throw new InvalidArgException ('$inservice', $inservice);
3019 return usePreparedUpdateBlade ('IPv4RS', array ('inservice' => $inservice), array ('id' => $rs_id));
3020 }
3021
3022 function executeAutoPorts ($object_id = 0, $type_id = 0)
3023 {
3024 if ($object_id == 0)
3025 throw new InvalidArgException ('$object_id', $object_id);
3026 if ($type_id == 0)
3027 throw new InvalidArgException ('$type_id', $type_id);
3028 foreach (getAutoPorts ($type_id) as $autoport)
3029 commitAddPort ($object_id, $autoport['name'], $autoport['type'], '', '');
3030 }
3031
3032 // Return only implicitly listed tags, the rest of the chain will be
3033 // generated/deducted later at higher levels.
3034 // Result is a chain: randomly indexed taginfo list.
3035 function loadEntityTags ($entity_realm = '', $entity_id = 0)
3036 {
3037 $ret = array();
3038 $result = usePreparedSelectBlade
3039 (
3040 "select tt.id, tag from " .
3041 "TagStorage as ts inner join TagTree as tt on ts.tag_id = tt.id " .
3042 "where entity_realm = ? and entity_id = ? " .
3043 "order by tt.tag",
3044 array ($entity_realm, $entity_id)
3045 );
3046 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3047 $ret[$row['id']] = $row;
3048 return getExplicitTagsOnly ($ret);
3049 }
3050
3051 # Universal autotags generator, a complementing function for loadEntityTags().
3052 # Bypass key isn't strictly typed, but interpreted depending on the realm.
3053 function generateEntityAutoTags ($cell)
3054 {
3055 $ret = array();
3056 if (! array_key_exists ('realm', $cell))
3057 throw new InvalidArgException ('cell', '(array)', 'malformed structure');
3058 switch ($cell['realm'])
3059 {
3060 case 'rack':
3061 $ret[] = array ('tag' => '$rackid_' . $cell['id']);
3062 $ret[] = array ('tag' => '$any_rack');
3063 break;
3064 case 'object':
3065 $ret[] = array ('tag' => '$id_' . $cell['id']);
3066 $ret[] = array ('tag' => '$typeid_' . $cell['objtype_id']);
3067 $ret[] = array ('tag' => '$any_object');
3068 if (validTagName ('$cn_' . $cell['name'], TRUE))
3069 $ret[] = array ('tag' => '$cn_' . $cell['name']);
3070 if (!strlen ($cell['rack_id']))
3071 $ret[] = array ('tag' => '$unmounted');
3072 if (!$cell['nports'])
3073 $ret[] = array ('tag' => '$portless');
3074 if ($cell['asset_no'] == '')
3075 $ret[] = array ('tag' => '$no_asset_tag');
3076 if ($cell['runs8021Q'])
3077 $ret[] = array ('tag' => '$runs_8021Q');
3078
3079 # dictionary attribute autotags '$attr_X_Y'
3080 $attrs = getAttrValues($cell['id']);
3081 foreach ($attrs as $attr_id => $attr_record)
3082 if (isset ($attr_record['key']))
3083 $ret[] = array ('tag' => "\$attr_{$attr_id}_{$attr_record['key']}");
3084 break;
3085 case 'ipv4net':
3086 $ret[] = array ('tag' => '$ip4netid_' . $cell['id']);
3087 $ret[] = array ('tag' => '$ip4net-' . str_replace ('.', '-', $cell['ip']) . '-' . $cell['mask']);
3088 for ($i = 8; $i < 32; $i++)
3089 {
3090 # these conditions hit 1 to 3 times per each i
3091 if ($cell['mask'] >= $i)
3092 $ret[] = array ('tag' => '$masklen_ge_' . $i);
3093 if ($cell['mask'] <= $i)
3094 $ret[] = array ('tag' => '$masklen_le_' . $i);
3095 if ($cell['mask'] == $i)
3096 $ret[] = array ('tag' => '$masklen_eq_' . $i);
3097 }
3098 $ret[] = array ('tag' => '$any_ip4net');
3099 $ret[] = array ('tag' => '$any_net');
3100 break;
3101 case 'ipv6net':
3102 $ret[] = array ('tag' => '$ip6netid_' . $cell['id']);
3103 $ret[] = array ('tag' => '$any_ip6net');
3104 $ret[] = array ('tag' => '$any_net');
3105 break;
3106 case 'ipv4vs':
3107 $ret[] = array ('tag' => '$ipv4vsid_' . $cell['id']);
3108 $ret[] = array ('tag' => '$any_ipv4vs');
3109 $ret[] = array ('tag' => '$any_vs');
3110 break;
3111 case 'ipv4rspool':
3112 $ret[] = array ('tag' => '$ipv4rspid_' . $cell['id']);
3113 $ret[] = array ('tag' => '$any_ipv4rsp');
3114 $ret[] = array ('tag' => '$any_rsp');
3115 break;
3116 case 'user':
3117 # {$username_XXX} autotag is generated always, but {$userid_XXX}
3118 # appears only for accounts, which exist in local database.
3119 $ret[] = array ('tag' => '$username_' . $cell['user_name']);
3120 if (isset ($cell['user_id']))
3121 $ret[] = array ('tag' => '$userid_' . $cell['user_id']);
3122 break;
3123 case 'file':
3124 $ret[] = array ('tag' => '$fileid_' . $cell['id']);
3125 $ret[] = array ('tag' => '$any_file');
3126 break;
3127 default:
3128 throw new InvalidArgException ('cell', '(array)', 'this input does not belong here');
3129 break;
3130 }
3131 # {$tagless} doesn't apply to users
3132 switch ($cell['realm'])
3133 {
3134 case 'rack':
3135 case 'object':
3136 case 'ipv4net':
3137 case 'ipv6net':
3138 case 'ipv4vs':
3139 case 'ipv4rspool':
3140 case 'file':
3141 if (!count ($cell['etags']))
3142 $ret[] = array ('tag' => '$untagged');
3143 break;
3144 default:
3145 break;
3146 }
3147 return $ret;
3148 }
3149
3150 // Return a tag chain with all DB tags on it.
3151 function getTagList ()
3152 {
3153 $ret = array();
3154 $result = usePreparedSelectBlade
3155 (
3156 "select id, parent_id, tag, entity_realm as realm, count(entity_id) as refcnt " .
3157 "from TagTree left join TagStorage on id = tag_id " .
3158 "group by id, entity_realm order by tag"
3159 );
3160 // Collation index. The resulting rows are ordered according to default collation,
3161 // which is utf8_general_ci for UTF-8.
3162 $ci = 0;
3163 while ($row = $result->fetch (PDO::FETCH_ASSOC))
3164 {
3165 if (!isset ($ret[$row['id']]))
3166 $ret[$row['id']] = array
3167 (
3168 'id' => $row['id'],
3169 'tag' => $row['tag'],
3170 'ci' => $ci++,
3171 'parent_id' => $row['parent_id'],
3172 'refcnt' => array ('total' => 0)
3173 );
3174 if ($row['realm'])
3175 {
3176 $ret[$row['id']]['refcnt'][$row['realm']] = $row['refcnt'];
3177 $ret[$row['id']]['refcnt']['total'] += $row['refcnt'];
3178 // introduce the 'pseudo'-ream 'ipnet' which combines 'ipv4net' and 'ipv6net' realms.
3179 if ($row['realm'] == 'ipv4net' || $row['realm'] == 'ipv6net')
3180 if (isset ($ret[$row['id']]['refcnt']['ipnet']))
3181 $ret[$row['id']]['refcnt']['ipnet'] += $row['refcnt'];
3182 else
3183 $ret[$row['id']]['refcnt']['ipnet'] = $row['refcnt'];
3184 }
3185 }
3186 return $ret;
3187 }
3188
3189 // Drop the whole chain stored.
3190 function destroyTagsForEntity ($entity_realm, $entity_id)
3191 {
3192 return usePreparedDeleteBlade ('TagStorage', array ('entity_realm' => $entity_realm, 'entity_id' => $entity_id));
3193 }
3194
3195 // Drop only one record. This operation doesn't involve retossing other tags, unlike when adding.
3196 // FIXME: this function could be used by 3rd-party scripts, dismiss it at some later point,
3197 // but not now.
3198 function deleteTagForEntity ($entity_realm, $entity_id, $tag_id)
3199 {
3200 return usePreparedDeleteBlade ('TagStorage', array ('entity_realm' => $entity_realm, 'entity_id' => $entity_id, 'tag_id' => $tag_id));
3201 }
3202
3203 // Push a record into TagStorage unconditionally.
3204 function addTagForEntity ($realm, $entity_id, $tag_id)
3205 {
3206 global $SQLSchema;
3207 if (! array_key_exists ($realm, $SQLSchema))
3208 throw new InvalidArgException ('realm', $realm);
3209 // spotEntity ($realm, $entity_id) would be a more expensive way
3210 // to validate two parameters
3211 return usePreparedInsertBlade
3212 (
3213 'TagStorage',
3214 array
3215 (
3216 'entity_realm' => $realm,
3217 'entity_id' => $entity_id,
3218 'tag_id' => $tag_id,
3219 )
3220 );
3221 }
3222
3223 // Add records into TagStorage, if this makes sense (IOW, they don't appear
3224 // on the implicit list already). Then remove any other records, which
3225 // appear on the "implicit" side of the chain. This will make sure,
3226 // that both the tag base is still minimal and all requested tags appear on
3227 // the resulting tag chain.
3228 // Return TRUE, if any changes were committed.
3229 function rebuildTagChainForEntity ($realm, $entity_id, $extrachain = array())
3230 {
3231 // Put the current explicit sub-chain into a buffer and merge all tags from
3232 // the extra chain, which aren't there yet.
3233 $newchain = $oldchain = loadEntityTags ($realm, $entity_id);
3234 foreach ($extrachain as $extratag)
3235 if (!tagOnChain ($extratag, $newchain))
3236 $newchain[] = $extratag;
3237 // Then minimize the working buffer and check if it differs from the original
3238 // chain we started with. If it is so, save the work and signal the upper layer.
3239 $newchain = getExplicitTagsOnly ($newchain);
3240 if (tagChainCmp ($oldchain, $newchain))
3241 {
3242 destroyTagsForEntity ($realm, $entity_id);
3243 foreach ($newchain as $taginfo)
3244 addTagForEntity ($realm, $entity_id, $taginfo['id']);
3245 return TRUE;
3246 }
3247 return FALSE;
3248 }
3249
3250 // Presume, that the target record has no tags attached.
3251 function produceTagsForLastRecord ($realm, $tagidlist, $last_insert_id = 0)
3252 {
3253 if (!$last_insert_id)
3254 $last_insert_id = lastInsertID();
3255 foreach (getExplicitTagsOnly (buildTagChainFromIds ($tagidlist)) as $taginfo)
3256 addTagForEntity ($realm, $last_insert_id, $taginfo['id']);
3257 }
3258
3259 function createIPv4Prefix ($range = '', $name = '', $is_bcast = FALSE, $taglist = array())
3260 {
3261 // $range is in x.x.x.x/x format, split into ip/mask vars
3262 $rangeArray = explode('/', $range);
3263 if (count ($rangeArray) != 2)
3264 throw new InvalidRequestArgException ('range', $range, 'Invalid IPv4 prefix');
3265 $ip = $rangeArray[0];
3266 $mask = $rangeArray[1];
3267
3268 if (!strlen ($ip) or !strlen ($mask))
3269 throw new InvalidRequestArgException ('range', $range, 'Invalid IPv4 prefix');
3270 $ipL = ip2long($ip);
3271 $maskL = ip2long($mask);
3272 if ($ipL == -1 || $ipL === FALSE)
3273 throw new InvalidRequestArgException ('range', $range, 'Invalid IPv4 address');
3274 if ($mask < 32 && $mask > 0)
3275 $maskL = $mask;
3276 else
3277 {
3278 $maskB = decbin($maskL);
3279 if (strlen($maskB)!=32)
3280 throw new InvalidRequestArgException ('range', $range, 'Invalid netmask');
3281 $ones=0;
3282