-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrapher.js
2465 lines (2384 loc) · 75 KB
/
grapher.js
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
/*
TrafGrapher
(c) 2015-2024 Jan ONDREJ (SAL) <ondrejj(at)salstar.sk>
Licensed under the MIT license.
*/
var trafgrapher_version = '3.4.0',
one_hour = 3600000,
last_reload = null,
degreeC = "℃";
// Predefined settings
var excluded_interfaces = [
// CISCO
/^unrouted[\ \-]VLAN/,
/^Control.Plane.Interface/,
// DELL
///^[\ \-]Link[\ \-]Aggregate[\ \-]/,
/^[\ \-]CPU[\ \-]Interface[\ \-]for[\ \-]/,
/^Backbone$/
];
// Sort by key0
function col0diff(a, b) {
return a[0]-b[0];
}
// Join two arrays into one. For same keys sum values.
function joinarrays(arr) {
var d = {}, i, key;
if (arr[0]) {
for (i=0; i<arr[0].length; i++) {
key = arr[0][i][0];
d[key] = arr[0][i][1];
}
}
for (var arr_id=1; arr_id<arr.length; arr_id++) {
if (arr[arr_id]) {
for (i=0; i<arr[arr_id].length; i++) {
key = arr[arr_id][i][0];
if (d[key]===undefined) d[key] = 0;
d[key] += arr[arr_id][i][1];
}
}
}
var a = [];
for (key in d) {
a.push([parseInt(key), d[key]]);
}
a.sort(col0diff);
return a;
}
// Create array with deltas of two arrays.
// Set time_related=true for time related data (value per second, like b/s)
function arraydelta(nodes, time_related) {
if (!nodes) return [];
if (nodes.length===0) return [];
var deltas = [];
nodes.sort(col0diff);
var prev = nodes[0], item, value, time_interval=1;
for(var i=1; i<nodes.length; i++) {
item = nodes[i];
value = item[1]-prev[1];
// divide by 1000 because time is in miliseconds
if (time_related)
time_interval = (item[0]-prev[0])/1000;
if (value<0) value = 0;
if (time_interval>0)
deltas.push([item[0], value/time_interval]);
prev = item;
}
return deltas;
}
// inverse values
function arrayinverse(arr) {
var ret = [];
for(var i=0; i<arr.length; i++)
ret.push([arr[i][0], -arr[i][1]]);
return ret;
}
// Convert to milisecond
function to_ms(value) {
return parseInt(value)*1000;
}
// Convert unit to kilo, mega, giga or tera.
function guessPrecision(ticksize) {
if (ticksize<0.01) return 3;
else if (ticksize<0.1) return 2;
else if (ticksize<1) return 1;
return 0;
}
function toNumber(sign, value, ki, pow, precision, unit) {
var prefixes = ["", "k", "M", "G", "T", "P"];
// fix precision for small values
var updated_value = value / Math.pow(ki, pow);
if (updated_value<10 && precision==0 && pow>0)
precision = 1;
return sign+updated_value.toFixed(precision)+" "+prefixes[pow]+unit;
}
function convert_unit(unit, value) {
var prefix = "", inet = "", base = unit, dimension = "", dimension_power, ki;
var match = unit.match(/^([numkMGTP]?)(i?)([bBWVAC℃shmg]+)([²³]?)$/);
if (match) {
prefix = match[1];
inet = match[2];
base = match[3];
dimension = match[4];
}
if (value===undefined) {
value = 1;
}
if (dimension=="³") {
dimension_power = 3;
} else if (dimension=="²") {
dimension_power = 2;
} else {
dimension_power = 1;
}
if (base.search(/^i?[bB](\/s)?$/)==0) {
ki = 1024;
} else {
ki = 1000;
}
ki = Math.pow(ki, dimension_power);
var prefixes = {
n: -3, u: -2, m: -1,
'': 0,
k: 1, M: 2, G: 3, T: 4, P: 5
}
var multiply = Math.pow(ki, prefixes[prefix]);
return {
prefix: prefix,
base: base,
unit: inet+base+dimension,
ki: ki,
dim: dimension,
multiply: multiply,
value: value * multiply
}
}
function format_unit(val, axis, unit) {
var precision = 3, aval = Math.abs(val), sign = "", ki;
if (typeof(axis)=="number") precision = axis;
else if (axis && axis.tickSize) precision = guessPrecision(axis.tickSize);
if (axis && unit===undefined) unit = axis.options.si_unit;
if ((unit=="C" || unit==degreeC || unit=="\u00b0C") && val<0) sign = "-";
if (unit=="") {
return aval.toFixed(precision);
}
var converted = convert_unit(unit, aval);
aval = converted.value;
unit = converted.unit;
ki = converted.ki;
if (unit=="s") {
if (aval<0.001) {
if (axis && axis.tickSize)
precision = guessPrecision(axis.tickSize*1000000);
return sign+(aval*1000000).toFixed(precision)+" us";
}
if (aval<1) {
if (axis && axis.tickSize)
precision = guessPrecision(axis.tickSize*1000);
return sign+(aval*1000).toFixed(precision)+" ms";
}
if (aval>3600*24) {
return sign+(aval/3600/24).toFixed(1)+" d";
}
if (aval>3600) {
return sign+(aval/3600).toFixed(1)+" h";
}
} else if (unit=="hPa") {
return sign+aval.toFixed(precision)+" "+unit;
} else {
if (aval>=(ki*ki*ki*ki*ki))
return toNumber(sign, aval, ki, 5, precision, unit);
if (aval>=(ki*ki*ki*ki))
return toNumber(sign, aval, ki, 4, precision, unit);
if (aval>=(ki*ki*ki))
return toNumber(sign, aval, ki, 3, precision, unit);
if (aval>=(ki*ki))
return toNumber(sign, aval, ki, 2, precision, unit);
if (aval>=ki)
return toNumber(sign, aval, ki, 1, precision, unit);
}
if (unit && unit[0]=="i" && unit[1]!="o")
return toNumber("", aval, ki, 0, precision, unit.substr(1));
return toNumber(sign, aval, ki, 0, precision, unit);
}
// Parse date and time in format "YYMMHH HHMMSS" into Date object.
function parsedatetime(d, t) {
if (d.length<8) d = "20" + d;
return Date.parse(
d[0]+d[1]+d[2]+d[3]+"-" + d[4]+d[5]+"-" + d[6]+d[7]+"T" +
t[0]+t[1]+":" + t[2]+t[3]+":" + t[4]+t[5] );
}
// Decode strings
function unbase(data) {
if (data && data[0]=="~" && window.atob!==undefined)
return window.atob(data.substr(1));
return data;
}
// Color generator from flot
function gen_colors(neededColors) {
var colorPool = ["#4da74d", "#cb4b4b", "#9440ed", "#edc240", "#afd8f8"],
colorPoolSize = colorPool.length,
colors = [], variation = 0;
for (var i = 0; i < neededColors; i++) {
c = $.color.parse(colorPool[i % colorPoolSize] || "#666");
// Each time we exhaust the colors in the pool we adjust
// a scaling factor used to produce more variations on
// those colors. The factor alternates negative/positive
// to produce lighter/darker colors.
// Reset the variation after every few cycles, or else
// it will end up producing only white or black colors.
if (i % colorPoolSize === 0 && i) {
if (variation >= 0) {
if (variation < 0.5) {
variation = -variation - 0.2;
} else variation = 0;
} else variation = -variation;
}
colors[i] = c.scale('rgb', 1 + variation);
}
return colors;
}
// Dark theme
function light_theme() {
$('head').append(
$('<link rel="stylesheet" type="text/css" href="light.css" />'));
}
// Escape selector ID
String.prototype.escapeSelector = function () {
return this.replace(/([ #;?%&,.+*~':"!\^$\[\]\\()=>|\/@])/g,"\\$1");
};
/*
Graph object
=============
*/
var Graph = function(ID) {
this.ID = ID;
this.div = $("div#"+ID);
this.deltas = {}; this.info = {};
this.loaders = [];
this.index_mode = "json";
this.index_files = [];
this.plot = null;
this.range_from = null; this.range_to = null; this.custom_range = false;
this.preselect_graphs = [];
this.placeholder = this.div.find("[id^=placeholder]");
this.filter = this.div.find("[id^=filter]");
this.interval = this.div.find("[id^=interval]");
this.graph_source = this.div.find("[id^=graph_source]");
this.graph_type = this.div.find("[id^=graph_type]");
this.unit_type = this.div.find("[id^=unit_type]");
this.add_menu_callbacks();
};
Graph.prototype.find = function(id, selectors) {
var sel = "[id^="+id+"]";
if (selectors===undefined) {
return this.div.find(sel);
} else {
return this.div.find(sel+" "+selectors);
}
};
// Array sum & avg
Graph.prototype.arraysum = function(arr) {
var value = 0, last = null;
if (arr.length===0) return 0;
for (var idx=arr.length-1; idx>=0; idx--) {
var t = arr[idx][0], v = arr[idx][1];
if (this.range_from<=t && t<this.range_to && v!==null && !isNaN(v)) {
if (last===null) last = t;
value += Math.abs(v)*(t-last)/1000;
last = t;
}
}
return value;
};
Graph.prototype.arraysum_values = function(arr) {
var value = 0;
if (arr.length===0) return 0;
for (var idx=arr.length-1; idx>=0; idx--) {
var t = arr[idx][0], v = arr[idx][1];
if (this.range_from<=t && t<this.range_to && v!==null && !isNaN(v)) {
value += Math.abs(v);
}
}
return value;
};
Graph.prototype.arrayavg = function(arr) {
var value = 0, count = 0, last = null;
if (arr.length===0) return 0;
for (var idx=arr.length-1; idx>=0; idx--) {
var t = arr[idx][0], v = arr[idx][1];
if (this.range_from<=t && t<this.range_to && v!==null && !isNaN(v)) {
if (last===null) last = t;
value += v;
count += 1;
last = t;
}
}
if (count===0) return null;
return value/count;
};
// Get data for current time interval
Graph.prototype.filter_interval = function(data, unit, use_max) {
var multiply = 1;
if (unit=="b") multiply = 8; // bits
var ret = [];
for (var j=0; j<data.length; j++) {
if (data[j][0]>=this.range_from && data[j][0]<this.range_to)
ret.push([data[j][0], data[j][1]*multiply]);
}
if (ret.length>2000) {
// group data
var min_t = ret[0][0], max_t = ret[ret.length-1][0];
var vsum = [], vcnt = [], vmax = [], gi = Math.abs(max_t-min_t)/400;
for (var i=0; i<ret.length; i++) {
var ti = Math.floor(ret[i][0]/gi);
if (ti in vcnt) {
vcnt[ti] += 1;
vsum[ti] += ret[i][1];
vmax[ti] = Math.max(vmax[ti], ret[i][1]);
} else {
vcnt[ti] = 1;
vsum[ti] = ret[i][1];
vmax[ti] = ret[i][1];
}
}
ret = [];
for (var key in vcnt) {
if (use_max) {
ret.push([key*gi, vmax[key]]);
} else {
ret.push([key*gi, vsum[key]/vcnt[key]]);
}
}
}
return ret;
};
// Reset range
Graph.prototype.reset_range = function () {
// set current interval
var current_datetime = new Date(),
range_end = this.div.find("[name^=range_end]").val(),
time_interval = parseInt(this.interval.val());
if (range_end) current_datetime = range_end * 1000;
this.custom_range = false;
this.range_from = Number(current_datetime - time_interval*one_hour);
this.range_to = Number(current_datetime); // convert to number
};
// Get unit
Graph.prototype.get_unit = function(label) {
var info = this.info[label];
if (typeof(info.unit)=="string") {
if (info.prefer_unit=="b") {
return info.unit.replace("B", "b");
} else {
return info.unit;
}
} else if (info.json && info.json.unit!==undefined) {
return info.json.unit;
} else if (this.unit_type && this.unit_type.length>0) {
return info.unit[this.unit_type.find("option:selected").val()];
} else if (this.graph_type && this.graph_type.length>0) {
return info.unit[this.graph_type.find("option:selected").val()[1]];
}
return "";
};
// Get color
Graph.prototype.get_color = function(label, n) {
var info = this.info[label].json;
if (info && info.color) {
if (typeof info.color === "number")
return this.palette[info.color];
return info.color;
}
return this.palette[n];
};
// Show information from json or MRTG info
Graph.prototype.show_info = function(label, ftime) {
var self = this;
// display information from json file
if (this.index_mode=="json" && self.info[label].json) {
var table = ['<table>'], info = self.info[label].json;
if (ftime) {
table.push("<tr><td>Time</td><td>"+ftime+"</td></tr>");
}
for (var key in info) {
if (key!="log" && typeof info[key]!=="object")
table.push("<tr><td>"+key+"</td><td>"+info[key]+"</td></tr>");
}
table.push("</table>");
self.find("info_table").html($(table.join('\n')));
}
// load table information from MRTG html file
if (self.index_mode=="mrtg" && self.info[label].html) {
$.ajax({
url: self.info[label].html,
dataType: "html"
}).done(function(data) {
// don't load images from .html
var noimgdata = data.replace(/\ src=/gi, " nosrc=");
var table = $(noimgdata).find("table");
self.find("info_table").html(table[0]);
});
}
}
// Add callbacks for plot
Graph.prototype.add_plot_callbacks = function(placeholder) {
var self = this;
// hover
placeholder.unbind("plothover");
placeholder.bind("plothover", function(event, pos, item) {
if (item) {
var label = item.series.label.name;
if (!self.deltas[label]) return; // already not defined
self.filter.find("li").css("border-color", "transparent");
self.filter.find(
"li#li"+self.ID+label.escapeSelector()).css(
"border-color", "black");
// compute bytes
var graph_type = item.series.label.gt,
unit = self.get_unit(label);
var value = format_unit(item.datapoint[1], 3, unit),
description = self.info[label].name,
switchname = self.info[label].ip,
dt = new Date(item.datapoint[0]),
sum_value, sum_text, avg_value, avg_text;
if (unit.match(/[bB]\/s$/)) { // bits per second
sum_value = self.arraysum(self.deltas[label][graph_type]);
sum_text = format_unit(sum_value, null, 'iB');
} else if (unit.match(/\/h$/)) {
sum_value = self.arraysum(self.deltas[label][graph_type])/3600;
sum_text = format_unit(sum_value, null, unit.split("/")[0]);
} else {
sum_value = self.arraysum_values(self.deltas[label][graph_type]);
sum_text = format_unit(sum_value, null, unit.replace(/\/s$/, ""));
}
avg_value = self.arrayavg(self.deltas[label][graph_type]);
avg_text = format_unit(avg_value, null, unit);
self.find("value_one").val(value);
self.find("value_sum").val(sum_text);
self.find("value_avg").val(avg_text);
if (self.info[label].json && self.info[label].json.price) {
var data = item.series.data,
hours = (data[data.length-1][0] - data[0][0]) / 3600000,
price = self.info[label].json.price * Math.abs(sum_value);
self.find("value_price").val(price.toFixed(4)+" €");
}
self.find("description").val(description);
self.find("switchname").val(switchname);
// show tooltip
var tooltip_position = {
top: item.pageY+5,
left: Math.min(item.pageX+5, window.innerWidth*0.8)
};
$("#tooltip").html(
description + "<br/>" + value +
"<br/>" +
dt.toDateString() +
"<br/>" +
dt.toTimeString()
).css(tooltip_position).show();
self.show_info(label, new Date(item.datapoint[0]).toLocaleString());
} else {
$("#tooltip").hide();
}
});
// click
placeholder.unbind("plotclick");
placeholder.bind("plotclick", function(event, pos, item) {
if (item) {
var label = item.series.label.name,
checkbox = self.div.find("input#cb"+self.ID+label.escapeSelector());
$("#tooltip").hide();
checkbox.prop("checked", !checkbox.prop("checked") );
if (self.groups) {
for (var srvi in self.groups) {
for (var grpi in self.groups[srvi]) {
if (self.groups[srvi][grpi].name==label)
self.groups[srvi][grpi].enabled = false;
}
}
}
self.plot_all_graphs();
self.urllink();
}
});
// selection
placeholder.unbind("plotselected");
placeholder.bind("plotselected", function (event, ranges) {
// zoom
self.custom_range = true;
self.range_from = ranges.xaxis.from;
self.range_to = ranges.xaxis.to;
self.plot.clearSelection();
self.plot_all_graphs();
self.urllink();
});
};
// Menu functions
Graph.prototype.select_all = function () {
if (this.groups) {
// nagios host graph
for (var srvi in this.groups) {
for (var grpi in this.groups[srvi]) {
this.groups[srvi][grpi].enabled = true;
}
}
} else {
this.filter.find("input").prop("checked", true);
}
this.plot_all_graphs();
this.urllink();
};
Graph.prototype.select_none = function () {
this.filter.find("input").prop("checked", false);
this.plot_graph();
this.urllink();
};
Graph.prototype.select_inv = function () {
this.filter.find("input").each(function () {
var sel = $(this);
sel.prop("checked", !sel.prop("checked"));
});
this.plot_graph();
this.urllink();
};
Graph.prototype.select_virt = function () {
var self = this;
this.filter.find("input").each(function () {
var sel = $(this);
if (self.deltas[this.name].info &&
self.deltas[this.name].info.ifType=='propVirtual')
sel.prop("checked", !sel.prop("checked"));
});
this.plot_graph();
this.urllink();
};
Graph.prototype.select_zero = function () {
// Invert rows with only zero values in currently displayed range.
var self = this;
function abs_sum(a, b) {
if (b[0]>=self.range_from && b[0]<=self.range_to) {
return a+Math.abs(b[1]);
}
return a;
}
this.filter.find("input").each(function () {
var sel = $(this);
var deltas = self.deltas[this.name];
var sum_all = 0;
for (var k in deltas) {
sum_all += deltas[k].reduce(abs_sum, 0);
}
if (sum_all==0) {
sel.prop("checked", !sel.prop("checked"));
};
});
this.plot_graph();
this.urllink();
};
// Add menu callbacks for graph
Graph.prototype.add_menu_callbacks = function () {
var self = this;
// buttons and selectors
this.interval.change(function () {
self.refresh_range();
self.urllink();
});
this.graph_source.change(function () {
self.change_source();
self.urllink();
});
$("select#service").change(function () {
self.filter.empty(); // checkbox names are different
self.refresh_graph();
self.urllink();
});
$("select#host").change(function () {
self.filter.empty(); // checkbox names are different
self.refresh_graph();
self.urllink();
});
this.find("toggle_info").click(function () {
self.find("info_table").animate({height: "toggle"}, 300);
});
this.find("toggle_filter").click(function () {
self.filter.toggle();
});
this.find("hide_graph").click(function () {
self.placeholder.toggle();
});
this.find("b_select_all").click(function () { self.select_all(); });
this.find("b_select_inv").click(function () { self.select_inv(); });
this.find("b_select_none").click(function () { self.select_none(); });
this.find("b_select_virt").click(function () { self.select_virt(); });
this.find("b_select_zero").click(function () { self.select_zero(); });
this.find("b_zoom_out").click(function () { self.zoom_out(); });
this.find("b_reload").click(function () { self.refresh_graph(); });
this.find("b_urllink").click(function () { self.urllink(); });
};
// Create link args for index files
Graph.prototype.files_to_args = function(prefix, suffix) {
var self = this, args = "", fn,
inputs_all = this.filter.find("input"),
inputs_checked = this.filter.find("input:checked");
for (var i=0; i<this.index_files.length; i++) {
if (args!=="") args += "&";
fn = this.index_files[i];
fn = fn.split(/[:;]/)[0];
args += prefix + "=" + fn;
if (suffix) args += suffix;
// add list of checked boxes
var ports = [], index_file;
if (inputs_checked.length<inputs_all.length) {
if ($.inArray(fn, self.preselect_only)>=0) {
ports.push("!");
}
inputs_checked.each(function () {
if (self.index_mode=="storage" ||
self.index_mode=="nagios_host" ||
self.index_mode=="sagator") {
ports.push(self.info[this.name]);
} else if (self.index_mode=="nagios_service") {
ports.push(this.name);
} else {
index_file = self.index_files[i].split(";")[0];
if (self.info[this.name].index == index_file) {
ports.push(self.info[this.name]["port_id"]);
}
}
});
if (ports.length>0)
args += ";" + ports.join(";");
}
}
return args;
};
// Update URL link according to current choices
Graph.prototype.urllink = function(force) {
var self = this, url,
inputs_all = this.filter.find("input"),
inputs_checked = this.filter.find("input:checked");
if (this.index_mode=="json") {
url = "?"+this.files_to_args("j");
} else if (this.index_mode=="mrtg") {
url = "?"+this.files_to_args("m");
} else if (this.index_mode=="storage") {
url = "?"+this.files_to_args("s");
} else if (this.index_mode=="nagios_service") {
url = "?"+this.files_to_args("n",
";"+$("select#service option:selected").val());
} else if (this.index_mode=="nagios_host") {
var host = $("select#host option:selected").val();
url = "?"+this.files_to_args("n", ";"+host).replace("::", ";");
if (self.groups) {
var enabled_services = [], all_services = 0;
for (var srvi in self.groups) {
for (var grpi in self.groups[srvi]) {
all_services += 1;
if (self.groups[srvi][grpi].enabled)
enabled_services.push(self.groups[srvi][grpi].name);
}
}
if (enabled_services.length<all_services)
url += ';' + enabled_services.join(";");
}
} else {
return;
}
url += "&i=" + this.interval.val() + "h";
if (this.unit_type.val())
url += "&u=" + this.unit_type.val();
if (this.graph_type.val())
url += "&t=" + this.graph_type.val();
if (this.custom_range) {
url += "&rf=" + this.range_from + "&rt=" + this.range_to;
}
if (filter_services.length>0) {
url += "&filter=" + filter_services.join(';');
}
current_url = current_url.split("?")[0] + url;
if ($("#b_urllink").length>0) {
// change URL only if urllink button present
if (history.replaceState) {
history.replaceState(
{"params": url},
url,
current_url);
} else if (force===true) {
window.location = current_url;
}
}
};
// Keyboard events
Graph.prototype.keyevent = function(event) {
var prevent_default = true;
if (event.ctrlKey || event.altKey) {
// ignore keyboard keys with alt | ctrl
return;
}
switch(event.which) {
case 'X'.charCodeAt(0):
this.select_inv();
break;
case 'N'.charCodeAt(0):
this.select_none();
break;
case 'A'.charCodeAt(0):
this.select_all();
break;
case 'V'.charCodeAt(0):
this.select_virt();
break;
case 'R'.charCodeAt(0):
this.refresh_graph();
break;
case 'Z'.charCodeAt(0):
this.zoom_out();
break;
case 'I'.charCodeAt(0):
this.find("info_table").animate({height: "toggle"}, 300);
break;
case '1'.charCodeAt(0):
this.interval.val(24);
this.refresh_range();
break;
case '3'.charCodeAt(0):
this.interval.val(24*3);
this.refresh_range();
break;
case '4'.charCodeAt(0):
this.interval.val(4);
this.refresh_range();
break;
case '5'.charCodeAt(0):
this.interval.val(744);
this.refresh_range();
break;
case '7'.charCodeAt(0):
this.interval.val(24*7);
this.refresh_range();
break;
case '8'.charCodeAt(0):
this.interval.val(8);
this.refresh_range();
break;
case '9'.charCodeAt(0):
this.interval.val(24*8766); // 1 year
this.refresh_range();
break;
case '2'.charCodeAt(0):
this.interval.val(24*8766*2); // 2 years
this.refresh_range();
break;
case '0'.charCodeAt(0):
this.interval.val(24*26298); // 3 years
this.refresh_range();
break;
case 39: // right
this.custom_range = true;
this.range_from += this.interval.val()*one_hour;
this.range_to += this.interval.val()*one_hour;
this.plot_all_graphs();
break;
case 37: // left
this.custom_range = true;
this.range_from -= this.interval.val()*one_hour;
this.range_to -= this.interval.val()*one_hour;
this.plot_all_graphs();
break;
case 38: // up
this.custom_range = true;
this.range_from -= this.interval.val()*one_hour;
this.range_to += this.interval.val()*one_hour;
this.plot_all_graphs();
break;
case 40: // down
var amount = this.interval.val()*one_hour;
if (this.range_to-this.range_from>amount*2) {
this.custom_range = true;
this.range_from += amount;
this.range_to -= amount;
this.plot_all_graphs();
}
break;
default:
prevent_default = false;
}
//if ((65<=event.which && event.which<=90) || (96<=event.which && event.which<=111)) {
//console.log(event.which, prevent_default);
if (prevent_default) {
event.preventDefault();
//console.log("prevent", event.which, prevent_default);
}
};
// Update checkboxes according to number of graphs.
Graph.prototype.update_checkboxes = function () {
var self = this;
// Skip updating filter checkboxes if at least one of them is checked.
// All checkboxes are unchecked when switching graph source to allow
// update.
if (this.filter.find("input:checked").length>0) return;
this.filter.empty();
var keys = [], key, keyid, idkey, checked;
for (key in this.deltas) keys.push(key);
keys.sort();
for (keyid in keys) {
key = keys[keyid];
idkey = this.ID+key;
checked = "checked='checked'";
if (this.preselect_graphs.length>0) {
if ($.inArray(key, this.preselect_graphs)<0)
checked = "";
}
this.filter.append("<li id='li" + idkey +
"'><table><tr>" +
"<td><div class='box'> </div></td>" +
"<td><input type='checkbox' name='" + key +
"' " + checked + " id='cb" + idkey + "'></input></td><td>" +
this.info[key].name +
"</td></tr></table></li>");
}
self.preselect_graphs = []; // clear after apply
// Add actions.
this.filter.find("input").click(function () {
self.plot_graph();
self.urllink();
});
this.filter.find("tr").hover(function () {
self.show_info($(this).find("input").attr("name"));
});
this.graph_type.change(function () {
self.plot_graph();
self.urllink();
});
this.unit_type.change(function () {
self.plot_graph();
self.urllink();
});
};
// Plot current graph.
Graph.prototype.plot_all_graphs = function () {
var graph, enabled_groups, placeholder;
if (this.groups) {
// make menu fixed (always visisble)
var selection = $("div.selection");
selection.addClass("noscroll");
$("div#placeholder").css("margin-top", selection.outerHeight());
for (var service in service_groups) {
if (service_groups[service].hide===true) continue; // skip
if (!this.groups[service]) continue;
graph = $("#graph_"+service);
if (graph.length===0) {
graph = document.createElement("div");
graph.id = "graph_"+service;
graph.className = "trafgrapher";
graph.textContent = service_groups[service].name;
if (filter_services.length==0) {
var urllink = document.createElement("a");
urllink.textContent = "\u2197"; // UpperRightArrow
urllink.href = current_url+'&filter='+escape(service);
graph.textContent += " ";
graph.append(urllink);
}
graph.append(document.createElement("br"));
placeholder = document.createElement("div");
placeholder.id = "placeholder_"+service;
placeholder.className = "graph200r";
graph.append(placeholder);
this.placeholder.append(graph);
this.add_plot_callbacks($(placeholder));
}
enabled_groups = [];
for (var grpi in this.groups[service]) {
if (this.groups[service][grpi].enabled)
enabled_groups.push(this.groups[service][grpi].name);
}
placeholder = $(graph).find("#placeholder_"+service);
this.plot_graph(enabled_groups, placeholder);
}
} else {
this.plot_graph();
}
};
Graph.prototype.plot_graph = function(checked_choices, placeholder) {
var flots = [], name, info, unit, color, axis, yaxis, axis_unit, axis_pos,
graph_type = this.graph_type.find("option:selected").val() || "jo";
if (checked_choices===undefined) {
checked_choices = [];
this.filter.find("input:checked").each(function () {
checked_choices.push($(this).prop("name"));
});
}
// main axis on left side
var multiple_axes = [{
font: { fill: "#eee" },
tickFormatter: format_unit,
//si_unit: undefined // redefined below
}];
// flot graphs
this.palette = gen_colors(checked_choices.length);
var ax_list = [];
for (var n=0; n<checked_choices.length; n++) {
name = checked_choices[n];
info = this.info[name];
unit = this.get_unit(name);
color = this.get_color(name, n);
if (this.index_mode=="storage") {
if (graph_type[0]=="x") {
// storage read and write graph
flots.push({
label: {name: name, gt: 'r'+graph_type[1]},
color: color,
data: this.filter_interval(this.deltas[name]['r'+graph_type[1]])
});
flots.push({
label: {name: name, gt: 'w'+graph_type[1]},
color: color,
data: this.filter_interval(arrayinverse(
this.deltas[name]['w'+graph_type[1]]))
});
} else {
// storage one way graph (read or write only)
flots.push({
label: {name: name, gt: graph_type[0]},
color: color,
data: this.filter_interval(this.deltas[name][graph_type])
});
}
} else {
// json/mrtg/nagios graph
for (var gt=0; gt<graph_type.length; gt++) {
if (this.deltas[name][graph_type[gt]]===undefined)
console.log("Undefined data: "+name+" "+graph_type[gt]);
if (this.deltas[name][graph_type[gt]].length===0)
continue; // skip empty graph
info.prefer_unit = this.unit_type.find("option:selected").val();
if (!info.prefer_unit && info.service && info.service.prefer_bits) {
info.prefer_unit = "b";
}
// force to Bytes for temperature and some special units
if (info.json && info.json.force_bytes) {
info.prefer_unit = "B";
}
unit = this.get_unit(name); // refresh unit
yaxis = 1;
if (info.json && info.json.yaxis!==undefined) {
axis = info.json.yaxis;
axis_pos = "right";
if (axis===true) {
// copy unit if it's set to True
axis_unit = unit;
} else if (typeof axis === "number") {
// copy unit and assign right/left position
axis_unit = unit;
if (axis < 0) { axis_pos = "left"; }
} else {
axis_unit = axis;
}
if (ax_list.indexOf(axis)<0) {
ax_list.push(axis);
multiple_axes.push({
position: axis_pos,
//alignTicksWithAxis: 1,
font: { fill: "#eee" },
tickFormatter: format_unit,