-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetrics.js
188 lines (138 loc) · 3.76 KB
/
metrics.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
'use strict';
var _ = require('lodash');
var bunyan = require('bunyan');
var onFinished = require('on-finished');
var url = require('url');
var influx = require('./db');
var log;
function Metrics(options) {
var self = this;
var defaults = {
metricsUrl : 'http://127.0.0.1:8086',
debug : false
};
self.options = options = _.assign(defaults, options);
// Create Bunyan logger
self.log = log = bunyan.createLogger({
name : 'astromo.metrics',
level : options.debug ? bunyan.DEBUG : bunyan.INFO
});
var influxOpts = url.parse(options.metricsUrl);
this.influxClient = new influx({
host : influxOpts.hostname,
port : influxOpts.port,
ssl : influxOpts.protocol === 'https'
});
}
/**
* /!\ Don't throw an error when something goes wrong!
* We still want the API to work even if it's not aggregating data
*/
Metrics.prototype.onError = function(err) {
log.error(err);
};
/**
* Calculates hrtime difference between then and now
* Both in nanoseconds and milliseconds
*/
Metrics.prototype.responseTime = function(hrtime) {
var diff = process.hrtime(hrtime);
var ns = diff[0] * 1e9 + diff[1];
var ms = diff[0] * 1e3 + diff[1] * 1e-6;
return {
ns: ns,
ms: ms.toFixed(3)
};
};
/**
* Capture incoming request data metrics
*/
Metrics.prototype.parseRequest = function(req) {
var self = this;
var host = self.options.host;
var path = req._parsedUrl.pathname;
var search = req._parsedUrl.search;
if (!host)
log.error('No hostname was configured for this proxy.');
return {
'_meta' : {
'host' : host
},
'req': {
'href' : host + path,
'path' : path,
'search' : search
}
};
};
/**
* Capture response data metrics
*/
Metrics.prototype.parseResponse = function(res) {
var delay = this.responseTime(res.req._startAt);
var statusCode = res._header ? res.statusCode : null;
return {
'res': {
'contentLength' : res._headers['content-length'],
'delay' : delay,
'statusCode' : statusCode,
}
};
};
/**
* Assemble correct data structure
*/
Metrics.prototype.assemble = function(metrics) {
var host = url.parse(metrics._meta.host).host;
return {
'database': 'test',
'tags': {
'host' : host,
'path' : metrics.req.path,
'search' : metrics.req.search
},
'points': [
{
'name': 'latency',
'timestamp': metrics.timestamp,
'fields': {
'ms': parseFloat(metrics.res.delay.ms),
'ns': metrics.res.delay.ns
}
}
]
};
};
/**
* Send metrics to the metrics aggregator
*/
Metrics.prototype.sendMetrics = function(metrics) {
log.debug('response code was %s', metrics.res.statusCode);
if (metrics.res.contentLength)
log.debug('Payload size was %s bytes', metrics.res.contentLength);
log.debug('delay: %d%s', metrics.res.delay.ms, 'ms');
metrics = this.assemble(metrics);
this.influxClient.write(metrics);
};
module.exports = function(options) {
var instance = new Metrics(options);
return function(req, res, next) {
res.req = req; // inject the request into the response
var metrics = instance.parseRequest(req);
// add the start timings
if (!req.hasOwnProperty('_startAt'))
req._startAt = process.hrtime();
// Wait for Express to send the response back to the client
onFinished(res, function(err, res) {
if (err)
return instance.onError(err);
// add response data to metrics payload
metrics = _.assign(metrics, instance.parseResponse(res));
// add timestamp for reporting
metrics.timestamp = new Date().toISOString();
log.debug('Collected %j', metrics);
instance.sendMetrics(metrics);
});
next();
};
};