-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathutils.ts
More file actions
831 lines (763 loc) · 25.2 KB
/
utils.ts
File metadata and controls
831 lines (763 loc) · 25.2 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
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import type {
ContextManager,
MeterProvider,
TextMapPropagator,
} from '@opentelemetry/api';
import { context, diag, propagation } from '@opentelemetry/api';
import {
CompositePropagator,
getNumberFromEnv,
getStringFromEnv,
getStringListFromEnv,
W3CBaggagePropagator,
W3CTraceContextPropagator,
} from '@opentelemetry/core';
import { OTLPTraceExporter as OTLPProtoTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';
import { OTLPTraceExporter as OTLPHttpTraceExporter } from '@opentelemetry/exporter-trace-otlp-http';
import { OTLPTraceExporter as OTLPGrpcTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc';
import { ZipkinExporter } from '@opentelemetry/exporter-zipkin';
import type {
DetectedResourceAttributes,
Resource,
ResourceDetector,
} from '@opentelemetry/resources';
import {
envDetector,
hostDetector,
osDetector,
processDetector,
resourceFromAttributes,
serviceInstanceIdDetector,
} from '@opentelemetry/resources';
import type {
SpanExporter,
SpanProcessor,
} from '@opentelemetry/sdk-trace-base';
import {
BatchSpanProcessor,
ConsoleSpanExporter,
SimpleSpanProcessor,
} from '@opentelemetry/sdk-trace-base';
import { B3InjectEncoding, B3Propagator } from '@opentelemetry/propagator-b3';
import { JaegerPropagator } from '@opentelemetry/propagator-jaeger';
import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks';
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 { CompressionAlgorithm } from '@opentelemetry/otlp-exporter-base';
import type {
ConfigurationModel,
LogRecordExporterConfigModel,
InstrumentTypeConfigModel,
AggregationConfigModel,
PeriodicMetricReaderConfigModel,
} from '@opentelemetry/configuration';
import type {
AggregationOption,
IMetricReader,
PushMetricExporter,
ViewOptions,
} from '@opentelemetry/sdk-metrics';
import {
AggregationType,
ConsoleMetricExporter,
InstrumentType,
PeriodicExportingMetricReader,
} from '@opentelemetry/sdk-metrics';
import { OTLPMetricExporter as OTLPGrpcMetricExporter } from '@opentelemetry/exporter-metrics-otlp-grpc';
import { OTLPMetricExporter as OTLPHttpMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http';
import { OTLPMetricExporter as OTLPProtoMetricExporter } from '@opentelemetry/exporter-metrics-otlp-proto';
import type {
BufferConfig,
LogRecordExporter,
LoggerProviderConfig,
LogRecordProcessor,
} from '@opentelemetry/sdk-logs';
import {
BatchLogRecordProcessor,
ConsoleLogRecordExporter,
SimpleLogRecordProcessor,
} from '@opentelemetry/sdk-logs';
const RESOURCE_DETECTOR_ENVIRONMENT = 'env';
const RESOURCE_DETECTOR_HOST = 'host';
const RESOURCE_DETECTOR_OS = 'os';
const RESOURCE_DETECTOR_PROCESS = 'process';
const RESOURCE_DETECTOR_SERVICE_INSTANCE_ID = 'serviceinstance';
export function getResourceFromConfiguration(
config: ConfigurationModel
): Resource | undefined {
if (config.resource && config.resource.attributes) {
const attr: DetectedResourceAttributes = {};
for (let i = 0; i < config.resource.attributes.length; i++) {
const a = config.resource.attributes[i];
attr[a.name] = a.value;
}
return resourceFromAttributes(attr, {
schemaUrl: config.resource.schema_url,
});
}
return undefined;
}
export function getResourceDetectorsFromEnv(): Array<ResourceDetector> {
// When updating this list, make sure to also update the section `resourceDetectors` on README.
const resourceDetectors = new Map<string, ResourceDetector>([
[RESOURCE_DETECTOR_HOST, hostDetector],
[RESOURCE_DETECTOR_OS, osDetector],
[RESOURCE_DETECTOR_SERVICE_INSTANCE_ID, serviceInstanceIdDetector],
[RESOURCE_DETECTOR_PROCESS, processDetector],
[RESOURCE_DETECTOR_ENVIRONMENT, envDetector],
]);
const resourceDetectorsFromEnv = getStringListFromEnv(
'OTEL_NODE_RESOURCE_DETECTORS'
) ?? ['all'];
if (resourceDetectorsFromEnv.includes('all')) {
return [...resourceDetectors.values()].flat();
}
if (resourceDetectorsFromEnv.includes('none')) {
return [];
}
return resourceDetectorsFromEnv.flatMap(detector => {
const resourceDetector = resourceDetectors.get(detector);
if (!resourceDetector) {
diag.warn(
`Invalid resource detector "${detector}" specified in the environment variable OTEL_NODE_RESOURCE_DETECTORS`
);
}
return resourceDetector || [];
});
}
export function getResourceDetectorsFromConfiguration(
config: ConfigurationModel
): Array<ResourceDetector> {
const detectors = config.resource?.['detection/development']?.detectors ?? [];
return detectors.flatMap(detector => {
const result: ResourceDetector[] = [];
if (detector.host != null) result.push(hostDetector);
if (detector.os != null) result.push(osDetector);
if (detector.process != null) result.push(processDetector);
if (detector.service != null) result.push(serviceInstanceIdDetector);
if (detector.env != null) result.push(envDetector);
return result;
});
}
export function getOtlpProtocolFromEnv(): string {
return (
getStringFromEnv('OTEL_EXPORTER_OTLP_TRACES_PROTOCOL') ??
getStringFromEnv('OTEL_EXPORTER_OTLP_PROTOCOL') ??
'http/protobuf'
);
}
function getOtlpExporterFromEnv(): SpanExporter {
const protocol = getOtlpProtocolFromEnv();
switch (protocol) {
case 'grpc':
return new OTLPGrpcTraceExporter();
case 'http/json':
return new OTLPHttpTraceExporter();
case 'http/protobuf':
return new OTLPProtoTraceExporter();
default:
diag.warn(
`Unsupported OTLP traces protocol: ${protocol}. Using http/protobuf.`
);
return new OTLPProtoTraceExporter();
}
}
export function getSpanProcessorsFromEnv(
meterProvider: MeterProvider | undefined
): SpanProcessor[] {
const exportersMap = new Map<string, () => SpanExporter>([
['otlp', () => getOtlpExporterFromEnv()],
['zipkin', () => new ZipkinExporter()],
['console', () => new ConsoleSpanExporter()],
]);
const exporters: SpanExporter[] = [];
const processors: SpanProcessor[] = [];
let traceExportersList = Array.from(
new Set(getStringListFromEnv('OTEL_TRACES_EXPORTER'))
).filter(s => s !== 'null');
if (traceExportersList[0] === 'none') {
diag.warn(
'OTEL_TRACES_EXPORTER contains "none". SDK will not be initialized.'
);
return [];
}
if (traceExportersList.length === 0) {
diag.debug('OTEL_TRACES_EXPORTER is empty. Using default otlp exporter.');
traceExportersList = ['otlp'];
} else if (
traceExportersList.length > 1 &&
traceExportersList.includes('none')
) {
diag.warn(
'OTEL_TRACES_EXPORTER contains "none" along with other exporters. Using default otlp exporter.'
);
traceExportersList = ['otlp'];
}
for (const name of traceExportersList) {
const exporter = exportersMap.get(name)?.();
if (exporter) {
exporters.push(exporter);
} else {
diag.warn(`Unrecognized OTEL_TRACES_EXPORTER value: ${name}.`);
}
}
for (const exp of exporters) {
if (exp instanceof ConsoleSpanExporter) {
processors.push(new SimpleSpanProcessor(exp, { meterProvider }));
} else {
processors.push(new BatchSpanProcessor(exp, { meterProvider }));
}
}
if (exporters.length === 0) {
diag.warn(
'Unable to set up trace exporter(s) due to invalid exporter and/or protocol values.'
);
}
return processors;
}
/**
* Get a propagator as defined by environment variables
*/
export function getPropagatorFromEnv(): TextMapPropagator | null | undefined {
// Empty and undefined MUST be treated equal.
const propagatorsEnvVarValue = getStringListFromEnv('OTEL_PROPAGATORS');
if (propagatorsEnvVarValue == null) {
// return undefined to fall back to default
return undefined;
}
if (propagatorsEnvVarValue.includes('none')) {
return null;
}
// Implementation note: this only contains specification required propagators that are actually hosted in this repo.
// Any other propagators (like aws, aws-lambda, should go into `@opentelemetry/auto-configuration-propagators` instead).
const propagatorsFactory = new Map<string, () => TextMapPropagator>([
['tracecontext', () => new W3CTraceContextPropagator()],
['baggage', () => new W3CBaggagePropagator()],
['b3', () => new B3Propagator()],
[
'b3multi',
() => new B3Propagator({ injectEncoding: B3InjectEncoding.MULTI_HEADER }),
],
['jaeger', () => new JaegerPropagator()],
]);
// Values MUST be deduplicated in order to register a Propagator only once.
const uniquePropagatorNames = Array.from(new Set(propagatorsEnvVarValue));
const validPropagators: TextMapPropagator[] = [];
uniquePropagatorNames.forEach(name => {
const propagator = propagatorsFactory.get(name)?.();
if (!propagator) {
diag.warn(
`Propagator "${name}" requested through environment variable is unavailable.`
);
return;
}
validPropagators.push(propagator);
});
if (validPropagators.length === 0) {
// null to signal that the default should **not** be used in its place.
return null;
} else if (uniquePropagatorNames.length === 1) {
return validPropagators[0];
} else {
return new CompositePropagator({
propagators: validPropagators,
});
}
}
/**
* Get a propagator as defined by configuration model from configuration
*/
export function getPropagatorFromConfiguration(
config: ConfigurationModel
): TextMapPropagator | null | undefined {
const propagatorsValue = getKeyListFromObjectArray(
config.propagator?.composite
);
if (propagatorsValue == null) {
// return undefined to fall back to default
return undefined;
}
if (propagatorsValue.includes('none')) {
return null;
}
// Implementation note: this only contains specification required propagators that are actually hosted in this repo.
// Any other propagators (like aws, aws-lambda, should go into `@opentelemetry/auto-configuration-propagators` instead).
const propagatorsFactory = new Map<string, () => TextMapPropagator>([
['tracecontext', () => new W3CTraceContextPropagator()],
['baggage', () => new W3CBaggagePropagator()],
['b3', () => new B3Propagator()],
[
'b3multi',
() => new B3Propagator({ injectEncoding: B3InjectEncoding.MULTI_HEADER }),
],
['jaeger', () => new JaegerPropagator()],
]);
// Values MUST be deduplicated in order to register a Propagator only once.
const uniquePropagatorNames = Array.from(new Set(propagatorsValue));
const validPropagators: TextMapPropagator[] = [];
uniquePropagatorNames.forEach(name => {
const propagator = propagatorsFactory.get(name)?.();
if (!propagator) {
diag.warn(
`Propagator "${name}" requested through configuration is unavailable.`
);
return;
}
validPropagators.push(propagator);
});
if (validPropagators.length === 0) {
// null to signal that the default should **not** be used in its place.
return null;
} else if (uniquePropagatorNames.length === 1) {
return validPropagators[0];
} else {
return new CompositePropagator({
propagators: validPropagators,
});
}
}
export function setupContextManager(
contextManager: ContextManager | null | undefined
) {
// null means 'do not register'
if (contextManager === null) {
return;
}
// undefined means 'register default'
if (contextManager === undefined) {
const defaultContextManager = new AsyncLocalStorageContextManager();
defaultContextManager.enable();
context.setGlobalContextManager(defaultContextManager);
return;
}
contextManager.enable();
context.setGlobalContextManager(contextManager);
}
export function setupPropagator(
propagator: TextMapPropagator | null | undefined
) {
// null means 'do not register'
if (propagator === null) {
return;
}
// undefined means 'register default'
if (propagator === undefined) {
propagation.setGlobalPropagator(
new CompositePropagator({
propagators: [
new W3CTraceContextPropagator(),
new W3CBaggagePropagator(),
],
})
);
return;
}
propagation.setGlobalPropagator(propagator);
}
export function getKeyListFromObjectArray(
obj: object[] | undefined
): string[] | undefined {
if (!obj || obj.length === 0) {
return undefined;
}
return obj
.map(item => Object.keys(item))
.reduce((prev, curr) => prev.concat(curr), []);
}
export function getNonNegativeNumberFromEnv(
envVarName: string
): number | undefined {
const value = getNumberFromEnv(envVarName);
if (value != null && value <= 0) {
diag.warn(
`${envVarName} (${value}) is invalid, expected number greater than 0, using default.`
);
return undefined;
}
return value;
}
export function getPeriodicExportingMetricReaderFromEnv(
exporter: PushMetricExporter
): IMetricReader {
const defaultTimeoutMillis = 30_000;
const defaultIntervalMillis = 60_000;
const rawExportIntervalMillis = getNonNegativeNumberFromEnv(
'OTEL_METRIC_EXPORT_INTERVAL'
);
const rawExportTimeoutMillis = getNonNegativeNumberFromEnv(
'OTEL_METRIC_EXPORT_TIMEOUT'
);
// Apply defaults
const exportIntervalMillis = rawExportIntervalMillis ?? defaultIntervalMillis;
let exportTimeoutMillis = rawExportTimeoutMillis ?? defaultTimeoutMillis;
// Ensure timeout doesn't exceed interval
if (exportTimeoutMillis > exportIntervalMillis) {
// determine which env vars were set and which ones defaulted for logging purposes
const timeoutSource =
rawExportTimeoutMillis != null
? rawExportTimeoutMillis.toString()
: `${defaultTimeoutMillis}, default`;
const intervalSource =
rawExportIntervalMillis != null
? rawExportIntervalMillis.toString()
: `${defaultIntervalMillis}, default`;
const bothSetByUser =
rawExportTimeoutMillis != null && rawExportIntervalMillis != null;
const logMessage = `OTEL_METRIC_EXPORT_TIMEOUT (${timeoutSource}) is greater than OTEL_METRIC_EXPORT_INTERVAL (${intervalSource}). Clamping timeout to interval value.`;
// only bother users if they explicitly set both values.
if (bothSetByUser) {
diag.warn(logMessage);
} else {
diag.info(logMessage);
}
exportTimeoutMillis = exportIntervalMillis;
}
return new PeriodicExportingMetricReader({
exportTimeoutMillis,
exportIntervalMillis,
exporter,
});
}
export function getOtlpMetricExporterFromEnv(): PushMetricExporter {
const protocol =
(
getStringFromEnv('OTEL_EXPORTER_OTLP_METRICS_PROTOCOL') ??
getStringFromEnv('OTEL_EXPORTER_OTLP_PROTOCOL')
)?.trim() || 'http/protobuf'; // Using || to also fall back on empty string
switch (protocol) {
case 'grpc':
return new OTLPGrpcMetricExporter();
case 'http/json':
return new OTLPHttpMetricExporter();
case 'http/protobuf':
return new OTLPProtoMetricExporter();
}
diag.warn(
`Unsupported OTLP metrics protocol: "${protocol}". Using http/protobuf.`
);
return new OTLPProtoMetricExporter();
}
export function getPeriodicMetricReaderFromConfiguration(
periodic: PeriodicMetricReaderConfigModel
): IMetricReader | undefined {
if (periodic.exporter) {
let exporter;
if (periodic.exporter.otlp_http) {
const encoding = periodic.exporter.otlp_http.encoding;
if (encoding === 'json') {
exporter = new OTLPHttpMetricExporter({
compression:
periodic.exporter.otlp_http.compression === 'gzip'
? CompressionAlgorithm.GZIP
: CompressionAlgorithm.NONE,
});
} else if (encoding === 'protobuf') {
exporter = new OTLPProtoMetricExporter({
compression:
periodic.exporter.otlp_http.compression === 'gzip'
? CompressionAlgorithm.GZIP
: CompressionAlgorithm.NONE,
});
} else {
diag.warn(`Unsupported OTLP metrics encoding: ${encoding}.`);
}
}
if (periodic.exporter.otlp_grpc) {
exporter = new OTLPGrpcMetricExporter({
compression:
periodic.exporter.otlp_grpc.compression === 'gzip'
? CompressionAlgorithm.GZIP
: CompressionAlgorithm.NONE,
});
}
if (exporter) {
// TODO(6425): add cardinality_limits
return new PeriodicExportingMetricReader({
exportIntervalMillis: periodic.interval ?? 60_000,
exportTimeoutMillis: periodic.timeout ?? 30_000,
exporter,
});
}
if (periodic.exporter.console) {
return new PeriodicExportingMetricReader({
exporter: new ConsoleMetricExporter(),
});
}
}
diag.warn(`Unsupported Metric Exporter.`);
return undefined;
}
/**
* Get LoggerProviderConfig from environment variables.
*/
export function getLoggerProviderConfigFromEnv(): LoggerProviderConfig {
return {
logRecordLimits: {
attributeCountLimit:
getNonNegativeNumberFromEnv('OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT') ??
getNonNegativeNumberFromEnv('OTEL_ATTRIBUTE_COUNT_LIMIT'),
attributeValueLengthLimit:
getNonNegativeNumberFromEnv(
'OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT'
) ?? getNonNegativeNumberFromEnv('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT'),
},
};
}
/**
* Get configuration for BatchLogRecordProcessor from environment variables.
*/
export function getBatchLogRecordProcessorConfigFromEnv(): BufferConfig {
return {
maxQueueSize: getNonNegativeNumberFromEnv('OTEL_BLRP_MAX_QUEUE_SIZE'),
scheduledDelayMillis: getNonNegativeNumberFromEnv(
'OTEL_BLRP_SCHEDULE_DELAY'
),
exportTimeoutMillis: getNonNegativeNumberFromEnv(
'OTEL_BLRP_EXPORT_TIMEOUT'
),
maxExportBatchSize: getNonNegativeNumberFromEnv(
'OTEL_BLRP_MAX_EXPORT_BATCH_SIZE'
),
};
}
export function getBatchLogRecordProcessorFromEnv(
exporter: LogRecordExporter
): BatchLogRecordProcessor {
return new BatchLogRecordProcessor(
exporter,
getBatchLogRecordProcessorConfigFromEnv()
);
}
export function getLogRecordExporter(
exporter: LogRecordExporterConfigModel
): LogRecordExporter | undefined {
if (exporter.otlp_http) {
const encoding = exporter.otlp_http.encoding;
if (encoding === 'json') {
return new OTLPHttpLogExporter({
compression:
exporter.otlp_http.compression === 'gzip'
? CompressionAlgorithm.GZIP
: CompressionAlgorithm.NONE,
});
}
if (encoding === 'protobuf') {
return new OTLPProtoLogExporter({
compression:
exporter.otlp_http.compression === 'gzip'
? CompressionAlgorithm.GZIP
: CompressionAlgorithm.NONE,
});
}
diag.warn(
`Unsupported OTLP logs encoding: ${encoding}. Using http/protobuf.`
);
return new OTLPProtoLogExporter({
compression:
exporter.otlp_http.compression === 'gzip'
? CompressionAlgorithm.GZIP
: CompressionAlgorithm.NONE,
});
} else if (exporter.otlp_grpc) {
return new OTLPGrpcLogExporter({
compression:
exporter.otlp_grpc.compression === 'gzip'
? CompressionAlgorithm.GZIP
: CompressionAlgorithm.NONE,
});
} else if (exporter.console) {
return new ConsoleLogRecordExporter();
}
diag.warn(`Unsupported Exporter value. No Log Record Exporter registered`);
return undefined;
}
export function getLogRecordProcessorsFromConfiguration(
config: ConfigurationModel
): LogRecordProcessor[] | undefined {
const logRecordProcessors: LogRecordProcessor[] = [];
config.logger_provider?.processors?.forEach(processor => {
if (processor.batch) {
const exporter = getLogRecordExporter(processor.batch.exporter);
if (exporter) {
logRecordProcessors.push(
new BatchLogRecordProcessor(exporter, {
maxQueueSize: processor.batch.max_queue_size,
maxExportBatchSize: processor.batch.max_export_batch_size,
scheduledDelayMillis: processor.batch.schedule_delay,
exportTimeoutMillis: processor.batch.export_timeout,
})
);
}
}
if (processor.simple) {
const exporter = getLogRecordExporter(processor.simple.exporter);
if (exporter) {
logRecordProcessors.push(new SimpleLogRecordProcessor(exporter));
}
}
});
if (logRecordProcessors.length > 0) {
return logRecordProcessors;
}
return undefined;
}
export function getMeterReadersFromConfiguration(
config: ConfigurationModel
): IMetricReader[] | undefined {
const metricReaders: IMetricReader[] = [];
config.meter_provider?.readers?.forEach(reader => {
if (reader.periodic) {
const periodicReader = getPeriodicMetricReaderFromConfiguration(
reader.periodic
);
if (periodicReader) {
metricReaders.push(periodicReader);
}
}
});
if (metricReaders.length > 0) {
return metricReaders;
}
return undefined;
}
export function getInstrumentType(
instrument: InstrumentTypeConfigModel
): InstrumentType | undefined {
switch (instrument) {
case 'counter':
return InstrumentType.COUNTER;
case 'gauge':
return InstrumentType.GAUGE;
case 'histogram':
return InstrumentType.HISTOGRAM;
case 'observable_counter':
return InstrumentType.OBSERVABLE_COUNTER;
case 'observable_gauge':
return InstrumentType.OBSERVABLE_GAUGE;
case 'observable_up_down_counter':
return InstrumentType.OBSERVABLE_UP_DOWN_COUNTER;
case 'up_down_counter':
return InstrumentType.UP_DOWN_COUNTER;
default:
diag.warn(`Unsupported instrument type: ${instrument}`);
return undefined;
}
}
export function getAggregationType(
aggregation: AggregationConfigModel
): AggregationOption | undefined {
if (aggregation.default) {
return {
type: AggregationType.DEFAULT,
};
}
if (aggregation.drop) {
return {
type: AggregationType.DROP,
};
}
if (aggregation.explicit_bucket_histogram) {
return {
type: AggregationType.EXPLICIT_BUCKET_HISTOGRAM,
options: {
recordMinMax:
aggregation.explicit_bucket_histogram.record_min_max ?? true,
boundaries: aggregation.explicit_bucket_histogram.boundaries ?? [
0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500,
10000,
],
},
};
}
if (aggregation.base2_exponential_bucket_histogram) {
return {
type: AggregationType.EXPONENTIAL_HISTOGRAM,
options: {
recordMinMax:
aggregation.base2_exponential_bucket_histogram.record_min_max ?? true,
maxSize: aggregation.base2_exponential_bucket_histogram.max_size,
},
};
}
if (aggregation.last_value) {
return {
type: AggregationType.LAST_VALUE,
};
}
if (aggregation.sum) {
return {
type: AggregationType.SUM,
};
}
diag.warn(`Unsupported aggregation type`);
return undefined;
}
export function getMeterViewsFromConfiguration(
config: ConfigurationModel
): ViewOptions[] | undefined {
const metricViews: ViewOptions[] = [];
config.meter_provider?.views?.forEach(view => {
const viewOption: ViewOptions = {};
if (view.selector) {
if (view.selector.instrument_name) {
viewOption.instrumentName = view.selector.instrument_name;
}
if (view.selector.instrument_type) {
const instrumentType = getInstrumentType(view.selector.instrument_type);
if (instrumentType) {
viewOption.instrumentType = instrumentType;
}
}
if (view.selector.unit) {
viewOption.instrumentUnit = view.selector.unit;
}
if (view.selector.meter_name) {
viewOption.meterName = view.selector.meter_name;
}
if (view.selector.meter_version) {
viewOption.meterVersion = view.selector.meter_version;
}
if (view.selector.meter_schema_url) {
viewOption.meterSchemaUrl = view.selector.meter_schema_url;
}
}
if (view.stream) {
viewOption.name = view.stream.name ?? view.selector?.instrument_name;
viewOption.aggregationCardinalityLimit =
view.stream.aggregation_cardinality_limit ?? 2_000;
if (view.stream.description) {
viewOption.description = view.stream.description;
}
if (view.stream.aggregation) {
const aggregationType = getAggregationType(view.stream.aggregation);
if (aggregationType) {
viewOption.aggregation = aggregationType;
}
}
// TODO(6427): add support for view.stream.attribute_keys and correspondent attributes processor configuration
}
if (Object.keys(viewOption).length > 0) {
metricViews.push(viewOption);
}
});
if (metricViews.length > 0) {
return metricViews;
}
return undefined;
}
export function getInstanceID(config: ConfigurationModel): string | undefined {
if (config.resource?.attributes) {
for (let i = 0; i < config.resource.attributes.length; i++) {
const element = config.resource.attributes[i];
if (element.name === 'service.instance.id') {
return element.value?.toString();
}
}
}
return undefined;
}