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