-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathindex.js
More file actions
229 lines (206 loc) · 7.56 KB
/
Copy pathindex.js
File metadata and controls
229 lines (206 loc) · 7.56 KB
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
const express = require('express');
const promClient = require('prom-client');
const UrlValueParser = require('url-value-parser');
const url = require('url');
const os = require('os');
const onFinished = require('on-finished');
const now = require('performance-now');
const _ = require('lodash');
const defaultOpts = {
metricsPath: '/metrics',
enableDurationHistogram: true,
enableDurationSummary: true,
timeBuckets: [0.01, 0.1, 0.5, 1, 5],
quantileBuckets: [0.1, 0.5, 0.95, 0.99],
includeError: false,
includePath: true,
paramIgnores: [],
durationHistogramName: 'http_request_duration_seconds',
durationSummaryName: 'http_request_duration_quantile_seconds',
};
/** Express middleware to add prometheus integration */
class MetricsMiddleware {
/**
* @typedef MetricsOptions
* @type {object}
* @property {string} metricsPath - defines custom metrics path
* @property {number[]} timeBuckets - the buckets to assign to duration histogram (in seconds)
* @property {number[]} quantileBuckets - the quantiles to assign to duration summary (0.0 - 1.0)
* @property {number} quantileMaxAge configures sliding time window for summary (in seconds)
* @property {number} quantileAgeBuckets configures number of sliding time window buckets for summary
* @property {string[]} paramIgnores - array of params _not_ to replace
* @property {boolean} includeError - whether or not to include presence of an unhandled error as a label - defaults to false
* @property {boolean} includePath - whether or not to include the URL path as a metric label - defaults to true
* @property {Function} normalizePath - a `function(req)` - generates path values from the express `req` object
* @property {Function} formatStatusCode - a `function(req)` - generates path values from the express `req` object
* @property {boolean} enableDurationHistogram - whether to enable the request duration histogram (default: true)
* @property {boolean} enableDurationSummary - whether to enable the request duration summary (default: true)
* @property {string} durationHistogramName - the name of the duration histogram metric (if enabled) - must be unique
* @property {string} durationSummaryName - the name of duration summary metric (if enabled) - must be unique
*/
/**
* Create a MetricsMiddleware
*
* @param {MetricsOptions} options - the options
*/
constructor(options = {}) {
_.defaults(options, defaultOpts, {
normalizePath: this.normalizePath.bind(this),
formatStatusCode: this.normalizeStatusCode.bind(this),
quantileMaxAge: 600,
quantileAgeBuckets: 5,
});
this.options = options;
this.router = express.Router();
this.urlValueParser = this.options.urlValueParser || new UrlValueParser();
this.durationMetrics = [];
}
/**
* Initialize the build_info metric
*
* @param {string} ns - the namespace for the metric - usually the name of the service
* @param {string} version - the service's version
* @param {string} revision - the git SHA hash for the running code (usually short-SHA)
*/
initBuildInfo(ns, version, revision) {
if (!ns) {
throw new Error('namespace (ns) must be provided for build_info metric!');
}
const buildInfo = new promClient.Gauge({
name: `${ns}_build_info`,
help: `A metric with a constant 1 value labeled by version, revision, platform, nodeVersion, os from which ${ns} was built`,
labelNames: ['version', 'revision', 'platform', 'nodeVersion', 'os', 'osRelease'],
});
buildInfo.set(
{
version,
revision,
platform: process.release.name,
nodeVersion: process.version,
os: process.platform,
osRelease: os.release(),
},
1,
);
return buildInfo;
}
initRoutes() {
const labelNames = ['status_code', 'method'];
if (this.options.includePath) {
labelNames.push('path');
}
if (this.options.enableDurationSummary) {
this.durationMetrics.push(new promClient.Summary({
name: this.options.durationSummaryName,
help: `duration summary of http responses labeled with: ${labelNames.join(', ')}`,
labelNames,
percentiles: this.options.quantileBuckets,
maxAgeSeconds: this.options.quantileMaxAge,
ageBuckets: this.options.quantileAgeBuckets,
}));
}
if (this.options.enableDurationHistogram) {
this.durationMetrics.push(new promClient.Histogram({
name: this.options.durationHistogramName,
help: `duration histogram of http responses labeled with: ${labelNames.join(', ')}`,
labelNames,
buckets: this.options.timeBuckets,
}));
}
promClient.collectDefaultMetrics();
this.router.get(this.options.metricsPath, this.metricsRoute.bind(this));
this.router.use(this.trackDuration.bind(this));
return this.router;
}
async metricsRoute(req, res) {
if (req.headers['x-forwarded-for']) {
res.writeHead(404);
return res.end('Not Found');
}
res.statusCode = 200;
return res.end(await promClient.register.metrics());
}
trackDuration(req, res, next) {
if (
this.options.excludeRoutes
&& this.matchVsRegExps(req.originalUrl, this.options.excludeRoutes)
) {
return next();
}
const start = now();
onFinished(res, (err, resp) => {
const end = now();
const labels = {
status_code: this.options.formatStatusCode(resp, this.options),
method: req.method,
};
// if we're on a route that has been mounted, resp.req.route.path will be set
if (
this.options.includePath
&& resp.req
&& resp.req.route
&& resp.req.route.path
) {
labels.path = this.options.normalizePath(req, this.options);
}
if (this.options.includeError && !!err) {
labels.error = 'true';
}
const duration = (parseFloat(end.toFixed(9)) - parseFloat(start.toFixed(9))) / 1000;
this.observeDurations(labels, duration);
});
return next();
}
observeDurations(labelValues, duration) {
this.durationMetrics.forEach((metric) => {
metric.observe(labelValues, duration);
});
}
normalizeStatusCode(res) {
return res.status_code || res.statusCode;
}
normalizePath(req) {
let path = url.parse(req.originalUrl).pathname;
path = this.replaceParams(path, req.params);
return this.urlValueParser.replacePathValues(path);
}
replaceParams(path, params) {
let pathValue = path;
if (params) {
Object.keys(params).forEach((param) => {
if (
Object.prototype.hasOwnProperty.call(params, param)
&& !this.options.paramIgnores.includes(param)
) {
pathValue = this.replaceParam(params, param, pathValue);
}
});
}
return pathValue;
}
replaceParam(params, param, path) {
let encoded = encodeURI(params[param]);
if (path.includes(encoded)) {
return path.replace(encoded, `#${param}`);
}
encoded = encodeURIComponent(params[param]);
if (path.includes(encoded)) {
return path.replace(encoded, `#${param}`);
}
if (path.includes(params[param])) {
return encodeURI(path.replace(params[param], `#${param}`));
}
return path;
}
matchVsRegExps(element, regexps) {
if (!element || !regexps) {
return false;
}
return regexps.some((regexp) => (regexp instanceof RegExp && element.match(regexp))
|| element === regexp);
}
}
// export prom-client for use in custom metrics
MetricsMiddleware.promClient = promClient;
MetricsMiddleware.defaultOpts = defaultOpts;
module.exports = MetricsMiddleware;