-
Notifications
You must be signed in to change notification settings - Fork 50
/
web-utils.js
3189 lines (2984 loc) · 124 KB
/
web-utils.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
/*
* Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
*/
var globalObj = {},
contentContainer = "#content-container";
globalObj['loadedScripts'] = [];
globalObj['loadedCSS'] = [];
globalObj['orchModel'] = 'openstack';
globalObj.NUM_FLOW_DATA_POINTS = 1000;
var globalAlerts = [],timeStampTolearence = 5 * 60 * 1000;//To check the mismatch between the browser time and the webserver time
var enableHardRefresh = false; //Set to true if "Hard Refresh" provision need to be shown in UI
//Set to true if we want to discard ongoing requests while refreshing the dataSource and start fetching from beginnging
//Ajax calls shouldn't be aborted if we don't want to discard ongoing update
var discardOngoingUpdate = true;
var DEFAULT_TIME_SLICE = 3600000,
pageContainer = "#content-container",
dblClick = 0;
var CONTRAIL_STATUS_USER = [];
var roles = {TENANT : "member",ADMIN : "superAdmin"};
var CONTRAIL_STATUS_PWD = [];
var flowKeyStack = [];
var aclIterKeyStack = [];
var d3Colors = {red:'#dc6660',green:'#7dc48a',blue:'#7892dd',orange:'#ffbf87'};
if(typeof(built_at) == 'undefined')
built_at = '';
var TENANT_API_URL = "/api/tenant/get-data";
var SANDESH_DATA_URL = "/api/admin/monitor/infrastructure/get-sandesh-data";
var INDENT_RIGHT = " ";
var INST_PAGINATION_CNT = 50;
var NETWORKS_PAGINATION_CNT = 25;
// Need to move to controller.utils.js files once the functions are accessible globally
var ctInitComplete = false;
var sevLevels = {
ERROR : 0, //Red
WARNING : 1, //Orange
NOTICE : 2, //Blue
INFO : 3, //Green
}
var infraAlertMsgs = {
'UVE_MISSING' : "System Information unavailable",
'PARTIAL_UVE_MISSING' : "Partial System Information",
'CONFIG_MISSING' : "Configuration unavailable",
'CONFIG_IP_MISMATCH' : "Configured IP mismatch",
'IFMAP_DOWN' : "Ifmap connection down",
'BGP_CONFIG_MISMATCH' : "BGP peer configuration mismatch",
'PROCESS_STATES_MISSING': "Process States unavailable",
'DOWN_CNT' : "{0} Down", //Used for displaying "XMPP Peers" & "BGP Peers" in node tooltip
'BGP_PEER_DOWN' : "{0:BGP Peer;BGP Peers} down",
'XMPP_PEER_DOWN' : "{0:XMPP Peer;XMPP Peers} down",
'INTERFACE_DOWN' : "{0:Interface;Interfaces} down",
'TIMESTAMP_MISMATCH_BEHIND' : "Browser is {0} behind system time",
'TIMESTAMP_MISMATCH_AHEAD' : "Browser is {0} ahead of system time",
'IFMAP_DOWN' : "Ifmap Connection down",
'PROCESS_DOWN' : "{0:Process;Processes} down",
'PROCESS_STARTING' : "{0:Process;Processes} starting",
'PROCESS_STOPPED' : "{0} stopped",
'PROCESS_DOWN_MSG' : "{0} down",
'PROCESS_STARTING_MSG' : "{0} starting",
'PROCESS_COREDUMP' : "{0:core dump;core dumps}",
'PROCESS_RESTART' : "{0:restart;restarts}",
'SPACE_THRESHOLD_EXCEEDED' : '{0} space usage exceeds threshold',
'SPACE_USAGE_WARNING' : '{0} space usage warning',
'NTP_UNSYNCED_ERROR' : 'NTP state unsynchronized'
}
////Contant to check if a nodemanger is installed in the setup or not and use is appropriately
var IS_NODE_MANAGER_INSTALLED = true;
var NO_RELOAD_JS_CLASSLIST = [
'infraMonitorView',
'tenantNetworkMonitorView',
'clustersPageLoader',
'serversPageLoader',
'imagesPageLoader',
'packagesPageLoader',
'smLoader',
'mnPageLoader'
];
//Sets the following prototype if not defined already.
//Array.prototype.unique - returns unique values of an array.
//Array.prototype.diff - difference between two arrays.
//Array.prototype.move - moves an element from one index to another.
//String.prototype.trim - trims 'spaces' of a string, both preceeding and succeeding.
initializePrototypes();
function initializePrototypes() {
if (!String.prototype.trim) {
String.prototype.trim = function () {
return
this.replace(/(?:(?:^|\n)s+|s+(?:$|\n))/g, "").replace(/s+/g, " ");
};
}
if (!Array.prototype.diff) {
Array.prototype.diff = function(a) {
return this.filter(function(i) {return !(a.indexOf(i) > -1);});
};
}
if (!Array.prototype.unique) {
Array.prototype.unique = function() {
var unique = [];
for (var i = 0; i < this.length; i++) {
if (unique.indexOf(this[i]) == -1) {
unique.push(this[i]);
}
}
return unique;
};
}
if (!Array.prototype.move) {
Array.prototype.move = function (old_index, new_index) {
while (old_index < 0) {
old_index += this.length;
}
while (new_index < 0) {
new_index += this.length;
}
if (new_index >= this.length) {
var k = new_index - this.length;
while ((k--) + 1) {
this.push(undefined);
}
}
this.splice(new_index, 0, this.splice(old_index, 1)[0]);
return this;
};
}
}
function collapseElement(e,collapseDivID) {
if($(e).prop("tagName").toUpperCase() == "I"){
$(e).toggleClass('icon-caret-right').toggleClass('icon-caret-down');
} else {
$(e).find("i.icon-caret-right,i.icon-caret-down").toggleClass('icon-caret-right').toggleClass('icon-caret-down');
}
//var widgetBodyElem = $(e).parents('div.widget-box').find('div.widget-body');
var widgetBoxElem;
if(collapseDivID != null && collapseDivID != "" && collapseDivID != undefined){
widgetBoxElem = $(collapseDivID);
// widgetBoxElem.toggleClass('hide');
}
else
widgetBoxElem = $(e).parents('div.widget-box');
$(widgetBoxElem).toggleClass('collapsed');
}
var siteMap = {};
var siteMapSearchStrings = [];
function keys(obj) {
var count = 0;
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
count++;
}
}
return count;
}
var defaultSeriesColors = [ "#70b5dd", "#1083c7", "#1c638d" ];
var defColors = ['#1c638d', '#4DA3D5'];
(function ($) {
$.extend($.fn, {
initWidgetHeader:function (data) {
var widgetHdrTemplate = contrail.getTemplate4Id("widget-header-template");
$(this).html(widgetHdrTemplate(data));
if(data['widgetBoxId'] != undefined){
startWidgetLoading(data['widgetBoxId']);
}
if (data['link'] != null)
$(this).find('span').addClass('href-link');
$(this).find('span').on('click', function () {
if ((data['link'] != null) && (data['link']['hashParams'] != null))
layoutHandler.setURLHashObj(data['link']['hashParams']);
});
},
initPortDistributionCharts:function (data) {
var chartsTemplate = contrail.getTemplate4Id('port-distribution-charts-template');
var networkChart, chartSelector;
if ((data['chartType'] == null) && ($.inArray(ifNull(data['context'], ''), ['domain', 'network', 'connected-nw', 'project', 'instance']) > -1)) {
networkChart = true;
chartSelector = '.port-distribution-chart';
} else {
networkChart = false;
//chartSelector = '.d3-chart';
chartSelector = '.port-distribution-chart';
}
$(this).html(chartsTemplate(data));
if (networkChart == true) {
//Add durationStr
$.each(data['d'], function (idx, obj) {
if (ifNull(obj['duration'], true)) {
if (obj['title'].indexOf('(') < 0)
obj['title'] += durationStr;
}
});
//Set the chart height to parent height - title height
}
//$(this).find('.stack-chart').setAvblSize();
var charts = $(this).find(chartSelector);
$.each(charts, function (idx, chart) {
//Bind the function to pass on the context of url & objectType to schema parse function
var chartData = data['d'][idx];
var chartType = ifNull(chartData['chartType'], '');
var fields;
var objectType = chartData['objectType'];
//Load asynchronously
initDeferred($.extend({},chartData,{selector:$(this),renderFn:'initScatterChart'}));
//If title is clickable
});
},
initCharts:function (data) {
var chartsTemplate = contrail.getTemplate4Id('charts-template');
var networkChart, chartSelector;
if ((data['chartType'] == null) && ($.inArray(ifNull(data['context'], ''), ['domain', 'network', 'connected-nw', 'project', 'instance']) > -1)) {
networkChart = true;
chartSelector = '.stack-chart';
} else {
networkChart = false;
//chartSelector = '.d3-chart';
chartSelector = '.stack-chart';
}
$(this).html(chartsTemplate(data));
if (networkChart == true) {
//Add durationStr
$.each(data['d'], function (idx, obj) {
if (ifNull(obj['duration'], true)) {
if (obj['title'].indexOf('(') < 0)
obj['title'] += durationStr;
}
});
//Set the chart height to parent height - title height
}
//$(this).find('.stack-chart').setAvblSize();
var charts = $(this).find(chartSelector);
$.each(charts, function (idx, chart) {
//Bind the function to pass on the context of url & objectType to schema parse function
var chartData = data['d'][idx];
var chartType = ifNull(chartData['chartType'], '');
var fields;
var objectType = chartData['objectType'];
//Load asynchronously
initDeferred($.extend({},chartData,{selector:$(this),renderFn:'initScatterChart'}));
//If title is clickable
if (chartData['link'] != null) {
var titleElem;
if ($(this).siblings('.example-title').length > 0)
titleElem = $(this).siblings('.example-title');
else
titleElem = $(this).parents('.widget-body').siblings('.widget-header').find('h4.smaller');
//titleElem.addClass('chart-title-link');
titleElem.on('click', function () {
if (chartData['link']['hashParams'] == null) {
var viewObj = tenantNetworkMonitorView;
var detailObj = chartData['link'];
//console.info(data['context']);
if (chartData['link']['context'] == 'instance') {
//Get the instance ip from drop-down
var instObj = getSelInstanceFromDropDown();
$.extend(detailObj,
{
ip:instObj['ip_address'],
vnName:instObj['virtual_network']
}
);
}
if (chartData['class'] != null)
viewObj = chartData['class'];
viewObj.loadSubView(detailObj);
} else {
//layoutHandler.setURLHashObj(chartData['link']['hashParams']);
layoutHandler.setURLHashParams(chartData['link']['hashParams']['q'], chartData['link']['conf']);
}
});
}
});
},
initSummaryStats:function (data) {
var statsRowTemplate = Handlebars.compile($('#summary-stats-template').html());
//If data['url'] == null,implies that populating the data will be handled by respective screen
$(this).html(statsRowTemplate(data['list']));
var self = $(this);
var statsElem = $(this);
var statsDatasource;
if (data['url'] != null) {
statsDatasource = new ContrailDataView({
remote:{
ajaxConfig:{
url:data['url']
},
dataParser:function (response) {
if (data['parseFn'] != null)
return data['parseFn'](response);
else
return [response];
},successCallback:function(response) {
statsDatasource.setData(response);
var statViewModel = new (function() {
var self = this;
self.toNetwork = ko.observable('');
self.fromNetwork = ko.observable('');
})();
statViewModel.toNetwork(response[0]['toNetwork']);
statViewModel.fromNetwork(response[0]['fromNetwork']);
ko.applyBindings(statViewModel, statsElem[0]);
}
},
});
} else {
ko.applyBindings(data['viewModel'], statsElem[0]);
}
},
initTemplates:function (data) {
var statsLen = $(this).find('.summary-stats').length;
if (!(data['stats'] instanceof Array))
data['stats'] = [data['stats']];
if (!(data['grids'] instanceof Array))
data['grids'] = [data['grids']];
if (!(data['charts'] instanceof Array))
data['charts'] = [data['charts']];
$(this).find('.summary-stats').each(function (idx) {
$(this).initSummaryStats(data['stats'][idx]);
});
//Assuming that all summary charts will be displayed at the bottom
//console.info($(this).find('.summary-charts').parent().height());
//$(this).find('.summary-charts').setAvblSize();
$(this).find('.summary-charts').each(function (idx) {
var contextObj = getContextObj(data);
$(this).initCharts($.extend({}, data['charts'][idx], {context:data['context']}, contextObj));
});
$(this).find('.port-distribution-charts').each(function (idx) {
var contextObj = getContextObj(data);
$(this).initPortDistributionCharts($.extend({}, data['charts'][idx], {context:data['context']}, contextObj));
});
$(this).find('.z-grid').each(function (idx) {
//If grid height is set pass height as 100%
if ($(this).height() > 0) {
if (data['grids'][idx]['config'] == null)
data['grids'][idx]['config'] = {};
$.extend(data['grids'][idx]['config'], {height:$(this).height()});
}
startWidgetLoading('charts');
$(this).initGrid(data['grids'][idx]);
endWidgetLoading('charts');
});
$(this).find('.ts-chart').each(function (idx) {
$(this).initD3TSChart(data['ts-chart']);
});
if (data['topology'] != null && (typeof data['topology']['renderFn'] == 'function')) {
data['topology']['renderFn']();
//loadGraph();
}
},
initHeatMap:function (response) {
var data=response['res'];
var selector = $(this);
var deferredObj = $.Deferred();
var margin = { top:20, right:0, bottom:100, left:20 },
width = 960 - margin.left - margin.right,
height = 230 - margin.top - margin.bottom,
gridSize = Math.floor(width / 64),
legendElementWidth = gridSize * 2,
buckets = 9,
colors = ["#ffffd9", "#edf8b1", "#c7e9b4", "#7fcdbb", "#41b6c4", "#1d91c0", "#225ea8", "#253494", "#081d58"], // alternatively colorbrewer.YlGnBu[9]
colors = ["white", "#599AC9"]; // alternatively colorbrewer.YlGnBu[9]
var maxValue = d3.max(data, function (d) {
return d.value;
});
if (maxValue == 0)
colors = ['white'];
var colorScale = d3.scale.quantile()
.domain([0, buckets - 1, maxValue])
.range(colors);
var svg = d3.select($(selector)[0]).append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var xValues = [], yValues = [];
for (var i = 0; i < 64; i++) {
xValues.push(i);
}
for (var i = 0; i < 4; i++) {
yValues.push(i);
}
var yLabels = svg.selectAll(".xLabel")
.data(yValues)
.enter().append("text")
//.text(function (d) { return d; })
.attr("x", 0)
.attr("y", function (d, i) {
return i * gridSize;
})
.style("text-anchor", "end")
.attr("transform", "translate(-6," + gridSize / 1.5 + ")")
.attr("class", function (d, i) {
return ((i >= 0 && i <= 4) ? "xLabel mono axis axis-workweek" : "xLabel mono axis");
});
var xLabels = svg.selectAll(".xLabel")
.data(xValues)
.enter().append("text")
//.text(function(d) { return d; })
.attr("x", function (d, i) {
return i * gridSize;
})
.attr("y", 0)
.style("text-anchor", "middle")
.attr("transform", "translate(" + gridSize / 2 + ", -6)")
.attr("class", function (d, i) {
return ((i >= 7 && i <= 16) ? "xLabel mono axis axis-worktime" : "xLabel mono axis");
});
var heatMap = svg.selectAll(".hour")
.data(data)
.enter().append("rect")
.attr("x", function (d) {
return (d.x - 1) * gridSize;
})
.attr("y", function (d) {
return (d.y - 1) * gridSize;
})
//.attr("rx", 4)
//.attr("ry", 4)
.attr("class", "hour bordered")
.attr("width", gridSize)
.attr("height", gridSize)
.style("fill", colors[0]);
heatMap.transition().duration(1000)
.style("fill", function (d) {
return colorScale(d.value);
});
heatMap.on('click',function(d){
var currHashObj = layoutHandler.getURLHashObj();
var startRange = ((64*d.y)+d.x)*256;
var endRange = startRange+255;
var params = {};
var protocolMap={'icmp':1,'tcp':6,'udp':17};
var divId = $($(selector)[0]).attr('id');
params['fqName'] = currHashObj['q']['fqName'];
params['port'] = startRange+"-"+endRange;
params['startTime'] = new XDate().addMinutes(-10).getTime();
params['endTime'] = new XDate().getTime();
params['portType'] = response['type'];
params['protocol'] = protocolMap[response['pType']];
layoutHandler.setURLHashParams(params,{p:'mon_networking_networks'});
});
heatMap.on('mouseover',function(){
d3.select(this).style('cursor','pointer');
});
heatMap.append("title").text(function (d) {
var startRange = ((64 * d.y) + d.x) * 256;
//return 'Hello' + d.value;
return startRange + ' - ' + (startRange + 255);
});
var legend = svg.selectAll(".legend")
.data([0].concat(colorScale.quantiles()), function (d) {
return d;
})
.enter().append("g")
.attr("class", "legend");
/*
legend.append("rect")
.attr("x", function(d, i) { return legendElementWidth * i; })
.attr("y", height)
.attr("width", legendElementWidth)
.attr("height", gridSize / 2)
.style("fill", function(d, i) { return colors[i]; });
legend.append("text")
.attr("class", "mono")
.text(function(d) { return "� " + Math.round(d); })
.attr("x", function(d, i) { return legendElementWidth * i; })
.attr("y", height + gridSize);
*/
//});
},
initSummaryTemplate:function (data) {
//Check for optional elements('ts-chart');
$(this).find('.summary-stats').initSummaryStats(data['stats']);
//$(this).find('.summary-charts').setAvblSize();
$(this).find('.summary-charts').initCharts(data['charts']);
},
//Requires url & columns
initGrid:function (data) {
var gridDetailConfig = { };
if (data['detailParseFn'] != null)
gridDetailConfig = {
template:$('#gridDetailTemplate').html(),
onInit:function (e,dc) {
var detailTemplate = contrail.getTemplate4Id('detailTemplate');
var rowData = e.data;
var grid = $(e['target']).closest('div.contrail-grid');
var dataItem = dc;
//Issue a call for fetching the details
if(dataItem['url'] != null) {
$.ajax({
url:dataItem['url']
}).done(function(result) {
//There will be only one entry in response,look at 0th element as we are requesting for specific VN/VM
var response = result;
if(result['value'] != null && result['value'][0] != null) {
response = result['value'][0];
e.detailRow.find('.row-fluid.advancedDetails').html('<div><pre style="background-color:white">' + syntaxHighlight(response) + '</pre></div>');
//DataItem consists of row data,passing it as a parameter to the parsefunction
e.detailRow.find('.row-fluid.basicDetails').html(detailTemplate(data['detailParseFn'](response,dataItem)));
$(grid).data('contrailGrid').adjustDetailRowHeight(dataItem['cgrid']);
} else if(!isEmptyObject(response)) {
e.detailRow.find('.row-fluid.advancedDetails').html('<div><pre style="background-color:white">' + syntaxHighlight(response) + '</pre></div>');
e.detailRow.find('.row-fluid.basicDetails').html(detailTemplate(data['detailParseFn'](response,dataItem)));
$(grid).data('contrailGrid').adjustDetailRowHeight(dataItem['cgrid']);
} else {
$(e.detailRow).html('<p class="error"><i class="icon-warning"></i>Information unavailable</p>');
}
if(data['rowExpansionCB'] != null && typeof(data['rowExpansionCB'] == 'function')) {
data['rowExpansionCB'](response,dataItem,grid);
}
}).fail(function(){
$(e.detailRow).html('<p class="error"><i class="icon-warning"></i>Error in fetching the details</p>');
});
}
},
onCollapse:function (e,dc) {
}
}
var transportCfg = {};
if(data['timeout'] != null)
transportCfg = {timeout:data['timeout']};
if(data['transportCfg'] != null)
transportCfg = data['transportCfg'];
var dataSource = {
remote:{
ajaxConfig: $.extend({
url:typeof data['url'] == 'function' ? data['url']() : data['url']
},transportCfg),
dataParser: function(response){
if (data['parseFn'] != null) {
if(transportCfg['url'] == '/api/tenant/get-data')
return data['parseFn'](response[0]);
else
return data['parseFn'](response);
} else
return response;
}
}
};
if(data['dataSource'] != null)
dataSource = {dataView: data['dataSource']};
if(data['isAsyncLoad'])
data['config']['showLoading'] = true;
if (data != null) {
var kGrid = $(this).contrailGrid($.extend({
header : {
title: {
text: data['config']['widgetGridTitle']
},
customControls:ifNull(data['config']['widgetGridActions'],[])
},
body: {
options: {
forceFitColumns:true,
enableColumnReorder:true,
detail: !$.isEmptyObject(gridDetailConfig) ? gridDetailConfig : false,
sortable:true,
lazyLoading: data['isAsyncLoad'] != null ? data['isAsyncLoad'] : false,
actionCell: data['config']['actionCell']
},
dataSource: dataSource,
statusMessages: {
loading: {
text: 'Loading..',
},
empty: {
text: ifNull(data['config']['noMsg'],'No data to display')
},
errorGettingData: {
type: 'error',
iconClasses: 'icon-warning',
text: 'Error in fetching the details'
}
}
},
columnHeader: {
columns:data['columns'],
},
/*dataBound:function (e) {
var sender = e.sender;
$(sender.element).data('loaded', true);
addExtraStylingToGrid(sender);
},
searchToolbar:(data['config'] != null && data['config']['widgetGridTitle'] != null) ? true : false*/
}, data['config']));
var cGrid = $(this).data('contrailGrid');
//If deferredObj is pending and record count is empty..then show loading icon implies that first set of records are not fetched yet
if((data['deferredObj'] != null && data['deferredObj'].state() == 'pending' && data['dataSource'].getItems().length == 0)
|| data['url'] != null) {
cGrid.showGridMessage('loading');
}
//As events will not be triggered on cached dataSource,fire events manually
//widget loading icon will be hidden when the deferredobj resolves or rejects
if(data['deferredObj'] != null) {
if(data['deferredObj'].state() != 'pending' && data['error'] == null)
triggerDatasourceEvents(data['dataSource']);
else if(data['deferredObj'].state() != 'pending' && data['error'] != null && data['errTxt'] != 'abort')
cGrid.showGridMessage('error','Error in fetching the details');
data['deferredObj'].fail(function(errObj){
if(cGrid != null) {
if(errObj['errTxt'] != null && errObj['errTxt'] != 'abort')
cGrid.showGridMessage('error','Error in fetching the details');
}
});
if(data['isAsyncLoad'] == true)
data['deferredObj'].always(function(){
if(cGrid != null) {
cGrid.removeGridLoading();
}
})
}
//Bind deferred Obj
if(data['loadedDeferredObj'] != null)
$(this).data('loadedDeferredObj',data['loadedDeferredObj']);
//calling refreshview, because sometimes the grid seems cluttered with data in the datasource
if(cGrid != null) {
cGrid.refreshView();
}
} else {
$(this).contrailGrid();
}
},
initListTemplate:function (data) {
$(this).find('.z-grid').initGrid(data);
},
getUnusedSize:function (sizingProperty) {
sizingProperty = ifNull(sizingProperty, 'height');
var innerSizingFn, sizingFn, outerSizingFn;
if (sizingProperty == 'height') {
innerSizingFn = 'innerHeight';
sizingFn = 'height';
outerSizingFn = 'outerHeight';
} else {
innerSizingFn = 'innerWidth';
sizingFn = 'width';
outerSizingFn = 'outerWidth';
}
//With box-sizing:border-box, innerHeight is more than height!!
var parentSize = Math.min($(this).parent()[innerSizingFn](), $(this).parent()[sizingFn]());
//console.info('parentSize:',parentSize);
//if($(this).parent()[0].style.height == 'auto')
if (parentSize < 1)
parentSize = $(this).parent().parent()[innerSizingFn]();
var siblingsSize = 0;
//Handle vertical margin collapse scenario
$(this).siblings().each(function () {
//Exclude hidden siblings;
if ($(this).is(':visible') == false)
return;
siblingsSize += $(this)[outerSizingFn](true);
//console.info($(this),$(this).outerHeight(true));
});
//console.info(parentSize,parentSize-siblingsSize);
return parentSize - siblingsSize;
},
setAvblSize:function (sizingProperty, buffer) {
sizingProperty = ifNull(sizingProperty, 'height');
var sizingFn;
buffer = ifNull(buffer, 0);
if (sizingProperty == 'height')
sizingFn = 'height';
else
sizingFn = 'width';
//To work for an array of elements
$(this).each(function () {
var unusedSize = $(this).getUnusedSize(sizingProperty);
//logMessage('Setting Height:',$(this),unusedHeight);
$(this)[sizingFn](unusedSize - buffer);
});
}
});
})(jQuery);
function formatLblValueTooltip(infoObj) {
var tooltipTemplateSel = 'title-lblval-tooltip-template';
var tooltipTemplate = contrail.getTemplate4Id(tooltipTemplateSel);
return tooltipTemplate(infoObj);
}
function formatLblValueMultiTooltip(data) {
var tooltipTemplateSel = 'overlapped-bubble-tooltip';
var tooltipTemplate = contrail.getTemplate4Id(tooltipTemplateSel);
return tooltipTemplate(data);
}
/**
* As dataSource events don't trigger on cached dataSource's, trigger events manually
*/
function triggerDatasourceEvents(dataSource){
if(dataSource != null) {
$(dataSource).trigger('change');
}
}
function prettifyBytes(obj) {
var bytes = obj['bytes'];
var maxPrecision = obj['maxPrecision'];
var noDecimal = obj['noDecimal'];
var stripUnit = obj['stripUnit'];
if (!$.isNumeric(bytes))
return '-';
if (bytes == 0)
return (stripUnit != null) ? 0 : '0 B';
var formatStr = '';
var decimalDigits = 2;
if ((maxPrecision != null) && (maxPrecision == true))
decimalDigits = 6;
if (noDecimal != null && noDecimal == true)
decimalDigits = 0;
//Ensure that bytes is always positive
bytes = parseInt(bytes);
bytes = makePositive(bytes);
var bytePrefixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB'];
var multipliers = [
1, //B
1024, //KB
1024 * 1024, //MB
1024 * 1024 * 1024, //GB
1024 * 1024 * 1024 * 1024, //TB
1024 * 1024 * 1024 * 1024 * 1024, //PB
1024 * 1024 * 1024 * 1024 * 1024 * 1024, //EB
1024 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024 //ZB
];
var prefixIdx = 0;
var multiplier = 1;
if ($.inArray(obj['prefix'], bytePrefixes) > -1) {
prefixIdx = $.inArray(obj['prefix'], bytePrefixes);
multiplier = multipliers[prefixIdx];
} else
$.each(bytePrefixes, function (idx, prefix) {
//Can be converted into higher unit
if (bytes / multiplier > 1024) {
multiplier = multiplier * 1024;
prefixIdx++;
} else
return false;
});
if (stripUnit != null)
formatStr = parseFloat((bytes / multiplier).toFixed(decimalDigits));
else
formatStr = contrail.format('{0} {1}', (bytes / multiplier).toFixed(decimalDigits), bytePrefixes[prefixIdx]);
logMessage('formatBytes', bytes, multiplier, prefixIdx, bytes / multiplier);
return formatStr;
}
/*
* This function formats the Throughput value if the input is integer/float which inturn uses the
* formatBytes function
* example of output 1234 bps
*/
function formatThroughput(bytes,noDecimal,maxPrecision) {
var data = formatBytes(bytes,noDecimal,maxPrecision);
if(data != '-')
return data.replace('B','b') + 'ps';
else
return '-';
}
function formatBytes(bytes, noDecimal, maxPrecision, precision) {
if (!$.isNumeric(bytes))
return '-';
if (bytes == 0)
return '0 B';
var formatStr = '';
var decimalDigits = 2;
if ((maxPrecision != null) && (maxPrecision == true)) {
decimalDigits = 6;
} else if(precision != null) {
decimalDigits = precision < 7 ? precision : 6;
}
if (noDecimal != null && noDecimal == true)
decimalDigits = 0;
//Ensure that bytes is always positive
bytes = parseInt(bytes);
bytes = makePositive(bytes);
var bytePrefixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB']
$.each(bytePrefixes, function (idx, prefix) {
if (bytes < 1024) {
formatStr = contrail.format('{0} {1}', parseFloat(bytes.toFixed(decimalDigits)), prefix);
return false;
} else {
//last iteration
if (idx == (bytePrefixes.length - 1))
formatStr = contrail.format('{0} {1}', parseFloat(bytes.toFixed(decimalDigits)), prefix);
else
bytes = bytes / 1024;
}
});
return formatStr;
}
function formatNumberByCommas(num) {
var numString = num.toString().split("").reverse(),
formattedNumstring = [],
numStringLength = numString.length;
for (var i = 0 ; i < numStringLength; i = i + 3) {
if (numStringLength - i < 3) {
formattedNumstring = formattedNumstring.concat(numString.slice(i, numStringLength));
} else {
formattedNumstring = formattedNumstring.concat(numString.slice(i, i + 3));
if (numStringLength - i > 3) {
formattedNumstring = formattedNumstring.concat([',']);
}
}
}
return formattedNumstring.reverse().join('');
}
function convertToBytes(formattedBytes) {
var formatStr;
var decimalDigits = 2;
var arr = formattedBytes.split(" ");
var value = arr[0];
var unit = arr[1];
var unitMultiplier = {'B':1, 'KB':1024, 'MB':1024 * 1024, 'GB':1024 * 1024 * 1024};
return value * unitMultiplier[unit];
}
function fixDecimals(number, maxPrecision) {
try {
return parseInt(number).toFixed(maxPrecision);
} catch (e) {
return number;
}
}
function ifNull(value, defValue) {
if (value == null)
return defValue;
else
return value;
}
function ifNotNumeric(value,defValue) {
if($.isNumeric(value))
return value;
else
return defValue;
}
function ifNullOrEmptyObject(value, defValue) {
//If value is null or an empty object
if (value == null || ($.isPlainObject(value) && $.isEmptyObject(value)))
return defValue;
else
return value;
}
function ifEmpty(value, defValue) {
if (value == '')
return defValue;
else
return value;
}
function ifNullOrEmpty(value, defValue) {
if (value == null || value == '')
return defValue;
else
return value;
}
function ifNotEmpty(value,defValue) {
if(value != '')
return defValue;
else
value;
}
function makePositive(num) {
if (num < 0)
return -1 * num;
else
return num;
}
function makeNegative(num) {
if (num > 0)
return -1 * num;
else
return num;
}
function dot2num(dot) {
var d = dot.split('.');
return ((((((+d[0]) * 256) + (+d[1])) * 256) + (+d[2])) * 256) + (+d[3]);
}
function num2dot(num) {
var d = num % 256;
for (var i = 3; i > 0; i--) {
num = Math.floor(num / 256);
d = num % 256 + '.' + d;
}
return d;
}
function ip2long(ip) {
if (typeof(ip) != 'string')
return ip;
var ipl = 0;
ip.split('.').forEach(function (octet) {
ipl <<= 8;
ipl += parseInt(octet);
});
return(ipl >>> 0);
}
function long2ip(ipl) {
if (typeof(ipl) != 'number')
return ipl;
return ( (ipl >>> 24) + '.' +
(ipl >> 16 & 255) + '.' +
(ipl >> 8 & 255) + '.' +
(ipl & 255) );
}
function pushBreadcrumb(breadcrumbsArr) {
for (var i = 0; i < breadcrumbsArr.length; i++) {
//Remove active class
$('#breadcrumb').children('li').removeClass('active');
if (i == 0) {
//Add divider icon for previous breadcrumb
$('#breadcrumb').children('li:last').append('<span class="divider"><i class="icon-angle-right"></i></span>')
}
if (i == breadcrumbsArr.length - 1) {
$('#breadcrumb').append('<li class="active"><a>' + breadcrumbsArr[i] + '</a></li>');
} else {
$('#breadcrumb').append('<li><a>' + breadcrumbsArr[i] + '</a><span class="divider"><i class="icon-angle-right"></i></span></li>');
}
}
}
function removeActiveBreadcrumb(breadcrumbsArr) {
if($('#breadcrumb').children('li.active:last')) {
$('#breadcrumb').children('li.active:last').remove();
$('#breadcrumb').children('li:last').children('span').remove();
}
}
function pushBreadcrumbDropdown(id){
$('#breadcrumb').children('li').removeClass('active');
$('#breadcrumb').children('li:last').append('<span class="divider"><i class="icon-angle-right"></i></span>');
$('#breadcrumb').append('<li class="active"><div id="' + id + '"></div></li>');
}
function MenuHandler() {
var self = this;
var menuObj;
//onHashChange is triggered once it is resolved
self.deferredObj = $.Deferred();
var menuDefferedObj = $.Deferred(),statDefferredObj = $.Deferred(),webServerDefObj = $.Deferred();
this.loadMenu = function () {
$.get('/menu.xml?built_at=' + built_at, function (xml) {
$.get('/api/admin/webconfig/features/disabled?built_at=' + built_at, function(disabledFeatures) {
$.get('/api/admin/webconfig/featurePkg/webController?built_at=' + built_at, function(webControllPkg) {
menuObj = $.xml2json(xml);
webServerDefObj.always(function(){
processXMLJSON(menuObj, disabledFeatures);
globalObj['webServerInfo']['disabledFeatures'] = ifNull(disabledFeatures,[]);
var menuShortcuts = contrail.getTemplate4Id('menu-shortcuts')(menuHandler.filterMenuItems(menuObj['items']['item'],'menushortcut', webControllPkg));
$("#sidebar-shortcuts").html(menuShortcuts);
['items']['item'] = menuHandler.filterMenuItems(menuObj['items']['item']);
menuDefferedObj.resolve();
});
});
})
});
//Add an event listener for clicking on menu items
$('#menu').on('click','ul > li > a',function(e) {
var href = $(this).attr('href');
loadFeature($.deparam.fragment(href));
if(!e.ctrlKey){
e.preventDefault();//Stop the page to navigate to the url set in href
}
});
//Compares client UTC time with the server UTC time and display alert if mismatch exceeds the threshold
$.ajax({
url:'/api/service/networking/web-server-info'
}).done(function (response) {
if(response['serverUTCTime'] != null) {
response['timeDiffInMillisecs'] = response['serverUTCTime'] - new Date().getTime();
if(Math.abs(response['timeDiffInMillisecs']) > timeStampTolearence){
if(response['timeDiffInMillisecs'] > 0)