-
Notifications
You must be signed in to change notification settings - Fork 0
/
MetricsListener.js
297 lines (247 loc) · 8.18 KB
/
MetricsListener.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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import {parse as urlParse} from 'url';
import Moment from 'moment';
import SystemInformation from 'systeminformation';
const DEFAULT_PATH_PREFIX = '/metrics';
const DEFAULT_INTERVAL = 1000;
export default class MetricsListener {
constructor(apiPath, interval) {
apiPath = apiPath || DEFAULT_PATH_PREFIX;
while (apiPath.endsWith('/')) {
apiPath = apiPath.substring(0, apiPath.length - 1);
}
if (!apiPath) {
apiPath = DEFAULT_PATH_PREFIX;
}
if (!Number.isInteger(interval) || interval < 1) {
interval = DEFAULT_INTERVAL;
}
this.apiPath = apiPath;
this.interval = interval;
this._initializeDefaults();
this._initCpuMonitoring();
this._initNetworkMonitoring();
return this.requestListener();
}
_initializeDefaults() {
// defaults
this.requestCount = 0;
this.lastCpuData = {
'dateCaptured': 0,
'avgload': 0,
'currentload': 0,
'currentload_user': 0,
'currentload_system': 0,
'currentload_nice': 0,
'currentload_idle': 100,
'currentload_irq': 0,
'raw_currentload': 0,
'raw_currentload_user': 0,
'raw_currentload_system': 0,
'raw_currentload_nice': 0,
'raw_currentload_idle': 0,
'raw_currentload_irq': 0,
'cpus': []
};
this.lastNetworkData = {
'dateCaptured': 0,
'iface': 'unknown',
'operstate': 'unknown',
'rx': 0,
'tx': 0,
'rx_sec': -1,
'tx_sec': -1,
'ms': 0
};
this.lastCpuError = null;
this.lastNetworkError = null;
}
_initCpuMonitoring() {
this.cpuIntervals = 0;
SystemInformation.currentLoad()
.then((_ignoreFirst) => {
// assure we track first call successfully
this.cpuIntervals++;
return _ignoreFirst;
})
.catch((error) => {
this.lastCpuError = error;
// first call failed, doesn't really matter we just want to interval forever
// allow promise chain to continue
})
.then((_ignoreFirst) => {
setInterval(() => {
SystemInformation.currentLoad()
.then((stats) => {
// only update stats on 2nd call
if (++this.cpuIntervals > 1) {
stats['dateCaptured'] = Moment.utc().unix();
this.lastCpuData = stats;
// on success we will remove last error always
this.lastCpuError = null;
}
})
.catch((error) => {
// we can at least propagate this through to caller
this.lastCpuError = error;
});
}, this.interval);
});
}
_initNetworkMonitoring() {
this.networkIntervals = 0;
SystemInformation.networkInterfaceDefault()
.then((nic) => {
// run network stats once (to initialize tx_sec/rx_sec start values)
return SystemInformation.networkStats(nic)
.then((_ignoreFirst) => {
// assure we track first call successfully
this.networkIntervals++;
return _ignoreFirst;
})
.catch((error) => {
this.lastNetworkError = error;
// first call failed, doesn't really matter we just want to interval forever
// allow promise chain to continue
})
.then((_ignoreFirst) => {
// begin interval to grab throughput data in background
setInterval(() => {
SystemInformation.networkStats(nic)
.then((stats) => {
if (++this.networkIntervals > 1) {
stats['dateCaptured'] = Moment.utc().unix();
this.lastNetworkData = stats;
this.lastNetworkError = null;
}
});
}, this.interval);
});
})
.catch((error) => {
// failed to acquire default interface, that's not good
this.lastNetworkError = error;
// attempt to start background interval again after brief wait
setTimeout(() => {
this._initNetworkMonitoring();
}, 1000);
});
}
requestListener() {
return (req, res) => {
let urlObj = urlParse(req.url);
if (urlObj.pathname !== this.apiPath && !urlObj.pathname.startsWith(`${this.apiPath}/`)) {
// we won't be handling this request at all
// but we'll still be counting requests
this.requestCount++;
return;
}
// claim ownership of request ASAP, downstream requestListeners will know to ignore
req.requestHandled = true;
switch (urlObj.pathname) {
case `${this.apiPath}/health`:
res.statusCode = 200;
res.end('ok');
break;
case `${this.apiPath}/requests/total`:
successResponse(res, `{"metric": ${this.requestCount}}`);
break;
case `${this.apiPath}/cpu`:
if (this.lastCpuError) {
errorResponse(res, this.lastCpuError);
} else {
successResponse(res, this.lastCpuData);
}
break;
case `${this.apiPath}/memory`:
SystemInformation.mem()
.then((memStats) => {
memStats['dateCaptured'] = Moment.utc().unix();
successResponse(res, memStats);
})
.catch((error) => {
errorResponse(res, error);
});
break;
case `${this.apiPath}/network`:
if (this.lastNetworkError) {
errorResponse(res, this.lastNetworkError);
} else {
successResponse(res, this.lastNetworkData);
}
break;
case `${this.apiPath}/network/rx`:
if (this.lastNetworkError) {
errorResponse(res, this.lastNetworkError);
} else {
successResponse(res, `{"metric": ${this.lastNetworkData.rx}}`);
}
break;
case `${this.apiPath}/network/tx`:
if (this.lastNetworkError) {
errorResponse(res, this.lastNetworkError);
} else {
successResponse(res, `{"metric": ${this.lastNetworkData.tx}}`);
}
break;
case `${this.apiPath}/all`:
SystemInformation.mem()
.then((memStats) => {
memStats['dateCaptured'] = Moment.utc().unix();
if (this.lastCpuError || this.lastNetworkError) {
let errors = {};
if (this.lastCpuError) {
errors.cpu = this.lastCpuError;
}
if (this.lastNetworkError) {
errors.network = this.lastNetworkError;
}
errorResponse(res, errors);
return;
}
let data = {
cpu: this.lastCpuData,
memory: memStats,
network: this.lastNetworkData
};
successResponse(res, data);
})
.catch((error) => {
let errors = {
memory: error
};
if (this.lastCpuError) {
errors.cpu = this.lastCpuError;
}
if (this.lastNetworkError) {
errors.network = this.lastNetworkError;
}
errorResponse(res, errors);
});
break;
default:
// ignore health and metric queries for request count
this.requestCount++;
// because we are taking full responsibility of handling request, we will return 404
res.statusCode = 404;
res.end();
break;
}
};
}
}
function successResponse(res, stat) {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
let body = typeof stat === 'string'
? stat
: JSON.stringify(stat);
res.end(body);
}
function errorResponse(res, error) {
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
let body = typeof error === 'string'
? error
: JSON.stringify(error);
res.end(body);
}