-
Notifications
You must be signed in to change notification settings - Fork 383
Expand file tree
/
Copy pathproxy.js
More file actions
348 lines (300 loc) · 11.2 KB
/
proxy.js
File metadata and controls
348 lines (300 loc) · 11.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
'use strict'
const { getValueFromEnvSources } = require('./config/helper')
const NoopProxy = require('./noop/proxy')
const DatadogTracer = require('./tracer')
const getConfig = require('./config')
const runtimeMetrics = require('./runtime_metrics')
const log = require('./log')
const { setStartupLogPluginManager, startupLog } = require('./startup-log')
const DynamicInstrumentation = require('./debugger')
const telemetry = require('./telemetry')
const nomenclature = require('./service-naming')
const PluginManager = require('./plugin_manager')
const NoopDogStatsDClient = require('./noop/dogstatsd')
const { IS_SERVERLESS } = require('./serverless')
const {
setBaggageItem,
getBaggageItem,
getAllBaggageItems,
removeBaggageItem,
removeAllBaggageItems,
} = require('./baggage')
class LazyModule {
constructor (provider) {
this.provider = provider
}
enable (...args) {
this.module = this.provider()
this.module.enable(...args)
}
disable () {
this.module?.disable()
}
}
function lazyProxy (...args) {
if (IS_SERVERLESS === false) {
defineEagerly(...args)
} else {
defineLazily(...args)
}
}
function defineEagerly (obj, property, getClass, ...args) {
const RealClass = getClass()
obj[property] = new RealClass(...args)
}
function defineLazily (obj, property, getClass, ...args) {
Reflect.defineProperty(obj, property, {
get () {
const RealClass = getClass()
const value = new RealClass(...args)
Reflect.defineProperty(obj, property, { value, configurable: true, enumerable: true })
return value
},
configurable: true,
enumerable: true,
})
}
class Tracer extends NoopProxy {
constructor () {
super()
this._initialized = false
this._nomenclature = nomenclature
this._pluginManager = new PluginManager(this)
this.dogstatsd = new NoopDogStatsDClient()
this._tracingInitialized = false
this._flare = new LazyModule(() => require('./flare'))
this.setBaggageItem = setBaggageItem
this.getBaggageItem = getBaggageItem
this.getAllBaggageItems = getAllBaggageItems
this.removeBaggageItem = removeBaggageItem
this.removeAllBaggageItems = removeAllBaggageItems
// these requires must work with esm bundler
this._modules = {
appsec: new LazyModule(() => require('./appsec')),
iast: new LazyModule(() => require('./appsec/iast')),
llmobs: new LazyModule(() => require('./llmobs')),
rewriter: new LazyModule(() => require('./appsec/iast/taint-tracking/rewriter')),
openfeature: new LazyModule(() => require('./openfeature')),
}
}
/**
* @override
*/
init (options) {
if (this._initialized) return this
this._initialized = true
try {
const config = getConfig(options) // TODO: support dynamic code config
if (config.crashtracking.enabled) {
require('./crashtracking').start(config)
}
if (config.heapSnapshot.count > 0) {
require('./heap_snapshots').start(config)
}
telemetry.start(config, this._pluginManager)
if (config.dogstatsd) {
// Custom Metrics
lazyProxy(this, 'dogstatsd', () => require('./dogstatsd').CustomMetrics, config)
}
if (config.spanLeakDebug > 0) {
const spanleak = require('./spanleak')
if (config.spanLeakDebug === spanleak.MODES.LOG) {
spanleak.enableLogging()
} else if (config.spanLeakDebug === spanleak.MODES.GC_AND_LOG) {
spanleak.enableGarbageCollection()
}
spanleak.startScrubber()
}
if (config.remoteConfig.enabled && !config.isCiVisibility) {
const RemoteConfig = require('./remote_config')
const rc = new RemoteConfig(config)
const tracingRemoteConfig = require('./config/remote_config')
tracingRemoteConfig.enable(rc, config, () => {
this.#updateTracing(config)
this.#updateDebugger(config, rc)
})
rc.setProductHandler('AGENT_CONFIG', (action, conf) => {
if (!conf?.name?.startsWith('flare-log-level.')) return
if (action === 'unapply') {
this._flare.disable()
} else if (conf.config?.log_level) {
this._flare.enable(config)
this._flare.module.prepare(conf.config.log_level)
}
})
rc.setProductHandler('AGENT_TASK', (action, conf) => {
if (action === 'unapply' || !conf) return
if (conf.task_type !== 'tracer_flare' || !conf.args) return
this._flare.enable(config)
this._flare.module.send(conf.args)
})
if (this._modules.appsec) {
const appsecRemoteConfig = require('./appsec/remote_config')
appsecRemoteConfig.enable(rc, config, this._modules.appsec)
}
if (config.dynamicInstrumentation.enabled) {
DynamicInstrumentation.start(config, rc)
}
const openfeatureRemoteConfig = require('./openfeature/remote_config')
openfeatureRemoteConfig.enable(rc, config, () => this.openfeature)
}
if (config.profiling.enabled === 'true') {
this._profilerStarted = this._startProfiler(config)
} else {
this._profilerStarted = Promise.resolve(false)
if (config.profiling.enabled === 'auto') {
const { SSIHeuristics } = require('./profiling/ssi-heuristics')
const ssiHeuristics = new SSIHeuristics(config)
ssiHeuristics.start()
ssiHeuristics.onTriggered(() => {
this._startProfiler(config)
ssiHeuristics.onTriggered() // deregister this callback
})
}
}
if (config.runtimeMetrics.enabled) {
runtimeMetrics.start(config)
}
this.#updateTracing(config)
this._modules.rewriter.enable(config)
if (config.tracing && config.isManualApiEnabled) {
const TestApiManualPlugin = require('./ci-visibility/test-api-manual/test-api-manual-plugin')
this._testApiManualPlugin = new TestApiManualPlugin(this)
// `shouldGetEnvironmentData` is passed as false so that we only lazily calculate it
// This is the only place where we need to do this because the rest of the plugins
// are lazily configured when the library is imported.
this._testApiManualPlugin.configure({ ...config, enabled: true }, false)
}
if (config.ciVisAgentlessLogSubmissionEnabled) {
if (getValueFromEnvSources('DD_API_KEY')) {
const LogSubmissionPlugin = require('./ci-visibility/log-submission/log-submission-plugin')
const automaticLogPlugin = new LogSubmissionPlugin(this)
automaticLogPlugin.configure({ ...config, enabled: true })
} else {
log.warn(
// eslint-disable-next-line @stylistic/max-len
'DD_AGENTLESS_LOG_SUBMISSION_ENABLED is set, but DD_API_KEY is undefined, so no automatic log submission will be performed.'
)
}
}
if (config.otelLogsEnabled) {
const { initializeOpenTelemetryLogs } = require('./opentelemetry/logs')
initializeOpenTelemetryLogs(config)
}
if (config.otelMetricsEnabled) {
const { initializeOpenTelemetryMetrics } = require('./opentelemetry/metrics')
initializeOpenTelemetryMetrics(config)
}
if (config.isTestDynamicInstrumentationEnabled) {
const getDynamicInstrumentationClient = require('./ci-visibility/dynamic-instrumentation')
// We instantiate the client but do not start the Worker here. The worker is started lazily
getDynamicInstrumentationClient(config)
}
} catch (e) {
log.error('Error initialising tracer', e)
}
return this
}
_startProfiler (config) {
// do not stop tracer initialization if the profiler fails to be imported
try {
return require('./profiler').start(config)
} catch (e) {
log.error(
'Error starting profiler. For troubleshooting tips, see <https://dtdg.co/nodejs-profiler-troubleshooting>',
e
)
}
}
#updateTracing (config) {
if (config.tracing !== false) {
if (config.appsec.enabled) {
this._modules.appsec.enable(config)
}
if (config.llmobs.enabled) {
this._modules.llmobs.enable(config)
}
if (!this._tracingInitialized) {
const prioritySampler = config.apmTracingEnabled === false
? require('./standalone').configure(config)
: undefined
this._tracer = new DatadogTracer(config, prioritySampler)
this.dataStreamsCheckpointer = this._tracer.dataStreamsCheckpointer
lazyProxy(this, 'appsec', () => require('./appsec/sdk'), this._tracer, config)
lazyProxy(this, 'llmobs', () => require('./llmobs/sdk'), this._tracer, this._modules.llmobs, config)
if (config.experimental?.aiguard?.enabled) {
lazyProxy(this, 'aiguard', () => require('./aiguard/sdk'), this._tracer, config)
}
this._tracingInitialized = true
}
if (config.experimental.flaggingProvider.enabled) {
this._modules.openfeature.enable(config)
lazyProxy(this, 'openfeature', () => require('./openfeature/flagging_provider'), this._tracer, config)
}
if (config.iast.enabled) {
this._modules.iast.enable(config, this._tracer)
}
// This needs to be after the IAST module is enabled
} else if (this._tracingInitialized) {
this._modules.appsec.disable()
this._modules.iast.disable()
this._modules.llmobs.disable()
this._modules.openfeature.disable()
}
if (this._tracingInitialized) {
this._tracer.configure(config)
this._pluginManager.configure(config)
DynamicInstrumentation.configure(config)
setStartupLogPluginManager(this._pluginManager)
// Emit startup log immediately after tracer is fully initialized
startupLog()
}
}
/**
* Updates the debugger (Dynamic Instrumentation) state based on remote config changes.
* Handles starting, stopping, and reconfiguring the debugger dynamically.
*
* @param {object} config - The tracer configuration object
* @param {object} rc - The RemoteConfig instance
*/
#updateDebugger (config, rc) {
const shouldBeEnabled = config.dynamicInstrumentation.enabled
const isCurrentlyStarted = DynamicInstrumentation.isStarted()
if (shouldBeEnabled) {
if (isCurrentlyStarted) {
log.debug('[proxy] Reconfiguring Dynamic Instrumentation via remote config')
DynamicInstrumentation.configure(config)
} else {
log.debug('[proxy] Starting Dynamic Instrumentation via remote config')
DynamicInstrumentation.start(config, rc)
}
} else if (isCurrentlyStarted) {
log.debug('[proxy] Stopping Dynamic Instrumentation via remote config')
DynamicInstrumentation.stop()
}
}
/**
* @override
*/
profilerStarted () {
if (!this._profilerStarted) {
// injection hardening: this is only ever invoked from tests.
throw new Error('profilerStarted() must be called after init()')
}
return this._profilerStarted
}
/**
* @override
*/
use () {
this._pluginManager.configurePlugin(...arguments)
return this
}
/**
* @override
*/
get TracerProvider () {
return require('./opentelemetry/tracer_provider')
}
}
module.exports = Tracer