]> arthur.barton.de Git - netdata.git/blob - node.d/node_modules/netdata.js
added a new element on all charts: context, which is the template upon the chart...
[netdata.git] / node.d / node_modules / netdata.js
1 'use strict';
2
3 var url = require('url');
4 var http = require('http');
5 var util = require('util');
6
7 /*
8 var netdata = require('netdata');
9
10 var example_chart = {
11         id: 'id',                                               // the unique id of the chart
12         name: 'name',                                   // the name of the chart
13         title: 'title',                                 // the title of the chart
14         units: 'units',                                 // the units of the chart dimensions
15         family: 'family',                               // the family of the chart
16         context: 'context',                             // the context of the chart
17         type: netdata.chartTypes.line,  // the type of the chart
18         priority: 0,                                    // the priority relative to others in the same family
19         update_every: 1,                                // the expected update frequency of the chart
20         dimensions: {
21                 'dim1': {
22                         id: 'dim1',                             // the unique id of the dimension
23                         name: 'name',                   // the name of the dimension
24                         algorithm: netdata.chartAlgorithms.absolute,    // the id of the netdata algorithm
25                         multiplier: 1,                  // the multiplier
26                         divisor: 1,                             // the divisor
27                         hidden: false,                  // is hidden (boolean)
28                 },
29                 'dim2': {
30                         id: 'dim2',                             // the unique id of the dimension
31                         name: 'name',                   // the name of the dimension
32                         algorithm: 'absolute',  // the id of the netdata algorithm
33                         multiplier: 1,                  // the multiplier
34                         divisor: 1,                             // the divisor
35                         hidden: false,                  // is hidden (boolean)
36                 }
37                 // add as many dimensions as needed
38         }
39 };
40 */
41
42 var netdata = {
43         options: {
44                 filename: __filename,
45                 DEBUG: false,
46                 update_every: 1,
47         },
48
49         chartAlgorithms: {
50                 incremental: 'incremental',
51                 absolute: 'absolute',
52                 percentage_of_absolute_row: 'percentage-of-absolute-row',
53                 percentage_of_incremental_row: 'percentage-of-incremental-row'
54         },
55
56         chartTypes: {
57                 line: 'line',
58                 area: 'area',
59                 stacked: 'stacked'
60         },
61
62         services: new Array(),
63         modules_configuring: 0,
64         charts: {},
65
66
67         processors: {
68                 http: {
69                         name: 'http',
70
71                         process: function(service, callback) {
72                                 if(netdata.options.DEBUG === true) netdata.debug(service.module.name + ': ' + service.name + ': making ' + this.name + ' request: ' + netdata.stringify(service.request));
73
74                                 var req = http.request(service.request, function(response) {
75                                         if(netdata.options.DEBUG === true) netdata.debug(service.module.name + ': ' + service.name + ': got server response...');
76
77                                         var end = false;
78                                         var data = '';
79                                         response.setEncoding('utf8');
80
81                                         if(response.statusCode !== 200) {
82                                                 if(end === false) {
83                                                         service.error('Got HTTP code ' + response.statusCode + ', failed to get data.');
84                                                         end = true;
85                                                         callback(null);
86                                                 }
87                                         }
88
89                                         response.on('data', function(chunk) {
90                                                 if(end === false) data += chunk;
91                                         });
92
93                                         response.on('error', function() {
94                                                 if(end === false) {
95                                                         service.error(': Read error, failed to get data.');
96                                                         end = true;
97                                                         callback(null);
98                                                 }
99                                         });
100
101                                         response.on('end', function() {
102                                                 if(end === false) {
103                                                         if(netdata.options.DEBUG === true) netdata.debug(service.module.name + ': ' + service.name + ': read completed.');
104                                                         end = true;
105                                                         callback(data);
106                                                 }
107                                         });
108                                 });
109
110                                 req.on('error', function(e) {
111                                         service.error('Failed to make request: ' + netdata.stringify(service.request) + ', message: ' + e.message);
112                                         callback(null);
113                                 });
114
115                                 // write data to request body
116                                 if(typeof service.postData !== 'undefined' && service.request.method === 'POST') {
117                                         if(netdata.options.DEBUG === true) netdata.debug(service.module.name + ': ' + service.name + ': posting data: ' + service.postData);
118                                         req.write(service.postData);
119                                 }
120
121                                 req.end();
122                         }
123                 }
124         },
125
126         stringify: function(obj) {
127                 return util.inspect(obj, {depth: 10});
128         },
129
130         // show debug info, if debug is enabled
131         debug: function(msg) {
132                 if(this.options.DEBUG === true) {
133                         var now = new Date();
134                         console.error(now.toString() + ': ' + netdata.options.filename + ': DEBUG: ' + ((typeof(msg) === 'object')?netdata.stringify(msg):msg).toString());
135                 }
136         },
137
138         // log an error
139         error: function(msg) {
140                 var now = new Date();
141                 console.error(now.toString() + ': ' + netdata.options.filename + ': ERROR: ' + ((typeof(msg) === 'object')?netdata.stringify(msg):msg).toString());
142         },
143
144         // send data to netdata
145         send: function(msg) {
146                 console.log(msg.toString());
147         },
148
149         service: function(service) {
150                 if(typeof service === 'undefined')
151                         service = {};
152
153                 var now = new Date().getTime();
154
155                 service._current_chart = null;  // the current chart we work on
156                 service._queue = '';                    // data to be sent to netdata
157
158                 service.error_reported = false; // error log flood control
159
160                 service.added = false;                  // added to netdata.services
161                 service.enabled = true;
162                 service.updates = 0;
163                 service.running = false;
164                 service.started = 0;
165                 service.ended = 0;
166
167                 if(typeof service.module === 'undefined') {
168                         service.module = { name: 'not-defined-module' };
169                         service.error('Attempted to create service without a module.');
170                         service.enabled = false;
171                 }
172
173                 if(typeof service.name === 'undefined') {
174                         service.name = 'unnamed@' + service.module.name + '/' + now;
175                 }
176
177                 if(typeof service.processor === 'undefined')
178                         service.processor = netdata.processors.http;
179
180                 if(typeof service.update_every === 'undefined')
181                         service.update_every = service.module.update_every;
182
183                 if(typeof service.update_every === 'undefined')
184                         service.update_every = netdata.options.update_every;
185
186                 if(service.update_every < netdata.options.update_every)
187                         service.update_every = netdata.options.update_every;
188
189                 // align the runs
190                 service.next_run = now - (now % (service.update_every * 1000));
191
192                 service.commit = function() {
193                         if(this.added !== true) {
194                                 this.added = true;
195                                 
196                                 var now = new Date().getTime();
197                                 while( this.next_run < now )
198                                         this.next_run += (this.update_every * 1000);
199
200                                 netdata.services.push(this);
201                                 if(netdata.options.DEBUG === true) netdata.debug(this.module.name + ': ' + this.name + ': service committed.');
202                         }
203                 };
204
205                 service.execute = function(callback) {
206                         if(service.enabled === false) {
207                                 callback(null);
208                                 return;
209                         }
210
211                         this.module.active++;
212                         this.running = true;
213                         this.started = new Date().getTime();
214                         this.updates++;
215
216                         if(netdata.options.DEBUG === true)
217                                 netdata.debug(this.module.name + ': ' + this.name + ': making ' + this.processor.name + ' request: ' + netdata.stringify(this));
218
219                         this.processor.process(this, function(response) {
220                                 service.ended = new Date().getTime();
221                                 service.duration = service.ended - service.started;
222
223                                 if(typeof response === 'undefined')
224                                         response = null;
225
226                                 if(response !== null)
227                                         service.errorClear();
228
229                                 if(netdata.options.DEBUG === true)
230                                         netdata.debug(service.module.name + ': ' + service.name + ': processing ' + service.processor.name + ' response (received in ' + (service.ended - service.started).toString() + ' ms)');
231
232                                 callback(service, response);
233
234                                 service.running = false;
235                                 service.module.active--;
236                                 if(service.module.active < 0) {
237                                         service.module.active = 0;
238                                         if(netdata.options.DEBUG === true) netdata.debug(service.module.name + ': active module counter below zero.');
239                                 }
240
241                                 if(service.module.active === 0) {
242                                         // check if we run under configure
243                                         if(service.module.configure_callback !== null) {
244                                                 if(netdata.options.DEBUG === true) netdata.debug(service.module.name + ': configuration finish callback called from processResponse().');
245                                                 var ccallback = service.module.configure_callback;
246                                                 service.module.configure_callback = null;
247                                                 ccallback();
248                                         }
249                                 }
250                         });
251                 };
252
253                 service.update = function() {
254                         if(netdata.options.DEBUG === true) netdata.debug(this.module.name + ': ' + this.name + ': starting data collection...');
255
256                         this.module.update(this, function() {
257                                 if(netdata.options.DEBUG === true) netdata.debug(service.module.name + ': ' + service.name + ': data collection ended in ' + service.duration.toString() + ' ms.');
258                         });
259                 };
260
261                 service.error = function(message) {
262                         if(this.error_reported === false) {
263                                 netdata.error(this.module.name + ': ' + this.name + ': ' + message);
264                                 this.error_reported = true;
265                         }
266                         else if(netdata.options.DEBUG === true)
267                                 netdata.debug(this.module.name + ': ' + this.name + ': ' + message);
268                 };
269
270                 service.errorClear = function() {
271                         this.error_reported = false;
272                 };
273
274                 service.queue = function(txt) {
275                         this._queue += txt + '\n';
276                 };
277
278                 service._send_chart_to_netdata = function(chart) {
279                         // internal function to send a chart to netdata
280                         this.queue('CHART "' + chart.id + '" "' + chart.name + '" "' + chart.title + '" "' + chart.units + '" "' + chart.family + '" "' + chart.context + '" "' + chart.type + '" ' + chart.priority.toString() + ' ' + chart.update_every.toString());
281                         
282                         for(var dim in chart.dimensions) {
283                                 var d = chart.dimensions[dim];
284
285                                 this.queue('DIMENSION "' + d.id + '" "' + d.name + '" "' + d.algorithm + '" ' + d.multiplier.toString() + ' ' + d.divisor.toString() + ' ' + ((d.hidden === true)?'hidden':'').toString());
286                                 d._created = true;
287                                 d._updated = false;
288                         }
289
290                         chart._created = true;
291                         chart._updated = false;
292                 };
293
294                 // begin data collection for a chart
295                 service.begin = function(chart) {
296                         if(this._current_chart !== null && this._current_chart !== chart) {
297                                 this.error('Called begin() for chart ' + chart.id + ' while chart ' + this._current_chart.id + ' is still open. Closing it.');
298                                 this.end();
299                         }
300
301                         if(typeof(chart.id) === 'undefined' || netdata.charts[chart.id] != chart) {
302                                 this.error('Called begin() for chart ' + chart.id + ' that is not mine. Where did you find it? Ignoring it.');
303                                 return false;
304                         }
305
306                         if(netdata.options.DEBUG === true) netdata.debug('setting current chart to ' + chart.id);
307                         this._current_chart = chart;
308                         this._current_chart._began = true;
309
310                         if(this._current_chart._dimensions_count !== 0) {
311                                 if(this._current_chart._created === false || this._current_chart._updated === true)
312                                         this._send_chart_to_netdata(this._current_chart);
313
314                                 var now = this.ended;
315                                 this.queue('BEGIN ' + this._current_chart.id + ' ' + ((this._current_chart._last_updated > 0)?((now - this._current_chart._last_updated) * 1000):'').toString());
316                         }
317                         // else this.error('Called begin() for chart ' + chart.id + ' which is empty.');
318
319                         this._current_chart._last_updated = now;
320                         this._current_chart._began = true;
321                         this._current_chart._counter++;
322
323                         return true;
324                 };
325
326                 // set a collected value for a chart
327                 // we do most things on the first value we attempt to set
328                 service.set = function(dimension, value) {
329                         if(this._current_chart === null) {
330                                 this.error('Called set(' + dimension + ', ' + value + ') without an open chart.');
331                                 return false;
332                         }
333
334                         if(typeof(this._current_chart.dimensions[dimension]) === 'undefined') {
335                                 this.error('Called set(' + dimension + ', ' + value + ') but dimension "' + dimension + '" does not exist in chart "' + this._current_chart.id + '".');
336                                 return false;
337                         }
338
339                         if(typeof value === 'undefined' || value === null)
340                                 return false;
341
342                         if(this._current_chart._dimensions_count !== 0)
343                                 this.queue('SET ' + dimension + ' = ' + value);
344
345                         return true;
346                 };
347
348                 // end data collection for the current chart - after calling begin()
349                 service.end = function() {
350                         if(this._current_chart !== null && this._current_chart._began === false) {
351                                 this.error('Called end() without an open chart.');
352                                 return false;
353                         }
354
355                         if(this._current_chart._dimensions_count !== 0) {
356                                 this.queue('END');
357                                 netdata.send(this._queue);
358                         }
359
360                         this._queue = '';
361                         this._current_chart._began = false;
362                         if(netdata.options.DEBUG === true) netdata.debug('sent chart ' + this._current_chart.id);
363                         this._current_chart = null;
364                         return true;
365                 };
366
367                 // discard the collected values for the current chart - after calling begin()
368                 service.flush = function() {
369                         if(this._current_chart === null || this._current_chart._began === false) {
370                                 this.error('Called flush() without an open chart.');
371                                 return false;
372                         }
373
374                         this._queue = '';
375                         this._current_chart._began = false;
376                         this._current_chart = null;
377                         return true;
378                 };
379
380                 // create a netdata chart
381                 service.chart = function(id, chart) {
382                         if(typeof(netdata.charts[id]) === 'undefined') {
383                                 netdata.charts[id] = {
384                                         _created: false,
385                                         _updated: true,
386                                         _began: false,
387                                         _counter: 0,
388                                         _last_updated: 0,
389                                         _dimensions_count: 0,
390                                         id: id,
391                                         name: id,
392                                         title: 'untitled chart',
393                                         units: 'a unit',
394                                         family: '',
395                                         context: '',
396                                         type: netdata.chartTypes.line,
397                                         priority: 50000,
398                                         update_every: netdata.options.update_every,
399                                         dimensions: {}
400                                 };
401                         }
402
403                         var c = netdata.charts[id];
404
405                         if(typeof(chart.name) !== 'undefined' && chart.name !== c.name) {
406                                 if(netdata.options.DEBUG === true) netdata.debug('chart ' + id + ' updated its name');
407                                 c.name = chart.name;
408                                 c._updated = true;
409                         }
410
411                         if(typeof(chart.title) !== 'undefined' && chart.title !== c.title) {
412                                 if(netdata.options.DEBUG === true) netdata.debug('chart ' + id + ' updated its title');
413                                 c.title = chart.title;
414                                 c._updated = true;
415                         }
416
417                         if(typeof(chart.units) !== 'undefined' && chart.units !== c.units) {
418                                 if(netdata.options.DEBUG === true) netdata.debug('chart ' + id + ' updated its units');
419                                 c.units = chart.units;
420                                 c._updated = true;
421                         }
422
423                         if(typeof(chart.family) !== 'undefined' && chart.family !== c.family) {
424                                 if(netdata.options.DEBUG === true) netdata.debug('chart ' + id + ' updated its family');
425                                 c.family = chart.family;
426                                 c._updated = true;
427                         }
428
429                         if(typeof(chart.context) !== 'undefined' && chart.context !== c.context) {
430                                 if(netdata.options.DEBUG === true) netdata.debug('chart ' + id + ' updated its context');
431                                 c.context = chart.context;
432                                 c._updated = true;
433                         }
434
435                         if(typeof(chart.type) !== 'undefined' && chart.type !== c.type) {
436                                 if(netdata.options.DEBUG === true) netdata.debug('chart ' + id + ' updated its type');
437                                 c.type = chart.type;
438                                 c._updated = true;
439                         }
440
441                         if(typeof(chart.priority) !== 'undefined' && chart.priority !== c.priority) {
442                                 if(netdata.options.DEBUG === true) netdata.debug('chart ' + id + ' updated its priority');
443                                 c.priority = chart.priority;
444                                 c._updated = true;
445                         }
446
447                         if(typeof(chart.update_every) !== 'undefined' && chart.update_every !== c.update_every) {
448                                 if(netdata.options.DEBUG === true) netdata.debug('chart ' + id + ' updated its update_every from ' + c.update_every + ' to ' + chart.update_every);
449                                 c.update_every = chart.update_every;
450                                 c._updated = true;
451                         }
452
453                         if(typeof(chart.dimensions) !== 'undefined') {
454                                 for(var x in chart.dimensions) {
455                                         if(typeof(c.dimensions[x]) === 'undefined') {
456                                                 c._dimensions_count++;
457
458                                                 c.dimensions[x] = {
459                                                         _created: false,
460                                                         _updated: false,
461                                                         id: x,                                  // the unique id of the dimension
462                                                         name: x,                                // the name of the dimension
463                                                         algorithm: netdata.chartAlgorithms.absolute,    // the id of the netdata algorithm
464                                                         multiplier: 1,                  // the multiplier
465                                                         divisor: 1,                             // the divisor
466                                                         hidden: false,                  // is hidden (boolean)
467                                                 };
468
469                                                 if(netdata.options.DEBUG === true) netdata.debug('chart ' + id + ' created dimension ' + x);
470                                                 c._updated = true;
471                                         }
472
473                                         var dim = chart.dimensions[x];
474                                         var d = c.dimensions[x];
475
476                                         if(typeof(dim.name) !== 'undefined' && d.name !== dim.name) {
477                                                 if(netdata.options.DEBUG === true) netdata.debug('chart ' + id + ', dimension ' + x + ' updated its name');
478                                                 d.name = dim.name;
479                                                 d._updated = true;
480                                         }
481
482                                         if(typeof(dim.algorithm) !== 'undefined' && d.algorithm !== dim.algorithm) {
483                                                 if(netdata.options.DEBUG === true) netdata.debug('chart ' + id + ', dimension ' + x + ' updated its algorithm from ' + d.algorithm + ' to ' + dim.algorithm);
484                                                 d.algorithm = dim.algorithm;
485                                                 d._updated = true;
486                                         }
487
488                                         if(typeof(dim.multiplier) !== 'undefined' && d.multiplier !== dim.multiplier) {
489                                                 if(netdata.options.DEBUG === true) netdata.debug('chart ' + id + ', dimension ' + x + ' updated its multiplier');
490                                                 d.multiplier = dim.multiplier;
491                                                 d._updated = true;
492                                         }
493
494                                         if(typeof(dim.divisor) !== 'undefined' && d.divisor !== dim.divisor) {
495                                                 if(netdata.options.DEBUG === true) netdata.debug('chart ' + id + ', dimension ' + x + ' updated its divisor');
496                                                 d.divisor = dim.divisor;
497                                                 d._updated = true;
498                                         }
499
500                                         if(typeof(dim.hidden) !== 'undefined' && d.hidden !== dim.hidden) {
501                                                 if(netdata.options.DEBUG === true) netdata.debug('chart ' + id + ', dimension ' + x + ' updated its hidden status');
502                                                 d.hidden = dim.hidden;
503                                                 d._updated = true;
504                                         }
505
506                                         if(d._updated) c._updated = true;
507                                 }
508                         }
509
510                         //if(netdata.options.DEBUG === true) netdata.debug(netdata.charts);
511                         return netdata.charts[id];
512                 };
513
514                 return service;
515         },
516
517         runAllServices: function() {
518                 if(netdata.options.DEBUG === true) netdata.debug('runAllServices()');
519
520                 var now = new Date().getTime();
521                 var len = netdata.services.length;
522                 while(len--) {
523                         var service = netdata.services[len];
524
525                         if(service.enabled === false || service.running === true) continue;
526                         if(now <= service.next_run) continue;
527
528                         service.update();
529
530                         now = new Date().getTime();
531                         while(service.next_run < now)
532                                 service.next_run += (service.update_every * 1000);
533                 }
534
535                 // 1/10th of update_every in pause
536                 setTimeout(netdata.runAllServices, netdata.options.update_every * 100);
537         },
538
539         start: function() {
540                 if(netdata.options.DEBUG === true) this.debug('started, services: ' + netdata.stringify(this.services));
541
542                 if(this.services.length === 0) {
543                         this.disableNodePlugin();
544                         process.exit(1);
545                 }
546                 else this.runAllServices();
547         },
548
549         // disable the whole node.js plugin
550         disableNodePlugin: function() {
551                 this.send('DISABLE');
552                 process.exit(1);
553         },
554
555         requestFromParams: function(protocol, hostname, port, path, method) {
556                 return {
557                         protocol: protocol,
558                         hostname: hostname,
559                         port: port,
560                         path: path,
561                         //family: 4,
562                         method: method,
563                         headers: {
564                                 'Content-Type': 'application/x-www-form-urlencoded',
565                                 'Connection': 'keep-alive'
566                         },
567                         agent: new http.Agent({
568                                 keepAlive: true,
569                                 keepAliveMsecs: netdata.options.update_every * 1000,
570                                 maxSockets: 2, // it must be 2 to work
571                                 maxFreeSockets: 1
572                         })
573                 };
574         },
575
576         requestFromURL: function(a_url) {
577                 var u = url.parse(a_url);
578                 return netdata.requestFromParams(u.protocol, u.hostname, u.port, u.path, 'GET');
579         },
580
581         configure: function(module, config, callback) {
582                 if(netdata.options.DEBUG === true) this.debug(module.name + ': configuring (update_every: ' + this.options.update_every + ')...');
583
584                 module.active = 0;
585                 module.update_every = this.options.update_every;
586
587                 if(typeof config.update_every !== 'undefined')
588                         module.update_every = config.update_every;
589
590                 module.enable_autodetect = (config.enable_autodetect)?true:false;
591
592                 if(typeof(callback) === 'function')
593                         module.configure_callback = callback;
594                 else
595                         module.configure_callback = null;
596
597                 var added = module.configure(config);
598
599                 if(netdata.options.DEBUG === true) this.debug(module.name + ': configured, reporting ' + added + ' eligible services.');
600
601                 if(module.configure_callback !== null && added === 0) {
602                         if(netdata.options.DEBUG === true) this.debug(module.name + ': configuration finish callback called from configure().');
603                         module.configure_callback = null;
604                         callback();
605                 }
606
607                 return added;
608         }
609 };
610
611 if(netdata.options.DEBUG === true) netdata.debug('loaded netdata from: ' + __filename);
612 module.exports = netdata;