libdd-library-config 5.0.1

Configuration management library for Datadog products.
Documentation
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
// Copyright 2023-Present Datadog, Inc. https://www.datadoghq.com/
// SPDX-License-Identifier: Apache-2.0
use libdd_trace_protobuf::opentelemetry::proto as otel_proto;

/// Thread-level context metadata the tracer wants to publish as part of the OTel process context.
/// Set [TracerMetadata::threadlocal_metadata] to `Some(_)` to enable the threadlocal section; the
/// fields inside then drive its contents.
#[cfg(feature = "otel-thread-ctx")]
#[derive(Debug, PartialEq, Default)]
pub struct ThreadLocalMetadata {
    /// Ordered list of attribute key names for thread-level context records. Key indices from
    /// thread context records index into this table.
    ///
    /// The first key is automatically set to `datadog.local_root_span_id` in the OTel process
    /// context, because the thread context handling elsewhere in libdatadog relies on this key's
    /// index to be zero. Only set additional keys here; the root span id is considered to always
    /// be present implicitly.
    pub attribute_keys: Vec<String>,

    /// Identifies the record schema the writer publishes (e.g. `"tlsdesc_v1_dev"` for
    /// libdatadog's own writer, `"nodejs_v1_dev"` for a Node.js writer). Defaults to
    /// `"tlsdesc_v1_dev"` when `None`.
    pub schema_version: Option<String>,

    /// Extra OTel process-context attributes the threadlocal writer wants to publish alongside the
    /// key map (e.g. language-runtime layout constants that the reader needs to know about). Each
    /// entry is emitted verbatim as a KeyValue.
    pub extra_attributes: Vec<(String, otel_proto::common::v1::any_value::Value)>,
}

/// This struct MUST be backward compatible.
#[derive(serde::Serialize, Debug, PartialEq)]
pub struct TracerMetadata {
    /// Version of the schema.
    pub schema_version: u8,
    /// Runtime UUID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub runtime_id: Option<String>,
    /// Programming language of the tracer library (e.g., “python”). Refers to telemetry
    /// for valid values.
    pub tracer_language: String,
    /// Version of the tracer (e.g., "1.0.0").
    pub tracer_version: String,
    /// Identifier of the machine running the process.
    pub hostname: String,
    /// Name of the service being instrumented.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service_name: Option<String>,
    /// Environment of the service being instrumented.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service_env: Option<String>,
    /// Version of the service being instrumented.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub service_version: Option<String>,
    /// Process tags of the application being instrumented.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub process_tags: Option<String>,
    /// Container id seen by the application.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub container_id: Option<String>,
    /// Thread-level context metadata; emit a `threadlocal.*` block in the OTel process context
    /// when `Some`. `None` disables the section entirely. See [ThreadLocalMetadata]. Ignored for
    /// (de)serialization; only used when converting to an OTel process context in
    /// [TracerMetadata::to_otel_process_ctx].
    #[cfg(feature = "otel-thread-ctx")]
    #[serde(skip)]
    pub threadlocal_metadata: Option<ThreadLocalMetadata>,
}

impl Default for TracerMetadata {
    fn default() -> Self {
        TracerMetadata {
            schema_version: 2,
            runtime_id: None,
            tracer_language: String::new(),
            tracer_version: String::new(),
            hostname: String::new(),
            service_name: None,
            service_env: None,
            service_version: None,
            process_tags: None,
            container_id: None,
            #[cfg(feature = "otel-thread-ctx")]
            threadlocal_metadata: None,
        }
    }
}

impl TracerMetadata {
    // The value of the telemetry.sdk.name field to put in the otel context resource.
    const OTEL_SDK_NAME: &str = "libdatadog";

