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: new Date().getTime(), // 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 pan_and_zoom_data_padding: true, // fetch more data for the master chart when panning or zooming
202 update_only_visible: true, // enable or disable visibility management
204 parallel_refresher: true, // enable parallel refresh of charts
206 concurrent_refreshes: true, // when parallel_refresher is enabled, sync also the charts
208 destroy_on_hide: false, // destroy charts when they are not visible
210 eliminate_zero_dimensions: true, // do not show dimensions with just zeros
212 stop_updates_when_focus_is_lost: true, // boolean - shall we stop auto-refreshes when document does not have user focus
213 stop_updates_while_resizing: 1000, // ms - time to stop auto-refreshes while resizing the charts
215 double_click_speed: 500, // ms - time between clicks / taps to detect double click/tap
217 smooth_plot: true, // enable smooth plot, where possible
219 charts_selection_animation_delay: 50, // delay to animate charts when syncing selection
221 color_fill_opacity_line: 1.0,
222 color_fill_opacity_area: 0.2,
223 color_fill_opacity_stacked: 0.8,
225 setOptionCallback: function() { ; }
233 chart_data_url: false,
234 chart_errors: false, // FIXME
243 // ----------------------------------------------------------------------------------------------------------------
244 // local storage options
246 NETDATA.localStorage = {
249 callback: {} // only used for resetting back to defaults
252 NETDATA.localStorageGet = function(key, def, callback) {
255 if(typeof NETDATA.localStorage.default[key.toString()] === 'undefined') {
256 NETDATA.localStorage.default[key.toString()] = def;
257 NETDATA.localStorage.callback[key.toString()] = callback;
260 if(typeof Storage !== "undefined" && typeof localStorage === 'object') {
262 // console.log('localStorage: loading "' + key.toString() + '"');
263 ret = localStorage.getItem(key.toString());
264 if(ret === null || ret === 'undefined') {
265 // console.log('localStorage: cannot load it, saving "' + key.toString() + '" with value "' + JSON.stringify(def) + '"');
266 localStorage.setItem(key.toString(), JSON.stringify(def));
270 // console.log('localStorage: got "' + key.toString() + '" with value "' + ret + '"');
271 ret = JSON.parse(ret);
272 // console.log('localStorage: loaded "' + key.toString() + '" as value ' + ret + ' of type ' + typeof(ret));
276 console.log('localStorage: failed to read "' + key.toString() + '", using default: "' + def.toString() + '"');
281 if(typeof ret === 'undefined' || ret === 'undefined') {
282 console.log('localStorage: LOADED UNDEFINED "' + key.toString() + '" as value ' + ret + ' of type ' + typeof(ret));
286 NETDATA.localStorage.current[key.toString()] = ret;
290 NETDATA.localStorageSet = function(key, value, callback) {
291 if(typeof value === 'undefined' || value === 'undefined') {
292 console.log('localStorage: ATTEMPT TO SET UNDEFINED "' + key.toString() + '" as value ' + value + ' of type ' + typeof(value));
295 if(typeof NETDATA.localStorage.default[key.toString()] === 'undefined') {
296 NETDATA.localStorage.default[key.toString()] = value;
297 NETDATA.localStorage.current[key.toString()] = value;
298 NETDATA.localStorage.callback[key.toString()] = callback;
301 if(typeof Storage !== "undefined" && typeof localStorage === 'object') {
302 // console.log('localStorage: saving "' + key.toString() + '" with value "' + JSON.stringify(value) + '"');
304 localStorage.setItem(key.toString(), JSON.stringify(value));
307 console.log('localStorage: failed to save "' + key.toString() + '" with value: "' + value.toString() + '"');
311 NETDATA.localStorage.current[key.toString()] = value;
315 NETDATA.localStorageGetRecursive = function(obj, prefix, callback) {
317 if(typeof obj[i] === 'object') {
318 //console.log('object ' + prefix + '.' + i.toString());
319 NETDATA.localStorageGetRecursive(obj[i], prefix + '.' + i.toString(), callback);
323 obj[i] = NETDATA.localStorageGet(prefix + '.' + i.toString(), obj[i], callback);
327 NETDATA.setOption = function(key, value) {
328 if(key.toString() === 'setOptionCallback') {
329 if(typeof NETDATA.options.current.setOptionCallback === 'function') {
330 NETDATA.options.current[key.toString()] = value;
331 NETDATA.options.current.setOptionCallback();
334 else if(NETDATA.options.current[key.toString()] !== value) {
335 var name = 'options.' + key.toString();
337 if(typeof NETDATA.localStorage.default[name.toString()] === 'undefined')
338 console.log('localStorage: setOption() on unsaved option: "' + name.toString() + '", value: ' + value);
340 //console.log(NETDATA.localStorage);
341 //console.log('setOption: setting "' + key.toString() + '" to "' + value + '" of type ' + typeof(value) + ' original type ' + typeof(NETDATA.options.current[key.toString()]));
342 //console.log(NETDATA.options);
343 NETDATA.options.current[key.toString()] = NETDATA.localStorageSet(name.toString(), value, null);
345 if(typeof NETDATA.options.current.setOptionCallback === 'function')
346 NETDATA.options.current.setOptionCallback();
352 NETDATA.getOption = function(key) {
353 return NETDATA.options.current[key.toString()];
356 // read settings from local storage
357 NETDATA.localStorageGetRecursive(NETDATA.options.current, 'options', null);
359 // always start with this option enabled.
360 NETDATA.setOption('stop_updates_when_focus_is_lost', true);
362 NETDATA.resetOptions = function() {
363 for(var i in NETDATA.localStorage.default) {
364 var a = i.split('.');
366 if(a[0] === 'options') {
367 if(a[1] === 'setOptionCallback') continue;
368 if(typeof NETDATA.localStorage.default[i] === 'undefined') continue;
369 if(NETDATA.options.current[i] === NETDATA.localStorage.default[i]) continue;
371 NETDATA.setOption(a[1], NETDATA.localStorage.default[i]);
373 else if(a[0] === 'chart_heights') {
374 if(typeof NETDATA.localStorage.callback[i] === 'function' && typeof NETDATA.localStorage.default[i] !== 'undefined') {
375 NETDATA.localStorage.callback[i](NETDATA.localStorage.default[i]);
381 // ----------------------------------------------------------------------------------------------------------------
383 if(NETDATA.options.debug.main_loop === true)
384 console.log('welcome to NETDATA');
386 NETDATA.onresize = function() {
387 NETDATA.options.last_resized = new Date().getTime();
391 NETDATA.onscroll = function() {
392 // console.log('onscroll');
394 NETDATA.options.last_page_scroll = new Date().getTime();
395 if(NETDATA.options.targets === null) return;
397 // when the user scrolls he sees that we have
398 // hidden all the not-visible charts
399 // using this little function we try to switch
400 // the charts back to visible quickly
401 var targets = NETDATA.options.targets;
402 var len = targets.length;
403 while(len--) targets[len].isVisible();
406 window.onresize = NETDATA.onresize;
407 window.onscroll = NETDATA.onscroll;
409 // ----------------------------------------------------------------------------------------------------------------
412 NETDATA.errorCodes = {
413 100: { message: "Cannot load chart library", alert: true },
414 101: { message: "Cannot load jQuery", alert: true },
415 402: { message: "Chart library not found", alert: false },
416 403: { message: "Chart library not enabled/is failed", alert: false },
417 404: { message: "Chart not found", alert: false }
419 NETDATA.errorLast = {
425 NETDATA.error = function(code, msg) {
426 NETDATA.errorLast.code = code;
427 NETDATA.errorLast.message = msg;
428 NETDATA.errorLast.datetime = new Date().getTime();
430 console.log("ERROR " + code + ": " + NETDATA.errorCodes[code].message + ": " + msg);
432 if(NETDATA.errorCodes[code].alert)
433 alert("ERROR " + code + ": " + NETDATA.errorCodes[code].message + ": " + msg);
436 NETDATA.errorReset = function() {
437 NETDATA.errorLast.code = 0;
438 NETDATA.errorLast.message = "You are doing fine!";
439 NETDATA.errorLast.datetime = 0;
442 // ----------------------------------------------------------------------------------------------------------------
445 // When multiple charts need the same chart, we avoid downloading it
446 // multiple times (and having it in browser memory multiple time)
447 // by using this registry.
449 // Every time we download a chart definition, we save it here with .add()
450 // Then we try to get it back with .get(). If that fails, we download it.
452 NETDATA.chartRegistry = {
455 fixid: function(id) {
456 return id.replace(/:/g, "_").replace(/\//g, "_");
459 add: function(host, id, data) {
460 host = this.fixid(host);
463 if(typeof this.charts[host] === 'undefined')
464 this.charts[host] = {};
466 //console.log('added ' + host + '/' + id);
467 this.charts[host][id] = data;
470 get: function(host, id) {
471 host = this.fixid(host);
474 if(typeof this.charts[host] === 'undefined')
477 if(typeof this.charts[host][id] === 'undefined')
480 //console.log('cached ' + host + '/' + id);
481 return this.charts[host][id];
484 downloadAll: function(host, callback) {
485 while(host.slice(-1) === '/')
486 host = host.substring(0, host.length - 1);
491 url: host + '/api/v1/charts',
492 crossDomain: NETDATA.options.crossDomainAjax,
496 .done(function(data) {
497 var h = NETDATA.chartRegistry.fixid(host);
498 //console.log('downloaded all charts from ' + host + ' (' + h + ')');
499 self.charts[h] = data.charts;
500 if(typeof callback === 'function')
504 if(typeof callback === 'function')
510 // ----------------------------------------------------------------------------------------------------------------
511 // Global Pan and Zoom on charts
513 // Using this structure are synchronize all the charts, so that
514 // when you pan or zoom one, all others are automatically refreshed
515 // to the same timespan.
517 NETDATA.globalPanAndZoom = {
518 seq: 0, // timestamp ms
519 // every time a chart is panned or zoomed
520 // we set the timestamp here
521 // then we use it as a sequence number
522 // to find if other charts are syncronized
525 master: null, // the master chart (state), to which all others
528 force_before_ms: null, // the timespan to sync all other charts
529 force_after_ms: null,
532 setMaster: function(state, after, before) {
533 if(NETDATA.options.current.sync_pan_and_zoom === false)
536 if(this.master !== null && this.master !== state)
537 this.master.resetChart(true, true);
539 var now = new Date().getTime();
542 this.force_after_ms = after;
543 this.force_before_ms = before;
544 NETDATA.options.auto_refresher_stop_until = now + NETDATA.options.current.global_pan_sync_time;
548 clearMaster: function() {
549 if(this.master !== null) {
550 var st = this.master;
557 this.force_after_ms = null;
558 this.force_before_ms = null;
559 NETDATA.options.auto_refresher_stop_until = 0;
562 // is the given state the master of the global
563 // pan and zoom sync?
564 isMaster: function(state) {
565 if(this.master === state) return true;
569 // are we currently have a global pan and zoom sync?
570 isActive: function() {
571 if(this.master !== null && this.force_before_ms !== null && this.force_after_ms !== null && this.seq !== 0) return true;
575 // check if a chart, other than the master
576 // needs to be refreshed, due to the global pan and zoom
577 shouldBeAutoRefreshed: function(state) {
578 if(this.master === null || this.seq === 0)
581 //if(state.needsRecreation())
584 if(state.tm.pan_and_zoom_seq === this.seq)
591 // ----------------------------------------------------------------------------------------------------------------
592 // dimensions selection
595 // move color assignment to dimensions, here
597 dimensionStatus = function(parent, label, name_div, value_div, color) {
598 this.enabled = false;
599 this.parent = parent;
601 this.name_div = null;
602 this.value_div = null;
605 if(parent.selected === parent.unselected)
606 this.selected = true;
608 this.selected = false;
610 this.setOptions(name_div, value_div, color);
613 dimensionStatus.prototype.invalidate = function() {
614 this.name_div = null;
615 this.value_div = null;
616 this.enabled = false;
619 dimensionStatus.prototype.setOptions = function(name_div, value_div, color) {
622 if(this.name_div != name_div) {
623 this.name_div = name_div;
624 this.name_div.title = this.label;
625 this.name_div.style.color = this.color;
626 if(this.selected === false)
627 this.name_div.className = 'netdata-legend-name not-selected';
629 this.name_div.className = 'netdata-legend-name selected';
632 if(this.value_div != value_div) {
633 this.value_div = value_div;
634 this.value_div.title = this.label;
635 this.value_div.style.color = this.color;
636 if(this.selected === false)
637 this.value_div.className = 'netdata-legend-value not-selected';
639 this.value_div.className = 'netdata-legend-value selected';
646 dimensionStatus.prototype.setHandler = function() {
647 if(this.enabled === false) return;
651 // this.name_div.onmousedown = this.value_div.onmousedown = function(e) {
652 this.name_div.onclick = this.value_div.onclick = function(e) {
654 if(ds.isSelected()) {
656 if(e.shiftKey === true || e.ctrlKey === true) {
657 // control or shift key is pressed -> unselect this (except is none will remain selected, in which case select all)
660 if(ds.parent.countSelected() === 0)
661 ds.parent.selectAll();
664 // no key is pressed -> select only this (except if it is the only selected already, in which case select all)
665 if(ds.parent.countSelected() === 1) {
666 ds.parent.selectAll();
669 ds.parent.selectNone();
675 // this is not selected
676 if(e.shiftKey === true || e.ctrlKey === true) {
677 // control or shift key is pressed -> select this too
681 // no key is pressed -> select only this
682 ds.parent.selectNone();
687 ds.parent.state.redrawChart();
691 dimensionStatus.prototype.select = function() {
692 if(this.enabled === false) return;
694 this.name_div.className = 'netdata-legend-name selected';
695 this.value_div.className = 'netdata-legend-value selected';
696 this.selected = true;
699 dimensionStatus.prototype.unselect = function() {
700 if(this.enabled === false) return;
702 this.name_div.className = 'netdata-legend-name not-selected';
703 this.value_div.className = 'netdata-legend-value hidden';
704 this.selected = false;
707 dimensionStatus.prototype.isSelected = function() {
708 return(this.enabled === true && this.selected === true);
711 // ----------------------------------------------------------------------------------------------------------------
713 dimensionsVisibility = function(state) {
716 this.dimensions = {};
717 this.selected_count = 0;
718 this.unselected_count = 0;
721 dimensionsVisibility.prototype.dimensionAdd = function(label, name_div, value_div, color) {
722 if(typeof this.dimensions[label] === 'undefined') {
724 this.dimensions[label] = new dimensionStatus(this, label, name_div, value_div, color);
727 this.dimensions[label].setOptions(name_div, value_div, color);
729 return this.dimensions[label];
732 dimensionsVisibility.prototype.dimensionGet = function(label) {
733 return this.dimensions[label];
736 dimensionsVisibility.prototype.invalidateAll = function() {
737 for(var d in this.dimensions)
738 this.dimensions[d].invalidate();
741 dimensionsVisibility.prototype.selectAll = function() {
742 for(var d in this.dimensions)
743 this.dimensions[d].select();
746 dimensionsVisibility.prototype.countSelected = function() {
748 for(var d in this.dimensions)
749 if(this.dimensions[d].isSelected()) i++;
754 dimensionsVisibility.prototype.selectNone = function() {
755 for(var d in this.dimensions)
756 this.dimensions[d].unselect();
759 dimensionsVisibility.prototype.selected2BooleanArray = function(array) {
760 var ret = new Array();
761 this.selected_count = 0;
762 this.unselected_count = 0;
764 for(var i = 0, len = array.length; i < len ; i++) {
765 var ds = this.dimensions[array[i]];
766 if(typeof ds === 'undefined') {
767 // console.log(array[i] + ' is not found');
772 if(ds.isSelected()) {
774 this.selected_count++;
778 this.unselected_count++;
782 if(this.selected_count === 0 && this.unselected_count !== 0) {
784 return this.selected2BooleanArray(array);
791 // ----------------------------------------------------------------------------------------------------------------
792 // global selection sync
794 NETDATA.globalSelectionSync = {
801 if(this.state !== null)
802 this.state.globalSelectionSyncStop();
806 if(this.state !== null) {
807 this.state.globalSelectionSyncDelay();
812 // ----------------------------------------------------------------------------------------------------------------
813 // Our state object, where all per-chart values are stored
815 chartState = function(element) {
816 var self = $(element);
817 this.element = element;
820 // all private functions should use 'that', instead of 'this'
824 * show an error instead of the chart
826 var error = function(msg) {
827 that.element.innerHTML = that.id + ': ' + msg;
828 that.enabled = false;
829 that.current = that.pan;
832 // GUID - a unique identifier for the chart
833 this.uuid = NETDATA.guid();
835 // string - the name of chart
836 this.id = self.data('netdata');
838 // string - the key for localStorage settings
839 this.settings_id = self.data('id') || null;
841 // the user given dimensions of the element
842 this.width = self.data('width') || NETDATA.chartDefaults.width;
843 this.height = self.data('height') || NETDATA.chartDefaults.height;
845 if(this.settings_id !== null) {
846 this.height = NETDATA.localStorageGet('chart_heights.' + this.settings_id, this.height, function(height) {
847 // this is the callback that will be called
848 // if and when the user resets all localStorage variables
851 resizeChartToHeight(height);
855 // string - the netdata server URL, without any path
856 this.host = self.data('host') || NETDATA.chartDefaults.host;
858 // make sure the host does not end with /
859 // all netdata API requests use absolute paths
860 while(this.host.slice(-1) === '/')
861 this.host = this.host.substring(0, this.host.length - 1);
863 // string - the grouping method requested by the user
864 this.method = self.data('method') || NETDATA.chartDefaults.method;
866 // the time-range requested by the user
867 this.after = self.data('after') || NETDATA.chartDefaults.after;
868 this.before = self.data('before') || NETDATA.chartDefaults.before;
870 // the pixels per point requested by the user
871 this.pixels_per_point = self.data('pixels-per-point') || 1;
872 this.points = self.data('points') || null;
874 // the dimensions requested by the user
875 this.dimensions = self.data('dimensions') || null;
877 // the chart library requested by the user
878 this.library_name = self.data('chart-library') || NETDATA.chartDefaults.library;
880 // object - the chart library used
885 this.colors_assigned = {};
886 this.colors_available = null;
888 // the element already created by the user
889 this.element_message = null;
891 // the element with the chart
892 this.element_chart = null;
894 // the element with the legend of the chart (if created by us)
895 this.element_legend = null;
896 this.element_legend_childs = {
906 this.chart_url = null; // string - the url to download chart info
907 this.chart = null; // object - the chart as downloaded from the server
909 this.title = self.data('title') || null; // the title of the chart
910 this.units = self.data('units') || null; // the units of the chart dimensions
911 this.append_options = self.data('append-options') || null; // the units of the chart dimensions
913 this.validated = false; // boolean - has the chart been validated?
914 this.enabled = true; // boolean - is the chart enabled for refresh?
915 this.paused = false; // boolean - is the chart paused for any reason?
916 this.selected = false; // boolean - is the chart shown a selection?
917 this.debug = false; // boolean - console.log() debug info about this chart
919 this.netdata_first = 0; // milliseconds - the first timestamp in netdata
920 this.netdata_last = 0; // milliseconds - the last timestamp in netdata
921 this.requested_after = null; // milliseconds - the timestamp of the request after param
922 this.requested_before = null; // milliseconds - the timestamp of the request before param
923 this.requested_padding = null;
925 this.view_before = 0;
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,
944 force_update_at: 0, // the timestamp to force the update at
945 force_before_ms: null,
949 // this is a pointer to one of the sub-classes below
951 this.current = this.auto;
953 // check the requested library is available
954 // we don't initialize it here - it will be initialized when
955 // this chart will be first used
956 if(typeof NETDATA.chartLibraries[that.library_name] === 'undefined') {
957 NETDATA.error(402, that.library_name);
958 error('chart library "' + that.library_name + '" is not found');
961 else if(NETDATA.chartLibraries[that.library_name].enabled === false) {
962 NETDATA.error(403, that.library_name);
963 error('chart library "' + that.library_name + '" is not enabled');
967 that.library = NETDATA.chartLibraries[that.library_name];
969 // milliseconds - the time the last refresh took
970 this.refresh_dt_ms = 0;
972 // if we need to report the rendering speed
973 // find the element that needs to be updated
974 var refresh_dt_element_name = self.data('dt-element-name') || null; // string - the element to print refresh_dt_ms
976 if(refresh_dt_element_name !== null)
977 this.refresh_dt_element = document.getElementById(refresh_dt_element_name) || null;
979 this.refresh_dt_element = null;
981 this.dimensions_visibility = new dimensionsVisibility(this);
983 // ============================================================================================================
986 var createDOM = function() {
987 if(that.enabled === false) return;
989 if(that.element_message !== null) that.element_message.innerHTML = '';
990 if(that.element_legend !== null) that.element_legend.innerHTML = '';
991 if(that.element_chart !== null) that.element_chart.innerHTML = '';
993 that.element.innerHTML = '';
995 that.element_message = document.createElement('div');
996 that.element_message.className = ' netdata-message hidden';
997 that.element.appendChild(that.element_message);
999 that.element_chart = document.createElement('div');
1000 that.element_chart.id = that.library_name + '-' + that.uuid + '-chart';
1001 that.element.appendChild(that.element_chart);
1003 if(that.hasLegend() === true) {
1004 that.element.className = "netdata-container-with-legend";
1005 that.element_chart.className = 'netdata-chart-with-legend-right netdata-' + that.library_name + '-chart-with-legend-right';
1007 that.element_legend = document.createElement('div');
1008 that.element_legend.className = 'netdata-chart-legend netdata-' + that.library_name + '-legend';
1009 that.element.appendChild(that.element_legend);
1012 that.element.className = "netdata-container";
1013 that.element_chart.className = ' netdata-chart netdata-' + that.library_name + '-chart';
1015 that.element_legend = null;
1017 that.element_legend_childs.series = null;
1019 if(typeof(that.width) === 'string')
1020 $(that.element).css('width', that.width);
1021 else if(typeof(that.width) === 'number')
1022 $(that.element).css('width', that.width + 'px');
1024 if(typeof(that.library.aspect_ratio) === 'undefined') {
1025 if(typeof(that.height) === 'string')
1026 $(that.element).css('height', that.height);
1027 else if(typeof(that.height) === 'number')
1028 $(that.element).css('height', that.height + 'px');
1031 var w = that.element.offsetWidth;
1032 if(w === null || w === 0) {
1033 // the div is hidden
1034 // this is resize the chart when next viewed
1035 that.tm.last_resized = 0;
1038 $(that.element).css('height', (that.element.offsetWidth * that.library.aspect_ratio / 100).toString() + 'px');
1041 if(NETDATA.chartDefaults.min_width !== null)
1042 $(that.element).css('min-width', NETDATA.chartDefaults.min_width);
1044 that.tm.last_dom_created = new Date().getTime();
1050 * initialize state viariables
1051 * destroy all (possibly) created state elements
1052 * create the basic DOM for a chart
1054 var init = function() {
1055 if(that.enabled === false) return;
1057 that.paused = false;
1058 that.selected = false;
1060 that.chart_created = false; // boolean - is the library.create() been called?
1061 that.updates_counter = 0; // numeric - the number of refreshes made so far
1062 that.updates_since_last_unhide = 0; // numeric - the number of refreshes made since the last time the chart was unhidden
1063 that.updates_since_last_creation = 0; // numeric - the number of refreshes made since the last time the chart was created
1066 last_initialized: 0, // milliseconds - the timestamp it was last initialized
1067 last_dom_created: 0, // milliseconds - the timestamp its DOM was last created
1068 last_mode_switch: 0, // milliseconds - the timestamp it switched modes
1070 last_info_downloaded: 0, // milliseconds - the timestamp we downloaded the chart
1071 last_updated: 0, // the timestamp the chart last updated with data
1072 pan_and_zoom_seq: 0, // the sequence number of the global synchronization
1074 // Used with NETDATA.globalPanAndZoom.seq
1075 last_visible_check: 0, // the time we last checked if it is visible
1076 last_resized: 0, // the time the chart was resized
1077 last_hidden: 0, // the time the chart was hidden
1078 last_unhidden: 0, // the time the chart was unhidden
1079 last_autorefreshed: 0 // the time the chart was last refreshed
1082 that.data = null; // the last data as downloaded from the netdata server
1083 that.data_url = 'invalid://'; // string - the last url used to update the chart
1084 that.data_points = 0; // number - the number of points returned from netdata
1085 that.data_after = 0; // milliseconds - the first timestamp of the data
1086 that.data_before = 0; // milliseconds - the last timestamp of the data
1087 that.data_update_every = 0; // milliseconds - the frequency to update the data
1089 that.tm.last_initialized = new Date().getTime();
1092 that.setMode('auto');
1095 var maxMessageFontSize = function() {
1096 // normally we want a font size, as tall as the element
1097 var h = that.element_message.clientHeight;
1099 // but give it some air, 20% let's say, or 5 pixels min
1100 var lost = Math.max(h * 0.2, 5);
1103 // center the text, verically
1104 var paddingTop = (lost - 5) / 2;
1106 // but check the width too
1107 // it should fit 10 characters in it
1108 var w = that.element_message.clientWidth / 10;
1110 paddingTop += (h - w) / 2;
1114 // and don't make it too huge
1115 // 5% of the screen size is good
1116 if(h > screen.height / 20) {
1117 paddingTop += (h - (screen.height / 20)) / 2;
1118 h = screen.height / 20;
1122 that.element_message.style.fontSize = h.toString() + 'px';
1123 that.element_message.style.paddingTop = paddingTop.toString() + 'px';
1126 var showMessage = function(msg) {
1127 that.element_message.className = 'netdata-message';
1128 that.element_message.innerHTML = msg;
1129 this.element_message.style.fontSize = 'x-small';
1130 that.element_message.style.paddingTop = '0px';
1131 that.___messageHidden___ = undefined;
1134 var showMessageIcon = function(icon) {
1135 that.element_message.innerHTML = icon;
1136 that.element_message.className = 'netdata-message icon';
1137 maxMessageFontSize();
1138 that.___messageHidden___ = undefined;
1141 var hideMessage = function() {
1142 if(typeof that.___messageHidden___ === 'undefined') {
1143 that.___messageHidden___ = true;
1144 that.element_message.className = 'netdata-message hidden';
1148 var showRendering = function() {
1150 if(that.chart !== null) {
1151 if(that.chart.chart_type === 'line')
1152 icon = '<i class="fa fa-line-chart"></i>';
1154 icon = '<i class="fa fa-area-chart"></i>';
1157 icon = '<i class="fa fa-area-chart"></i>';
1159 showMessageIcon(icon + ' netdata');
1162 var showLoading = function() {
1163 if(that.chart_created === false) {
1164 showMessageIcon('<i class="fa fa-refresh"></i> netdata');
1170 var isHidden = function() {
1171 if(typeof that.___chartIsHidden___ !== 'undefined')
1177 // hide the chart, when it is not visible - called from isVisible()
1178 var hideChart = function() {
1179 // hide it, if it is not already hidden
1180 if(isHidden() === true) return;
1182 if(that.chart_created === true) {
1183 // we should destroy it
1184 if(NETDATA.options.current.destroy_on_hide === true) {
1189 that.element_chart.style.display = 'none';
1190 if(that.element_legend !== null) that.element_legend.style.display = 'none';
1191 that.tm.last_hidden = new Date().getTime();
1195 that.___chartIsHidden___ = true;
1198 // unhide the chart, when it is visible - called from isVisible()
1199 var unhideChart = function() {
1200 if(isHidden() === false) return;
1202 that.___chartIsHidden___ = undefined;
1203 that.updates_since_last_unhide = 0;
1205 if(that.chart_created === false) {
1206 // we need to re-initialize it, to show our background
1207 // logo in bootstrap tabs, until the chart loads
1211 that.tm.last_unhidden = new Date().getTime();
1212 that.element_chart.style.display = '';
1213 if(that.element_legend !== null) that.element_legend.style.display = '';
1219 var canBeRendered = function() {
1220 if(isHidden() === true || that.isVisible(true) === false)
1226 // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
1227 var callChartLibraryUpdateSafely = function(data) {
1230 if(canBeRendered() === false)
1233 if(NETDATA.options.debug.chart_errors === true)
1234 status = that.library.update(that, data);
1237 status = that.library.update(that, data);
1244 if(status === false) {
1245 error('chart failed to be updated as ' + that.library_name);
1252 // https://github.com/petkaantonov/bluebird/wiki/Optimization-killers
1253 var callChartLibraryCreateSafely = function(data) {
1256 if(canBeRendered() === false)
1259 if(NETDATA.options.debug.chart_errors === true)
1260 status = that.library.create(that, data);
1263 status = that.library.create(that, data);
1270 if(status === false) {
1271 error('chart failed to be created as ' + that.library_name);
1275 that.chart_created = true;
1276 that.updates_since_last_creation = 0;
1280 // ----------------------------------------------------------------------------------------------------------------
1283 // resizeChart() - private
1284 // to be called just before the chart library to make sure that
1285 // a properly sized dom is available
1286 var resizeChart = function() {
1287 if(that.isVisible() === true && that.tm.last_resized < NETDATA.options.last_resized) {
1288 if(that.chart_created === false) return;
1290 if(that.needsRecreation()) {
1293 else if(typeof that.library.resize === 'function') {
1294 that.library.resize(that);
1296 if(that.element_legend_childs.nano !== null && that.element_legend_childs.nano_options !== null)
1297 $(that.element_legend_childs.nano).nanoScroller();
1299 maxMessageFontSize();
1302 that.tm.last_resized = new Date().getTime();
1306 // this is the actual chart resize algorithm
1308 // - resize the entire container
1309 // - update the internal states
1310 // - resize the chart as the div changes height
1311 // - update the scrollbar of the legend
1312 var resizeChartToHeight = function(h) {
1314 that.element.style.height = h;
1316 if(that.settings_id !== null)
1317 NETDATA.localStorageSet('chart_heights.' + that.settings_id, h);
1319 var now = new Date().getTime();
1320 NETDATA.options.last_page_scroll = now;
1321 NETDATA.options.auto_refresher_stop_until = now + NETDATA.options.current.stop_updates_while_resizing;
1324 that.tm.last_resized = 0;
1328 this.resizeHandler = function(e) {
1331 if(typeof this.event_resize === 'undefined'
1332 || this.event_resize.chart_original_w === 'undefined'
1333 || this.event_resize.chart_original_h === 'undefined')
1334 this.event_resize = {
1335 chart_original_w: this.element.clientWidth,
1336 chart_original_h: this.element.clientHeight,
1340 if(e.type === 'touchstart') {
1341 this.event_resize.mouse_start_x = e.touches.item(0).pageX;
1342 this.event_resize.mouse_start_y = e.touches.item(0).pageY;
1345 this.event_resize.mouse_start_x = e.clientX;
1346 this.event_resize.mouse_start_y = e.clientY;
1349 this.event_resize.chart_start_w = this.element.clientWidth;
1350 this.event_resize.chart_start_h = this.element.clientHeight;
1351 this.event_resize.chart_last_w = this.element.clientWidth;
1352 this.event_resize.chart_last_h = this.element.clientHeight;
1354 var now = new Date().getTime();
1355 if(now - this.event_resize.last <= NETDATA.options.current.double_click_speed) {
1356 // double click / double tap event
1358 // the optimal height of the chart
1359 // showing the entire legend
1360 var optimal = this.event_resize.chart_last_h
1361 + this.element_legend_childs.content.scrollHeight
1362 - this.element_legend_childs.content.clientHeight;
1364 // if we are not optimal, be optimal
1365 if(this.event_resize.chart_last_h != optimal)
1366 resizeChartToHeight(optimal.toString() + 'px');
1368 // else if we do not have the original height
1369 // reset to the original height
1370 else if(this.event_resize.chart_last_h != this.event_resize.chart_original_h)
1371 resizeChartToHeight(this.event_resize.chart_original_h.toString() + 'px');
1374 this.event_resize.last = now;
1376 // process movement event
1377 document.onmousemove =
1378 document.ontouchmove =
1379 this.element_legend_childs.resize_handler.onmousemove =
1380 this.element_legend_childs.resize_handler.ontouchmove =
1385 case 'mousemove': y = e.clientY; break;
1386 case 'touchmove': y = e.touches.item(e.touches - 1).pageY; break;
1390 var newH = that.event_resize.chart_start_h + y - that.event_resize.mouse_start_y;
1392 if(newH >= 70 && newH !== that.event_resize.chart_last_h) {
1393 resizeChartToHeight(newH.toString() + 'px');
1394 that.event_resize.chart_last_h = newH;
1399 // process end event
1400 document.onmouseup =
1401 document.ontouchend =
1402 this.element_legend_childs.resize_handler.onmouseup =
1403 this.element_legend_childs.resize_handler.ontouchend =
1405 // remove all the hooks
1406 document.onmouseup =
1407 document.onmousemove =
1408 document.ontouchmove =
1409 document.ontouchend =
1410 that.element_legend_childs.resize_handler.onmousemove =
1411 that.element_legend_childs.resize_handler.ontouchmove =
1412 that.element_legend_childs.resize_handler.onmouseout =
1413 that.element_legend_childs.resize_handler.onmouseup =
1414 that.element_legend_childs.resize_handler.ontouchend =
1417 // allow auto-refreshes
1418 NETDATA.options.auto_refresher_stop_until = 0;
1424 var noDataToShow = function() {
1425 showMessageIcon('<i class="fa fa-warning"></i> empty');
1426 that.legendUpdateDOM();
1427 that.tm.last_autorefreshed = new Date().getTime();
1428 // that.data_update_every = 30 * 1000;
1429 //that.element_chart.style.display = 'none';
1430 //if(that.element_legend !== null) that.element_legend.style.display = 'none';
1431 //that.___chartIsHidden___ = true;
1434 // ============================================================================================================
1437 this.error = function(msg) {
1441 this.setMode = function(m) {
1442 if(this.current !== null && this.current.name === m) return;
1445 this.current = this.auto;
1446 else if(m === 'pan')
1447 this.current = this.pan;
1448 else if(m === 'zoom')
1449 this.current = this.zoom;
1451 this.current = this.auto;
1453 this.current.force_update_at = 0;
1454 this.current.force_before_ms = null;
1455 this.current.force_after_ms = null;
1457 this.tm.last_mode_switch = new Date().getTime();
1460 // ----------------------------------------------------------------------------------------------------------------
1461 // global selection sync
1463 // prevent to global selection sync for some time
1464 this.globalSelectionSyncDelay = function(ms) {
1465 if(NETDATA.options.current.sync_selection === false)
1468 if(typeof ms === 'number')
1469 NETDATA.globalSelectionSync.dont_sync_before = new Date().getTime() + ms;
1471 NETDATA.globalSelectionSync.dont_sync_before = new Date().getTime() + NETDATA.options.current.sync_selection_delay;
1474 // can we globally apply selection sync?
1475 this.globalSelectionSyncAbility = function() {
1476 if(NETDATA.options.current.sync_selection === false)
1479 if(NETDATA.globalSelectionSync.dont_sync_before > new Date().getTime())
1485 this.globalSelectionSyncIsMaster = function() {
1486 if(NETDATA.globalSelectionSync.state === this)
1492 // this chart is the master of the global selection sync
1493 this.globalSelectionSyncBeMaster = function() {
1495 if(this.globalSelectionSyncIsMaster()) {
1496 if(this.debug === true)
1497 this.log('sync: I am the master already.');
1502 if(NETDATA.globalSelectionSync.state) {
1503 if(this.debug === true)
1504 this.log('sync: I am not the sync master. Resetting global sync.');
1506 this.globalSelectionSyncStop();
1509 // become the master
1510 if(this.debug === true)
1511 this.log('sync: becoming sync master.');
1513 this.selected = true;
1514 NETDATA.globalSelectionSync.state = this;
1516 // find the all slaves
1517 var targets = NETDATA.options.targets;
1518 var len = targets.length;
1523 if(this.debug === true)
1524 st.log('sync: not adding me to sync');
1526 else if(st.globalSelectionSyncIsEligible()) {
1527 if(this.debug === true)
1528 st.log('sync: adding to sync as slave');
1530 st.globalSelectionSyncBeSlave();
1534 // this.globalSelectionSyncDelay(100);
1537 // can the chart participate to the global selection sync as a slave?
1538 this.globalSelectionSyncIsEligible = function() {
1539 if(this.enabled === true
1540 && this.library !== null
1541 && typeof this.library.setSelection === 'function'
1542 && this.isVisible() === true
1543 && this.chart_created === true)
1549 // this chart becomes a slave of the global selection sync
1550 this.globalSelectionSyncBeSlave = function() {
1551 if(NETDATA.globalSelectionSync.state !== this)
1552 NETDATA.globalSelectionSync.slaves.push(this);
1555 // sync all the visible charts to the given time
1556 // this is to be called from the chart libraries
1557 this.globalSelectionSync = function(t) {
1558 if(this.globalSelectionSyncAbility() === false) {
1559 if(this.debug === true)
1560 this.log('sync: cannot sync (yet?).');
1565 if(this.globalSelectionSyncIsMaster() === false) {
1566 if(this.debug === true)
1567 this.log('sync: trying to be sync master.');
1569 this.globalSelectionSyncBeMaster();
1571 if(this.globalSelectionSyncAbility() === false) {
1572 if(this.debug === true)
1573 this.log('sync: cannot sync (yet?).');
1579 NETDATA.globalSelectionSync.last_t = t;
1580 $.each(NETDATA.globalSelectionSync.slaves, function(i, st) {
1585 // stop syncing all charts to the given time
1586 this.globalSelectionSyncStop = function() {
1587 if(NETDATA.globalSelectionSync.slaves.length) {
1588 if(this.debug === true)
1589 this.log('sync: cleaning up...');
1591 $.each(NETDATA.globalSelectionSync.slaves, function(i, st) {
1593 if(that.debug === true)
1594 st.log('sync: not adding me to sync stop');
1597 if(that.debug === true)
1598 st.log('sync: removed slave from sync');
1600 st.clearSelection();
1604 NETDATA.globalSelectionSync.last_t = 0;
1605 NETDATA.globalSelectionSync.slaves = [];
1606 NETDATA.globalSelectionSync.state = null;
1609 this.clearSelection();
1612 this.setSelection = function(t) {
1613 if(typeof this.library.setSelection === 'function') {
1614 if(this.library.setSelection(this, t) === true)
1615 this.selected = true;
1617 this.selected = false;
1619 else this.selected = true;
1621 if(this.selected === true && this.debug === true)
1622 this.log('selection set to ' + t.toString());
1624 return this.selected;
1627 this.clearSelection = function() {
1628 if(this.selected === true) {
1629 if(typeof this.library.clearSelection === 'function') {
1630 if(this.library.clearSelection(this) === true)
1631 this.selected = false;
1633 this.selected = true;
1635 else this.selected = false;
1637 if(this.selected === false && this.debug === true)
1638 this.log('selection cleared');
1643 return this.selected;
1646 // find if a timestamp (ms) is shown in the current chart
1647 this.timeIsVisible = function(t) {
1648 if(t >= this.data_after && t <= this.data_before)
1653 this.calculateRowForTime = function(t) {
1654 if(this.timeIsVisible(t) === false) return -1;
1655 return Math.floor((t - this.data_after) / this.data_update_every);
1658 // ----------------------------------------------------------------------------------------------------------------
1661 this.log = function(msg) {
1662 console.log(this.id + ' (' + this.library_name + ' ' + this.uuid + '): ' + msg);
1665 this.pauseChart = function() {
1666 if(this.paused === false) {
1667 if(this.debug === true)
1668 this.log('pauseChart()');
1674 this.unpauseChart = function() {
1675 if(this.paused === true) {
1676 if(this.debug === true)
1677 this.log('unpauseChart()');
1679 this.paused = false;
1683 this.resetChart = function(dont_clear_master, dont_update) {
1684 if(this.debug === true)
1685 this.log('resetChart(' + dont_clear_master + ', ' + dont_update + ') called');
1687 if(typeof dont_clear_master === 'undefined')
1688 dont_clear_master = false;
1690 if(typeof dont_update === 'undefined')
1691 dont_update = false;
1693 if(dont_clear_master !== true && NETDATA.globalPanAndZoom.isMaster(this) === true) {
1694 if(this.debug === true)
1695 this.log('resetChart() diverting to clearMaster().');
1696 // this will call us back with master === true
1697 NETDATA.globalPanAndZoom.clearMaster();
1701 this.clearSelection();
1703 this.tm.pan_and_zoom_seq = 0;
1705 this.setMode('auto');
1706 this.current.force_update_at = 0;
1707 this.current.force_before_ms = null;
1708 this.current.force_after_ms = null;
1709 this.tm.last_autorefreshed = 0;
1710 this.paused = false;
1711 this.selected = false;
1712 this.enabled = true;
1713 // this.debug = false;
1715 // do not update the chart here
1716 // or the chart will flip-flop when it is the master
1717 // of a selection sync and another chart becomes
1720 if(dont_update !== true && this.isVisible() === true) {
1725 this.updateChartPanOrZoom = function(after, before) {
1726 var logme = 'updateChartPanOrZoom(' + after + ', ' + before + '): ';
1729 if(this.debug === true)
1732 if(before < after) {
1733 this.log(logme + 'flipped parameters, rejecting it.');
1737 if(typeof this.fixed_min_duration === 'undefined')
1738 this.fixed_min_duration = Math.round((this.chartWidth() / 30) * this.chart.update_every * 1000);
1740 var min_duration = this.fixed_min_duration;
1741 var current_duration = Math.round(this.view_before - this.view_after);
1743 // round the numbers
1744 after = Math.round(after);
1745 before = Math.round(before);
1747 // align them to update_every
1748 // stretching them further away
1749 after -= after % this.data_update_every;
1750 before += this.data_update_every - (before % this.data_update_every);
1752 // the final wanted duration
1753 var wanted_duration = before - after;
1755 // to allow panning, accept just a point below our minimum
1756 if((current_duration - this.data_update_every) < min_duration)
1757 min_duration = current_duration - this.data_update_every;
1759 // we do it, but we adjust to minimum size and return false
1760 // when the wanted size is below the current and the minimum
1762 if(this.current === this.zoom && wanted_duration < current_duration && wanted_duration < min_duration) {
1763 if(this.debug === true)
1764 this.log(logme + 'too small: min_duration: ' + (min_duration / 1000).toString() + ', wanted: ' + (wanted_duration / 1000).toString());
1766 min_duration = this.fixed_min_duration;
1768 var dt = (min_duration - wanted_duration) / 2;
1774 var tolerance = this.data_update_every * 2;
1775 var movement = Math.abs(before - this.view_before);
1777 if(Math.abs(current_duration - wanted_duration) <= tolerance && movement <= tolerance) {
1778 if(this.debug === true)
1779 this.log(logme + 'REJECTING UPDATE: current duration: ' + (current_duration / 1000).toString() + ', wanted duration: ' + (wanted_duration / 1000).toString() + ', duration diff: ' + (Math.round(Math.abs(current_duration - wanted_duration) / 1000)).toString() + ', movement: ' + (movement / 1000).toString() + ', tolerance: ' + (tolerance / 1000).toString() + ', returning: ' + false);
1783 if(this.current.name === 'auto') {
1784 this.log(logme + 'caller called me with mode: ' + this.current.name);
1785 this.setMode('pan');
1788 if(this.debug === true)
1789 this.log(logme + 'ACCEPTING UPDATE: current duration: ' + (current_duration / 1000).toString() + ', wanted duration: ' + (wanted_duration / 1000).toString() + ', duration diff: ' + (Math.round(Math.abs(current_duration - wanted_duration) / 1000)).toString() + ', movement: ' + (movement / 1000).toString() + ', tolerance: ' + (tolerance / 1000).toString() + ', returning: ' + ret);
1791 this.current.force_update_at = new Date().getTime() + NETDATA.options.current.pan_and_zoom_delay;
1792 this.current.force_after_ms = after;
1793 this.current.force_before_ms = before;
1794 NETDATA.globalPanAndZoom.setMaster(this, after, before);
1798 this.legendFormatValue = function(value) {
1799 if(value === null || value === 'undefined') return '-';
1800 if(typeof value !== 'number') return value;
1802 var abs = Math.abs(value);
1803 if(abs >= 1000) return (Math.round(value)).toLocaleString();
1804 if(abs >= 100 ) return (Math.round(value * 10) / 10).toLocaleString();
1805 if(abs >= 1 ) return (Math.round(value * 100) / 100).toLocaleString();
1806 if(abs >= 0.1 ) return (Math.round(value * 1000) / 1000).toLocaleString();
1807 return (Math.round(value * 10000) / 10000).toLocaleString();
1810 this.legendSetLabelValue = function(label, value) {
1811 var series = this.element_legend_childs.series[label];
1812 if(typeof series === 'undefined') return;
1813 if(series.value === null && series.user === null) return;
1815 // if the value has not changed, skip DOM update
1816 //if(series.last === value) return;
1819 if(typeof value === 'number') {
1820 var v = Math.abs(value);
1821 s = r = this.legendFormatValue(value);
1823 if(typeof series.last === 'number') {
1824 if(v > series.last) s += '<i class="fa fa-angle-up" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1825 else if(v < series.last) s += '<i class="fa fa-angle-down" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1826 else s += '<i class="fa fa-angle-left" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1828 else s += '<i class="fa fa-angle-right" style="width: 8px; text-align: center; overflow: hidden; vertical-align: middle;"></i>';
1833 series.last = value;
1836 if(series.value !== null) series.value.innerHTML = s;
1837 if(series.user !== null) series.user.innerHTML = r;
1840 this.legendSetDate = function(ms) {
1841 if(typeof ms !== 'number') {
1842 this.legendShowUndefined();
1846 var d = new Date(ms);
1848 if(this.element_legend_childs.title_date)
1849 this.element_legend_childs.title_date.innerHTML = d.toLocaleDateString();
1851 if(this.element_legend_childs.title_time)
1852 this.element_legend_childs.title_time.innerHTML = d.toLocaleTimeString();
1854 if(this.element_legend_childs.title_units)
1855 this.element_legend_childs.title_units.innerHTML = this.units;
1858 this.legendShowUndefined = function() {
1859 if(this.element_legend_childs.title_date)
1860 this.element_legend_childs.title_date.innerHTML = ' ';
1862 if(this.element_legend_childs.title_time)
1863 this.element_legend_childs.title_time.innerHTML = this.chart.name;
1865 if(this.element_legend_childs.title_units)
1866 this.element_legend_childs.title_units.innerHTML = ' ';
1868 if(this.data && this.element_legend_childs.series !== null) {
1869 var labels = this.data.dimension_names;
1870 var i = labels.length;
1872 var label = labels[i];
1874 if(typeof label === 'undefined') continue;
1875 if(typeof this.element_legend_childs.series[label] === 'undefined') continue;
1876 this.legendSetLabelValue(label, null);
1881 this.legendShowLatestValues = function() {
1882 if(this.chart === null) return;
1883 if(this.selected) return;
1885 if(this.data === null || this.element_legend_childs.series === null) {
1886 this.legendShowUndefined();
1890 var show_undefined = true;
1891 if(Math.abs(this.netdata_last - this.view_before) <= this.data_update_every)
1892 show_undefined = false;
1894 if(show_undefined) {
1895 this.legendShowUndefined();
1899 this.legendSetDate(this.view_before);
1901 var labels = this.data.dimension_names;
1902 var i = labels.length;
1904 var label = labels[i];
1906 if(typeof label === 'undefined') continue;
1907 if(typeof this.element_legend_childs.series[label] === 'undefined') continue;
1910 this.legendSetLabelValue(label, null);
1912 this.legendSetLabelValue(label, this.data.view_latest_values[i]);
1916 this.legendReset = function() {
1917 this.legendShowLatestValues();
1920 // this should be called just ONCE per dimension per chart
1921 this._chartDimensionColor = function(label) {
1922 if(this.colors === null) this.chartColors();
1924 if(typeof this.colors_assigned[label] === 'undefined') {
1925 if(this.colors_available.length === 0) {
1926 for(var i = 0, len = NETDATA.colors.length; i < len ; i++)
1927 this.colors_available.push(NETDATA.colors[i]);
1930 this.colors_assigned[label] = this.colors_available.shift();
1932 if(this.debug === true)
1933 this.log('label "' + label + '" got color "' + this.colors_assigned[label]);
1936 if(this.debug === true)
1937 this.log('label "' + label + '" already has color "' + this.colors_assigned[label] + '"');
1940 this.colors.push(this.colors_assigned[label]);
1941 return this.colors_assigned[label];
1944 this.chartColors = function() {
1945 if(this.colors !== null) return this.colors;
1947 this.colors = new Array();
1948 this.colors_available = new Array();
1950 var c = $(this.element).data('colors');
1951 // this.log('read colors: ' + c);
1952 if(typeof c !== 'undefined' && c !== null) {
1953 if(typeof c !== 'string') {
1954 this.log('invalid color given: ' + c + ' (give a space separated list of colors)');
1961 for(var i = 0, len = c.length; i < len ; i++) {
1963 this.colors_available.push(c[i]);
1964 // this.log('adding color: ' + c[i]);
1970 // push all the standard colors too
1971 for(var i = 0, len = NETDATA.colors.length; i < len ; i++)
1972 this.colors_available.push(NETDATA.colors[i]);
1977 this.legendUpdateDOM = function() {
1980 // check that the legend DOM is up to date for the downloaded dimensions
1981 if(typeof this.element_legend_childs.series !== 'object' || this.element_legend_childs.series === null) {
1982 // this.log('the legend does not have any series - requesting legend update');
1985 else if(this.data === null) {
1986 // this.log('the chart does not have any data - requesting legend update');
1989 else if(typeof this.element_legend_childs.series.labels_key === 'undefined') {
1993 var labels = this.data.dimension_names.toString();
1994 if(labels !== this.element_legend_childs.series.labels_key) {
1997 if(this.debug === true)
1998 this.log('NEW LABELS: "' + labels + '" NOT EQUAL OLD LABELS: "' + this.element_legend_childs.series.labels_key + '"');
2002 if(needed === false) {
2003 // make sure colors available
2006 // do we have to update the current values?
2007 // we do this, only when the visible chart is current
2008 if(Math.abs(this.netdata_last - this.view_before) <= this.data_update_every) {
2009 if(this.debug === true)
2010 this.log('chart is in latest position... updating values on legend...');
2012 //var labels = this.data.dimension_names;
2013 //var i = labels.length;
2015 // this.legendSetLabelValue(labels[i], this.data.latest_values[i]);
2019 if(this.colors === null) {
2020 // this is the first time we update the chart
2021 // let's assign colors to all dimensions
2022 if(this.library.track_colors() === true)
2023 for(var dim in this.chart.dimensions)
2024 this._chartDimensionColor(this.chart.dimensions[dim].name);
2026 // we will re-generate the colors for the chart
2027 // based on the selected dimensions
2030 if(this.debug === true)
2031 this.log('updating Legend DOM');
2033 // mark all dimensions as invalid
2034 this.dimensions_visibility.invalidateAll();
2036 var genLabel = function(state, parent, name, count) {
2037 var color = state._chartDimensionColor(name);
2039 var user_element = null;
2040 var user_id = self.data('show-value-of-' + name + '-at') || null;
2041 if(user_id !== null) {
2042 user_element = document.getElementById(user_id) || null;
2043 if(user_element === null)
2044 me.log('Cannot find element with id: ' + user_id);
2047 state.element_legend_childs.series[name] = {
2048 name: document.createElement('span'),
2049 value: document.createElement('span'),
2054 var label = state.element_legend_childs.series[name];
2056 // create the dimension visibility tracking for this label
2057 state.dimensions_visibility.dimensionAdd(name, label.name, label.value, color);
2059 var rgb = NETDATA.colorHex2Rgb(color);
2060 label.name.innerHTML = '<table class="netdata-legend-name-table-'
2061 + state.chart.chart_type
2062 + '" style="background-color: '
2063 + 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + NETDATA.options.current['color_fill_opacity_' + state.chart.chart_type] + ')'
2064 + '"><tr class="netdata-legend-name-tr"><td class="netdata-legend-name-td"></td></tr></table>'
2066 var text = document.createTextNode(' ' + name);
2067 label.name.appendChild(text);
2070 parent.appendChild(document.createElement('br'));
2072 parent.appendChild(label.name);
2073 parent.appendChild(label.value);
2076 var content = document.createElement('div');
2078 if(this.hasLegend()) {
2079 this.element_legend_childs = {
2081 resize_handler: document.createElement('div'),
2082 title_date: document.createElement('span'),
2083 title_time: document.createElement('span'),
2084 title_units: document.createElement('span'),
2085 nano: document.createElement('div'),
2087 paneClass: 'netdata-legend-series-pane',
2088 sliderClass: 'netdata-legend-series-slider',
2089 contentClass: 'netdata-legend-series-content',
2090 enabledClass: '__enabled',
2091 flashedClass: '__flashed',
2092 activeClass: '__active',
2094 alwaysVisible: true,
2100 this.element_legend.innerHTML = '';
2102 this.element_legend_childs.resize_handler.className += " netdata-legend-resize-handler";
2103 this.element_legend_childs.resize_handler.innerHTML = '<i class="fa fa-chevron-up"></i><i class="fa fa-chevron-down"></i>';
2104 this.element.appendChild(this.element_legend_childs.resize_handler);
2107 this.element_legend_childs.resize_handler.onmousedown =
2109 that.resizeHandler(e);
2113 this.element_legend_childs.resize_handler.addEventListener('touchstart', function(e) {
2114 that.resizeHandler(e);
2117 this.element_legend_childs.title_date.className += " netdata-legend-title-date";
2118 this.element_legend.appendChild(this.element_legend_childs.title_date);
2120 this.element_legend.appendChild(document.createElement('br'));
2122 this.element_legend_childs.title_time.className += " netdata-legend-title-time";
2123 this.element_legend.appendChild(this.element_legend_childs.title_time);
2125 this.element_legend.appendChild(document.createElement('br'));
2127 this.element_legend_childs.title_units.className += " netdata-legend-title-units";
2128 this.element_legend.appendChild(this.element_legend_childs.title_units);
2130 this.element_legend.appendChild(document.createElement('br'));
2132 this.element_legend_childs.nano.className = 'netdata-legend-series';
2133 this.element_legend.appendChild(this.element_legend_childs.nano);
2135 content.className = 'netdata-legend-series-content';
2136 this.element_legend_childs.nano.appendChild(content);
2139 this.element_legend_childs = {
2141 resize_handler: null,
2152 this.element_legend_childs.series.labels_key = this.data.dimension_names.toString();
2153 if(this.debug === true)
2154 this.log('labels from data: "' + this.element_legend_childs.series.labels_key + '"');
2156 for(var i = 0, len = this.data.dimension_names.length; i < len ;i++) {
2157 genLabel(this, content, this.data.dimension_names[i], i);
2161 var tmp = new Array();
2162 for(var dim in this.chart.dimensions) {
2163 tmp.push(this.chart.dimensions[dim].name);
2164 genLabel(this, content, this.chart.dimensions[dim].name, i);
2166 this.element_legend_childs.series.labels_key = tmp.toString();
2167 if(this.debug === true)
2168 this.log('labels from chart: "' + this.element_legend_childs.series.labels_key + '"');
2171 // create a hidden div to be used for hidding
2172 // the original legend of the chart library
2173 var el = document.createElement('div');
2174 if(this.element_legend !== null)
2175 this.element_legend.appendChild(el);
2176 el.style.display = 'none';
2178 this.element_legend_childs.hidden = document.createElement('div');
2179 el.appendChild(this.element_legend_childs.hidden);
2181 if(this.element_legend_childs.nano !== null && this.element_legend_childs.nano_options !== null)
2182 $(this.element_legend_childs.nano).nanoScroller(this.element_legend_childs.nano_options);
2184 this.legendShowLatestValues();
2187 this.hasLegend = function() {
2188 if(typeof this.___hasLegendCache___ !== 'undefined')
2189 return this.___hasLegendCache___;
2192 if(this.library && this.library.legend(this) === 'right-side') {
2193 var legend = $(this.element).data('legend') || 'yes';
2194 if(legend === 'yes') leg = true;
2197 this.___hasLegendCache___ = leg;
2201 this.legendWidth = function() {
2202 return (this.hasLegend())?140:0;
2205 this.legendHeight = function() {
2206 return $(this.element).height();
2209 this.chartWidth = function() {
2210 return $(this.element).width() - this.legendWidth();
2213 this.chartHeight = function() {
2214 return $(this.element).height();
2217 this.chartPixelsPerPoint = function() {
2218 // force an options provided detail
2219 var px = this.pixels_per_point;
2221 if(this.library && px < this.library.pixels_per_point(this))
2222 px = this.library.pixels_per_point(this);
2224 if(px < NETDATA.options.current.pixels_per_point)
2225 px = NETDATA.options.current.pixels_per_point;
2230 this.needsRecreation = function() {
2232 this.chart_created === true
2234 && this.library.autoresize() === false
2235 && this.tm.last_resized < NETDATA.options.last_resized
2239 this.chartURL = function() {
2240 var after, before, points_multiplier = 1;
2241 if(NETDATA.globalPanAndZoom.isActive() && NETDATA.globalPanAndZoom.isMaster(this) === false) {
2242 this.tm.pan_and_zoom_seq = NETDATA.globalPanAndZoom.seq;
2244 after = Math.round(NETDATA.globalPanAndZoom.force_after_ms / 1000);
2245 before = Math.round(NETDATA.globalPanAndZoom.force_before_ms / 1000);
2246 this.view_after = after * 1000;
2247 this.view_before = before * 1000;
2249 this.requested_padding = null;
2250 points_multiplier = 1;
2252 else if(this.current.force_before_ms !== null && this.current.force_after_ms !== null) {
2253 this.tm.pan_and_zoom_seq = 0;
2255 before = Math.round(this.current.force_before_ms / 1000);
2256 after = Math.round(this.current.force_after_ms / 1000);
2257 this.view_after = after * 1000;
2258 this.view_before = before * 1000;
2260 if(NETDATA.options.current.pan_and_zoom_data_padding === true) {
2261 this.requested_padding = Math.round((before - after) / 2);
2262 after -= this.requested_padding;
2263 before += this.requested_padding;
2264 this.requested_padding *= 1000;
2265 points_multiplier = 2;
2268 this.current.force_before_ms = null;
2269 this.current.force_after_ms = null;
2272 this.tm.pan_and_zoom_seq = 0;
2274 before = this.before;
2276 this.view_after = after * 1000;
2277 this.view_before = before * 1000;
2279 this.requested_padding = null;
2280 points_multiplier = 1;
2283 this.requested_after = after * 1000;
2284 this.requested_before = before * 1000;
2286 this.data_points = this.points || Math.round(this.chartWidth() / this.chartPixelsPerPoint());
2288 // build the data URL
2289 this.data_url = this.chart.data_url;
2290 this.data_url += "&format=" + this.library.format();
2291 this.data_url += "&points=" + (this.data_points * points_multiplier).toString();
2292 this.data_url += "&group=" + this.method;
2293 this.data_url += "&options=" + this.library.options(this);
2294 this.data_url += '|jsonwrap';
2296 if(NETDATA.options.current.eliminate_zero_dimensions === true)
2297 this.data_url += '|nonzero';
2299 if(this.append_options !== null)
2300 this.data_url += '|' + this.append_options.toString();
2303 this.data_url += "&after=" + after.toString();
2306 this.data_url += "&before=" + before.toString();
2309 this.data_url += "&dimensions=" + this.dimensions;
2311 if(NETDATA.options.debug.chart_data_url === true || this.debug === true)
2312 this.log('chartURL(): ' + this.data_url + ' WxH:' + this.chartWidth() + 'x' + this.chartHeight() + ' points: ' + this.data_points + ' library: ' + this.library_name);
2315 this.redrawChart = function() {
2316 if(this.data !== null)
2317 this.updateChartWithData(this.data);
2320 this.updateChartWithData = function(data) {
2321 if(this.debug === true)
2322 this.log('updateChartWithData() called.');
2324 // this may force the chart to be re-created
2328 this.updates_counter++;
2329 this.updates_since_last_unhide++;
2330 this.updates_since_last_creation++;
2332 var started = new Date().getTime();
2334 // if the result is JSON, find the latest update-every
2335 this.data_update_every = data.view_update_every * 1000;
2336 this.data_after = data.after * 1000;
2337 this.data_before = data.before * 1000;
2338 this.netdata_first = data.first_entry * 1000;
2339 this.netdata_last = data.last_entry * 1000;
2340 this.data_points = data.points;
2343 if(NETDATA.options.current.pan_and_zoom_data_padding === true && this.requested_padding !== null) {
2344 if(this.view_after < this.data_after) {
2345 // console.log('adusting view_after from ' + this.view_after + ' to ' + this.data_after);
2346 this.view_after = this.data_after;
2349 if(this.view_before > this.data_before) {
2350 // console.log('adusting view_before from ' + this.view_before + ' to ' + this.data_before);
2351 this.view_before = this.data_before;
2355 this.view_after = this.data_after;
2356 this.view_before = this.data_before;
2359 if(this.debug === true) {
2360 this.log('UPDATE No ' + this.updates_counter + ' COMPLETED');
2362 if(this.current.force_after_ms)
2363 this.log('STATUS: forced : ' + (this.current.force_after_ms / 1000).toString() + ' - ' + (this.current.force_before_ms / 1000).toString());
2365 this.log('STATUS: forced : unset');
2367 this.log('STATUS: requested : ' + (this.requested_after / 1000).toString() + ' - ' + (this.requested_before / 1000).toString());
2368 this.log('STATUS: downloaded: ' + (this.data_after / 1000).toString() + ' - ' + (this.data_before / 1000).toString());
2369 this.log('STATUS: rendered : ' + (this.view_after / 1000).toString() + ' - ' + (this.view_before / 1000).toString());
2370 this.log('STATUS: points : ' + (this.data_points).toString());
2373 if(this.data_points === 0) {
2378 if(this.updates_since_last_creation >= this.library.max_updates_to_recreate()) {
2379 if(this.debug === true)
2380 this.log('max updates of ' + this.updates_since_last_creation.toString() + ' reached. Forcing re-generation.');
2382 this.chart_created = false;
2385 // check and update the legend
2386 this.legendUpdateDOM();
2388 if(this.chart_created === true
2389 && typeof this.library.update === 'function') {
2391 if(this.debug === true)
2392 this.log('updating chart...');
2394 if(callChartLibraryUpdateSafely(data) === false)
2398 if(this.debug === true)
2399 this.log('creating chart...');
2401 if(callChartLibraryCreateSafely(data) === false)
2405 this.legendShowLatestValues();
2406 if(this.selected === true)
2407 NETDATA.globalSelectionSync.stop();
2409 // update the performance counters
2410 var now = new Date().getTime();
2411 this.tm.last_updated = now;
2413 // don't update last_autorefreshed if this chart is
2414 // forced to be updated with global PanAndZoom
2415 if(NETDATA.globalPanAndZoom.isActive())
2416 this.tm.last_autorefreshed = 0;
2418 if(NETDATA.options.current.parallel_refresher === true && NETDATA.options.current.concurrent_refreshes)
2419 this.tm.last_autorefreshed = Math.round(now / this.data_update_every) * this.data_update_every;
2421 this.tm.last_autorefreshed = now;
2424 this.refresh_dt_ms = now - started;
2425 NETDATA.options.auto_refresher_fast_weight += this.refresh_dt_ms;
2427 if(this.refresh_dt_element !== null)
2428 this.refresh_dt_element.innerHTML = this.refresh_dt_ms.toString();
2431 this.updateChart = function(callback) {
2432 if(this.debug === true)
2433 this.log('updateChart() called.');
2435 // due to late initialization of charts and libraries
2436 // we need to check this too
2437 if(this.enabled === false) {
2438 if(this.debug === true)
2439 this.log('I am not enabled');
2441 if(typeof callback === 'function') callback();
2445 if(canBeRendered() === false) {
2446 if(typeof callback === 'function') callback();
2450 if(this.chart === null) {
2451 this.getChart(function() { that.updateChart(callback); });
2455 if(this.library.initialized === false) {
2456 if(this.library.enabled === true) {
2457 this.library.initialize(function() { that.updateChart(callback); });
2461 error('chart library "' + this.library_name + '" is not available.');
2462 if(typeof callback === 'function') callback();
2467 this.clearSelection();
2470 if(this.debug === true)
2471 this.log('updating from ' + this.data_url);
2473 this.xhr = $.ajax( {
2475 crossDomain: NETDATA.options.crossDomainAjax,
2479 .success(function(data) {
2480 if(that.debug === true)
2481 that.log('data received. updating chart.');
2483 that.updateChartWithData(data);
2486 error('data download failed for url: ' + that.data_url);
2488 .always(function() {
2489 if(typeof callback === 'function') callback();
2495 this.isVisible = function(nocache) {
2496 if(typeof nocache === 'undefined')
2499 // this.log('last_visible_check: ' + this.tm.last_visible_check + ', last_page_scroll: ' + NETDATA.options.last_page_scroll);
2501 // caching - we do not evaluate the charts visibility
2502 // if the page has not been scrolled since the last check
2503 if(nocache === false && this.tm.last_visible_check > NETDATA.options.last_page_scroll)
2504 return this.___isVisible___;
2506 this.tm.last_visible_check = new Date().getTime();
2508 var wh = window.innerHeight;
2509 var x = this.element.getBoundingClientRect();
2513 if(x.width === 0 || x.height === 0) {
2515 this.___isVisible___ = false;
2516 return this.___isVisible___;
2519 if(x.top < 0 && -x.top > x.height) {
2520 // the chart is entirely above
2521 ret = -x.top - x.height;
2523 else if(x.top > wh) {
2524 // the chart is entirely below
2528 if(ret > tolerance) {
2529 // the chart is too far
2532 this.___isVisible___ = false;
2533 return this.___isVisible___;
2536 // the chart is inside or very close
2539 this.___isVisible___ = true;
2540 return this.___isVisible___;
2544 this.isAutoRefreshed = function() {
2545 return (this.current.autorefresh);
2548 this.canBeAutoRefreshed = function() {
2549 now = new Date().getTime();
2551 if(this.enabled === false) {
2552 if(this.debug === true)
2553 this.log('I am not enabled');
2558 if(this.library === null || this.library.enabled === false) {
2559 error('charting library "' + this.library_name + '" is not available');
2560 if(this.debug === true)
2561 this.log('My chart library ' + this.library_name + ' is not available');
2566 if(this.isVisible() === false) {
2567 if(NETDATA.options.debug.visibility === true || this.debug === true)
2568 this.log('I am not visible');
2573 if(this.current.force_update_at !== 0 && this.current.force_update_at < now) {
2574 if(this.debug === true)
2575 this.log('timed force update detected - allowing this update');
2577 this.current.force_update_at = 0;
2581 if(this.isAutoRefreshed() === true) {
2582 // allow the first update, even if the page is not visible
2583 if(this.updates_counter && this.updates_since_last_unhide && NETDATA.options.page_is_visible === false) {
2584 if(NETDATA.options.debug.focus === true || this.debug === true)
2585 this.log('canBeAutoRefreshed(): page does not have focus');
2590 if(this.needsRecreation() === true) {
2591 if(this.debug === true)
2592 this.log('canBeAutoRefreshed(): needs re-creation.');
2597 // options valid only for autoRefresh()
2598 if(NETDATA.options.auto_refresher_stop_until === 0 || NETDATA.options.auto_refresher_stop_until < now) {
2599 if(NETDATA.globalPanAndZoom.isActive()) {
2600 if(NETDATA.globalPanAndZoom.shouldBeAutoRefreshed(this)) {
2601 if(this.debug === true)
2602 this.log('canBeAutoRefreshed(): global panning: I need an update.');
2607 if(this.debug === true)
2608 this.log('canBeAutoRefreshed(): global panning: I am already up to date.');
2614 if(this.selected === true) {
2615 if(this.debug === true)
2616 this.log('canBeAutoRefreshed(): I have a selection in place.');
2621 if(this.paused === true) {
2622 if(this.debug === true)
2623 this.log('canBeAutoRefreshed(): I am paused.');
2628 if(now - this.tm.last_autorefreshed >= this.data_update_every) {
2629 if(this.debug === true)
2630 this.log('canBeAutoRefreshed(): It is time to update me.');
2640 this.autoRefresh = function(callback) {
2641 if(this.canBeAutoRefreshed() === true) {
2642 this.updateChart(callback);
2645 if(typeof callback !== 'undefined')
2650 this._defaultsFromDownloadedChart = function(chart) {
2652 this.chart_url = chart.url;
2653 this.data_update_every = chart.update_every * 1000;
2654 this.data_points = Math.round(this.chartWidth() / this.chartPixelsPerPoint());
2655 this.tm.last_info_downloaded = new Date().getTime();
2657 if(this.title === null)
2658 this.title = chart.title;
2660 if(this.units === null)
2661 this.units = chart.units;
2664 // fetch the chart description from the netdata server
2665 this.getChart = function(callback) {
2666 this.chart = NETDATA.chartRegistry.get(this.host, this.id);
2668 this._defaultsFromDownloadedChart(this.chart);
2669 if(typeof callback === 'function') callback();
2672 this.chart_url = this.host + "/api/v1/chart?chart=" + this.id;
2674 if(this.debug === true)
2675 this.log('downloading ' + this.chart_url);
2678 url: this.chart_url,
2679 crossDomain: NETDATA.options.crossDomainAjax,
2683 .done(function(chart) {
2684 chart.url = that.chart_url;
2685 chart.data_url = (that.host + chart.data_url);
2686 that._defaultsFromDownloadedChart(chart);
2687 NETDATA.chartRegistry.add(that.host, that.id, chart);
2690 NETDATA.error(404, that.chart_url);
2691 error('chart not found on url "' + that.chart_url + '"');
2693 .always(function() {
2694 if(typeof callback === 'function') callback();
2699 // ============================================================================================================
2705 NETDATA.resetAllCharts = function(state) {
2706 // first clear the global selection sync
2707 // to make sure no chart is in selected state
2708 state.globalSelectionSyncStop();
2710 // there are 2 possibilities here
2711 // a. state is the global Pan and Zoom master
2712 // b. state is not the global Pan and Zoom master
2714 if(NETDATA.globalPanAndZoom.isMaster(state) === false)
2717 // clear the global Pan and Zoom
2718 // this will also refresh the master
2719 // and unblock any charts currently mirroring the master
2720 NETDATA.globalPanAndZoom.clearMaster();
2722 // if we were not the master, reset our status too
2723 // this is required because most probably the mouse
2724 // is over this chart, blocking it from autorefreshing
2725 if(master === false && (state.paused === true || state.selected === true))
2729 // get or create a chart state, given a DOM element
2730 NETDATA.chartState = function(element) {
2731 var state = $(element).data('netdata-state-object') || null;
2732 if(state === null) {
2733 state = new chartState(element);
2734 $(element).data('netdata-state-object', state);
2739 // ----------------------------------------------------------------------------------------------------------------
2740 // Library functions
2742 // Load a script without jquery
2743 // This is used to load jquery - after it is loaded, we use jquery
2744 NETDATA._loadjQuery = function(callback) {
2745 if(typeof jQuery === 'undefined') {
2746 if(NETDATA.options.debug.main_loop === true)
2747 console.log('loading ' + NETDATA.jQuery);
2749 var script = document.createElement('script');
2750 script.type = 'text/javascript';
2751 script.async = true;
2752 script.src = NETDATA.jQuery;
2754 // script.onabort = onError;
2755 script.onerror = function(err, t) { NETDATA.error(101, NETDATA.jQuery); };
2756 if(typeof callback === "function")
2757 script.onload = callback;
2759 var s = document.getElementsByTagName('script')[0];
2760 s.parentNode.insertBefore(script, s);
2762 else if(typeof callback === "function")
2766 NETDATA._loadCSS = function(filename) {
2767 // don't use jQuery here
2768 // styles are loaded before jQuery
2769 // to eliminate showing an unstyled page to the user
2771 var fileref = document.createElement("link");
2772 fileref.setAttribute("rel", "stylesheet");
2773 fileref.setAttribute("type", "text/css");
2774 fileref.setAttribute("href", filename);
2776 if (typeof fileref !== 'undefined')
2777 document.getElementsByTagName("head")[0].appendChild(fileref);
2780 NETDATA.colorHex2Rgb = function(hex) {
2781 // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
2782 var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
2783 hex = hex.replace(shorthandRegex, function(m, r, g, b) {
2784 return r + r + g + g + b + b;
2787 var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
2789 r: parseInt(result[1], 16),
2790 g: parseInt(result[2], 16),
2791 b: parseInt(result[3], 16)
2795 NETDATA.colorLuminance = function(hex, lum) {
2796 // validate hex string
2797 hex = String(hex).replace(/[^0-9a-f]/gi, '');
2799 hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
2803 // convert to decimal and change luminosity
2804 var rgb = "#", c, i;
2805 for (i = 0; i < 3; i++) {
2806 c = parseInt(hex.substr(i*2,2), 16);
2807 c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
2808 rgb += ("00"+c).substr(c.length);
2814 NETDATA.guid = function() {
2816 return Math.floor((1 + Math.random()) * 0x10000)
2821 return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
2824 NETDATA.zeropad = function(x) {
2825 if(x > -10 && x < 10) return '0' + x.toString();
2826 else return x.toString();
2829 // user function to signal us the DOM has been
2831 NETDATA.updatedDom = function() {
2832 NETDATA.options.updated_dom = true;
2835 NETDATA.ready = function(callback) {
2836 NETDATA.options.pauseCallback = callback;
2839 NETDATA.pause = function(callback) {
2840 if(NETDATA.options.pause === true)
2843 NETDATA.options.pauseCallback = callback;
2846 NETDATA.unpause = function() {
2847 NETDATA.options.pauseCallback = null;
2848 NETDATA.options.updated_dom = true;
2849 NETDATA.options.pause = false;
2852 // ----------------------------------------------------------------------------------------------------------------
2854 // this is purely sequencial charts refresher
2855 // it is meant to be autonomous
2856 NETDATA.chartRefresherNoParallel = function(index) {
2857 if(NETDATA.options.debug.mail_loop === true)
2858 console.log('NETDATA.chartRefresherNoParallel(' + index + ')');
2860 if(NETDATA.options.updated_dom === true) {
2861 // the dom has been updated
2862 // get the dom parts again
2863 NETDATA.parseDom(NETDATA.chartRefresher);
2866 if(index >= NETDATA.options.targets.length) {
2867 if(NETDATA.options.debug.main_loop === true)
2868 console.log('waiting to restart main loop...');
2870 NETDATA.options.auto_refresher_fast_weight = 0;
2872 setTimeout(function() {
2873 NETDATA.chartRefresher();
2874 }, NETDATA.options.current.idle_between_loops);
2877 var state = NETDATA.options.targets[index];
2879 if(NETDATA.options.auto_refresher_fast_weight < NETDATA.options.current.fast_render_timeframe) {
2880 if(NETDATA.options.debug.main_loop === true)
2881 console.log('fast rendering...');
2883 state.autoRefresh(function() {
2884 NETDATA.chartRefresherNoParallel(++index);
2888 if(NETDATA.options.debug.main_loop === true) console.log('waiting for next refresh...');
2889 NETDATA.options.auto_refresher_fast_weight = 0;
2891 setTimeout(function() {
2892 state.autoRefresh(function() {
2893 NETDATA.chartRefresherNoParallel(++index);
2895 }, NETDATA.options.current.idle_between_charts);
2900 // this is part of the parallel refresher
2901 // its cause is to refresh sequencially all the charts
2902 // that depend on chart library initialization
2903 // it will call the parallel refresher back
2904 // as soon as it sees a chart that its chart library
2906 NETDATA.chartRefresher_unitialized = function() {
2907 if(NETDATA.options.updated_dom === true) {
2908 // the dom has been updated
2909 // get the dom parts again
2910 NETDATA.parseDom(NETDATA.chartRefresher);
2914 if(NETDATA.options.sequencial.length === 0)
2915 NETDATA.chartRefresher();
2917 var state = NETDATA.options.sequencial.pop();
2918 if(state.library.initialized === true)
2919 NETDATA.chartRefresher();
2921 state.autoRefresh(NETDATA.chartRefresher_unitialized);
2925 NETDATA.chartRefresherWaitTime = function() {
2926 return NETDATA.options.current.idle_parallel_loops;
2929 // the default refresher
2930 // it will create 2 sets of charts:
2931 // - the ones that can be refreshed in parallel
2932 // - the ones that depend on something else
2933 // the first set will be executed in parallel
2934 // the second will be given to NETDATA.chartRefresher_unitialized()
2935 NETDATA.chartRefresher = function() {
2936 if(NETDATA.options.pause === true) {
2937 // console.log('auto-refresher is paused');
2938 setTimeout(NETDATA.chartRefresher,
2939 NETDATA.chartRefresherWaitTime());
2943 if(typeof NETDATA.options.pauseCallback === 'function') {
2944 // console.log('auto-refresher is calling pauseCallback');
2945 NETDATA.options.pause = true;
2946 NETDATA.options.pauseCallback();
2947 NETDATA.chartRefresher();
2951 if(NETDATA.options.current.parallel_refresher === false) {
2952 NETDATA.chartRefresherNoParallel(0);
2956 if(NETDATA.options.updated_dom === true) {
2957 // the dom has been updated
2958 // get the dom parts again
2959 NETDATA.parseDom(NETDATA.chartRefresher);
2963 var parallel = new Array();
2964 var targets = NETDATA.options.targets;
2965 var len = targets.length;
2967 if(targets[len].isVisible() === false)
2970 var state = targets[len];
2971 if(state.library.initialized === false) {
2972 if(state.library.enabled === true) {
2973 state.library.initialize(NETDATA.chartRefresher);
2977 state.error('chart library "' + state.library_name + '" is not enabled.');
2981 parallel.unshift(state);
2984 if(parallel.length > 0) {
2985 var parallel_jobs = parallel.length;
2987 // this will execute the jobs in parallel
2988 $(parallel).each(function() {
2989 this.autoRefresh(function() {
2992 if(parallel_jobs === 0) {
2993 setTimeout(NETDATA.chartRefresher,
2994 NETDATA.chartRefresherWaitTime());
3000 setTimeout(NETDATA.chartRefresher,
3001 NETDATA.chartRefresherWaitTime());
3005 NETDATA.parseDom = function(callback) {
3006 NETDATA.options.last_page_scroll = new Date().getTime();
3007 NETDATA.options.updated_dom = false;
3009 var targets = $('div[data-netdata]'); //.filter(':visible');
3011 if(NETDATA.options.debug.main_loop === true)
3012 console.log('DOM updated - there are ' + targets.length + ' charts on page.');
3014 NETDATA.options.targets = new Array();
3015 var len = targets.length;
3017 // the initialization will take care of sizing
3018 // and the "loading..." message
3019 NETDATA.options.targets.push(NETDATA.chartState(targets[len]));
3022 if(typeof callback === 'function') callback();
3025 // this is the main function - where everything starts
3026 NETDATA.start = function() {
3027 // this should be called only once
3029 NETDATA.options.page_is_visible = true;
3031 $(window).blur(function() {
3032 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
3033 NETDATA.options.page_is_visible = false;
3034 if(NETDATA.options.debug.focus === true)
3035 console.log('Lost Focus!');
3039 $(window).focus(function() {
3040 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
3041 NETDATA.options.page_is_visible = true;
3042 if(NETDATA.options.debug.focus === true)
3043 console.log('Focus restored!');
3047 if(typeof document.hasFocus === 'function' && !document.hasFocus()) {
3048 if(NETDATA.options.current.stop_updates_when_focus_is_lost === true) {
3049 NETDATA.options.page_is_visible = false;
3050 if(NETDATA.options.debug.focus === true)
3051 console.log('Document has no focus!');
3055 // bootstrap tab switching
3056 $('a[data-toggle="tab"]').on('shown.bs.tab', NETDATA.onscroll);
3058 // bootstrap modal switching
3059 $('.modal').on('hidden.bs.modal', NETDATA.onscroll);
3060 $('.modal').on('shown.bs.modal', NETDATA.onscroll);
3062 NETDATA.parseDom(NETDATA.chartRefresher);
3065 // ----------------------------------------------------------------------------------------------------------------
3068 NETDATA.peityInitialize = function(callback) {
3069 if(typeof netdataNoPeitys === 'undefined' || !netdataNoPeitys) {
3071 url: NETDATA.peity_js,
3076 NETDATA.registerChartLibrary('peity', NETDATA.peity_js);
3079 NETDATA.chartLibraries.peity.enabled = false;
3080 NETDATA.error(100, NETDATA.peity_js);
3082 .always(function() {
3083 if(typeof callback === "function")
3088 NETDATA.chartLibraries.peity.enabled = false;
3089 if(typeof callback === "function")
3094 NETDATA.peityChartUpdate = function(state, data) {
3095 state.peity_instance.innerHTML = data.result;
3097 if(state.peity_options.stroke !== state.chartColors()[0]) {
3098 state.peity_options.stroke = state.chartColors()[0];
3099 if(state.chart.chart_type === 'line')
3100 state.peity_options.fill = '#FFF';
3102 state.peity_options.fill = NETDATA.colorLuminance(state.chartColors()[0], NETDATA.chartDefaults.fill_luminance);
3105 $(state.peity_instance).peity('line', state.peity_options);
3109 NETDATA.peityChartCreate = function(state, data) {
3110 state.peity_instance = document.createElement('div');
3111 state.element_chart.appendChild(state.peity_instance);
3113 var self = $(state.element);
3114 state.peity_options = {
3116 strokeWidth: self.data('peity-strokewidth') || 1,
3117 width: state.chartWidth(),
3118 height: state.chartHeight(),
3122 NETDATA.peityChartUpdate(state, data);
3126 // ----------------------------------------------------------------------------------------------------------------
3129 NETDATA.sparklineInitialize = function(callback) {
3130 if(typeof netdataNoSparklines === 'undefined' || !netdataNoSparklines) {
3132 url: NETDATA.sparkline_js,
3137 NETDATA.registerChartLibrary('sparkline', NETDATA.sparkline_js);
3140 NETDATA.chartLibraries.sparkline.enabled = false;
3141 NETDATA.error(100, NETDATA.sparkline_js);
3143 .always(function() {
3144 if(typeof callback === "function")
3149 NETDATA.chartLibraries.sparkline.enabled = false;
3150 if(typeof callback === "function")
3155 NETDATA.sparklineChartUpdate = function(state, data) {
3156 state.sparkline_options.width = state.chartWidth();
3157 state.sparkline_options.height = state.chartHeight();
3159 $(state.element_chart).sparkline(data.result, state.sparkline_options);
3163 NETDATA.sparklineChartCreate = function(state, data) {
3164 var self = $(state.element);
3165 var type = self.data('sparkline-type') || 'line';
3166 var lineColor = self.data('sparkline-linecolor') || state.chartColors()[0];
3167 var fillColor = self.data('sparkline-fillcolor') || (state.chart.chart_type === 'line')?'#FFF':NETDATA.colorLuminance(lineColor, NETDATA.chartDefaults.fill_luminance);
3168 var chartRangeMin = self.data('sparkline-chartrangemin') || undefined;
3169 var chartRangeMax = self.data('sparkline-chartrangemax') || undefined;
3170 var composite = self.data('sparkline-composite') || undefined;
3171 var enableTagOptions = self.data('sparkline-enabletagoptions') || undefined;
3172 var tagOptionPrefix = self.data('sparkline-tagoptionprefix') || undefined;
3173 var tagValuesAttribute = self.data('sparkline-tagvaluesattribute') || undefined;
3174 var disableHiddenCheck = self.data('sparkline-disablehiddencheck') || undefined;
3175 var defaultPixelsPerValue = self.data('sparkline-defaultpixelspervalue') || undefined;
3176 var spotColor = self.data('sparkline-spotcolor') || undefined;
3177 var minSpotColor = self.data('sparkline-minspotcolor') || undefined;
3178 var maxSpotColor = self.data('sparkline-maxspotcolor') || undefined;
3179 var spotRadius = self.data('sparkline-spotradius') || undefined;
3180 var valueSpots = self.data('sparkline-valuespots') || undefined;
3181 var highlightSpotColor = self.data('sparkline-highlightspotcolor') || undefined;
3182 var highlightLineColor = self.data('sparkline-highlightlinecolor') || undefined;
3183 var lineWidth = self.data('sparkline-linewidth') || undefined;
3184 var normalRangeMin = self.data('sparkline-normalrangemin') || undefined;
3185 var normalRangeMax = self.data('sparkline-normalrangemax') || undefined;
3186 var drawNormalOnTop = self.data('sparkline-drawnormalontop') || undefined;
3187 var xvalues = self.data('sparkline-xvalues') || undefined;
3188 var chartRangeClip = self.data('sparkline-chartrangeclip') || undefined;
3189 var xvalues = self.data('sparkline-xvalues') || undefined;
3190 var chartRangeMinX = self.data('sparkline-chartrangeminx') || undefined;
3191 var chartRangeMaxX = self.data('sparkline-chartrangemaxx') || undefined;
3192 var disableInteraction = self.data('sparkline-disableinteraction') || false;
3193 var disableTooltips = self.data('sparkline-disabletooltips') || false;
3194 var disableHighlight = self.data('sparkline-disablehighlight') || false;
3195 var highlightLighten = self.data('sparkline-highlightlighten') || 1.4;
3196 var highlightColor = self.data('sparkline-highlightcolor') || undefined;
3197 var tooltipContainer = self.data('sparkline-tooltipcontainer') || undefined;
3198 var tooltipClassname = self.data('sparkline-tooltipclassname') || undefined;
3199 var tooltipFormat = self.data('sparkline-tooltipformat') || undefined;
3200 var tooltipPrefix = self.data('sparkline-tooltipprefix') || undefined;
3201 var tooltipSuffix = self.data('sparkline-tooltipsuffix') || ' ' + state.units;
3202 var tooltipSkipNull = self.data('sparkline-tooltipskipnull') || true;
3203 var tooltipValueLookups = self.data('sparkline-tooltipvaluelookups') || undefined;
3204 var tooltipFormatFieldlist = self.data('sparkline-tooltipformatfieldlist') || undefined;
3205 var tooltipFormatFieldlistKey = self.data('sparkline-tooltipformatfieldlistkey') || undefined;
3206 var numberFormatter = self.data('sparkline-numberformatter') || function(n){ return n.toFixed(2); };
3207 var numberDigitGroupSep = self.data('sparkline-numberdigitgroupsep') || undefined;
3208 var numberDecimalMark = self.data('sparkline-numberdecimalmark') || undefined;
3209 var numberDigitGroupCount = self.data('sparkline-numberdigitgroupcount') || undefined;
3210 var animatedZooms = self.data('sparkline-animatedzooms') || false;
3212 state.sparkline_options = {
3214 lineColor: lineColor,
3215 fillColor: fillColor,
3216 chartRangeMin: chartRangeMin,
3217 chartRangeMax: chartRangeMax,
3218 composite: composite,
3219 enableTagOptions: enableTagOptions,
3220 tagOptionPrefix: tagOptionPrefix,
3221 tagValuesAttribute: tagValuesAttribute,
3222 disableHiddenCheck: disableHiddenCheck,
3223 defaultPixelsPerValue: defaultPixelsPerValue,
3224 spotColor: spotColor,
3225 minSpotColor: minSpotColor,
3226 maxSpotColor: maxSpotColor,
3227 spotRadius: spotRadius,
3228 valueSpots: valueSpots,
3229 highlightSpotColor: highlightSpotColor,
3230 highlightLineColor: highlightLineColor,
3231 lineWidth: lineWidth,
3232 normalRangeMin: normalRangeMin,
3233 normalRangeMax: normalRangeMax,
3234 drawNormalOnTop: drawNormalOnTop,
3236 chartRangeClip: chartRangeClip,
3237 chartRangeMinX: chartRangeMinX,
3238 chartRangeMaxX: chartRangeMaxX,
3239 disableInteraction: disableInteraction,
3240 disableTooltips: disableTooltips,
3241 disableHighlight: disableHighlight,
3242 highlightLighten: highlightLighten,
3243 highlightColor: highlightColor,
3244 tooltipContainer: tooltipContainer,
3245 tooltipClassname: tooltipClassname,
3246 tooltipChartTitle: state.title,
3247 tooltipFormat: tooltipFormat,
3248 tooltipPrefix: tooltipPrefix,
3249 tooltipSuffix: tooltipSuffix,
3250 tooltipSkipNull: tooltipSkipNull,
3251 tooltipValueLookups: tooltipValueLookups,
3252 tooltipFormatFieldlist: tooltipFormatFieldlist,
3253 tooltipFormatFieldlistKey: tooltipFormatFieldlistKey,
3254 numberFormatter: numberFormatter,
3255 numberDigitGroupSep: numberDigitGroupSep,
3256 numberDecimalMark: numberDecimalMark,
3257 numberDigitGroupCount: numberDigitGroupCount,
3258 animatedZooms: animatedZooms,
3259 width: state.chartWidth(),
3260 height: state.chartHeight()
3263 $(state.element_chart).sparkline(data.result, state.sparkline_options);
3267 // ----------------------------------------------------------------------------------------------------------------
3274 NETDATA.dygraphSetSelection = function(state, t) {
3275 if(typeof state.dygraph_instance !== 'undefined') {
3276 var r = state.calculateRowForTime(t);
3278 state.dygraph_instance.setSelection(r);
3280 state.dygraph_instance.clearSelection();
3281 state.legendShowUndefined();
3288 NETDATA.dygraphClearSelection = function(state, t) {
3289 if(typeof state.dygraph_instance !== 'undefined') {
3290 state.dygraph_instance.clearSelection();
3295 NETDATA.dygraphSmoothInitialize = function(callback) {
3297 url: NETDATA.dygraph_smooth_js,
3302 NETDATA.dygraph.smooth = true;
3303 smoothPlotter.smoothing = 0.3;
3306 NETDATA.dygraph.smooth = false;
3308 .always(function() {
3309 if(typeof callback === "function")
3314 NETDATA.dygraphInitialize = function(callback) {
3315 if(typeof netdataNoDygraphs === 'undefined' || !netdataNoDygraphs) {
3317 url: NETDATA.dygraph_js,
3322 NETDATA.registerChartLibrary('dygraph', NETDATA.dygraph_js);
3325 NETDATA.chartLibraries.dygraph.enabled = false;
3326 NETDATA.error(100, NETDATA.dygraph_js);
3328 .always(function() {
3329 if(NETDATA.chartLibraries.dygraph.enabled === true && NETDATA.options.current.smooth_plot === true)
3330 NETDATA.dygraphSmoothInitialize(callback);
3331 else if(typeof callback === "function")
3336 NETDATA.chartLibraries.dygraph.enabled = false;
3337 if(typeof callback === "function")
3342 NETDATA.dygraphChartUpdate = function(state, data) {
3343 var dygraph = state.dygraph_instance;
3345 if(typeof dygraph === 'undefined')
3346 return NETDATA.dygraphChartCreate(state, data);
3348 // when the chart is not visible, and hidden
3349 // if there is a window resize, dygraph detects
3350 // its element size as 0x0.
3351 // this will make it re-appear properly
3353 if(state.tm.last_unhidden > state.dygraph_last_rendered)
3357 file: data.result.data,
3358 colors: state.chartColors(),
3359 labels: data.result.labels,
3360 labelsDivWidth: state.chartWidth() - 70,
3361 visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names)
3364 if(state.current.name !== 'auto') {
3365 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3366 state.log('dygraphChartUpdate() loose update');
3369 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3370 state.log('dygraphChartUpdate() strict update');
3372 options.dateWindow = null;
3373 options.valueRange = null;
3376 if(state.dygraph_smooth_eligible === true) {
3377 if((NETDATA.options.current.smooth_plot === true && state.dygraph_options.plotter !== smoothPlotter)
3378 || (NETDATA.options.current.smooth_plot === false && state.dygraph_options.plotter === smoothPlotter)) {
3379 NETDATA.dygraphChartCreate(state, data);
3384 dygraph.updateOptions(options);
3385 state.dygraph_last_rendered = new Date().getTime();
3389 NETDATA.dygraphChartCreate = function(state, data) {
3390 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3391 state.log('dygraphChartCreate()');
3393 var self = $(state.element);
3395 var chart_type = state.chart.chart_type;
3396 if(chart_type === 'stacked' && data.dimensions === 1) chart_type = 'area';
3397 chart_type = self.data('dygraph-type') || chart_type;
3399 var smooth = (chart_type === 'line' && !NETDATA.chartLibraries.dygraph.isSparkline(state))?true:false;
3400 smooth = self.data('dygraph-smooth') || smooth;
3402 if(NETDATA.dygraph.smooth === false)
3405 var strokeWidth = (chart_type === 'stacked')?0.1:((smooth)?1.5:0.7)
3406 var highlightCircleSize = (NETDATA.chartLibraries.dygraph.isSparkline(state))?3:4;
3408 state.dygraph_options = {
3409 colors: self.data('dygraph-colors') || state.chartColors(),
3411 // leave a few pixels empty on the right of the chart
3412 rightGap: self.data('dygraph-rightgap') || 5,
3413 showRangeSelector: self.data('dygraph-showrangeselector') || false,
3414 showRoller: self.data('dygraph-showroller') || false,
3416 title: self.data('dygraph-title') || state.title,
3417 titleHeight: self.data('dygraph-titleheight') || 19,
3419 legend: self.data('dygraph-legend') || 'always', // 'onmouseover',
3420 labels: data.result.labels,
3421 labelsDiv: self.data('dygraph-labelsdiv') || state.element_legend_childs.hidden,
3422 labelsDivStyles: self.data('dygraph-labelsdivstyles') || { 'fontSize':'1px' },
3423 labelsDivWidth: self.data('dygraph-labelsdivwidth') || state.chartWidth() - 70,
3424 labelsSeparateLines: self.data('dygraph-labelsseparatelines') || true,
3425 labelsShowZeroValues: self.data('dygraph-labelsshowzerovalues') || true,
3428 showLabelsOnHighlight: self.data('dygraph-showlabelsonhighlight') || true,
3429 hideOverlayOnMouseOut: self.data('dygraph-hideoverlayonmouseout') || true,
3431 ylabel: state.units,
3432 yLabelWidth: self.data('dygraph-ylabelwidth') || 12,
3434 // the function to plot the chart
3437 // The width of the lines connecting data points. This can be used to increase the contrast or some graphs.
3438 strokeWidth: self.data('dygraph-strokewidth') || strokeWidth,
3439 strokePattern: self.data('dygraph-strokepattern') || undefined,
3441 // The size of the dot to draw on each point in pixels (see drawPoints). A dot is always drawn when a point is "isolated",
3442 // i.e. there is a missing point on either side of it. This also controls the size of those dots.
3443 drawPoints: self.data('dygraph-drawpoints') || false,
3445 // Draw points at the edges of gaps in the data. This improves visibility of small data segments or other data irregularities.
3446 drawGapEdgePoints: self.data('dygraph-drawgapedgepoints') || true,
3448 connectSeparatedPoints: self.data('dygraph-connectseparatedpoints') || false,
3449 pointSize: self.data('dygraph-pointsize') || 1,
3451 // enabling this makes the chart with little square lines
3452 stepPlot: self.data('dygraph-stepplot') || false,
3454 // Draw a border around graph lines to make crossing lines more easily distinguishable. Useful for graphs with many lines.
3455 strokeBorderColor: self.data('dygraph-strokebordercolor') || 'white',
3456 strokeBorderWidth: self.data('dygraph-strokeborderwidth') || (chart_type === 'stacked')?0.0:0.0,
3458 fillGraph: self.data('dygraph-fillgraph') || (chart_type === 'area' || chart_type === 'stacked')?true:false,
3459 fillAlpha: self.data('dygraph-fillalpha') || (chart_type === 'stacked')?NETDATA.options.current.color_fill_opacity_stacked:NETDATA.options.current.color_fill_opacity_area,
3460 stackedGraph: self.data('dygraph-stackedgraph') || (chart_type === 'stacked')?true:false,
3461 stackedGraphNaNFill: self.data('dygraph-stackedgraphnanfill') || 'none',
3463 drawAxis: self.data('dygraph-drawaxis') || true,
3464 axisLabelFontSize: self.data('dygraph-axislabelfontsize') || 10,
3465 axisLineColor: self.data('dygraph-axislinecolor') || '#CCC',
3466 axisLineWidth: self.data('dygraph-axislinewidth') || 0.3,
3468 drawGrid: self.data('dygraph-drawgrid') || true,
3469 drawXGrid: self.data('dygraph-drawxgrid') || undefined,
3470 drawYGrid: self.data('dygraph-drawygrid') || undefined,
3471 gridLinePattern: self.data('dygraph-gridlinepattern') || null,
3472 gridLineWidth: self.data('dygraph-gridlinewidth') || 0.3,
3473 gridLineColor: self.data('dygraph-gridlinecolor') || '#DDD',
3475 maxNumberWidth: self.data('dygraph-maxnumberwidth') || 8,
3476 sigFigs: self.data('dygraph-sigfigs') || null,
3477 digitsAfterDecimal: self.data('dygraph-digitsafterdecimal') || 2,
3478 valueFormatter: self.data('dygraph-valueformatter') || function(x){ return x.toFixed(2); },
3480 highlightCircleSize: self.data('dygraph-highlightcirclesize') || highlightCircleSize,
3481 highlightSeriesOpts: self.data('dygraph-highlightseriesopts') || null, // TOO SLOW: { strokeWidth: 1.5 },
3482 highlightSeriesBackgroundAlpha: self.data('dygraph-highlightseriesbackgroundalpha') || null, // TOO SLOW: (chart_type === 'stacked')?0.7:0.5,
3484 pointClickCallback: self.data('dygraph-pointclickcallback') || undefined,
3485 visibility: state.dimensions_visibility.selected2BooleanArray(state.data.dimension_names),
3489 ticker: Dygraph.dateTicker,
3490 axisLabelFormatter: function (d, gran) {
3491 return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds());
3493 valueFormatter: function (ms) {
3494 var d = new Date(ms);
3495 return d.toLocaleDateString() + ' ' + d.toLocaleTimeString();
3496 // return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds());
3501 valueFormatter: function (x) {
3502 // we format legends with the state object
3503 // no need to do anything here
3504 // return (Math.round(x*100) / 100).toLocaleString();
3505 // return state.legendFormatValue(x);
3510 legendFormatter: function(data) {
3511 var elements = state.element_legend_childs;
3513 // if the hidden div is not there
3514 // we are not managing the legend
3515 if(elements.hidden === null) return;
3517 if (typeof data.x !== 'undefined') {
3518 state.legendSetDate(data.x);
3519 var i = data.series.length;
3521 var series = data.series[i];
3522 if(!series.isVisible) continue;
3523 state.legendSetLabelValue(series.label, series.y);
3529 drawCallback: function(dygraph, is_initial) {
3530 if(state.current.name !== 'auto') {
3531 if(NETDATA.options.debug.dygraph === true)
3532 state.log('dygraphDrawCallback()');
3534 var x_range = dygraph.xAxisRange();
3535 var after = Math.round(x_range[0]);
3536 var before = Math.round(x_range[1]);
3538 if(before <= state.netdata_last && after >= state.netdata_first)
3539 state.updateChartPanOrZoom(after, before);
3542 zoomCallback: function(minDate, maxDate, yRanges) {
3543 if(NETDATA.options.debug.dygraph === true)
3544 state.log('dygraphZoomCallback()');
3546 state.globalSelectionSyncStop();
3547 state.globalSelectionSyncDelay();
3549 if(state.updateChartPanOrZoom(minDate, maxDate) === false) {
3550 // we should not zoom that much
3551 state.dygraph_instance.updateOptions({
3557 highlightCallback: function(event, x, points, row, seriesName) {
3558 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3559 state.log('dygraphHighlightCallback()');
3563 // there is a bug in dygraph when the chart is zoomed enough
3564 // the time it thinks is selected is wrong
3565 // here we calculate the time t based on the row number selected
3567 var t = state.data_after + row * state.data_update_every;
3568 // console.log('row = ' + row + ', x = ' + x + ', t = ' + t + ' ' + ((t === x)?'SAME':(Math.abs(x-t)<=state.data_update_every)?'SIMILAR':'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);
3570 state.globalSelectionSync(x);
3572 // fix legend zIndex using the internal structures of dygraph legend module
3573 // this works, but it is a hack!
3574 // state.dygraph_instance.plugins_[0].plugin.legend_div_.style.zIndex = 10000;
3576 unhighlightCallback: function(event) {
3577 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3578 state.log('dygraphUnhighlightCallback()');
3580 state.unpauseChart();
3581 state.globalSelectionSyncStop();
3583 interactionModel : {
3584 mousedown: function(event, dygraph, context) {
3585 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3586 state.log('interactionModel.mousedown()');
3588 state.globalSelectionSyncStop();
3590 if(NETDATA.options.debug.dygraph === true)
3591 state.log('dygraphMouseDown()');
3593 // Right-click should not initiate a zoom.
3594 if(event.button && event.button === 2) return;
3596 context.initializeMouseDown(event, dygraph, context);
3598 if(event.button && event.button === 1) {
3599 if (event.altKey || event.shiftKey) {
3600 state.setMode('pan');
3601 state.globalSelectionSyncDelay();
3602 Dygraph.startPan(event, dygraph, context);
3605 state.setMode('zoom');
3606 state.globalSelectionSyncDelay();
3607 Dygraph.startZoom(event, dygraph, context);
3611 if (event.altKey || event.shiftKey) {
3612 state.setMode('zoom');
3613 state.globalSelectionSyncDelay();
3614 Dygraph.startZoom(event, dygraph, context);
3617 state.setMode('pan');
3618 state.globalSelectionSyncDelay();
3619 Dygraph.startPan(event, dygraph, context);
3623 mousemove: function(event, dygraph, context) {
3624 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3625 state.log('interactionModel.mousemove()');
3627 if(context.isPanning) {
3628 state.globalSelectionSyncStop();
3629 state.globalSelectionSyncDelay();
3630 state.setMode('pan');
3631 Dygraph.movePan(event, dygraph, context);
3633 else if(context.isZooming) {
3634 state.globalSelectionSyncStop();
3635 state.globalSelectionSyncDelay();
3636 state.setMode('zoom');
3637 Dygraph.moveZoom(event, dygraph, context);
3640 mouseup: function(event, dygraph, context) {
3641 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3642 state.log('interactionModel.mouseup()');
3644 if (context.isPanning) {
3645 state.globalSelectionSyncDelay();
3646 Dygraph.endPan(event, dygraph, context);
3648 else if (context.isZooming) {
3649 state.globalSelectionSyncDelay();
3650 Dygraph.endZoom(event, dygraph, context);
3653 click: function(event, dygraph, context) {
3654 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3655 state.log('interactionModel.click()');
3657 event.preventDefault();
3659 dblclick: function(event, dygraph, context) {
3660 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3661 state.log('interactionModel.dblclick()');
3662 NETDATA.resetAllCharts(state);
3664 mousewheel: function(event, dygraph, context) {
3665 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3666 state.log('interactionModel.mousewheel()');
3668 // Take the offset of a mouse event on the dygraph canvas and
3669 // convert it to a pair of percentages from the bottom left.
3670 // (Not top left, bottom is where the lower value is.)
3671 function offsetToPercentage(g, offsetX, offsetY) {
3672 // This is calculating the pixel offset of the leftmost date.
3673 var xOffset = g.toDomCoords(g.xAxisRange()[0], null)[0];
3674 var yar0 = g.yAxisRange(0);
3676 // This is calculating the pixel of the higest value. (Top pixel)
3677 var yOffset = g.toDomCoords(null, yar0[1])[1];
3679 // x y w and h are relative to the corner of the drawing area,
3680 // so that the upper corner of the drawing area is (0, 0).
3681 var x = offsetX - xOffset;
3682 var y = offsetY - yOffset;
3684 // This is computing the rightmost pixel, effectively defining the
3686 var w = g.toDomCoords(g.xAxisRange()[1], null)[0] - xOffset;
3688 // This is computing the lowest pixel, effectively defining the height.
3689 var h = g.toDomCoords(null, yar0[0])[1] - yOffset;
3691 // Percentage from the left.
3692 var xPct = w === 0 ? 0 : (x / w);
3693 // Percentage from the top.
3694 var yPct = h === 0 ? 0 : (y / h);
3696 // The (1-) part below changes it from "% distance down from the top"
3697 // to "% distance up from the bottom".
3698 return [xPct, (1-yPct)];
3701 // Adjusts [x, y] toward each other by zoomInPercentage%
3702 // Split it so the left/bottom axis gets xBias/yBias of that change and
3703 // tight/top gets (1-xBias)/(1-yBias) of that change.
3705 // If a bias is missing it splits it down the middle.
3706 function zoomRange(g, zoomInPercentage, xBias, yBias) {
3707 xBias = xBias || 0.5;
3708 yBias = yBias || 0.5;
3710 function adjustAxis(axis, zoomInPercentage, bias) {
3711 var delta = axis[1] - axis[0];
3712 var increment = delta * zoomInPercentage;
3713 var foo = [increment * bias, increment * (1-bias)];
3715 return [ axis[0] + foo[0], axis[1] - foo[1] ];
3718 var yAxes = g.yAxisRanges();
3720 for (var i = 0; i < yAxes.length; i++) {
3721 newYAxes[i] = adjustAxis(yAxes[i], zoomInPercentage, yBias);
3724 return adjustAxis(g.xAxisRange(), zoomInPercentage, xBias);
3727 if(event.altKey || event.shiftKey) {
3728 state.globalSelectionSyncStop();
3729 state.globalSelectionSyncDelay();
3731 // http://dygraphs.com/gallery/interaction-api.js
3732 var normal = (event.detail) ? event.detail * -1 : event.wheelDelta / 40;
3733 var percentage = normal / 50;
3735 if (!(event.offsetX && event.offsetY)){
3736 event.offsetX = event.layerX - event.target.offsetLeft;
3737 event.offsetY = event.layerY - event.target.offsetTop;
3740 var percentages = offsetToPercentage(dygraph, event.offsetX, event.offsetY);
3741 var xPct = percentages[0];
3742 var yPct = percentages[1];
3744 var new_x_range = zoomRange(dygraph, percentage, xPct, yPct);
3746 var after = new_x_range[0];
3747 var before = new_x_range[1];
3749 var first = state.netdata_first + state.data_update_every;
3750 var last = state.netdata_last + state.data_update_every;
3753 after -= (before - last);
3760 state.setMode('zoom');
3761 if(state.updateChartPanOrZoom(after, before) === true)
3762 dygraph.updateOptions({ dateWindow: [ after, before ] });
3764 event.preventDefault();
3767 touchstart: function(event, dygraph, context) {
3768 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3769 state.log('interactionModel.touchstart()');
3771 state.setMode('zoom');
3774 Dygraph.defaultInteractionModel.touchstart(event, dygraph, context);
3776 // we overwrite the touch directions at the end, to overwrite
3777 // the internal default of dygraphs
3778 context.touchDirections = { x: true, y: false };
3780 state.dygraph_last_touch_start = new Date().getTime();
3781 state.dygraph_last_touch_move = 0;
3783 if(typeof event.touches[0].pageX === 'number')
3784 state.dygraph_last_touch_page_x = event.touches[0].pageX;
3786 state.dygraph_last_touch_page_x = 0;
3788 touchmove: function(event, dygraph, context) {
3789 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3790 state.log('interactionModel.touchmove()');
3792 Dygraph.defaultInteractionModel.touchmove(event, dygraph, context);
3794 state.dygraph_last_touch_move = new Date().getTime();
3796 touchend: function(event, dygraph, context) {
3797 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3798 state.log('interactionModel.touchend()');
3800 Dygraph.defaultInteractionModel.touchend(event, dygraph, context);
3802 // if it didn't move, it is a selection
3803 if(state.dygraph_last_touch_move === 0 && state.dygraph_last_touch_page_x !== 0) {
3804 // internal api of dygraphs
3805 var pct = (state.dygraph_last_touch_page_x - (dygraph.plotter_.area.x + state.element.getBoundingClientRect().left)) / dygraph.plotter_.area.w;
3806 var t = Math.round(state.data_after + (state.data_before - state.data_after) * pct);
3807 if(NETDATA.dygraphSetSelection(state, t) === true)
3808 state.globalSelectionSync(t);
3811 // if it was double tap within double click time, reset the charts
3812 var now = new Date().getTime();
3813 if(typeof state.dygraph_last_touch_end !== 'undefined') {
3814 if(state.dygraph_last_touch_move === 0) {
3815 var dt = now - state.dygraph_last_touch_end;
3816 if(dt <= NETDATA.options.current.double_click_speed)
3817 NETDATA.resetAllCharts(state);
3821 // remember the timestamp of the last touch end
3822 state.dygraph_last_touch_end = now;
3827 if(NETDATA.chartLibraries.dygraph.isSparkline(state)) {
3828 state.dygraph_options.drawGrid = false;
3829 state.dygraph_options.drawAxis = false;
3830 state.dygraph_options.title = undefined;
3831 state.dygraph_options.units = undefined;
3832 state.dygraph_options.ylabel = undefined;
3833 state.dygraph_options.yLabelWidth = 0;
3834 state.dygraph_options.labelsDivWidth = 120;
3835 state.dygraph_options.labelsDivStyles.width = '120px';
3836 state.dygraph_options.labelsSeparateLines = true;
3837 state.dygraph_options.rightGap = 0;
3840 if(smooth === true) {
3841 state.dygraph_smooth_eligible = true;
3843 if(NETDATA.options.current.smooth_plot === true)
3844 state.dygraph_options.plotter = smoothPlotter;
3846 else state.dygraph_smooth_eligible = false;
3848 state.dygraph_instance = new Dygraph(state.element_chart,
3849 data.result.data, state.dygraph_options);
3851 state.dygraph_last_rendered = new Date().getTime();
3855 // ----------------------------------------------------------------------------------------------------------------
3858 NETDATA.morrisInitialize = function(callback) {
3859 if(typeof netdataNoMorris === 'undefined' || !netdataNoMorris) {
3861 // morris requires raphael
3862 if(!NETDATA.chartLibraries.raphael.initialized) {
3863 if(NETDATA.chartLibraries.raphael.enabled) {
3864 NETDATA.raphaelInitialize(function() {
3865 NETDATA.morrisInitialize(callback);
3869 NETDATA.chartLibraries.morris.enabled = false;
3870 if(typeof callback === "function")
3875 NETDATA._loadCSS(NETDATA.morris_css);
3878 url: NETDATA.morris_js,
3883 NETDATA.registerChartLibrary('morris', NETDATA.morris_js);
3886 NETDATA.chartLibraries.morris.enabled = false;
3887 NETDATA.error(100, NETDATA.morris_js);
3889 .always(function() {
3890 if(typeof callback === "function")
3896 NETDATA.chartLibraries.morris.enabled = false;
3897 if(typeof callback === "function")
3902 NETDATA.morrisChartUpdate = function(state, data) {
3903 state.morris_instance.setData(data.result.data);
3907 NETDATA.morrisChartCreate = function(state, data) {
3909 state.morris_options = {
3910 element: state.element_chart.id,
3911 data: data.result.data,
3913 ykeys: data.dimension_names,
3914 labels: data.dimension_names,
3920 continuousLine: false,
3921 behaveLikeLine: false
3924 if(state.chart.chart_type === 'line')
3925 state.morris_instance = new Morris.Line(state.morris_options);
3927 else if(state.chart.chart_type === 'area') {
3928 state.morris_options.behaveLikeLine = true;
3929 state.morris_instance = new Morris.Area(state.morris_options);
3932 state.morris_instance = new Morris.Area(state.morris_options);
3937 // ----------------------------------------------------------------------------------------------------------------
3940 NETDATA.raphaelInitialize = function(callback) {
3941 if(typeof netdataStopRaphael === 'undefined' || !netdataStopRaphael) {
3943 url: NETDATA.raphael_js,
3948 NETDATA.registerChartLibrary('raphael', NETDATA.raphael_js);
3951 NETDATA.chartLibraries.raphael.enabled = false;
3952 NETDATA.error(100, NETDATA.raphael_js);
3954 .always(function() {
3955 if(typeof callback === "function")
3960 NETDATA.chartLibraries.raphael.enabled = false;
3961 if(typeof callback === "function")
3966 NETDATA.raphaelChartUpdate = function(state, data) {
3967 $(state.element_chart).raphael(data.result, {
3968 width: state.chartWidth(),
3969 height: state.chartHeight()
3975 NETDATA.raphaelChartCreate = function(state, data) {
3976 $(state.element_chart).raphael(data.result, {
3977 width: state.chartWidth(),
3978 height: state.chartHeight()
3984 // ----------------------------------------------------------------------------------------------------------------
3987 NETDATA.c3Initialize = function(callback) {
3988 if(typeof netdataNoC3 === 'undefined' || !netdataNoC3) {
3991 if(!NETDATA.chartLibraries.d3.initialized) {
3992 if(NETDATA.chartLibraries.d3.enabled) {
3993 NETDATA.d3Initialize(function() {
3994 NETDATA.c3Initialize(callback);
3998 NETDATA.chartLibraries.c3.enabled = false;
3999 if(typeof callback === "function")
4004 NETDATA._loadCSS(NETDATA.c3_css);
4012 NETDATA.registerChartLibrary('c3', NETDATA.c3_js);
4015 NETDATA.chartLibraries.c3.enabled = false;
4016 NETDATA.error(100, NETDATA.c3_js);
4018 .always(function() {
4019 if(typeof callback === "function")
4025 NETDATA.chartLibraries.c3.enabled = false;
4026 if(typeof callback === "function")
4031 NETDATA.c3ChartUpdate = function(state, data) {
4032 state.c3_instance.destroy();
4033 return NETDATA.c3ChartCreate(state, data);
4035 //state.c3_instance.load({
4036 // rows: data.result,
4043 NETDATA.c3ChartCreate = function(state, data) {
4045 state.element_chart.id = 'c3-' + state.uuid;
4046 // console.log('id = ' + state.element_chart.id);
4048 state.c3_instance = c3.generate({
4049 bindto: '#' + state.element_chart.id,
4051 width: state.chartWidth(),
4052 height: state.chartHeight()
4055 pattern: state.chartColors()
4060 type: (state.chart.chart_type === 'line')?'spline':'area-spline'
4066 format: function(x) {
4067 return NETDATA.zeropad(x.getHours()) + ":" + NETDATA.zeropad(x.getMinutes()) + ":" + NETDATA.zeropad(x.getSeconds());
4094 // console.log(state.c3_instance);
4099 // ----------------------------------------------------------------------------------------------------------------
4102 NETDATA.d3Initialize = function(callback) {
4103 if(typeof netdataStopD3 === 'undefined' || !netdataStopD3) {
4110 NETDATA.registerChartLibrary('d3', NETDATA.d3_js);
4113 NETDATA.chartLibraries.d3.enabled = false;
4114 NETDATA.error(100, NETDATA.d3_js);
4116 .always(function() {
4117 if(typeof callback === "function")
4122 NETDATA.chartLibraries.d3.enabled = false;
4123 if(typeof callback === "function")
4128 NETDATA.d3ChartUpdate = function(state, data) {
4132 NETDATA.d3ChartCreate = function(state, data) {
4136 // ----------------------------------------------------------------------------------------------------------------
4139 NETDATA.googleInitialize = function(callback) {
4140 if(typeof netdataNoGoogleCharts === 'undefined' || !netdataNoGoogleCharts) {
4142 url: NETDATA.google_js,
4147 NETDATA.registerChartLibrary('google', NETDATA.google_js);
4148 google.load('visualization', '1.1', {
4149 'packages': ['corechart', 'controls'],
4150 'callback': callback
4154 NETDATA.chartLibraries.google.enabled = false;
4155 NETDATA.error(100, NETDATA.google_js);
4156 if(typeof callback === "function")
4161 NETDATA.chartLibraries.google.enabled = false;
4162 if(typeof callback === "function")
4167 NETDATA.googleChartUpdate = function(state, data) {
4168 var datatable = new google.visualization.DataTable(data.result);
4169 state.google_instance.draw(datatable, state.google_options);
4173 NETDATA.googleChartCreate = function(state, data) {
4174 var datatable = new google.visualization.DataTable(data.result);
4176 state.google_options = {
4177 colors: state.chartColors(),
4179 // do not set width, height - the chart resizes itself
4180 //width: state.chartWidth(),
4181 //height: state.chartHeight(),
4186 // title: "Time of Day",
4187 // format:'HH:mm:ss',
4188 viewWindowMode: 'maximized',
4200 viewWindowMode: 'pretty',
4215 focusTarget: 'category',
4222 titlePosition: 'out',
4233 curveType: 'function',
4238 switch(state.chart.chart_type) {
4240 state.google_options.vAxis.viewWindowMode = 'maximized';
4241 state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_area;
4242 state.google_instance = new google.visualization.AreaChart(state.element_chart);
4246 state.google_options.isStacked = true;
4247 state.google_options.areaOpacity = NETDATA.options.current.color_fill_opacity_stacked;
4248 state.google_options.vAxis.viewWindowMode = 'maximized';
4249 state.google_options.vAxis.minValue = null;
4250 state.google_options.vAxis.maxValue = null;
4251 state.google_instance = new google.visualization.AreaChart(state.element_chart);
4256 state.google_options.lineWidth = 2;
4257 state.google_instance = new google.visualization.LineChart(state.element_chart);
4261 state.google_instance.draw(datatable, state.google_options);
4265 // ----------------------------------------------------------------------------------------------------------------
4267 NETDATA.percentFromValueMax = function(value, max) {
4268 if(value === null) value = 0;
4269 if(max < value) max = value;
4273 pcent = Math.round(value * 100 / max);
4274 if(pcent === 0 && value > 0) pcent = 1;
4280 // ----------------------------------------------------------------------------------------------------------------
4283 NETDATA.easypiechartInitialize = function(callback) {
4284 if(typeof netdataNoEasyPieChart === 'undefined' || !netdataNoEasyPieChart) {
4286 url: NETDATA.easypiechart_js,
4291 NETDATA.registerChartLibrary('easypiechart', NETDATA.easypiechart_js);
4294 NETDATA.error(100, NETDATA.easypiechart_js);
4296 .always(function() {
4297 if(typeof callback === "function")
4302 NETDATA.chartLibraries.easypiechart.enabled = false;
4303 if(typeof callback === "function")
4308 NETDATA.easypiechartClearSelection = function(state) {
4309 if(typeof state.easyPieChartEvent !== 'undefined') {
4310 if(state.easyPieChartEvent.timer !== null)
4311 clearTimeout(state.easyPieChartEvent.timer);
4313 state.easyPieChartEvent.timer = null;
4316 if(state.isAutoRefreshed() === true && state.data !== null) {
4317 NETDATA.easypiechartChartUpdate(state, state.data);
4320 state.easyPieChartLabel.innerHTML = state.legendFormatValue(null);
4321 state.easyPieChart_instance.update(0);
4323 state.easyPieChart_instance.enableAnimation();
4328 NETDATA.easypiechartSetSelection = function(state, t) {
4329 if(state.timeIsVisible(t) !== true)
4330 return NETDATA.easypiechartClearSelection(state);
4332 var slot = state.calculateRowForTime(t);
4333 if(slot < 0 || slot >= state.data.result.length)
4334 return NETDATA.easypiechartClearSelection(state);
4336 if(typeof state.easyPieChartEvent === 'undefined') {
4337 state.easyPieChartEvent = {
4344 var value = state.data.result[state.data.result.length - 1 - slot];
4345 var max = (state.easyPieChartMax === null)?state.data.max:state.easyPieChartMax;
4346 var pcent = NETDATA.percentFromValueMax(value, max);
4348 state.easyPieChartEvent.value = value;
4349 state.easyPieChartEvent.pcent = pcent;
4350 state.easyPieChartLabel.innerHTML = state.legendFormatValue(value);
4352 if(state.easyPieChartEvent.timer === null) {
4353 state.easyPieChart_instance.disableAnimation();
4355 state.easyPieChartEvent.timer = setTimeout(function() {
4356 state.easyPieChartEvent.timer = null;
4357 state.easyPieChart_instance.update(state.easyPieChartEvent.pcent);
4358 }, NETDATA.options.current.charts_selection_animation_delay);
4364 NETDATA.easypiechartChartUpdate = function(state, data) {
4365 var value, max, pcent;
4367 if(NETDATA.globalPanAndZoom.isActive() === true || state.isAutoRefreshed() === false) {
4373 value = data.result[0];
4374 max = (state.easyPieChartMax === null)?data.max:state.easyPieChartMax;
4375 pcent = NETDATA.percentFromValueMax(value, max);
4378 state.easyPieChartLabel.innerHTML = state.legendFormatValue(value);
4379 state.easyPieChart_instance.update(pcent);
4383 NETDATA.easypiechartChartCreate = function(state, data) {
4384 var self = $(state.element);
4385 var chart = $(state.element_chart);
4387 var value = data.result[0];
4388 var max = self.data('easypiechart-max-value') || null;
4389 var adjust = self.data('easypiechart-adjust') || null;
4393 state.easyPieChartMax = null;
4396 state.easyPieChartMax = max;
4398 var pcent = NETDATA.percentFromValueMax(value, max);
4400 chart.data('data-percent', pcent);
4404 case 'width': size = state.chartHeight(); break;
4405 case 'min': size = Math.min(state.chartWidth(), state.chartHeight()); break;
4406 case 'max': size = Math.max(state.chartWidth(), state.chartHeight()); break;
4408 default: size = state.chartWidth(); break;
4410 state.element.style.width = size + 'px';
4411 state.element.style.height = size + 'px';
4413 var stroke = Math.floor(size / 22);
4414 if(stroke < 3) stroke = 2;
4416 var valuefontsize = Math.floor((size * 2 / 3) / 5);
4417 var valuetop = Math.round((size - valuefontsize - (size / 40)) / 2);
4418 state.easyPieChartLabel = document.createElement('span');
4419 state.easyPieChartLabel.className = 'easyPieChartLabel';
4420 state.easyPieChartLabel.innerHTML = state.legendFormatValue(value);
4421 state.easyPieChartLabel.style.fontSize = valuefontsize + 'px';
4422 state.easyPieChartLabel.style.top = valuetop.toString() + 'px';
4423 state.element_chart.appendChild(state.easyPieChartLabel);
4425 var titlefontsize = Math.round(valuefontsize * 1.6 / 3);
4426 var titletop = Math.round(valuetop - (titlefontsize * 2) - (size / 40));
4427 state.easyPieChartTitle = document.createElement('span');
4428 state.easyPieChartTitle.className = 'easyPieChartTitle';
4429 state.easyPieChartTitle.innerHTML = state.title;
4430 state.easyPieChartTitle.style.fontSize = titlefontsize + 'px';
4431 state.easyPieChartTitle.style.lineHeight = titlefontsize + 'px';
4432 state.easyPieChartTitle.style.top = titletop.toString() + 'px';
4433 state.element_chart.appendChild(state.easyPieChartTitle);
4435 var unitfontsize = Math.round(titlefontsize * 0.9);
4436 var unittop = Math.round(valuetop + (valuefontsize + unitfontsize) + (size / 40));
4437 state.easyPieChartUnits = document.createElement('span');
4438 state.easyPieChartUnits.className = 'easyPieChartUnits';
4439 state.easyPieChartUnits.innerHTML = state.units;
4440 state.easyPieChartUnits.style.fontSize = unitfontsize + 'px';
4441 state.easyPieChartUnits.style.top = unittop.toString() + 'px';
4442 state.element_chart.appendChild(state.easyPieChartUnits);
4444 chart.easyPieChart({
4445 barColor: self.data('easypiechart-barcolor') || state.chartColors()[0], //'#ef1e25',
4446 trackColor: self.data('easypiechart-trackcolor') || '#f0f0f0',
4447 scaleColor: self.data('easypiechart-scalecolor') || '#dfe0e0',
4448 scaleLength: self.data('easypiechart-scalelength') || 5,
4449 lineCap: self.data('easypiechart-linecap') || 'round',
4450 lineWidth: self.data('easypiechart-linewidth') || stroke,
4451 trackWidth: self.data('easypiechart-trackwidth') || undefined,
4452 size: self.data('easypiechart-size') || size,
4453 rotate: self.data('easypiechart-rotate') || 0,
4454 animate: self.data('easypiechart-rotate') || {duration: 500, enabled: true},
4455 easing: self.data('easypiechart-easing') || undefined
4458 // when we just re-create the chart
4459 // do not animate the first update
4461 if(typeof state.easyPieChart_instance !== 'undefined')
4464 state.easyPieChart_instance = chart.data('easyPieChart');
4465 if(animate === false) state.easyPieChart_instance.disableAnimation();
4466 state.easyPieChart_instance.update(pcent);
4467 if(animate === false) state.easyPieChart_instance.enableAnimation();
4471 // ----------------------------------------------------------------------------------------------------------------
4474 NETDATA.gaugeInitialize = function(callback) {
4475 if(typeof netdataNoGauge === 'undefined' || !netdataNoGauge) {
4477 url: NETDATA.gauge_js,
4482 NETDATA.registerChartLibrary('gauge', NETDATA.gauge_js);
4485 NETDATA.error(100, NETDATA.gauge_js);
4487 .always(function() {
4488 if(typeof callback === "function")
4493 NETDATA.chartLibraries.gauge.enabled = false;
4494 if(typeof callback === "function")
4499 NETDATA.gaugeAnimation = function(state, status) {
4502 if(typeof status === 'boolean' && status === false)
4504 else if(typeof status === 'number')
4507 state.gauge_instance.animationSpeed = speed;
4508 state.___gaugeOld__.speed = speed;
4511 NETDATA.gaugeSet = function(state, value, min, max) {
4512 if(typeof value !== 'number') value = 0;
4513 if(typeof min !== 'number') min = 0;
4514 if(typeof max !== 'number') max = 0;
4515 if(value > max) max = value;
4516 if(value < min) min = value;
4525 // gauge.js has an issue if the needle
4526 // is smaller than min or larger than max
4527 // when we set the new values
4528 // the needle will go crazy
4530 // to prevent it, we always feed it
4531 // with a percentage, so that the needle
4532 // is always between min and max
4533 var pcent = (value - min) * 100 / (max - min);
4535 state.gauge_instance.set(pcent);
4537 state.___gaugeOld__.value = value;
4538 state.___gaugeOld__.min = min;
4539 state.___gaugeOld__.max = max;
4542 NETDATA.gaugeSetLabels = function(state, value, min, max) {
4543 if(state.___gaugeOld__.valueLabel !== value) {
4544 state.___gaugeOld__.valueLabel = value;
4545 state.gaugeChartLabel.innerHTML = state.legendFormatValue(value);
4547 if(state.___gaugeOld__.minLabel !== min) {
4548 state.___gaugeOld__.minLabel = min;
4549 state.gaugeChartMin.innerHTML = state.legendFormatValue(min);
4551 if(state.___gaugeOld__.maxLabel !== max) {
4552 state.___gaugeOld__.maxLabel = max;
4553 state.gaugeChartMax.innerHTML = state.legendFormatValue(max);
4557 NETDATA.gaugeClearSelection = function(state) {
4558 if(typeof state.gaugeEvent !== 'undefined') {
4559 if(state.gaugeEvent.timer !== null)
4560 clearTimeout(state.gaugeEvent.timer);
4562 state.gaugeEvent.timer = null;
4565 if(state.isAutoRefreshed() === true && state.data !== null) {
4566 NETDATA.gaugeChartUpdate(state, state.data);
4569 NETDATA.gaugeAnimation(state, false);
4570 NETDATA.gaugeSet(state, null, null, null);
4571 NETDATA.gaugeSetLabels(state, null, null, null);
4574 NETDATA.gaugeAnimation(state, true);
4578 NETDATA.gaugeSetSelection = function(state, t) {
4579 if(state.timeIsVisible(t) !== true)
4580 return NETDATA.gaugeClearSelection(state);
4582 var slot = state.calculateRowForTime(t);
4583 if(slot < 0 || slot >= state.data.result.length)
4584 return NETDATA.gaugeClearSelection(state);
4586 if(typeof state.gaugeEvent === 'undefined') {
4587 state.gaugeEvent = {
4595 var value = state.data.result[state.data.result.length - 1 - slot];
4596 var max = (state.gaugeMax === null)?state.data.max:state.gaugeMax;
4599 state.gaugeEvent.value = value;
4600 state.gaugeEvent.max = max;
4601 state.gaugeEvent.min = min;
4602 NETDATA.gaugeSetLabels(state, value, min, max);
4604 if(state.gaugeEvent.timer === null) {
4605 NETDATA.gaugeAnimation(state, false);
4607 state.gaugeEvent.timer = setTimeout(function() {
4608 state.gaugeEvent.timer = null;
4609 NETDATA.gaugeSet(state, state.gaugeEvent.value, state.gaugeEvent.min, state.gaugeEvent.max);
4610 }, NETDATA.options.current.charts_selection_animation_delay);
4616 NETDATA.gaugeChartUpdate = function(state, data) {
4617 var value, min, max;
4619 if(NETDATA.globalPanAndZoom.isActive() === true || state.isAutoRefreshed() === false) {
4623 NETDATA.gaugeSetLabels(state, null, null, null);
4626 value = data.result[0];
4628 max = (state.gaugeMax === null)?data.max:state.gaugeMax;
4629 if(value > max) max = value;
4630 NETDATA.gaugeSetLabels(state, value, min, max);
4633 NETDATA.gaugeSet(state, value, min, max);
4637 NETDATA.gaugeChartCreate = function(state, data) {
4638 var self = $(state.element);
4639 var chart = $(state.element_chart);
4641 var value = data.result[0];
4642 var max = self.data('gauge-max-value') || null;
4643 var adjust = self.data('gauge-adjust') || null;
4644 var pointerColor = self.data('gauge-pointer-color') || '#C0C0C0';
4645 var strokeColor = self.data('gauge-stroke-color') || '#F0F0F0';
4646 var startColor = self.data('gauge-start-color') || state.chartColors()[0];
4647 var stopColor = self.data('gauge-stop-color') || void 0;
4648 var generateGradient = self.data('gauge-generate-gradient') || false;
4652 state.gaugeMax = null;
4655 state.gaugeMax = max;
4657 var width = state.chartWidth(), height = state.chartHeight(); //, ratio = 1.5;
4659 // case 'width': width = height * ratio; break;
4661 // default: height = width / ratio; break;
4663 //state.element.style.width = width.toString() + 'px';
4664 //state.element.style.height = height.toString() + 'px';
4669 lines: 12, // The number of lines to draw
4670 angle: 0.15, // The length of each line
4671 lineWidth: 0.44, // 0.44 The line thickness
4673 length: 0.8, // 0.9 The radius of the inner circle
4674 strokeWidth: 0.035, // The rotation offset
4675 color: pointerColor // Fill color
4677 colorStart: startColor, // Colors
4678 colorStop: stopColor, // just experiment with them
4679 strokeColor: strokeColor, // to see which ones work best for you
4681 generateGradient: generateGradient,
4684 [0.0, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 0))],
4685 [0.1, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 1))],
4686 [0.2, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 2))],
4687 [0.3, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 3))],
4688 [0.4, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 4))],
4689 [0.5, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 5))],
4690 [0.6, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 6))],
4691 [0.7, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 7))],
4692 [0.8, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 8))],
4693 [0.9, NETDATA.colorLuminance(state.chartColors()[0], (lum_d * 10) - (lum_d * 9))],
4694 [1.0, state.chartColors()[0]]]
4697 state.gauge_canvas = document.createElement('canvas');
4698 state.gauge_canvas.id = 'gauge-' + state.uuid + '-canvas';
4699 state.gauge_canvas.className = 'gaugeChart';
4700 state.gauge_canvas.width = width;
4701 state.gauge_canvas.height = height;
4702 state.element_chart.appendChild(state.gauge_canvas);
4704 var valuefontsize = Math.floor(height / 6);
4705 var valuetop = Math.round((height - valuefontsize - (height / 6)) / 2);
4706 state.gaugeChartLabel = document.createElement('span');
4707 state.gaugeChartLabel.className = 'gaugeChartLabel';
4708 state.gaugeChartLabel.style.fontSize = valuefontsize + 'px';
4709 state.gaugeChartLabel.style.top = valuetop.toString() + 'px';
4710 state.element_chart.appendChild(state.gaugeChartLabel);
4712 var titlefontsize = Math.round(valuefontsize / 2);
4714 state.gaugeChartTitle = document.createElement('span');
4715 state.gaugeChartTitle.className = 'gaugeChartTitle';
4716 state.gaugeChartTitle.innerHTML = state.title;
4717 state.gaugeChartTitle.style.fontSize = titlefontsize + 'px';
4718 state.gaugeChartTitle.style.lineHeight = titlefontsize + 'px';
4719 state.gaugeChartTitle.style.top = titletop.toString() + 'px';
4720 state.element_chart.appendChild(state.gaugeChartTitle);
4722 var unitfontsize = Math.round(titlefontsize * 0.9);
4723 state.gaugeChartUnits = document.createElement('span');
4724 state.gaugeChartUnits.className = 'gaugeChartUnits';
4725 state.gaugeChartUnits.innerHTML = state.units;
4726 state.gaugeChartUnits.style.fontSize = unitfontsize + 'px';
4727 state.element_chart.appendChild(state.gaugeChartUnits);
4729 state.gaugeChartMin = document.createElement('span');
4730 state.gaugeChartMin.className = 'gaugeChartMin';
4731 state.gaugeChartMin.style.fontSize = Math.round(valuefontsize * 0.75).toString() + 'px';
4732 state.element_chart.appendChild(state.gaugeChartMin);
4734 state.gaugeChartMax = document.createElement('span');
4735 state.gaugeChartMax.className = 'gaugeChartMax';
4736 state.gaugeChartMax.style.fontSize = Math.round(valuefontsize * 0.75).toString() + 'px';
4737 state.element_chart.appendChild(state.gaugeChartMax);
4739 // when we just re-create the chart
4740 // do not animate the first update
4742 if(typeof state.gauge_instance !== 'undefined')
4745 state.gauge_instance = new Gauge(state.gauge_canvas).setOptions(options); // create sexy gauge!
4747 state.___gaugeOld__ = {
4756 // we will always feed a percentage
4757 state.gauge_instance.minValue = 0;
4758 state.gauge_instance.maxValue = 100;
4760 NETDATA.gaugeAnimation(state, animate);
4761 NETDATA.gaugeSet(state, value, 0, max);
4762 NETDATA.gaugeSetLabels(state, value, 0, max);
4763 NETDATA.gaugeAnimation(state, true);
4767 // ----------------------------------------------------------------------------------------------------------------
4768 // Charts Libraries Registration
4770 NETDATA.chartLibraries = {
4772 initialize: NETDATA.dygraphInitialize,
4773 create: NETDATA.dygraphChartCreate,
4774 update: NETDATA.dygraphChartUpdate,
4775 resize: function(state) {
4776 if(typeof state.dygraph_instance.resize === 'function')
4777 state.dygraph_instance.resize();
4779 setSelection: NETDATA.dygraphSetSelection,
4780 clearSelection: NETDATA.dygraphClearSelection,
4783 format: function(state) { return 'json'; },
4784 options: function(state) { return 'ms|flip'; },
4785 legend: function(state) {
4786 if(this.isSparkline(state) === false)
4787 return 'right-side';
4791 autoresize: function(state) { return true; },
4792 max_updates_to_recreate: function(state) { return 5000; },
4793 track_colors: function(state) { return true; },
4794 pixels_per_point: function(state) {
4795 if(this.isSparkline(state) === false)
4801 isSparkline: function(state) {
4802 if(typeof state.dygraph_sparkline === 'undefined') {
4803 var t = $(state.element).data('dygraph-theme');
4804 if(t === 'sparkline')
4805 state.dygraph_sparkline = true;
4807 state.dygraph_sparkline = false;
4809 return state.dygraph_sparkline;
4813 initialize: NETDATA.sparklineInitialize,
4814 create: NETDATA.sparklineChartCreate,
4815 update: NETDATA.sparklineChartUpdate,
4817 setSelection: undefined, // function(state, t) { return true; },
4818 clearSelection: undefined, // function(state) { return true; },
4821 format: function(state) { return 'array'; },
4822 options: function(state) { return 'flip|abs'; },
4823 legend: function(state) { return null; },
4824 autoresize: function(state) { return false; },
4825 max_updates_to_recreate: function(state) { return 5000; },
4826 track_colors: function(state) { return false; },
4827 pixels_per_point: function(state) { return 3; }
4830 initialize: NETDATA.peityInitialize,
4831 create: NETDATA.peityChartCreate,
4832 update: NETDATA.peityChartUpdate,
4834 setSelection: undefined, // function(state, t) { return true; },
4835 clearSelection: undefined, // function(state) { return true; },
4838 format: function(state) { return 'ssvcomma'; },
4839 options: function(state) { return 'null2zero|flip|abs'; },
4840 legend: function(state) { return null; },
4841 autoresize: function(state) { return false; },
4842 max_updates_to_recreate: function(state) { return 5000; },
4843 track_colors: function(state) { return false; },
4844 pixels_per_point: function(state) { return 3; }
4847 initialize: NETDATA.morrisInitialize,
4848 create: NETDATA.morrisChartCreate,
4849 update: NETDATA.morrisChartUpdate,
4851 setSelection: undefined, // function(state, t) { return true; },
4852 clearSelection: undefined, // function(state) { return true; },
4855 format: function(state) { return 'json'; },
4856 options: function(state) { return 'objectrows|ms'; },
4857 legend: function(state) { return null; },
4858 autoresize: function(state) { return false; },
4859 max_updates_to_recreate: function(state) { return 50; },
4860 track_colors: function(state) { return false; },
4861 pixels_per_point: function(state) { return 15; }
4864 initialize: NETDATA.googleInitialize,
4865 create: NETDATA.googleChartCreate,
4866 update: NETDATA.googleChartUpdate,
4868 setSelection: undefined, //function(state, t) { return true; },
4869 clearSelection: undefined, //function(state) { return true; },
4872 format: function(state) { return 'datatable'; },
4873 options: function(state) { return ''; },
4874 legend: function(state) { return null; },
4875 autoresize: function(state) { return false; },
4876 max_updates_to_recreate: function(state) { return 300; },
4877 track_colors: function(state) { return false; },
4878 pixels_per_point: function(state) { return 4; }
4881 initialize: NETDATA.raphaelInitialize,
4882 create: NETDATA.raphaelChartCreate,
4883 update: NETDATA.raphaelChartUpdate,
4885 setSelection: undefined, // function(state, t) { return true; },
4886 clearSelection: undefined, // function(state) { return true; },
4889 format: function(state) { return 'json'; },
4890 options: function(state) { return ''; },
4891 legend: function(state) { return null; },
4892 autoresize: function(state) { return false; },
4893 max_updates_to_recreate: function(state) { return 5000; },
4894 track_colors: function(state) { return false; },
4895 pixels_per_point: function(state) { return 3; }
4898 initialize: NETDATA.c3Initialize,
4899 create: NETDATA.c3ChartCreate,
4900 update: NETDATA.c3ChartUpdate,
4902 setSelection: undefined, // function(state, t) { return true; },
4903 clearSelection: undefined, // function(state) { return true; },
4906 format: function(state) { return 'csvjsonarray'; },
4907 options: function(state) { return 'milliseconds'; },
4908 legend: function(state) { return null; },
4909 autoresize: function(state) { return false; },
4910 max_updates_to_recreate: function(state) { return 5000; },
4911 track_colors: function(state) { return false; },
4912 pixels_per_point: function(state) { return 15; }
4915 initialize: NETDATA.d3Initialize,
4916 create: NETDATA.d3ChartCreate,
4917 update: NETDATA.d3ChartUpdate,
4919 setSelection: undefined, // function(state, t) { return true; },
4920 clearSelection: undefined, // function(state) { return true; },
4923 format: function(state) { return 'json'; },
4924 options: function(state) { return ''; },
4925 legend: function(state) { return null; },
4926 autoresize: function(state) { return false; },
4927 max_updates_to_recreate: function(state) { return 5000; },
4928 track_colors: function(state) { return false; },
4929 pixels_per_point: function(state) { return 3; }
4932 initialize: NETDATA.easypiechartInitialize,
4933 create: NETDATA.easypiechartChartCreate,
4934 update: NETDATA.easypiechartChartUpdate,
4936 setSelection: NETDATA.easypiechartSetSelection,
4937 clearSelection: NETDATA.easypiechartClearSelection,
4940 format: function(state) { return 'array'; },
4941 options: function(state) { return 'absolute'; },
4942 legend: function(state) { return null; },
4943 autoresize: function(state) { return false; },
4944 max_updates_to_recreate: function(state) { return 5000; },
4945 track_colors: function(state) { return true; },
4946 pixels_per_point: function(state) { return 3; },
4950 initialize: NETDATA.gaugeInitialize,
4951 create: NETDATA.gaugeChartCreate,
4952 update: NETDATA.gaugeChartUpdate,
4954 setSelection: NETDATA.gaugeSetSelection,
4955 clearSelection: NETDATA.gaugeClearSelection,
4958 format: function(state) { return 'array'; },
4959 options: function(state) { return 'absolute'; },
4960 legend: function(state) { return null; },
4961 autoresize: function(state) { return false; },
4962 max_updates_to_recreate: function(state) { return 5000; },
4963 track_colors: function(state) { return true; },
4964 pixels_per_point: function(state) { return 3; },
4969 NETDATA.registerChartLibrary = function(library, url) {
4970 if(NETDATA.options.debug.libraries === true)
4971 console.log("registering chart library: " + library);
4973 NETDATA.chartLibraries[library].url = url;
4974 NETDATA.chartLibraries[library].initialized = true;
4975 NETDATA.chartLibraries[library].enabled = true;
4978 // ----------------------------------------------------------------------------------------------------------------
4981 NETDATA.requiredJs = [
4983 url: NETDATA.serverDefault + 'lib/bootstrap.min.js',
4984 isAlreadyLoaded: function() {
4985 if(typeof $().emulateTransitionEnd == 'function')
4988 if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
4996 url: NETDATA.serverDefault + 'lib/jquery.nanoscroller.min.js',
4997 isAlreadyLoaded: function() { return false; }
5000 url: NETDATA.serverDefault + 'lib/bootstrap-toggle.min.js',
5001 isAlreadyLoaded: function() { return false; }
5005 NETDATA.requiredCSS = [
5007 url: NETDATA.serverDefault + 'css/bootstrap.min.css',
5008 isAlreadyLoaded: function() {
5009 if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
5016 url: NETDATA.serverDefault + 'css/font-awesome.min.css',
5017 isAlreadyLoaded: function() { return false; }
5020 url: NETDATA.dashboard_css,
5021 isAlreadyLoaded: function() { return false; }
5024 url: NETDATA.serverDefault + 'css/bootstrap-toggle.min.css',
5025 isAlreadyLoaded: function() { return false; }
5029 NETDATA.loadRequiredJs = function(index, callback) {
5030 if(index >= NETDATA.requiredJs.length) {
5031 if(typeof callback === 'function')
5036 if(NETDATA.requiredJs[index].isAlreadyLoaded()) {
5037 NETDATA.loadRequiredJs(++index, callback);
5041 if(NETDATA.options.debug.main_loop === true)
5042 console.log('loading ' + NETDATA.requiredJs[index].url);
5045 url: NETDATA.requiredJs[index].url,
5049 .success(function() {
5050 if(NETDATA.options.debug.main_loop === true)
5051 console.log('loaded ' + NETDATA.requiredJs[index].url);
5053 NETDATA.loadRequiredJs(++index, callback);
5056 alert('Cannot load required JS library: ' + NETDATA.requiredJs[index].url);
5060 NETDATA.loadRequiredCSS = function(index) {
5061 if(index >= NETDATA.requiredCSS.length)
5064 if(NETDATA.requiredCSS[index].isAlreadyLoaded()) {
5065 NETDATA.loadRequiredCSS(++index);
5069 if(NETDATA.options.debug.main_loop === true)
5070 console.log('loading ' + NETDATA.requiredCSS[index].url);
5072 NETDATA._loadCSS(NETDATA.requiredCSS[index].url);
5073 NETDATA.loadRequiredCSS(++index);
5076 NETDATA.errorReset();
5077 NETDATA.loadRequiredCSS(0);
5079 NETDATA._loadjQuery(function() {
5080 NETDATA.loadRequiredJs(0, function() {
5081 if(typeof netdataDontStart === 'undefined' || !netdataDontStart) {
5082 if(NETDATA.options.debug.main_loop === true)
5083 console.log('starting chart refresh thread');
5090 // window.NETDATA = NETDATA;
5091 // })(window, document);