-
Notifications
You must be signed in to change notification settings - Fork 836
/
Copy pathPrometheusExporter.ts
220 lines (205 loc) · 6.33 KB
/
PrometheusExporter.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
/*
* Copyright The OpenTelemetry 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
*
* https://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 { diag } from '@opentelemetry/api';
import {
globalErrorHandler,
} from '@opentelemetry/core';
import {
Aggregation,
AggregationTemporality,
MetricReader
} from '@opentelemetry/sdk-metrics';
import {
createServer,
IncomingMessage,
Server,
ServerResponse
} from 'http';
import { ExporterConfig } from './export/types';
import { PrometheusSerializer } from './PrometheusSerializer';
/** Node.js v8.x compat */
import { URL } from 'url';
export class PrometheusExporter extends MetricReader {
static readonly DEFAULT_OPTIONS = {
host: undefined,
port: 9464,
endpoint: '/metrics',
prefix: '',
appendTimestamp: true,
};
private readonly _host?: string;
private readonly _port: number;
private readonly _baseUrl: string;
private readonly _endpoint: string;
private readonly _server: Server;
private readonly _prefix?: string;
private readonly _appendTimestamp: boolean;
private _serializer: PrometheusSerializer;
// This will be required when histogram is implemented. Leaving here so it is not forgotten
// Histogram cannot have a attribute named 'le'
// private static readonly RESERVED_HISTOGRAM_LABEL = 'le';
/**
* Constructor
* @param config Exporter configuration
* @param callback Callback to be called after a server was started
*/
constructor(config: ExporterConfig = {}, callback?: () => void) {
super({
aggregationSelector: _instrumentType => Aggregation.Default(),
aggregationTemporalitySelector: _instrumentType => AggregationTemporality.CUMULATIVE
});
this._host =
config.host ||
process.env.OTEL_EXPORTER_PROMETHEUS_HOST ||
PrometheusExporter.DEFAULT_OPTIONS.host;
this._port =
config.port ||
Number(process.env.OTEL_EXPORTER_PROMETHEUS_PORT) ||
PrometheusExporter.DEFAULT_OPTIONS.port;
this._prefix = config.prefix || PrometheusExporter.DEFAULT_OPTIONS.prefix;
this._appendTimestamp =
typeof config.appendTimestamp === 'boolean'
? config.appendTimestamp
: PrometheusExporter.DEFAULT_OPTIONS.appendTimestamp;
// unref to prevent prometheus exporter from holding the process open on exit
this._server = createServer(this._requestHandler).unref();
this._serializer = new PrometheusSerializer(
this._prefix,
this._appendTimestamp
);
this._baseUrl = `http://${this._host}:${this._port}/`;
this._endpoint = (
config.endpoint || PrometheusExporter.DEFAULT_OPTIONS.endpoint
).replace(/^([^/])/, '/$1');
if (config.preventServerStart !== true) {
this.startServer()
.then(callback)
.catch(err => diag.error(err));
} else if (callback) {
callback();
}
}
override async onForceFlush(): Promise<void> {
/** do nothing */
}
/**
* Shuts down the export server and clears the registry
*/
override onShutdown(): Promise<void> {
return this.stopServer();
}
/**
* Stops the Prometheus export server
*/
stopServer(): Promise<void> {
if (!this._server) {
diag.debug(
'Prometheus stopServer() was called but server was never started.'
);
return Promise.resolve();
} else {
return new Promise(resolve => {
this._server.close(err => {
if (!err) {
diag.debug('Prometheus exporter was stopped');
} else {
if (
((err as unknown) as { code: string }).code !==
'ERR_SERVER_NOT_RUNNING'
) {
globalErrorHandler(err);
}
}
resolve();
});
});
}
}
/**
* Starts the Prometheus export server
*/
startServer(): Promise<void> {
return new Promise(resolve => {
this._server.listen(
{
port: this._port,
host: this._host,
},
() => {
diag.debug(
`Prometheus exporter server started: ${this._host}:${this._port}/${this._endpoint}`
);
resolve();
}
);
});
}
/**
* Request handler that responds with the current state of metrics
* @param _request Incoming HTTP request of server instance
* @param response HTTP response objet used to response to request
*/
public getMetricsRequestHandler(
_request: IncomingMessage,
response: ServerResponse
): void {
this._exportMetrics(response);
}
/**
* Request handler used by http library to respond to incoming requests
* for the current state of metrics by the Prometheus backend.
*
* @param request Incoming HTTP request to export server
* @param response HTTP response object used to respond to request
*/
private _requestHandler = (
request: IncomingMessage,
response: ServerResponse
) => {
if (request.url != null && new URL(request.url, this._baseUrl).pathname === this._endpoint) {
this._exportMetrics(response);
} else {
this._notFound(response);
}
};
/**
* Responds to incoming message with current state of all metrics.
*/
private _exportMetrics = (response: ServerResponse) => {
response.statusCode = 200;
response.setHeader('content-type', 'text/plain');
this.collect()
.then(
collectionResult => {
const { resourceMetrics, errors } = collectionResult;
if (errors.length) {
diag.error('PrometheusExporter: metrics collection errors', ...errors);
}
response.end(this._serializer.serialize(resourceMetrics));
},
err => {
response.end(`# failed to export metrics: ${err}`);
}
);
};
/**
* Responds with 404 status code to all requests that do not match the configured endpoint.
*/
private _notFound = (response: ServerResponse) => {
response.statusCode = 404;
response.end();
};
}