    pub fn to_otel_process_ctx(&self) -> otel_proto::common::v1::ProcessContext {
        #[cfg(feature = "otel-thread-ctx")]
        use otel_proto::common::v1::ArrayValue;
        use otel_proto::{
            common::v1::{AnyValue, KeyValue, ProcessContext, any_value},
            resource::v1::Resource,
        };

        fn key_value(key: &'static str, val: String) -> KeyValue {
            KeyValue {
                key: key.to_owned(),
                value: Some(AnyValue {
                    value: Some(any_value::Value::StringValue(val)),
                }),
                key_ref: 0,
            }
        }

        fn key_value_if_some(key: &'static str, val: &Option<String>) -> Option<KeyValue> {
            val.as_ref().map(|val| key_value(key, val.clone()))
        }

        // Every field of `self` should get propagated to the otel context.
        // If you add a new field, please also add it here and as a key/value in the otel context.
        let TracerMetadata {
            // This one isn't propagated on purpose
            schema_version: _,
            runtime_id,
            tracer_language,
            tracer_version,
            hostname,
            service_name,
            service_env,
            service_version,
            process_tags,
            container_id,
            #[cfg(feature = "otel-thread-ctx")]
            threadlocal_metadata,
        } = self;

        let resource_attrs = [
            key_value_if_some("service.name", service_name),
            key_value_if_some("service.instance.id", runtime_id),
            key_value_if_some("service.version", service_version),
            key_value_if_some("deployment.environment.name", service_env),
            Some(key_value("telemetry.sdk.language", tracer_language.clone())),
            Some(key_value("telemetry.sdk.version", tracer_version.clone())),
            Some(key_value(
                "telemetry.sdk.name",
                Self::OTEL_SDK_NAME.to_owned(),
            )),
            Some(key_value("host.name", hostname.clone())),
            key_value_if_some("container.id", container_id),
        ]
        .into_iter()
        .flatten()
        .collect();

        // `mut` is only needed when `otel-thread-ctx` is enabled.
        #[allow(unused_mut)]
        let mut extra_attributes: Vec<_> = key_value_if_some("datadog.process_tags", process_tags)
            .into_iter()
            .collect();

        #[cfg(feature = "otel-thread-ctx")]
        if let Some(ThreadLocalMetadata {
            attribute_keys,
            schema_version,
            extra_attributes: threadlocal_extras,
        }) = threadlocal_metadata.as_ref()
        {
            extra_attributes.push(key_value(
                "threadlocal.schema_version",
                schema_version
                    .clone()
                    .unwrap_or_else(|| "tlsdesc_v1_dev".to_owned()),
            ));

            extra_attributes.push(KeyValue {
                key: "threadlocal.attribute_key_map".to_owned(),
                value: Some(AnyValue {
                    value: Some(any_value::Value::ArrayValue(ArrayValue {
                        values: core::iter::once(AnyValue {
                            value: Some(any_value::Value::StringValue(
                                "datadog.local_root_span_id".to_owned(),
                            )),
                        })
                        .chain(attribute_keys.iter().map(|k| AnyValue {
                            value: Some(any_value::Value::StringValue(k.clone())),
                        }))
                        .collect(),
                    })),
                }),
                key_ref: 0,
            });

            extra_attributes.extend(threadlocal_extras.iter().map(|(k, v)| KeyValue {
                key: k.clone(),
                value: Some(AnyValue {
                    value: Some(v.clone()),
                }),
                key_ref: 0,
            }));
        }

        ProcessContext {
            resource: Some(Resource {
                attributes: resource_attrs,
                dropped_attributes_count: 0,
                entity_refs: vec![],
            }),
            extra_attributes,
        }
    }
}

pub enum AnonymousFileHandle {
    #[cfg(target_os = "linux")]
    Linux(memfd::Memfd),
    #[cfg(not(target_os = "linux"))]
    Other(()),
}

#[cfg(target_os = "linux")]
mod linux {
    use anyhow::Context;
    use rand::Rng;
    use rand::distributions::Alphanumeric;
    use std::io::Write;

    /// Create a memfd file storing the tracer metadata. This function also attempts to publish the
    /// tracer metadata as an OTel process context separately, but will ignore resulting errors.
    pub fn store_tracer_metadata(
        data: &super::TracerMetadata,
    ) -> anyhow::Result<super::AnonymousFileHandle> {
        #[cfg(feature = "process-context-writer")]
        let _ = crate::otel_process_ctx::publish(&data.to_otel_process_ctx());

        let uid: String = rand::thread_rng()
            .sample_iter(&Alphanumeric)
            .take(8)
            .map(char::from)
            .collect();

        let mfd_name: String = format!("datadog-tracer-info-{uid}");

        let mfd = memfd::MemfdOptions::default()
            .close_on_exec(true)
            .allow_sealing(true)
            .create::<&str>(mfd_name.as_ref())
            .context("unable to create memfd")?;

        let buf = rmp_serde::to_vec_named(data).context("failed serialization")?;
        mfd.as_file()
            .write_all(&buf)
            .context("unable to write into memfd")?;

        mfd.add_seals(&[
            memfd::FileSeal::SealShrink,
            memfd::FileSeal::SealGrow,
            memfd::FileSeal::SealSeal,
        ])
        .context("unable to seal memfd")?;

        Ok(super::AnonymousFileHandle::Linux(mfd))
    }
}

