/
database.php
6217 lines (5811 loc) · 185 KB
/
database.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
# This file is a part of RackTables, a datacenter and server room management
# framework. See accompanying file "COPYING" for the full copyright and
# licensing information.
/*
*
* This file is a library of database access functions for RackTables.
*
*/
$SQLSchema = array
(
'object' => array
(
'table' => 'RackObject',
'columns' => array
(
'id' => 'id',
'name' => 'name',
'label' => 'label',
'asset_no' => 'asset_no',
'objtype_id' => 'objtype_id',
'rack_id' => '(SELECT MIN(rack_id) FROM RackSpace WHERE object_id = RackObject.id)',
'rack_id_2' => "(SELECT MIN(parent_entity_id) FROM EntityLink WHERE child_entity_type='object' AND child_entity_id = RackObject.id AND parent_entity_type = 'rack')",
'container_id' => "(SELECT MIN(parent_entity_id) FROM EntityLink WHERE child_entity_type='object' AND child_entity_id = RackObject.id AND parent_entity_type = 'object')",
'container_name' => '(SELECT name FROM RackObject WHERE id = container_id)',
'container_objtype_id' => '(SELECT objtype_id FROM RackObject WHERE id = container_id)',
'has_problems' => 'has_problems',
'comment' => 'comment',
'nports' => '(SELECT COUNT(*) FROM Port WHERE object_id = RackObject.id)',
'8021q_domain_id' => '(SELECT domain_id FROM VLANSwitch WHERE object_id = id LIMIT 1)',
'8021q_template_id' => '(SELECT template_id FROM VLANSwitch WHERE object_id = id LIMIT 1)',
),
'keycolumn' => 'id',
'ordcolumns' => array ('RackObject.name'),
),
'user' => array
(
'table' => 'UserAccount',
'columns' => array
(
'user_id' => 'user_id',
'user_name' => 'user_name',
'user_password_hash' => 'user_password_hash',
'user_realname' => 'user_realname',
),
'keycolumn' => 'user_id',
'ordcolumns' => array ('UserAccount.user_name'),
),
'ipv4net' => array
(
'table' => 'IPv4Network',
'columns' => array
(
'id' => 'id',
'ip_bin' => 'ip',
'mask' => 'mask',
'name' => 'name',
'comment' => 'comment',
'8021q' => '(SELECT GROUP_CONCAT(CONCAT(domain_id, "-", vlan_id) ORDER BY domain_id, vlan_id) FROM VLANIPv4 WHERE ipv4net_id = id)',
),
'keycolumn' => 'id',
'ordcolumns' => array ('IPv4Network.ip', 'IPv4Network.mask'),
),
'ipv6net' => array
(
'table' => 'IPv6Network',
'columns' => array
(
'id' => 'id',
'ip_bin' => 'ip',
'mask' => 'mask',
'name' => 'name',
'comment' => 'comment',
'8021q' => '(SELECT GROUP_CONCAT(CONCAT(domain_id, "-", vlan_id) ORDER BY domain_id, vlan_id) FROM VLANIPv6 WHERE ipv6net_id = id)',
),
'keycolumn' => 'id',
'ordcolumns' => array ('IPv6Network.ip', 'IPv6Network.mask'),
),
'file' => array
(
'table' => 'File',
'columns' => array
(
'id' => 'id',
'name' => 'name',
'type' => 'type',
'size' => 'size',
'ctime' => 'ctime',
'mtime' => 'mtime',
'atime' => 'atime',
'comment' => 'comment',
),
'keycolumn' => 'id',
'ordcolumns' => array ('File.name'),
),
'ipv4vs' => array
(
'table' => 'IPv4VS',
'columns' => array
(
'id' => 'id',
'vip_bin' => 'vip',
'vport' => 'vport',
'proto' => 'proto',
'name' => 'name',
'vsconfig' => 'vsconfig',
'rsconfig' => 'rsconfig',
'refcnt' => '(select count(vs_id) from IPv4LB where vs_id = id)',
//'vip' =>
//'dname' =>
),
'keycolumn' => 'id',
'ordcolumns' => array ('IPv4VS.vip', 'IPv4VS.proto', 'IPv4VS.vport'),
),
'ipvs' => array
(
'table' => 'VS',
'columns' => array
(
'id' => 'id',
'name' => 'name',
'vsconfig' => 'vsconfig',
'rsconfig' => 'rsconfig',
),
'keycolumn' => 'id',
),
'ipv4rspool' => array
(
'table' => 'IPv4RSPool',
'columns' => array
(
'id' => 'id',
'name' => 'name',
'refcnt' => '(select count(rspool_id) from IPv4LB where rspool_id = id)',
'rscount' => '(select count(rspool_id) from IPv4RS where rspool_id = IPv4RSPool.id)',
'vsconfig' => 'vsconfig',
'rsconfig' => 'rsconfig',
),
'keycolumn' => 'id',
'ordcolumns' => array ('IPv4RSPool.name', 'IPv4RSPool.id'),
),
'rack' => array
(
'table' => 'Rack',
'columns' => array
(
'id' => 'id',
'name' => 'name',
'height' => 'height',
'asset_no' => 'asset_no',
'has_problems' => 'has_problems',
'comment' => 'comment',
'row_id' => 'row_id',
'row_name' => 'row_name',
'location_id' => 'location_id',
'location_name' => 'location_name',
),
'keycolumn' => 'id',
'ordcolumns' => array ('location_name', 'row_name', 'sort_order', 'Rack.name'),
'pidcolumn' => 'row_id',
),
'row' => array
(
'table' => 'Row',
'columns' => array
(
'id' => 'id',
'name' => 'name',
'location_id' => 'location_id',
'location_name' => 'location_name',
'rackc' => '(select count(Rack.id) from Rack where row_id = Row.id)',
),
'keycolumn' => 'id',
'ordcolumns' => array ('location_name', 'name'),
),
'location' => array
(
'table' => 'Location',
'columns' => array
(
'id' => 'id',
'name' => 'name',
'has_problems' => 'has_problems',
'comment' => 'comment',
'parent_id' => 'parent_id',
'parent_name' => 'parent_name',
'refcnt' => "(SELECT COUNT(child_entity_id) FROM EntityLink EL WHERE EL.parent_entity_type = 'location' AND EL.parent_entity_id = Location.id)",
),
'keycolumn' => 'id',
'ordcolumns' => array ('name'),
),
'vst' => array
(
'table' => 'VLANSwitchTemplate',
'columns' => array
(
'id' => 'id',
'description' => 'description',
'mutex_rev' => 'mutex_rev',
'saved_by' => 'saved_by',
'switchc' => '(SELECT COUNT(object_id) FROM VLANSwitch WHERE template_id = id)',
'rulec' => '(SELECT COUNT(rule_no) FROM VLANSTRule WHERE vst_id = id)',
),
'keycolumn' => 'id',
'ordcolumns' => array ('description'),
),
);
$searchfunc = array
(
'object' => array
(
'by_port' => 'getPortSearchResults',
'by_attr' => 'getObjectAttrsSearchResults',
'by_iface' => 'getObjectIfacesSearchResults',
'by_nat' => 'getObjectNATSearchResults',
'by_cableid' => 'searchCableIDs',
),
);
$tablemap_8021q = array
(
'desired' => array
(
'pvm' => 'PortVLANMode',
'pav' => 'PortAllowedVLAN',
'pnv' => 'PortNativeVLAN',
),
'cached' => array
(
'pvm' => 'CachedPVM',
'pav' => 'CachedPAV',
'pnv' => 'CachedPNV',
),
);
// VST roles
$port_role_options = array
(
'none' => 'none',
'access' => 'user: access only',
'trunk' => 'user: trunk only',
'anymode' => 'user: any mode',
'uplink' => 'system: uplink trunk',
'downlink' => 'system: downlink trunk',
);
// flags to pass to scanIPSpace, scanIPv4Space, scanIPv6Space
define ('IPSCAN_DO_ADDR', 1 << 0);
define ('IPSCAN_DO_ALLOCS', 1 << 1);
define ('IPSCAN_DO_VS', 1 << 2);
define ('IPSCAN_DO_RS', 1 << 3);
define ('IPSCAN_DO_NAT', 1 << 4);
define ('IPSCAN_DO_LOG', 1 << 5);
define ('IPSCAN_RTR_ONLY', 1 << 6);
define ('IPSCAN_ANY', -1 ^ IPSCAN_RTR_ONLY);
define ('IPSCAN_DO_SLB', IPSCAN_DO_VS | IPSCAN_DO_RS);
$object_attribute_cache = array();
// Return list of locations directly under a specified location
function getLocations ($location_id)
{
$result = usePreparedSelectBlade
(
'SELECT id, name FROM Location WHERE parent_id = ? ORDER BY name',
array ($location_id)
);
return reduceSubarraysToColumn (reindexById ($result->fetchAll (PDO::FETCH_ASSOC)), 'name');
}
// Return detailed information about one rack row.
function getRowInfo ($row_id)
{
$query =
"SELECT Row.id AS id, Row.name AS name, COUNT(Rack.id) AS count, " .
"IF(ISNULL(SUM(Rack.height)),0,SUM(Rack.height)) AS sum, " .
"Location.id AS location_id, Location.name AS location " .
"FROM Row LEFT JOIN Rack ON Rack.row_id = Row.id " .
"LEFT OUTER JOIN Location ON Row.location_id = Location.id " .
"WHERE Row.id = ? " .
"GROUP BY Row.id, Location.id";
$result = usePreparedSelectBlade ($query, array ($row_id));
if ($row = $result->fetch (PDO::FETCH_ASSOC))
return $row;
throw new EntityNotFoundException ('rackrow', $row_id);
}
// TODO: deprecated function. delete it
function getAllRows ()
{
return listCells ('row');
}
// Return list of rows directly under a specified location
function getRows ($location_id)
{
$result = usePreparedSelectBlade
(
'SELECT R.id, R.name FROM Row R ' .
'INNER JOIN EntityLink EL ON ' .
"EL.parent_entity_type = 'location' " .
"AND EL.child_entity_type = 'row' " .
"AND EL.child_entity_id = R.id " .
'WHERE EL.parent_entity_id = ? ' .
'ORDER BY R.name',
array ($location_id)
);
return reduceSubarraysToColumn (reindexById ($result->fetchAll (PDO::FETCH_ASSOC)), 'name');
}
function getRacks ($row_id)
{
$result = usePreparedSelectBlade
(
'SELECT id, name, asset_no, height, sort_order, comment, row_name FROM Rack WHERE row_id = ? ORDER BY sort_order',
array ($row_id)
);
return reindexById ($result->fetchAll (PDO::FETCH_ASSOC));
}
# Return rack and row details for those objects on the list that have
# at least one rackspace atom allocated to them.
function getMountInfo ($object_ids)
{
if (! count ($object_ids))
return array();
# In theory number of involved racks can be equal or even greater, than the
# number of objects, but in practice it will often be tens times less. Hence
# the scope of the 1st pass is to tell IDs of all involved racks without
# fetching lots of duplicate data.
$result = usePreparedSelectBlade
(
'SELECT object_id, rack_id ' .
'FROM RackSpace ' .
'WHERE object_id IN(' . questionMarks (count ($object_ids)) . ') ' .
'GROUP BY object_id, rack_id ' .
'UNION ' .
'SELECT child_entity_id AS object_id, parent_entity_id AS rack_id ' .
'FROM EntityLink ' .
'WHERE child_entity_id IN(' . questionMarks (count ($object_ids)) . ') ' .
"AND parent_entity_type = 'rack' AND child_entity_type = 'object' " .
'ORDER BY rack_id ASC',
array_merge($object_ids, $object_ids)
);
$rackidlist = $objectlist = array();
foreach ($result as $row)
{
$objectlist[$row['object_id']][] = $row['rack_id'];
$rackidlist[] = $row['rack_id'];
}
unset ($result);
# short-cut to exit in case no object had rackspace allocated
if (! count ($rackidlist))
{
$ret = array();
foreach ($object_ids as $object_id)
$ret[$object_id] = array();
return $ret;
}
# Pass 2. Fetch shorter, but better extra data about the rows and racks,
# set displayed names for both.
$result = usePreparedSelectBlade
(
'SELECT Rack_.id as rack_id, Rack_.name AS rack_name, Rack_.label as rack_label, ' .
'parent_entity_id AS row_id, Row_.name AS row_name ' .
'FROM Object Rack_ ' .
"LEFT JOIN EntityLink ON (Rack_.id = child_entity_id AND parent_entity_type = 'row' AND child_entity_type = 'rack') " .
'LEFT JOIN Object Row_ ON parent_entity_id = Row_.id ' .
'WHERE Rack_.id IN(' . questionMarks (count ($rackidlist)) . ') ',
$rackidlist
);
$rackinfo = array();
foreach ($result as $row)
{
$rackinfo[$row['rack_id']] = array
(
'rack_id' => $row['rack_id'],
'row_id' => $row['row_id'],
);
if ('' != $row['rack_name'])
$rackinfo[$row['rack_id']]['rack_name'] = $row['rack_name'];
elseif ('' != $row['rack_label'])
$rackinfo[$row['rack_id']]['rack_name'] = $row['rack_label'];
else
$rackinfo[$row['rack_id']]['rack_name'] = 'rack#' . $row['rack_id'];
if ('' != $row['row_name'])
$rackinfo[$row['rack_id']]['row_name'] = $row['row_name'];
else
$rackinfo[$row['rack_id']]['row_name'] = 'row#' . $row['row_id'];
}
unset ($result);
# Pass 3. Combine retrieved data into returned array.
$ret = array();
foreach ($objectlist as $object_id => $racklist)
foreach ($racklist as $rack_id)
$ret[$object_id][] = $rackinfo[$rack_id];
return $ret;
}
# Return container details for a list of objects
function getContainerInfo ($object_ids)
{
if (! count ($object_ids))
return array ();
$result = usePreparedSelectBlade
(
'SELECT EL.child_entity_id, EL.parent_entity_id, RO.name, RO.objtype_id ' .
'FROM EntityLink EL ' .
'LEFT JOIN RackObject RO ON EL.parent_entity_id = RO.id ' .
'WHERE EL.child_entity_id IN (' . questionMarks (count ($object_ids)) . ') ' .
"AND EL.parent_entity_type = 'object' " .
"AND EL.child_entity_type = 'object' " .
'ORDER BY RO.name',
$object_ids
);
$ret = array ();
foreach ($result as $row)
$ret[$row['child_entity_id']][] = array
(
'container_id' => $row['parent_entity_id'],
'container_dname' => formatObjectDisplayedName ($row['name'], $row['objtype_id'])
);
unset ($result);
return $ret;
}
// For a given realm return a list of entity records, each with
// enough information for judgeCell() to execute.
function listCells ($realm, $parent_id = 0)
{
if (!$parent_id)
{
global $entityCache;
if (isset ($entityCache['complete'][$realm]))
return $entityCache['complete'][$realm];
}
global $SQLSchema;
if (!isset ($SQLSchema[$realm]))
throw new InvalidArgException ('realm', $realm);
$SQLinfo = $SQLSchema[$realm];
$qparams = array ();
$query = 'SELECT ';
foreach ($SQLinfo['columns'] as $alias => $expression)
// Automatically prepend table name to each single column, but leave all others intact.
$query .= ($alias == $expression ? "${SQLinfo['table']}.${alias}" : "${expression} as ${alias}") . ', ';
$query = trim($query, ', ');
$query .= " FROM ${SQLinfo['table']}";
if (isset ($SQLinfo['pidcolumn']) && $parent_id)
{
$query .= " WHERE ${SQLinfo['table']}.${SQLinfo['pidcolumn']} = ?";
$qparams[] = $parent_id;
}
if (isset ($SQLinfo['ordcolumns']))
{
$query .= " ORDER BY ";
foreach ($SQLinfo['ordcolumns'] as $oc)
$query .= "${oc}, ";
$query = trim($query, ', ');
}
$result = usePreparedSelectBlade ($query, $qparams);
$ret = array();
// Index returned result by the value of key column.
while ($row = $result->fetch (PDO::FETCH_ASSOC))
{
$entity_id = $row[$SQLinfo['keycolumn']];
$ret[$entity_id] = array ('realm' => $realm);
$ret[$entity_id]['etags'] = array();
foreach (array_keys ($SQLinfo['columns']) as $alias)
$ret[$entity_id][$alias] = $row[$alias];
// use the temporary rack_id_2 key and remove this key from the result array
if ($realm == 'object')
{
if (! isset ($ret[$entity_id]['rack_id']))
$ret[$entity_id]['rack_id'] = $ret[$entity_id]['rack_id_2'];
unset ($ret[$entity_id]['rack_id_2']);
}
}
unset($result);
// select tags and link them to previosly fetched entities
$query = 'SELECT entity_id, tag_id, user AS tag_user, UNIX_TIMESTAMP(date) AS tag_time FROM TagStorage WHERE entity_realm = ?';
$result = usePreparedSelectBlade ($query, array($realm));
global $taglist;
while ($row = $result->fetch (PDO::FETCH_ASSOC))
{
$tag_id = $row['tag_id'];
if (array_key_exists($row['entity_id'], $ret))
$ret[$row['entity_id']]['etags'][$tag_id] = array
(
'id' => $tag_id,
'tag' => $taglist[$tag_id]['tag'],
'parent_id' => $taglist[$tag_id]['parent_id'],
'color' => $taglist[$tag_id]['color'],
'user' => $row['tag_user'],
'time' => $row['tag_time'],
);
}
unset($result);
// Add necessary finish to the list before returning it. Maintain caches.
if (!$parent_id)
unset ($entityCache['partial'][$realm]);
if ($realm == 'object') // cache dict attributes of all objects to speed up autotags calculation
cacheDictAttrValues();
foreach ($ret as $entity_id => &$entity)
{
sortEntityTags ($entity); // changes ['etags'] and ['itags']
switch ($realm)
{
case 'object':
setDisplayedName ($entity); // set $entity['dname']
break;
case 'ipv4net':
$entity = array_merge ($entity, constructIPRange (ip4_int2bin ($entity['ip_bin']), $entity['mask']));
processIPNetVlans ($entity);
$entity['spare_ranges'] = array();
$entity['kidc'] = 0;
break;
case 'ipv6net':
$entity = array_merge ($entity, constructIPRange ($entity['ip_bin'], $entity['mask']));
processIPNetVlans ($entity);
$entity['spare_ranges'] = array();
$entity['kidc'] = 0;
break;
case 'ipv4vs':
$entity['vip'] = ip_format ($entity['vip_bin']);
setDisplayedName ($entity); // set $entity['dname']
$entity['vsconfig'] = dos2unix ($entity['vsconfig']);
$entity['rsconfig'] = dos2unix ($entity['rsconfig']);
break;
case 'ipv4rspool':
$entity['vsconfig'] = dos2unix ($entity['vsconfig']);
$entity['rsconfig'] = dos2unix ($entity['rsconfig']);
break;
case 'ipvs':
$entity['vsconfig'] = dos2unix ($entity['vsconfig']);
$entity['rsconfig'] = dos2unix ($entity['rsconfig']);
break;
default:
break;
}
}
if ($realm == 'ipv4net' || $realm == 'ipv6net')
fillIPNetsCorrelation ($ret);
foreach (array_keys ($ret) as $entity_id)
{
$entity = &$ret[$entity_id];
$entity['atags'] = callHook ('generateEntityAutoTags', $entity);
if (!$parent_id)
$entityCache['complete'][$realm][$entity_id] = $entity;
else
$entityCache['partial'][$realm][$entity_id] = $entity;
}
return $ret;
}
// Very much like listCells(), but return only one record requested
// throws an exception if entity not exists
function spotEntity ($realm, $id, $ignore_cache = FALSE)
{
if (! $ignore_cache)
{
global $entityCache;
if (isset ($entityCache['complete'][$realm]))
{
if (isset ($entityCache['complete'][$realm][$id]))
return $entityCache['complete'][$realm][$id];
}
elseif (isset ($entityCache['partial'][$realm][$id]))
return $entityCache['partial'][$realm][$id];
}
global $SQLSchema;
if (!isset ($SQLSchema[$realm]))
throw new InvalidArgException ('realm', $realm);
$SQLinfo = $SQLSchema[$realm];
$query = 'SELECT tag_id, TagStorage.user as tag_user, UNIX_TIMESTAMP(TagStorage.date) AS tag_time';
foreach ($SQLinfo['columns'] as $alias => $expression)
// Automatically prepend table name to each single column, but leave all others intact.
$query .= ', ' . ($alias == $expression ? "${SQLinfo['table']}.${alias}" : "${expression} as ${alias}");
$query .= " FROM ${SQLinfo['table']} LEFT JOIN TagStorage on entity_realm = ? and entity_id = ${SQLinfo['table']}.${SQLinfo['keycolumn']}";
$query .= " WHERE ${SQLinfo['table']}.${SQLinfo['keycolumn']} = ?";
$result = usePreparedSelectBlade ($query, array ($realm, $id));
$ret = array();
global $taglist;
while ($row = $result->fetch (PDO::FETCH_ASSOC))
if (!isset ($ret['realm']))
{
$ret = array ('realm' => $realm);
foreach (array_keys ($SQLinfo['columns']) as $alias)
$ret[$alias] = $row[$alias];
// use the temporary rack_id_2 key and remove this key from the result array
if ($realm == 'object')
{
if (! isset ($ret['rack_id']))
$ret['rack_id'] = $ret['rack_id_2'];
unset ($ret['rack_id_2']);
}
$ret['etags'] = array();
if ($row['tag_id'] != NULL && isset ($taglist[$row['tag_id']]))
$ret['etags'][$row['tag_id']] = array
(
'id' => $row['tag_id'],
'tag' => $taglist[$row['tag_id']]['tag'],
'parent_id' => $taglist[$row['tag_id']]['parent_id'],
'color' => $taglist[$row['tag_id']]['color'],
'user' => $row['tag_user'],
'time' => $row['tag_time'],
);
}
elseif (isset ($taglist[$row['tag_id']]))
$ret['etags'][$row['tag_id']] = array
(
'id' => $row['tag_id'],
'tag' => $taglist[$row['tag_id']]['tag'],
'parent_id' => $taglist[$row['tag_id']]['parent_id'],
'color' => $taglist[$row['tag_id']]['color'],
'user' => $row['tag_user'],
'time' => $row['tag_time'],
);
unset ($result);
if (!isset ($ret['realm'])) // no rows were returned
throw new EntityNotFoundException ($realm, $id);
sortEntityTags ($ret); // changes ['etags'] and ['itags']
switch ($realm)
{
case 'object':
setDisplayedName ($ret); // set $ret['dname']
break;
case 'ipv4net':
processIPNetVlans ($ret);
$ret = array_merge ($ret, constructIPRange (ip4_int2bin ($ret['ip_bin']), $ret['mask']));
if (! fillNetKids ($ret))
{
$ret['spare_ranges'] = array();
$ret['kidc'] = 0;
}
break;
case 'ipv6net':
processIPNetVlans ($ret);
$ret = array_merge ($ret, constructIPRange ($ret['ip_bin'], $ret['mask']));
if (! fillNetKids ($ret))
{
$ret['spare_ranges'] = array();
$ret['kidc'] = 0;
}
break;
case 'ipv4vs':
$ret['vip'] = ip_format ($ret['vip_bin']);
setDisplayedName ($ret); // set $ret['dname']
$ret['vsconfig'] = dos2unix ($ret['vsconfig']);
$ret['rsconfig'] = dos2unix ($ret['rsconfig']);
break;
case 'ipv4rspool':
$ret['vsconfig'] = dos2unix ($ret['vsconfig']);
$ret['rsconfig'] = dos2unix ($ret['rsconfig']);
break;
case 'ipvs':
$ret['vsconfig'] = dos2unix ($ret['vsconfig']);
$ret['rsconfig'] = dos2unix ($ret['rsconfig']);
break;
default:
break;
}
$ret['atags'] = generateEntityAutoTags ($ret);
if (! $ignore_cache)
$entityCache['partial'][$realm][$id] = $ret;
return $ret;
}
function fillNetKids (&$net_cell)
{
if ($net_cell['realm'] == 'ipv6net')
{
$table = 'IPv6Network';
$ip_first = $net_cell['ip_bin'];
$ip_last = ip_last ($net_cell);
}
else
{
$table = 'IPv4Network';
$ip_first = ip4_bin2db ($net_cell['ip_bin']);
$ip_last = ip4_bin2db (ip_last ($net_cell));
}
$result = usePreparedSelectBlade ("
SELECT id, ip as ip_bin, mask FROM $table
WHERE ip BETWEEN ? AND ? AND mask >= ?
ORDER BY ip, mask
", array ($ip_first, $ip_last, $net_cell['mask']));
$nets = array();
while ($net_row = $result->fetch (PDO::FETCH_ASSOC))
{
$ip_bin = $net_row['ip_bin'];
if ($net_cell['realm'] == 'ipv4net')
$ip_bin = ip4_int2bin ($ip_bin);
$nets[] = constructIPRange ($ip_bin, $net_row['mask']) +
array(
'id' => $net_row['id'],
'spare_ranges' => array(),
'kidc' => 0,
);
}
unset ($result);
fillIPNetsCorrelation ($nets, 1);
if (is_array ($nets[0]) && $nets[0]['id'] == $net_cell['id'])
{
$net_cell['spare_ranges'] = $nets[0]['spare_ranges'];
$net_cell['kidc'] = $nets[0]['kidc'];
return TRUE;
}
return FALSE;
}
// This function can be used with array_walk().
function amplifyCell (&$record, $dummy = NULL)
{
switch ($record['realm'])
{
case 'object':
$record['ports'] = getObjectPortsAndLinks ($record['id']);
$record['ipv4'] = getObjectIPv4Allocations ($record['id']);
$record['ipv6'] = getObjectIPv6Allocations ($record['id']);
$record['nat4'] = getNATv4ForObject ($record['id']);
$record['files'] = getFilesOfEntity ($record['realm'], $record['id']);
break;
case 'file':
$record['links'] = getFileLinks ($record['id']);
break;
case 'location':
$record['locations'] = getLocations ($record['id']);
$record['rows'] = getRows ($record['id']);
break;
case 'row':
$record['racks'] = getRacks ($record['id']);
break;
case 'rack':
// start with default rackspace
for ($i = $record['height']; $i > 0; $i--)
for ($locidx = 0; $locidx < 3; $locidx++)
$record[$i][$locidx]['state'] = 'F';
// load difference
$query =
"select unit_no, atom, state, object_id, has_problems " .
"from RackSpace LEFT JOIN Object ON Object.id = object_id where rack_id = ? and " .
"unit_no between 1 and ? order by unit_no";
$result = usePreparedSelectBlade ($query, array ($record['id'], $record['height']));
global $loclist;
$mounted_objects = array();
// fetch Zero-U mounted objects
foreach (getChildren ($record, 'object') as $child)
$mounted_objects[$child['id']] = TRUE;
$rows = $result->fetchAll (PDO::FETCH_ASSOC);
unset ($result);
foreach ($rows as $row)
{
$record[$row['unit_no']][$loclist[$row['atom']]]['state'] = $row['state'];
$record[$row['unit_no']][$loclist[$row['atom']]]['object_id'] = $row['object_id'];
$record[$row['unit_no']][$loclist[$row['atom']]]['hl'] = $row['has_problems'] == 'yes' ? 'w' : '';
if ($row['state'] == 'T' && $row['object_id'] != NULL)
$mounted_objects[$row['object_id']] = TRUE;
}
$record['isDeletable'] = (count ($rows) || count ($mounted_objects)) ? FALSE : TRUE;
$record['mountedObjects'] = array_keys ($mounted_objects);
break;
case 'vst':
$record['rules'] = array();
$record['switches'] = array();
$result = usePreparedSelectBlade
(
'SELECT rule_no, port_pcre, port_role, wrt_vlans, description ' .
'FROM VLANSTRule WHERE vst_id = ? ORDER BY rule_no',
array ($record['id'])
);
while ($row = $result->fetch (PDO::FETCH_ASSOC))
$record['rules'][$row['rule_no']] = $row;
unset ($result);
$result = usePreparedSelectBlade ('SELECT object_id, domain_id FROM VLANSwitch WHERE template_id = ?', array ($record['id']));
while ($row = $result->fetch (PDO::FETCH_ASSOC))
$record['switches'][$row['object_id']] = $row;
break;
case 'ipvs':
$record['ports'] = array();
$record['vips'] = array();
$result = usePreparedSelectBlade ("SELECT proto, vport, vsconfig, rsconfig FROM VSPorts WHERE vs_id = ?", array ($record['id']));
while ($row = $result->fetch (PDO::FETCH_ASSOC))
{
$row['vsconfig'] = dos2unix ($row['vsconfig']);
$row['rsconfig'] = dos2unix ($row['rsconfig']);
$record['ports'][] = $row;
}
unset ($result);
$result = usePreparedSelectBlade ("SELECT vip, vsconfig, rsconfig FROM VSIPs WHERE vs_id = ?", array ($record['id']));
while ($row = $result->fetch (PDO::FETCH_ASSOC))
{
$row['vsconfig'] = dos2unix ($row['vsconfig']);
$row['rsconfig'] = dos2unix ($row['rsconfig']);
$record['vips'][] = $row;
}
unset ($result);
break;
default:
}
}
// is called by spotEntity and listCells.
// replaces ['8021q'] text value in cell by an array with 'domain_id' and 'vlan_id' subkeys
// also sets ['vlanc'] cell key to the binded vlans count.
function processIPNetVlans (&$cell)
{
if (empty ($cell['8021q']))
$cell['8021q'] = array();
else
{
$ck_list = explode (',', $cell['8021q']);
$cell['8021q'] = array();
foreach ($ck_list as $vlan_ck)
{
list ($domain_id, $vlan_id) = decodeVLANCK ($vlan_ck);
$cell['8021q'][] = array ('domain_id' => $domain_id, 'vlan_id' => $vlan_id);
}
}
$cell['vlanc'] = count ($cell['8021q']);
}
function fetchPortList ($sql_where_clause, $query_params = array())
{
// Heredoc, not nowdoc!
$query = <<<"END"
SELECT
Port.id,
Port.name,
Port.object_id,
Object.name AS object_name,
Port.l2address,
Port.label,
Port.reservation_comment,
Port.iif_id,
Port.type AS oif_id,
(SELECT PortInnerInterface.iif_name FROM PortInnerInterface WHERE PortInnerInterface.id = Port.iif_id) AS iif_name,
(SELECT PortOuterInterface.oif_name FROM PortOuterInterface WHERE PortOuterInterface.id = Port.type) AS oif_name,
IF(la.porta, la.cable, lb.cable) AS cableid,
IF(la.porta, pa.id, pb.id) AS remote_id,
IF(la.porta, pa.name, pb.name) AS remote_name,
IF(la.porta, pa.object_id, pb.object_id) AS remote_object_id,
IF(la.porta, oa.name, ob.name) AS remote_object_name,
IF(la.porta, oa.objtype_id, ob.objtype_id) AS remote_object_tid,
(SELECT COUNT(*) FROM PortLog WHERE PortLog.port_id = Port.id) AS log_count,
PortLog.user,
UNIX_TIMESTAMP(PortLog.date) as time
FROM
Port
INNER JOIN Object ON Port.object_id = Object.id
LEFT JOIN Link AS la ON la.porta = Port.id
LEFT JOIN Port AS pa ON pa.id = la.portb
LEFT JOIN Object AS oa ON pa.object_id = oa.id
LEFT JOIN Link AS lb on lb.portb = Port.id
LEFT JOIN Port AS pb ON pb.id = lb.porta
LEFT JOIN Object AS ob ON pb.object_id = ob.id
LEFT JOIN PortLog ON PortLog.id = (SELECT id FROM PortLog WHERE PortLog.port_id = Port.id ORDER BY date DESC LIMIT 1)
WHERE
$sql_where_clause
END;
$result = usePreparedSelectBlade ($query, $query_params);
$ret = array();
while ($row = $result->fetch (PDO::FETCH_ASSOC))
{
$row['l2address'] = l2addressFromDatabase ($row['l2address']);
$row['linked'] = isset ($row['remote_id']) ? 1 : 0;
// last changed log
$row['last_log'] = array();
if ($row['log_count'])
{
$row['last_log']['user'] = $row['user'];
$row['last_log']['time'] = $row['time'];
}
unset ($row['user']);
unset ($row['time']);
$ret[] = $row;
}
return $ret;
}
function getObjectPortsAndLinks ($object_id, $sorted = TRUE)
{
$ret = fetchPortList ("Port.object_id = ?", array ($object_id));
if ($sorted)
$ret = sortPortList ($ret, TRUE);
return $ret;
}
// This function provides data for replaceObjectPorts() and requires only two tables locked.
function getObjectPortsAndLinksTerse ($object_id)
{
$result = usePreparedSelectBlade
(
'SELECT id, name, iif_id, type AS oif_id, label, l2address, reservation_comment, ' .
'(SELECT COUNT(*) FROM Link WHERE porta = Port.id OR portb = Port.id) AS link_count ' .
'FROM Port WHERE object_id = ?',
array ($object_id)
);
return $result->fetchAll (PDO::FETCH_ASSOC);
}
// Fetch the object type via SQL.
// spotEntity cannot be used because it references RackObject, which doesn't suit Racks, Rows, or Locations.
function getObjectType ($object_id)
{
$result = usePreparedSelectBlade ('SELECT objtype_id from Object WHERE id = ?', array ($object_id));
return $result->fetchColumn ();
}
// If the given name is used by any object other than the current object,
// raise an exception. Validation is bypassed for certain object types
// where duplicates are acceptable.
// NOTE: This could be enforced more strictly at the database level using triggers.
function checkObjectNameUniqueness ($name, $type_id, $object_id = 0)
{
// Some object types do not need unique names
// 1560 - Rack
// 1561 - Row
$dupes_allowed = array (1560, 1561);
if (in_array ($type_id, $dupes_allowed))
return;
$result = usePreparedSelectBlade
(
'SELECT COUNT(*) FROM Object WHERE name = ? AND id != ?',
array ($name, $object_id)
);
$row = $result->fetch (PDO::FETCH_NUM);
if ($row[0] != 0)
throw new InvalidRequestArgException ('name', $name, 'An object with that name already exists');
}
function commitAddObject ($new_name, $new_label, $new_type_id, $new_asset_no, $taglist = array())
{
checkObjectNameUniqueness ($new_name, $new_type_id);
usePreparedInsertBlade
(
'Object',
array
(
'name' => nullIfEmptyStr ($new_name),
'label' => nullIfEmptyStr ($new_label),
'objtype_id' => $new_type_id,
'asset_no' => nullIfEmptyStr ($new_asset_no),
)
);
$object_id = lastInsertID();
switch ($new_type_id)
{
case 1560:
$realm = 'rack';
break;
case 1561:
$realm = 'row';
break;
case 1562:
$realm = 'location';
break;
default:
$realm = 'object';
}
lastCreated ($realm, $object_id);
// Store any tags before executeAutoPorts() calls spotEntity() and populates the cache.
produceTagsForNewRecord ($realm, $taglist, $object_id);
// Do AutoPorts magic
if ($realm == 'object')
executeAutoPorts ($object_id);
recordObjectHistory ($object_id);
return $object_id;
}
function commitRenameObject ($object_id, $new_name)
{
$type_id = getObjectType ($object_id);
checkObjectNameUniqueness ($new_name, $type_id, $object_id);
usePreparedUpdateBlade
(
'Object',
array
(
'name' => nullIfEmptyStr ($new_name),
),
array
(