-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
107 lines (83 loc) · 2.55 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
var EventEmitter = require('events').EventEmitter;
var influx = require('influx');
var url = require('url');
// create a collector for the given series
function Collector(series, uri) {
if (!(this instanceof Collector)) {
return new Collector(series, uri);
}
var self = this;
if (!uri) {
return;
}
if (!series) {
throw new Error('series name must be specified');
}
var parsed = url.parse(uri, true /* parse query args */);
var username = undefined;
var password = undefined;
if (parsed.auth) {
var parts = parsed.auth.split(':');
username = parts.shift();
password = parts.shift();
}
self._client = influx({
host : parsed.hostname,
port : parsed.port,
protocol : parsed.protocol,
username : username,
password : password,
database : parsed.pathname.slice(1) // remove leading '/'
})
self._points = [];
var opt = parsed.query || {};
self._series_name = series;
self._instant_flush = opt.instantFlush == 'yes';
self._time_precision = opt.time_precision;
// no automatic flush
if (opt.autoFlush == 'no' || self._instant_flush) {
return;
}
var flush_interval = opt.flushInterval || 5000;
// flush on an interval
// or option to auto_flush=false
setInterval(function() {
self.flush();
}, flush_interval).unref();
}
Collector.prototype.__proto__ = EventEmitter.prototype;
Collector.prototype.flush = function() {
var self = this;
if (!self._points || self._points.length === 0) {
return;
}
// only send N points at a time to avoid making requests too large
// TODO what if we are backed up?
var points = self._points.splice(0, 50);
var opt = { precision: self._time_precision };
self._client.writePoints(self._series_name, points, opt, function(err) {
if (err) {
// TODO if error put points back to send again?
return self.emit('error', err);
}
// there are more points to flush out
if (self._points.length >0) {
setImmediate(self.flush.bind(self));
}
});
};
// collect a data point (or object)
// @param [Object] value the data
// @param [Object] tags the tags (optional)
Collector.prototype.collect = function(value, tags) {
var self = this;
// disabled (due to no URL)
if (!self._points) {
return;
}
self._points.push([value, tags]);
if (self._instant_flush) {
self.flush();
}
};
module.exports = Collector;