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