-
Notifications
You must be signed in to change notification settings - Fork 834
/
Copy pathOTLPMetricExporter.test.ts
304 lines (287 loc) · 10.2 KB
/
OTLPMetricExporter.test.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
304
/*
* 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 * as protoLoader from '@grpc/proto-loader';
import {
Counter,
ValueObserver,
ValueRecorder,
} from '@opentelemetry/api-metrics';
import { diag } from '@opentelemetry/api';
import { otlpTypes } from '@opentelemetry/exporter-otlp-http';
import * as metrics from '@opentelemetry/sdk-metrics-base';
import * as assert from 'assert';
import * as fs from 'fs';
import * as grpc from '@grpc/grpc-js';
import * as path from 'path';
import * as sinon from 'sinon';
import { OTLPMetricExporter } from '../src';
import {
ensureExportedCounterIsCorrect,
ensureExportedObserverIsCorrect,
ensureExportedValueRecorderIsCorrect,
ensureMetadataIsCorrect,
ensureResourceIsCorrect,
mockCounter,
mockObserver,
mockValueRecorder,
} from './helper';
const metricsServiceProtoPath =
'opentelemetry/proto/collector/metrics/v1/metrics_service.proto';
const includeDirs = [path.resolve(__dirname, '../protos')];
const address = 'localhost:1501';
type TestParams = {
useTLS?: boolean;
metadata?: grpc.Metadata;
};
const metadata = new grpc.Metadata();
metadata.set('k', 'v');
const testOTLPMetricExporter = (params: TestParams) =>
describe(`OTLPMetricExporter - node ${
params.useTLS ? 'with' : 'without'
} TLS, ${params.metadata ? 'with' : 'without'} metadata`, () => {
let collectorExporter: OTLPMetricExporter;
let server: grpc.Server;
let exportedData:
| otlpTypes.opentelemetryProto.metrics.v1.ResourceMetrics[]
| undefined;
let metrics: metrics.MetricRecord[];
let reqMetadata: grpc.Metadata | undefined;
before(done => {
server = new grpc.Server();
protoLoader
.load(metricsServiceProtoPath, {
keepCase: false,
longs: String,
enums: String,
defaults: true,
oneofs: true,
includeDirs,
})
.then((packageDefinition: protoLoader.PackageDefinition) => {
const packageObject: any = grpc.loadPackageDefinition(
packageDefinition
);
server.addService(
packageObject.opentelemetry.proto.collector.metrics.v1
.MetricsService.service,
{
Export: (data: {
request: otlpTypes.opentelemetryProto.collector.metrics.v1.ExportMetricsServiceRequest;
metadata: grpc.Metadata;
}) => {
try {
exportedData = data.request.resourceMetrics;
reqMetadata = data.metadata;
} catch (e) {
exportedData = undefined;
}
},
}
);
const credentials = params.useTLS
? grpc.ServerCredentials.createSsl(
fs.readFileSync('./test/certs/ca.crt'),
[
{
cert_chain: fs.readFileSync('./test/certs/server.crt'),
private_key: fs.readFileSync('./test/certs/server.key'),
},
]
)
: grpc.ServerCredentials.createInsecure();
server.bindAsync(address, credentials, () => {
server.start();
done();
});
});
});
after(() => {
server.forceShutdown();
});
beforeEach(async () => {
const credentials = params.useTLS
? grpc.credentials.createSsl(
fs.readFileSync('./test/certs/ca.crt'),
fs.readFileSync('./test/certs/client.key'),
fs.readFileSync('./test/certs/client.crt')
)
: undefined;
collectorExporter = new OTLPMetricExporter({
url: 'grpcs://' + address,
credentials,
metadata: params.metadata,
});
// Overwrites the start time to make tests consistent
Object.defineProperty(collectorExporter, '_startTime', {
value: 1592602232694000000,
});
metrics = [];
const counter: metrics.Metric<metrics.BoundCounter> &
Counter = mockCounter();
const observer: metrics.Metric<metrics.BoundObserver> &
ValueObserver = mockObserver(observerResult => {
observerResult.observe(3, {});
observerResult.observe(6, {});
});
const recorder: metrics.Metric<metrics.BoundValueRecorder> &
ValueRecorder = mockValueRecorder();
counter.add(1);
recorder.record(7);
recorder.record(14);
metrics.push((await counter.getMetricRecord())[0]);
metrics.push((await observer.getMetricRecord())[0]);
metrics.push((await recorder.getMetricRecord())[0]);
});
afterEach(() => {
exportedData = undefined;
reqMetadata = undefined;
sinon.restore();
});
describe('instance', () => {
it('should warn about headers', () => {
// Need to stub/spy on the underlying logger as the 'diag' instance is global
const spyLoggerWarn = sinon.stub(diag, 'warn');
collectorExporter = new OTLPMetricExporter({
url: `http://${address}`,
headers: {
foo: 'bar',
},
});
const args = spyLoggerWarn.args[0];
assert.strictEqual(args[0], 'Headers cannot be set when using grpc');
});
it('should warn about path in url', () => {
const spyLoggerWarn = sinon.stub(diag, 'warn');
collectorExporter = new OTLPMetricExporter({
url: `http://${address}/v1/metrics`
});
const args = spyLoggerWarn.args[0];
assert.strictEqual(
args[0],
'URL path should not be set when using grpc, the path part of the URL will be ignored.'
);
});
});
describe('export', () => {
it('should export metrics', done => {
const responseSpy = sinon.spy();
collectorExporter.export(metrics, responseSpy);
setTimeout(() => {
assert.ok(
typeof exportedData !== 'undefined',
'resource' + " doesn't exist"
);
let resource;
if (exportedData) {
resource = exportedData[0].resource;
const counter =
exportedData[0].instrumentationLibraryMetrics[0].metrics[0];
const observer =
exportedData[0].instrumentationLibraryMetrics[0].metrics[1];
const recorder =
exportedData[0].instrumentationLibraryMetrics[0].metrics[2];
ensureExportedCounterIsCorrect(
counter,
counter.intSum?.dataPoints[0].timeUnixNano
);
ensureExportedObserverIsCorrect(
observer,
observer.doubleGauge?.dataPoints[0].timeUnixNano
);
ensureExportedValueRecorderIsCorrect(
recorder,
recorder.intHistogram?.dataPoints[0].timeUnixNano,
[0, 100],
['0', '2', '0']
);
assert.ok(
typeof resource !== 'undefined',
"resource doesn't exist"
);
if (resource) {
ensureResourceIsCorrect(resource);
}
}
if (params.metadata && reqMetadata) {
ensureMetadataIsCorrect(reqMetadata, params.metadata);
}
done();
}, 500);
});
});
});
describe('OTLPMetricExporter - node (getDefaultUrl)', () => {
it('should default to localhost', done => {
const collectorExporter = new OTLPMetricExporter({});
setTimeout(() => {
assert.strictEqual(collectorExporter['url'], 'localhost:4317');
done();
});
});
it('should keep the URL if included', done => {
const url = 'http://foo.bar.com';
const collectorExporter = new OTLPMetricExporter({ url });
setTimeout(() => {
assert.strictEqual(collectorExporter['url'], 'foo.bar.com');
done();
});
});
});
describe('when configuring via environment', () => {
const envSource = process.env;
it('should use url defined in env', () => {
envSource.OTEL_EXPORTER_OTLP_ENDPOINT = 'http://foo.bar';
const collectorExporter = new OTLPMetricExporter();
assert.strictEqual(
collectorExporter.url,
'foo.bar'
);
envSource.OTEL_EXPORTER_OTLP_ENDPOINT = '';
});
it('should override global exporter url with signal url defined in env', () => {
envSource.OTEL_EXPORTER_OTLP_ENDPOINT = 'http://foo.bar';
envSource.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT = 'http://foo.metrics';
const collectorExporter = new OTLPMetricExporter();
assert.strictEqual(
collectorExporter.url,
'foo.metrics'
);
envSource.OTEL_EXPORTER_OTLP_ENDPOINT = '';
envSource.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT = '';
});
it('should use headers defined via env', () => {
envSource.OTEL_EXPORTER_OTLP_HEADERS = 'foo=bar';
const collectorExporter = new OTLPMetricExporter();
assert.deepStrictEqual(collectorExporter.metadata?.get('foo'), ['bar']);
envSource.OTEL_EXPORTER_OTLP_HEADERS = '';
});
it('should override global headers config with signal headers defined via env', () => {
const metadata = new grpc.Metadata();
metadata.set('foo', 'bar');
metadata.set('goo', 'lol');
envSource.OTEL_EXPORTER_OTLP_HEADERS = 'foo=jar,bar=foo';
envSource.OTEL_EXPORTER_OTLP_METRICS_HEADERS = 'foo=boo';
const collectorExporter = new OTLPMetricExporter({ metadata });
assert.deepStrictEqual(collectorExporter.metadata?.get('foo'), ['boo']);
assert.deepStrictEqual(collectorExporter.metadata?.get('bar'), ['foo']);
assert.deepStrictEqual(collectorExporter.metadata?.get('goo'), ['lol']);
envSource.OTEL_EXPORTER_OTLP_METRICS_HEADERS = '';
envSource.OTEL_EXPORTER_OTLP_HEADERS = '';
});
});
testOTLPMetricExporter({ useTLS: true });
testOTLPMetricExporter({ useTLS: false });
testOTLPMetricExporter({ metadata });