This repository has been archived by the owner on Oct 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 97
/
prometheus-stats.ts
303 lines (277 loc) · 8.6 KB
/
prometheus-stats.ts
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
298
299
300
301
302
303
/**
* Copyright 2018, OpenCensus Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
AggregationType,
DistributionData,
ExporterConfig,
logger,
Logger,
Measurement,
StatsEventListener,
TagKey,
TagValue,
View,
} from '@opencensus/core';
import * as express from 'express';
import * as http from 'http';
import {
Counter,
Gauge,
Histogram,
labelValues,
Metric,
Registry,
} from 'prom-client';
export interface PrometheusExporterOptions extends ExporterConfig {
/** App prefix for metrics, if needed - default opencensus */
prefix?: string;
/**
* Port number for Prometheus exporter server
* Default registered port is 9464:
* https://github.com/prometheus/prometheus/wiki/Default-port-allocations
*/
port?: number;
/**
* Define if the Prometheus exporter server will be started - default false
*/
startServer?: boolean;
}
/** Format and sends Stats to Prometheus exporter */
export class PrometheusStatsExporter implements StatsEventListener {
static readonly DEFAULT_OPTIONS = {
port: 9464,
startServer: false,
contentType: 'text/plain; text/plain; version=0.0.15; charset=utf-8',
prefix: '',
};
private logger: Logger;
private prefix: string;
private port: number;
private app = express();
private server?: http.Server;
// Registry instance from Prometheus to keep the metrics
private registry = new Registry();
// Histogram cannot have a label named 'le'
private static readonly RESERVED_HISTOGRAM_LABEL = 'le';
constructor(options: PrometheusExporterOptions) {
this.logger = options.logger || logger.logger();
this.port = options.port || PrometheusStatsExporter.DEFAULT_OPTIONS.port;
this.prefix =
options.prefix || PrometheusStatsExporter.DEFAULT_OPTIONS.prefix;
/** Start the server if the startServer option is true */
if (options.startServer) {
this.startServer();
}
}
/**
* Not used because registering metrics requires information that is
* present in Measurement objects
* @param view
*/
onRegisterView(view: View) {}
/**
* Method called every new stats' record
* @param views The views related to the measurement
* @param measurement The recorded measurement
* @param tags The tags to which the value is applied
*/
onRecord(
views: View[],
measurement: Measurement,
tags: Map<TagKey, TagValue>
) {
for (const view of views) {
this.updateMetric(view, measurement, tags);
}
}
/**
* Starts the Prometheus exporter that polls Metric from Metrics library and
* send batched data to backend.
*/
start(): void {
// TODO(mayurkale): add setInterval here to poll Metric, transform and send
// // it to backend (dependency with PR#253).
}
/** Stops the exporter. */
stop(): void {
this.stopServer();
}
private getLabelValues(
columns: TagKey[],
tags: Map<TagKey, TagValue>
): labelValues {
const labels: labelValues = {};
// TODO: Consider make original tags map with string:TagValue type.
const tagsWithStringKey: Map<string, TagValue | undefined> = new Map();
for (const key of tags.keys()) {
tagsWithStringKey.set(key.name, tags.get(key));
}
columns.forEach(tagKey => {
if (tagsWithStringKey.has(tagKey.name)) {
const tagValue = tagsWithStringKey.get(tagKey.name);
if (tagValue) {
labels[tagKey.name] = tagValue.value;
}
}
});
return labels;
}
/**
* Register or get a metric in Prometheus
* @param view View will be used to register the metric
* @param labels Object with label keys and values
*/
private registerMetric(view: View, tags: Map<TagKey, TagValue>): Metric {
const metricName = this.getPrometheusMetricName(view);
/** Get metric if already registered */
let metric = this.registry.getSingleMetric(metricName);
// Return metric if already registered
if (metric) {
return metric;
}
const labelNames = view.getColumns().map(tagKey => tagKey.name);
// Create a new metric if there is no one
const metricObj = { name: metricName, help: view.description, labelNames };
// Creating the metric based on aggregation type
switch (view.aggregation) {
case AggregationType.COUNT:
metric = new Counter(metricObj);
break;
case AggregationType.SUM:
case AggregationType.LAST_VALUE:
metric = new Gauge(metricObj);
break;
case AggregationType.DISTRIBUTION:
this.validateDisallowedLeLabelForHistogram(labelNames);
const distribution = {
name: metricName,
help: view.description,
labelNames,
buckets: this.getBoundaries(view, tags),
};
metric = new Histogram(distribution);
break;
default:
this.logger.error(`Aggregation ${view.aggregation} is not supported`);
}
this.registry.registerMetric(metric);
return metric;
}
/**
* Update the metric from a measurement value
* @param view View will be used to update the metric
* @param measurement Measurement with the new value to update the metric
*/
private updateMetric(
view: View,
measurement: Measurement,
tags: Map<TagKey, TagValue>
) {
const metric = this.registerMetric(view, tags);
// Updating the metric based on metric instance type and aggregation type
const labelValues = this.getLabelValues(view.getColumns(), tags);
if (metric instanceof Counter) {
metric.inc(labelValues);
} else if (
view.aggregation === AggregationType.SUM &&
metric instanceof Gauge
) {
metric.inc(labelValues, measurement.value);
} else if (
view.aggregation === AggregationType.LAST_VALUE &&
metric instanceof Gauge
) {
metric.set(labelValues, measurement.value);
} else if (metric instanceof Histogram) {
metric.observe(labelValues, measurement.value);
} else {
this.logger.error('Metric not supported');
}
}
/**
* Build a metric name from view name
* @param view View used to build the metric name
*/
private getPrometheusMetricName(view: View): string {
let metricName;
if (this.prefix) {
metricName = `${this.prefix}_${view.name}`;
} else {
metricName = view.name;
}
return this.sanitizePrometheusMetricName(metricName);
}
/**
* Sanitize metric name
* @param name string The name of the metric.
*/
private sanitizePrometheusMetricName(name: string): string {
// replace all characters other than [A-Za-z0-9_].
return name.replace(/\W/g, '_');
}
/**
* Throws an error labels contain "le" label name in histogram label names.
*/
private validateDisallowedLeLabelForHistogram(labels: string[]): void {
labels.forEach(label => {
if (label === PrometheusStatsExporter.RESERVED_HISTOGRAM_LABEL) {
throw new Error(
`${PrometheusStatsExporter.RESERVED_HISTOGRAM_LABEL} is a reserved label keyword`
);
}
});
}
/**
* Get the boundaries from buckets
* @param view View used to get the DistributionData
* @param tags Tags used to get the DistributionData
*/
private getBoundaries(view: View, tags: Map<TagKey, TagValue>): number[] {
const tagValues = view.getColumns().map(tagKey => tags.get(tagKey) || null);
const data = view.getSnapshot(tagValues) as DistributionData;
return data.buckets;
}
/**
* Start the Prometheus exporter server
*/
startServer(callback?: () => void) {
const self = this;
this.app.get('/metrics', (req, res) => {
res.set(
'Content-Type',
PrometheusStatsExporter.DEFAULT_OPTIONS.contentType
);
res.end(this.registry.metrics());
});
this.server = this.app.listen(this.port, () => {
self.logger.debug('Prometheus Exporter started on port ' + self.port);
if (callback) {
callback();
}
});
}
/**
* Stop the Prometheus exporter server
* @param callback
*/
stopServer(callback?: () => void) {
if (this.server) {
this.registry.clear();
this.server.close(callback);
this.logger.debug('Prometheus Exporter shutdown');
}
}
}