#[cfg(not(target_os = "linux"))]
mod other {
    pub fn store_tracer_metadata(
        _data: &super::TracerMetadata,
    ) -> anyhow::Result<super::AnonymousFileHandle> {
        Ok(super::AnonymousFileHandle::Other(()))
    }
}

#[cfg(target_os = "linux")]
pub use linux::*;
#[cfg(not(target_os = "linux"))]
pub use other::*;

#[cfg(test)]
mod tests {
    use super::*;
    use libdd_trace_protobuf::opentelemetry::proto::common::v1::any_value;
    use libdd_trace_protobuf::opentelemetry::proto::common::v1::{AnyValue, ProcessContext};

    fn find_extra_attr<'a>(ctx: &'a ProcessContext, key: &str) -> Option<&'a AnyValue> {
        ctx.extra_attributes
            .iter()
            .find(|kv| kv.key == key)?
            .value
            .as_ref()
    }

    fn find_resource_attr<'a>(ctx: &'a ProcessContext, key: &str) -> Option<&'a AnyValue> {
        ctx.resource
            .as_ref()?
            .attributes
            .iter()
            .find(|kv| kv.key == key)?
            .value
            .as_ref()
    }

    #[test]
    fn tracer_metadata_equality() {
        let a = TracerMetadata {
            tracer_language: "python".into(),
            ..Default::default()
        };
        let b = TracerMetadata {
            tracer_language: "python".into(),
            ..Default::default()
        };
        let c = TracerMetadata {
            tracer_language: "ruby".into(),
            ..Default::default()
        };

        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn absent_optional_metadata_is_omitted_from_process_context() {
        let ctx = TracerMetadata::default().to_otel_process_ctx();

        for key in [
            "service.name",
            "service.instance.id",
            "service.version",
            "deployment.environment.name",
            "container.id",
        ] {
            assert!(find_resource_attr(&ctx, key).is_none(), "unexpected {key}");
        }
        assert!(find_extra_attr(&ctx, "datadog.process_tags").is_none());
        assert!(find_extra_attr(&ctx, "threadlocal.schema_version").is_none());
        assert!(find_extra_attr(&ctx, "threadlocal.attribute_key_map").is_none());
    }

    #[test]
    fn present_optional_metadata_is_emitted_in_process_context() {
        let ctx = TracerMetadata {
            runtime_id: Some("runtime-id".to_owned()),
            service_name: Some("checkout".to_owned()),
            service_env: Some("production".to_owned()),
            service_version: Some("1.2.3".to_owned()),
            process_tags: Some("region:us-east-1".to_owned()),
            container_id: Some("container-id".to_owned()),
            ..Default::default()
        }
        .to_otel_process_ctx();

        for (key, expected) in [
            ("service.name", "checkout"),
            ("service.instance.id", "runtime-id"),
            ("service.version", "1.2.3"),
            ("deployment.environment.name", "production"),
            ("container.id", "container-id"),
        ] {
            assert_eq!(
                find_resource_attr(&ctx, key).and_then(|value| value.value.as_ref()),
                Some(&any_value::Value::StringValue(expected.to_owned()))
            );
        }
        assert_eq!(
            find_extra_attr(&ctx, "datadog.process_tags").and_then(|value| value.value.as_ref()),
            Some(&any_value::Value::StringValue(
                "region:us-east-1".to_owned()
            ))
        );
    }

    #[cfg(feature = "otel-thread-ctx")]
    #[test]
    fn threadlocal_attrs_present_with_correct_values() {
        let ctx = TracerMetadata {
            threadlocal_metadata: Some(ThreadLocalMetadata {
                attribute_keys: vec![
                    "span.id".to_owned(),
                    "trace.id".to_owned(),
                    "custom.key".to_owned(),
                ],
                ..Default::default()
            }),
            ..Default::default()
        }
        .to_otel_process_ctx();

        // Schema version attribute
        let schema_version = find_extra_attr(&ctx, "threadlocal.schema_version")
            .expect("threadlocal.schema_version should be present");
        assert_eq!(
            schema_version.value,
            Some(any_value::Value::StringValue("tlsdesc_v1_dev".to_owned()))
        );

        // Key map attribute: ordered array of key name strings
        let key_map = find_extra_attr(&ctx, "threadlocal.attribute_key_map")
            .expect("threadlocal.attribute_key_map should be present");
        let array = match &key_map.value {
            Some(any_value::Value::ArrayValue(a)) => a,
            other => panic!("expected ArrayValue, got {:?}", other),
        };
        let keys: Vec<&str> = array
            .values
            .iter()
            .map(|v| match &v.value {
                Some(any_value::Value::StringValue(s)) => s.as_str(),
                other => panic!("expected StringValue, got {:?}", other),
            })
            .collect();
        assert_eq!(
            keys,
            [
                "datadog.local_root_span_id",
                "span.id",
                "trace.id",
                "custom.key"
            ]
        );
    }

    #[cfg(feature = "otel-thread-ctx")]
    #[test]
    fn threadlocal_schema_version_override() {
        let ctx = TracerMetadata {
            threadlocal_metadata: Some(ThreadLocalMetadata {
                schema_version: Some("nodejs_v1_dev".to_owned()),
                ..Default::default()
            }),
            ..Default::default()
        }
        .to_otel_process_ctx();

        let schema_version = find_extra_attr(&ctx, "threadlocal.schema_version")
            .expect("threadlocal.schema_version should be present");
        assert_eq!(
            schema_version.value,
            Some(any_value::Value::StringValue("nodejs_v1_dev".to_owned()))
        );
    }

    #[cfg(feature = "otel-thread-ctx")]
    #[test]
    fn threadlocal_extra_attributes_are_emitted() {
        let ctx = TracerMetadata {
            threadlocal_metadata: Some(ThreadLocalMetadata {
                attribute_keys: vec!["k".to_owned()],
                extra_attributes: vec![
                    (
                        "threadlocal.wrapped_object_offset".to_owned(),
                        any_value::Value::IntValue(24),
                    ),
                    (
                        "threadlocal.tagged_size".to_owned(),
                        any_value::Value::IntValue(8),
                    ),
                    (
                        "threadlocal.runtime.name".to_owned(),
                        any_value::Value::StringValue("nodejs".to_owned()),
                    ),
                ],
                ..Default::default()
            }),
            ..Default::default()
        }
        .to_otel_process_ctx();

        assert_eq!(
            find_extra_attr(&ctx, "threadlocal.wrapped_object_offset")
                .and_then(|v| v.value.clone()),
            Some(any_value::Value::IntValue(24))
        );
        assert_eq!(
            find_extra_attr(&ctx, "threadlocal.tagged_size").and_then(|v| v.value.clone()),
            Some(any_value::Value::IntValue(8))
        );
        assert_eq!(
            find_extra_attr(&ctx, "threadlocal.runtime.name").and_then(|v| v.value.clone()),
            Some(any_value::Value::StringValue("nodejs".to_owned()))
        );
    }

    #[cfg(feature = "otel-thread-ctx")]
    #[test]
    fn default_threadlocal_metadata_preserves_legacy_metadata() {
        let mut metadata = TracerMetadata {
            service_name: Some("checkout".to_owned()),
            ..Default::default()
        };

        let legacy_before = rmp_serde::to_vec_named(&metadata).expect("metadata should serialize");

        metadata.threadlocal_metadata = Some(ThreadLocalMetadata::default());

        let ctx = metadata.to_otel_process_ctx();

        for key in [
            "threadlocal.schema_version",
            "threadlocal.attribute_key_map",
        ] {
            let count = ctx
                .extra_attributes
                .iter()
                .filter(|attribute| attribute.key == key)
                .count();

            assert_eq!(count, 1, "expected exactly one {key}");
        }

        let schema = find_extra_attr(&ctx, "threadlocal.schema_version")
            .expect("schema version should be present");

        assert_eq!(
            schema.value,
            Some(any_value::Value::StringValue("tlsdesc_v1_dev".to_owned()))
        );

        let key_map = find_extra_attr(&ctx, "threadlocal.attribute_key_map")
            .expect("attribute key map should be present");

        let array = match &key_map.value {
            Some(any_value::Value::ArrayValue(array)) => array,
            other => panic!("expected ArrayValue, got {other:?}"),
        };

        assert_eq!(array.values.len(), 1);
        assert_eq!(
            array.values[0].value,
            Some(any_value::Value::StringValue(
                "datadog.local_root_span_id".to_owned()
            ))
        );

        let legacy_after = rmp_serde::to_vec_named(&metadata).expect("metadata should serialize");

        assert_eq!(legacy_before, legacy_after);
    }
}