forked from ganglia/ganglia-web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.php
1293 lines (1073 loc) · 38.3 KB
/
functions.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
#
# Some common functions for the Ganglia PHP website.
# Assumes the Gmeta XML tree has already been parsed,
# and the global variables $metrics, $clusters, and $hosts
# have been set.
#
include_once ( dirname(__FILE__) . "/lib/json.php" );
#
# Load event API driver.
#
$driver = ucfirst(strtolower( !isset($conf['overlay_events_provider']) ? "Json" : $conf['overlay_events_provider'] ));
if (file_exists( dirname(__FILE__) . "/lib/Events/Driver_${driver}.php")) {
include_once( dirname(__FILE__) . "/lib/Events/Driver_${driver}.php" );
}
#------------------------------------------------------------------------------
# Allows a form of inheritance for template files.
# If a file does not exist in the chosen template, the
# default is used. Cuts down on code duplication.
function template ($name)
{
global $conf;
$fn = "./templates/${conf['template_name']}/$name";
$default = "./templates/default/$name";
if (file_exists($fn)) {
return $fn;
}
else {
return $default;
}
}
#------------------------------------------------------------------------------
# Creates a hidden input field in a form. Used to save CGI variables.
function hiddenvar ($name, $var)
{
$hidden = "";
if ($var) {
#$url = rawurlencode($var);
$hidden = "<input type=\"hidden\" name=\"$name\" value=\"$var\">\n";
}
return $hidden;
}
#------------------------------------------------------------------------------
# Gives a readable time string, from a "number of seconds" integer.
# Often used to compute uptime.
function uptime($uptimeS)
{
$uptimeD=intval($uptimeS/86400);
$uptimeS=$uptimeD ? $uptimeS % ($uptimeD*86400) : $uptimeS;
$uptimeH=intval($uptimeS/3600);
$uptimeS=$uptimeH ? $uptimeS % ($uptimeH*3600) : $uptimeS;
$uptimeM=intval($uptimeS/60);
$uptimeS=$uptimeM ? $uptimeS % ($uptimeM*60) : $uptimeS;
$s = ($uptimeD!=1) ? "s" : "";
return sprintf("$uptimeD day$s, %d:%02d:%02d",$uptimeH,$uptimeM,$uptimeS);
}
#------------------------------------------------------------------------------
# Try to determine a nodes location in the cluster. Attempts to find the
# LOCATION attribute first. Requires the host attribute array from
# $hosts[$cluster][$name], where $name is the hostname.
# Returns [-1,-1,-1] if we could not determine location.
#
function findlocation($attrs)
{
$rack=$rank=$plane=-1;
$loc=$attrs['LOCATION'];
if ($loc) {
sscanf($loc, "%d,%d,%d", $rack, $rank, $plane);
#echo "Found LOCATION: $rack, $rank, $plane.<br>";
}
if ($rack<0 or $rank<0) {
# Try to parse the host name. Assumes a compute-<rack>-<rank>
# naming scheme.
$n=sscanf($attrs['NAME'], "compute-%d-%d", $rack, $rank);
$plane=0;
}
return array($rack,$rank,$plane);
}
#------------------------------------------------------------------------------
function cluster_sum($name, $metrics)
{
$sum = 0;
foreach ($metrics as $host => $val)
{
if(isset($val[$name]['VAL'])) $sum += $val[$name]['VAL'];
}
return $sum;
}
#------------------------------------------------------------------------------
function cluster_min($name, $metrics)
{
$min = "";
foreach ($metrics as $host => $val)
{
$v = $val[$name]['VAL'];
if (!is_numeric($min) or $min < $v)
{
$min = $v;
$minhost = $host;
}
}
return array($min, $minhost);
}
#------------------------------------------------------------------------------
#
# A useful function for giving the correct picture for a given
# load. Scope is "node | cluster | grid". Value is 0 <= v <= 1.
function load_image ($scope, $value)
{
global $conf;
$scaled_load = $value / $conf['load_scale'];
if ($scaled_load>1.00) {
$image = template("images/${scope}_overloaded.jpg");
}
else if ($scaled_load>=0.75) {
$image = template("images/${scope}_75-100.jpg");
}
else if ($scaled_load >= 0.50) {
$image = template("images/${scope}_50-74.jpg");
}
else if ($scaled_load>=0.25) {
$image = template("images/${scope}_25-49.jpg");
}
else {
$image = template("images/${scope}_0-24.jpg");
}
return $image;
}
#------------------------------------------------------------------------------
# A similar function that specifies the background color for a graph
# based on load. Quantizes the load figure into 6 sets.
function load_color ($value)
{
global $conf;
$scaled_load = $value / $conf['load_scale'];
if ($scaled_load>1.00) {
$color = $conf['load_colors']["100+"];
}
else if ($scaled_load>=0.75) {
$color = $conf['load_colors']["75-100"];
}
else if ($scaled_load >= 0.50) {
$color = $conf['load_colors']["50-75"];
}
else if ($scaled_load>=0.25) {
$color = $conf['load_colors']["25-50"];
}
else if ($scaled_load < 0.0)
$color = $conf['load_colors']["down"];
else {
$color = $conf['load_colors']["0-25"];
}
return $color;
}
#------------------------------------------------------------------------------
#
# Just a useful function to print the HTML for
# the load/death of a cluster node
function node_image ($metrics)
{
global $hosts_down;
# More rigorous checking if variables are set before trying to use them.
if ( isset($metrics['cpu_num']['VAL']) and $metrics['cpu_num']['VAL'] != 0 ) {
$cpu_num = $metrics['cpu_num']['VAL'];
} else {
$cpu_num = 1;
}
if ( isset($metrics['load_one']['VAL']) ) {
$load_one = $metrics['load_one']['VAL'];
} else {
$load_one = 0;
}
$value = $load_one / $cpu_num;
# Check if the host is down
# RFM - Added isset() check to eliminate error messages in ssl_error_log
if (isset($hosts_down) and $hosts_down)
$image = template("images/node_dead.jpg");
else
$image = load_image("node", $value);
return $image;
}
#------------------------------------------------------------------------------
#
# Finds the min/max over a set of metric graphs. Nodes is
# an array keyed by host names.
#
function find_limits($nodes, $metricname)
{
global $conf, $metrics, $clustername, $rrd_dir, $start, $end, $rrd_options;
if (!count($metrics))
return array(0, 0);
$firsthost = key($metrics);
if (array_key_exists($metricname,$metrics[$firsthost])) {
if ($metrics[$firsthost][$metricname]['TYPE'] == "string"
or $metrics[$firsthost][$metricname]['SLOPE'] == "zero")
return array(0,0);
}
else {
return array(0,0);
}
$max=0;
$min=0;
if ($conf['graph_engine'] == "graphite") {
$target = $conf['graphite_prefix'] . $clustername . ".[a-zA-Z0-9]*." . $metricname . ".sum";
$raw_highestMax = file_get_contents($conf['graphite_url_base'] . "?target=highestMax(" . $target . ",1)&from=" . $start . "&until=" . $end . "&format=json");
$highestMax = json_decode($raw_highestMax, TRUE);
$highestMaxDatapoints = $highestMax[0]['datapoints'];
$maxdatapoints = array();
foreach ( $highestMaxDatapoints as $datapoint ) {
array_push($maxdatapoints, $datapoint[0]);
}
$max = max($maxdatapoints);
}
else {
foreach ( $nodes as $host => $value ) {
$out = array();
$rrd_dir = "${conf['rrds']}/$clustername/$host";
$rrd_file = "$rrd_dir/$metricname.rrd";
if (file_exists($rrd_file)) {
if ( extension_loaded( 'rrd' ) ) {
$values = rrd_fetch($rrd_file,
array(
"--start", $start,
"--end", $end,
"AVERAGE"
)
);
$values = (array_filter(array_values($values['data']['sum']), 'is_finite'));
$thismax = max($values);
$thismin = min($values);
} else {
$command = $conf['rrdtool'] . " graph /dev/null $rrd_options ".
"--start $start --end $end ".
"DEF:limits='$rrd_dir/$metricname.rrd':'sum':AVERAGE ".
"PRINT:limits:MAX:%.2lf ".
"PRINT:limits:MIN:%.2lf";
exec($command, $out);
if(isset($out[1])) {
$thismax = $out[1];
} else {
$thismax = NULL;
}
if (!is_numeric($thismax)) continue;
$thismin=$out[2];
if (!is_numeric($thismin)) continue;
}
if ($max < $thismax) $max = $thismax;
if ($min > $thismin) $min = $thismin;
#echo "$host: $thismin - $thismax (now $value)<br>\n";
}
}
}
return array($min, $max);
}
#------------------------------------------------------------------------------
#
# Finds the avg of the given cluster & metric from the summary rrds.
#
function find_avg($clustername, $hostname, $metricname)
{
global $conf, $start, $end, $rrd_options;
$avg = 0;
if ($hostname)
$sum_dir = "${conf['rrds']}/$clustername/$hostname";
else
$sum_dir = "${conf['rrds']}/$clustername/__SummaryInfo__";
$command = $conf['rrdtool'] . " graph /dev/null $rrd_options ".
"--start $start --end $end ".
"DEF:avg='$sum_dir/$metricname.rrd':'sum':AVERAGE ".
"PRINT:avg:AVERAGE:%.2lf ";
exec($command, $out);
if ( isset($out[1]) )
$avg = $out[1];
else
$avg = 0;
#echo "$sum_dir: avg($metricname)=$avg<br>\n";
return $avg;
}
#------------------------------------------------------------------------------
# Alternate between even and odd row styles.
function rowstyle()
{
static $style;
if ($style == "even") { $style = "odd"; }
else { $style = "even"; }
return $style;
}
#------------------------------------------------------------------------------
# Return a version of the string which is safe for display on a web page.
# Potentially dangerous characters are converted to HTML entities.
# Resulting string is not URL-encoded.
function clean_string( $string )
{
return htmlentities( $string );
}
#------------------------------------------------------------------------------
function sanitize ( $string ) {
return escapeshellcmd( clean_string( rawurldecode( $string ) ) ) ;
}
#------------------------------------------------------------------------------
# If arg is a valid number, return it. Otherwise, return null.
function clean_number( $value )
{
return is_numeric( $value ) ? $value : null;
}
#------------------------------------------------------------------------------
# Return true if string is a 3 or 6 character hex color.Return false otherwise.
function is_valid_hex_color( $string )
{
$return_value = false;
if( strlen( $string ) == 6 || strlen( $string ) == 3 ) {
if( preg_match( '/^[0-9a-fA-F]+$/', $string ) ) {
$return_value = true;
}
}
return $return_value;
}
#------------------------------------------------------------------------------
# Return a shortened version of a FQDN
# if "hostname" is numeric only, assume it is an IP instead
#
function strip_domainname( $hostname ) {
$postition = strpos($hostname, '.');
$name = substr( $hostname , 0, $postition );
if ( FALSE === $postition || is_numeric($name) ) {
return $hostname;
} else {
return $name;
}
}
#------------------------------------------------------------------------------
# Read a file containing key value pairs
function file_to_hash($filename, $sep)
{
$lines = file($filename, FILE_IGNORE_NEW_LINES);
foreach ($lines as $line)
{
list($k, $v) = explode($sep, rtrim($line));
$params[$k] = $v;
}
return $params;
}
#------------------------------------------------------------------------------
# Read a file containing key value pairs
# Multiple values permitted for each key
function file_to_hash_multi($filename, $sep)
{
$lines = file($filename);
foreach ($lines as $line)
{
list($k, $v) = explode($sep, rtrim($line));
$params[$k][] = $v;
}
return $params;
}
#------------------------------------------------------------------------------
# Obtain a list of distinct values from an array of arrays
function hash_get_distinct_values($h)
{
$values = array();
$values_done = array();
foreach($h as $k => $v)
{
if($values_done[$v] != "x")
{
$values_done[$v] = "x";
$values[] = $v;
}
}
return $values;
}
$filter_defs = array();
#------------------------------------------------------------------------------
# Scan $conf['filter_dir'] and populate $filter_defs
function discover_filters()
{
global $conf, $filter_defs;
# Check whether filtering is configured or not
if(!isset($conf['filter_dir']))
return;
if(!is_dir($conf['filter_dir']))
{
error_log("discover_filters(): not a directory: ${conf['filter_dir']}");
return;
}
if($dh = opendir($conf['filter_dir']))
{
while(($filter_conf_filename = readdir($dh)) !== false) {
if(!is_dir($filter_conf_filename))
{
# Parse the file contents
$full_filename = "${conf['filter_dir']}/$filter_conf_filename";
$filter_params = file_to_hash($full_filename, '=');
$filter_shortname = $filter_params["shortname"];
$filter_type = $filter_params["type"];
if($filter_type = "url")
{
$filter_data_url = $filter_params['url'];
$filter_defs[$filter_shortname] = $filter_params;
$filter_defs[$filter_shortname]["data"] = file_to_hash($filter_data_url, ',');
$filter_defs[$filter_shortname]["choices"] = hash_get_distinct_values($filter_defs[$filter_shortname]["data"]);
}
}
}
closedir($dh);
}
}
$filter_permit_list = NULL;
#------------------------------------------------------------------------------
# Initialise the filter permit list, if necessary
function filter_init()
{
global $conf, $filter_permit_list, $filter_defs, $choose_filter;
if(!is_null($filter_permit_list))
{
return;
}
if(!isset($conf['filter_dir']))
{
$filter_permit_list = FALSE;
return;
}
$filter_permit_list = array();
$filter_count = 0;
foreach($choose_filter as $filter_shortname => $filter_choice)
{
if($filter_choice == "")
continue;
$filter_params = $filter_defs[$filter_shortname];
if($filter_count == 0)
{
foreach($filter_params["data"] as $key => $value)
{
if($value == $filter_choice)
$filter_permit_list[$key] = $key;
}
}
else
{
foreach($filter_permit_list as $key => $value)
{
$remove_key = TRUE;
if(isset($filter_params["data"][$key]))
{
if($filter_params["data"][$key] == $filter_choice)
{
$remove_key = FALSE;
}
}
if($remove_key)
{
unset($filter_permit_list[$key]);
}
}
}
$filter_count++;
}
if($filter_count == 0)
$filter_permit_list = FALSE;
}
#------------------------------------------------------------------------------
# Decide whether the given source is permitted by the filters, if any
function filter_permit($source_name)
{
global $filter_permit_list;
filter_init();
# Handle the case where filtering is not active
if(!is_array($filter_permit_list))
return true;
return isset($filter_permit_list[$source_name]);
}
///////////////////////////////////////////////////////////////////////////////
// Get all the available views
///////////////////////////////////////////////////////////////////////////////
function get_available_views() {
global $conf;
/* -----------------------------------------------------------------------
Find available views by looking in the GANGLIA_DIR/conf directory
anything that matches view_*.json. Read them all and build a available_views
array
----------------------------------------------------------------------- */
$available_views = array();
if ($handle = opendir($conf['views_dir'])) {
while (false !== ($file = readdir($handle))) {
if ( preg_match("/^view_(.*)\.json$/", $file, $out) ) {
$view_config_file = $conf['views_dir'] . "/" . $file;
if ( ! is_file ($view_config_file) ) {
echo("Can't read view config file " . $view_config_file . ". Please check permissions");
}
$view = json_decode(file_get_contents($view_config_file), TRUE);
// Check whether view type has been specified ie. regex.
// If not it's standard view
$view_type =
isset($view['view_type']) ? $view['view_type'] : "standard";
$default_size = isset($view['default_size']) ?
$view['default_size'] : $conf['default_view_graph_size'];
$available_views[] = array ("file_name" => $view_config_file,
"view_name" => $view['view_name'],
"default_size" => $default_size,
"items" => $view['items'],
"view_type" => $view_type);
unset($view);
}
}
closedir($handle);
}
foreach ($available_views as $key => $row) {
$name[$key] = strtolower($row['view_name']);
}
@array_multisort($name,SORT_ASC, $available_views);
return $available_views;
}
///////////////////////////////////////////////////////////////////////////////
// Get image graph URLS
// This function returns an array of graph URLs to be used when rendering the
// view. It returns only the base ie. cluster, host, metric information.
// It is up to the caller to add proper size information, time ranges etc.
///////////////////////////////////////////////////////////////////////////////
function get_view_graph_elements($view) {
global $conf, $index_array;
retrieve_metrics_cache();
$view_elements = array();
// set the default size from the view or global config
if ( isset($conf['default_view_graph_size']) ) {
$default_size = $conf['default_view_graph_size'];
}
if ( isset($view['default_size']) ) {
$default_size = $view['default_size'];
}
switch ( $view['view_type'] ) {
case "standard":
// Does view have any items/graphs defined
if ( sizeof($view['items']) == 0 ) {
continue;
// print "No graphs defined for this view. Please add some";
} else {
// Loop through graph items
foreach ( $view['items'] as $item_id => $item ) {
// Check if item is an aggregate graph
if ( isset($item['aggregate_graph']) ) {
foreach ( $item['host_regex'] as $reg_id => $regex_array ) {
$graph_args_array[] = "hreg[]=" . urlencode($regex_array["regex"]);
}
if ( isset($item['metric_regex']) ) {
foreach ( $item['metric_regex'] as $reg_id => $regex_array ) {
$graph_args_array[] = "mreg[]=" . urlencode($regex_array["regex"]);
$mreg[] = $regex_array["regex"];
}
}
if ( isset($item['size']) ) {
$graph_args_array[] = "z=" . $item['size'];
} else {
$graph_args_array[] = "z=" . $default_size;
}
// If graph type is not specified default to line graph
if ( isset($item['graph_type']) && in_array($item['graph_type'], array('line', 'stack') ) )
$graph_args_array[] = "gtype=" . $item['graph_type'];
else
$graph_args_array[] = "gtype=line";
if (isset($item['upper_limit']))
$graph_args_array[] = "x=" .$item['upper_limit'];
if (isset($item['lower_limit']))
$graph_args_array[] = "n=" .$item['lower_limit'];
if (isset($item['vertical_label']))
$graph_args_array[] = "vl=" . urlencode($item['vertical_label']);
if (isset($item['title']))
$graph_args_array[] = "title=" . urlencode($item['title']);
if ( isset($item['metric']) ) {
$graph_args_array[] = "m=" . $item['metric'];
}
if ( isset($item['glegend']) )
$graph_args_array[] = "glegend=" . $item["glegend"];
if ( isset($item['cluster']) ) {
$graph_args_array[] = "c=" . urlencode($item['cluster']);
}
if ( isset($item['exclude_host_from_legend_label']) ) {
$graph_args_array[] = "lgnd_xh=" . $item['exclude_host_from_legend_label'];
}
$graph_args_array[] = "aggregate=1";
$view_elements[] = array ( "graph_args" => join("&", $graph_args_array),
"aggregate_graph" => 1,
"name" => isset($item['title']) && $item['title'] != "" ? $item['title'] : $mreg[0] . " Aggregate graph"
);
unset($graph_args_array);
// It's standard metric graph
} else {
// Is it a metric or a graph(report)
if ( isset($item['metric']) ) {
$graph_args_array[] = "m=" . $item['metric'];
$name = $item['metric'];
} else {
$graph_args_array[] = "g=" . urlencode($item['graph']);
$name = $item['graph'];
}
if ( isset($item['size']) ) {
$graph_args_array[] = "z=" . $item['size'];
} else {
$graph_args_array[] = "z=" . $default_size;
}
if (isset($item['hostname'])) {
$hostname = $item['hostname'];
$cluster = array_key_exists($hostname, $index_array['cluster']) ?
$index_array['cluster'][$hostname][0] : NULL;
} else if (isset($item['cluster'])) {
$hostname = "";
$cluster = $item['cluster'];
} else {
$hostname = "";
$cluster = "";
}
$graph_args_array[] = "h=" . urlencode($hostname);
$graph_args_array[] = "c=" . urlencode($cluster);
if (isset($item['vertical_label']))
$graph_args_array[] = "vl=" . urlencode($item['vertical_label']);
if (isset($item['title']))
$graph_args_array[] = "title=" . urlencode($item['title']);
if (isset($item['warning'])) {
$view_e['warning'] = $item['warning'];
$graph_args_array[] = "warn=" . $item['warning'];
}
if (isset($item['critical'])) {
$view_e['critical'] = $item['critical'];
$graph_args_array[] = "crit=" . $item['critical'];
}
$view_e["graph_args"] = join("&", $graph_args_array);
$view_e['hostname'] = $hostname;
$view_e['cluster'] = $cluster;
$view_e['name'] = $name;
$view_elements[] = $view_e;
unset($view_e);
unset($graph_args_array);
}
} // end of foreach ( $view['items']
} // end of if ( sizeof($view['items'])
break;
;;
///////////////////////////////////////////////////////////////////////////
// Currently only supports matching hosts.
///////////////////////////////////////////////////////////////////////////
case "regex":
foreach ( $view['items'] as $item_id => $item ) {
// Is it a metric or a graph(report)
if ( isset($item['metric']) ) {
$metric_suffix = "m=" . $item['metric'];
$name = $item['metric'];
} else {
$metric_suffix = "g=" . $item['graph'];
$name = $item['graph'];
}
// Find hosts matching a criteria
$query = $item['hostname'];
foreach ( $index_array['hosts'] as $key => $host_name ) {
if ( preg_match("/$query/", $host_name ) ) {
$clusters = $index_array['cluster'][$host_name];
foreach ($clusters AS $cluster) {
$graph_args_array[] = "h=" . urlencode($host_name);
$graph_args_array[] = "c=" . urlencode($cluster);
$view_elements[] = array ( "graph_args" => $metric_suffix . "&" . join("&", $graph_args_array),
"hostname" => $host_name,
"cluster" => $cluster,
"name" => $name);
unset($graph_args_array);
}
}
}
} // end of foreach ( $view['items'] as $item_id => $item )
break;;
} // end of switch ( $view['view_type'] ) {
return ($view_elements);
}
function legendEntry($vname, $legend_items) {
$legend = "";
if (in_array("now", $legend_items))
$legend .= "VDEF:{$vname}_last={$vname},LAST ";
if (in_array("min", $legend_items))
$legend .= "VDEF:{$vname}_min={$vname},MINIMUM ";
if (in_array("avg", $legend_items))
$legend .= "VDEF:{$vname}_avg={$vname},AVERAGE ";
if (in_array("max", $legend_items))
$legend .= "VDEF:{$vname}_max={$vname},MAXIMUM ";
$terminate = FALSE;
if (in_array("now", $legend_items)) {
$legend .= "GPRINT:'{$vname}_last':'Now\:%5.1lf%s";
$terminate = TRUE;
}
if (in_array("min", $legend_items)) {
if ($terminate)
$legend .= "' ";
$legend .= "GPRINT:'{$vname}_min':'Min\:%5.1lf%s";
$terminate = TRUE;
}
if (in_array("avg", $legend_items)) {
if ($terminate)
$legend .= "' ";
$legend .= "GPRINT:'{$vname}_avg':'Avg\:%5.1lf%s";
$terminate = TRUE;
}
if (in_array("max", $legend_items)) {
if ($terminate)
$legend .= "' ";
$legend .= "GPRINT:'{$vname}_max':'Max\:%5.1lf%s";
$terminate = TRUE;
}
if ($terminate)
$legend .= "\\l' ";
return $legend;
}
/**
* Check if current user has a privilege (view, edit, etc) on a resource.
* If resource is unspecified, we assume GangliaAcl::ALL.
*
* Examples
* checkAccess( GangliaAcl::ALL_CLUSTERS, GangliaAcl::EDIT, $conf ); // user has global edit?
* checkAccess( GangliaAcl::ALL_CLUSTERS, GangliaAcl::VIEW, $conf ); // user has global view?
* checkAccess( $cluster, GangliaAcl::EDIT, $conf ); // user can edit current cluster?
* checkAccess( 'cluster1', GangliaAcl::EDIT, $conf ); // user has edit privilege on cluster1?
* checkAccess( 'cluster1', GangliaAcl::VIEW, $conf ); // user has view privilege on cluster1?
*/
function checkAccess($resource, $privilege, $conf) {
if(!is_array($conf)) {
trigger_error('checkAccess: $conf is not an array.', E_USER_ERROR);
}
if(!isSet($conf['auth_system'])) {
trigger_error("checkAccess: \$conf['auth_system'] is not defined.", E_USER_ERROR);
}
switch( $conf['auth_system'] ) {
case 'readonly':
$out = ($privilege == GangliaAcl::VIEW);
break;
case 'enabled':
// TODO: 'edit' needs to check for writeability of data directory. error log if edit is allowed but we're unable to due to fs problems.
$acl = GangliaAcl::getInstance();
$auth = GangliaAuth::getInstance();
if(!$auth->isAuthenticated()) {
$user = GangliaAcl::GUEST;
} else {
$user = $auth->getUser();
}
if(!$acl->has($resource)) {
$resource = GangliaAcl::ALL_CLUSTERS;
}
$out = false;
if($acl->hasRole($user)) {
$out = (bool) $acl->isAllowed($user, $resource, $privilege);
}
// error_log("checkAccess() user=$user, resource=$resource, priv=$privilege == $out");
break;
case 'disabled':
$out = true;
break;
default:
trigger_error( "Invalid value '".$conf['auth_system']."' for \$conf['auth_system'].", E_USER_ERROR );
return false;
}
return $out;
}
function viewId($view_name) {
$id = 'v_' . preg_replace('/[^a-zA-Z0-9_]/', '_', $view_name);
return $id;
}
///////////////////////////////////////////////////////////////////////////////
// Taken from
// http://au2.php.net/manual/en/function.json-encode.php#80339
// Pretty print JSON
///////////////////////////////////////////////////////////////////////////////
function json_prettyprint($json)
{
$tab = " ";
$new_json = "";
$indent_level = 0;
$in_string = false;
$len = strlen($json);
for($c = 0; $c < $len; $c++)
{
$char = $json[$c];
switch($char)
{
case '{':
case '[':
if(!$in_string)
{
$new_json .= $char . "\n" . str_repeat($tab, $indent_level+1);
$indent_level++;
}
else
{
$new_json .= $char;
}
break;
case '}':
case ']':
if(!$in_string)
{
$indent_level--;
$new_json .= "\n" . str_repeat($tab, $indent_level) . $char;
}
else
{
$new_json .= $char;
}
break;
case ',':
if(!$in_string)
{
$new_json .= ",\n" . str_repeat($tab, $indent_level);
}
else
{
$new_json .= $char;
}
break;
case ':':
if(!$in_string)
{
$new_json .= ": ";
}
else
{
$new_json .= $char;
}
break;
case '"':
if($c > 0 && $json[$c-1] != '\\')
{
$in_string = !$in_string;
}
default:
$new_json .= $char;
break;
}
}
return $new_json;
}
function ganglia_cache_metrics() {
global $conf, $index_array, $hosts, $grid, $clusters, $debug, $metrics;