-
Notifications
You must be signed in to change notification settings - Fork 407
Expand file tree
/
Copy pathindex.js
More file actions
813 lines (727 loc) · 30.5 KB
/
Copy pathindex.js
File metadata and controls
813 lines (727 loc) · 30.5 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
'use strict'
const fs = require('node:fs')
const os = require('node:os')
const { URL, format } = require('node:url')
const { channel } = require('dc-polyfill')
const exporters = require('../../../../ext/exporters')
const rfdc = require('../../../../vendor/dist/rfdc')({ proto: false, circles: false })
const uuid = require('../../../../vendor/dist/crypto-randomuuid') // we need to keep the old uuid dep because of cypress
const set = require('../../../datadog-core/src/utils/src/set')
const { DD_MAJOR, NODE_MAJOR } = require('../../../../version')
const log = require('../log')
const pkg = require('../pkg')
const { isTrue } = require('../util')
const telemetry = require('../telemetry')
const telemetryMetrics = require('../telemetry/metrics')
const {
getServerlessPlatformTags,
IS_SERVERLESS,
getIsGCPFunction,
getIsAzureFunction,
} = require('../serverless')
const { ORIGIN_KEY, DATADOG_MINI_AGENT_PATH } = require('../constants')
const { appendRules } = require('../payload-tagging/config')
const ConfigBase = require('./config-base')
const {
getEnvironmentVariable,
getEnvironmentVariables,
getStableConfigSources,
getValueFromEnvSources,
} = require('./helper')
const {
defaults,
fallbackConfigurations,
configurationsTable,
optionsTable,
configWithOrigin,
parseErrors,
generateTelemetry,
warnInvalidValue,
} = require('./defaults')
const { normalizeService } = require('./normalize-service')
const { programmaticTypeCoercions, transformers } = require('./parsers')
const TEST_OPTIMIZATION_WORKER_EXPORTERS = new Set([
exporters.CUCUMBER_WORKER,
exporters.JEST_WORKER,
exporters.MOCHA_WORKER,
exporters.PLAYWRIGHT_WORKER,
exporters.VITEST_WORKER,
])
let runtimeId
channel('datadog:identity:update').subscribe(refreshRuntimeId)
/**
* Lazily generates the process-wide runtime ID on first access instead of at module load,
* so modules that merely require this file without constructing a Config never pay for it.
*
* @returns {string}
*/
function getRuntimeId () {
runtimeId ??= uuid()
return runtimeId
}
const tracerMetrics = telemetryMetrics.manager.namespace('tracers')
/**
* @typedef {'default'
* | 'code'
* | 'remote_config'
* | 'calculated'
* | 'env_var'
* | 'local_stable_config'
* | 'fleet_stable_config'} TelemetrySource
* @typedef {'remote_config' | 'calculated'} RevertibleTelemetrySource
* @typedef {import('../../../../index').TracerOptions} TracerOptions
* @typedef {import('./config-types').ConfigKey} ConfigKey
* @typedef {import('./config-types').ConfigPath} ConfigPath
* @typedef {import('./config-types').ConfigurationOption} ConfigurationOption
* @typedef {{
* value: import('./config-types').ConfigPathValue<ConfigPath>,
* source: TelemetrySource
* }} TrackedConfigEntry
* @typedef {{
* baseValuesByPath: Partial<Record<ConfigPath, TrackedConfigEntry>>,
* remote_config: Set<ConfigPath>,
* calculated: Set<ConfigPath>,
* }} ChangeTracker
*/
/** @type {Config | null} */
let configInstance = null
// An entry that is undefined means it is the default value.
/** @type {Map<ConfigPath, TelemetrySource>} */
const trackedConfigOrigins = new Map()
// ChangeTracker tracks the changes to the config up to programmatic options (code).
/** @type {ChangeTracker} */
const changeTracker = {
baseValuesByPath: {},
remote_config: new Set(),
calculated: new Set(),
}
/**
* @param {Config} config
* @param {RevertibleTelemetrySource} source
*/
function undo (config, source) {
for (const name of changeTracker[source]) {
const entry = changeTracker.baseValuesByPath[name] ?? { source: 'default', value: defaults[name] }
setAndTrack(config, name, entry.value, undefined, entry.source)
}
}
function get (object, path) {
// Fast path for simple property access.
if (object[path] !== undefined) {
return object[path]
}
let index = 0
while (true) {
const nextIndex = path.indexOf('.', index)
if (nextIndex === -1) {
return object[path.slice(index)]
}
object = object[path.slice(index, nextIndex)]
index = nextIndex + 1
}
}
/**
* @param {Config} config
* @template {ConfigPath} TPath
* @param {TPath} name
* @param {import('./config-types').ConfigPathValue<TPath>} value
* @param {unknown} [rawValue]
* @param {TelemetrySource} [source]
*/
function setAndTrack (config, name, value, rawValue = value, source = 'calculated') {
// envs can not be undefined
if (value == null) {
// TODO: This works as before while ignoring undefined programmatic options is not ideal.
if (source !== 'default') {
if (rawValue !== value) {
generateTelemetry(rawValue, source, name)
}
return
}
} else if (source === 'calculated' || source === 'remote_config') {
if (source === 'calculated' && value === get(config, name)) {
return
}
changeTracker[source].add(name)
} else {
// Programmatic-only options (e.g. logger, lookup, plugins) have no row in
// `configurationsTable` and hold opaque user-supplied references that may
// carry cycles or non-plain prototypes — for example a winston Logger
// extends a Transform stream. Use a reference for these instead of cloning.
const copy = typeof value === 'object' && value !== null && name in configurationsTable
? rfdc(value)
: value
changeTracker.baseValuesByPath[name] = { value: copy, source }
}
set(config, name, value)
generateTelemetry(rawValue, source, name)
if (source === 'default') {
trackedConfigOrigins.delete(name)
} else {
trackedConfigOrigins.set(name, source)
}
}
module.exports = getConfig
// We extend from ConfigBase to make our types work
class Config extends ConfigBase {
/**
* parsed DD_TAGS, usable as a standalone tag set across products
* @type {Record<string, string>}
*/
#parsedDdTags
/**
* @type {Record<string, string>}
*/
get parsedDdTags () {
return this.#parsedDdTags
}
/**
* @param {TracerOptions} [options]
*/
constructor (options = {}) {
super()
const configEnvSources = getStableConfigSources()
this.stableConfig = {
fleetEntries: configEnvSources.fleetStableConfig ?? {},
localEntries: configEnvSources.localStableConfig ?? {},
warnings: configEnvSources.stableConfigWarnings,
}
// Configure the logger first so it can be used to warn about other configs
// TODO: Implement auto buffering of inside of log module before first
// configure call. That way the logger is always available and the
// application doesn't need to configure it first and the configuration
// happens inside of config instead of inside of log module. If the logger
// is not deactivated, the buffered logs would be discarded. That way stable
// config warnings can also be logged directly and do not need special
// handling.
this.debug = log.configure(options)
// Process stable config warnings, if any
const stableConfigWarnings = this.stableConfig?.warnings
if (stableConfigWarnings) {
for (const warning of stableConfigWarnings) {
log.warn(warning)
}
}
this.#applyDefaults()
// TODO: Update origin documentation to list all valid sources. Add local_stable_config and fleet_stable_config.
this.#applyEnvs(getEnvironmentVariables(this.stableConfig.localEntries, true), 'local_stable_config')
this.#applyEnvs(getEnvironmentVariables(undefined, true), 'env_var')
this.#applyEnvs(getEnvironmentVariables(this.stableConfig.fleetEntries, true), 'fleet_stable_config')
// Experimental options are applied first, so they can be overridden by non-experimental options.
// TODO: When using programmatic options, check if there is a higher
// priority name in the same options object. Use the highest priority name.
const { experimental, ...rest } = options
if (experimental) {
// @ts-expect-error - Difficult to type this correctly.
this.#applyOptions(experimental, 'code', 'experimental')
}
this.#applyOptions(rest, 'code')
this.#applyCalculated()
warnWrongOtelSettings()
parseErrors.clear()
}
#applyDefaults () {
for (const [name, value] of Object.entries(defaults)) {
set(this, name, value)
}
}
/**
* @param {import('./helper').TracerEnv} envs
* @param {'env_var' | 'local_stable_config' | 'fleet_stable_config'} source
*/
#applyEnvs (envs, source) {
for (const [name, value] of Object.entries(envs)) {
const entry = configurationsTable[name]
const parsed = entry.parser(value, name, source)
const transformed = parsed !== undefined && entry.transformer ? entry.transformer(parsed, name, source) : parsed
const rawValue = transformed !== null && typeof transformed === 'object' ? value : parsed
setAndTrack(this, entry.property ?? name, transformed, rawValue, source)
}
}
/**
* @param {TracerOptions} options
* @param {'code' | 'remote_config'} source
* @param {string} [root]
*/
#applyOptions (options, source, root = '') {
for (const [name, value] of Object.entries(options)) {
const fullName = root ? `${root}.${name}` : name
let entry = optionsTable[fullName]
if (!entry) {
// TODO: Fix this by by changing remote config to use env styles.
if (name !== 'DD_TRACE_ENABLED' || source !== 'remote_config') {
log.warn('Unknown option %s with value %o', fullName, value)
continue
}
// @ts-expect-error - The entry is defined in the configurationsTable.
entry = configurationsTable.DD_TRACE_ENABLED
}
if (entry.nestedProperties) {
let matched = false
if (typeof value === 'object' && value !== null) {
for (const nestedProperty of entry.nestedProperties) {
// WARNING: if the property name might be part of the value we look at, this could conflict!
// Defining an option that receives an object as value may not contain a property that is also
// potentially a nested property!
if (Object.hasOwn(value, nestedProperty)) {
this.#applyOptions(value, source, fullName)
matched = true
break
}
}
}
if (matched) {
continue
}
if (entry.option) {
entry = entry.option
} else {
if (fullName === 'tracePropagationStyle') {
// TracePropagationStyle is special. It is a single option that is used to set both inject and extract.
// TODO: Consider what to do with this later
// @ts-expect-error - Difficult to type this correctly.
this.#applyOptions({ inject: value, extract: value }, source, 'tracePropagationStyle')
} else {
log.warn('Unknown option %s with value %o', fullName, value)
}
continue
}
}
const coerced = programmaticTypeCoercions[entry.type](value)
if (coerced === undefined && value !== undefined) {
warnInvalidValue(value, fullName, source, `Invalid ${entry.type} input`)
}
const transformed = coerced !== undefined && entry.transformer
? entry.transformer(coerced, fullName, source)
: coerced
setAndTrack(this, entry.property ?? name, transformed, value, source)
}
}
/**
* Set the configuration with remote config settings.
* Applies remote configuration, recalculates derived values, and merges all configuration sources.
*
* @param {TracerOptions|null} options - Configurations received via Remote
* Config or null to reset all remote configuration
*/
setRemoteConfig (options) {
// Clear all RC-managed fields to ensure previous values don't persist.
// State is instead managed by the `RCClientLibConfigManager` class
undo(this, 'remote_config')
// Special case: if options is null, nothing to apply
// This happens when all remote configs are removed
if (options !== null) {
this.#applyOptions(options, 'remote_config')
}
this.#applyCalculated()
}
/**
* @param {ConfigPath} name
*/
getOrigin (name) {
return trackedConfigOrigins.get(name) ?? 'default'
}
// Handles values calculated from a mixture of options and env vars
#applyCalculated () {
undo(this, 'calculated')
if (this.featureFlags.DD_FEATURE_FLAGS_ENABLED &&
!trackedConfigOrigins.has('featureFlags.DD_FEATURE_FLAGS_CONFIGURATION_SOURCE') &&
trackedConfigOrigins.has('experimental.flaggingProvider.enabled')) {
if (this.experimental.flaggingProvider.enabled) {
setAndTrack(this, 'featureFlags.DD_FEATURE_FLAGS_CONFIGURATION_SOURCE', 'remote_config')
} else {
setAndTrack(this, 'featureFlags.DD_FEATURE_FLAGS_ENABLED', false)
}
}
const configurationSource = this.featureFlags.DD_FEATURE_FLAGS_CONFIGURATION_SOURCE
if (this.featureFlags.DD_FEATURE_FLAGS_ENABLED &&
configurationSource !== 'agentless' &&
configurationSource !== 'remote_config') {
warnInvalidValue(
configurationSource,
'DD_FEATURE_FLAGS_CONFIGURATION_SOURCE',
this.getOrigin('featureFlags.DD_FEATURE_FLAGS_CONFIGURATION_SOURCE'),
'Unsupported Feature Flagging configuration source',
undefined,
'provider disabled'
)
setAndTrack(this, 'featureFlags.DD_FEATURE_FLAGS_ENABLED', false)
}
if (this.url ||
os.type() !== 'Windows_NT' &&
!trackedConfigOrigins.has('hostname') &&
!trackedConfigOrigins.has('port') &&
fs.existsSync('/var/run/datadog/apm.socket')) {
setAndTrack(this, 'url', new URL(this.url || 'unix:///var/run/datadog/apm.socket'))
} else {
setAndTrack(this, 'url', new URL(format({ protocol: 'http:', hostname: this.hostname, port: this.port })))
}
if (this.isCiVisibility) {
setAndTrack(this, 'isServiceUserProvided', trackedConfigOrigins.has('service'))
this.tags[ORIGIN_KEY] = 'ciapp-test'
}
// Compute OTLP logs and metrics URLs to send payloads to the active Datadog Agent
const agentHostname = this.hostname || /** @type {URL} */ (this.url).hostname
if (!trackedConfigOrigins.has('dogstatsd.hostname')) {
setAndTrack(this, 'dogstatsd.hostname', agentHostname)
}
// Disable log injection when OTEL logs are enabled
// OTEL logs and DD log injection are mutually exclusive
if (this.DD_LOGS_OTEL_ENABLED) {
setAndTrack(this, 'logInjection', false)
}
if (this.DD_METRICS_OTEL_ENABLED &&
trackedConfigOrigins.has('OTEL_METRICS_EXPORTER') &&
this.OTEL_METRICS_EXPORTER === 'none') {
setAndTrack(this, 'DD_METRICS_OTEL_ENABLED', false)
}
if (this.OTEL_TRACES_EXPORTER === 'otlp' && trackedConfigOrigins.has('protocolVersion')) {
log.warn('DD_TRACE_AGENT_PROTOCOL_VERSION is set, disabling OTLP traces export')
setAndTrack(this, 'OTEL_TRACES_EXPORTER', 'none')
}
if (this.telemetry.DD_TELEMETRY_HEARTBEAT_INTERVAL) {
setAndTrack(this, 'telemetry.DD_TELEMETRY_HEARTBEAT_INTERVAL',
Math.floor(this.telemetry.DD_TELEMETRY_HEARTBEAT_INTERVAL * 1000))
}
// Allocation profiling needs a sampling hook only available on Node.js 26+.
setAndTrack(this, 'DD_PROFILING_ALLOCATION_ENABLED', NODE_MAJOR >= 26 && this.DD_PROFILING_ALLOCATION_ENABLED)
if (this.telemetry.DD_TELEMETRY_EXTENDED_HEARTBEAT_INTERVAL) {
setAndTrack(this, 'telemetry.DD_TELEMETRY_EXTENDED_HEARTBEAT_INTERVAL',
Math.floor(this.telemetry.DD_TELEMETRY_EXTENDED_HEARTBEAT_INTERVAL * 1000))
}
// Enable resource renaming when appsec is enabled and only
// if DD_TRACE_RESOURCE_RENAMING_ENABLED is not explicitly set
if (!trackedConfigOrigins.has('DD_TRACE_RESOURCE_RENAMING_ENABLED')) {
setAndTrack(this, 'DD_TRACE_RESOURCE_RENAMING_ENABLED', this.appsec.enabled ?? false)
}
if (!trackedConfigOrigins.has('spanComputePeerService') && this.spanAttributeSchema !== 'v0') {
setAndTrack(this, 'spanComputePeerService', true)
}
if (!this.apmTracingEnabled) {
setAndTrack(this, 'stats.DD_TRACE_STATS_COMPUTATION_ENABLED', false)
} else if (!trackedConfigOrigins.has('stats.DD_TRACE_STATS_COMPUTATION_ENABLED')) {
setAndTrack(this, 'stats.DD_TRACE_STATS_COMPUTATION_ENABLED', getIsGCPFunction() || getIsAzureFunction())
}
// TODO: Remove the experimental env vars as a major or deprecate the option?
if (this.experimental?.b3) {
if (!this.tracePropagationStyle.inject.includes('b3')) {
this.tracePropagationStyle.inject.push('b3')
}
if (!this.tracePropagationStyle.extract.includes('b3')) {
this.tracePropagationStyle.extract.push('b3')
}
if (!this.tracePropagationStyle.inject.includes('b3 single header')) {
this.tracePropagationStyle.inject.push('b3 single header')
}
if (!this.tracePropagationStyle.extract.includes('b3 single header')) {
this.tracePropagationStyle.extract.push('b3 single header')
}
setAndTrack(this, 'tracePropagationStyle.inject', this.tracePropagationStyle.inject)
setAndTrack(this, 'tracePropagationStyle.extract', this.tracePropagationStyle.extract)
}
if (getEnvironmentVariable('AWS_LAMBDA_FUNCTION_NAME') && !fs.existsSync(DATADOG_MINI_AGENT_PATH)) {
setAndTrack(this, 'flushInterval', 0)
}
if (!trackedConfigOrigins.has('apmTracingEnabled') &&
trackedConfigOrigins.has('experimental.appsec.standalone.enabled')) {
setAndTrack(this, 'apmTracingEnabled', !this.experimental.appsec.standalone.enabled)
}
if (this.cloudPayloadTagging?.request || this.cloudPayloadTagging?.response) {
setAndTrack(this, 'cloudPayloadTagging.rules', appendRules(
this.cloudPayloadTagging.request,
this.cloudPayloadTagging.response
))
}
if (this.DD_INJECTION_ENABLED) {
setAndTrack(this, 'instrumentationSource', 'ssi')
}
if (!trackedConfigOrigins.has('runtimeMetrics.enabled') && this.OTEL_METRICS_EXPORTER === 'none') {
setAndTrack(this, 'runtimeMetrics.enabled', false)
}
// Apply the OTel sampler when the user opted into OTel traces or explicitly set the sampler.
// OTEL_TRACES_SAMPLER has `default: parentbased_always_on` (per OTel spec), so opt-in users
// that don't set the sampler still get parent-based sampling.
if (!trackedConfigOrigins.has('sampleRate') &&
(trackedConfigOrigins.has('OTEL_TRACES_SAMPLER') || this.OTEL_TRACES_EXPORTER === 'otlp')) {
setAndTrack(this, 'sampleRate',
getFromOtelSamplerMap(this.OTEL_TRACES_SAMPLER, this.OTEL_TRACES_SAMPLER_ARG))
}
if (this.DD_SPAN_SAMPLING_RULES_FILE) {
try {
// TODO: Should we log a warning in case this is defined next to spanSamplingRules?
setAndTrack(this, 'spanSamplingRules', transformers.toCamelCase(JSON.parse(this.DD_SPAN_SAMPLING_RULES_FILE)))
} catch (error) {
log.warn('Error reading span sampling rules file %s; %o', this.DD_SPAN_SAMPLING_RULES_FILE, error)
}
}
// All sampler options are tracked as individual values. No need to track the sampler object as a whole.
this.sampler = {
rules: this.samplingRules,
rateLimit: this.rateLimit,
sampleRate: this.sampleRate,
spanSamplingRules: this.spanSamplingRules,
}
// For LLMObs, we want to auto enable it when other llmobs options are defined.
if (!this.llmobs.DD_LLMOBS_ENABLED &&
!trackedConfigOrigins.has('llmobs.DD_LLMOBS_ENABLED') &&
(trackedConfigOrigins.has('llmobs.agentlessEnabled') ||
trackedConfigOrigins.has('llmobs.mlApp'))) {
setAndTrack(this, 'llmobs.DD_LLMOBS_ENABLED', true)
}
if (this.OTEL_RESOURCE_ATTRIBUTES) {
for (const [key, value] of Object.entries(this.OTEL_RESOURCE_ATTRIBUTES)) {
// Not replacing existing tags keeps the order of the tags as before.
if (!this.tags[key]) {
this.tags[key] = value
}
}
}
if (this.DD_TRACE_TAGS) {
// TODO: This is a hack to keep the order of the tags as before.
// That hack is not sufficient, since it does not handle other cases where the tags are set by the user.
if (trackedConfigOrigins.get('tags') === 'code') {
for (const [key, value] of Object.entries(this.DD_TRACE_TAGS)) {
// Not replacing existing tags keeps the order of the tags as before.
if (!this.tags[key]) {
this.tags[key] = value
}
}
} else {
Object.assign(this.tags, this.DD_TRACE_TAGS)
}
}
if (!this.#parsedDdTags) {
this.#parsedDdTags = rfdc(this.tags)
}
if (!this.env && this.tags.env !== undefined) {
setAndTrack(this, 'env', this.tags.env)
}
if (!this.version) {
setAndTrack(this, 'version', this.tags.version || pkg.version)
this.tags.version ??= pkg.version
}
let isServiceNameInferred = false
if (!trackedConfigOrigins.has('service')) {
if (this.tags.service) {
setAndTrack(this, 'service', this.tags.service)
} else {
const NX_TASK_TARGET_PROJECT = getEnvironmentVariable('NX_TASK_TARGET_PROJECT')
if (NX_TASK_TARGET_PROJECT) {
if (DD_MAJOR >= 6 || this.DD_ENABLE_NX_SERVICE_NAME) {
setAndTrack(this, 'service', normalizeService(NX_TASK_TARGET_PROJECT) || 'node')
isServiceNameInferred = true
} else if (DD_MAJOR < 6) {
log.warn(
// eslint-disable-next-line eslint-rules/eslint-log-printf-style
'NX_TASK_TARGET_PROJECT is set but no service name was configured. In v6, NX_TASK_TARGET_PROJECT will ' +
'be used as the default service name. Set DD_ENABLE_NX_SERVICE_NAME=true to opt-in to this behavior ' +
'now, or set a service name explicitly.'
)
}
}
}
if (!this.service) {
const serverlessName = IS_SERVERLESS
? (
getEnvironmentVariable('AWS_LAMBDA_FUNCTION_NAME') ||
getEnvironmentVariable('FUNCTION_NAME') || // Google Cloud Function Name set by deprecated runtimes
getEnvironmentVariable('K_SERVICE') || // Google Cloud Function Name set by newer runtimes
getEnvironmentVariable('WEBSITE_SITE_NAME') // set by Azure Functions
)
: undefined
setAndTrack(this, 'service', normalizeService(serverlessName) || normalizeService(pkg.name) || 'node')
this.tags.service ??= /** @type {string} */ (this.service)
isServiceNameInferred = true
}
}
// This should not be tracked.
// TODO: Consider moving this outside of the config.
set(this, 'isServiceNameInferred', isServiceNameInferred)
// Add missing tags, in case they are defined otherwise.
if (this.service) {
this.tags.service = this.service
}
if (this.env) {
this.tags.env = this.env
}
if (this.version) {
this.tags.version = this.version
}
this.tags['runtime-id'] = getRuntimeId()
const platformTags = getServerlessPlatformTags()
if (platformTags) {
for (let i = 0; i < platformTags.length; i += 2) {
this.tags[platformTags[i]] ??= platformTags[i + 1]
}
}
if (IS_SERVERLESS) {
setAndTrack(this, 'telemetry.DD_INSTRUMENTATION_TELEMETRY_ENABLED', false)
setAndTrack(this, 'DD_CRASHTRACKING_ENABLED', false)
setAndTrack(this, 'remoteConfig.DD_REMOTE_CONFIGURATION_ENABLED', false)
}
const isTestOptimizationWorker = this.isCiVisibility &&
TEST_OPTIMIZATION_WORKER_EXPORTERS.has(this.experimental.exporter)
if (isTestOptimizationWorker) {
setAndTrack(this, 'telemetry.DD_INSTRUMENTATION_TELEMETRY_ENABLED', false)
}
// Experimental agentless APM span intake
// When enabled, sends spans directly to Datadog intake without an agent
// TODO: Replace this with a proper configuration
const agentlessEnabled = isTrue(getEnvironmentVariable('_DD_APM_TRACING_AGENTLESS_ENABLED'))
if (agentlessEnabled) {
setAndTrack(this, 'experimental.exporter', 'agentless')
// Disable client-side stats computation
setAndTrack(this, 'stats.DD_TRACE_STATS_COMPUTATION_ENABLED', false)
// Enable hostname reporting
setAndTrack(this, 'reportHostname', true)
// Disable rate limiting - server-side sampling will be used
setAndTrack(this, 'sampler.rateLimit', -1)
// Clear sampling rules - server-side sampling handles this
setAndTrack(this, 'sampler.rules', [])
// Agentless intake only accepts 64-bit trace IDs; disable 128-bit generation
if (!trackedConfigOrigins.has('traceId128BitGenerationEnabled')) {
setAndTrack(this, 'traceId128BitGenerationEnabled', false)
}
}
// Apply all fallbacks to the calculated config.
for (const [configName, alias] of fallbackConfigurations) {
if (!trackedConfigOrigins.has(configName) && trackedConfigOrigins.has(alias)) {
setAndTrack(this, configName, this[alias])
}
}
// TODO: This could likely be moved to the base class and allow easier GRPC handling
// Default OTLP endpoints follow the configured agent host so users who point DD at a custom
// agent (DD_AGENT_HOST / DD_TRACE_AGENT_URL) also reach OTLP on that host.
const defaultOtlpBase = this.OTEL_EXPORTER_OTLP_ENDPOINT?.replace(/\/$/, '') ?? `http://${agentHostname}:4318`
if (!this.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT) {
setAndTrack(this, 'OTEL_EXPORTER_OTLP_LOGS_ENDPOINT', `${defaultOtlpBase}/v1/logs`)
}
if (!this.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT) {
setAndTrack(this, 'OTEL_EXPORTER_OTLP_METRICS_ENDPOINT', `${defaultOtlpBase}/v1/metrics`)
}
if (!this.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT) {
setAndTrack(this, 'OTEL_EXPORTER_OTLP_TRACES_ENDPOINT', `${defaultOtlpBase}/v1/traces`)
}
const autoTraceMetrics = this.OTEL_TRACES_EXPORTER === 'otlp' && this.DD_METRICS_OTEL_ENABLED === true
setAndTrack(this, 'OTEL_TRACES_SPAN_METRICS_ENABLED', this.OTEL_TRACES_SPAN_METRICS_ENABLED ?? autoTraceMetrics)
if (this.OTEL_TRACES_SPAN_METRICS_ENABLED) {
this.stats = { ...this.stats, DD_TRACE_STATS_COMPUTATION_ENABLED: true }
}
const flushInterval = getValueFromEnvSources('_DD_TRACE_METRICS_OTEL_FLUSH_INTERVAL')
setAndTrack(this, '_DD_TRACE_METRICS_OTEL_FLUSH_INTERVAL', flushInterval)
if (process.platform === 'win32') {
// OOM monitoring does not work properly on Windows, so it will be disabled.
deactivateIfEnabledAndWarnOnWindows(this, 'DD_PROFILING_EXPERIMENTAL_OOM_MONITORING_ENABLED')
// Profiler sampling contexts are not available on Windows, so features
// depending on those (code hotspots and endpoint collection) need to be disabled on Windows.
deactivateIfEnabledAndWarnOnWindows(this, 'DD_PROFILING_CODEHOTSPOTS_ENABLED')
deactivateIfEnabledAndWarnOnWindows(this, 'DD_PROFILING_ENDPOINT_COLLECTION_ENABLED')
deactivateIfEnabledAndWarnOnWindows(this, 'DD_PROFILING_CPU_ENABLED')
deactivateIfEnabledAndWarnOnWindows(this, 'DD_PROFILING_TIMELINE_ENABLED')
deactivateIfEnabledAndWarnOnWindows(this, 'DD_PROFILING_ASYNC_CONTEXT_FRAME_ENABLED')
}
// Single tags update is tracked as a calculated value.
setAndTrack(this, 'tags', this.tags)
telemetry.updateConfig([...configWithOrigin.values()], this)
}
}
/**
* @param {Config} config
* @param {ConfigKey} envVar
*/
function deactivateIfEnabledAndWarnOnWindows (config, envVar) {
if (config[envVar]) {
const source = trackedConfigOrigins.get(envVar)
setAndTrack(config, envVar, false)
// TODO: Should we log even for default values?
if (source) {
log.warn('%s is not supported on Windows. Deactivating. (source: %s)', envVar, source)
}
}
}
function increaseCounter (event, ddVar, otelVar) {
const tags = []
if (ddVar) {
tags.push(`config_datadog:${ddVar.toLowerCase()}`)
}
tags.push(`config_opentelemetry:${otelVar.toLowerCase()}`)
tracerMetrics.count(event, tags).inc()
}
function getFromOtelSamplerMap (otelTracesSampler, otelTracesSamplerArg) {
const NON_PARENTBASED_TO_PARENTBASED = {
always_on: 'parentbased_always_on',
always_off: 'parentbased_always_off',
traceidratio: 'parentbased_traceidratio',
}
const OTEL_TRACES_SAMPLER_MAPPING = {
parentbased_always_on: 1,
parentbased_always_off: 0,
}
const parentBasedEquivalent = NON_PARENTBASED_TO_PARENTBASED[otelTracesSampler]
if (parentBasedEquivalent) {
log.info(
'OTEL_TRACES_SAMPLER=%s does not respect upstream sampling decisions; using parent-based equivalent %s instead',
otelTracesSampler, parentBasedEquivalent
)
otelTracesSampler = parentBasedEquivalent
}
const result = OTEL_TRACES_SAMPLER_MAPPING[otelTracesSampler] ?? otelTracesSamplerArg
if (result === undefined) {
increaseCounter('otel.env.invalid', 'DD_TRACE_SAMPLE_RATE', 'OTEL_TRACES_SAMPLER')
}
return result
}
function warnWrongOtelSettings () {
// This mostly works for non-aliased environment variables only.
// TODO: Adjust this to work across all sources.
for (const [otelEnvVar, ddEnvVar, key] of [
// eslint-disable-next-line eslint-rules/eslint-env-aliases
['OTEL_LOG_LEVEL', 'DD_TRACE_LOG_LEVEL', 'logLevel'],
// eslint-disable-next-line eslint-rules/eslint-env-aliases
['OTEL_PROPAGATORS', 'DD_TRACE_PROPAGATION_STYLE', 'DD_TRACE_PROPAGATION_STYLE'],
// eslint-disable-next-line eslint-rules/eslint-env-aliases
['OTEL_SERVICE_NAME', 'DD_SERVICE', 'service'],
['OTEL_TRACES_SAMPLER', 'DD_TRACE_SAMPLE_RATE'],
['OTEL_TRACES_SAMPLER_ARG', 'DD_TRACE_SAMPLE_RATE'],
['OTEL_TRACES_EXPORTER', 'DD_TRACE_ENABLED'],
['OTEL_METRICS_EXPORTER', 'DD_RUNTIME_METRICS_ENABLED'],
['OTEL_RESOURCE_ATTRIBUTES', 'DD_TAGS'],
['OTEL_SDK_DISABLED', 'DD_TRACE_OTEL_ENABLED'],
['OTEL_LOGS_EXPORTER'],
]) {
// eslint-disable-next-line eslint-rules/eslint-process-env
const envs = process.env
const otelSource = trackedConfigOrigins.get(/** @type {ConfigPath} */ (key ?? otelEnvVar))
const otelEnvValue = envs[otelEnvVar]
if (otelEnvValue) {
if (envs[ddEnvVar]) {
log.warn('Conflicting %s and %s environment variables are set for %s', ddEnvVar, otelEnvVar, otelSource)
increaseCounter('otel.env.hiding', ddEnvVar, otelEnvVar)
}
const invalidOtelValue = !otelSource
if (invalidOtelValue) {
increaseCounter('otel.env.invalid', ddEnvVar, otelEnvVar)
}
}
}
}
/**
* @param {TracerOptions} [options]
*/
function getConfig (options) {
if (!configInstance) {
configInstance = new Config(options)
}
return configInstance
}
/**
* Regenerates the runtime ID.
*
* Used for Lambda MicroVM `/run` lifecycle hooks, giving each clone a distinct runtime identity.
*
* @param {import('./config-base')} config
*/
function refreshRuntimeId (config) {
runtimeId = uuid()
config.tags['runtime-id'] = runtimeId
}