-
Notifications
You must be signed in to change notification settings - Fork 828
/
sdk.ts
514 lines (456 loc) · 16.2 KB
/
sdk.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
/*
* 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 {
ContextManager,
TextMapPropagator,
metrics,
diag,
DiagConsoleLogger,
} from '@opentelemetry/api';
import { logs } from '@opentelemetry/api-logs';
import {
Instrumentation,
registerInstrumentations,
} from '@opentelemetry/instrumentation';
import {
Detector,
DetectorSync,
detectResourcesSync,
envDetector,
hostDetector,
IResource,
processDetector,
Resource,
ResourceDetectionConfig,
} from '@opentelemetry/resources';
import {
LogRecordProcessor,
LoggerProvider,
BatchLogRecordProcessor,
ConsoleLogRecordExporter,
LogRecordExporter,
SimpleLogRecordProcessor,
} from '@opentelemetry/sdk-logs';
import { OTLPLogExporter as OTLPHttpLogExporter } from '@opentelemetry/exporter-logs-otlp-http';
import { OTLPLogExporter as OTLPGrpcLogExporter } from '@opentelemetry/exporter-logs-otlp-grpc';
import { OTLPLogExporter as OTLPProtoLogExporter } from '@opentelemetry/exporter-logs-otlp-proto';
import { OTLPMetricExporter as OTLPGrpcMetricExporter } from '@opentelemetry/exporter-metrics-otlp-grpc';
import { OTLPMetricExporter as OTLPProtoMetricExporter } from '@opentelemetry/exporter-metrics-otlp-proto';
import { OTLPMetricExporter as OTLPHttpMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';
import { PrometheusExporter as PrometheusMetricExporter } from '@opentelemetry/exporter-prometheus';
import {
MeterProvider,
MetricReader,
ViewOptions,
ConsoleMetricExporter,
PeriodicExportingMetricReader,
} from '@opentelemetry/sdk-metrics';
import {
BatchSpanProcessor,
SpanProcessor,
} from '@opentelemetry/sdk-trace-base';
import {
NodeTracerConfig,
NodeTracerProvider,
} from '@opentelemetry/sdk-trace-node';
import { ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions';
import { NodeSDKConfiguration } from './types';
import { getEnv, getEnvWithoutDefaults } from '@opentelemetry/core';
import {
getResourceDetectorsFromEnv,
getSpanProcessorsFromEnv,
filterBlanksAndNulls,
} from './utils';
/** This class represents everything needed to register a fully configured OpenTelemetry Node.js SDK */
export type MeterProviderConfig = {
/**
* Reference to the MetricReader instance by the NodeSDK
*/
reader?: MetricReader;
/**
* List of {@link ViewOptions}s that should be passed to the MeterProvider
*/
views?: ViewOptions[];
};
export type LoggerProviderConfig = {
/**
* Reference to the LoggerRecordProcessor instance by the NodeSDK
*/
logRecordProcessors: LogRecordProcessor[];
};
/**
* @Returns param value, if set else returns the default value
*/
function getValueInMillis(envName: string, defaultValue: number): number {
return parseInt(process.env[envName] || '') || defaultValue;
}
/**
*
* @returns MetricReader[] if appropriate environment variables are configured
*/
function configureMetricProviderFromEnv(): MetricReader[] {
const metricReaders: MetricReader[] = [];
const metricsExporterList = process.env.OTEL_METRICS_EXPORTER?.trim();
if (!metricsExporterList) {
return metricReaders;
}
const enabledExporters = filterBlanksAndNulls(metricsExporterList.split(','));
if (enabledExporters.length === 0) {
diag.info('OTEL_METRICS_EXPORTER is empty. Using default otlp exporter.');
}
if (enabledExporters.includes('none')) {
diag.info(
`OTEL_METRICS_EXPORTER contains "none". Metric provider will not be initialized.`
);
return metricReaders;
}
enabledExporters.forEach(exporter => {
if (exporter === 'otlp') {
const protocol =
process.env.OTEL_EXPORTER_OTLP_METRICS_PROTOCOL?.trim() ||
process.env.OTEL_EXPORTER_OTLP_PROTOCOL?.trim();
const exportIntervalMillis = getValueInMillis(
'OTEL_METRIC_EXPORT_INTERVAL',
60000
);
const exportTimeoutMillis = getValueInMillis(
'OTEL_METRIC_EXPORT_TIMEOUT',
30000
);
switch (protocol) {
case 'grpc':
metricReaders.push(
new PeriodicExportingMetricReader({
exporter: new OTLPGrpcMetricExporter(),
exportIntervalMillis: exportIntervalMillis,
exportTimeoutMillis: exportTimeoutMillis,
})
);
break;
case 'http/json':
metricReaders.push(
new PeriodicExportingMetricReader({
exporter: new OTLPHttpMetricExporter(),
exportIntervalMillis: exportIntervalMillis,
exportTimeoutMillis: exportTimeoutMillis,
})
);
break;
case 'http/protobuf':
metricReaders.push(
new PeriodicExportingMetricReader({
exporter: new OTLPProtoMetricExporter(),
exportIntervalMillis: exportIntervalMillis,
exportTimeoutMillis: exportTimeoutMillis,
})
);
break;
default:
diag.warn(
`Unsupported OTLP metrics protocol: "${protocol}". Using http/protobuf.`
);
metricReaders.push(
new PeriodicExportingMetricReader({
exporter: new OTLPProtoMetricExporter(),
exportIntervalMillis: exportIntervalMillis,
exportTimeoutMillis: exportTimeoutMillis,
})
);
}
} else if (exporter === 'console') {
metricReaders.push(
new PeriodicExportingMetricReader({
exporter: new ConsoleMetricExporter(),
})
);
} else if (exporter === 'prometheus') {
metricReaders.push(new PrometheusMetricExporter());
} else {
diag.warn(
`Unsupported OTEL_METRICS_EXPORTER value: "${exporter}". Supported values are: otlp, console, prometheus, none.`
);
}
});
return metricReaders;
}
export class NodeSDK {
private _tracerProviderConfig?: {
tracerConfig: NodeTracerConfig;
spanProcessors: SpanProcessor[];
contextManager?: ContextManager;
textMapPropagator?: TextMapPropagator;
};
private _loggerProviderConfig?: LoggerProviderConfig;
private _meterProviderConfig?: MeterProviderConfig;
private _instrumentations: Instrumentation[];
private _resource: IResource;
private _resourceDetectors: Array<Detector | DetectorSync>;
private _autoDetectResources: boolean;
private _tracerProvider?: NodeTracerProvider;
private _loggerProvider?: LoggerProvider;
private _meterProvider?: MeterProvider;
private _serviceName?: string;
private _configuration?: Partial<NodeSDKConfiguration>;
private _disabled?: boolean;
/**
* Create a new NodeJS SDK instance
*/
public constructor(configuration: Partial<NodeSDKConfiguration> = {}) {
const env = getEnv();
const envWithoutDefaults = getEnvWithoutDefaults();
if (env.OTEL_SDK_DISABLED) {
this._disabled = true;
// Functions with possible side-effects are set
// to no-op via the _disabled flag
}
// Default is INFO, use environment without defaults to check
// if the user originally set the environment variable.
if (envWithoutDefaults.OTEL_LOG_LEVEL) {
diag.setLogger(new DiagConsoleLogger(), {
logLevel: envWithoutDefaults.OTEL_LOG_LEVEL,
});
}
this._configuration = configuration;
this._resource = configuration.resource ?? Resource.default();
this._autoDetectResources = configuration.autoDetectResources ?? true;
if (!this._autoDetectResources) {
this._resourceDetectors = [];
} else if (configuration.resourceDetectors != null) {
this._resourceDetectors = configuration.resourceDetectors;
} else if (process.env.OTEL_NODE_RESOURCE_DETECTORS != null) {
this._resourceDetectors = getResourceDetectorsFromEnv();
} else {
this._resourceDetectors = [envDetector, processDetector, hostDetector];
}
this._serviceName = configuration.serviceName;
// If a tracer provider can be created from manual configuration, create it
if (
configuration.traceExporter ||
configuration.spanProcessor ||
configuration.spanProcessors
) {
const tracerProviderConfig: NodeTracerConfig = {};
if (configuration.sampler) {
tracerProviderConfig.sampler = configuration.sampler;
}
if (configuration.spanLimits) {
tracerProviderConfig.spanLimits = configuration.spanLimits;
}
if (configuration.idGenerator) {
tracerProviderConfig.idGenerator = configuration.idGenerator;
}
if (configuration.spanProcessor) {
diag.warn(
"The 'spanProcessor' option is deprecated. Please use 'spanProcessors' instead."
);
}
const spanProcessor =
configuration.spanProcessor ??
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
new BatchSpanProcessor(configuration.traceExporter!);
const spanProcessors = configuration.spanProcessors ?? [spanProcessor];
this._tracerProviderConfig = {
tracerConfig: tracerProviderConfig,
spanProcessors,
contextManager: configuration.contextManager,
textMapPropagator: configuration.textMapPropagator,
};
}
if (configuration.logRecordProcessors) {
this._loggerProviderConfig = {
logRecordProcessors: configuration.logRecordProcessors,
};
} else if (configuration.logRecordProcessor) {
this._loggerProviderConfig = {
logRecordProcessors: [configuration.logRecordProcessor],
};
diag.warn(
"The 'logRecordProcessor' option is deprecated. Please use 'logRecordProcessors' instead."
);
} else {
this.configureLoggerProviderFromEnv();
}
if (configuration.metricReader || configuration.views) {
const meterProviderConfig: MeterProviderConfig = {};
if (configuration.metricReader) {
meterProviderConfig.reader = configuration.metricReader;
}
if (configuration.views) {
meterProviderConfig.views = configuration.views;
}
this._meterProviderConfig = meterProviderConfig;
}
this._instrumentations = configuration.instrumentations?.flat() ?? [];
}
/**
* Call this method to construct SDK components and register them with the OpenTelemetry API.
*/
public start(): void {
if (this._disabled) {
return;
}
registerInstrumentations({
instrumentations: this._instrumentations,
});
if (this._autoDetectResources) {
const internalConfig: ResourceDetectionConfig = {
detectors: this._resourceDetectors,
};
this._resource = this._resource.merge(
detectResourcesSync(internalConfig)
);
}
this._resource =
this._serviceName === undefined
? this._resource
: this._resource.merge(
new Resource({
[ATTR_SERVICE_NAME]: this._serviceName,
})
);
const spanProcessors = this._tracerProviderConfig
? this._tracerProviderConfig.spanProcessors
: getSpanProcessorsFromEnv();
// If the Provider is configured with Env Exporters, we need to check if the SDK had any manual configurations and set them here
this._tracerProvider = new NodeTracerProvider({
...this._configuration,
resource: this._resource,
spanProcessors,
});
// Only register if there is a span processor
if (spanProcessors.length > 0) {
this._tracerProvider.register({
contextManager:
this._tracerProviderConfig?.contextManager ??
// _tracerProviderConfig may be undefined if trace-specific settings are not provided - fall back to raw config
this._configuration?.contextManager,
propagator: this._tracerProviderConfig?.textMapPropagator,
});
}
if (this._loggerProviderConfig) {
const loggerProvider = new LoggerProvider({
resource: this._resource,
});
for (const logRecordProcessor of this._loggerProviderConfig
.logRecordProcessors) {
loggerProvider.addLogRecordProcessor(logRecordProcessor);
}
this._loggerProvider = loggerProvider;
logs.setGlobalLoggerProvider(loggerProvider);
}
const metricReadersFromEnv: MetricReader[] =
configureMetricProviderFromEnv();
if (this._meterProviderConfig || metricReadersFromEnv.length > 0) {
const readers: MetricReader[] = [];
if (this._meterProviderConfig?.reader) {
readers.push(this._meterProviderConfig.reader);
}
if (readers.length === 0) {
metricReadersFromEnv.forEach((r: MetricReader) => readers.push(r));
}
const meterProvider = new MeterProvider({
resource: this._resource,
views: this._meterProviderConfig?.views ?? [],
readers: readers,
});
this._meterProvider = meterProvider;
metrics.setGlobalMeterProvider(meterProvider);
// TODO: This is a workaround to fix https://github.com/open-telemetry/opentelemetry-js/issues/3609
// If the MeterProvider is not yet registered when instrumentations are registered, all metrics are dropped.
// This code is obsolete once https://github.com/open-telemetry/opentelemetry-js/issues/3622 is implemented.
for (const instrumentation of this._instrumentations) {
instrumentation.setMeterProvider(metrics.getMeterProvider());
}
}
}
public shutdown(): Promise<void> {
const promises: Promise<unknown>[] = [];
if (this._tracerProvider) {
promises.push(this._tracerProvider.shutdown());
}
if (this._loggerProvider) {
promises.push(this._loggerProvider.shutdown());
}
if (this._meterProvider) {
promises.push(this._meterProvider.shutdown());
}
return (
Promise.all(promises)
// return void instead of the array from Promise.all
.then(() => {})
);
}
private configureLoggerProviderFromEnv(): void {
const logExportersList = process.env.OTEL_LOGS_EXPORTER ?? '';
const enabledExporters = filterBlanksAndNulls(logExportersList.split(','));
if (enabledExporters.length === 0) {
diag.info('OTEL_LOGS_EXPORTER is empty. Using default otlp exporter.');
enabledExporters.push('otlp');
}
if (enabledExporters.includes('none')) {
diag.info(
`OTEL_LOGS_EXPORTER contains "none". Logger provider will not be initialized.`
);
return;
}
const exporters: LogRecordExporter[] = [];
enabledExporters.forEach(exporter => {
if (exporter === 'otlp') {
const protocol = (
process.env.OTEL_EXPORTER_OTLP_LOGS_PROTOCOL ??
process.env.OTEL_EXPORTER_OTLP_PROTOCOL
)?.trim();
switch (protocol) {
case 'grpc':
exporters.push(new OTLPGrpcLogExporter());
break;
case 'http/json':
exporters.push(new OTLPHttpLogExporter());
break;
case 'http/protobuf':
exporters.push(new OTLPProtoLogExporter());
break;
case undefined:
case '':
exporters.push(new OTLPProtoLogExporter());
break;
default:
diag.warn(
`Unsupported OTLP logs protocol: "${protocol}". Using http/protobuf.`
);
exporters.push(new OTLPProtoLogExporter());
}
} else if (exporter === 'console') {
exporters.push(new ConsoleLogRecordExporter());
} else {
diag.warn(
`Unsupported OTEL_LOGS_EXPORTER value: "${exporter}". Supported values are: otlp, console, none.`
);
}
});
if (exporters.length > 0) {
this._loggerProviderConfig = {
logRecordProcessors: exporters.map(exporter => {
if (exporter instanceof ConsoleLogRecordExporter) {
return new SimpleLogRecordProcessor(exporter);
} else {
return new BatchLogRecordProcessor(exporter);
}
}),
};
}
}
}