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