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 netdataNoBootstrap = true; // do not load bootstrap
10 // var netdataDontStart = true; // do not start the thread to process the charts
12 // You can also set the default netdata server, using the following.
13 // When this variable is not set, we assume the page is hosted on your
14 // netdata server already.
15 // var netdataServer = "http://yourhost:19999"; // set your NetData server
17 //(function(window, document, undefined) {
18 // fix IE issue with console
19 if(!window.console){ window.console = {log: function(){} }; }
22 var NETDATA = window.NETDATA || {};
24 // ----------------------------------------------------------------------------------------------------------------
25 // Detect the netdata server
27 // http://stackoverflow.com/questions/984510/what-is-my-script-src-url
28 // http://stackoverflow.com/questions/6941533/get-protocol-domain-and-port-from-url
29 NETDATA._scriptSource = function(scripts) {
30 var script = null, base = null;
32 if(typeof document.currentScript !== 'undefined') {
33 script = document.currentScript;
36 var all_scripts = document.getElementsByTagName('script');
37 script = all_scripts[all_scripts.length - 1];
40 if (typeof script.getAttribute.length !== 'undefined')
43 script = script.getAttribute('src', -1);
45 var link = document.createElement('a');
46 link.setAttribute('href', script);
48 if(!link.protocol || !link.hostname) return null;
51 if(base) base += "//";
52 base += link.hostname;
54 if(link.port) base += ":" + link.port;
60 if(typeof netdataServer !== 'undefined')
61 NETDATA.serverDefault = netdataServer;
63 NETDATA.serverDefault = NETDATA._scriptSource();
65 if(NETDATA.serverDefault === null)
66 NETDATA.serverDefault = '';
67 else if(NETDATA.serverDefault.slice(-1) !== '/')
68 NETDATA.serverDefault += '/';
70 // default URLs for all the external files we need
71 // make them RELATIVE so that the whole thing can also be
72 // installed under a web server
73 NETDATA.jQuery = NETDATA.serverDefault + 'lib/jquery-1.11.3.min.js';
74 NETDATA.peity_js = NETDATA.serverDefault + 'lib/jquery.peity.min.js';
75 NETDATA.sparkline_js = NETDATA.serverDefault + 'lib/jquery.sparkline.min.js';
76 NETDATA.easypiechart_js = NETDATA.serverDefault + 'lib/jquery.easypiechart.min.js';
77 NETDATA.dygraph_js = NETDATA.serverDefault + 'lib/dygraph-combined.js';
78 NETDATA.dygraph_smooth_js = NETDATA.serverDefault + 'lib/dygraph-smooth-plotter.js';
79 NETDATA.raphael_js = NETDATA.serverDefault + 'lib/raphael-min.js';
80 NETDATA.morris_js = NETDATA.serverDefault + 'lib/morris.min.js';
81 NETDATA.morris_css = NETDATA.serverDefault + 'css/morris.css';
82 NETDATA.dashboard_css = NETDATA.serverDefault + 'dashboard.css';
83 NETDATA.google_js = 'https://www.google.com/jsapi';
85 // these are the colors Google Charts are using
86 // we have them here to attempt emulate their look and feel on the other chart libraries
87 // http://there4.io/2012/05/02/google-chart-color-list/
88 //NETDATA.colors = [ '#3366CC', '#DC3912', '#FF9900', '#109618', '#990099', '#3B3EAC', '#0099C6',
89 // '#DD4477', '#66AA00', '#B82E2E', '#316395', '#994499', '#22AA99', '#AAAA11',
90 // '#6633CC', '#E67300', '#8B0707', '#329262', '#5574A6', '#3B3EAC' ];
92 NETDATA.colors = [ '#3366CC', '#DC3912', '#109618', '#FF9900', '#990099', '#DD4477', '#3B3EAC',
93 '#66AA00', '#0099C6', '#B82E2E', '#AAAA11', '#5574A6', '#994499', '#22AA99',
94 '#6633CC', '#E67300', '#316395', '#8B0707', '#329262', '#3B3EAC' ];
96 // http://www.mulinblog.com/a-color-palette-optimized-for-data-visualization/
97 // (blue) (red) (orange) (green) (pink) (brown) (purple) (yellow) (gray)
98 //NETDATA.colors = [ '#5DA5DA', '#F15854', '#FAA43A', '#60BD68', '#F17CB0', '#B2912F', '#B276B2', '#DECF3F', '#4D4D4D' ];
100 // ----------------------------------------------------------------------------------------------------------------
101 // the defaults for all charts
103 // if the user does not specify any of these, the following will be used
105 NETDATA.chartDefaults = {
106 host: NETDATA.serverDefault, // the server to get data from
107 width: '100%', // the chart width - can be null
108 height: '100%', // the chart height - can be null
109 min_width: null, // the chart minimum width - can be null
110 library: 'dygraph', // the graphing library to use
111 method: 'average', // the grouping method
112 before: 0, // panning
113 after: -600, // panning
114 pixels_per_point: 1, // the detail of the chart
115 fill_luminance: 0.8 // luminance of colors in solit areas
118 // ----------------------------------------------------------------------------------------------------------------
122 readyCallback: null, // a callback when we load the required stuf
123 pauseCallback: null, // a callback when we are really paused
125 pause: false, // when enabled we don't auto-refresh the charts
127 targets: null, // an array of all the state objects that are
128 // currently active (independently of their
129 // viewport visibility)
131 updated_dom: true, // when true, the DOM has been updated with
132 // new elements we have to check.
134 auto_refresher_fast_weight: 0, // this is the current time in ms, spent
135 // rendering charts continiously.
136 // used with .current.fast_render_timeframe
138 page_is_visible: true, // when true, this page is visible
140 auto_refresher_stop_until: 0, // timestamp in ms - used internaly, to stop the
141 // auto-refresher for some time (when a chart is
142 // performing pan or zoom, we need to stop refreshing
143 // all other charts, to have the maximum speed for
144 // rendering the chart that is panned or zoomed).
145 // Used with .current.global_pan_sync_time
147 last_resized: 0, // the timestamp of the last resize request
149 crossDomainAjax: false, // enable this to request crossDomain AJAX
151 last_page_scroll: 0, // the timestamp the last time the page was scrolled
153 // the current profile
154 // we may have many...
156 pixels_per_point: 1, // the minimum pixels per point for all charts
157 // increase this to speed javascript up
158 // each chart library has its own limit too
159 // the max of this and the chart library is used
160 // the final is calculated every time, so a change
161 // here will have immediate effect on the next chart
164 idle_between_charts: 100, // ms - how much time to wait between chart updates
166 fast_render_timeframe: 200, // ms - render continously until this time of continious
167 // rendering has been reached
168 // this setting is used to make it render e.g. 10
169 // charts at once, sleep idle_between_charts time
170 // and continue for another 10 charts.
172 idle_between_loops: 500, // ms - if all charts have been updated, wait this
173 // time before starting again.
175 idle_parallel_loops: 100, // ms - the time between parallel refresher updates
177 idle_lost_focus: 500, // ms - when the window does not have focus, check
178 // if focus has been regained, every this time
180 global_pan_sync_time: 1500, // ms - when you pan or zoon a chart, the background
181 // autorefreshing of charts is paused for this amount
184 sync_selection_delay: 2500, // ms - when you pan or zoom a chart, wait this amount
185 // of time before setting up synchronized selections
188 sync_selection: true, // enable or disable selection sync
190 pan_and_zoom_delay: 50, // when panning or zooming, how ofter to update the chart
192 sync_pan_and_zoom: true, // enable or disable pan and zoom sync
194 update_only_visible: true, // enable or disable visibility management
196 parallel_refresher: true, // enable parallel refresh of charts
198 destroy_on_hide: false, // destroy charts when they are not visible
200 eliminate_zero_dimensions: true, // do not show dimensions with just zeros
202 color_fill_opacity: {
214 chart_data_url: false,
223 if(NETDATA.options.debug.main_loop === true)
224 console.log('welcome to NETDATA');
226 window.onresize = function(event) {
227 NETDATA.options.last_page_scroll = new Date().getTime();
228 NETDATA.options.last_resized = new Date().getTime();
231 window.onscroll = function(event) {
232 NETDATA.options.last_page_scroll = new Date().getTime();
233 if(NETDATA.options.targets === null) return;
235 // when the user scrolls he sees that we have
236 // hidden all the not-visible charts
237 // using this little function we try to switch
238 // the charts back to visible quickly
239 var targets = NETDATA.options.targets;
240 var len = targets.length;
241 while(len--) targets[len].isVisible();
244 // ----------------------------------------------------------------------------------------------------------------
247 NETDATA.errorCodes = {
248 100: { message: "Cannot load chart library", alert: true },
249 101: { message: "Cannot load jQuery", alert: true },
250 402: { message: "Chart library not found", alert: false },
251 403: { message: "Chart library not enabled/is failed", alert: false },
252 404: { message: "Chart not found", alert: false }
254 NETDATA.errorLast = {
260 NETDATA.error = function(code, msg) {
261 NETDATA.errorLast.code = code;
262 NETDATA.errorLast.message = msg;
263 NETDATA.errorLast.datetime = new Date().getTime();
265 console.log("ERROR " + code + ": " + NETDATA.errorCodes[code].message + ": " + msg);
267 if(NETDATA.errorCodes[code].alert)
268 alert("ERROR " + code + ": " + NETDATA.errorCodes[code].message + ": " + msg);
271 NETDATA.errorReset = function() {
272 NETDATA.errorLast.code = 0;
273 NETDATA.errorLast.message = "You are doing fine!";
274 NETDATA.errorLast.datetime = 0;
277 // ----------------------------------------------------------------------------------------------------------------
280 // When multiple charts need the same chart, we avoid downloading it
281 // multiple times (and having it in browser memory multiple time)
282 // by using this registry.
284 // Every time we download a chart definition, we save it here with .add()
285 // Then we try to get it back with .get(). If that fails, we download it.
287 NETDATA.chartRegistry = {
290 fixid: function(id) {
291 return id.replace(/:/g, "_").replace(/\//g, "_");
294 add: function(host, id, data) {
295 host = this.fixid(host);
298 if(typeof this.charts[host] === 'undefined')
299 this.charts[host] = {};
301 //console.log('added ' + host + '/' + id);
302 this.charts[host][id] = data;
305 get: function(host, id) {
306 host = this.fixid(host);
309 if(typeof this.charts[host] === 'undefined')
312 if(typeof this.charts[host][id] === 'undefined')
315 //console.log('cached ' + host + '/' + id);
316 return this.charts[host][id];
319 downloadAll: function(host, callback) {
320 while(host.slice(-1) === '/')
321 host = host.substring(0, host.length - 1);
326 url: host + '/api/v1/charts',
327 crossDomain: NETDATA.options.crossDomainAjax,
331 .done(function(data) {
332 var h = NETDATA.chartRegistry.fixid(host);
333 //console.log('downloaded all charts from ' + host + ' (' + h + ')');
334 self.charts[h] = data.charts;
335 if(typeof callback === 'function')
339 if(typeof callback === 'function')
345 // ----------------------------------------------------------------------------------------------------------------
346 // Global Pan and Zoom on charts
348 // Using this structure are synchronize all the charts, so that
349 // when you pan or zoom one, all others are automatically refreshed
350 // to the same timespan.
352 NETDATA.globalPanAndZoom = {
353 seq: 0, // timestamp ms
354 // every time a chart is panned or zoomed
355 // we set the timestamp here
356 // then we use it as a sequence number
357 // to find if other charts are syncronized
360 master: null, // the master chart (state), to which all others
363 force_before_ms: null, // the timespan to sync all other charts
364 force_after_ms: null,
367 setMaster: function(state, after, before) {
368 if(NETDATA.options.current.sync_pan_and_zoom === false)
371 if(this.master !== null && this.master !== state)
372 this.master.resetChart();
374 var now = new Date().getTime();
377 this.force_after_ms = after;
378 this.force_before_ms = before;
379 NETDATA.options.auto_refresher_stop_until = now + NETDATA.options.current.global_pan_sync_time;
383 clearMaster: function() {
384 if(NETDATA.options.current.sync_pan_and_zoom === false)
387 if(this.master !== null) {
388 var state = this.master;
389 this.master = null; // prevent infinite recursion
392 NETDATA.options.auto_refresher_stop_until = 0;
397 this.force_after_ms = null;
398 this.force_before_ms = null;
401 // is the given state the master of the global
402 // pan and zoom sync?
403 isMaster: function(state) {
404 if(this.master === state) return true;
408 // are we currently have a global pan and zoom sync?
409 isActive: function() {
410 if(this.master !== null && this.force_before_ms !== null && this.force_after_ms !== null && this.seq !== 0) return true;
414 // check if a chart, other than the master
415 // needs to be refreshed, due to the global pan and zoom
416 shouldBeAutoRefreshed: function(state) {
417 if(this.master === null || this.seq === 0)
420 if(state.needsRecreation())
423 if(state.tm.pan_and_zoom_seq === this.seq)
430 // ----------------------------------------------------------------------------------------------------------------
431 // Our state object, where all per-chart values are stored
433 chartState = function(element) {
434 var self = $(element);
437 uuid: NETDATA.guid(), // GUID - a unique identifier for the chart
438 id: self.data('netdata'), // string - the name of chart
440 // the user given dimensions of the element
441 width: self.data('width') || NETDATA.chartDefaults.width,
442 height: self.data('height') || NETDATA.chartDefaults.height,
444 // string - the netdata server URL, without any path
445 host: self.data('host') || NETDATA.chartDefaults.host,
447 // string - the grouping method requested by the user
448 method: self.data('method') || NETDATA.chartDefaults.method,
450 // the time-range requested by the user
451 after: self.data('after') || NETDATA.chartDefaults.after,
452 before: self.data('before') || NETDATA.chartDefaults.before,
454 // the pixels per point requested by the user
455 pixels_per_point: self.data('pixels-per-point') || 1,
456 points: self.data('points') || null,
458 // the dimensions requested by the user
459 dimensions: self.data('dimensions') || null,
461 // the chart library requested by the user
462 library_name: self.data('chart-library') || NETDATA.chartDefaults.library,
463 library: null, // object - the chart library used
467 colors_available: null,
469 element: element, // the element already created by the user
470 element_message: null,
471 element_loading: null,
472 element_chart: null, // the element with the chart
473 element_chart_id: null,
474 element_legend: null, // the element with the legend of the chart (if created by us)
475 element_legend_id: null,
476 element_legend_childs: {
486 chart_url: null, // string - the url to download chart info
487 chart: null, // object - the chart as downloaded from the server
489 validated: false, // boolean - has the chart been validated?
490 enabled: true, // boolean - is the chart enabled for refresh?
491 paused: false, // boolean - is the chart paused for any reason?
492 selected: false, // boolean - is the chart shown a selection?
493 debug: false, // boolean - console.log() debug info about this chart
495 dom_created: false, // boolean - is the DOM for the chart created?
496 chart_created: false, // boolean - is the library.create() been called?
498 updates_counter: 0, // numeric - the number of refreshes made so far
499 updates_since_last_creation: 0,
502 last_info_downloaded: 0, // milliseconds - the timestamp we downloaded the chart
504 last_updated: 0, // the timestamp the chart last updated with data
506 pan_and_zoom_seq: 0, // the sequence number of the global synchronization
508 // Used with NETDATA.globalPanAndZoom.seq
510 last_visible_check: 0, // the time we last checked if it is visible
512 last_resized: 0, // the time the chart was resized
513 last_hidden: 0, // the time the chart was hidden
514 last_unhidden: 0, // the time the chart was unhidden
516 last_autorefreshed: 0 // the time the chart was last refreshed
519 current: null, // auto, pan, zoom
520 // this is a pointer to one of the sub-classes below
525 url: 'invalid://', // string - the last url used to update the chart
526 view_update_every: 0, // milliseconds - the minimum acceptable refresh duration
527 after_ms: 0, // milliseconds - the first timestamp of the data
528 before_ms: 0, // milliseconds - the last timestamp of the data
529 points: 0, // number - the number of points in the data
530 data: null, // the last downloaded data
531 force_update_at: 0, // the timestamp to force the update at
532 force_before_ms: null,
533 force_after_ms: null,
534 requested_before_ms: null,
535 requested_after_ms: null,
536 first_entry_ms: null,
542 url: 'invalid://', // string - the last url used to update the chart
543 view_update_every: 0, // milliseconds - the minimum acceptable refresh duration
544 after_ms: 0, // milliseconds - the first timestamp of the data
545 before_ms: 0, // milliseconds - the last timestamp of the data
546 points: 0, // number - the number of points in the data
547 data: null, // the last downloaded data
548 force_update_at: 0, // the timestamp to force the update at
549 force_before_ms: null,
550 force_after_ms: null,
551 requested_before_ms: null,
552 requested_after_ms: null,
553 first_entry_ms: null,
559 url: 'invalid://', // string - the last url used to update the chart
560 view_update_every: 0, // milliseconds - the minimum acceptable refresh duration
561 after_ms: 0, // milliseconds - the first timestamp of the data
562 before_ms: 0, // milliseconds - the last timestamp of the data
563 points: 0, // number - the number of points in the data
564 data: null, // the last downloaded data
565 force_update_at: 0, // the timestamp to force the update at
566 force_before_ms: null,
567 force_after_ms: null,
568 requested_before_ms: null,
569 requested_after_ms: null,
570 first_entry_ms: null,
574 refresh_dt_ms: 0, // milliseconds - the time the last refresh took
575 refresh_dt_element_name: self.data('dt-element-name') || null, // string - the element to print refresh_dt_ms
576 refresh_dt_element: null
582 // ----------------------------------------------------------------------------------------------------------------
583 // global selection sync
585 NETDATA.globalSelectionSync = {
591 // prevent to global selection sync for some time
592 chartState.prototype.globalSelectionSyncDelay = function(ms) {
593 if(NETDATA.options.current.sync_selection === false)
596 if(typeof ms === 'number')
597 NETDATA.globalSelectionSync.dont_sync_before = new Date().getTime() + ms;
599 NETDATA.globalSelectionSync.dont_sync_before = new Date().getTime() + NETDATA.options.current.sync_selection_delay;
602 // can we globally apply selection sync?
603 chartState.prototype.globalSelectionSyncAbility = function() {
604 if(NETDATA.options.current.sync_selection === false)
607 if(NETDATA.globalSelectionSync.dont_sync_before > new Date().getTime()) return false;
611 chartState.prototype.globalSelectionSyncIsMaster = function() {
612 if(NETDATA.globalSelectionSync.state === this)
618 // this chart is the master of the global selection sync
619 chartState.prototype.globalSelectionSyncBeMaster = function() {
621 if(this.globalSelectionSyncIsMaster()) {
622 if(this.debug === true)
623 this.log('sync: I am the master already.');
628 if(NETDATA.globalSelectionSync.state) {
629 if(this.debug === true)
630 this.log('sync: I am not the sync master. Resetting global sync.');
632 this.globalSelectionSyncStop();
636 if(this.debug === true)
637 this.log('sync: becoming sync master.');
639 this.selected = true;
640 NETDATA.globalSelectionSync.state = this;
642 // find the all slaves
643 var targets = NETDATA.options.targets;
644 var len = targets.length;
649 if(this.debug === true)
650 st.log('sync: not adding me to sync');
652 else if(st.globalSelectionSyncIsEligible()) {
653 if(this.debug === true)
654 st.log('sync: adding to sync as slave');
656 st.globalSelectionSyncBeSlave();
660 // this.globalSelectionSyncDelay(100);
663 // can the chart participate to the global selection sync as a slave?
664 chartState.prototype.globalSelectionSyncIsEligible = function() {
665 if(this.enabled === true
666 && this.library !== null
667 && typeof this.library.setSelection === 'function'
669 && this.dom_created === true
670 && this.chart_created === true)
676 // this chart is a slave of the global selection sync
677 chartState.prototype.globalSelectionSyncBeSlave = function() {
678 if(NETDATA.globalSelectionSync.state !== this)
679 NETDATA.globalSelectionSync.slaves.push(this);
682 // sync all the visible charts to the given time
683 // this is to be called from the chart libraries
684 chartState.prototype.globalSelectionSync = function(t) {
685 if(this.globalSelectionSyncAbility() === false) {
686 if(this.debug === true)
687 this.log('sync: cannot sync (yet?).');
692 if(this.globalSelectionSyncIsMaster() === false) {
693 if(this.debug === true)
694 this.log('sync: trying to be sync master.');
696 this.globalSelectionSyncBeMaster();
698 if(this.globalSelectionSyncAbility() === false) {
699 if(this.debug === true)
700 this.log('sync: cannot sync (yet?).');
706 $.each(NETDATA.globalSelectionSync.slaves, function(i, st) {
711 // stop syncing all charts to the given time
712 chartState.prototype.globalSelectionSyncStop = function() {
713 if(NETDATA.globalSelectionSync.slaves.length) {
714 if(this.debug === true)
715 this.log('sync: cleaning up...');
718 $.each(NETDATA.globalSelectionSync.slaves, function(i, st) {
720 if(self.debug === true)
721 st.log('sync: not adding me to sync stop');
724 if(self.debug === true)
725 st.log('sync: removed slave from sync');
731 NETDATA.globalSelectionSync.slaves = [];
732 NETDATA.globalSelectionSync.state = null;
735 // since we are the sync master, we should not call this.clearSelection()
736 // dygraphs is taking care of visualizing our selection.
737 this.selected = false;
740 chartState.prototype.setSelection = function(t) {
741 if(typeof this.library.setSelection === 'function') {
742 if(this.library.setSelection(this, t) === true)
743 this.selected = true;
745 this.selected = false;
747 else this.selected = true;
749 if(this.selected === true && this.debug === true)
750 this.log('selection set to ' + t.toString());
752 return this.selected;
755 chartState.prototype.clearSelection = function() {
756 if(this.selected === true) {
757 if(typeof this.library.clearSelection === 'function') {
758 if(this.library.clearSelection(this) === true)
759 this.selected = false;
761 this.selected = true;
763 else this.selected = false;
765 if(this.selected === false && this.debug === true)
766 this.log('selection cleared');
770 return this.selected;
773 // find if a timestamp (ms) is shown in the current chart
774 chartState.prototype.timeIsVisible = function(t) {
775 if(t >= this.current.after_ms && t <= this.current.before_ms)
780 chartState.prototype.calculateRowForTime = function(t) {
781 if(this.timeIsVisible(t) === false) return -1;
782 return Math.floor((t - this.current.after_ms) / this.current.view_update_every);
785 // ----------------------------------------------------------------------------------------------------------------
788 chartState.prototype.log = function(msg) {
789 console.log(this.id + ' (' + this.library_name + ' ' + this.uuid + '): ' + msg);
792 chartState.prototype.pauseChart = function() {
793 if(this.paused === false) {
794 if(this.debug === true)
801 chartState.prototype.unpauseChart = function() {
803 if(this.debug === true)
804 this.log('unpaused');
810 chartState.prototype.resetChart = function() {
811 if(NETDATA.globalPanAndZoom.isMaster(this) && this.isVisible())
812 NETDATA.globalPanAndZoom.clearMaster();
814 this.tm.pan_and_zoom_seq = 0;
816 this.clearSelection();
818 this.setMode('auto');
819 this.current.force_update_at = 0;
820 this.current.force_before_ms = null;
821 this.current.force_after_ms = null;
822 this.tm.last_autorefreshed = 0;
824 this.selected = false;
828 // do not update the chart here
829 // or the chart will flip-flop when it is the master
830 // of a selection sync and another chart becomes
832 if(NETDATA.options.current.sync_pan_and_zoom === false && this.isVisible() === true)
836 chartState.prototype.setMode = function(m) {
838 if(this.current.name === m) return;
840 this[m].url = this.current.url;
841 this[m].view_update_every = this.current.view_update_every;
842 this[m].after_ms = this.current.after_ms;
843 this[m].before_ms = this.current.before_ms;
844 this[m].points = this.current.points;
845 this[m].data = this.current.data;
846 this[m].requested_before_ms = this.current.requested_before_ms;
847 this[m].requested_after_ms = this.current.requested_after_ms;
848 this[m].first_entry_ms = this.current.first_entry_ms;
849 this[m].last_entry_ms = this.current.last_entry_ms;
853 this.current = this.auto;
855 this.current = this.pan;
856 else if(m === 'zoom')
857 this.current = this.zoom;
859 this.current = this.auto;
861 this.current.force_update_at = 0;
862 this.current.force_before_ms = null;
863 this.current.force_after_ms = null;
865 if(this.debug === true)
866 this.log('mode set to ' + this.current.name);
869 chartState.prototype.updateChartPanOrZoom = function(after, before) {
870 if(before < after) return false;
872 var min_duration = Math.round((this.chartWidth() / 30 * this.chart.update_every * 1000));
874 if(this.debug === true)
875 this.log('requested duration of ' + ((before - after) / 1000).toString() + ' (' + after + ' - ' + before + '), minimum ' + min_duration / 1000);
877 if((before - after) < min_duration) return false;
879 var current_duration = this.current.before_ms - this.current.after_ms;
880 var wanted_duration = before - after;
881 var tolerance = this.current.view_update_every * 2;
882 var movement = Math.abs(before - this.current.before_ms);
884 if(this.debug === true)
885 this.log('current duration: ' + current_duration / 1000 + ', wanted duration: ' + wanted_duration / 1000 + ', movement: ' + movement / 1000 + ', tolerance: ' + tolerance / 1000);
887 if(Math.abs(current_duration - wanted_duration) <= tolerance && movement <= tolerance) {
888 if(this.debug === true)
894 if(this.current.name === 'auto') {
897 if(this.debug === true)
898 this.log('updateChartPanOrZoom(): caller did not set proper mode');
901 this.current.force_update_at = new Date().getTime() + NETDATA.options.current.pan_and_zoom_delay;
902 this.current.force_after_ms = after;
903 this.current.force_before_ms = before;
904 NETDATA.globalPanAndZoom.setMaster(this, after, before);
908 chartState.prototype.legendFormatValue = function(value) {
909 if(value === null || value === 'undefined') return '-';
910 if(typeof value !== 'number') return value;
912 var abs = Math.abs(value);
913 if(abs >= 1) return (Math.round(value * 100) / 100).toLocaleString();
914 if(abs >= 0.1) return (Math.round(value * 1000) / 1000).toLocaleString();
915 return (Math.round(value * 10000) / 10000).toLocaleString();
918 chartState.prototype.legendSetLabelValue = function(label, value) {
919 var series = this.element_legend_childs.series[label];
920 if(typeof series === 'undefined') return;
921 if(series.value === null && series.user === null) return;
923 value = this.legendFormatValue(value);
925 // if the value has not changed, skip DOM update
926 if(series.last === value) return;
929 if(series.value !== null) series.value.innerHTML = value;
930 if(series.user !== null) series.user.innerHTML = value;
933 chartState.prototype.legendSetDate = function(ms) {
934 if(typeof ms !== 'number') {
935 this.legendShowUndefined();
939 var d = new Date(ms);
941 if(this.element_legend_childs.title_date)
942 this.element_legend_childs.title_date.innerHTML = d.toLocaleDateString();
944 if(this.element_legend_childs.title_time)
945 this.element_legend_childs.title_time.innerHTML = d.toLocaleTimeString();
947 if(this.element_legend_childs.title_units)
948 this.element_legend_childs.title_units.innerHTML = this.chart.units;
951 chartState.prototype.legendShowUndefined = function() {
952 if(this.element_legend_childs.title_date)
953 this.element_legend_childs.title_date.innerHTML = ' ';
955 if(this.element_legend_childs.title_time)
956 this.element_legend_childs.title_time.innerHTML = this.chart.name;
958 if(this.element_legend_childs.title_units)
959 this.element_legend_childs.title_units.innerHTML = ' ';
961 if(this.current.data && this.element_legend_childs.series !== null) {
962 var labels = this.current.data.dimension_names;
963 var i = labels.length;
965 var label = labels[i];
967 if(typeof label === 'undefined') continue;
968 if(typeof this.element_legend_childs.series[label] === 'undefined') continue;
969 this.legendSetLabelValue(label, null);
974 chartState.prototype.legendShowLatestValues = function() {
975 if(this.chart === null) return;
976 if(this.selected) return;
978 if(this.current.data === null || this.element_legend_childs.series === null) {
979 this.legendShowUndefined();
983 var show_undefined = true;
984 if(Math.abs(this.current.data.last_entry_t - this.current.data.before) <= this.current.data.view_update_every)
985 show_undefined = false;
988 this.legendShowUndefined();
990 this.legendSetDate(this.current.data.before * 1000);
992 var labels = this.current.data.dimension_names;
993 var i = labels.length;
995 var label = labels[i];
997 if(typeof label === 'undefined') continue;
998 if(typeof this.element_legend_childs.series[label] === 'undefined') continue;
1001 this.legendSetLabelValue(label, null);
1003 this.legendSetLabelValue(label, this.current.data.result_latest_values[i]);
1007 chartState.prototype.legendReset = function() {
1008 this.legendShowLatestValues();
1011 // this should be called just ONCE per dimension per chart
1012 chartState.prototype._chartDimensionColor = function(label) {
1013 if(this.colors === null) this.chartColors();
1015 if(typeof this.colors_assigned[label] === 'undefined') {
1016 if(this.colors_available.length === 0) {
1017 for(var i = 0, len = NETDATA.colors.length; i < len ; i++)
1018 this.colors_available.push(NETDATA.colors[i]);
1021 this.colors_assigned[label] = this.colors_available.shift();
1023 if(this.debug === true)
1024 this.log('label "' + label + '" got color "' + this.colors_assigned[label]);
1027 if(this.debug === true)
1028 this.log('label "' + label + '" already has color "' + this.colors_assigned[label] + '"');
1031 this.colors.push(this.colors_assigned[label]);
1032 return this.colors_assigned[label];
1035 chartState.prototype.chartColors = function() {
1036 if(this.colors !== null) return this.colors;
1038 this.colors = new Array();
1039 this.colors_available = new Array();
1040 // this.colors_assigned = {};
1042 var c = $(this.element).data('colors');
1043 if(typeof c !== 'undefined' && c !== null) {
1044 if(typeof c !== 'string') {
1045 this.log('invalid color given: ' + c + ' (give a space separated list of colors)');
1049 for(var i = 0, len = c.length; i < len ; i++)
1050 this.colors_available.push(c[i]);
1054 // push all the standard colors too
1055 for(var i = 0, len = NETDATA.colors.length; i < len ; i++)
1056 this.colors_available.push(NETDATA.colors[i]);
1061 chartState.prototype.legendUpdateDOM = function() {
1064 // check that the legend DOM is up to date for the downloaded dimensions
1065 if(typeof this.element_legend_childs.series !== 'object' || this.element_legend_childs.series === null) {
1066 // this.log('the legend does not have any series - requesting legend update');
1069 else if(this.current.data === null) {
1070 // this.log('the chart does not have any data - requesting legend update');
1073 else if(typeof this.element_legend_childs.series.labels_key === 'undefined') {
1077 var labels = this.current.data.dimension_names.toString();
1078 if(labels !== this.element_legend_childs.series.labels_key) {
1081 if(this.debug === true)
1082 this.log('NEW LABELS: "' + labels + '" NOT EQUAL OLD LABELS: "' + this.element_legend_childs.series.labels_key + '"');
1086 if(needed === false) {
1087 // make sure colors available
1090 // do we have to update the current values?
1091 // we do this, only when the visible chart is current
1092 if(Math.abs(this.current.data.last_entry_t - this.current.data.before) <= this.current.data.view_update_every) {
1093 if(this.debug === true)
1094 this.log('chart in running... updating values on legend...');
1096 var labels = this.current.data.dimension_names;
1097 var i = labels.length;
1099 this.legendSetLabelValue(labels[i], this.current.data.latest_values[i]);
1103 if(this.colors === null) {
1104 // this is the first time we update the chart
1105 // let's assign colors to all dimensions
1106 if(this.library.track_colors() === true)
1107 for(var dim in this.chart.dimensions)
1108 this._chartDimensionColor(this.chart.dimensions[dim].name);
1110 // we will re-generate the colors for the chart
1113 if(this.debug === true)
1114 this.log('updating Legend DOM');
1116 var self = $(this.element);
1117 var genLabel = function(state, parent, name, count) {
1118 var color = state._chartDimensionColor(name);
1120 var user_element = null;
1121 var user_id = self.data('show-value-of-' + name + '-at') || null;
1122 if(user_id !== null) {
1123 user_element = document.getElementById(user_id) || null;
1124 if(user_element === null)
1125 me.log('Cannot find element with id: ' + user_id);
1128 state.element_legend_childs.series[name] = {
1129 name: document.createElement('span'),
1130 value: document.createElement('span'),
1135 var label = state.element_legend_childs.series[name];
1137 label.name.className += ' netdata-legend-name';
1138 label.value.className += ' netdata-legend-value';
1139 label.name.title = name;
1140 label.value.title = name;
1142 var rgb = NETDATA.colorHex2Rgb(color);
1143 label.name.innerHTML = '<table class="netdata-legend-name-table-'
1144 + state.chart.chart_type
1145 + '" style="background-color: '
1146 + 'rgba(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ',' + NETDATA.options.current.color_fill_opacity[state.chart.chart_type] + ')'
1147 + '"><tr class="netdata-legend-name-tr"><td class="netdata-legend-name-td"></td></tr></table>'
1149 var text = document.createTextNode(' ' + name);
1150 label.name.appendChild(text);
1152 label.name.style.color = color;
1153 label.value.style.color = color;
1156 parent.appendChild(document.createElement('br'));
1158 parent.appendChild(label.name);
1159 parent.appendChild(label.value);
1162 var content = document.createElement('div');
1164 if(this.hasLegend()) {
1165 this.element_legend_childs = {
1166 title_date: document.createElement('span'),
1167 title_time: document.createElement('span'),
1168 title_units: document.createElement('span'),
1169 nano: document.createElement('div'),
1171 paneClass: 'netdata-legend-series-pane',
1172 sliderClass: 'netdata-legend-series-slider',
1173 contentClass: 'netdata-legend-series-content',
1174 enabledClass: '__enabled',
1175 flashedClass: '__flashed',
1176 activeClass: '__active',
1183 this.element_legend.innerHTML = '';
1185 this.element_legend_childs.title_date.className += " netdata-legend-title-date";
1186 this.element_legend.appendChild(this.element_legend_childs.title_date);
1188 this.element_legend.appendChild(document.createElement('br'));
1190 this.element_legend_childs.title_time.className += " netdata-legend-title-time";
1191 this.element_legend.appendChild(this.element_legend_childs.title_time);
1193 this.element_legend.appendChild(document.createElement('br'));
1195 this.element_legend_childs.title_units.className += " netdata-legend-title-units";
1196 this.element_legend.appendChild(this.element_legend_childs.title_units);
1198 this.element_legend.appendChild(document.createElement('br'));
1200 this.element_legend_childs.nano.className = 'netdata-legend-series';
1201 this.element_legend.appendChild(this.element_legend_childs.nano);
1203 content.className = 'netdata-legend-series-content';
1204 this.element_legend_childs.nano.appendChild(content);
1207 this.element_legend_childs = {
1217 if(this.current.data) {
1218 this.element_legend_childs.series.labels_key = this.current.data.dimension_names.toString();
1219 if(this.debug === true)
1220 this.log('labels from data: "' + this.element_legend_childs.series.labels_key + '"');
1222 for(var i = 0, len = this.current.data.dimension_names.length; i < len ;i++) {
1223 genLabel(this, content, this.current.data.dimension_names[i], i);
1227 var tmp = new Array();
1228 for(var dim in this.chart.dimensions) {
1229 tmp.push(this.chart.dimensions[dim].name);
1230 genLabel(this, content, this.chart.dimensions[dim].name, i);
1232 this.element_legend_childs.series.labels_key = tmp.toString();
1233 if(this.debug === true)
1234 this.log('labels from chart: "' + this.element_legend_childs.series.labels_key + '"');
1237 // create a hidden div to be used for hidding
1238 // the original legend of the chart library
1239 var el = document.createElement('div');
1240 this.element_legend.appendChild(el);
1241 el.style.display = 'none';
1243 this.element_legend_childs.hidden = document.createElement('div');
1244 el.appendChild(this.element_legend_childs.hidden);
1246 if(this.element_legend_childs.nano !== null && this.element_legend_childs.nano_options !== null)
1247 $(this.element_legend_childs.nano).nanoScroller(this.element_legend_childs.nano_options);
1249 this.legendShowLatestValues();
1252 chartState.prototype.createChartDOM = function() {
1253 if(this.debug === true)
1254 this.log('creating DOM');
1256 this.element_chart_id = this.library_name + '-' + this.uuid + '-chart';
1257 this.element_chart = document.createElement('div');
1258 this.element_chart.className += ' netdata-chart' + (this.hasLegend()?'-with-legend-right':'').toString();
1259 this.element_chart.className += ' netdata-' + this.library_name + '-chart' + (this.hasLegend()?'-with-legend-right':'').toString();
1260 this.element_chart.id = this.element_chart_id;
1261 $(this.element_chart).data('netdata-state-object', this);
1262 this.element.appendChild(this.element_chart);
1264 this.element_legend_id = this.library_name + '-' + this.uuid + '-legend';
1265 this.element_legend = document.createElement('div');
1266 this.element_legend.className += ' netdata-chart-legend';
1267 this.element_legend.className += ' netdata-' + this.library_name + '-legend';
1268 this.element_legend.id = this.element_legend_id;
1269 $(this.element_legend).data('netdata-state-object', this);
1271 if(this.hasLegend() === false)
1272 this.element_legend.style.display = 'none';
1274 this.element.appendChild(this.element_legend);
1276 this.element_legend_childs.series = null;
1277 this.legendUpdateDOM();
1279 // in case the user has an active global selection sync in place
1281 this.globalSelectionSyncStop();
1282 this.dom_created = true;
1285 chartState.prototype.hasLegend = function() {
1286 if(typeof this.___hasLegendCache___ !== 'undefined')
1287 return this.___hasLegendCache___;
1290 if(this.library && this.library.legend(this) === 'right-side') {
1291 var legend = $(this.element).data('legend') || 'yes';
1292 if(legend === 'yes') leg = true;
1295 this.___hasLegendCache___ = leg;
1299 chartState.prototype.legendWidth = function() {
1300 return (this.hasLegend())?110:0;
1303 chartState.prototype.legendHeight = function() {
1304 return $(this.element).height();
1307 chartState.prototype.chartWidth = function() {
1308 return $(this.element).width() - this.legendWidth();
1311 chartState.prototype.chartHeight = function() {
1312 return $(this.element).height();
1315 chartState.prototype.chartPixelsPerPoint = function() {
1316 // force an options provided detail
1317 var px = this.pixels_per_point;
1319 if(this.library && px < this.library.pixels_per_point(this))
1320 px = this.library.pixels_per_point(this);
1322 if(px < NETDATA.options.current.pixels_per_point)
1323 px = NETDATA.options.current.pixels_per_point;
1328 chartState.prototype.needsRecreation = function() {
1330 this.dom_created === true
1331 && this.chart_created === true
1333 && this.library.autoresize() === false
1334 && this.tm.last_resized < NETDATA.options.last_resized
1338 chartState.prototype.resizeChart = function() {
1339 if(this.needsRecreation()) {
1340 if(this.debug === true)
1341 this.log('forcing re-generation due to window resize.');
1343 this.destroyChart();
1346 this.tm.last_resized = new Date().getTime();
1349 chartState.prototype.chartURL = function() {
1352 if(NETDATA.globalPanAndZoom.isActive()) {
1353 after = Math.round(NETDATA.globalPanAndZoom.force_after_ms / 1000);
1354 before = Math.round(NETDATA.globalPanAndZoom.force_before_ms / 1000);
1355 this.tm.pan_and_zoom_seq = NETDATA.globalPanAndZoom.seq;
1358 before = this.current.force_before_ms !== null ? Math.round(this.current.force_before_ms / 1000) : this.before;
1359 after = this.current.force_after_ms !== null ? Math.round(this.current.force_after_ms / 1000) : this.after;
1360 this.tm.pan_and_zoom_seq = 0;
1363 this.current.requested_after_ms = after * 1000;
1364 this.current.requested_before_ms = before * 1000;
1366 this.current.points = this.points || Math.round(this.chartWidth() / this.chartPixelsPerPoint());
1368 // build the data URL
1369 this.current.url = this.chart.data_url;
1370 this.current.url += "&format=" + this.library.format();
1371 this.current.url += "&points=" + this.current.points.toString();
1372 this.current.url += "&group=" + this.method;
1373 this.current.url += "&options=" + this.library.options();
1374 this.current.url += '|jsonwrap';
1376 if(NETDATA.options.current.eliminate_zero_dimensions === true)
1377 this.current.url += '|nonzero';
1380 this.current.url += "&after=" + after.toString();
1383 this.current.url += "&before=" + before.toString();
1386 this.current.url += "&dimensions=" + this.dimensions;
1388 if(NETDATA.options.debug.chart_data_url === true || this.debug === true)
1389 this.log('chartURL(): ' + this.current.url + ' WxH:' + this.chartWidth() + 'x' + this.chartHeight() + ' points: ' + this.current.points + ' library: ' + this.library_name);
1392 chartState.prototype.updateChartWithData = function(data) {
1393 if(this.debug === true)
1394 this.log('got data from netdata server');
1396 this.current.data = data;
1397 this.updates_counter++;
1399 var started = new Date().getTime();
1400 this.tm.last_updated = started;
1402 // if the result is JSON, find the latest update-every
1403 if(typeof data === 'object') {
1404 if(typeof data.view_update_every !== 'undefined')
1405 this.current.view_update_every = data.view_update_every * 1000;
1407 if(typeof data.after !== 'undefined')
1408 this.current.after_ms = data.after * 1000;
1410 if(typeof data.before !== 'undefined')
1411 this.current.before_ms = data.before * 1000;
1413 if(typeof data.first_entry_t !== 'undefined')
1414 this.current.first_entry_ms = data.first_entry_t * 1000;
1416 if(typeof data.last_entry_t !== 'undefined')
1417 this.current.last_entry_ms = data.last_entry_t * 1000;
1419 if(typeof data.points !== 'undefined')
1420 this.current.points = data.points;
1425 if(this.debug === true) {
1426 this.log('UPDATE No ' + this.updates_counter + ' COMPLETED');
1428 if(this.current.force_after_ms)
1429 this.log('STATUS: forced : ' + (this.current.force_after_ms / 1000).toString() + ' - ' + (this.current.force_before_ms / 1000).toString());
1431 this.log('STATUS: forced: unset');
1433 this.log('STATUS: requested: ' + (this.current.requested_after_ms / 1000).toString() + ' - ' + (this.current.requested_before_ms / 1000).toString());
1434 this.log('STATUS: rendered : ' + (this.current.after_ms / 1000).toString() + ' - ' + (this.current.before_ms / 1000).toString());
1435 this.log('STATUS: points : ' + (this.current.points).toString());
1438 if(data.points === 0) {
1443 // this may force the chart to be re-created
1446 if(this.updates_since_last_creation >= this.library.max_updates_to_recreate()) {
1447 if(this.debug === true)
1448 this.log('max updates of ' + this.updates_since_last_creation.toString() + ' reached. Forcing re-generation.');
1450 this.chart_created = false;
1453 if(this.chart_created === true
1454 && this.dom_created === true
1455 && typeof this.library.update === 'function') {
1457 if(this.debug === true)
1458 this.log('updating chart...');
1460 // check and update the legend
1461 this.legendUpdateDOM();
1463 this.updates_since_last_creation++;
1464 if(NETDATA.options.debug.chart_errors === true) {
1465 this.library.update(this, data);
1469 this.library.update(this, data);
1472 this.error('chart failed to be updated as ' + this.library_name);
1477 if(this.debug === true)
1478 this.log('creating chart...');
1480 this.createChartDOM();
1481 this.updates_since_last_creation = 0;
1483 if(NETDATA.options.debug.chart_errors === true) {
1484 this.library.create(this, data);
1485 this.chart_created = true;
1489 this.library.create(this, data);
1490 this.chart_created = true;
1493 this.error('chart failed to be created as ' + this.library_name);
1497 this.legendShowLatestValues();
1499 // update the performance counters
1500 var now = new Date().getTime();
1502 // don't update last_autorefreshed if this chart is
1503 // forced to be updated with global PanAndZoom
1504 if(NETDATA.globalPanAndZoom.isActive())
1505 this.tm.last_autorefreshed = 0;
1507 //if(NETDATA.options.current.parallel_refresher === true)
1508 // this.tm.last_autorefreshed = Math.round(now / 1000) * 1000;
1510 this.tm.last_autorefreshed = now;
1513 this.refresh_dt_ms = now - started;
1514 NETDATA.options.auto_refresher_fast_weight += this.refresh_dt_ms;
1516 if(this.refresh_dt_element)
1517 this.refresh_dt_element.innerHTML = this.refresh_dt_ms.toString();
1520 chartState.prototype.updateChart = function(callback) {
1521 // due to late initialization of charts and libraries
1522 // we need to check this too
1523 if(this.enabled === false) {
1524 if(this.debug === true)
1525 this.log('I am not enabled');
1527 if(typeof callback === 'function') callback();
1531 if(this.chart === null) {
1533 this.getChart(function() { self.updateChart(callback); });
1537 if(this.library.initialized === false) {
1538 if(this.library.enabled === true) {
1540 this.library.initialize(function() { self.updateChart(callback); });
1544 this.error('chart library "' + this.library_name + '" is not available.');
1545 if(typeof callback === 'function') callback();
1550 this.clearSelection();
1554 if(this.debug === true)
1555 this.log('updating from ' + this.current.url);
1558 this.xhr = $.ajax( {
1559 url: this.current.url,
1560 crossDomain: NETDATA.options.crossDomainAjax,
1564 .success(function(data) {
1567 if(self.debug === true)
1568 self.log('data received. updating chart.');
1570 self.updateChartWithData(data);
1574 self.error('data download failed for url: ' + self.current.url);
1576 .always(function() {
1578 if(typeof callback === 'function') callback();
1582 chartState.prototype.destroyChart = function() {
1583 if(this.debug === true)
1584 this.log('destroying chart');
1586 if(this.element_message !== null) {
1587 this.element_message.innerHTML = '';
1588 this.element_message = null;
1591 if(this.element_loading !== null) {
1592 this.element_loading.innerHTML = '';
1593 this.element_loading = null;
1596 if(this.element_legend !== null) {
1597 this.element_legend.innerHTML = '';
1598 this.element_legend = null;
1601 if(this.element_chart !== null) {
1602 this.element_chart.innerHTML = '';
1603 this.element_chart = null;
1606 this.element_legend_childs = {
1616 this.element.innerHTML = '';
1617 this.refresh_dt_element = null;
1619 this.dom_created = false;
1620 this.chart_created = false;
1621 this.paused = false;
1622 this.selected = false;
1623 this.updates_counter = 0;
1624 this.updates_since_last_creation = 0;
1625 this.tm.pan_and_zoom_seq = 0;
1626 this.tm.last_resized = 0;
1627 this.tm.last_visible_check = 0;
1628 this.tm.last_hidden = 0;
1629 this.tm.last_unhidden = 0;
1630 this.tm.last_autorefreshed = 0;
1632 if(this.current !== null) {
1633 this.current.view_update_every = 0;
1634 this.current.after_ms = 0;
1635 this.current.before_ms = 0;
1636 this.current.points = 0;
1637 this.current.data = null;
1638 this.current.force_update_at = 0;
1639 this.current.force_after_ms = null;
1640 this.current.force_before_ms = null;
1641 this.current.requested_after_ms = null;
1642 this.current.requested_before_ms = null;
1643 this.current.first_entry_ms = null;
1644 this.current.last_entry_ms = null;
1649 chartState.prototype.unhideChart = function() {
1650 if(typeof this.___isHidden___ !== 'undefined' && this.enabled === true) {
1651 if(this.debug === true)
1652 this.log('unhiding chart');
1654 this.element_message.style.display = 'none';
1655 if(this.element_chart !== null) this.element_chart.style.display = 'inline-block';
1656 if(this.element_legend !== null) this.element_legend.style.display = 'inline-block';
1657 if(this.element_loading !== null) this.element_loading.style.display = 'none';
1658 this.___isHidden___ = undefined;
1659 this.element_message.innerHTML = 'chart ' + this.id + ' is visible now';
1661 // refresh the scrolbar
1662 if(this.element_legend_childs.nano !== null && this.element_legend_childs.nano_options !== null)
1663 $(this.element_legend_childs.nano).nanoScroller(this.element_legend_childs.nano_options);
1665 this.tm.last_unhidden = new Date().getTime();
1669 chartState.prototype.hideChart = function() {
1670 if(typeof this.___isHidden___ === 'undefined' && this.enabled === true) {
1671 if(NETDATA.options.current.destroy_on_hide === true)
1672 this.destroyChart();
1674 if(this.debug === true)
1675 this.log('hiding chart');
1677 this.element_message.style.display = 'inline-block';
1678 if(this.element_chart !== null) this.element_chart.style.display = 'none';
1679 if(this.element_legend !== null) this.element_legend.style.display = 'none';
1680 if(this.element_loading !== null) this.element_loading.style.display = 'none';
1681 this.___isHidden___ = true;
1682 this.___showsLoading___ = undefined;
1683 this.element_message.innerHTML = 'chart ' + this.id + ' is hidden to speed up the browser';
1684 this.tm.last_hidden = new Date().getTime();
1688 chartState.prototype.hideLoading = function() {
1689 if(typeof this.___showsLoading___ !== 'undefined' && this.enabled === true) {
1690 if(this.debug === true)
1691 this.log('hide loading...');
1693 this.element_message.style.display = 'none';
1694 if(this.element_chart !== null) this.element_chart.style.display = 'inline-block';
1695 if(this.element_legend !== null) this.element_legend.style.display = 'inline-block';
1696 if(this.element_loading !== null) this.element_loading.style.display = 'none';
1697 this.___showsLoading___ = undefined;
1698 this.element_loading.innerHTML = 'chart ' + this.id + ' finished loading!';
1699 this.tm.last_unhidden = new Date().getTime();
1703 chartState.prototype.showLoading = function() {
1704 if(typeof this.___showsLoading___ === 'undefined' && this.chart_created === false && this.enabled === true) {
1705 if(this.debug === true)
1706 this.log('show loading...');
1708 this.element_message.style.display = 'none';
1709 if(this.element_chart !== null) this.element_chart.style.display = 'none';
1710 if(this.element_legend !== null) this.element_legend.style.display = 'none';
1711 if(this.element_loading !== null) this.element_loading.style.display = 'inline-block';
1712 this.___showsLoading___ = true;
1713 this.___isHidden___ = undefined;
1714 this.element_loading.innerHTML = 'chart ' + this.id + ' is loading...';
1715 this.tm.last_hidden = new Date().getTime();
1719 chartState.prototype.isVisible = function() {
1720 // this.log('last_visible_check: ' + this.tm.last_visible_check + ', last_page_scroll: ' + NETDATA.options.last_page_scroll);
1721 if(this.tm.last_visible_check > NETDATA.options.last_page_scroll) {
1722 if(this.debug === true)
1723 this.log('isVisible: ' + this.___isVisible___);
1725 return this.___isVisible___;
1728 this.tm.last_visible_check = new Date().getTime();
1730 var wh = window.innerHeight;
1731 var x = this.element.getBoundingClientRect();
1735 if(x.top < 0 && -x.top > x.height) {
1736 // the chart is entirely above
1737 ret = -x.top - x.height;
1739 else if(x.top > wh) {
1740 // the chart is entirely below
1744 if(ret > tolerance) {
1745 // the chart is too far
1746 this.___isVisible___ = false;
1747 if(this.chart_created === true) this.hideChart();
1749 if(this.debug === true)
1750 this.log('isVisible: ' + this.___isVisible___);
1752 return this.___isVisible___;
1755 // the chart is inside or very close
1756 this.___isVisible___ = true;
1759 if(this.debug === true)
1760 this.log('isVisible: ' + this.___isVisible___);
1762 return this.___isVisible___;
1766 chartState.prototype.isAutoRefreshed = function() {
1767 return (this.current.autorefresh);
1770 chartState.prototype.canBeAutoRefreshed = function() {
1771 now = new Date().getTime();
1773 if(this.enabled === false) {
1774 if(this.debug === true)
1775 this.log('I am not enabled');
1780 if(this.library === null || this.library.enabled === false) {
1781 this.error('charting library "' + this.library_name + '" is not available');
1782 if(this.debug === true)
1783 this.log('My chart library ' + this.library_name + ' is not available');
1788 if(this.isVisible() === false) {
1789 if(NETDATA.options.debug.visibility === true || this.debug === true)
1790 this.log('I am not visible');
1795 if(this.current.force_update_at !== 0 && this.current.force_update_at < now) {
1796 if(this.debug === true)
1797 this.log('timed force update detected - allowing this update');
1799 this.current.force_update_at = 0;
1803 if(this.isAutoRefreshed() === true) {
1804 // allow the first update, even if the page is not visible
1805 if(this.updates_counter && NETDATA.options.page_is_visible === false) {
1806 if(NETDATA.options.debug.focus === true || this.debug === true)
1807 this.log('canBeAutoRefreshed(): page does not have focus');
1812 if(this.needsRecreation() === true) {
1813 if(this.debug === true)
1814 this.log('canBeAutoRefreshed(): needs re-creation.');
1819 // options valid only for autoRefresh()
1820 if(NETDATA.options.auto_refresher_stop_until === 0 || NETDATA.options.auto_refresher_stop_until < now) {
1821 if(NETDATA.globalPanAndZoom.isActive()) {
1822 if(NETDATA.globalPanAndZoom.shouldBeAutoRefreshed(this)) {
1823 if(this.debug === true)
1824 this.log('canBeAutoRefreshed(): global panning: I need an update.');
1829 if(this.debug === true)
1830 this.log('canBeAutoRefreshed(): global panning: I am already up to date.');
1836 if(this.selected === true) {
1837 if(this.debug === true)
1838 this.log('canBeAutoRefreshed(): I have a selection in place.');
1843 if(this.paused === true) {
1844 if(this.debug === true)
1845 this.log('canBeAutoRefreshed(): I am paused.');
1850 if(now - this.tm.last_autorefreshed > this.current.view_update_every) {
1851 if(this.debug === true)
1852 this.log('canBeAutoRefreshed(): It is time to update me.');
1862 chartState.prototype.autoRefresh = function(callback) {
1863 if(this.canBeAutoRefreshed() === true) {
1864 this.updateChart(callback);
1867 if(typeof callback !== 'undefined')
1872 chartState.prototype._defaultsFromDownloadedChart = function(chart) {
1874 this.chart_url = chart.url;
1875 this.current.view_update_every = chart.update_every * 1000;
1876 this.current.points = Math.round(this.chartWidth() / this.chartPixelsPerPoint());
1877 this.tm.last_info_downloaded = new Date().getTime();
1880 // fetch the chart description from the netdata server
1881 chartState.prototype.getChart = function(callback) {
1882 this.chart = NETDATA.chartRegistry.get(this.host, this.id);
1884 this._defaultsFromDownloadedChart(this.chart);
1885 if(typeof callback === 'function') callback();
1888 this.chart_url = this.host + "/api/v1/chart?chart=" + this.id;
1890 if(this.debug === true)
1891 this.log('downloading ' + this.chart_url);
1896 url: this.chart_url,
1897 crossDomain: NETDATA.options.crossDomainAjax,
1901 .done(function(chart) {
1902 chart.url = self.chart_url;
1903 chart.data_url = (self.host + chart.data_url);
1904 self._defaultsFromDownloadedChart(chart);
1905 NETDATA.chartRegistry.add(self.host, self.id, chart);
1908 NETDATA.error(404, self.chart_url);
1909 self.error('chart not found on url "' + self.chart_url + '"');
1911 .always(function() {
1912 if(typeof callback === 'function') callback();
1917 // resize the chart to its real dimensions
1918 // as given by the caller
1919 chartState.prototype.sizeChart = function() {
1920 this.element.className += " netdata-container";
1922 if(this.debug === true)
1923 this.log('sizing element');
1925 if(this.width !== 0)
1926 $(this.element).css('width', this.width);
1928 if(this.height !== 0)
1929 $(this.element).css('height', this.height);
1931 if(NETDATA.chartDefaults.min_width !== null)
1932 $(this.element).css('min-width', NETDATA.chartDefaults.min_width);
1935 chartState.prototype.noData = function() {
1936 if(this.dom_created === false)
1937 this.createChartDOM();
1939 this.tm.last_autorefreshed = new Date().getTime();
1940 this.current.view_update_every = 30 * 1000;
1943 // show a message in the chart
1944 chartState.prototype.message = function(type, msg) {
1946 this.element_message.innerHTML = msg;
1948 if(this.debug === null)
1952 // show an error on the chart and stop it forever
1953 chartState.prototype.error = function(msg) {
1954 this.message('error', this.id + ': ' + msg);
1955 this.enabled = false;
1958 // show a message indicating the chart is loading
1959 chartState.prototype.info = function(msg) {
1960 this.message('info', this.id + ': ' + msg);
1963 chartState.prototype.init = function() {
1964 this.element.innerHTML = '';
1966 this.element_message = document.createElement('div');
1967 this.element_message.className += ' netdata-message';
1968 this.element.appendChild(this.element_message);
1970 this.element_loading = document.createElement('div');
1971 this.element_loading.className += ' netdata-chart-is-loading';
1972 this.element.appendChild(this.element_loading);
1974 if(this.debug === null)
1975 this.log('created');
1979 // make sure the host does not end with /
1980 // all netdata API requests use absolute paths
1981 while(this.host.slice(-1) === '/')
1982 this.host = this.host.substring(0, this.host.length - 1);
1984 // check the requested library is available
1985 // we don't initialize it here - it will be initialized when
1986 // this chart will be first used
1987 if(typeof NETDATA.chartLibraries[this.library_name] === 'undefined') {
1988 NETDATA.error(402, this.library_name);
1989 this.error('chart library "' + this.library_name + '" is not found');
1991 else if(NETDATA.chartLibraries[this.library_name].enabled === false) {
1992 NETDATA.error(403, this.library_name);
1993 this.error('chart library "' + this.library_name + '" is not enabled');
1996 this.library = NETDATA.chartLibraries[this.library_name];
1998 // if we need to report the rendering speed
1999 // find the element that needs to be updated
2000 if(this.refresh_dt_element_name)
2001 this.refresh_dt_element = document.getElementById(this.refresh_dt_element_name) || null;
2003 // the default mode for all charts
2004 this.setMode('auto');
2007 // get or create a chart state, given a DOM element
2008 NETDATA.chartState = function(element) {
2009 var state = $(element).data('netdata-state-object') || null;
2010 if(state === null) {
2011 state = new chartState(element);
2012 $(element).data('netdata-state-object', state);
2017 // ----------------------------------------------------------------------------------------------------------------
2018 // Library functions
2020 // Load a script without jquery
2021 // This is used to load jquery - after it is loaded, we use jquery
2022 NETDATA._loadjQuery = function(callback) {
2023 if(typeof jQuery === 'undefined') {
2024 if(NETDATA.options.debug.main_loop === true)
2025 console.log('loading ' + NETDATA.jQuery);
2027 var script = document.createElement('script');
2028 script.type = 'text/javascript';
2029 script.async = true;
2030 script.src = NETDATA.jQuery;
2032 // script.onabort = onError;
2033 script.onerror = function(err, t) { NETDATA.error(101, NETDATA.jQuery); };
2034 if(typeof callback === "function")
2035 script.onload = callback;
2037 var s = document.getElementsByTagName('script')[0];
2038 s.parentNode.insertBefore(script, s);
2040 else if(typeof callback === "function")
2044 NETDATA._loadCSS = function(filename) {
2045 // don't use jQuery here
2046 // styles are loaded before jQuery
2047 // to eliminate showing an unstyled page to the user
2049 var fileref = document.createElement("link");
2050 fileref.setAttribute("rel", "stylesheet");
2051 fileref.setAttribute("type", "text/css");
2052 fileref.setAttribute("href", filename);
2054 if (typeof fileref !== 'undefined')
2055 document.getElementsByTagName("head")[0].appendChild(fileref);
2058 NETDATA.colorHex2Rgb = function(hex) {
2059 // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
2060 var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
2061 hex = hex.replace(shorthandRegex, function(m, r, g, b) {
2062 return r + r + g + g + b + b;
2065 var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
2067 r: parseInt(result[1], 16),
2068 g: parseInt(result[2], 16),
2069 b: parseInt(result[3], 16)
2073 NETDATA.colorLuminance = function(hex, lum) {
2074 // validate hex string
2075 hex = String(hex).replace(/[^0-9a-f]/gi, '');
2077 hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
2081 // convert to decimal and change luminosity
2082 var rgb = "#", c, i;
2083 for (i = 0; i < 3; i++) {
2084 c = parseInt(hex.substr(i*2,2), 16);
2085 c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
2086 rgb += ("00"+c).substr(c.length);
2092 NETDATA.guid = function() {
2094 return Math.floor((1 + Math.random()) * 0x10000)
2099 return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
2102 NETDATA.zeropad = function(x) {
2103 if(x > -10 && x < 10) return '0' + x.toString();
2104 else return x.toString();
2107 // user function to signal us the DOM has been
2109 NETDATA.updatedDom = function() {
2110 NETDATA.options.updated_dom = true;
2113 NETDATA.ready = function(callback) {
2114 NETDATA.options.readyCallback = callback;
2117 NETDATA.pause = function(callback) {
2118 NETDATA.options.pauseCallback = callback;
2121 NETDATA.unpause = function() {
2122 NETDATA.options.pauseCallback = null;
2123 NETDATA.options.updated_dom = true;
2124 NETDATA.options.pause = false;
2127 // ----------------------------------------------------------------------------------------------------------------
2129 // this is purely sequencial charts refresher
2130 // it is meant to be autonomous
2131 NETDATA.chartRefresherNoParallel = function(index) {
2132 if(NETDATA.options.debug.mail_loop === true)
2133 console.log('NETDATA.chartRefresherNoParallel(' + index + ')');
2135 if(NETDATA.options.updated_dom === true) {
2136 // the dom has been updated
2137 // get the dom parts again
2138 NETDATA.parseDom(NETDATA.chartRefresher);
2141 if(index >= NETDATA.options.targets.length) {
2142 if(NETDATA.options.debug.main_loop === true)
2143 console.log('waiting to restart main loop...');
2145 NETDATA.options.auto_refresher_fast_weight = 0;
2147 setTimeout(function() {
2148 NETDATA.chartRefresher();
2149 }, NETDATA.options.current.idle_between_loops);
2152 var state = NETDATA.options.targets[index];
2154 if(NETDATA.options.auto_refresher_fast_weight < NETDATA.options.current.fast_render_timeframe) {
2155 if(NETDATA.options.debug.main_loop === true)
2156 console.log('fast rendering...');
2158 state.autoRefresh(function() {
2159 NETDATA.chartRefresherNoParallel(++index);
2163 if(NETDATA.options.debug.main_loop === true) console.log('waiting for next refresh...');
2164 NETDATA.options.auto_refresher_fast_weight = 0;
2166 setTimeout(function() {
2167 state.autoRefresh(function() {
2168 NETDATA.chartRefresherNoParallel(++index);
2170 }, NETDATA.options.current.idle_between_charts);
2175 // this is part of the parallel refresher
2176 // its cause is to refresh sequencially all the charts
2177 // that depend on chart library initialization
2178 // it will call the parallel refresher back
2179 // as soon as it sees a chart that its chart library
2181 NETDATA.chartRefresher_unitialized = function() {
2182 if(NETDATA.options.updated_dom === true) {
2183 // the dom has been updated
2184 // get the dom parts again
2185 NETDATA.parseDom(NETDATA.chartRefresher);
2189 if(NETDATA.options.sequencial.length === 0)
2190 NETDATA.chartRefresher();
2192 var state = NETDATA.options.sequencial.pop();
2193 if(state.library.initialized === true)
2194 NETDATA.chartRefresher();
2196 state.autoRefresh(NETDATA.chartRefresher_unitialized);
2200 NETDATA.chartRefresherWaitTime = function() {
2201 return NETDATA.options.current.idle_parallel_loops;
2204 // the default refresher
2205 // it will create 2 sets of charts:
2206 // - the ones that can be refreshed in parallel
2207 // - the ones that depend on something else
2208 // the first set will be executed in parallel
2209 // the second will be given to NETDATA.chartRefresher_unitialized()
2210 NETDATA.chartRefresher = function() {
2211 if(NETDATA.options.pause === true) {
2212 // console.log('auto-refresher is paused');
2213 setTimeout(NETDATA.chartRefresher,
2214 NETDATA.chartRefresherWaitTime());
2218 if(typeof NETDATA.options.pauseCallback === 'function') {
2219 // console.log('auto-refresher is calling pauseCallback');
2220 NETDATA.options.pause = true;
2221 NETDATA.options.pauseCallback();
2222 NETDATA.chartRefresher();
2226 if(NETDATA.options.current.parallel_refresher === false) {
2227 NETDATA.chartRefresherNoParallel(0);
2231 if(NETDATA.options.updated_dom === true) {
2232 // the dom has been updated
2233 // get the dom parts again
2234 NETDATA.parseDom(NETDATA.chartRefresher);
2238 var parallel = new Array();
2239 var targets = NETDATA.options.targets;
2240 var len = targets.length;
2242 if(targets[len].isVisible() === false)
2245 var state = targets[len];
2246 if(state.library.initialized === false) {
2247 if(state.library.enabled === true) {
2248 state.library.initialize(NETDATA.chartRefresher);
2252 state.error('chart library "' + state.library_name + '" is not enabled.');
2253 state.enabled = false;
2257 parallel.unshift(state);
2260 if(parallel.length > 0) {
2261 var parallel_jobs = parallel.length;
2263 // this will execute the jobs in parallel
2264 $(parallel).each(function() {
2265 this.autoRefresh(function() {
2268 if(parallel_jobs === 0) {
2269 setTimeout(NETDATA.chartRefresher,
2270 NETDATA.chartRefresherWaitTime());
2276 setTimeout(NETDATA.chartRefresher,
2277 NETDATA.chartRefresherWaitTime());
2281 NETDATA.parseDom = function(callback) {
2282 NETDATA.options.last_page_scroll = new Date().getTime();
2283 NETDATA.options.updated_dom = false;
2285 var targets = $('div[data-netdata]').filter(':visible');
2287 if(NETDATA.options.debug.main_loop === true)
2288 console.log('DOM updated - there are ' + targets.length + ' charts on page.');
2290 NETDATA.options.targets = new Array();
2291 var len = targets.length;
2293 // the initialization will take care of sizing
2294 // and the "loading..." message
2295 NETDATA.options.targets.push(NETDATA.chartState(targets[len]));
2298 if(typeof callback === 'function') callback();
2301 // this is the main function - where everything starts
2302 NETDATA.start = function() {
2303 // this should be called only once
2305 NETDATA.options.page_is_visible = true;
2307 $(window).blur(function() {
2308 NETDATA.options.page_is_visible = false;
2309 if(NETDATA.options.debug.focus === true)
2310 console.log('Lost Focus!');
2313 $(window).focus(function() {
2314 NETDATA.options.page_is_visible = true;
2315 if(NETDATA.options.debug.focus === true)
2316 console.log('Focus restored!');
2319 if(typeof document.hasFocus === 'function' && !document.hasFocus()) {
2320 NETDATA.options.page_is_visible = false;
2321 if(NETDATA.options.debug.focus === true)
2322 console.log('Document has no focus!');
2325 NETDATA.parseDom(NETDATA.chartRefresher);
2328 // ----------------------------------------------------------------------------------------------------------------
2331 NETDATA.peityInitialize = function(callback) {
2332 if(typeof netdataNoPeitys === 'undefined' || !netdataNoPeitys) {
2334 url: NETDATA.peity_js,
2339 NETDATA.registerChartLibrary('peity', NETDATA.peity_js);
2342 NETDATA.chartLibraries.peity.enabled = false;
2343 NETDATA.error(100, NETDATA.peity_js);
2345 .always(function() {
2346 if(typeof callback === "function")
2351 NETDATA.chartLibraries.peity.enabled = false;
2352 if(typeof callback === "function")
2357 NETDATA.peityChartUpdate = function(state, data) {
2358 state.peity_instance.innerHTML = data.result;
2360 if(state.peity_options.stroke !== state.chartColors()[0]) {
2361 state.peity_options.stroke = state.chartColors()[0];
2362 if(state.chart.chart_type === 'line')
2363 state.peity_options.fill = '#FFF';
2365 state.peity_options.fill = NETDATA.colorLuminance(state.chartColors()[0], NETDATA.chartDefaults.fill_luminance);
2368 $(state.peity_instance).peity('line', state.peity_options);
2371 NETDATA.peityChartCreate = function(state, data) {
2372 state.peity_instance = document.createElement('div');
2373 state.element_chart.appendChild(state.peity_instance);
2375 var self = $(state.element);
2376 state.peity_options = {
2378 strokeWidth: self.data('peity-strokewidth') || 1,
2379 width: state.chartWidth(),
2380 height: state.chartHeight(),
2384 NETDATA.peityChartUpdate(state, data);
2387 // ----------------------------------------------------------------------------------------------------------------
2390 NETDATA.sparklineInitialize = function(callback) {
2391 if(typeof netdataNoSparklines === 'undefined' || !netdataNoSparklines) {
2393 url: NETDATA.sparkline_js,
2398 NETDATA.registerChartLibrary('sparkline', NETDATA.sparkline_js);
2401 NETDATA.chartLibraries.sparkline.enabled = false;
2402 NETDATA.error(100, NETDATA.sparkline_js);
2404 .always(function() {
2405 if(typeof callback === "function")
2410 NETDATA.chartLibraries.sparkline.enabled = false;
2411 if(typeof callback === "function")
2416 NETDATA.sparklineChartUpdate = function(state, data) {
2417 state.sparkline_options.width = state.chartWidth();
2418 state.sparkline_options.height = state.chartHeight();
2420 $(state.element_chart).sparkline(data.result, state.sparkline_options);
2423 NETDATA.sparklineChartCreate = function(state, data) {
2424 var self = $(state.element);
2425 var type = self.data('sparkline-type') || 'line';
2426 var lineColor = self.data('sparkline-linecolor') || state.chartColors()[0];
2427 var fillColor = self.data('sparkline-fillcolor') || (state.chart.chart_type === 'line')?'#FFF':NETDATA.colorLuminance(lineColor, NETDATA.chartDefaults.fill_luminance);
2428 var chartRangeMin = self.data('sparkline-chartrangemin') || undefined;
2429 var chartRangeMax = self.data('sparkline-chartrangemax') || undefined;
2430 var composite = self.data('sparkline-composite') || undefined;
2431 var enableTagOptions = self.data('sparkline-enabletagoptions') || undefined;
2432 var tagOptionPrefix = self.data('sparkline-tagoptionprefix') || undefined;
2433 var tagValuesAttribute = self.data('sparkline-tagvaluesattribute') || undefined;
2434 var disableHiddenCheck = self.data('sparkline-disablehiddencheck') || undefined;
2435 var defaultPixelsPerValue = self.data('sparkline-defaultpixelspervalue') || undefined;
2436 var spotColor = self.data('sparkline-spotcolor') || undefined;
2437 var minSpotColor = self.data('sparkline-minspotcolor') || undefined;
2438 var maxSpotColor = self.data('sparkline-maxspotcolor') || undefined;
2439 var spotRadius = self.data('sparkline-spotradius') || undefined;
2440 var valueSpots = self.data('sparkline-valuespots') || undefined;
2441 var highlightSpotColor = self.data('sparkline-highlightspotcolor') || undefined;
2442 var highlightLineColor = self.data('sparkline-highlightlinecolor') || undefined;
2443 var lineWidth = self.data('sparkline-linewidth') || undefined;
2444 var normalRangeMin = self.data('sparkline-normalrangemin') || undefined;
2445 var normalRangeMax = self.data('sparkline-normalrangemax') || undefined;
2446 var drawNormalOnTop = self.data('sparkline-drawnormalontop') || undefined;
2447 var xvalues = self.data('sparkline-xvalues') || undefined;
2448 var chartRangeClip = self.data('sparkline-chartrangeclip') || undefined;
2449 var xvalues = self.data('sparkline-xvalues') || undefined;
2450 var chartRangeMinX = self.data('sparkline-chartrangeminx') || undefined;
2451 var chartRangeMaxX = self.data('sparkline-chartrangemaxx') || undefined;
2452 var disableInteraction = self.data('sparkline-disableinteraction') || false;
2453 var disableTooltips = self.data('sparkline-disabletooltips') || false;
2454 var disableHighlight = self.data('sparkline-disablehighlight') || false;
2455 var highlightLighten = self.data('sparkline-highlightlighten') || 1.4;
2456 var highlightColor = self.data('sparkline-highlightcolor') || undefined;
2457 var tooltipContainer = self.data('sparkline-tooltipcontainer') || undefined;
2458 var tooltipClassname = self.data('sparkline-tooltipclassname') || undefined;
2459 var tooltipFormat = self.data('sparkline-tooltipformat') || undefined;
2460 var tooltipPrefix = self.data('sparkline-tooltipprefix') || undefined;
2461 var tooltipSuffix = self.data('sparkline-tooltipsuffix') || ' ' + state.chart.units;
2462 var tooltipSkipNull = self.data('sparkline-tooltipskipnull') || true;
2463 var tooltipValueLookups = self.data('sparkline-tooltipvaluelookups') || undefined;
2464 var tooltipFormatFieldlist = self.data('sparkline-tooltipformatfieldlist') || undefined;
2465 var tooltipFormatFieldlistKey = self.data('sparkline-tooltipformatfieldlistkey') || undefined;
2466 var numberFormatter = self.data('sparkline-numberformatter') || function(n){ return n.toFixed(2); };
2467 var numberDigitGroupSep = self.data('sparkline-numberdigitgroupsep') || undefined;
2468 var numberDecimalMark = self.data('sparkline-numberdecimalmark') || undefined;
2469 var numberDigitGroupCount = self.data('sparkline-numberdigitgroupcount') || undefined;
2470 var animatedZooms = self.data('sparkline-animatedzooms') || false;
2472 state.sparkline_options = {
2474 lineColor: lineColor,
2475 fillColor: fillColor,
2476 chartRangeMin: chartRangeMin,
2477 chartRangeMax: chartRangeMax,
2478 composite: composite,
2479 enableTagOptions: enableTagOptions,
2480 tagOptionPrefix: tagOptionPrefix,
2481 tagValuesAttribute: tagValuesAttribute,
2482 disableHiddenCheck: disableHiddenCheck,
2483 defaultPixelsPerValue: defaultPixelsPerValue,
2484 spotColor: spotColor,
2485 minSpotColor: minSpotColor,
2486 maxSpotColor: maxSpotColor,
2487 spotRadius: spotRadius,
2488 valueSpots: valueSpots,
2489 highlightSpotColor: highlightSpotColor,
2490 highlightLineColor: highlightLineColor,
2491 lineWidth: lineWidth,
2492 normalRangeMin: normalRangeMin,
2493 normalRangeMax: normalRangeMax,
2494 drawNormalOnTop: drawNormalOnTop,
2496 chartRangeClip: chartRangeClip,
2497 chartRangeMinX: chartRangeMinX,
2498 chartRangeMaxX: chartRangeMaxX,
2499 disableInteraction: disableInteraction,
2500 disableTooltips: disableTooltips,
2501 disableHighlight: disableHighlight,
2502 highlightLighten: highlightLighten,
2503 highlightColor: highlightColor,
2504 tooltipContainer: tooltipContainer,
2505 tooltipClassname: tooltipClassname,
2506 tooltipChartTitle: state.chart.title,
2507 tooltipFormat: tooltipFormat,
2508 tooltipPrefix: tooltipPrefix,
2509 tooltipSuffix: tooltipSuffix,
2510 tooltipSkipNull: tooltipSkipNull,
2511 tooltipValueLookups: tooltipValueLookups,
2512 tooltipFormatFieldlist: tooltipFormatFieldlist,
2513 tooltipFormatFieldlistKey: tooltipFormatFieldlistKey,
2514 numberFormatter: numberFormatter,
2515 numberDigitGroupSep: numberDigitGroupSep,
2516 numberDecimalMark: numberDecimalMark,
2517 numberDigitGroupCount: numberDigitGroupCount,
2518 animatedZooms: animatedZooms,
2519 width: state.chartWidth(),
2520 height: state.chartHeight()
2523 $(state.element_chart).sparkline(data.result, state.sparkline_options);
2526 // ----------------------------------------------------------------------------------------------------------------
2533 NETDATA.dygraphSetSelection = function(state, t) {
2534 if(typeof state.dygraph_instance !== 'undefined') {
2535 var r = state.calculateRowForTime(t);
2537 state.dygraph_instance.setSelection(r);
2539 state.dygraph_instance.clearSelection();
2540 state.legendShowUndefined();
2547 NETDATA.dygraphClearSelection = function(state, t) {
2548 if(typeof state.dygraph_instance !== 'undefined') {
2549 state.dygraph_instance.clearSelection();
2554 NETDATA.dygraphSmoothInitialize = function(callback) {
2556 url: NETDATA.dygraph_smooth_js,
2561 NETDATA.dygraph.smooth = true;
2562 smoothPlotter.smoothing = 0.3;
2565 NETDATA.dygraph.smooth = false;
2567 .always(function() {
2568 if(typeof callback === "function")
2573 NETDATA.dygraphInitialize = function(callback) {
2574 if(typeof netdataNoDygraphs === 'undefined' || !netdataNoDygraphs) {
2576 url: NETDATA.dygraph_js,
2581 NETDATA.registerChartLibrary('dygraph', NETDATA.dygraph_js);
2584 NETDATA.chartLibraries.dygraph.enabled = false;
2585 NETDATA.error(100, NETDATA.dygraph_js);
2587 .always(function() {
2588 if(NETDATA.chartLibraries.dygraph.enabled === true)
2589 NETDATA.dygraphSmoothInitialize(callback);
2590 else if(typeof callback === "function")
2595 NETDATA.chartLibraries.dygraph.enabled = false;
2596 if(typeof callback === "function")
2601 NETDATA.dygraphChartUpdate = function(state, data) {
2602 var dygraph = state.dygraph_instance;
2604 if(typeof dygraph === 'undefined')
2605 NETDATA.dygraphChartCreate(state, data);
2607 // when the chart is not visible, and hidden
2608 // if there is a window resize, dygraph detects
2609 // its element size as 0x0.
2610 // this will make it re-appear properly
2612 if(state.tm.last_unhidden > state.dygraph_last_rendered)
2615 if(state.current.name === 'pan') {
2616 if(NETDATA.options.debug.dygraph === true || state.debug === true)
2617 state.log('dygraphChartUpdate() loose update');
2619 dygraph.updateOptions({
2620 file: data.result.data,
2621 colors: state.chartColors(),
2622 labels: data.result.labels,
2623 labelsDivWidth: state.chartWidth() - 70
2627 if(NETDATA.options.debug.dygraph === true || state.debug === true)
2628 state.log('dygraphChartUpdate() strict update');
2630 dygraph.updateOptions({
2631 file: data.result.data,
2632 colors: state.chartColors(),
2633 labels: data.result.labels,
2634 labelsDivWidth: state.chartWidth() - 70,
2640 state.dygraph_last_rendered = new Date().getTime();
2643 NETDATA.dygraphChartCreate = function(state, data) {
2644 if(NETDATA.options.debug.dygraph === true || state.debug === true)
2645 state.log('dygraphChartCreate()');
2647 var self = $(state.element);
2649 var chart_type = state.chart.chart_type;
2650 if(chart_type === 'stacked' && data.dimensions === 1) chart_type = 'area';
2651 chart_type = self.data('dygraph-type') || chart_type;
2653 var smooth = (chart_type === 'line' && !NETDATA.chartLibraries.dygraph.isSparkline(state))?true:false;
2654 smooth = self.data('dygraph-smooth') || smooth;
2656 if(NETDATA.dygraph.smooth === false)
2659 var strokeWidth = (chart_type === 'stacked')?0.0:((smooth)?1.5:1.0)
2660 var highlightCircleSize = (NETDATA.chartLibraries.dygraph.isSparkline(state))?3:4;
2663 state.dygraph_options = {
2664 colors: self.data('dygraph-colors') || state.chartColors(),
2666 // leave a few pixels empty on the right of the chart
2667 rightGap: self.data('dygraph-rightgap') || 5,
2668 showRangeSelector: self.data('dygraph-showrangeselector') || false,
2669 showRoller: self.data('dygraph-showroller') || false,
2671 title: self.data('dygraph-title') || state.chart.title,
2672 titleHeight: self.data('dygraph-titleheight') || 19,
2674 legend: self.data('dygraph-legend') || 'always', // 'onmouseover',
2675 labels: data.result.labels,
2676 labelsDiv: self.data('dygraph-labelsdiv') || state.element_legend_childs.hidden,
2677 labelsDivStyles: self.data('dygraph-labelsdivstyles') || { 'fontSize':'10px', 'zIndex': 10000 },
2678 labelsDivWidth: self.data('dygraph-labelsdivwidth') || state.chartWidth() - 70,
2679 labelsSeparateLines: self.data('dygraph-labelsseparatelines') || true,
2680 labelsShowZeroValues: self.data('dygraph-labelsshowzerovalues') || true,
2683 showLabelsOnHighlight: self.data('dygraph-showlabelsonhighlight') || true,
2684 hideOverlayOnMouseOut: self.data('dygraph-hideoverlayonmouseout') || true,
2686 ylabel: state.chart.units,
2687 yLabelWidth: self.data('dygraph-ylabelwidth') || 12,
2689 // the function to plot the chart
2692 // The width of the lines connecting data points. This can be used to increase the contrast or some graphs.
2693 strokeWidth: self.data('dygraph-strokewidth') || strokeWidth,
2694 strokePattern: self.data('dygraph-strokepattern') || undefined,
2696 // The size of the dot to draw on each point in pixels (see drawPoints). A dot is always drawn when a point is "isolated",
2697 // i.e. there is a missing point on either side of it. This also controls the size of those dots.
2698 drawPoints: self.data('dygraph-drawpoints') || false,
2700 // Draw points at the edges of gaps in the data. This improves visibility of small data segments or other data irregularities.
2701 drawGapEdgePoints: self.data('dygraph-drawgapedgepoints') || true,
2703 connectSeparatedPoints: self.data('dygraph-connectseparatedpoints') || false,
2704 pointSize: self.data('dygraph-pointsize') || 1,
2706 // enabling this makes the chart with little square lines
2707 stepPlot: self.data('dygraph-stepplot') || false,
2709 // Draw a border around graph lines to make crossing lines more easily distinguishable. Useful for graphs with many lines.
2710 strokeBorderColor: self.data('dygraph-strokebordercolor') || 'white',
2711 strokeBorderWidth: self.data('dygraph-strokeborderwidth') || (chart_type === 'stacked')?0.0:0.0,
2713 fillGraph: self.data('dygraph-fillgraph') || (chart_type === 'area')?true:false,
2714 fillAlpha: self.data('dygraph-fillalpha') || (chart_type === 'stacked')?0.8:0.2,
2715 stackedGraph: self.data('dygraph-stackedgraph') || (chart_type === 'stacked')?true:false,
2716 stackedGraphNaNFill: self.data('dygraph-stackedgraphnanfill') || 'none',
2718 drawAxis: self.data('dygraph-drawaxis') || true,
2719 axisLabelFontSize: self.data('dygraph-axislabelfontsize') || 10,
2720 axisLineColor: self.data('dygraph-axislinecolor') || '#CCC',
2721 axisLineWidth: self.data('dygraph-axislinewidth') || 0.3,
2723 drawGrid: self.data('dygraph-drawgrid') || true,
2724 drawXGrid: self.data('dygraph-drawxgrid') || undefined,
2725 drawYGrid: self.data('dygraph-drawygrid') || undefined,
2726 gridLinePattern: self.data('dygraph-gridlinepattern') || null,
2727 gridLineWidth: self.data('dygraph-gridlinewidth') || 0.3,
2728 gridLineColor: self.data('dygraph-gridlinecolor') || '#DDD',
2730 maxNumberWidth: self.data('dygraph-maxnumberwidth') || 8,
2731 sigFigs: self.data('dygraph-sigfigs') || null,
2732 digitsAfterDecimal: self.data('dygraph-digitsafterdecimal') || 2,
2733 valueFormatter: self.data('dygraph-valueformatter') || function(x){ return x.toFixed(2); },
2735 highlightCircleSize: self.data('dygraph-highlightcirclesize') || highlightCircleSize,
2736 highlightSeriesOpts: self.data('dygraph-highlightseriesopts') || null, // TOO SLOW: { strokeWidth: 1.5 },
2737 highlightSeriesBackgroundAlpha: self.data('dygraph-highlightseriesbackgroundalpha') || null, // TOO SLOW: (chart_type === 'stacked')?0.7:0.5,
2739 pointClickCallback: self.data('dygraph-pointclickcallback') || undefined,
2743 ticker: Dygraph.dateTicker,
2744 axisLabelFormatter: function (d, gran) {
2745 return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds());
2747 valueFormatter: function (ms) {
2748 var d = new Date(ms);
2749 return d.toLocaleDateString() + ' ' + d.toLocaleTimeString();
2750 // return NETDATA.zeropad(d.getHours()) + ":" + NETDATA.zeropad(d.getMinutes()) + ":" + NETDATA.zeropad(d.getSeconds());
2755 valueFormatter: function (x) {
2756 // return (Math.round(x*100) / 100).toLocaleString();
2757 //return state.legendFormatValue(x);
2763 legendFormatter: function(data) {
2764 var g = data.dygraph;
2766 var elements = state.element_legend_childs;
2768 // if the hidden div is not there
2769 // we are not managing the legend
2770 if(elements.hidden === null) return;
2772 if (typeof data.x === 'undefined') {
2773 state.legendReset();
2776 state.legendSetDate(data.x);
2777 var i = data.series.length;
2779 var series = data.series[i];
2780 if(!series.isVisible) continue;
2781 state.legendSetLabelValue(series.label, series.y);
2787 drawCallback: function(dygraph, is_initial) {
2788 if(state.current.name !== 'auto') {
2789 if(NETDATA.options.debug.dygraph === true)
2790 state.log('dygraphDrawCallback()');
2792 var first = state.current.data.first_entry_t * 1000;
2793 var last = state.current.data.last_entry_t * 1000;
2795 var x_range = dygraph.xAxisRange();
2796 var after = Math.round(x_range[0]);
2797 var before = Math.round(x_range[1]);
2799 if(before <= last && after >= first)
2800 state.updateChartPanOrZoom(after, before);
2803 zoomCallback: function(minDate, maxDate, yRanges) {
2804 if(NETDATA.options.debug.dygraph === true)
2805 state.log('dygraphZoomCallback()');
2807 state.globalSelectionSyncStop();
2808 state.globalSelectionSyncDelay();
2810 if(state.updateChartPanOrZoom(minDate, maxDate) == false) {
2811 // we should not zoom that much
2812 state.dygraph_instance.updateOptions({
2818 highlightCallback: function(event, x, points, row, seriesName) {
2819 if(NETDATA.options.debug.dygraph === true || state.debug === true)
2820 state.log('dygraphHighlightCallback()');
2824 // there is a bug in dygraph when the chart is zoomed enough
2825 // the time it thinks is selected is wrong
2826 // here we calculate the time t based on the row number selected
2828 var t = state.current.after_ms + row * state.current.view_update_every;
2829 // console.log('row = ' + row + ', x = ' + x + ', t = ' + t + ' ' + ((t === x)?'SAME':'DIFFERENT') + ', rows in db: ' + state.current.data.points + ' visible(x) = ' + state.timeIsVisible(x) + ' visible(t) = ' + state.timeIsVisible(t) + ' r(x) = ' + state.calculateRowForTime(x) + ' r(t) = ' + state.calculateRowForTime(t) + ' range: ' + state.current.after_ms + ' - ' + state.current.before_ms + ' real: ' + state.current.data.after + ' - ' + state.current.data.before + ' every: ' + state.current.view_update_every);
2831 state.globalSelectionSync(t);
2833 // fix legend zIndex using the internal structures of dygraph legend module
2834 // this works, but it is a hack!
2835 // state.dygraph_instance.plugins_[0].plugin.legend_div_.style.zIndex = 10000;
2837 unhighlightCallback: function(event) {
2838 if(NETDATA.options.debug.dygraph === true || state.debug === true)
2839 state.log('dygraphUnhighlightCallback()');
2841 state.unpauseChart();
2842 state.globalSelectionSyncStop();
2844 interactionModel : {
2845 mousedown: function(event, dygraph, context) {
2846 if(NETDATA.options.debug.dygraph === true || state.debug === true)
2847 state.log('interactionModel.mousedown()');
2849 state.globalSelectionSyncStop();
2851 if(NETDATA.options.debug.dygraph === true)
2852 state.log('dygraphMouseDown()');
2854 // Right-click should not initiate a zoom.
2855 if(event.button && event.button === 2) return;
2857 context.initializeMouseDown(event, dygraph, context);
2859 if(event.button && event.button === 1) {
2860 if (event.altKey || event.shiftKey) {
2861 state.setMode('pan');
2862 state.globalSelectionSyncDelay();
2863 Dygraph.startPan(event, dygraph, context);
2866 state.setMode('zoom');
2867 state.globalSelectionSyncDelay();
2868 Dygraph.startZoom(event, dygraph, context);
2872 if (event.altKey || event.shiftKey) {
2873 state.setMode('zoom');
2874 state.globalSelectionSyncDelay();
2875 Dygraph.startZoom(event, dygraph, context);
2878 state.setMode('pan');
2879 state.globalSelectionSyncDelay();
2880 Dygraph.startPan(event, dygraph, context);
2884 mousemove: function(event, dygraph, context) {
2885 if(NETDATA.options.debug.dygraph === true || state.debug === true)
2886 state.log('interactionModel.mousemove()');
2888 if(context.isPanning) {
2889 state.globalSelectionSyncStop();
2890 state.globalSelectionSyncDelay();
2891 state.setMode('pan');
2892 Dygraph.movePan(event, dygraph, context);
2894 else if(context.isZooming) {
2895 state.globalSelectionSyncStop();
2896 state.globalSelectionSyncDelay();
2897 state.setMode('zoom');
2898 Dygraph.moveZoom(event, dygraph, context);
2901 mouseup: function(event, dygraph, context) {
2902 if(NETDATA.options.debug.dygraph === true || state.debug === true)
2903 state.log('interactionModel.mouseup()');
2905 if (context.isPanning) {
2906 state.globalSelectionSyncDelay();
2907 Dygraph.endPan(event, dygraph, context);
2909 else if (context.isZooming) {
2910 state.globalSelectionSyncDelay();
2911 Dygraph.endZoom(event, dygraph, context);
2914 click: function(event, dygraph, context) {
2915 if(NETDATA.options.debug.dygraph === true || state.debug === true)
2916 state.log('interactionModel.click()');
2918 event.preventDefault();
2920 dblclick: function(event, dygraph, context) {
2921 if(NETDATA.options.debug.dygraph === true || state.debug === true)
2922 state.log('interactionModel.dblclick()');
2924 state.globalSelectionSyncStop();
2925 NETDATA.globalPanAndZoom.clearMaster();
2928 mousewheel: function(event, dygraph, context) {
2929 if(NETDATA.options.debug.dygraph === true || state.debug === true)
2930 state.log('interactionModel.mousewheel()');
2932 // Take the offset of a mouse event on the dygraph canvas and
2933 // convert it to a pair of percentages from the bottom left.
2934 // (Not top left, bottom is where the lower value is.)
2935 function offsetToPercentage(g, offsetX, offsetY) {
2936 // This is calculating the pixel offset of the leftmost date.
2937 var xOffset = g.toDomCoords(g.xAxisRange()[0], null)[0];
2938 var yar0 = g.yAxisRange(0);
2940 // This is calculating the pixel of the higest value. (Top pixel)
2941 var yOffset = g.toDomCoords(null, yar0[1])[1];
2943 // x y w and h are relative to the corner of the drawing area,
2944 // so that the upper corner of the drawing area is (0, 0).
2945 var x = offsetX - xOffset;
2946 var y = offsetY - yOffset;
2948 // This is computing the rightmost pixel, effectively defining the
2950 var w = g.toDomCoords(g.xAxisRange()[1], null)[0] - xOffset;
2952 // This is computing the lowest pixel, effectively defining the height.
2953 var h = g.toDomCoords(null, yar0[0])[1] - yOffset;
2955 // Percentage from the left.
2956 var xPct = w === 0 ? 0 : (x / w);
2957 // Percentage from the top.
2958 var yPct = h === 0 ? 0 : (y / h);
2960 // The (1-) part below changes it from "% distance down from the top"
2961 // to "% distance up from the bottom".
2962 return [xPct, (1-yPct)];
2965 // Adjusts [x, y] toward each other by zoomInPercentage%
2966 // Split it so the left/bottom axis gets xBias/yBias of that change and
2967 // tight/top gets (1-xBias)/(1-yBias) of that change.
2969 // If a bias is missing it splits it down the middle.
2970 function zoomRange(g, zoomInPercentage, xBias, yBias) {
2971 xBias = xBias || 0.5;
2972 yBias = yBias || 0.5;
2974 function adjustAxis(axis, zoomInPercentage, bias) {
2975 var delta = axis[1] - axis[0];
2976 var increment = delta * zoomInPercentage;
2977 var foo = [increment * bias, increment * (1-bias)];
2979 return [ axis[0] + foo[0], axis[1] - foo[1] ];
2982 var yAxes = g.yAxisRanges();
2984 for (var i = 0; i < yAxes.length; i++) {
2985 newYAxes[i] = adjustAxis(yAxes[i], zoomInPercentage, yBias);
2988 return adjustAxis(g.xAxisRange(), zoomInPercentage, xBias);
2991 if(event.altKey || event.shiftKey) {
2992 state.globalSelectionSyncStop();
2993 state.globalSelectionSyncDelay();
2995 // http://dygraphs.com/gallery/interaction-api.js
2996 var normal = (event.detail) ? event.detail * -1 : event.wheelDelta / 40;
2997 var percentage = normal / 50;
2999 if (!(event.offsetX && event.offsetY)){
3000 event.offsetX = event.layerX - event.target.offsetLeft;
3001 event.offsetY = event.layerY - event.target.offsetTop;
3004 var percentages = offsetToPercentage(dygraph, event.offsetX, event.offsetY);
3005 var xPct = percentages[0];
3006 var yPct = percentages[1];
3008 var new_x_range = zoomRange(dygraph, percentage, xPct, yPct);
3010 var after = new_x_range[0];
3011 var before = new_x_range[1];
3013 var first = (state.current.data.first_entry_t + state.current.data.view_update_every) * 1000;
3014 var last = (state.current.data.last_entry_t + state.current.data.view_update_every) * 1000;
3017 after -= (before - last);
3024 state.setMode('zoom');
3025 if(state.updateChartPanOrZoom(after, before) === true)
3026 dygraph.updateOptions({ dateWindow: [ after, before ] });
3028 event.preventDefault();
3031 touchstart: function(event, dygraph, context) {
3032 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3033 state.log('interactionModel.touchstart()');
3035 state.globalSelectionSyncStop();
3036 state.globalSelectionSyncDelay();
3037 Dygraph.Interaction.startTouch(event, dygraph, context);
3038 context.touchDirections = { x: true, y: false };
3039 state.setMode('zoom');
3041 touchmove: function(event, dygraph, context) {
3042 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3043 state.log('interactionModel.touchmove()');
3045 //Dygraph.cancelEvent(event);
3046 state.globalSelectionSyncStop();
3047 Dygraph.Interaction.moveTouch(event, dygraph, context);
3049 touchend: function(event, dygraph, context) {
3050 if(NETDATA.options.debug.dygraph === true || state.debug === true)
3051 state.log('interactionModel.touchend()');
3053 Dygraph.Interaction.endTouch(event, dygraph, context);
3058 if(NETDATA.chartLibraries.dygraph.isSparkline(state)) {
3059 state.dygraph_options.drawGrid = false;
3060 state.dygraph_options.drawAxis = false;
3061 state.dygraph_options.title = undefined;
3062 state.dygraph_options.units = undefined;
3063 state.dygraph_options.ylabel = undefined;
3064 state.dygraph_options.yLabelWidth = 0;
3065 state.dygraph_options.labelsDivWidth = 120;
3066 state.dygraph_options.labelsDivStyles.width = '120px';
3067 state.dygraph_options.labelsSeparateLines = true;
3068 state.dygraph_options.rightGap = 0;
3071 if(smooth === true) state.dygraph_options.plotter = smoothPlotter;
3073 state.dygraph_instance = new Dygraph(state.element_chart,
3074 data.result.data, state.dygraph_options);
3076 state.dygraph_last_rendered = new Date().getTime();
3079 // ----------------------------------------------------------------------------------------------------------------
3082 NETDATA.morrisInitialize = function(callback) {
3083 if(typeof netdataNoMorris === 'undefined' || !netdataNoMorris) {
3085 // morris requires raphael
3086 if(!NETDATA.chartLibraries.raphael.initialized) {
3087 if(NETDATA.chartLibraries.raphael.enabled) {
3088 NETDATA.raphaelInitialize(function() {
3089 NETDATA.morrisInitialize(callback);
3093 NETDATA.chartLibraries.morris.enabled = false;
3094 if(typeof callback === "function")
3099 NETDATA._loadCSS(NETDATA.morris_css);
3102 url: NETDATA.morris_js,
3107 NETDATA.registerChartLibrary('morris', NETDATA.morris_js);
3110 NETDATA.chartLibraries.morris.enabled = false;
3111 NETDATA.error(100, NETDATA.morris_js);
3113 .always(function() {
3114 if(typeof callback === "function")
3120 NETDATA.chartLibraries.morris.enabled = false;
3121 if(typeof callback === "function")
3126 NETDATA.morrisChartUpdate = function(state, data) {
3127 state.morris_instance.setData(data.result.data);
3130 NETDATA.morrisChartCreate = function(state, data) {
3132 state.morris_options = {
3133 element: state.element_chart_id,
3134 data: data.result.data,
3136 ykeys: data.dimension_names,
3137 labels: data.dimension_names,
3143 continuousLine: false,
3144 behaveLikeLine: false
3147 if(state.chart.chart_type === 'line')
3148 state.morris_instance = new Morris.Line(state.morris_options);
3150 else if(state.chart.chart_type === 'area') {
3151 state.morris_options.behaveLikeLine = true;
3152 state.morris_instance = new Morris.Area(state.morris_options);
3155 state.morris_instance = new Morris.Area(state.morris_options);
3158 // ----------------------------------------------------------------------------------------------------------------
3161 NETDATA.raphaelInitialize = function(callback) {
3162 if(typeof netdataStopRaphael === 'undefined' || !netdataStopRaphael) {
3164 url: NETDATA.raphael_js,
3169 NETDATA.registerChartLibrary('raphael', NETDATA.raphael_js);
3172 NETDATA.chartLibraries.raphael.enabled = false;
3173 NETDATA.error(100, NETDATA.raphael_js);
3175 .always(function() {
3176 if(typeof callback === "function")
3181 NETDATA.chartLibraries.raphael.enabled = false;
3182 if(typeof callback === "function")
3187 NETDATA.raphaelChartUpdate = function(state, data) {
3188 $(state.element_chart).raphael(data.result, {
3189 width: state.chartWidth(),
3190 height: state.chartHeight()
3194 NETDATA.raphaelChartCreate = function(state, data) {
3195 $(state.element_chart).raphael(data.result, {
3196 width: state.chartWidth(),
3197 height: state.chartHeight()
3201 // ----------------------------------------------------------------------------------------------------------------
3204 NETDATA.googleInitialize = function(callback) {
3205 if(typeof netdataNoGoogleCharts === 'undefined' || !netdataNoGoogleCharts) {
3207 url: NETDATA.google_js,
3212 NETDATA.registerChartLibrary('google', NETDATA.google_js);
3213 google.load('visualization', '1.1', {
3214 'packages': ['corechart', 'controls'],
3215 'callback': callback
3219 NETDATA.chartLibraries.google.enabled = false;
3220 NETDATA.error(100, NETDATA.google_js);
3221 if(typeof callback === "function")
3226 NETDATA.chartLibraries.google.enabled = false;
3227 if(typeof callback === "function")
3232 NETDATA.googleChartUpdate = function(state, data) {
3233 var datatable = new google.visualization.DataTable(data.result);
3234 state.google_instance.draw(datatable, state.google_options);
3237 NETDATA.googleChartCreate = function(state, data) {
3238 var datatable = new google.visualization.DataTable(data.result);
3240 state.google_options = {
3241 // do not set width, height - the chart resizes itself
3242 //width: state.chartWidth(),
3243 //height: state.chartHeight(),
3245 title: state.chart.title,
3248 // title: "Time of Day",
3249 // format:'HH:mm:ss',
3250 viewWindowMode: 'maximized',
3261 title: state.chart.units,
3262 viewWindowMode: 'pretty',
3277 focusTarget: 'category',
3284 titlePosition: 'out',
3295 curveType: 'function',
3300 switch(state.chart.chart_type) {
3302 state.google_options.vAxis.viewWindowMode = 'maximized';
3303 state.google_instance = new google.visualization.AreaChart(state.element_chart);
3307 state.google_options.isStacked = true;
3308 state.google_options.areaOpacity = 0.85;
3309 state.google_options.vAxis.viewWindowMode = 'maximized';
3310 state.google_options.vAxis.minValue = null;
3311 state.google_options.vAxis.maxValue = null;
3312 state.google_instance = new google.visualization.AreaChart(state.element_chart);
3317 state.google_options.lineWidth = 2;
3318 state.google_instance = new google.visualization.LineChart(state.element_chart);
3322 state.google_instance.draw(datatable, state.google_options);
3325 // ----------------------------------------------------------------------------------------------------------------
3328 NETDATA.easypiechartInitialize = function(callback) {
3329 if(typeof netdataNoEasyPieChart === 'undefined' || !netdataNoEasyPieChart) {
3331 url: NETDATA.easypiechart_js,
3336 NETDATA.registerChartLibrary('easypiechart', NETDATA.easypiechart_js);
3339 NETDATA.error(100, NETDATA.easypiechart_js);
3341 .always(function() {
3342 if(typeof callback === "function")
3347 NETDATA.chartLibraries.easypiechart.enabled = false;
3348 if(typeof callback === "function")
3353 NETDATA.easypiechartChartUpdate = function(state, data) {
3355 state.easypiechart_instance.update();
3358 NETDATA.easypiechartChartCreate = function(state, data) {
3359 var self = $(state.element);
3364 $(state.element_chart).data('data-percent', pcent);
3365 data.element_chart.innerHTML = value.toString();
3367 state.easypiechart_instance = new EasyPieChart(state.element_chart, {
3368 barColor: self.data('easypiechart-barcolor') || '#ef1e25',
3369 trackColor: self.data('easypiechart-trackcolor') || '#f2f2f2',
3370 scaleColor: self.data('easypiechart-scalecolor') || '#dfe0e0',
3371 scaleLength: self.data('easypiechart-scalelength') || 5,
3372 lineCap: self.data('easypiechart-linecap') || 'round',
3373 lineWidth: self.data('easypiechart-linewidth') || 3,
3374 trackWidth: self.data('easypiechart-trackwidth') || undefined,
3375 size: self.data('easypiechart-size') || Math.min(state.chartWidth(), state.chartHeight()),
3376 rotate: self.data('easypiechart-rotate') || 0,
3377 animate: self.data('easypiechart-rotate') || {duration: 0, enabled: false},
3378 easing: self.data('easypiechart-easing') || undefined
3382 // ----------------------------------------------------------------------------------------------------------------
3383 // Charts Libraries Registration
3385 NETDATA.chartLibraries = {
3387 initialize: NETDATA.dygraphInitialize,
3388 create: NETDATA.dygraphChartCreate,
3389 update: NETDATA.dygraphChartUpdate,
3390 setSelection: NETDATA.dygraphSetSelection,
3391 clearSelection: NETDATA.dygraphClearSelection,
3394 format: function(state) { return 'json'; },
3395 options: function(state) { return 'ms|flip'; },
3396 legend: function(state) {
3397 if(this.isSparkline(state) === false)
3398 return 'right-side';
3402 autoresize: function(state) { return true; },
3403 max_updates_to_recreate: function(state) { return 5000; },
3404 track_colors: function(state) { return true; },
3405 pixels_per_point: function(state) {
3406 if(this.isSparkline(state) === false)
3412 isSparkline: function(state) {
3413 if(typeof state.dygraph_sparkline === 'undefined') {
3414 var t = $(state.element).data('dygraph-theme');
3415 if(t === 'sparkline')
3416 state.dygraph_sparkline = true;
3418 state.dygraph_sparkline = false;
3420 return state.dygraph_sparkline;
3424 initialize: NETDATA.sparklineInitialize,
3425 create: NETDATA.sparklineChartCreate,
3426 update: NETDATA.sparklineChartUpdate,
3427 setSelection: function(t) { return true; },
3428 clearSelection: function() { return true; },
3431 format: function(state) { return 'array'; },
3432 options: function(state) { return 'flip|abs'; },
3433 legend: function(state) { return null; },
3434 autoresize: function(state) { return false; },
3435 max_updates_to_recreate: function(state) { return 5000; },
3436 track_colors: function(state) { return false; },
3437 pixels_per_point: function(state) { return 3; }
3440 initialize: NETDATA.peityInitialize,
3441 create: NETDATA.peityChartCreate,
3442 update: NETDATA.peityChartUpdate,
3443 setSelection: function(t) { return true; },
3444 clearSelection: function() { return true; },
3447 format: function(state) { return 'ssvcomma'; },
3448 options: function(state) { return 'null2zero|flip|abs'; },
3449 legend: function(state) { return null; },
3450 autoresize: function(state) { return false; },
3451 max_updates_to_recreate: function(state) { return 5000; },
3452 track_colors: function(state) { return false; },
3453 pixels_per_point: function(state) { return 3; }
3456 initialize: NETDATA.morrisInitialize,
3457 create: NETDATA.morrisChartCreate,
3458 update: NETDATA.morrisChartUpdate,
3459 setSelection: function(t) { return true; },
3460 clearSelection: function() { return true; },
3463 format: function(state) { return 'json'; },
3464 options: function(state) { return 'objectrows|ms'; },
3465 legend: function(state) { return null; },
3466 autoresize: function(state) { return false; },
3467 max_updates_to_recreate: function(state) { return 50; },
3468 track_colors: function(state) { return false; },
3469 pixels_per_point: function(state) { return 15; }
3472 initialize: NETDATA.googleInitialize,
3473 create: NETDATA.googleChartCreate,
3474 update: NETDATA.googleChartUpdate,
3475 setSelection: function(t) { return true; },
3476 clearSelection: function() { return true; },
3479 format: function(state) { return 'datatable'; },
3480 options: function(state) { return ''; },
3481 legend: function(state) { return null; },
3482 autoresize: function(state) { return false; },
3483 max_updates_to_recreate: function(state) { return 300; },
3484 track_colors: function(state) { return false; },
3485 pixels_per_point: function(state) { return 4; }
3488 initialize: NETDATA.raphaelInitialize,
3489 create: NETDATA.raphaelChartCreate,
3490 update: NETDATA.raphaelChartUpdate,
3491 setSelection: function(t) { return true; },
3492 clearSelection: function() { return true; },
3495 format: function(state) { return 'json'; },
3496 options: function(state) { return ''; },
3497 legend: function(state) { return null; },
3498 autoresize: function(state) { return false; },
3499 max_updates_to_recreate: function(state) { return 5000; },
3500 track_colors: function(state) { return false; },
3501 pixels_per_point: function(state) { return 3; }
3504 initialize: NETDATA.easypiechartInitialize,
3505 create: NETDATA.easypiechartChartCreate,
3506 update: NETDATA.easypiechartChartUpdate,
3507 setSelection: function(t) { return true; },
3508 clearSelection: function() { return true; },
3511 format: function(state) { return 'json'; },
3512 options: function(state) { return ''; },
3513 legend: function(state) { return null; },
3514 autoresize: function(state) { return false; },
3515 max_updates_to_recreate: function(state) { return 5000; },
3516 track_colors: function(state) { return false; },
3517 pixels_per_point: function(state) { return 3; }
3521 NETDATA.registerChartLibrary = function(library, url) {
3522 if(NETDATA.options.debug.libraries === true)
3523 console.log("registering chart library: " + library);
3525 NETDATA.chartLibraries[library].url = url;
3526 NETDATA.chartLibraries[library].initialized = true;
3527 NETDATA.chartLibraries[library].enabled = true;
3530 // ----------------------------------------------------------------------------------------------------------------
3533 NETDATA.requiredJs = [
3535 url: NETDATA.serverDefault + 'lib/bootstrap.min.js',
3536 isAlreadyLoaded: function() {
3537 if(typeof $().emulateTransitionEnd == 'function')
3540 if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
3548 url: NETDATA.serverDefault + 'lib/jquery.nanoscroller.min.js',
3549 isAlreadyLoaded: function() { return false; }
3553 NETDATA.requiredCSS = [
3555 url: NETDATA.serverDefault + 'css/bootstrap.min.css',
3556 isAlreadyLoaded: function() {
3557 if(typeof netdataNoBootstrap !== 'undefined' && netdataNoBootstrap)
3564 url: NETDATA.dashboard_css,
3565 isAlreadyLoaded: function() { return false; }
3569 NETDATA.loadRequiredJs = function(index, callback) {
3570 if(index >= NETDATA.requiredJs.length) {
3571 if(typeof callback === 'function')
3576 if(NETDATA.requiredJs[index].isAlreadyLoaded()) {
3577 NETDATA.loadRequiredJs(++index, callback);
3581 if(NETDATA.options.debug.main_loop === true)
3582 console.log('loading ' + NETDATA.requiredJs[index].url);
3585 url: NETDATA.requiredJs[index].url,
3589 .success(function() {
3590 if(NETDATA.options.debug.main_loop === true)
3591 console.log('loaded ' + NETDATA.requiredJs[index].url);
3593 NETDATA.loadRequiredJs(++index, callback);
3596 alert('Cannot load required JS library: ' + NETDATA.requiredJs[index].url);
3600 NETDATA.loadRequiredCSS = function(index) {
3601 if(index >= NETDATA.requiredCSS.length)
3604 if(NETDATA.requiredCSS[index].isAlreadyLoaded()) {
3605 NETDATA.loadRequiredCSS(++index);
3609 if(NETDATA.options.debug.main_loop === true)
3610 console.log('loading ' + NETDATA.requiredCSS[index].url);
3612 NETDATA._loadCSS(NETDATA.requiredCSS[index].url);
3613 NETDATA.loadRequiredCSS(++index);
3616 NETDATA.errorReset();
3617 NETDATA.loadRequiredCSS(0);
3619 NETDATA._loadjQuery(function() {
3620 NETDATA.loadRequiredJs(0, function() {
3621 if(typeof netdataDontStart === 'undefined' || !netdataDontStart) {
3622 if(NETDATA.options.debug.main_loop === true)
3623 console.log('starting chart refresh thread');
3628 if(typeof NETDATA.options.readyCallback === 'function')
3629 NETDATA.options.readyCallback();
3633 // window.NETDATA = NETDATA;
3634 // })(window, document);