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