forked from defunctzombie/node-influx-collector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
120 lines (90 loc) · 2.52 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
108
109
110
111
112
113
114
115
116
117
118
119
120
var EventEmitter = require('events').EventEmitter;
var superagent = require('superagent');
var url = require('url');
// http://influxdb.com/docs/v0.7/api/reading_and_writing_data.html
function Collector(uri) {
if (!(this instanceof Collector)) {
return new Collector(uri);
}
var self = this;
if (!uri) {
return;
}
var parsed = url.parse(uri, true /* parse query args */);
var info = {
protocol: parsed.protocol,
slashes: parsed.slashes,
port: parsed.port,
auth: parsed.auth,
hostname: parsed.hostname,
pathname: '/db' + parsed.pathname + '/series',
};
self._uri = url.format(info);
self.collections = Object.create(null);
var opt = parsed.query || {};
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._uri) {
return;
}
var body = [];
Object.keys(self.collections).forEach(function(key) {
body.push(self.collections[key]);
});
if (body.length === 0) {
return;
}
superagent
.post(self._uri)
.query({ time_precision: self._time_precision })
.send(body)
.end(function(err, res) {
if (err) {
return self.emit('error', err);
}
if (res.status !== 200) {
return self.emit('error', new Error(res.text));
}
});
self.collections = [];
};
Collector.prototype.collect = function(series, obj) {
var self = this;
if (!self._uri) {
return;
}
var collections = self.collections;
var keys = Object.keys(obj).sort();
var key = series + keys.join('');
var collection = self.collections[key];
if (!collection) {
collection = self.collections[key] = {
name: series,
columns: keys,
points: []
};
}
var points = new Array(keys.lenth);
for (var i=0 ; i<keys.length ; ++i) {
points[i] = obj[keys[i]];
}
collection.points.push(points);
if (self._instant_flush) {
self.flush();
}
};
module.exports = Collector;