1 // You can set the following variables before loading this script:
3 // var netdataNoDygraphs = true; // do not use dygraph
4 // var netdataNoSparklines = true; // do not use sparkline
5 // var netdataNoPeitys = true; // do not use peity
6 // var netdataNoGoogleCharts = true; // do not use google
7 // var netdataNoMorris = true; // do not use morris
8 // var netdataNoEasyPieChart = true; // do not use easy pie chart
9 // var netdataNoGauge = true; // do not use gauge.js
10 // var netdataNoD3 = true; // do not use D3
11 // var netdataNoC3 = true; // do not use C3
12 // var netdataNoBootstrap = true; // do not load bootstrap
13 // var netdataDontStart = true; // do not start the thread to process the charts
15 // You can also set the default netdata server, using the following.
16 // When this variable is not set, we assume the page is hosted on your
17 // netdata server already.
18 // var netdataServer = "http://yourhost:19999"; // set your NetData server
20 //(function(window, document, undefined) {
21 // fix IE issue with console
22 if(!window.console){ window.console = {log: function(){} }; }
25 var NETDATA = window.NETDATA || {};
27 // ----------------------------------------------------------------------------------------------------------------
28 // Detect the netdata server
30 // http://stackoverflow.com/questions/984510/what-is-my-script-src-url
31 // http://stackoverflow.com/questions/6941533/get-protocol-domain-and-port-from-url
32 NETDATA._scriptSource = function(scripts) {
33 var script = null, base = null;
35 if(typeof document.currentScript !== 'undefined') {
36 script = document.currentScript;
39 var all_scripts = document.getElementsByTagName('script');
40 script = all_scripts[all_scripts.length - 1];
43 if (typeof script.getAttribute.length !== 'undefined')
46 script = script.getAttribute('src', -1);
48 var link = document.createElement('a');
49 link.setAttribute('href', script);
51 if(!link.protocol || !link.hostname) return null;
54 if(base) base += "//";
55 base += link.hostname;
57 if(link.port) base += ":" + link.port;
63 if(typeof netdataServer !== 'undefined')
64 NETDATA.serverDefault = netdataServer;
66 NETDATA.serverDefault = NETDATA._scriptSource();
68 if(NETDATA.serverDefault === null)
69 NETDATA.serverDefault = '';
70 else if(NETDATA.serverDefault.slice(-1) !== '/')
71 NETDATA.serverDefault += '/';
73 // default URLs for all the external files we need
74 // make them RELATIVE so that the whole thing can also be
75 // installed under a web server
76 NETDATA.jQuery = NETDATA.serverDefault + 'lib/jquery-1.12.0.min.js';
77 NETDATA.peity_js = NETDATA.serverDefault + 'lib/jquery.peity.min.js';
78 NETDATA.sparkline_js = NETDATA.serverDefault + 'lib/jquery.sparkline.min.js';
79 NETDATA.easypiechart_js = NETDATA.serverDefault + 'lib/jquery.easypiechart.min.js';
80 NETDATA.gauge_js = NETDATA.serverDefault + 'lib/gauge.min.js';
81 NETDATA.dygraph_js = NETDATA.serverDefault + 'lib/dygraph-combined.js';
82 NETDATA.dygraph_smooth_js = NETDATA.serverDefault + 'lib/dygraph-smooth-plotter.js';
83 NETDATA.raphael_js = NETDATA.serverDefault + 'lib/raphael-min.js';
84 NETDATA.morris_js = NETDATA.serverDefault + 'lib/morris.min.js';
85 NETDATA.d3_js = NETDATA.serverDefault + 'lib/d3.min.js';
86 NETDATA.c3_js = NETDATA.serverDefault + 'lib/c3.min.js';
87 NETDATA.c3_css = NETDATA.serverDefault + 'css/c3.min.css';
88 NETDATA.morris_css = NETDATA.serverDefault + 'css/morris.css';
89 NETDATA.dashboard_css = NETDATA.serverDefault + 'dashboard.css';
90 NETDATA.google_js = 'https://www.google.com/jsapi';
92 // these are the colors Google Charts are using
93 // we have them here to attempt emulate their look and feel on the other chart libraries
94 // http://there4.io/2012/05/02/google-chart-color-list/
95 //NETDATA.colors = [ '#3366CC', '#DC3912', '#FF9900', '#109618', '#990099', '#3B3EAC', '#0099C6',
96 // '#DD4477', '#66AA00', '#B82E2E', '#316395', '#994499', '#22AA99', '#AAAA11',
97 // '#6633CC', '#E67300', '#8B0707', '#329262', '#5574A6', '#3B3EAC' ];
99 NETDATA.colors = [ '#3366CC', '#DC3912', '#109618', '#FF9900', '#990099', '#DD4477', '#3B3EAC',
100 '#66AA00', '#0099C6', '#B82E2E', '#AAAA11', '#5574A6', '#994499', '#22AA99',
101 '#6633CC', '#E67300', '#316395', '#8B0707', '#329262', '#3B3EAC' ];
102 // an alternative set
103 // http://www.mulinblog.com/a-color-palette-optimized-for-data-visualization/
104 // (blue) (red) (orange) (green) (pink) (brown) (purple) (yellow) (gray)
105 //NETDATA.colors = [ '#5DA5DA', '#F15854', '#FAA43A', '#60BD68', '#F17CB0', '#B2912F', '#B276B2', '#DECF3F', '#4D4D4D' ];
107 // ----------------------------------------------------------------------------------------------------------------
108 // the defaults for all charts
110 // if the user does not specify any of these, the following will be used
112 NETDATA.chartDefaults = {
113 host: NETDATA.serverDefault, // the server to get data from
114 width: '100%', // the chart width - can be null
115 height: '100%', // the chart height - can be null
116 min_width: null, // the chart minimum width - can be null
117 library: 'dygraph', // the graphing library to use
118 method: 'average', // the grouping method
119 before: 0, // panning
120 after: -600, // panning
121 pixels_per_point: 1, // the detail of the chart
122 fill_luminance: 0.8 // luminance of colors in solit areas
125 // ----------------------------------------------------------------------------------------------------------------
129 pauseCallback: null, // a callback when we are really paused
131 pause: false, // when enabled we don't auto-refresh the charts
133 targets: null, // an array of all the state objects that are
134 // currently active (independently of their
135 // viewport visibility)
137 updated_dom: true, // when true, the DOM has been updated with
138 // new elements we have to check.
140 auto_refresher_fast_weight: 0, // this is the current time in ms, spent
141 // rendering charts continiously.
142 // used with .current.fast_render_timeframe
144 page_is_visible: true, // when true, this page is visible
146 auto_refresher_stop_until: 0, // timestamp in ms - used internaly, to stop the
147 // auto-refresher for some time (when a chart is
148 // performing pan or zoom, we need to stop refreshing
149 // all other charts, to have the maximum speed for
150 // rendering the chart that is panned or zoomed).
151 // Used with .current.global_pan_sync_time
153 last_resized: 0, // the timestamp of the last resize request
155 crossDomainAjax: false, // enable this to request crossDomain AJAX
157 last_page_scroll: 0, // the timestamp the last time the page was scrolled
159 // the current profile
160 // we may have many...
162 pixels_per_point: 1, // the minimum pixels per point for all charts
163 // increase this to speed javascript up
164 // each chart library has its own limit too
165 // the max of this and the chart library is used
166 // the final is calculated every time, so a change
167 // here will have immediate effect on the next chart
170 idle_between_charts: 100, // ms - how much time to wait between chart updates
172 fast_render_timeframe: 200, // ms - render continously until this time of continious
173 // rendering has been reached
174 // this setting is used to make it render e.g. 10
175 // charts at once, sleep idle_between_charts time
176 // and continue for another 10 charts.
178 idle_between_loops: 500, // ms - if all charts have been updated, wait this
179 // time before starting again.
181 idle_parallel_loops: 100, // ms - the time between parallel refresher updates
183 idle_lost_focus: 500, // ms - when the window does not have focus, check
184 // if focus has been regained, every this time
186 global_pan_sync_time: 1000, // ms - when you pan or zoon a chart, the background
187 // autorefreshing of charts is paused for this amount
190 sync_selection_delay: 1500, // ms - when you pan or zoom a chart, wait this amount
191 // of time before setting up synchronized selections
194 sync_selection: true, // enable or disable selection sync
196 pan_and_zoom_delay: 50, // when panning or zooming, how ofter to update the chart
198 sync_pan_and_zoom: true, // enable or disable pan and zoom sync
200 update_only_visible: true, // enable or disable visibility management
202 parallel_refresher: true, // enable parallel refresh of charts
204 concurrent_refreshes: true, // when parallel_refresher is enabled, sync also the charts
206 destroy_on_hide: false, // destroy charts when they are not visible
208 eliminate_zero_dimensions: true, // do not show dimensions with just zeros
210 stop_updates_when_focus_is_lost: true, // boolean - shall we stop auto-refreshes when document does not have user focus
211 stop_updates_while_resizing: 1000, // ms - time to stop auto-refreshes while resizing the charts
213 double_click_speed: 500, // ms - time between clicks / taps to detect double click/tap
215 smooth_plot: true, // enable smooth plot, where possible
217 color_fill_opacity_line: 1.0,
218 color_fill_opacity_area: 0.2,
219 color_fill_opacity_stacked: 0.8,
221 setOptionCallback: function() { ; }
229 chart_data_url: false,
230 chart_errors: false, // FIXME
239 // ----------------------------------------------------------------------------------------------------------------
240 // local storage options
242 NETDATA.localStorage = {
245 callback: {} // only used for resetting back to defaults
248 NETDATA.localStorageGet = function(key, def, callback) {
251 if(typeof NETDATA.localStorage.default[key.toString()] === 'undefined') {
252 NETDATA.localStorage.default[key.toString()] = def;
253 NETDATA.localStorage.callback[key.toString()] = callback;
256 if(typeof Storage !== "undefined" && typeof localStorage === 'object') {
258 // console.log('localStorage: loading "' + key.toString() + '"');
259 ret = localStorage.getItem(key.toString());
260 if(ret === null || ret === 'undefined') {
261 // console.log('localStorage: cannot load it, saving "' + key.toString() + '" with value "' + JSON.stringify(def) + '"');
262 localStorage.setItem(key.toString(), JSON.stringify(def));
266 // console.log('localStorage: got "' + key.toString() + '" with value "' + ret + '"');
267 ret = JSON.parse(ret);
268 // console.log('localStorage: loaded "' + key.toString() + '" as value ' + ret + ' of type ' + typeof(ret));
272 console.log('localStorage: failed to read "' + key.toString() + '", using default: "' + def.toString() + '"');
277 if(typeof ret === 'undefined' || ret === 'undefined') {
278 console.log('localStorage: LOADED UNDEFINED "' + key.toString() + '" as value ' + ret + ' of type ' + typeof(ret));
282 NETDATA.localStorage.current[key.toString()] = ret;
286 NETDATA.localStorageSet = function(key, value, callback) {
287 if(typeof value === 'undefined' || value === 'undefined') {
288 console.log('localStorage: ATTEMPT TO SET UNDEFINED "' + key.toString() + '" as value ' + value + ' of type ' + typeof(value));
291 if(typeof NETDATA.localStorage.default[key.toString()] === 'undefined') {
292 NETDATA.localStorage.default[key.toString()] = value;
293 NETDATA.localStorage.current[key.toString()] = value;
294 NETDATA.localStorage.callback[key.toString()] = callback;
297 if(typeof Storage !== "undefined" && typeof localStorage === 'object') {
298 // console.log('localStorage: saving "' + key.toString() + '" with value "' + JSON.stringify(value) + '"');
300 localStorage.setItem(key.toString(), JSON.stringify(value));
303 console.log('localStorage: failed to save "' + key.toString() + '" with value: "' + value.toString() + '"');
307 NETDATA.localStorage.current[key.toString()] = value;
311 NETDATA.localStorageGetRecursive = function(obj, prefix, callback) {
313 if(typeof obj[i] === 'object') {
314 //console.log('object ' + prefix + '.' + i.toString());
315 NETDATA.localStorageGetRecursive(obj[i], prefix + '.' + i.toString(), callback);
319 obj[i] = NETDATA.localStorageGet(prefix + '.' + i.toString(), obj[i], callback);
323 NETDATA.setOption = function(key, value) {
324 if(key.toString() === 'setOptionCallback') {
325 if(typeof NETDATA.options.current.setOptionCallback === 'function') {
326 NETDATA.options.current[key.toString()] = value;
327 NETDATA.options.current.setOptionCallback();
330 else if(NETDATA.options.current[key.toString()] !== value) {
331 var name = 'options.' + key.toString();
333 if(typeof NETDATA.localStorage.default[name.toString()] === 'undefined')
334 console.log('localStorage: setOption() on unsaved option: "' + name.toString() + '", value: ' + value);
336 //console.log(NETDATA.localStorage);
337 //console.log('setOption: setting "' + key.toString() + '" to "' + value + '" of type ' + typeof(value) + ' original type ' + typeof(NETDATA.options.current[key.toString()]));
338 //console.log(NETDATA.options);
339 NETDATA.options.current[key.toString()] = NETDATA.localStorageSet(name.toString(), value, null);
341 if(typeof NETDATA.options.current.setOptionCallback === 'function')
342 NETDATA.options.current.setOptionCallback();
348 NETDATA.getOption = function(key) {
349 return NETDATA.options.current[key.toString()];
352 // read settings from local storage
353 NETDATA.localStorageGetRecursive(NETDATA.options.current, 'options', null);
355 // always start with this option enabled.
356 NETDATA.setOption('stop_updates_when_focus_is_lost', true);
358 NETDATA.resetOptions = function() {
359 for(var i in NETDATA.localStorage.default) {
360 var a = i.split('.');
362 if(a[0] === 'options') {
363 if(a[1] === 'setOptionCallback') continue;
364 if(typeof NETDATA.localStorage.default[i] === 'undefined') continue;
365 if(NETDATA.options.current[i] === NETDATA.localStorage.default[i]) continue;
367 NETDATA.setOption(a[1], NETDATA.localStorage.default[i]);
369 else if(a[0] === 'chart_heights') {
370 if(typeof NETDATA.localStorage.callback[i] === 'function' && typeof NETDATA.localStorage.default[i] !== 'undefined') {
371 NETDATA.localStorage.callback[i](NETDATA.localStorage.default[i]);
377 // ----------------------------------------------------------------------------------------------------------------
379 if(NETDATA.options.debug.main_loop === true)
380 console.log('welcome to NETDATA');
382 NETDATA.onresize = function() {
383 NETDATA.options.last_resized = new Date().getTime();
387 NETDATA.onscroll = function() {
388 // console.log('onscroll');
390 NETDATA.options.last_page_scroll = new Date().getTime();
391 if(NETDATA.options.targets === null) return;
393 // when the user scrolls he sees that we have
394 // hidden all the not-visible charts
395 // using this little function we try to switch
396 // the charts back to visible quickly
397 var targets = NETDATA.options.targets;
398 var len = targets.length;
399 while(len--) targets[len].isVisible();
402 window.onresize = NETDATA.onresize;
403 window.onscroll = NETDATA.onscroll;
405 // ----------------------------------------------------------------------------------------------------------------
408 NETDATA.errorCodes = {
409 100: { message: "Cannot load chart library", alert: true },
410 101: { message: "Cannot load jQuery", alert: true },
411 402: { message: "Chart library not found", alert: false },
412 403: { message: "Chart library not enabled/is failed", alert: false },
413 404: { message: "Chart not found", alert: false }
415 NETDATA.errorLast = {
421 NETDATA.error = function(code, msg) {
422 NETDATA.errorLast.code = code;
423 NETDATA.errorLast.message = msg;
424 NETDATA.errorLast.datetime = new Date().getTime();
426 console.log("ERROR " + code + ": " + NETDATA.errorCodes[code].message + ": " + msg);
428 if(NETDATA.errorCodes[code].alert)
429 alert("ERROR " + code + ": " + NETDATA.errorCodes[code].message + ": " + msg);
432 NETDATA.errorReset = function() {
433 NETDATA.errorLast.code = 0;
434 NETDATA.errorLast.message = "You are doing fine!";
435 NETDATA.errorLast.datetime = 0;
438 // ----------------------------------------------------------------------------------------------------------------
441 // When multiple charts need the same chart, we avoid downloading it
442 // multiple times (and having it in browser memory multiple time)
443 // by using this registry.
445 // Every time we download a chart definition, we save it here with .add()
446 // Then we try to get it back with .get(). If that fails, we download it.
448 NETDATA.chartRegistry = {
451 fixid: function(id) {
452 return id.replace(/:/g, "_").replace(/\//g, "_");
455 add: function(host, id, data) {
456 host = this.fixid(host);
459 if(typeof this.charts[host] === 'undefined')
460 this.charts[host] = {};
462 //console.log('added ' + host + '/' + id);
463 this.charts[host][id] = data;
466 get: function(host, id) {
467 host = this.fixid(host);
470 if(typeof this.charts[host] === 'undefined')
473 if(typeof this.charts[host][id] === 'undefined')
476 //console.log('cached ' + host + '/' + id);
477 return this.charts[host][id];
480 downloadAll: function(host, callback) {
481 while(host.slice(-1) === '/')
482 host = host.substring(0, host.length - 1);
487 url: host + '/api/v1/charts',
488 crossDomain: NETDATA.options.crossDomainAjax,
492 .done(function(data) {
493 var h = NETDATA.chartRegistry.fixid(host);
494 //console.log('downloaded all charts from ' + host + ' (' + h + ')');
495 self.charts[h] = data.charts;
496 if(typeof callback === 'function')
500 if(typeof callback === 'function')
506 // ----------------------------------------------------------------------------------------------------------------
507 // Global Pan and Zoom on charts
509 // Using this structure are synchronize all the charts, so that
510 // when you pan or zoom one, all others are automatically refreshed
511 // to the same timespan.
513 NETDATA.globalPanAndZoom = {
514 seq: 0, // timestamp ms
515 // every time a chart is panned or zoomed
516 // we set the timestamp here
517 // then we use it as a sequence number
518 // to find if other charts are syncronized
521 master: null, // the master chart (state), to which all others
524 force_before_ms: null, // the timespan to sync all other charts
525 force_after_ms: null,
528 setMaster: function(state, after, before) {
529 if(NETDATA.options.current.sync_pan_and_zoom === false)
532 if(this.master !== null && this.master !== state)
533 this.master.resetChart(true, true);
535 var now = new Date().getTime();
538 this.force_after_ms = after;
539 this.force_before_ms = before;
540 NETDATA.options.auto_refresher_stop_until = now + NETDATA.options.current.global_pan_sync_time;
544 clearMaster: function() {
545 if(this.master !== null) {
546 var st = this.master;
553 this.force_after_ms = null;
554 this.force_before_ms = null;
555 NETDATA.options.auto_refresher_stop_until = 0;
558 // is the given state the master of the global
559 // pan and zoom sync?
560 isMaster: function(state) {
561 if(this.master === state) return true;
565 // are we currently have a global pan and zoom sync?
566 isActive: function() {
567 if(this.master !== null && this.force_before_ms !== null && this.force_after_ms !== null && this.seq !== 0) return true;
571 // check if a chart, other than the master
572 // needs to be refreshed, due to the global pan and zoom
573 shouldBeAutoRefreshed: function(state) {
574 if(this.master === null || this.seq === 0)
577 if(state.needsRecreation())
580 if(state.tm.pan_and_zoom_seq === this.seq)
587 // ----------------------------------------------------------------------------------------------------------------
588 // dimensions selection
591 // move color assignment to dimensions, here
593 dimensionStatus = function(parent, label, name_div, value_div, color) {
594 this.enabled = false;
595 this.parent = parent;
597 this.name_div = null;
598 this.value_div = null;
601 if(parent.selected === parent.unselected)
602 this.selected = true;
604 this.selected = false;
606 this.setOptions(name_div, value_div, color);
609 dimensionStatus.prototype.invalidate = function() {
610 this.name_div = null;
611 this.value_div = null;
612 this.enabled = false;
615 dimensionStatus.prototype.setOptions = function(name_div, value_div, color) {
618 if(this.name_div != name_div) {
619 this.name_div = name_div;
620 this.name_div.title = this.label;
621 this.name_div.style.color = this.color;
622 if(this.selected === false)
623 this.name_div.className = 'netdata-legend-name not-selected';
625 this.name_div.className = 'netdata-legend-name selected';
628 if(this.value_div != value_div) {
629 this.value_div = value_div;
630 this.value_div.title = this.label;
631 this.value_div.style.color = this.color;
632 if(this.selected === false)
633 this.value_div.className = 'netdata-legend-value not-selected';
635 this.value_div.className = 'netdata-legend-value selected';
642 dimensionStatus.prototype.setHandler = function() {
643 if(this.enabled === false) return;
647 // this.name_div.onmousedown = this.value_div.onmousedown = function(e) {
648 this.name_div.onclick = this.value_div.onclick = function(e) {
650 if(ds.isSelected()) {
652 if(e.shiftKey === true || e.ctrlKey === true) {
653 // control or shift key is pressed -> unselect this (except is none will remain selected, in which case select all)
656 if(ds.parent.countSelected() === 0)
657 ds.parent.selectAll();
660 // no key is pressed -> select only this (except if it is the only selected already, in which case select all)
661 if(ds.parent.countSelected() === 1) {
662 ds.parent.selectAll();
665 ds.parent.selectNone();
671 // this is not selected
672 if(e.shiftKey === true || e.ctrlKey === true) {
673 // control or shift key is pressed -> select this too
677 // no key is pressed -> select only this
678 ds.parent.selectNone();
683 ds.parent.state.redrawChart();
687 dimensionStatus.prototype.select = function() {
688 if(this.enabled === false) return;
690 this.name_div.className = 'netdata-legend-name selected';
691 this.value_div.className = 'netdata-legend-value selected';
692 this.selected = true;
695 dimensionStatus.prototype.unselect = function() {
696 if(this.enabled === false) return;
698 this.name_div.className = 'netdata-legend-name not-selected';
699 this.value_div.className = 'netdata-legend-value hidden';
700 this.selected = false;
703 dimensionStatus.prototype.isSelected = function() {
704 return(this.enabled === true && this.selected === true);
707 // ----------------------------------------------------------------------------------------------------------------
709 dimensionsVisibility = function(state) {
712 this.dimensions = {};
713 this.selected_count = 0;
714 this.unselected_count = 0;
717 dimensionsVisibility.prototype.dimensionAdd = function(label, name_div, value_div, color) {
718 if(typeof this.dimensions[label] === 'undefined') {
720 this.dimensions[label] = new dimensionStatus(this, label, name_div, value_div, color);
723 this.dimensions[label].setOptions(name_div, value_div, color);
725 return this.dimensions[label];
728 dimensionsVisibility.prototype.dimensionGet = function(label) {
729 return this.dimensions[label];
732 dimensionsVisibility.prototype.invalidateAll = function() {
733 for(var d in this.dimensions)
734 this.dimensions[d].invalidate();
737 dimensionsVisibility.prototype.selectAll = function() {
738 for(var d in this.dimensions)
739 this.dimensions[d].select();
742 dimensionsVisibility.prototype.countSelected = function() {
744 for(var d in this.dimensions)
745 if(this.dimensions[d].isSelected()) i++;
750 dimensionsVisibility.prototype.selectNone = function() {
751 for(var d in this.dimensions)
752 this.dimensions[d].unselect();
755 dimensionsVisibility.prototype.selected2BooleanArray = function(array) {
756 var ret = new Array();
757 this.selected_count = 0;
758 this.unselected_count = 0;
760 for(var i = 0, len = array.length; i < len ; i++) {
761 var ds = this.dimensions[array[i]];
762 if(typeof ds === 'undefined') {
763 // console.log(array[i] + ' is not found');
768 if(ds.isSelected()) {
770 this.selected_count++;
774 this.unselected_count++;
778 if(this.selected_count === 0 && this.unselected_count !== 0) {
780 return this.selected2BooleanArray(array);
787 // ----------------------------------------------------------------------------------------------------------------
788 // global selection sync
790 NETDATA.globalSelectionSync = {
797 if(this.state !== null)
798 this.state.globalSelectionSyncStop();
802 if(this.state !== null) {
803 this.state.globalSelectionSyncDelay();
808 // ----------------------------------------------------------------------------------------------------------------
809 // Our state object, where all per-chart values are stored
811 chartState = function(element) {
812 var self = $(element);
813 this.element = element;
816 // all private functions should use 'that', instead of 'this'
820 * show an error instead of the chart
822 var error = function(msg) {
823 that.element.innerHTML = that.id + ': ' + msg;
824 that.enabled = false;
825 that.current = that.pan;
828 // GUID - a unique identifier for the chart
829 this.uuid = NETDATA.guid();
831 // string - the name of chart
832 this.id = self.data('netdata');
834 // string - the key for localStorage settings
835 this.settings_id = self.data('id') || null;
837 // the user given dimensions of the element
838 this.width = self.data('width') || NETDATA.chartDefaults.width;
839 this.height = self.data('height') || NETDATA.chartDefaults.height;
841 if(this.settings_id !== null) {
842 this.height = NETDATA.localStorageGet('chart_heights.' + this.settings_id, this.height, function(height) {
843 // this is the callback that will be called
844 // if and when the user resets all localStorage variables
847 resizeChartToHeight(height);
851 // string - the netdata server URL, without any path
852 this.host = self.data('host') || NETDATA.chartDefaults.host;
854 // make sure the host does not end with /
855 // all netdata API requests use absolute paths
856 while(this.host.slice(-1) === '/')
857 this.host = this.host.substring(0, this.host.length - 1);
859 // string - the grouping method requested by the user
860 this.method = self.data('method') || NETDATA.chartDefaults.method;
862 // the time-range requested by the user
863 this.after = self.data('after') || NETDATA.chartDefaults.after;
864 this.before = self.data('before') || NETDATA.chartDefaults.before;
866 // the pixels per point requested by the user
867 this.pixels_per_point = self.data('pixels-per-point') || 1;
868 this.points = self.data('points') || null;
870 // the dimensions requested by the user
871 this.dimensions = self.data('dimensions') || null;
873 // the chart library requested by the user
874 this.library_name = self.data('chart-library') || NETDATA.chartDefaults.library;
876 // object - the chart library used
881 this.colors_assigned = {};
882 this.colors_available = null;
884 // the element already created by the user
885 this.element_message = null;
887 // the element with the chart
888 this.element_chart = null;
890 // the element with the legend of the chart (if created by us)
891 this.element_legend = null;
892 this.element_legend_childs = {
902 this.chart_url = null; // string - the url to download chart info
903 this.chart = null; // object - the chart as downloaded from the server
905 this.title = self.data('title') || null; // the title of the chart
906 this.units = self.data('units') || null; // the units of the chart dimensions
907 this.append_options = self.data('append-options') || null; // the units of the chart dimensions
909 this.validated = false; // boolean - has the chart been validated?
910 this.enabled = true; // boolean - is the chart enabled for refresh?
911 this.paused = false; // boolean - is the chart paused for any reason?
912 this.selected = false; // boolean - is the chart shown a selection?
913 this.debug = false; // boolean - console.log() debug info about this chart
915 this.netdata_first = 0; // milliseconds - the first timestamp in netdata
916 this.netdata_last = 0; // milliseconds - the last timestamp in netdata
917 this.requested_after = null; // milliseconds - the timestamp of the request after param
918 this.requested_before = null; // milliseconds - the timestamp of the request before param
923 force_update_at: 0, // the timestamp to force the update at
924 force_before_ms: null,
930 force_update_at: 0, // the timestamp to force the update at
931 force_before_ms: null,
937 force_update_at: 0, // the timestamp to force the update at
938 force_before_ms: null,
942 // this is a pointer to one of the sub-classes below
944 this.current = this.auto;
946 // check the requested library is available
947 // we don't initialize it here - it will be initialized when
948 // this chart will be first used
949 if(typeof NETDATA.chartLibraries[that.library_name] === 'undefined') {
950 NETDATA.error(402, that.library_name);
951 error('chart library "' + that.library_name + '" is not found');
954 else if(NETDATA.chartLibraries[that.library_name].enabled === false) {
955 NETDATA.error(403, that.library_name);
956 error('chart library "' + that.library_name + '" is not enabled');
960 that.library = NETDATA.chartLibraries[that.library_name];
962 // milliseconds - the time the last refresh took
963 this.refresh_dt_ms = 0;
965 // if we need to report the rendering speed
966 // find the element that needs to be updated
967 var refresh_dt_element_name = self.data('dt-element-name') || null; // string - the element to print refresh_dt_ms
969 if(refresh_dt_element_name !== null)
970 this.refresh_dt_element = document.getElementById(refresh_dt_element_name) || null;
972 this.refresh_dt_element = null;
974 this.dimensions_visibility = new dimensionsVisibility(this);
976 // ============================================================================================================
979 var createDOM = function() {
980 if(that.enabled === false) return;
982 if(that.element_message !== null) that.element_message.innerHTML = '';
983 if(that.element_legend !== null) that.element_legend.innerHTML = '';
984 if(that.element_chart !== null) that.element_chart.innerHTML = '';
986 that.element.innerHTML = '';
988 that.element_message = document.createElement('div');
989 that.element_message.className = ' netdata-message hidden';
990 that.element.appendChild(that.element_message);
992 that.element_chart = document.createElement('div');
993 that.element_chart.id = that.library_name + '-' + that.uuid + '-chart';
994 that.element.appendChild(that.element_chart);
996 if(that.hasLegend() === true) {
997 that.element.className = "netdata-container-with-legend";
998 that.element_chart.className = 'netdata-chart-with-legend-right netdata-' + that.library_name + '-chart-with-legend-right';
1000 that.element_legend = document.createElement('div');
1001 that.element_legend.className = 'netdata-chart-legend netdata-' + that.library_name + '-legend';
1002 that.element.appendChild(that.element_legend);
1005 that.element.className = "netdata-container";
1006 that.element_chart.className = ' netdata-chart netdata-' + that.library_name + '-chart';
1008 that.element_legend = null;
1010 that.element_legend_childs.series = null;
1012 if(typeof(that.width) === 'string')
1013 $(that.element).css('width', that.width);
1014 else if(typeof(that.width) === 'number')
1015 $(that.element).css('width', that.width + 'px');
1017 if(typeof(that.library.aspect_ratio) === 'undefined') {
1018 if(typeof(that.height) === 'string')
1019 $(that.element).css('height', that.height);
1020 else if(typeof(that.height) === 'number')
1021 $(that.element).css('height', that.height + 'px');
1024 var w = that.element.offsetWidth;
1025 if(w === null || w === 0)
1026 that.tm.last_resized = 0;
1028 $(that.element).css('height', (that.element.offsetWidth * that.library.aspect_ratio / 100).toString() + 'px');
1031 if(NETDATA.chartDefaults.min_width !== null)
1032 $(that.element).css('min-width', NETDATA.chartDefaults.min_width);
1034 that.tm.last_dom_created = new Date().getTime();
1040 * initialize state viariables
1041 * destroy all (possibly) created state elements
1042 * create the basic DOM for a chart
1044 var init = function() {
1045 if(that.enabled === false) return;
1047 that.paused = false;
1048 that.selected = false;
1050 that.chart_created = false; // boolean - is the library.create() been called?
1051 that.updates_counter = 0; // numeric - the number of refreshes made so far
1052 that.updates_since_last_creation = 0;
1055 last_initialized: 0, // milliseconds - the timestamp it was last initialized
1056 last_dom_created: 0, // milliseconds - the timestamp its DOM was last created
1057 last_mode_switch: 0, // milliseconds - the timestamp it switched modes
1059 last_info_downloaded: 0, // milliseconds - the timestamp we downloaded the chart
1060 last_updated: 0, // the timestamp the chart last updated with data
1061 pan_and_zoom_seq: 0, // the sequence number of the global synchronization
1063 // Used with NETDATA.globalPanAndZoom.seq
1064 last_visible_check: 0, // the time we last checked if it is visible
1065 last_resized: 0, // the time the chart was resized
1066 last_hidden: 0, // the time the chart was hidden
1067 last_unhidden: 0, // the time the chart was unhidden
1068 last_autorefreshed: 0 // the time the chart was last refreshed
1071 that.data = null; // the last data as downloaded from the netdata server
1072 that.data_url = 'invalid://'; // string - the last url used to update the chart
1073 that.data_points = 0; // number - the number of points returned from netdata
1074 that.data_after = 0; // milliseconds - the first timestamp of the data
1075 that.data_before = 0; // milliseconds - the last timestamp of the data
1076 that.data_update_every = 0; // milliseconds - the frequency to update the data
1078 that.tm.last_initialized = new Date().getTime();
1081 that.setMode('auto');
1084 var maxMessageFontSize = function() {
1085 // normally we want a font size, as tall as the element
1086 var h = that.element_message.clientHeight;
1088 // but give it some air, 20% let's say, or 5 pixels min
1089 var lost = Math.max(h * 0.2, 5);
1092 // center the text, verically
1093 var paddingTop = (lost - 5) / 2;
1095 // but check the width too
1096 // it should fit 10 characters in it
1097 var w = that.element_message.clientWidth / 10;
1099 paddingTop += (h - w) / 2;
1103 // and don't make it too huge
1104 // 5% of the screen size is good
1105 if(h > screen.height / 20) {
1106 paddingTop += (h - (screen.height / 20)) / 2;
1107 h = screen.height / 20;
1111 that.element_message.style.fontSize = h.toString() + 'px';
1112 that.element_message.style.paddingTop = paddingTop.toString() + 'px';
1115 var showMessage = function(msg) {
1116 that.element_message.className = 'netdata-message';
1117 that.element_message.innerHTML = msg;
1118 this.element_message.style.fontSize = 'x-small';
1119 that.element_message.style.paddingTop = '0px';
1120 that.___messageHidden___ = undefined;
1123 var showMessageIcon = function(icon) {
1124 that.element_message.innerHTML = icon;
1125 that.element_message.className = 'netdata-message icon';
1126 maxMessageFontSize();
1127 that.___messageHidden___ = undefined;
1130 var hideMessage = function() {
1131 if(typeof that.___messageHidden___ === 'undefined') {
1132 that.___messageHidden___ = true;
1133 that.element_message.className = 'netdata-message hidden';
1137 var showRendering = function() {
1139 if(that.chart !== null) {
1140 if(that.chart.chart_type === 'line')
1141 icon = '<i class="fa fa-line-chart"></i>';
1143 icon = '<i class="fa fa-area-chart"></i>';
1146 icon = '<i class="fa fa-area-chart"></i>';
1148 showMessageIcon(icon + ' netdata');
1151 var showLoading = function() {
1152 if(that.chart_created === false) {
1153 showMessageIcon('<i class="fa fa-refresh"></i> netdata');
1159 var isHidden = function() {
1160 if(typeof that.___chartIsHidden___ !== 'undefined')
1166 // hide the chart, when it is not visible - called from isVisible()
1167 var hideChart = function() {
1168 // hide it, if it is not already hidden
1169 if(isHidden() === true) return;
1171 if(that.chart_created === true) {
1172 // we should destroy it
1173 if(NETDATA.options.current.destroy_on_hide === true) {
1178 that.element_chart.style.display = 'none';
1179 if(that.element_legend !== null) that.element_legend.style.display = 'none';
1183 that.___chartIsHidden___ = true;
1186 // unhide the chart, when it is visible - called from isVisible()
1187 var unhideChart = function() {
1188 if(isHidden() === false) return;
1190 that.___chartIsHidden___ = undefined;
1192 if(that.chart_created === false) {
1193 // we need to re-initialize it, to show our background
1194 // logo in bootstrap tabs, until the chart loads
1198 that.element_chart.style.display = '';
1199 if(that.element_legend !== null) that.element_legend.style.display = '';
1205 var canBeRendered = function() {
1206 if(isHidden() === true || that.isVisible(true) === false)
1212 // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
1213 var callChartLibraryUpdateSafely = function(data) {
1216 if(canBeRendered() === false)
1219 if(NETDATA.options.debug.chart_errors === true)
1220 status = that.library.update(that, data);
1223 status = that.library.update(that, data);
1230 if(status === false) {
1231 error('chart failed to be updated as ' + that.library_name);
1235 that.updates_since_last_creation++;
1239 // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
1240 var callChartLibraryCreateSafely = function(data) {
1243 if(canBeRendered() === false)
1246 if(NETDATA.options.debug.chart_errors === true)
1247 status = that.library.create(that, data);
1250 status = that.library.create(that, data);
1257 if(status === false) {
1258 error('chart failed to be created as ' + that.library_name);
1262 that.chart_created = true;
1263 that.updates_since_last_creation = 0;
1267 // ----------------------------------------------------------------------------------------------------------------
1270 // resizeChart() - private
1271 // to be called just before the chart library to make sure that
1272 // a properly sized dom is available
1273 var resizeChart = function() {
1274 if(that.isVisible() === true && that.tm.last_resized < NETDATA.options.last_resized) {
1275 if(that.chart_created === false) return;
1277 if(that.needsRecreation()) {
1280 else if(typeof that.library.resize === 'function') {
1281 that.library.resize(that);
1283 if(that.element_legend_childs.nano !== null && that.element_legend_childs.nano_options !== null)
1284 $(that.element_legend_childs.nano).nanoScroller();
1286 maxMessageFontSize();
1289 that.tm.last_resized = new Date().getTime();
1293 // this is the actual chart resize algorithm
1295 // - resize the entire container
1296 // - update the internal states
1297 // - resize the chart as the div changes height
1298 // - update the scrollbar of the legend
1299 var resizeChartToHeight = function(h) {
1301 that.element.style.height = h;
1303 if(that.settings_id !== null)
1304 NETDATA.localStorageSet('chart_heights.' + that.settings_id, h);
1306 var now = new Date().getTime();
1307 NETDATA.options.last_page_scroll = now;
1308 NETDATA.options.last_resized = now;
1309 NETDATA.options.auto_refresher_stop_until = now + NETDATA.options.current.stop_updates_while_resizing;
1312 that.tm.last_resized = 0;
1316 this.resizeHandler = function(e) {
1319 if(typeof this.event_resize === 'undefined'
1320 || this.event_resize.chart_original_w === 'undefined'
1321 || this.event_resize.chart_original_h === 'undefined')
1322 this.event_resize = {
1323 chart_original_w: this.element.clientWidth,
1324 chart_original_h: this.element.clientHeight,
1328 if(e.type === 'touchstart') {
1329 this.event_resize.mouse_start_x = e.touches.item(0).pageX;
1330 this.event_resize.mouse_start_y = e.touches.item(0).pageY;
1333 this.event_resize.mouse_start_x = e.clientX;
1334 this.event_resize.mouse_start_y = e.clientY;
1337 this.event_resize.chart_start_w = this.element.clientWidth;
1338 this.event_resize.chart_start_h = this.element.clientHeight;
1339 this.event_resize.chart_last_w = this.element.clientWidth;
1340 this.event_resize.chart_last_h = this.element.clientHeight;
1342 var now = new Date().getTime();
1343 if(now - this.event_resize.last <= NETDATA.options.current.double_click_speed) {
1344 // double click / double tap event
1346 // the optimal height of the chart
1347 // showing the entire legend
1348 var optimal = this.event_resize.chart_last_h
1349 + this.element_legend_childs.content.scrollHeight
1350 - this.element_legend_childs.content.clientHeight;
1352 // if we are not optimal, be optimal
1353 if(this.event_resize.chart_last_h != optimal)
1354 resizeChartToHeight(optimal.toString() + 'px');
1356 // else if we do not have the original height
1357 // reset to the original height
1358 else if(this.event_resize.chart_last_h != this.event_resize.chart_original_h)
1359 resizeChartToHeight(this.event_resize.chart_original_h.toString() + 'px');
1362 this.event_resize.last = now;
1364 // process movement event
1365 document.onmousemove =
1366 document.ontouchmove =
1367 this.element_legend_childs.resize_handler.onmousemove =
1368 this.element_legend_childs.resize_handler.ontouchmove =
1373 case 'mousemove': y = e.clientY; break;
1374 case 'touchmove': y = e.touches.item(e.touches - 1).pageY; break;
1378 var newH = that.event_resize.chart_start_h + y - that.event_resize.mouse_start_y;
1380 if(newH >= 70 && newH !== that.event_resize.chart_last_h) {
1381 resizeChartToHeight(newH.toString() + 'px');
1382 that.event_resize.chart_last_h = newH;
1387 // process end event
1388 document.onmouseup =
1389 document.ontouchend =
1390 this.element_legend_childs.resize_handler.onmouseup =
1391 this.element_legend_childs.resize_handler.ontouchend =
1393 // remove all the hooks
1394 document.onmouseup =
1395 document.onmousemove =
1396 document.ontouchmove =
1397 document.ontouchend =
1398 that.element_legend_childs.resize_handler.onmousemove =
1399 that.element_legend_childs.resize_handler.ontouchmove =
1400 that.element_legend_childs.resize_handler.onmouseout =
1401 that.element_legend_childs.resize_handler.onmouseup =
1402 that.element_legend_childs.resize_handler.ontouchend =
1405 // allow auto-refreshes
1406 NETDATA.options.auto_refresher_stop_until = 0;
1412 var noDataToShow = function() {
1413 showMessageIcon('<i class="fa fa-warning"></i> empty');
1414 that.legendUpdateDOM();
1415 that.tm.last_autorefreshed = new Date().getTime();
1416 that.data_update_every = 30 * 1000;
1419 // ============================================================================================================
1422 this.error = function(msg) {
1426 this.setMode = function(m) {
1427 if(this.current !== null && this.current.name === m) return;
1430 this.current = this.auto;
1431 else if(m === 'pan')
1432 this.current = this.pan;
1433 else if(m === 'zoom')
1434 this.current = this.zoom;
1436 this.current = this.auto;
1438 this.current.force_update_at = 0;
1439 this.current.force_before_ms = null;
1440 this.current.force_after_ms = null;
1442 this.tm.last_mode_switch = new Date().getTime();
1445 // ----------------------------------------------------------------------------------------------------------------
1446 // global selection sync
1448 // prevent to global selection sync for some time
1449 this.globalSelectionSyncDelay = function(ms) {
1450 if(NETDATA.options.current.sync_selection === false)
1453 if(typeof ms === 'number')
1454 NETDATA.globalSelectionSync.dont_sync_before = new Date().getTime() + ms;
1456 NETDATA.globalSelectionSync.dont_sync_before = new Date().getTime() + NETDATA.options.current.sync_selection_delay;
1459 // can we globally apply selection sync?
1460 this.globalSelectionSyncAbility = function() {
1461 if(NETDATA.options.current.sync_selection === false)
1464 if(NETDATA.globalSelectionSync.dont_sync_before > new Date().getTime())
1470 this.globalSelectionSyncIsMaster = function() {
1471 if(NETDATA.globalSelectionSync.state === this)
1477 // this chart is the master of the global selection sync
1478 this.globalSelectionSyncBeMaster = function() {
1480 if(this.globalSelectionSyncIsMaster()) {
1481 if(this.debug === true)
1482 this.log('sync: I am the master already.');
1487 if(NETDATA.globalSelectionSync.state) {
1488 if(this.debug === true)
1489 this.log('sync: I am not the sync master. Resetting global sync.');
1491 this.globalSelectionSyncStop();
1494 // become the master
1495 if(this.debug === true)
1496 this.log('sync: becoming sync master.');
1498 this.selected = true;
1499 NETDATA.globalSelectionSync.state = this;
1501 // find the all slaves
1502 var targets = NETDATA.options.targets;
1503 var len = targets.length;
1508 if(this.debug === true)
1509 st.log('sync: not adding me to sync');
1511 else if(st.globalSelectionSyncIsEligible()) {
1512 if(this.debug === true)
1513 st.log('sync: adding to sync as slave');
1515 st.globalSelectionSyncBeSlave();
1519 // this.globalSelectionSyncDelay(100);
1522 // can the chart participate to the global selection sync as a slave?
1523 this.globalSelectionSyncIsEligible = function() {
1524 if(this.enabled === true
1525 && this.library !== null
1526 && typeof this.library.setSelection === 'function'
1527 && this.isVisible() === true
1528 && this.chart_created === true)
1534 // this chart becomes a slave of the global selection sync
1535 this.globalSelectionSyncBeSlave = function() {
1536 if(NETDATA.globalSelectionSync.state !== this)
1537 NETDATA.globalSelectionSync.slaves.push(this);
1540 // sync all the visible charts to the given time
1541 // this is to be called from the chart libraries
1542 this.globalSelectionSync = function(t) {
1543 if(this.globalSelectionSyncAbility() === false) {
1544 if(this.debug === true)
1545 this.log('sync: cannot sync (yet?).');
1550 if(this.globalSelectionSyncIsMaster() === false) {
1551 if(this.debug === true)
1552 this.log('sync: trying to be sync master.');
1554 this.globalSelectionSyncBeMaster();
1556 if(this.globalSelectionSyncAbility() === false) {
1557 if(this.debug === true)
1558 this.log('sync: cannot sync (yet?).');
1564 NETDATA.globalSelectionSync.last_t = t;
1565 $.each(NETDATA.globalSelectionSync.slaves, function(i, st) {
1570 // stop syncing all charts to the given time
1571 this.globalSelectionSyncStop = function() {
1572 if(NETDATA.globalSelectionSync.slaves.length) {
1573 if(this.debug === true)
1574 this.log('sync: cleaning up...');
1576 $.each(NETDATA.globalSelectionSync.slaves, function(i, st) {
1578 if(that.debug === true)
1579 st.log('sync: not adding me to sync stop');
1582 if(that.debug === true)
1583 st.log('sync: removed slave from sync');
1585 st.clearSelection();
1589 NETDATA.globalSelectionSync.last_t = 0;
1590 NETDATA.globalSelectionSync.slaves = [];
1591 NETDATA.globalSelectionSync.state = null;
1594 this.clearSelection();
1597 this.setSelection = function(t) {
1598 if(typeof this.library.setSelection === 'function') {
1599 if(this.library.setSelection(this, t) === true)
1600 this.selected = true;
1602 this.selected = false;
1604 else this.selected = true;
1606 if(this.selected === true && this.debug === true)
1607 this.log('selection set to ' + t.toString());
1609 return this.selected;
1612 this.clearSelection = function() {
1613 if(this.selected === true) {
1614 if(typeof this.library.clearSelection === 'function') {
1615 if(this.library.clearSelection(this) === true)
1616 this.selected = false;
1618 this.selected = true;
1620 else this.selected = false;
1622 if(this.selected === false && this.debug === true)
1623 this.log('selection cleared');
1628 return this.selected;
1631 // find if a timestamp (ms) is shown in the current chart
1632 this.timeIsVisible = function(t) {
1633 if(t >= this.data_after && t <= this.data_before)
1638 this.calculateRowForTime = function(t) {
1639 if(this.timeIsVisible(t) === false) return -1;
1640 return Math.floor((t - this.data_after) / this.data_update_every);
1643 // ----------------------------------------------------------------------------------------------------------------
1646 this.log = function(msg) {
1647 console.log(this.id + ' (' + this.library_name + ' ' + this.uuid + '): ' + msg);
1650 this.pauseChart = function() {
1651 if(this.paused === false) {
1652 if(this.debug === true)
1653 this.log('pauseChart()');
1659 this.unpauseChart = function() {
1660 if(this.paused === true) {
1661 if(this.debug === true)
1662 this.log('unpauseChart()');
1664 this.paused = false;
1668 this.resetChart = function(dont_clear_master, dont_update) {
1669 if(this.debug === true)
1670 this.log('resetChart(' + dont_clear_master + ', ' + dont_update + ') called');
1672 if(typeof dont_clear_master === 'undefined')
1673 dont_clear_master = false;
1675 if(typeof dont_update === 'undefined')
1676 dont_update = false;
1678 if(dont_clear_master !== true && NETDATA.globalPanAndZoom.isMaster(this) === true) {
1679 if(this.debug === true)
1680 this.log('resetChart() diverting to clearMaster().');
1681 // this will call us back with master === true
1682 NETDATA.globalPanAndZoom.clearMaster();
1686 this.clearSelection();
1688 this.tm.pan_and_zoom_seq = 0;
1690 this.setMode('auto');
1691 this.current.force_update_at = 0;
1692 this.current.force_before_ms = null;
1693 this.current.force_after_ms = null;
1694 this.tm.last_autorefreshed = 0;
1695 this.paused = false;
1696 this.selected = false;
1697 this.enabled = true;
1698 // this.debug = false;
1700 // do not update the chart here
1701 // or the chart will flip-flop when it is the master
1702 // of a selection sync and another chart becomes
1705 if(dont_update !== true && this.isVisible() === true) {
1710 this.updateChartPanOrZoom = function(after, before) {
1711 if(this.debug === true)
1712 this.log('updateChartPanOrZoom() called.');
1714 if(before < after) return false;
1716 var min_duration = Math.round((this.chartWidth() / 30 * this.chart.update_every * 1000));
1718 if(this.debug === true)
1719 this.log('requested duration of ' + ((before - after) / 1000).toString() + ' (' + after + ' - ' + before + '), minimum ' + min_duration / 1000);
1721 if((before - after) < min_duration) return false;
1723 var current_duration = this.data_before - this.data_after;
1724 var wanted_duration = before - after;
1725 var tolerance = this.data_update_every * 2;
1726 var movement = Math.abs(before - this.data_before);
1728 if(this.debug === true)
1729 this.log('current duration: ' + current_duration / 1000 + ', wanted duration: ' + wanted_duration / 1000 + ', movement: ' + movement / 1000 + ', tolerance: ' + tolerance / 1000);
1731 if(Math.abs(current_duration - wanted_duration) <= tolerance && movement <= tolerance) {
1732 if(this.debug === true)
1733 this.log('IGNORED');
1738 if(this.current.name === 'auto') {
1739 this.setMode('pan');
1741 if(this.debug === true)
1742 this.log('updateChartPanOrZoom(): caller did not set proper mode');
1745 this.current.force_update_at = new Date().getTime() + NETDATA.options.current.pan_and_zoom_delay;
1746 this.current.force_after_ms = after;
1747 this.current.force_before_ms = before;
1748 NETDATA.globalPanAndZoom.setMaster(this, after, before);
1752 this.legendFormatValue = function(value) {
1753 if(value === null || value === 'undefined') return '-';
1754 if(typeof value !== 'number') return value;
1756 var abs = Math.abs(value);
1757 if(abs >= 100) return Math.round(value).toLocaleString();
1758 if(abs >= 1) return (Math.round(value * 100) / 100).toLocaleString();
1759 if(abs >= 0.1) return (Math.round(value * 1000) / 1000).toLocaleString();
1760 return (Math.round(value * 10000) / 10000).toLocaleString();
1763 this.legendSetLabelValue = function(label, value) {
1764 var series = this.element_legend_childs.series[label];
1765 if(typeof series === 'undefined') return;
1766 if(series.value === null && series.user === null) return;
1768 // if the value has not changed, skip DOM update
1769 //if(series.last === value) return;
1772 if(typeof value === 'number') {
1773 var v = Math.abs(value);
1774 s = r = this.legendFormatValue(value);
1776 if(typeof series.last === 'number') {
1777 if(v > series.last) s += '<i class="fa fa-angle-up" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1778 else if(v < series.last) s += '<i class="fa fa-angle-down" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1779 else s += '<i class="fa fa-angle-left" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1781 else s += '<i class="fa fa-angle-right" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1786 series.last = value;
1789 if(series.value !== null) series.value.innerHTML = s;
1790 if(series.user !== null) series.user.innerHTML = r;
1793 this.legendSetDate = function(ms) {
1794 if(typeof ms !== 'number') {
1795 this.legendShowUndefined();
1799 var d = new Date(ms);
1801 if(this.element_legend_childs.title_date)
1802 this.element_legend_childs.title_date.innerHTML = d.toLocaleDateString();
1804 if(this.element_legend_childs.title_time)
1805 this.element_legend_childs.title_time.innerHTML = d.toLocaleTimeString();
1807 if(this.element_legend_childs.title_units)
1808 this.element_legend_childs.title_units.innerHTML = this.units;
1811 this.legendShowUndefined = function() {
1812 if(this.element_legend_childs.title_date)
1813 this.element_legend_childs.title_date.innerHTML = ' ';
1815 if(this.element_legend_childs.title_time)
1816 this.element_legend_childs.title_time.innerHTML = this.chart.name;
1818 if(this.element_legend_childs.title_units)
1819 this.element_legend_childs.title_units.innerHTML = ' ';
1821 if(this.data && this.element_legend_childs.series !== null) {
1822 var labels = this.data.dimension_names;
1823 var i = labels.length;
1825 var label = labels[i];
1827 if(typeof label === 'undefined') continue;
1828 if(typeof this.element_legend_childs.series[label] === 'undefined') continue;
1829 this.legendSetLabelValue(label, null);
1834 this.legendShowLatestValues = function() {
1835 if(this.chart === null) return;
1836 if(this.selected) return;
1838 if(this.data === null || this.element_legend_childs.series === null) {
1839 this.legendShowUndefined();
1843 var show_undefined = true;
1844 if(Math.abs(this.data.last_entry - this.data.before) <= this.data.view_update_every)
1845 show_undefined = false;
1847 if(show_undefined) {
1848 this.legendShowUndefined();
1852 this.legendSetDate(this.data.before * 1000);
1854 var labels = this.data.dimension_names;
1855 var i = labels.length;
1857 var label = labels[i];
1859 if(typeof label === 'undefined') continue;
1860 if(typeof this.element_legend_childs.series[label] === 'undefined') continue;
1863 this.legendSetLabelValue(label, null);
1865 this.legendSetLabelValue(label, this.data.view_latest_values[i]);
1869 this.legendReset = function() {
1870 this.legendShowLatestValues();
1873 // this should be called just ONCE per dimension per chart
1874 this._chartDimensionColor = function(label) {
1875 if(this.colors === null) this.chartColors();
1877 if(typeof this.colors_assigned[label] === 'undefined') {
1878 if(this.colors_available.length === 0) {
1879 for(var i = 0, len = NETDATA.colors.length; i < len ; i++)
1880 this.colors_available.push(NETDATA.colors[i]);
1883 this.colors_assigned[label] = this.colors_available.shift();
1885 if(this.debug === true)
1886 this.log('label "' + label + '" got color "' + this.colors_assigned[label]);
1889 if(this.debug === true)
1890 this.log('label "' + label + '" already has color "' + this.colors_assigned[label] + '"');
1893 this.colors.push(this.colors_assigned[label]);
1894 return this.colors_assigned[label];
1897 this.chartColors = function() {
1898 if(this.colors !== null) return this.colors;
1900 this.colors = new Array();
1901 this.colors_available = new Array();
1902 // this.colors_assigned = {};
1904 var c = $(this.element).data('colors');
1905 if(typeof c !== 'undefined' && c !== null) {
1906 if(typeof c !== 'string') {
1907 this.log('invalid color given: ' + c + ' (give a space separated list of colors)');
1911 for(var i = 0, len = c.length; i < len ; i++)
1912 this.colors_available.push(c[i]);
1916 // push all the standard colors too
1917 for(var i = 0, len = NETDATA.colors.length; i < len ; i++)
1918 this.colors_available.push(NETDATA.colors[i]);
1923 this.legendUpdateDOM = function() {
1926 // check that the legend DOM is up to date for the downloaded dimensions
1927 if(typeof this.element_legend_childs.series !== 'object' || this.element_legend_childs.series === null) {
1928 // this.log('the legend does not have any series - requesting legend update');
1931 else if(this.data === null) {
1932 // this.log('the chart does not have any data - requesting legend update');
1935 else if(typeof this.element_legend_childs.series.labels_key === 'undefined') {
1939 var labels = this.data.dimension_names.toString();
1940 if(labels !== this.element_legend_childs.series.labels_key) {
1943 if(this.debug === true)
1944 this.log('NEW LABELS: "' + labels + '" NOT EQUAL OLD LABELS: "' + this.element_legend_childs.series.labels_key + '"');
1948 if(needed === false) {
1949 // make sure colors available
1952 // do we have to update the current values?
1953 // we do this, only when the visible chart is current
1954 if(Math.abs(this.data.last_entry - this.data.before) <= this.data.view_update_every) {
1955 if(this.debug === true)
1956 this.log('chart in running... updating values on legend...');
1958 //var labels = this.data.dimension_names;
1959 //var i = labels.length;
1961 // this.legendSetLabelValue(labels[i], this.data.latest_values[i]);
1965 if(this.colors === null) {
1966 // this is the first time we update the chart
1967 // let's assign colors to all dimensions
1968 if(this.library.track_colors() === true)
1969 for(var dim in this.chart.dimensions)
1970 this._chartDimensionColor(this.chart.dimensions[dim].name);
1972 // we will re-generate the colors for the chart
1975 if(this.debug === true)
1976 this.log('updating Legend DOM');
1978 // mark all dimensions as invalid
1979 this.dimensions_visibility.invalidateAll();
1981 var genLabel = function(state, parent, name, count) {
1982 var color = state._chartDimensionColor(name);
1984 var user_element = null;
1985 var user_id = self.data('show-value-of-' + name + '-at') || null;
1986 if(user_id !== null) {
1987 user_element = document.getElementById(user_id) || null;
1988 if(user_element === null)
1989 me.log('Cannot find element with id: ' + user_id);
1992 state.element_legend_childs.series[name] = {
1993 name: document.createElement('span'),
1994 value: document.createElement('span'),
1999 var label = state.element_legend_childs.series[name];
2001 // create the dimension visibility tracking for this label
2002 state.dimensions_visibility.dimensionAdd(name, label.name, label.value, color);
2004 var rgb = NETDATA.colorHex2Rgb(color);
2005 label.name.innerHTML = '<table class="netdata-legend-name-table-'
2006 + state.chart.chart_type
2007 + '" style="background-color: '
2008 + 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + NETDATA.options.current['color_fill_opacity_' + state.chart.chart_type] + ')'
2009 + '"><tr class="netdata-legend-name-tr"><td class="netdata-legend-name-td"></td></tr></table>'
2011 var text = document.createTextNode(' ' + name);
2012 label.name.appendChild(text);
2015 parent.appendChild(document.createElement('br'));
2017 parent.appendChild(label.name);
2018 parent.appendChild(label.value);
2021 var content = document.createElement('div');
2023 if(this.hasLegend()) {
2024 this.element_legend_childs = {
2026 resize_handler: document.createElement('div'),
2027 title_date: document.createElement('span'),
2028 title_time: document.createElement('span'),
2029 title_units: document.createElement('span'),
2030 nano: document.createElement('div'),
2032 paneClass: 'netdata-legend-series-pane',
2033 sliderClass: 'netdata-legend-series-slider',
2034 contentClass: 'netdata-legend-series-content',
2035 enabledClass: '__enabled',
2036 flashedClass: '__flashed',
2037 activeClass: '__active',
2039 alwaysVisible: true,
2045 this.element_legend.innerHTML = '';
2047 this.element_legend_childs.resize_handler.className += " netdata-legend-resize-handler";
2048 this.element_legend_childs.resize_handler.innerHTML = '<i class="fa fa-chevron-up"></i><i class="fa fa-chevron-down"></i>';
2049 this.element.appendChild(this.element_legend_childs.resize_handler);
2052 this.element_legend_childs.resize_handler.onmousedown =
2054 that.resizeHandler(e);
2058 this.element_legend_childs.resize_handler.addEventListener('touchstart', function(e) {
2059 that.resizeHandler(e);
2062 this.element_legend_childs.title_date.className += " netdata-legend-title-date";
2063 this.element_legend.appendChild(this.element_legend_childs.title_date);
2065 this.element_legend.appendChild(document.createElement('br'));
2067 this.element_legend_childs.title_time.className += " netdata-legend-title-time";
2068 this.element_legend.appendChild(this.element_legend_childs.title_time);
2070 this.element_legend.appendChild(document.createElement('br'));
2072 this.element_legend_childs.title_units.className += " netdata-legend-title-units";
2073 this.element_legend.appendChild(this.element_legend_childs.title_units);
2075 this.element_legend.appendChild(document.createElement('br'));
2077 this.element_legend_childs.nano.className = 'netdata-legend-series';
2078 this.element_legend.appendChild(this.element_legend_childs.nano);
2080 content.className = 'netdata-legend-series-content';
2081 this.element_legend_childs.nano.appendChild(content);
2084 this.element_legend_childs = {
2086 resize_handler: null,
2097 this.element_legend_childs.series.labels_key = this.data.dimension_names.toString();
2098 if(this.debug === true)
2099 this.log('labels from data: "' + this.element_legend_childs.series.labels_key + '"');
2101 for(var i = 0, len = this.data.dimension_names.length; i < len ;i++) {
2102 genLabel(this, content, this.data.dimension_names[i], i);
2106 var tmp = new Array();
2107 for(var dim in this.chart.dimensions) {
2108 tmp.push(this.chart.dimensions[dim].name);
2109 genLabel(this, content, this.chart.dimensions[dim].name, i);
2111 this.element_legend_childs.series.labels_key = tmp.toString();
2112 if(this.debug === true)
2113 this.log('labels from chart: "' + this.element_legend_childs.series.labels_key + '"');
2116 // create a hidden div to be used for hidding
2117 // the original legend of the chart library
2118 var el = document.createElement('div');
2119 if(this.element_legend !== null)
2120 this.element_legend.appendChild(el);
2121 el.style.display = 'none';
2123 this.element_legend_childs.hidden = document.createElement('div');
2124 el.appendChild(this.element_legend_childs.hidden);
2126 if(this.element_legend_childs.nano !== null && this.element_legend_childs.nano_options !== null)
2127 $(this.element_legend_childs.nano).nanoScroller(this.element_legend_childs.nano_options);
2129 this.legendShowLatestValues();
2132 this.hasLegend = function() {
2133 if(typeof this.___hasLegendCache___ !== 'undefined')
2134 return this.___hasLegendCache___;
2137 if(this.library && this.library.legend(this) === 'right-side') {
2138 var legend = $(this.element).data('legend') || 'yes';
2139 if(legend === 'yes') leg = true;
2142 this.___hasLegendCache___ = leg;
2146 this.legendWidth = function() {
2147 return (this.hasLegend())?140:0;
2150 this.legendHeight = function() {
2151 return $(this.element).height();
2154 this.chartWidth = function() {
2155 return $(this.element).width() - this.legendWidth();
2158 this.chartHeight = function() {
2159 return $(this.element).height();
2162 this.chartPixelsPerPoint = function() {
2163 // force an options provided detail
2164 var px = this.pixels_per_point;
2166 if(this.library && px < this.library.pixels_per_point(this))
2167 px = this.library.pixels_per_point(this);
2169 if(px < NETDATA.options.current.pixels_per_point)
2170 px = NETDATA.options.current.pixels_per_point;
2175 this.needsRecreation = function() {
2177 this.chart_created === true
2179 && this.library.autoresize() === false
2180 && this.tm.last_resized < NETDATA.options.last_resized
2184 this.chartURL = function() {
2187 if(NETDATA.globalPanAndZoom.isActive()) {
2188 after = Math.round(NETDATA.globalPanAndZoom.force_after_ms / 1000);
2189 before = Math.round(NETDATA.globalPanAndZoom.force_before_ms / 1000);
2190 this.tm.pan_and_zoom_seq = NETDATA.globalPanAndZoom.seq;
2193 before = this.current.force_before_ms !== null ? Math.round(this.current.force_before_ms / 1000) : this.before;
2194 after = this.current.force_after_ms !== null ? Math.round(this.current.force_after_ms / 1000) : this.after;
2195 this.tm.pan_and_zoom_seq = 0;
2198 this.requested_after = after * 1000;
2199 this.requested_before = before * 1000;
2201 this.data_points = this.points || Math.round(this.chartWidth() / this.chartPixelsPerPoint());
2203 // build the data URL
2204 this.data_url = this.chart.data_url;
2205 this.data_url += "&format=" + this.library.format();
2206 this.data_url += "&points=" + this.data_points.toString();
2207 this.data_url += "&group=" + this.method;
2208 this.data_url += "&options=" + this.library.options(this);
2209 this.data_url += '|jsonwrap';
2211 if(NETDATA.options.current.eliminate_zero_dimensions === true)
2212 this.data_url += '|nonzero';
2214 if(this.append_options !== null)
2215 this.data_url += '|' + this.append_options.toString();
2218 this.data_url += "&after=" + after.toString();
2221 this.data_url += "&before=" + before.toString();
2224 this.data_url += "&dimensions=" + this.dimensions;
2226 if(NETDATA.options.debug.chart_data_url === true || this.debug === true)
2227 this.log('chartURL(): ' + this.data_url + ' WxH:' + this.chartWidth() + 'x' + this.chartHeight() + ' points: ' + this.data_points + ' library: ' + this.library_name);
2230 this.redrawChart = function() {
2231 if(this.data !== null)
2232 this.updateChartWithData(this.data);
2235 this.updateChartWithData = function(data) {
2236 if(this.debug === true)
2237 this.log('updateChartWithData() called.');
2239 // this may force the chart to be re-created
2243 this.updates_counter++;
2245 var started = new Date().getTime();
2247 // if the result is JSON, find the latest update-every
2248 if(typeof data === 'object') {
2249 if(typeof data.view_update_every !== 'undefined')
2250 this.data_update_every = data.view_update_every * 1000;
2252 if(typeof data.after !== 'undefined')
2253 this.data_after = data.after * 1000;
2255 if(typeof data.before !== 'undefined')
2256 this.data_before = data.before * 1000;
2258 if(typeof data.first_entry !== 'undefined')
2259 this.netdata_first = data.first_entry * 1000;
2261 if(typeof data.last_entry !== 'undefined')
2262 this.netdata_last = data.last_entry * 1000;
2264 if(typeof data.points !== 'undefined')
2265 this.data_points = data.points;
2270 if(this.debug === true) {
2271 this.log('UPDATE No ' + this.updates_counter + ' COMPLETED');
2273 if(this.current.force_after_ms)
2274 this.log('STATUS: forced : ' + (this.current.force_after_ms / 1000).toString() + ' - ' + (this.current.force_before_ms / 1000).toString());
2276 this.log('STATUS: forced: unset');
2278 this.log('STATUS: requested: ' + (this.requested_after / 1000).toString() + ' - ' + (this.requested_before / 1000).toString());
2279 this.log('STATUS: rendered : ' + (this.data_after / 1000).toString() + ' - ' + (this.data_before / 1000).toString());
2280 this.log('STATUS: points : ' + (this.data_points).toString());
2283 if(this.data_points === 0) {
2288 if(this.updates_since_last_creation >= this.library.max_updates_to_recreate()) {
2289 if(this.debug === true)
2290 this.log('max updates of ' + this.updates_since_last_creation.toString() + ' reached. Forcing re-generation.');
2292 this.chart_created = false;
2295 // check and update the legend
2296 this.legendUpdateDOM();
2298 if(this.chart_created === true
2299 && typeof this.library.update === 'function') {
2301 if(this.debug === true)
2302 this.log('updating chart...');
2304 if(callChartLibraryUpdateSafely(data) === false)
2308 if(this.debug === true)
2309 this.log('creating chart...');
2311 if(callChartLibraryCreateSafely(data) === false)
2315 this.legendShowLatestValues();
2316 if(this.selected === true)
2317 NETDATA.globalSelectionSync.stop();
2319 // update the performance counters
2320 var now = new Date().getTime();
2321 this.tm.last_updated = now;
2323 // don't update last_autorefreshed if this chart is
2324 // forced to be updated with global PanAndZoom
2325 if(NETDATA.globalPanAndZoom.isActive())
2326 this.tm.last_autorefreshed = 0;
2328 if(NETDATA.options.current.parallel_refresher === true && NETDATA.options.current.concurrent_refreshes)
2329 this.tm.last_autorefreshed = Math.round(now / this.data_update_every) * this.data_update_every;
2331 this.tm.last_autorefreshed = now;
2334 this.refresh_dt_ms = now - started;
2335 NETDATA.options.auto_refresher_fast_weight += this.refresh_dt_ms;
2337 if(this.refresh_dt_element !== null)
2338 this.refresh_dt_element.innerHTML = this.refresh_dt_ms.toString();
2341 this.updateChart = function(callback) {
2342 if(this.debug === true)
2343 this.log('updateChart() called.');
2345 // due to late initialization of charts and libraries
2346 // we need to check this too
2347 if(this.enabled === false) {
2348 if(this.debug === true)
2349 this.log('I am not enabled');
2351 if(typeof callback === 'function') callback();
2355 if(canBeRendered() === false) {
2356 if(typeof callback === 'function') callback();
2360 if(this.chart === null) {
2361 this.getChart(function() { that.updateChart(callback); });
2365 if(this.library.initialized === false) {
2366 if(this.library.enabled === true) {
2367 this.library.initialize(function() { that.updateChart(callback); });
2371 error('chart library "' + this.library_name + '" is not available.');
2372 if(typeof callback === 'function') callback();
2377 this.clearSelection();
2380 if(this.debug === true)
2381 this.log('updating from ' + this.data_url);
2383 this.xhr = $.ajax( {
2385 crossDomain: NETDATA.options.crossDomainAjax,
2389 .success(function(data) {
2390 if(that.debug === true)
2391 that.log('data received. updating chart.');
2393 that.updateChartWithData(data);
2396 error('data download failed for url: ' + that.data_url);
2398 .always(function() {
2399 if(typeof callback === 'function') callback();
2405 this.isVisible = function(nocache) {
2406 if(typeof nocache === 'undefined')
2409 // this.log('last_visible_check: ' + this.tm.last_visible_check + ', last_page_scroll: ' + NETDATA.options.last_page_scroll);
2411 // caching - we do not evaluate the charts visibility
2412 // if the page has not been scrolled since the last check
2413 if(nocache === false && this.tm.last_visible_check > NETDATA.options.last_page_scroll) {
2414 if(this.debug === true)
2415 this.log('isVisible: ' + this.___isVisible___);
2417 return this.___isVisible___;
2420 this.tm.last_visible_check = new Date().getTime();
2422 var wh = window.innerHeight;
2423 var x = this.element.getBoundingClientRect();
2427 if(x.width === 0 || x.height === 0) {
2429 this.___isVisible___ = false;
2431 if(this.debug === true)
2432 this.log('isVisible (width:' + x.width + ', height:' + x.height + ', display:"' + this.element.style.display + '"): ' + this.___isVisible___);
2434 return this.___isVisible___;
2437 if(x.top < 0 && -x.top > x.height) {
2438 // the chart is entirely above
2439 ret = -x.top - x.height;
2441 else if(x.top > wh) {
2442 // the chart is entirely below
2446 if(ret > tolerance) {
2447 // the chart is too far
2450 this.___isVisible___ = false;
2452 if(this.debug === true)
2453 this.log('isVisible: ' + this.___isVisible___);
2455 return this.___isVisible___;
2458 // the chart is inside or very close
2461 this.___isVisible___ = true;
2463 if(this.debug === true)
2464 this.log('isVisible: ' + this.___isVisible___);
2466 return this.___isVisible___;
2470 this.isAutoRefreshed = function() {
2471 return (this.current.autorefresh);
2474 this.canBeAutoRefreshed = function() {
2475 now = new Date().getTime();
2477 if(this.enabled === false) {
2478 if(this.debug === true)
2479 this.log('I am not enabled');
2484 if(this.library === null || this.library.enabled === false) {
2485 error('charting library "' + this.library_name + '" is not available');
2486 if(this.debug === true)
2487 this.log('My chart library ' + this.library_name + ' is not available');
2492 if(this.isVisible() === false) {
2493 if(NETDATA.options.debug.visibility === true || this.debug === true)
2494 this.log('I am not visible');
2499 if(this.current.force_update_at !== 0 && this.current.force_update_at < now) {
2500 if(this.debug === true)
2501 this.log('timed force update detected - allowing this update');
2503 this.current.force_update_at = 0;
2507 if(this.isAutoRefreshed() === true) {
2508 // allow the first update, even if the page is not visible
2509 if(this.updates_counter && NETDATA.options.page_is_visible === false) {
2510 if(NETDATA.options.debug.focus === true || this.debug === true)
2511 this.log('canBeAutoRefreshed(): page does not have focus');
2516 if(this.needsRecreation() === true) {
2517 if(this.debug === true)
2518 this.log('canBeAutoRefreshed(): needs re-creation.');
2523 // options valid only for autoRefresh()
2524 if(NETDATA.options.auto_refresher_stop_until === 0 || NETDATA.options.auto_refresher_stop_until < now) {
2525 if(NETDATA.globalPanAndZoom.isActive()) {
2526 if(NETDATA.globalPanAndZoom.shouldBeAutoRefreshed(this)) {
2527 if(this.debug === true)
2528 this.log('canBeAutoRefreshed(): global panning: I need an update.');
2533 if(this.debug === true)
2534 this.log('canBeAutoRefreshed(): global panning: I am already up to date.');
2540 if(this.selected === true) {
2541 if(this.debug === true)
2542 this.log('canBeAutoRefreshed(): I have a selection in place.');
2547 if(this.paused === true) {
2548 if(this.debug === true)
2549 this.log('canBeAutoRefreshed(): I am paused.');
2554 if(now - this.tm.last_autorefreshed >= this.data_update_every) {
2555 if(this.debug === true)
2556 this.log('canBeAutoRefreshed(): It is time to update me.');
2566 this.autoRefresh = function(callback) {
2567 if(this.canBeAutoRefreshed() === true) {
2568 this.updateChart(callback);
2571 if(typeof callback !== 'undefined')
2576 this._defaultsFromDownloadedChart = function(chart) {
2578 this.chart_url = chart.url;
2579 this.data_update_every = chart.update_every * 1000;
2580 this.data_points = Math.round(this.chartWidth() / this.chartPixelsPerPoint());
2581 this.tm.last_info_downloaded = new Date().getTime();
2583 if(this.title === null)
2584 this.title = chart.title;
2586 if(this.units === null)
2587 this.units = chart.units;
2590 // fetch the chart description from the netdata server
2591 this.getChart = function(callback) {
2592 this.chart = NETDATA.chartRegistry.get(this.host, this.id);
2594 this._defaultsFromDownloadedChart(this.chart);
2595 if(typeof callback === 'function') callback();
2598 this.chart_url = this.host + "/api/v1/chart?chart=" + this.id;
2600 if(this.debug === true)
2601 this.log('downloading ' + this.chart_url);
2604 url: this.chart_url,
2605 crossDomain: NETDATA.options.crossDomainAjax,
2609 .done(function(chart) {
2610 chart.url = that.chart_url;
2611 chart.data_url = (that.host + chart.data_url);
2612 that._defaultsFromDownloadedChart(chart);
2613 NETDATA.chartRegistry.add(that.host, that.id, chart);
2616 NETDATA.error(404, that.chart_url);
2617 error('chart not found on url "' + that.chart_url + '"');
2619 .always(function() {
2620 if(typeof callback === 'function') callback();
2625 // ============================================================================================================
2631 NETDATA.resetAllCharts = function(state) {
2632 // first clear the global selection sync
2633 // to make sure no chart is in selected state
2634 state.globalSelectionSyncStop();
2636 // there are 2 possibilities here
2637 // a. state is the global Pan and Zoom master
2638 // b. state is not the global Pan and Zoom master
2640 if(NETDATA.globalPanAndZoom.isMaster(state) === false)
2643 // clear the global Pan and Zoom
2644 // this will also refresh the master
2645 // and unblock any charts currently mirroring the master
2646 NETDATA.globalPanAndZoom.clearMaster();
2648 // if we were not the master, reset our status too
2649 // this is required because most probably the mouse
2650 // is over this chart, blocking it from autorefreshing
2651 if(master === false && (state.paused === true || state.selected === true))
2655 // get or create a chart state, given a DOM element
2656 NETDATA.chartState = function(element) {
2657 var state = $(element).data('netdata-state-object') || null;
2658 if(state === null) {
2659 state = new chartState(element);
2660 $(element).data('netdata-state-object', state);
2665 // ----------------------------------------------------------------------------------------------------------------
2666 // Library functions
2668 // Load a script without jquery
2669 // This is used to load jquery - after it is loaded, we use jquery
2670 NETDATA._loadjQuery = function(callback) {
2671 if(typeof jQuery === 'undefined') {
2672 if(NETDATA.options.debug.main_loop === true)
2673 console.log('loading ' + NETDATA.jQuery);
2675 var script = document.createElement('script');
2676 script.type = 'text/javascript';
2677 script.async = true;
2678 script.src = NETDATA.jQuery;
2680 // script.onabort = onError;
2681 script.onerror = function(err, t) { NETDATA.error(101, NETDATA.jQuery); };
2682 if(typeof callback === "function")
2683 script.onload = callback;
2685 var s = document.getElementsByTagName('script')[0];
2686 s.parentNode.insertBefore(script, s);
2688 else if(typeof callback === "function")
2692 NETDATA._loadCSS = function(filename) {
2693 // don't use jQuery here
2694 // styles are loaded before jQuery
2695 // to eliminate showing an unstyled page to the user
2697 var fileref = document.createElement("link");
2698 fileref.setAttribute("rel", "stylesheet");
2699 fileref.setAttribute("type", "text/css");
2700 fileref.setAttribute("href", filename);
2702 if (typeof fileref !== 'undefined')
2703 document.getElementsByTagName("head")[0].appendChild(fileref);
2706 NETDATA.colorHex2Rgb = function(hex) {
2707 // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
2708 var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
2709 hex = hex.replace(shorthandRegex, function(m, r, g, b) {
2710 return r + r + g + g + b + b;
2713 var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
2715 r: parseInt(result[1], 16),
2716 g: parseInt(result[2], 16),
2717 b: parseInt(result[3], 16)
2721 NETDATA.colorLuminance = function(hex, lum) {
2722 // validate hex string
2723 hex = String(hex).replace(/[^0-9a-f]/gi, '');
2725 hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
2729 // convert to decimal and change luminosity
2730 var rgb = "#", c, i;
2731 for (i = 0; i < 3; i++) {
2732 c = parseInt(hex.substr(i*2,2), 16);
2733 c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
2734 rgb += ("00"+c).substr(c.length);
2740 NETDATA.guid = function() {
2742 return Math.floor((1 + Math.random()) * 0x10000)
2747 return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
2750 NETDATA.zeropad = function(x) {
2751 if(x > -10 && x < 10) return '0' + x.toString();
2752 else return x.toString();
2755 // user function to signal us the DOM has been
2757 NETDATA.updatedDom = function() {
2758 NETDATA.options.updated_dom = true;
2761 NETDATA.ready = function(callback) {
2762 NETDATA.options.pauseCallback = callback;
2765 NETDATA.pause = function(callback) {
2766 if(NETDATA.options.pause === true)
2769 NETDATA.options.pauseCallback = callback;
2772 NETDATA.unpause = function() {
2773 NETDATA.options.pauseCallback = null;
2774 NETDATA.options.updated_dom = true;
2775 NETDATA.options.pause = false;
2778 // ----------------------------------------------------------------------------------------------------------------
2780 // this is purely sequencial charts refresher
2781 // it is meant to be autonomous
2782 NETDATA.chartRefresherNoParallel = function(index) {
2783 if(NETDATA.options.debug.mail_loop === true)
2784 console.log('NETDATA.chartRefresherNoParallel(' + index + ')');
2786 if(NETDATA.options.updated_dom === true) {
2787 // the dom has been updated
2788 // get the dom parts again
2789 NETDATA.parseDom(NETDATA.chartRefresher);
2792 if(index >= NETDATA.options.targets.length) {
2793 if(NETDATA.options.debug.main_loop === true)
2794 console.log('waiting to restart main loop...');
2796 NETDATA.options.auto_refresher_fast_weight = 0;
2798 setTimeout(function() {
2799 NETDATA.chartRefresher();
2800 }, NETDATA.options.current.idle_between_loops);
2803 var state = NETDATA.options.targets[index];
2805 if(NETDATA.options.auto_refresher_fast_weight < NETDATA.options.current.fast_render_timeframe) {
2806 if(NETDATA.options.debug.main_loop === true)
2807 console.log('fast rendering...');
2809 state.autoRefresh(function() {
2810 NETDATA.chartRefresherNoParallel(++index);
2814 if(NETDATA.options.debug.main_loop === true) console.log('waiting for next refresh...');
2815 NETDATA.options.auto_refresher_fast_weight = 0;
2817 setTimeout(function() {
2818 state.autoRefresh(function() {
2819 NETDATA.chartRefresherNoParallel(++index);
2821 }, NETDATA.options.current.idle_between_charts);
2826 // this is part of the parallel refresher
2827 // its cause is to refresh sequencially all the charts
2828 // that depend on chart library initialization
2829 // it will call the parallel refresher back
2830 // as soon as it sees a chart that its chart library
2832 NETDATA.chartRefresher_unitialized = function() {
2833 if(NETDATA.options.updated_dom === true) {
2834 // the dom has been updated
2835 // get the dom parts again
2836 NETDATA.parseDom(NETDATA.chartRefresher);
2840 if(NETDATA.options.sequencial.length === 0)
2841 NETDATA.chartRefresher();
2843 var state = NETDATA.options.sequencial.pop();
2844 if(state.library.initialized === true)
2845 NETDATA.chartRefresher();
2847 state.autoRefresh(NETDATA.chartRefresher_unitialized);
2851 NETDATA.chartRefresherWaitTime = function() {
2852 return NETDATA.options.current.idle_parallel_loops;
2855 // the default refresher
2856 // it will create 2 sets of charts:
2857 // - the ones that can be refreshed in parallel
2858 // - the ones that depend on something else
2859 // the first set will be executed in parallel
2860 // the second will be given to NETDATA.chartRefresher_unitialized()
2861 NETDATA.chartRefresher = function() {
2862 if(NETDATA.options.pause === true) {
2863 // console.log('auto-refresher is paused');
2864 setTimeout(NETDATA.chartRefresher,
2865 NETDATA.chartRefresherWaitTime());
2869 if(typeof NETDATA.options.pauseCallback === 'function') {
2870 // console.log('auto-refresher is calling pauseCallback');
2871 NETDATA.options.pause = true;
2872 NETDATA.options.pauseCallback();
2873 NETDATA.chartRefresher();
2877 if(NETDATA.options.current.parallel_refresher === false) {
2878 NETDATA.chartRefresherNoParallel(0);
2882 if(NETDATA.options.updated_dom === true) {
2883 // the dom has been updated
2884 // get the dom parts again
2885 NETDATA.parseDom(NETDATA.chartRefresher);
2889 var parallel = new Array();
2890 var targets = NETDATA.options.targets;
2891 var len = targets.length;
2893 if(targets[len].isVisible() === false)
2896 var state = targets[len];
2897 if(state.library.initialized === false) {
2898 if(state.library.enabled === true) {
2899 state.library.initialize(NETDATA.chartRefresher);
2903 state.error('chart library "' + state.library_name + '" is not enabled.');
2907 parallel.unshift(state);
2910 if(parallel.length > 0) {
2911 var parallel_jobs = parallel.length;
2913 // this will execute the jobs in parallel
2914 $(parallel).each(function() {
2915 this.autoRefresh(function() {
2918 if(parallel_jobs === 0) {
2919 setTimeout(NETDATA.chartRefresher,
2920 NETDATA.chartRefresherWaitTime());
2926 setTimeout(NETDATA.chartRefresher,
2927 NETDATA.chartRefresherWaitTime());
2931 NETDATA.parseDom = function(callback) {
2932 NETDATA.options.last_page_scroll = new Date().getTime();
2933 NETDATA.options.updated_dom = false;
2935 var targets = $('div[data-netdata]'); //.filter(':visible');
2937 if(NETDATA.options.debug.main_loop === true)
2938 console.log('DOM updated - there are ' + targets.length + ' charts on page.');
2940 NETDATA.options.targets = new Array();
2941 var len = targets.length;
2943 // the initialization will take care of sizing
2944 // and the "loading..." message
2945 NETDATA.options.targets.push(NETDATA.chartState(targets[len]));
2948 if(typeof callback === 'function') callback();
2951 // this is the main function - where everything starts
2952 NETDATA.start = function() {
2953 // this should be called only once
2955 NETDATA.options.page_is_visible = true;
2957 $(window).blur(function() {
2958 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
2959 NETDATA.options.page_is_visible = false;
2960 if(NETDATA.options.debug.focus === true)
2961 console.log('Lost Focus!');
2965 $(window).focus(function() {
2966 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
2967 NETDATA.options.page_is_visible = true;
2968 if(NETDATA.options.debug.focus === true)
2969 console.log('Focus restored!');
2973 if(typeof document.hasFocus === 'function' && !document.hasFocus()) {
2974 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
2975 NETDATA.options.page_is_visible = false;
2976 if(NETDATA.options.debug.focus === true)
2977 console.log('Document has no focus!');
2981 // bootstrap tab switching
2982 $('a[data-toggle="tab"]').on('shown.bs.tab', NETDATA.onscroll);
2984 // bootstrap modal switching
2985 $('.modal').on('hidden.bs.modal', NETDATA.onscroll);
2986 $('.modal').on('shown.bs.modal', NETDATA.onscroll);
2988 NETDATA.parseDom(NETDATA.chartRefresher);
2991 // ----------------------------------------------------------------------------------------------------------------
2994 NETDATA.peityInitialize = function(callback) {
2995 if(typeof netdataNoPeitys === 'undefined' || !netdataNoPeitys) {
2997 url: NETDATA.peity_js,
3002 NETDATA.registerChartLibrary('peity', NETDATA.peity_js);
3005 NETDATA.chartLibraries.peity.enabled = false;
3006 NETDATA.error(100, NETDATA.peity_js);
3008 .always(function() {
3009 if(typeof callback === "function")
3014 NETDATA.chartLibraries.peity.enabled = false;
3015 if(typeof callback === "function")
3020 NETDATA.peityChartUpdate = function(state, data) {
3021 state.peity_instance.innerHTML = data.result;
3023 if(state.peity_options.stroke !== state.chartColors()[0]) {
3024 state.peity_options.stroke = state.chartColors()[0];
3025 if(state.chart.chart_type === 'line')
3026 state.peity_options.fill = '#FFF';
3028 state.peity_options.fill = NETDATA.colorLuminance(state.chartColors()[0], NETDATA.chartDefaults.fill_luminance);
3031 $(state.peity_instance).peity('line', state.peity_options);
3035 NETDATA.peityChartCreate = function(state, data) {
3036 state.peity_instance = document.createElement('div');
3037 state.element_chart.appendChild(state.peity_instance);
3039 var self = $(state.element);
3040 state.peity_options = {
3042 strokeWidth: self.data('peity-strokewidth') || 1,
3043 width: state.chartWidth(),
3044 height: state.chartHeight(),
3048 NETDATA.peityChartUpdate(state, data);
3052 // ----------------------------------------------------------------------------------------------------------------
3055 NETDATA.sparklineInitialize = function(callback) {
3056 if(typeof netdataNoSparklines === 'undefined' || !netdataNoSparklines) {
3058 url: NETDATA.sparkline_js,
3063 NETDATA.registerChartLibrary('sparkline', NETDATA.sparkline_js);
3066 NETDATA.chartLibraries.sparkline.enabled = false;
3067 NETDATA.error(100, NETDATA.sparkline_js);
3069 .always(function() {
3070 if(typeof callback === "function")
3075 NETDATA.chartLibraries.sparkline.enabled = false;
3076 if(typeof callback === "function")
3081 NETDATA.sparklineChartUpdate = function(state, data) {
3082 state.sparkline_options.width = state.chartWidth();
3083 state.sparkline_options.height = state.chartHeight();
3085 $(state.element_chart).sparkline(data.result, state.sparkline_options);
3089 NETDATA.sparklineChartCreate = function(state, data) {
3090 var self = $(state.element);
3091 var type = self.data('sparkline-type') || 'line';
3092 var lineColor = self.data('sparkline-linecolor') || state.chartColors()[0];
3093 var fillColor = self.data('sparkline-fillcolor') || (state.chart.chart_type === 'line')?'#FFF':NETDATA.colorLuminance(lineColor, NETDATA.chartDefaults.fill_luminance);
3094 var chartRangeMin = self.data('sparkline-chartrangemin') || undefined;
3095 var chartRangeMax = self.data('sparkline-chartrangemax') || undefined;
3096 var composite = self.data('sparkline-composite') || undefined;
3097 var enableTagOptions = self.data('sparkline-enabletagoptions') || undefined;
3098 var tagOptionPrefix = self.data('sparkline-tagoptionprefix') || undefined;
3099 var tagValuesAttribute = self.data('sparkline-tagvaluesattribute') || undefined;
3100 var disableHiddenCheck = self.data('sparkline-disablehiddencheck') || undefined;
3101 var defaultPixelsPerValue = self.data('sparkline-defaultpixelspervalue') || undefined;
3102 var spotColor = self.data('sparkline-spotcolor') || undefined;
3103 var minSpotColor = self.data('sparkline-minspotcolor') || undefined;
3104 var maxSpotColor = self.data('sparkline-maxspotcolor') || undefined;
3105 var spotRadius = self.data('sparkline-spotradius') || undefined;
3106 var valueSpots = self.data('sparkline-valuespots') || undefined;
3107 var highlightSpotColor = self.data('sparkline-highlightspotcolor') || undefined;
3108 var highlightLineColor = self.data('sparkline-highlightlinecolor') || undefined;
3109 var lineWidth = self.data('sparkline-linewidth') || undefined;
3110 var normalRangeMin = self.data('sparkline-normalrangemin') || undefined;
3111 var normalRangeMax = self.data('sparkline-normalrangemax') || undefined;
3112 var drawNormalOnTop = self.data('sparkline-drawnormalontop') || undefined;
3113 var xvalues = self.data('sparkline-xvalues') || undefined;
3114 var chartRangeClip = self.data('sparkline-chartrangeclip') || undefined;
3115 var xvalues = self.data('sparkline-xvalues') || undefined;
3116 var chartRangeMinX = self.data('sparkline-chartrangeminx') || undefined;
3117 var chartRangeMaxX = self.data('sparkline-chartrangemaxx') || undefined;
3118 var disableInteraction = self.data('sparkline-disableinteraction') || false;
3119 var disableTooltips = self.data('sparkline-disabletooltips') || false;
3120 var disableHighlight = self.data('sparkline-disablehighlight') || false;
3121 var highlightLighten = self.data('sparkline-highlightlighten') || 1.4;
3122 var highlightColor = self.data('sparkline-highlightcolor') || undefined;
3123 var tooltipContainer = self.data('sparkline-tooltipcontainer') || undefined;
3124 var tooltipClassname = self.data('sparkline-tooltipclassname') || undefined;
3125 var tooltipFormat = self.data('sparkline-tooltipformat') || undefined;
3126 var tooltipPrefix = self.data('sparkline-tooltipprefix') || undefined;
3127 var tooltipSuffix = self.data('sparkline-tooltipsuffix') || ' ' + state.units;
3128 var tooltipSkipNull = self.data('sparkline-tooltipskipnull') || true;
3129 var tooltipValueLookups = self.data('sparkline-tooltipvaluelookups') || undefined;
3130 var tooltipFormatFieldlist = self.data('sparkline-tooltipformatfieldlist') || undefined;
3131 var tooltipFormatFieldlistKey = self.data('sparkline-tooltipformatfieldlistkey') || undefined;
3132 var numberFormatter = self.data('sparkline-numberformatter') || function(n){ return n.toFixed(2); };
3133 var numberDigitGroupSep = self.data('sparkline-numberdigitgroupsep') || undefined;
3134 var numberDecimalMark = self.data('sparkline-numberdecimalmark') || undefined;
3135 var numberDigitGroupCount = self.data('sparkline-numberdigitgroupcount') || undefined;
3136 var animatedZooms = self.data('sparkline-animatedzooms') || false;
3138 state.sparkline_options = {
3140 lineColor: lineColor,
3141 fillColor: fillColor,
3142 chartRangeMin: chartRangeMin,
3143 chartRangeMax: chartRangeMax,
3144 composite: composite,
3145 enableTagOptions: enableTagOptions,
3146 tagOptionPrefix: tagOptionPrefix,
3147 tagValuesAttribute: tagValuesAttribute,
3148 disableHiddenCheck: disableHiddenCheck,
3149 defaultPixelsPerValue: defaultPixelsPerValue,
3150 spotColor: spotColor,
3151 minSpotColor: minSpotColor,
3152 maxSpotColor: maxSpotColor,
3153 spotRadius: spotRadius,
3154 valueSpots: valueSpots,
3155 highlightSpotColor: highlightSpotColor,
3156 highlightLineColor: highlightLineColor,
3157 lineWidth: lineWidth,
3158 normalRangeMin: normalRangeMin,
3159 normalRangeMax: normalRangeMax,
3160 drawNormalOnTop: drawNormalOnTop,
3162 chartRangeClip: chartRangeClip,
3163 chartRangeMinX: chartRangeMinX,
3164 chartRangeMaxX: chartRangeMaxX,
3165 disableInteraction: disableInteraction,
3166 disableTooltips: disableTooltips,
3167 disableHighlight: disableHighlight,
3168 highlightLighten: highlightLighten,
3169 highlightColor: highlightColor,
3170 tooltipContainer: tooltipContainer,
3171 tooltipClassname: tooltipClassname,
3172 tooltipChartTitle: state.title,
3173 tooltipFormat: tooltipFormat,
3174 tooltipPrefix: tooltipPrefix,
3175 tooltipSuffix: tooltipSuffix,
3176 tooltipSkipNull: tooltipSkipNull,
3177 tooltipValueLookups: tooltipValueLookups,
3178 tooltipFormatFieldlist: tooltipFormatFieldlist,
3179 tooltipFormatFieldlistKey: tooltipFormatFieldlistKey,
3180 numberFormatter: numberFormatter,
3181 numberDigitGroupSep: numberDigitGroupSep,
3182 numberDecimalMark: numberDecimalMark,
3183 numberDigitGroupCount: numberDigitGroupCount,
3184 animatedZooms: animatedZooms,
3185 width: state.chartWidth(),
3186 height: state.chartHeight()
3189 $(state.element_chart).sparkline(data.result, state.sparkline_options);
3193 // ----------------------------------------------------------------------------------------------------------------
3200 NETDATA.dygraphSetSelection = function(state, t) {
3201 if(typeof state.dygraph_instance !== 'undefined') {
3202 var r = state.calculateRowForTime(t);
3204 state.dygraph_instance.setSelection(r);
3206 state.dygraph_instance.clearSelection();
3207 state.legendShowUndefined();
3214 NETDATA.dygraphClearSelection = function(state, t) {
3215 if(typeof state.dygraph_instance !== 'undefined') {
3216 state.dygraph_instance.clearSelection();
3221 NETDATA.dygraphSmoothInitialize = function(callback) {
3223 url: NETDATA.dygraph_smooth_js,
3228 NETDATA.dygraph.smooth = true;
3229 smoothPlotter.smoothing = 0.3;
3232 NETDATA.dygraph.smooth = false;
3234 .always(function() {
3235 if(typeof callback === "function")
3240 NETDATA.dygraphInitialize = function(callback) {
3241 if(typeof netdataNoDygraphs === 'undefined' || !netdataNoDygraphs) {
3243 url: NETDATA.dygraph_js,
3248 NETDATA.registerChartLibrary('dygraph', NETDATA.dygraph_js);
3251 NETDATA.chartLibraries.dygraph.enabled = false;
3252 NETDATA.error(100, NETDATA.dygraph_js);
3254 .always(function() {
3255 if(NETDATA.chartLibraries.dygraph.enabled === true && NETDATA.options.current.smooth_plot === true)
3256 NETDATA.dygraphSmoothInitialize(callback);
3257 else if(typeof callback === "function")
3262 NETDATA.chartLibraries.dygraph.enabled = false;
3263 if(typeof callback === "function")
3268 NETDATA.dygraphChartUpdate = function(state, data) {
3269 var dygraph = state.dygraph_instance;
3271 if(typeof dygraph === 'undefined')
3272 NETDATA.dygraphChartCreate(state, data);
3274 // when the chart is not visible, and hidden
3275 // if there is a window resize, dygraph detects
3276 // its element size as 0x0.
3277 // this will make it re-appear properly
3279 if(state.tm.last_unhidden > state.dygraph_last_rendered)
3283 file: data.result.data,
3284 colors: state.chartColors(),
3285 labels: data.result.labels,
3286 labelsDivWidth: state.chartWidth() - 70,
3287 visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names)
3290 if(state.current.name === 'pan') {
3291 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3292 state.log('dygraphChartUpdate() loose update');
3295 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3296 state.log('dygraphChartUpdate() strict update');
3298 options.dateWindow = null;
3299 options.valueRange = null;
3302 if(state.dygraph_smooth_eligible === true) {
3303 if((NETDATA.options.current.smooth_plot === true && state.dygraph_options.plotter !== smoothPlotter)
3304 || (NETDATA.options.current.smooth_plot === false && state.dygraph_options.plotter === smoothPlotter)) {
3305 NETDATA.dygraphChartCreate(state, data);
3310 dygraph.updateOptions(options);
3311 state.dygraph_last_rendered = new Date().getTime();
3315 NETDATA.dygraphChartCreate = function(state, data) {
3316 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3317 state.log('dygraphChartCreate()');
3319 var self = $(state.element);
3321 var chart_type = state.chart.chart_type;
3322 if(chart_type === 'stacked' && data.dimensions === 1) chart_type = 'area';
3323 chart_type = self.data('dygraph-type') || chart_type;
3325 var smooth = (chart_type === 'line' && !NETDATA.chartLibraries.dygraph.isSparkline(state))?true:false;
3326 smooth = self.data('dygraph-smooth') || smooth;
3328 if(NETDATA.dygraph.smooth === false)
3331 var strokeWidth = (chart_type === 'stacked')?0.1:((smooth)?1.5:0.7)
3332 var highlightCircleSize = (NETDATA.chartLibraries.dygraph.isSparkline(state))?3:4;
3334 state.dygraph_options = {
3335 colors: self.data('dygraph-colors') || state.chartColors(),
3337 // leave a few pixels empty on the right of the chart
3338 rightGap: self.data('dygraph-rightgap') || 5,
3339 showRangeSelector: self.data('dygraph-showrangeselector') || false,
3340 showRoller: self.data('dygraph-showroller') || false,
3342 title: self.data('dygraph-title') || state.title,
3343 titleHeight: self.data('dygraph-titleheight') || 19,
3345 legend: self.data('dygraph-legend') || 'always', // 'onmouseover',
3346 labels: data.result.labels,
3347 labelsDiv: self.data('dygraph-labelsdiv') || state.element_legend_childs.hidden,
3348 labelsDivStyles: self.data('dygraph-labelsdivstyles') || { 'fontSize':'1px' },
3349 labelsDivWidth: self.data('dygraph-labelsdivwidth') || state.chartWidth() - 70,
3350 labelsSeparateLines: self.data('dygraph-labelsseparatelines') || true,
3351 labelsShowZeroValues: self.data('dygraph-labelsshowzerovalues') || true,
3354 showLabelsOnHighlight: self.data('dygraph-showlabelsonhighlight') || true,
3355 hideOverlayOnMouseOut: self.data('dygraph-hideoverlayonmouseout') || true,
3357 ylabel: state.units,
3358 yLabelWidth: self.data('dygraph-ylabelwidth') || 12,
3360 // the function to plot the chart
3363 // The width of the lines connecting data points. This can be used to increase the contrast or some graphs.
3364 strokeWidth: self.data('dygraph-strokewidth') || strokeWidth,
3365 strokePattern: self.data('dygraph-strokepattern') || undefined,
3367 // The size of the dot to draw on each point in pixels (see drawPoints). A dot is always drawn when a point is "isolated",
3368 // i.e. there is a missing point on either side of it. This also controls the size of those dots.
3369 drawPoints: self.data('dygraph-drawpoints') || false,
3371 // Draw points at the edges of gaps in the data. This improves visibility of small data segments or other data irregularities.
3372 drawGapEdgePoints: self.data('dygraph-drawgapedgepoints') || true,
3374 connectSeparatedPoints: self.data('dygraph-connectseparatedpoints') || false,
3375 pointSize: self.data('dygraph-pointsize') || 1,
3377 // enabling this makes the chart with little square lines
3378 stepPlot: self.data('dygraph-stepplot') || false,
3380 // Draw a border around graph lines to make crossing lines more easily distinguishable. Useful for graphs with many lines.
3381 strokeBorderColor: self.data('dygraph-strokebordercolor') || 'white',
3382 strokeBorderWidth: self.data('dygraph-strokeborderwidth') || (chart_type === 'stacked')?0.0:0.0,
3384 fillGraph: self.data('dygraph-fillgraph') || (chart_type === 'area' || chart_type === 'stacked')?true:false,
3385 fillAlpha: self.data('dygraph-fillalpha') || (chart_type === 'stacked')?NETDATA.options.current.color_fill_opacity_stacked:NETDATA.options.current.color_fill_opacity_area,
3386 stackedGraph: self.data('dygraph-stackedgraph') || (chart_type === 'stacked')?true:false,
3387 stackedGraphNaNFill: self.data('dygraph-stackedgraphnanfill') || 'none',
3389 drawAxis: self.data('dygraph-drawaxis') || true,
3390 axisLabelFontSize: self.data('dygraph-axislabelfontsize') || 10,
3391 axisLineColor: self.data('dygraph-axislinecolor') || '#CCC',
3392 axisLineWidth: self.data('dygraph-axislinewidth') || 0.3,
3394 drawGrid: self.data('dygraph-drawgrid') || true,
3395 drawXGrid: self.data('dygraph-drawxgrid') || undefined,
3396 drawYGrid: self.data('dygraph-drawygrid') || undefined,
3397 gridLinePattern: self.data('dygraph-gridlinepattern') || null,
3398 gridLineWidth: self.data('dygraph-gridlinewidth') || 0.3,
3399 gridLineColor: self.data('dygraph-gridlinecolor') || '#DDD',
3401 maxNumberWidth: self.data('dygraph-maxnumberwidth') || 8,
3402 sigFigs: self.data('dygraph-sigfigs') || null,
3403 digitsAfterDecimal: self.data('dygraph-digitsafterdecimal') || 2,
3404 valueFormatter: self.data('dygraph-valueformatter') || function(x){ return x.toFixed(2); },
3406 highlightCircleSize: self.data('dygraph-highlightcirclesize') || highlightCircleSize,
3407 highlightSeriesOpts: self.data('dygraph-highlightseriesopts') || null, // TOO SLOW: { strokeWidth: 1.5 },
3408 highlightSeriesBackgroundAlpha: self.data('dygraph-highlightseriesbackgroundalpha') || null, // TOO SLOW: (chart_type === 'stacked')?0.7:0.5,
3410 pointClickCallback: self.data('dygraph-pointclickcallback') || undefined,
3411 visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names),
3415 ticker: Dygraph.dateTicker,
3416 axisLabelFormatter: function (d, gran) {
3417 return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds());
3419 valueFormatter: function (ms) {
3420 var d = new Date(ms);
3421 return d.toLocaleDateString() + ' ' + d.toLocaleTimeString();
3422 // return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds());
3427 valueFormatter: function (x) {
3428 // we format legends with the state object
3429 // no need to do anything here
3430 // return (Math.round(x*100) / 100).toLocaleString();
3431 // return state.legendFormatValue(x);
3436 legendFormatter: function(data) {
3437 var elements = state.element_legend_childs;
3439 // if the hidden div is not there
3440 // we are not managing the legend
3441 if(elements.hidden === null) return;
3443 if (typeof data.x !== 'undefined') {
3444 state.legendSetDate(data.x);
3445 var i = data.series.length;
3447 var series = data.series[i];
3448 if(!series.isVisible) continue;
3449 state.legendSetLabelValue(series.label, series.y);
3455 drawCallback: function(dygraph, is_initial) {
3456 if(state.current.name !== 'auto') {
3457 if(NETDATA.options.debug.dygraph === true)
3458 state.log('dygraphDrawCallback()');
3460 var first = state.data.first_entry * 1000;
3461 var last = state.data.last_entry * 1000;
3463 var x_range = dygraph.xAxisRange();
3464 var after = Math.round(x_range[0]);
3465 var before = Math.round(x_range[1]);
3467 if(before <= last && after >= first)
3468 state.updateChartPanOrZoom(after, before);
3471 zoomCallback: function(minDate, maxDate, yRanges) {
3472 if(NETDATA.options.debug.dygraph === true)
3473 state.log('dygraphZoomCallback()');
3475 state.globalSelectionSyncStop();
3476 state.globalSelectionSyncDelay();
3478 if(state.updateChartPanOrZoom(minDate, maxDate) === false) {
3479 // we should not zoom that much
3480 state.dygraph_instance.updateOptions({
3486 highlightCallback: function(event, x, points, row, seriesName) {
3487 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3488 state.log('dygraphHighlightCallback()');
3492 // there is a bug in dygraph when the chart is zoomed enough
3493 // the time it thinks is selected is wrong
3494 // here we calculate the time t based on the row number selected
3496 var t = state.data_after + row * state.data_update_every;
3497 // console.log('row = ' + row + ', x = ' + x + ', t = ' + t + ' ' + ((t === x)?'SAME':'DIFFERENT') + ', rows in db: ' + state.data_points + ' visible(x) = ' + state.timeIsVisible(x) + ' visible(t) = ' + state.timeIsVisible(t) + ' r(x) = ' + state.calculateRowForTime(x) + ' r(t) = ' + state.calculateRowForTime(t) + ' range: ' + state.data_after + ' - ' + state.data_before + ' real: ' + state.data.after + ' - ' + state.data.before + ' every: ' + state.data_update_every);
3499 state.globalSelectionSync(t);
3501 // fix legend zIndex using the internal structures of dygraph legend module
3502 // this works, but it is a hack!
3503 // state.dygraph_instance.plugins_[0].plugin.legend_div_.style.zIndex = 10000;
3505 unhighlightCallback: function(event) {
3506 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3507 state.log('dygraphUnhighlightCallback()');
3509 state.unpauseChart();
3510 state.globalSelectionSyncStop();
3512 interactionModel : {
3513 mousedown: function(event, dygraph, context) {
3514 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3515 state.log('interactionModel.mousedown()');
3517 state.globalSelectionSyncStop();
3519 if(NETDATA.options.debug.dygraph === true)
3520 state.log('dygraphMouseDown()');
3522 // Right-click should not initiate a zoom.
3523 if(event.button && event.button === 2) return;
3525 context.initializeMouseDown(event, dygraph, context);
3527 if(event.button && event.button === 1) {
3528 if (event.altKey || event.shiftKey) {
3529 state.setMode('pan');
3530 state.globalSelectionSyncDelay();
3531 Dygraph.startPan(event, dygraph, context);
3534 state.setMode('zoom');
3535 state.globalSelectionSyncDelay();
3536 Dygraph.startZoom(event, dygraph, context);
3540 if (event.altKey || event.shiftKey) {
3541 state.setMode('zoom');
3542 state.globalSelectionSyncDelay();
3543 Dygraph.startZoom(event, dygraph, context);
3546 state.setMode('pan');
3547 state.globalSelectionSyncDelay();
3548 Dygraph.startPan(event, dygraph, context);
3552 mousemove: function(event, dygraph, context) {
3553 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3554 state.log('interactionModel.mousemove()');
3556 if(context.isPanning) {
3557 state.globalSelectionSyncStop();
3558 state.globalSelectionSyncDelay();
3559 state.setMode('pan');
3560 Dygraph.movePan(event, dygraph, context);
3562 else if(context.isZooming) {
3563 state.globalSelectionSyncStop();
3564 state.globalSelectionSyncDelay();
3565 state.setMode('zoom');
3566 Dygraph.moveZoom(event, dygraph, context);
3569 mouseup: function(event, dygraph, context) {
3570 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3571 state.log('interactionModel.mouseup()');
3573 if (context.isPanning) {
3574 state.globalSelectionSyncDelay();
3575 Dygraph.endPan(event, dygraph, context);
3577 else if (context.isZooming) {
3578 state.globalSelectionSyncDelay();
3579 Dygraph.endZoom(event, dygraph, context);
3582 click: function(event, dygraph, context) {
3583 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3584 state.log('interactionModel.click()');
3586 event.preventDefault();
3588 dblclick: function(event, dygraph, context) {
3589 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3590 state.log('interactionModel.dblclick()');
3591 NETDATA.resetAllCharts(state);
3593 mousewheel: function(event, dygraph, context) {
3594 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3595 state.log('interactionModel.mousewheel()');
3597 // Take the offset of a mouse event on the dygraph canvas and
3598 // convert it to a pair of percentages from the bottom left.
3599 // (Not top left, bottom is where the lower value is.)
3600 function offsetToPercentage(g, offsetX, offsetY) {
3601 // This is calculating the pixel offset of the leftmost date.
3602 var xOffset = g.toDomCoords(g.xAxisRange()[0], null)[0];
3603 var yar0 = g.yAxisRange(0);
3605 // This is calculating the pixel of the higest value. (Top pixel)
3606 var yOffset = g.toDomCoords(null, yar0[1])[1];
3608 // x y w and h are relative to the corner of the drawing area,
3609 // so that the upper corner of the drawing area is (0, 0).
3610 var x = offsetX - xOffset;
3611 var y = offsetY - yOffset;
3613 // This is computing the rightmost pixel, effectively defining the
3615 var w = g.toDomCoords(g.xAxisRange()[1], null)[0] - xOffset;
3617 // This is computing the lowest pixel, effectively defining the height.
3618 var h = g.toDomCoords(null, yar0[0])[1] - yOffset;
3620 // Percentage from the left.
3621 var xPct = w === 0 ? 0 : (x / w);
3622 // Percentage from the top.
3623 var yPct = h === 0 ? 0 : (y / h);
3625 // The (1-) part below changes it from "% distance down from the top"
3626 // to "% distance up from the bottom".
3627 return [xPct, (1-yPct)];
3630 // Adjusts [x, y] toward each other by zoomInPercentage%
3631 // Split it so the left/bottom axis gets xBias/yBias of that change and
3632 // tight/top gets (1-xBias)/(1-yBias) of that change.
3634 // If a bias is missing it splits it down the middle.
3635 function zoomRange(g, zoomInPercentage, xBias, yBias) {
3636 xBias = xBias || 0.5;
3637 yBias = yBias || 0.5;
3639 function adjustAxis(axis, zoomInPercentage, bias) {
3640 var delta = axis[1] - axis[0];
3641 var increment = delta * zoomInPercentage;
3642 var foo = [increment * bias, increment * (1-bias)];
3644 return [ axis[0] + foo[0], axis[1] - foo[1] ];
3647 var yAxes = g.yAxisRanges();
3649 for (var i = 0; i < yAxes.length; i++) {
3650 newYAxes[i] = adjustAxis(yAxes[i], zoomInPercentage, yBias);
3653 return adjustAxis(g.xAxisRange(), zoomInPercentage, xBias);
3656 if(event.altKey || event.shiftKey) {
3657 state.globalSelectionSyncStop();
3658 state.globalSelectionSyncDelay();
3660 // http://dygraphs.com/gallery/interaction-api.js
3661 var normal = (event.detail) ? event.detail * -1 : event.wheelDelta / 40;
3662 var percentage = normal / 50;
3664 if (!(event.offsetX && event.offsetY)){
3665 event.offsetX = event.layerX - event.target.offsetLeft;
3666 event.offsetY = event.layerY - event.target.offsetTop;
3669 var percentages = offsetToPercentage(dygraph, event.offsetX, event.offsetY);
3670 var xPct = percentages[0];
3671 var yPct = percentages[1];
3673 var new_x_range = zoomRange(dygraph, percentage, xPct, yPct);
3675 var after = new_x_range[0];
3676 var before = new_x_range[1];
3678 var first = (state.data.first_entry + state.data.view_update_every) * 1000;
3679 var last = (state.data.last_entry + state.data.view_update_every) * 1000;
3682 after -= (before - last);
3689 state.setMode('zoom');
3690 if(state.updateChartPanOrZoom(after, before) === true)
3691 dygraph.updateOptions({ dateWindow: [ after, before ] });
3693 event.preventDefault();
3696 touchstart: function(event, dygraph, context) {
3697 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3698 state.log('interactionModel.touchstart()');
3700 state.setMode('zoom');
3703 Dygraph.defaultInteractionModel.touchstart(event, dygraph, context);
3705 // we overwrite the touch directions at the end, to overwrite
3706 // the internal default of dygraphs
3707 context.touchDirections = { x: true, y: false };
3709 state.dygraph_last_touch_start = new Date().getTime();
3710 state.dygraph_last_touch_move = 0;
3712 if(typeof event.touches[0].pageX === 'number')
3713 state.dygraph_last_touch_page_x = event.touches[0].pageX;
3715 state.dygraph_last_touch_page_x = 0;
3717 touchmove: function(event, dygraph, context) {
3718 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3719 state.log('interactionModel.touchmove()');
3721 Dygraph.defaultInteractionModel.touchmove(event, dygraph, context);
3723 state.dygraph_last_touch_move = new Date().getTime();
3725 touchend: function(event, dygraph, context) {
3726 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3727 state.log('interactionModel.touchend()');
3729 Dygraph.defaultInteractionModel.touchend(event, dygraph, context);
3731 // if it didn't move, it is a selection
3732 if(state.dygraph_last_touch_move === 0 && state.dygraph_last_touch_page_x !== 0) {
3733 // internal api of dygraphs
3734 var pct = (state.dygraph_last_touch_page_x - (dygraph.plotter_.area.x + state.element.getBoundingClientRect().left)) / dygraph.plotter_.area.w;
3735 var t = Math.round(state.data_after + (state.data_before - state.data_after) * pct);
3736 if(NETDATA.dygraphSetSelection(state, t) === true)
3737 state.globalSelectionSync(t);
3740 // if it was double tap within double click time, reset the charts
3741 var now = new Date().getTime();
3742 if(typeof state.dygraph_last_touch_end !== 'undefined') {
3743 if(state.dygraph_last_touch_move === 0) {
3744 var dt = now - state.dygraph_last_touch_end;
3745 if(dt <= NETDATA.options.current.double_click_speed)
3746 NETDATA.resetAllCharts(state);
3750 // remember the timestamp of the last touch end
3751 state.dygraph_last_touch_end = now;
3756 if(NETDATA.chartLibraries.dygraph.isSparkline(state)) {
3757 state.dygraph_options.drawGrid = false;
3758 state.dygraph_options.drawAxis = false;
3759 state.dygraph_options.title = undefined;
3760 state.dygraph_options.units = undefined;
3761 state.dygraph_options.ylabel = undefined;
3762 state.dygraph_options.yLabelWidth = 0;
3763 state.dygraph_options.labelsDivWidth = 120;
3764 state.dygraph_options.labelsDivStyles.width = '120px';
3765 state.dygraph_options.labelsSeparateLines = true;
3766 state.dygraph_options.rightGap = 0;
3769 if(smooth === true) {
3770 state.dygraph_smooth_eligible = true;
3772 if(NETDATA.options.current.smooth_plot === true)
3773 state.dygraph_options.plotter = smoothPlotter;
3775 else state.dygraph_smooth_eligible = false;
3777 state.dygraph_instance = new Dygraph(state.element_chart,
3778 data.result.data, state.dygraph_options);
3780 state.dygraph_last_rendered = new Date().getTime();
3784 // ----------------------------------------------------------------------------------------------------------------
3787 NETDATA.morrisInitialize = function(callback) {
3788 if(typeof netdataNoMorris === 'undefined' || !netdataNoMorris) {
3790 // morris requires raphael
3791 if(!NETDATA.chartLibraries.raphael.initialized) {
3792 if(NETDATA.chartLibraries.raphael.enabled) {
3793 NETDATA.raphaelInitialize(function() {
3794 NETDATA.morrisInitialize(callback);
3798 NETDATA.chartLibraries.morris.enabled = false;
3799 if(typeof callback === "function")
3804 NETDATA._loadCSS(NETDATA.morris_css);
3807 url: NETDATA.morris_js,
3812 NETDATA.registerChartLibrary('morris', NETDATA.morris_js);
3815 NETDATA.chartLibraries.morris.enabled = false;
3816 NETDATA.error(100, NETDATA.morris_js);
3818 .always(function() {
3819 if(typeof callback === "function")
3825 NETDATA.chartLibraries.morris.enabled = false;
3826 if(typeof callback === "function")
3831 NETDATA.morrisChartUpdate = function(state, data) {
3832 state.morris_instance.setData(data.result.data);
3836 NETDATA.morrisChartCreate = function(state, data) {
3838 state.morris_options = {
3839 element: state.element_chart.id,
3840 data: data.result.data,
3842 ykeys: data.dimension_names,
3843 labels: data.dimension_names,
3849 continuousLine: false,
3850 behaveLikeLine: false
3853 if(state.chart.chart_type === 'line')
3854 state.morris_instance = new Morris.Line(state.morris_options);
3856 else if(state.chart.chart_type === 'area') {
3857 state.morris_options.behaveLikeLine = true;
3858 state.morris_instance = new Morris.Area(state.morris_options);
3861 state.morris_instance = new Morris.Area(state.morris_options);
3866 // ----------------------------------------------------------------------------------------------------------------
3869 NETDATA.raphaelInitialize = function(callback) {
3870 if(typeof netdataStopRaphael === 'undefined' || !netdataStopRaphael) {
3872 url: NETDATA.raphael_js,
3877 NETDATA.registerChartLibrary('raphael', NETDATA.raphael_js);
3880 NETDATA.chartLibraries.raphael.enabled = false;
3881 NETDATA.error(100, NETDATA.raphael_js);
3883 .always(function() {
3884 if(typeof callback === "function")
3889 NETDATA.chartLibraries.raphael.enabled = false;
3890 if(typeof callback === "function")
3895 NETDATA.raphaelChartUpdate = function(state, data) {
3896 $(state.element_chart).raphael(data.result, {
3897 width: state.chartWidth(),
3898 height: state.chartHeight()
3904 NETDATA.raphaelChartCreate = function(state, data) {
3905 $(state.element_chart).raphael(data.result, {
3906 width: state.chartWidth(),
3907 height: state.chartHeight()
3913 // ----------------------------------------------------------------------------------------------------------------
3916 NETDATA.c3Initialize = function(callback) {
3917 if(typeof netdataNoC3 === 'undefined' || !netdataNoC3) {
3920 if(!NETDATA.chartLibraries.d3.initialized) {
3921 if(NETDATA.chartLibraries.d3.enabled) {
3922 NETDATA.d3Initialize(function() {
3923 NETDATA.c3Initialize(callback);
3927 NETDATA.chartLibraries.c3.enabled = false;
3928 if(typeof callback === "function")
3933 NETDATA._loadCSS(NETDATA.c3_css);
3941 NETDATA.registerChartLibrary('c3', NETDATA.c3_js);
3944 NETDATA.chartLibraries.c3.enabled = false;
3945 NETDATA.error(100, NETDATA.c3_js);
3947 .always(function() {
3948 if(typeof callback === "function")
3954 NETDATA.chartLibraries.c3.enabled = false;
3955 if(typeof callback === "function")
3960 NETDATA.c3ChartUpdate = function(state, data) {
3961 state.c3_instance.destroy();
3962 return NETDATA.c3ChartCreate(state, data);
3964 //state.c3_instance.load({
3965 // rows: data.result,
3972 NETDATA.c3ChartCreate = function(state, data) {
3974 state.element_chart.id = 'c3-' + state.uuid;
3975 // console.log('id = ' + state.element_chart.id);
3977 state.c3_instance = c3.generate({
3978 bindto: '#' + state.element_chart.id,
3980 width: state.chartWidth(),
3981 height: state.chartHeight()
3984 pattern: state.chartColors()
3989 type: (state.chart.chart_type === 'line')?'spline':'area-spline'
3995 format: function(x) {
3996 return NETDATA.zeropad(x.getHours()) + ":" + NETDATA.zeropad(x.getMinutes()) + ":" + NETDATA.zeropad(x.getSeconds());
4023 // console.log(state.c3_instance);
4028 // ----------------------------------------------------------------------------------------------------------------
4031 NETDATA.d3Initialize = function(callback) {
4032 if(typeof netdataStopD3 === 'undefined' || !netdataStopD3) {
4039 NETDATA.registerChartLibrary('d3', NETDATA.d3_js);
4042 NETDATA.chartLibraries.d3.enabled = false;
4043 NETDATA.error(100, NETDATA.d3_js);
4045 .always(function() {
4046 if(typeof callback === "function")
4051 NETDATA.chartLibraries.d3.enabled = false;
4052 if(typeof callback === "function")
4057 NETDATA.d3ChartUpdate = function(state, data) {
4061 NETDATA.d3ChartCreate = function(state, data) {
4065 // ----------------------------------------------------------------------------------------------------------------
4068 NETDATA.googleInitialize = function(callback) {
4069 if(typeof netdataNoGoogleCharts === 'undefined' || !netdataNoGoogleCharts) {
4071 url: NETDATA.google_js,
4076 NETDATA.registerChartLibrary('google', NETDATA.google_js);
4077 google.load('visualization', '1.1', {
4078 'packages': ['corechart', 'controls'],
4079 'callback': callback
4083 NETDATA.chartLibraries.google.enabled = false;
4084 NETDATA.error(100, NETDATA.google_js);
4085 if(typeof callback === "function")
4090 NETDATA.chartLibraries.google.enabled = false;
4091 if(typeof callback === "function")
4096 NETDATA.googleChartUpdate = function(state, data) {
4097 var datatable = new google.visualization.DataTable(data.result);
4098 state.google_instance.draw(datatable, state.google_options);
4102 NETDATA.googleChartCreate = function(state, data) {
4103 var datatable = new google.visualization.DataTable(data.result);
4105 state.google_options = {
4106 colors: state.chartColors(),
4108 // do not set width, height - the chart resizes itself
4109 //width: state.chartWidth(),
4110 //height: state.chartHeight(),
4115 // title: "Time of Day",
4116 // format:'HH:mm:ss',
4117 viewWindowMode: 'maximized',
4129 viewWindowMode: 'pretty',
4144 focusTarget: 'category',
4151 titlePosition: 'out',
4162 curveType: 'function',
4167 switch(state.chart.chart_type) {
4169 state.google_options.vAxis.viewWindowMode = 'maximized';
4170 state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_area;
4171 state.google_instance = new google.visualization.AreaChart(state.element_chart);
4175 state.google_options.isStacked = true;
4176 state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_stacked;
4177 state.google_options.vAxis.viewWindowMode = 'maximized';
4178 state.google_options.vAxis.minValue = null;
4179 state.google_options.vAxis.maxValue = null;
4180 state.google_instance = new google.visualization.AreaChart(state.element_chart);
4185 state.google_options.lineWidth = 2;
4186 state.google_instance = new google.visualization.LineChart(state.element_chart);
4190 state.google_instance.draw(datatable, state.google_options);
4194 // ----------------------------------------------------------------------------------------------------------------
4196 NETDATA.percentFromValueMax = function(value, max) {
4197 if(value === null) value = 0;
4198 if(max < value) max = value;
4202 pcent = Math.round(value * 100 / max);
4203 if(pcent === 0 && value > 0) pcent = 1;
4209 // ----------------------------------------------------------------------------------------------------------------
4212 NETDATA.easypiechartInitialize = function(callback) {
4213 if(typeof netdataNoEasyPieChart === 'undefined' || !netdataNoEasyPieChart) {
4215 url: NETDATA.easypiechart_js,
4220 NETDATA.registerChartLibrary('easypiechart', NETDATA.easypiechart_js);
4223 NETDATA.error(100, NETDATA.easypiechart_js);
4225 .always(function() {
4226 if(typeof callback === "function")
4231 NETDATA.chartLibraries.easypiechart.enabled = false;
4232 if(typeof callback === "function")
4237 NETDATA.easypiechartClearSelection = function(state) {
4238 if(typeof state.easyPieChartEvent !== 'undefined') {
4239 if(state.easyPieChartEvent.timer !== null)
4240 clearTimeout(state.easyPieChartEvent.timer);
4242 state.easyPieChartEvent.timer = null;
4245 if(state.isAutoRefreshed() === true && state.data !== null) {
4246 NETDATA.easypiechartChartUpdate(state, state.data);
4249 state.easyPieChartLabel.innerHTML = state.legendFormatValue(null);
4250 state.easyPieChart_instance.update(0);
4252 state.easyPieChart_instance.enableAnimation();
4257 NETDATA.easypiechartSetSelection = function(state, t) {
4258 if(t < state.data_after || t > state.data_before)
4259 return NETDATA.easypiechartClearSelection(state);
4261 var slot = Math.floor(state.data.result.length - 1 - (t - state.data_after) / state.data_update_every);
4262 if(slot < 0 || slot >= state.data.result.length)
4263 return NETDATA.easypiechartClearSelection(state);
4265 if(typeof state.easyPieChartEvent === 'undefined') {
4266 state.easyPieChartEvent = {
4273 var value = state.data.result[slot];
4274 var max = (state.easyPieChartMax === null)?state.data.max:state.easyPieChartMax;
4275 var pcent = NETDATA.percentFromValueMax(value, max);
4277 state.easyPieChartEvent.value = value;
4278 state.easyPieChartEvent.pcent = pcent;
4279 state.easyPieChartLabel.innerHTML = state.legendFormatValue(value);
4281 if(state.easyPieChartEvent.timer === null) {
4282 state.easyPieChart_instance.disableAnimation();
4284 state.easyPieChartEvent.timer = setTimeout(function() {
4285 state.easyPieChartEvent.timer = null;
4286 state.easyPieChart_instance.update(state.easyPieChartEvent.pcent);
4293 NETDATA.easypiechartChartUpdate = function(state, data) {
4294 var value, max, pcent;
4296 if(NETDATA.globalPanAndZoom.isActive() === true || state.isAutoRefreshed() === false) {
4302 value = data.result[0];
4303 max = (state.easyPieChartMax === null)?data.max:state.easyPieChartMax;
4304 pcent = NETDATA.percentFromValueMax(value, max);
4307 state.easyPieChartLabel.innerHTML = state.legendFormatValue(value);
4308 state.easyPieChart_instance.update(pcent);
4312 NETDATA.easypiechartChartCreate = function(state, data) {
4313 var self = $(state.element);
4314 var chart = $(state.element_chart);
4316 var value = data.result[0];
4317 var max = self.data('easypiechart-max-value') || null;
4318 var adjust = self.data('easypiechart-adjust') || null;
4322 state.easyPieChartMax = null;
4325 state.easyPieChartMax = max;
4327 var pcent = NETDATA.percentFromValueMax(value, max);
4329 chart.data('data-percent', pcent);
4333 case 'width': size = state.chartHeight(); break;
4334 case 'min': size = Math.min(state.chartWidth(), state.chartHeight()); break;
4335 case 'max': size = Math.max(state.chartWidth(), state.chartHeight()); break;
4337 default: size = state.chartWidth(); break;
4339 state.element.style.width = size + 'px';
4340 state.element.style.height = size + 'px';
4342 var stroke = Math.floor(size / 22);
4343 if(stroke < 3) stroke = 2;
4345 var valuefontsize = Math.floor((size * 2 / 3) / 5);
4346 var valuetop = Math.round((size - valuefontsize - (size / 40)) / 2);
4347 state.easyPieChartLabel = document.createElement('span');
4348 state.easyPieChartLabel.className = 'easyPieChartLabel';
4349 state.easyPieChartLabel.innerHTML = state.legendFormatValue(value);
4350 state.easyPieChartLabel.style.fontSize = valuefontsize + 'px';
4351 state.easyPieChartLabel.style.top = valuetop.toString() + 'px';
4352 state.element_chart.appendChild(state.easyPieChartLabel);
4354 var titlefontsize = Math.round(valuefontsize * 1.6 / 3);
4355 var titletop = Math.round(valuetop - (titlefontsize * 2) - (size / 40));
4356 state.easyPieChartTitle = document.createElement('span');
4357 state.easyPieChartTitle.className = 'easyPieChartTitle';
4358 state.easyPieChartTitle.innerHTML = state.title;
4359 state.easyPieChartTitle.style.fontSize = titlefontsize + 'px';
4360 state.easyPieChartTitle.style.lineHeight = titlefontsize + 'px';
4361 state.easyPieChartTitle.style.top = titletop.toString() + 'px';
4362 state.element_chart.appendChild(state.easyPieChartTitle);
4364 var unitfontsize = Math.round(titlefontsize * 0.9);
4365 var unittop = Math.round(valuetop + (valuefontsize + unitfontsize) + (size / 40));
4366 state.easyPieChartUnits = document.createElement('span');
4367 state.easyPieChartUnits.className = 'easyPieChartUnits';
4368 state.easyPieChartUnits.innerHTML = state.units;
4369 state.easyPieChartUnits.style.fontSize = unitfontsize + 'px';
4370 state.easyPieChartUnits.style.top = unittop.toString() + 'px';
4371 state.element_chart.appendChild(state.easyPieChartUnits);
4373 chart.easyPieChart({
4374 barColor: self.data('easypiechart-barcolor') || state.chartColors()[0], //'#ef1e25',
4375 trackColor: self.data('easypiechart-trackcolor') || '#f0f0f0',
4376 scaleColor: self.data('easypiechart-scalecolor') || '#dfe0e0',
4377 scaleLength: self.data('easypiechart-scalelength') || 5,
4378 lineCap: self.data('easypiechart-linecap') || 'round',
4379 lineWidth: self.data('easypiechart-linewidth') || stroke,
4380 trackWidth: self.data('easypiechart-trackwidth') || undefined,
4381 size: self.data('easypiechart-size') || size,
4382 rotate: self.data('easypiechart-rotate') || 0,
4383 animate: self.data('easypiechart-rotate') || {duration: 500, enabled: true},
4384 easing: self.data('easypiechart-easing') || undefined
4387 // when we just re-create the chart
4388 // do not animate the first update
4390 if(typeof state.easyPieChart_instance !== 'undefined')
4393 state.easyPieChart_instance = chart.data('easyPieChart');
4394 if(animate === false) state.easyPieChart_instance.disableAnimation();
4395 state.easyPieChart_instance.update(pcent);
4396 if(animate === false) state.easyPieChart_instance.enableAnimation();
4400 // ----------------------------------------------------------------------------------------------------------------
4403 NETDATA.gaugeInitialize = function(callback) {
4404 if(typeof netdataNoGauge === 'undefined' || !netdataNoGauge) {
4406 url: NETDATA.gauge_js,
4411 NETDATA.registerChartLibrary('gauge', NETDATA.gauge_js);
4414 NETDATA.error(100, NETDATA.gauge_js);
4416 .always(function() {
4417 if(typeof callback === "function")
4422 NETDATA.chartLibraries.gauge.enabled = false;
4423 if(typeof callback === "function")
4428 NETDATA.gaugeAnimation = function(state, status) {
4431 if(typeof status === 'boolean' && status === false)
4433 else if(typeof status === 'number')
4436 state.gauge_instance.animationSpeed = speed;
4437 state.___gaugeOld__.speed = speed;
4440 NETDATA.gaugeSet = function(state, value, min, max) {
4441 if(typeof value !== 'number') value = 0;
4442 if(typeof min !== 'number') min = 0;
4443 if(typeof max !== 'number') max = 0;
4444 if(value > max) max = value;
4445 if(value < min) min = value;
4447 var dvalue = state.gauge_instance.displayedValue;
4449 if(dvalue >= min && dvalue <= max) {
4450 state.gauge_instance.minValue = min;
4451 state.gauge_instance.maxValue = max;
4452 state.gauge_instance.set(value);
4455 // the current display value of the gauge
4456 // is outside min-max.
4457 // we have to disable animation
4458 // otherwise, the gauge will go crazy
4459 var old_speed = state.___gaugeOld__.speed;
4460 NETDATA.gaugeAnimation(state, false);
4461 state.gauge_instance.minValue = min;
4462 state.gauge_instance.maxValue = max;
4463 state.gauge_instance.set(value);
4464 NETDATA.gaugeAnimation(state, old_speed);
4467 state.___gaugeOld__.value = value;
4468 state.___gaugeOld__.min = min;
4469 state.___gaugeOld__.max = max;
4472 NETDATA.gaugeSetLabels = function(state, value, min, max) {
4473 if(state.___gaugeOld__.valueLabel !== value) {
4474 state.___gaugeOld__.valueLabel = value;
4475 state.gaugeChartLabel.innerHTML = state.legendFormatValue(value);
4477 if(state.___gaugeOld__.minLabel !== min) {
4478 state.___gaugeOld__.minLabel = min;
4479 state.gaugeChartMin.innerHTML = state.legendFormatValue(min);
4481 if(state.___gaugeOld__.maxLabel !== max) {
4482 state.___gaugeOld__.maxLabel = max;
4483 state.gaugeChartMax.innerHTML = state.legendFormatValue(max);
4487 NETDATA.gaugeClearSelection = function(state) {
4488 if(typeof state.gaugeEvent !== 'undefined') {
4489 if(state.gaugeEvent.timer !== null)
4490 clearTimeout(state.gaugeEvent.timer);
4492 state.gaugeEvent.timer = null;
4495 if(state.isAutoRefreshed() === true && state.data !== null) {
4496 NETDATA.gaugeChartUpdate(state, state.data);
4499 NETDATA.gaugeAnimation(state, false);
4500 NETDATA.gaugeSet(state, null, null, null);
4501 NETDATA.gaugeSetLabels(state, null, null, null);
4504 NETDATA.gaugeAnimation(state, true);
4508 NETDATA.gaugeSetSelection = function(state, t) {
4509 if(t < state.data_after || t > state.data_before)
4510 return NETDATA.gaugeClearSelection(state);
4512 var slot = Math.floor(state.data.result.length - 1 - (t - state.data_after) / state.data_update_every);
4513 if(slot < 0 || slot >= state.data.result.length)
4514 return NETDATA.gaugeClearSelection(state);
4516 if(typeof state.gaugeEvent === 'undefined') {
4517 state.gaugeEvent = {
4525 var value = state.data.result[slot];
4526 var max = (state.gaugeMax === null)?state.data.max:state.gaugeMax;
4529 state.gaugeEvent.value = value;
4530 state.gaugeEvent.max = max;
4531 state.gaugeEvent.min = min;
4532 NETDATA.gaugeSetLabels(state, value, min, max);
4534 if(state.gaugeEvent.timer === null) {
4535 NETDATA.gaugeAnimation(state, false);
4537 state.gaugeEvent.timer = setTimeout(function() {
4538 state.gaugeEvent.timer = null;
4539 NETDATA.gaugeSet(state, state.gaugeEvent.value, state.gaugeEvent.min, state.gaugeEvent.max);
4546 NETDATA.gaugeChartUpdate = function(state, data) {
4547 var value, min, max;
4549 if(NETDATA.globalPanAndZoom.isActive() === true || state.isAutoRefreshed() === false) {
4553 NETDATA.gaugeSetLabels(state, null, null, null);
4556 value = data.result[0];
4558 max = (state.gaugeMax === null)?data.max:state.gaugeMax;
4559 if(value > max) max = value;
4560 NETDATA.gaugeSetLabels(state, value, min, max);
4563 NETDATA.gaugeSet(state, value, min, max);
4567 NETDATA.gaugeChartCreate = function(state, data) {
4568 var self = $(state.element);
4569 var chart = $(state.element_chart);
4571 var value = data.result[0];
4572 var max = self.data('gauge-max-value') || null;
4573 var adjust = self.data('gauge-adjust') || null;
4577 state.gaugeMax = null;
4580 state.gaugeMax = max;
4582 var width = state.chartWidth(), height = state.chartHeight(); //, ratio = 1.5;
4584 // case 'width': width = height * ratio; break;
4586 // default: height = width / ratio; break;
4588 //state.element.style.width = width.toString() + 'px';
4589 //state.element.style.height = height.toString() + 'px';
4594 lines: 12, // The number of lines to draw
4595 angle: 0.15, // The length of each line
4596 lineWidth: 0.44, // 0.44 The line thickness
4598 length: 0.8, // 0.9 The radius of the inner circle
4599 strokeWidth: 0.035, // The rotation offset
4600 color: '#C0C0C0' // Fill color
4602 colorStart: state.chartColors()[0], // Colors
4603 colorStop: void 0, // just experiment with them
4604 strokeColor: '#F0F0F0', // to see which ones work best for you
4606 generateGradient: false,
4609 [0.0, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 0))],
4610 [0.1, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 1))],
4611 [0.2, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 2))],
4612 [0.3, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 3))],
4613 [0.4, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 4))],
4614 [0.5, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 5))],
4615 [0.6, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 6))],
4616 [0.7, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 7))],
4617 [0.8, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 8))],
4618 [0.9, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 9))],
4619 [1.0, state.chartColors()[0]]]
4622 state.gauge_canvas = document.createElement('canvas');
4623 state.gauge_canvas.id = 'gauge-' + state.uuid + '-canvas';
4624 state.gauge_canvas.className = 'gaugeChart';
4625 state.gauge_canvas.width = width;
4626 state.gauge_canvas.height = height;
4627 state.element_chart.appendChild(state.gauge_canvas);
4629 var valuefontsize = Math.floor(height / 6);
4630 var valuetop = Math.round((height - valuefontsize - (height / 6)) / 2);
4631 state.gaugeChartLabel = document.createElement('span');
4632 state.gaugeChartLabel.className = 'gaugeChartLabel';
4633 state.gaugeChartLabel.style.fontSize = valuefontsize + 'px';
4634 state.gaugeChartLabel.style.top = valuetop.toString() + 'px';
4635 state.element_chart.appendChild(state.gaugeChartLabel);
4637 var titlefontsize = Math.round(valuefontsize / 2);
4639 state.gaugeChartTitle = document.createElement('span');
4640 state.gaugeChartTitle.className = 'gaugeChartTitle';
4641 state.gaugeChartTitle.innerHTML = state.title;
4642 state.gaugeChartTitle.style.fontSize = titlefontsize + 'px';
4643 state.gaugeChartTitle.style.lineHeight = titlefontsize + 'px';
4644 state.gaugeChartTitle.style.top = titletop.toString() + 'px';
4645 state.element_chart.appendChild(state.gaugeChartTitle);
4647 var unitfontsize = Math.round(titlefontsize * 0.9);
4648 state.gaugeChartUnits = document.createElement('span');
4649 state.gaugeChartUnits.className = 'gaugeChartUnits';
4650 state.gaugeChartUnits.innerHTML = state.units;
4651 state.gaugeChartUnits.style.fontSize = unitfontsize + 'px';
4652 state.element_chart.appendChild(state.gaugeChartUnits);
4654 state.gaugeChartMin = document.createElement('span');
4655 state.gaugeChartMin.className = 'gaugeChartMin';
4656 state.gaugeChartMin.style.fontSize = Math.round(valuefontsize * 0.75).toString() + 'px';
4657 state.element_chart.appendChild(state.gaugeChartMin);
4659 state.gaugeChartMax = document.createElement('span');
4660 state.gaugeChartMax.className = 'gaugeChartMax';
4661 state.gaugeChartMax.style.fontSize = Math.round(valuefontsize * 0.75).toString() + 'px';
4662 state.element_chart.appendChild(state.gaugeChartMax);
4664 // when we just re-create the chart
4665 // do not animate the first update
4667 if(typeof state.gauge_instance !== 'undefined')
4670 state.gauge_instance = new Gauge(state.gauge_canvas).setOptions(options); // create sexy gauge!
4672 state.___gaugeOld__ = {
4681 NETDATA.gaugeAnimation(state, animate);
4682 NETDATA.gaugeSet(state, value, 0, max);
4683 NETDATA.gaugeSetLabels(state, value, 0, max);
4684 NETDATA.gaugeAnimation(state, true);
4688 // ----------------------------------------------------------------------------------------------------------------
4689 // Charts Libraries Registration
4691 NETDATA.chartLibraries = {
4693 initialize: NETDATA.dygraphInitialize,
4694 create: NETDATA.dygraphChartCreate,
4695 update: NETDATA.dygraphChartUpdate,
4696 resize: function(state) {
4697 if(typeof state.dygraph_instance.resize === 'function')
4698 state.dygraph_instance.resize();
4700 setSelection: NETDATA.dygraphSetSelection,
4701 clearSelection: NETDATA.dygraphClearSelection,
4704 format: function(state) { return 'json'; },
4705 options: function(state) { return 'ms|flip'; },
4706 legend: function(state) {
4707 if(this.isSparkline(state) === false)
4708 return 'right-side';
4712 autoresize: function(state) { return true; },
4713 max_updates_to_recreate: function(state) { return 5000; },
4714 track_colors: function(state) { return true; },
4715 pixels_per_point: function(state) {
4716 if(this.isSparkline(state) === false)
4722 isSparkline: function(state) {
4723 if(typeof state.dygraph_sparkline === 'undefined') {
4724 var t = $(state.element).data('dygraph-theme');
4725 if(t === 'sparkline')
4726 state.dygraph_sparkline = true;
4728 state.dygraph_sparkline = false;
4730 return state.dygraph_sparkline;
4734 initialize: NETDATA.sparklineInitialize,
4735 create: NETDATA.sparklineChartCreate,
4736 update: NETDATA.sparklineChartUpdate,
4738 setSelection: undefined, // function(state, t) { return true; },
4739 clearSelection: undefined, // function(state) { return true; },
4742 format: function(state) { return 'array'; },
4743 options: function(state) { return 'flip|abs'; },
4744 legend: function(state) { return null; },
4745 autoresize: function(state) { return false; },
4746 max_updates_to_recreate: function(state) { return 5000; },
4747 track_colors: function(state) { return false; },
4748 pixels_per_point: function(state) { return 3; }
4751 initialize: NETDATA.peityInitialize,
4752 create: NETDATA.peityChartCreate,
4753 update: NETDATA.peityChartUpdate,
4755 setSelection: undefined, // function(state, t) { return true; },
4756 clearSelection: undefined, // function(state) { return true; },
4759 format: function(state) { return 'ssvcomma'; },
4760 options: function(state) { return 'null2zero|flip|abs'; },
4761 legend: function(state) { return null; },
4762 autoresize: function(state) { return false; },
4763 max_updates_to_recreate: function(state) { return 5000; },
4764 track_colors: function(state) { return false; },
4765 pixels_per_point: function(state) { return 3; }
4768 initialize: NETDATA.morrisInitialize,
4769 create: NETDATA.morrisChartCreate,
4770 update: NETDATA.morrisChartUpdate,
4772 setSelection: undefined, // function(state, t) { return true; },
4773 clearSelection: undefined, // function(state) { return true; },
4776 format: function(state) { return 'json'; },
4777 options: function(state) { return 'objectrows|ms'; },
4778 legend: function(state) { return null; },
4779 autoresize: function(state) { return false; },
4780 max_updates_to_recreate: function(state) { return 50; },
4781 track_colors: function(state) { return false; },
4782 pixels_per_point: function(state) { return 15; }
4785 initialize: NETDATA.googleInitialize,
4786 create: NETDATA.googleChartCreate,
4787 update: NETDATA.googleChartUpdate,
4789 setSelection: undefined, //function(state, t) { return true; },
4790 clearSelection: undefined, //function(state) { return true; },
4793 format: function(state) { return 'datatable'; },
4794 options: function(state) { return ''; },
4795 legend: function(state) { return null; },
4796 autoresize: function(state) { return false; },
4797 max_updates_to_recreate: function(state) { return 300; },
4798 track_colors: function(state) { return false; },
4799 pixels_per_point: function(state) { return 4; }
4802 initialize: NETDATA.raphaelInitialize,
4803 create: NETDATA.raphaelChartCreate,
4804 update: NETDATA.raphaelChartUpdate,
4806 setSelection: undefined, // function(state, t) { return true; },
4807 clearSelection: undefined, // function(state) { return true; },
4810 format: function(state) { return 'json'; },
4811 options: function(state) { return ''; },
4812 legend: function(state) { return null; },
4813 autoresize: function(state) { return false; },
4814 max_updates_to_recreate: function(state) { return 5000; },
4815 track_colors: function(state) { return false; },
4816 pixels_per_point: function(state) { return 3; }
4819 initialize: NETDATA.c3Initialize,
4820 create: NETDATA.c3ChartCreate,
4821 update: NETDATA.c3ChartUpdate,
4823 setSelection: undefined, // function(state, t) { return true; },
4824 clearSelection: undefined, // function(state) { return true; },
4827 format: function(state) { return 'csvjsonarray'; },
4828 options: function(state) { return 'milliseconds'; },
4829 legend: function(state) { return null; },
4830 autoresize: function(state) { return false; },
4831 max_updates_to_recreate: function(state) { return 5000; },
4832 track_colors: function(state) { return false; },
4833 pixels_per_point: function(state) { return 15; }
4836 initialize: NETDATA.d3Initialize,
4837 create: NETDATA.d3ChartCreate,
4838 update: NETDATA.d3ChartUpdate,
4840 setSelection: undefined, // function(state, t) { return true; },
4841 clearSelection: undefined, // function(state) { return true; },
4844 format: function(state) { return 'json'; },
4845 options: function(state) { return ''; },
4846 legend: function(state) { return null; },
4847 autoresize: function(state) { return false; },
4848 max_updates_to_recreate: function(state) { return 5000; },
4849 track_colors: function(state) { return false; },
4850 pixels_per_point: function(state) { return 3; }
4853 initialize: NETDATA.easypiechartInitialize,
4854 create: NETDATA.easypiechartChartCreate,
4855 update: NETDATA.easypiechartChartUpdate,
4857 setSelection: NETDATA.easypiechartSetSelection,
4858 clearSelection: NETDATA.easypiechartClearSelection,
4861 format: function(state) { return 'array'; },
4862 options: function(state) { return 'absolute'; },
4863 legend: function(state) { return null; },
4864 autoresize: function(state) { return false; },
4865 max_updates_to_recreate: function(state) { return 5000; },
4866 track_colors: function(state) { return false; },
4867 pixels_per_point: function(state) { return 3; },
4871 initialize: NETDATA.gaugeInitialize,
4872 create: NETDATA.gaugeChartCreate,
4873 update: NETDATA.gaugeChartUpdate,
4875 setSelection: NETDATA.gaugeSetSelection,
4876 clearSelection: NETDATA.gaugeClearSelection,
4879 format: function(state) { return 'array'; },
4880 options: function(state) { return 'absolute'; },
4881 legend: function(state) { return null; },
4882 autoresize: function(state) { return false; },
4883 max_updates_to_recreate: function(state) { return 5000; },
4884 track_colors: function(state) { return false; },
4885 pixels_per_point: function(state) { return 3; },
4890 NETDATA.registerChartLibrary = function(library, url) {
4891 if(NETDATA.options.debug.libraries === true)
4892 console.log("registering chart library: " + library);
4894 NETDATA.chartLibraries[library].url = url;
4895 NETDATA.chartLibraries[library].initialized = true;
4896 NETDATA.chartLibraries[library].enabled = true;
4899 // ----------------------------------------------------------------------------------------------------------------
4902 NETDATA.requiredJs = [
4904 url: NETDATA.serverDefault + 'lib/bootstrap.min.js',
4905 isAlreadyLoaded: function() {
4906 if(typeof $().emulateTransitionEnd == 'function')
4909 if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
4917 url: NETDATA.serverDefault + 'lib/jquery.nanoscroller.min.js',
4918 isAlreadyLoaded: function() { return false; }
4921 url: NETDATA.serverDefault + 'lib/bootstrap-toggle.min.js',
4922 isAlreadyLoaded: function() { return false; }
4926 NETDATA.requiredCSS = [
4928 url: NETDATA.serverDefault + 'css/bootstrap.min.css',
4929 isAlreadyLoaded: function() {
4930 if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
4937 url: NETDATA.serverDefault + 'css/font-awesome.min.css',
4938 isAlreadyLoaded: function() { return false; }
4941 url: NETDATA.dashboard_css,
4942 isAlreadyLoaded: function() { return false; }
4945 url: NETDATA.serverDefault + 'css/bootstrap-toggle.min.css',
4946 isAlreadyLoaded: function() { return false; }
4950 NETDATA.loadRequiredJs = function(index, callback) {
4951 if(index >= NETDATA.requiredJs.length) {
4952 if(typeof callback === 'function')
4957 if(NETDATA.requiredJs[index].isAlreadyLoaded()) {
4958 NETDATA.loadRequiredJs(++index, callback);
4962 if(NETDATA.options.debug.main_loop === true)
4963 console.log('loading ' + NETDATA.requiredJs[index].url);
4966 url: NETDATA.requiredJs[index].url,
4970 .success(function() {
4971 if(NETDATA.options.debug.main_loop === true)
4972 console.log('loaded ' + NETDATA.requiredJs[index].url);
4974 NETDATA.loadRequiredJs(++index, callback);
4977 alert('Cannot load required JS library: ' + NETDATA.requiredJs[index].url);
4981 NETDATA.loadRequiredCSS = function(index) {
4982 if(index >= NETDATA.requiredCSS.length)
4985 if(NETDATA.requiredCSS[index].isAlreadyLoaded()) {
4986 NETDATA.loadRequiredCSS(++index);
4990 if(NETDATA.options.debug.main_loop === true)
4991 console.log('loading ' + NETDATA.requiredCSS[index].url);
4993 NETDATA._loadCSS(NETDATA.requiredCSS[index].url);
4994 NETDATA.loadRequiredCSS(++index);
4997 NETDATA.errorReset();
4998 NETDATA.loadRequiredCSS(0);
5000 NETDATA._loadjQuery(function() {
5001 NETDATA.loadRequiredJs(0, function() {
5002 if(typeof netdataDontStart === 'undefined' || !netdataDontStart) {
5003 if(NETDATA.options.debug.main_loop === true)
5004 console.log('starting chart refresh thread');
5011 // window.NETDATA = NETDATA;
5012 // })(window, document);