Skip to main content

datadog_agent_config/
lib.rs

1/// Deserializers that coerce a scalar leaf the way the Agent's own type cast does.
2mod cast_de;
3
4pub mod classifier;
5
6mod duration_de;
7
8/// Decoders that turn a raw environment-variable string into the JSON shape a schema leaf declares.
9pub mod env_decode;
10mod list_de;
11
12/// Builds the typed configuration base by reading environment variables directly and decoding them
13/// into the nested configuration shape.
14pub mod env_reader;
15
16/// Build-time generated code, produced from `core_schema.yaml` plus `schema_overlay.yaml`.
17mod generated;
18
19/// Runtime selection of a schema `platform_default` value, called by generated default functions.
20mod platform_default;
21
22/// A shared, immutable view of the vendored schema's defaults.
23mod schema_defaults;
24
25/// Parses a byte-size setting the way the Agent's `GetSizeInBytes` does.
26mod size_in_bytes;
27
28/// The translation error type recorded by the translator and surfaced by the witness driver.
29mod translate_error;
30
31pub use cast_de::cast_to_f64;
32pub use cast_de::cast_to_string;
33pub use env_decode::EnvDecode;
34pub use env_reader::{
35    apply_datadog_env, apply_datadog_env_vars, apply_env_at_path, datadog_leaf_paths, datadog_renamed_keys, EnvKey,
36    RenamedKey,
37};
38pub use generated::{drive, DatadogConfigWitness, DatadogConfiguration, Leaf, LeafValue, LEAVES};
39pub use platform_default::is_containerized;
40pub use size_in_bytes::parse_size_in_bytes;
41pub use translate_error::{TranslateError, TranslateErrors};
42
43#[cfg(test)]
44mod string_list_shape_tests {
45    use super::DatadogConfiguration;
46
47    // A string-list leaf must accept both shapes the config sources produce: a real sequence (from a
48    // file or the remote Agent stream) and a single space-separated string (from an environment
49    // variable, e.g. `DD_DOGSTATSD_TAGS="env:prod team:core"`). The generated deserializer wires the
50    // shape-tolerant reader onto every `Vec<String>` leaf; these assertions guard that wiring so a
51    // regenerate that drops it fails loudly instead of crashing config load on the string form.
52
53    #[test]
54    fn string_list_leaf_accepts_a_space_separated_string() {
55        let config: DatadogConfiguration =
56            serde_json::from_value(serde_json::json!({ "dogstatsd_tags": "env:prod team:core" }))
57                .expect("space-separated string deserializes into the string-list leaf");
58        assert_eq!(config.dogstatsd_tags, vec!["env:prod", "team:core"]);
59    }
60
61    #[test]
62    fn string_list_leaf_accepts_a_json_encoded_list() {
63        let config: DatadogConfiguration = serde_json::from_value(serde_json::json!({
64            "apm_config": { "obfuscation": { "elasticsearch": { "keep_values": r#"["cr-a","cr-b"]"# } } }
65        }))
66        .expect("JSON-encoded list deserializes into the string-list leaf");
67        assert_eq!(
68            config.apm_config.obfuscation.elasticsearch.keep_values,
69            vec!["cr-a", "cr-b"]
70        );
71    }
72
73    #[test]
74    fn string_list_leaf_accepts_a_sequence() {
75        let config: DatadogConfiguration =
76            serde_json::from_value(serde_json::json!({ "dogstatsd_tags": ["env:prod", "team:core"] }))
77                .expect("sequence deserializes into the string-list leaf");
78        assert_eq!(config.dogstatsd_tags, vec!["env:prod", "team:core"]);
79    }
80}
81
82#[cfg(test)]
83mod string_map_list_shape_tests {
84    use super::DatadogConfiguration;
85
86    #[test]
87    fn additional_endpoints_accept_scalar_values() {
88        let config: DatadogConfiguration = serde_json::from_value(serde_json::json!({
89            "additional_endpoints": {
90                "https://agent.datadoghq.com.": "ENC[vault://api-key]"
91            }
92        }))
93        .expect("scalar additional endpoint API key deserializes");
94
95        assert_eq!(
96            config.additional_endpoints["https://agent.datadoghq.com."],
97            ["ENC[vault://api-key]"]
98        );
99    }
100
101    #[test]
102    fn additional_endpoints_accept_sequence_values() {
103        let config: DatadogConfiguration = serde_json::from_value(serde_json::json!({
104            "additional_endpoints": {
105                "https://agent.datadoghq.com.": ["first", "second"]
106            }
107        }))
108        .expect("additional endpoint API key sequence deserializes");
109
110        assert_eq!(
111            config.additional_endpoints["https://agent.datadoghq.com."],
112            ["first", "second"]
113        );
114    }
115}
116
117#[cfg(test)]
118mod scalar_shape_tests {
119    use serde_json::{json, Value};
120
121    use super::env_decode::EnvDecode;
122    use super::generated::env_keys::DATADOG_ENV_KEYS;
123    use super::DatadogConfiguration;
124
125    // The Agent reads a setting by casting whatever is stored to the accessor's type, so a leaf must
126    // accept more than the JSON type its schema declares. These assertions cover the wiring generated
127    // for that (`crate::cast_de`), so a regenerate that drops it fails here instead of rejecting a
128    // configuration the Agent accepts — which, at the strict startup gate, means ADP fails to boot.
129
130    #[test]
131    fn boolean_leaf_accepts_a_boolean_string() {
132        let config: DatadogConfiguration = serde_json::from_value(json!({ "dogstatsd_non_local_traffic": "true" }))
133            .expect("boolean string deserializes");
134        assert!(config.dogstatsd_non_local_traffic);
135    }
136
137    #[test]
138    fn number_map_leaf_accepts_numeric_string_values() {
139        let config: DatadogConfiguration = serde_json::from_value(json!({
140            "apm_config": { "analyzed_rate_by_service": { "service": "0.8" } }
141        }))
142        .expect("numeric string map deserializes");
143        assert_eq!(config.apm_config.analyzed_rate_by_service["service"], 0.8);
144    }
145
146    #[test]
147    fn integer_leaf_accepts_a_numeric_string() {
148        let config: DatadogConfiguration =
149            serde_json::from_value(json!({ "dogstatsd_port": "8125" })).expect("numeric string deserializes");
150        assert_eq!(config.dogstatsd_port, 8125);
151    }
152
153    #[test]
154    fn integer_leaf_reads_a_quoted_zero_padded_number_as_octal() {
155        let config: DatadogConfiguration =
156            serde_json::from_value(json!({ "dogstatsd_buffer_size": "010" })).expect("numeric string deserializes");
157        assert_eq!(config.dogstatsd_buffer_size, 8);
158    }
159
160    #[test]
161    fn string_leaf_accepts_a_boolean() {
162        // The Agent reads this leaf with `GetString`, so a YAML boolean reaches it as `"true"`.
163        let config: DatadogConfiguration =
164            serde_json::from_value(json!({ "use_v3_api": { "series": { "enabled": true } } }))
165                .expect("boolean V3 series mode deserializes");
166        assert_eq!(config.use_v3_api.series.enabled, "true");
167    }
168
169    #[test]
170    fn string_leaf_accepts_a_numeric_byte_count() {
171        // A byte size is schema-typed as a string but documented as a bare byte count as well.
172        let config: DatadogConfiguration = serde_json::from_value(json!({ "dogstatsd_log_file_max_size": 10485760 }))
173            .expect("byte count deserializes");
174        assert_eq!(config.dogstatsd_log_file_max_size, "10485760");
175    }
176
177    #[test]
178    fn every_scalar_leaf_accepts_the_agent_castable_form_of_its_type() {
179        // The environment table is the runtime inventory of leaves with their declared types, so this
180        // reaches every scalar leaf rather than the handful spelled out above.
181        let defaults = serde_json::to_value(DatadogConfiguration::default()).expect("defaults serialize");
182
183        for key in DATADOG_ENV_KEYS {
184            let pointer = format!("/{}", key.path.join("/"));
185            let current = defaults.pointer(&pointer);
186
187            // A boolean, integer, or float leaf must accept its string spelling (how it arrives from an
188            // environment variable, and how an operator may write it in YAML); a string leaf must accept
189            // a boolean. An integer leaf must also accept the base-prefixed spelling the Agent's integer
190            // cast reads. Each written value differs from the leaf's default, so a coercion that silently
191            // failed to land cannot be mistaken for one that worked.
192            let cases = match key.decode {
193                EnvDecode::Bool => {
194                    let flipped = !current.and_then(Value::as_bool).unwrap_or(false);
195                    vec![(json!(flipped.to_string()), json!(flipped))]
196                }
197                EnvDecode::Integer => {
198                    let bumped = current.and_then(Value::as_i64).unwrap_or(0) + 1;
199                    let sign = if bumped < 0 { "-" } else { "" };
200                    let hex = format!("{sign}{:#x}", bumped.unsigned_abs());
201                    vec![(json!(bumped.to_string()), json!(bumped)), (json!(hex), json!(bumped))]
202                }
203                EnvDecode::Float => {
204                    let bumped = current.and_then(Value::as_f64).unwrap_or(0.0) + 1.5;
205                    vec![(json!(bumped.to_string()), json!(bumped))]
206                }
207                EnvDecode::RawString => {
208                    let flag = current.and_then(Value::as_str) != Some("true");
209                    vec![(json!(flag), json!(flag.to_string()))]
210                }
211                _ => continue,
212            };
213
214            for (written, expected) in cases {
215                let mut tree = written.clone();
216                for segment in key.path.iter().rev() {
217                    tree = json!({ *segment: tree });
218                }
219
220                let leaf = key.path.join(".");
221                let config: DatadogConfiguration =
222                    serde_json::from_value(tree).unwrap_or_else(|e| panic!("leaf `{leaf}` rejected {written}: {e}"));
223                let coerced = serde_json::to_value(config).expect("the configuration serializes");
224                assert_eq!(
225                    coerced.pointer(&pointer),
226                    Some(&expected),
227                    "leaf `{leaf}` did not coerce {written}"
228                );
229            }
230        }
231    }
232
233    #[test]
234    fn a_malformed_scalar_is_still_rejected() {
235        // Permissive is not unconditional: a value the Agent's cast cannot convert must fail here
236        // rather than silently reading as the type's zero value, which is what the Agent does.
237        for malformed in [
238            json!({ "dogstatsd_non_local_traffic": "yes" }),
239            json!({ "dogstatsd_port": "8125ms" }),
240            json!({ "dogstatsd_log_file_max_size": ["10MB"] }),
241        ] {
242            let result: Result<DatadogConfiguration, _> = serde_json::from_value(malformed.clone());
243            assert!(result.is_err(), "{malformed} should be rejected");
244        }
245    }
246
247    #[test]
248    fn a_null_scalar_reads_as_the_type_zero_value() {
249        let config: DatadogConfiguration =
250            serde_json::from_value(json!({ "api_key": Value::Null })).expect("an explicitly null leaf deserializes");
251        assert_eq!(config.api_key, "");
252    }
253}
254
255#[cfg(test)]
256mod null_collection_tests {
257    use serde_json::{json, Value};
258
259    use super::env_decode::EnvDecode;
260    use super::generated::env_keys::DATADOG_ENV_KEYS;
261    use super::DatadogConfiguration;
262
263    // The Agent's configuration stream carries `null` for an empty or cleared list or map, and the
264    // Agent's accessors read it as empty. A key that is absent is different: it keeps the schema default.
265
266    #[test]
267    fn every_collection_leaf_accepts_null() {
268        // Scalar leaves are covered by `scalar_shape_tests`; durations are not collections.
269        let collections = DATADOG_ENV_KEYS.iter().filter(|key| {
270            !matches!(
271                key.decode,
272                EnvDecode::Bool
273                    | EnvDecode::Integer
274                    | EnvDecode::Float
275                    | EnvDecode::RawString
276                    | EnvDecode::DurationString
277            )
278        });
279
280        for key in collections {
281            let mut tree = Value::Null;
282            for segment in key.path.iter().rev() {
283                tree = json!({ *segment: tree });
284            }
285
286            let leaf = key.path.join(".");
287            serde_json::from_value::<DatadogConfiguration>(tree)
288                .unwrap_or_else(|e| panic!("leaf `{leaf}` rejected null: {e}"));
289        }
290    }
291
292    #[test]
293    fn a_null_string_list_is_empty_while_an_absent_one_keeps_its_default() {
294        let absent: DatadogConfiguration = serde_json::from_value(json!({})).expect("empty configuration deserializes");
295        assert!(
296            !absent.histogram_aggregates.is_empty(),
297            "the schema default is not empty"
298        );
299
300        let null: DatadogConfiguration =
301            serde_json::from_value(json!({ "histogram_aggregates": null, "proxy": { "no_proxy": null } }))
302                .expect("null string lists deserialize");
303        assert!(null.histogram_aggregates.is_empty());
304        assert!(null.proxy.no_proxy.is_empty());
305    }
306
307    #[test]
308    fn null_maps_and_object_arrays_are_empty() {
309        let config: DatadogConfiguration = serde_json::from_value(json!({
310            "additional_endpoints": null,
311            "dogstatsd_mapper_profiles": null,
312            "apm_config": { "replace_tags": null },
313            "use_v3_api": { "series": { "endpoints": null } }
314        }))
315        .expect("null collections deserialize");
316
317        assert!(config.additional_endpoints.is_empty());
318        assert!(config.dogstatsd_mapper_profiles.is_empty());
319        assert!(config.apm_config.replace_tags.is_empty());
320        assert!(config.use_v3_api.series.endpoints.is_empty());
321    }
322
323    #[test]
324    fn a_null_replace_tags_rule_is_an_empty_map() {
325        let config: DatadogConfiguration =
326            serde_json::from_value(json!({ "apm_config": { "replace_tags": [null, { "name": "*" }] } }))
327                .expect("a null rule deserializes");
328
329        assert_eq!(config.apm_config.replace_tags.len(), 2);
330        assert!(config.apm_config.replace_tags[0].is_empty());
331        assert_eq!(config.apm_config.replace_tags[1]["name"], "*");
332    }
333}
334
335#[cfg(test)]
336mod leaves_tests {
337    use serde_json::json;
338
339    use super::generated::env_keys::DATADOG_ENV_KEYS;
340    use super::{DatadogConfiguration, LeafValue, LEAVES};
341
342    // `LEAVES` and `DATADOG_ENV_KEYS` are independently generated (by `witness_gen.rs` and
343    // `env_reader_gen.rs` respectively) from the same overlay key set, so comparing them catches a
344    // divergence between the two generators rather than just a generator agreeing with itself.
345    #[test]
346    fn leaves_has_one_entry_per_supported_key() {
347        assert_eq!(LEAVES.len(), DATADOG_ENV_KEYS.len());
348        for env_key in DATADOG_ENV_KEYS {
349            let dotted = env_key.path.join(".");
350            assert!(
351                LEAVES.iter().any(|leaf| leaf.key == dotted),
352                "no LEAVES entry for supported key `{dotted}`"
353            );
354        }
355    }
356
357    #[test]
358    fn leaves_are_sorted_and_unique_by_key() {
359        for pair in LEAVES.windows(2) {
360            assert!(
361                pair[0].key < pair[1].key,
362                "LEAVES is not sorted (or has a duplicate) between `{}` and `{}`",
363                pair[0].key,
364                pair[1].key
365            );
366        }
367    }
368
369    #[test]
370    fn leaves_read_typed_values_of_several_kinds() {
371        let config: DatadogConfiguration = serde_json::from_value(json!({
372            "dogstatsd_non_local_traffic": true,
373            "dogstatsd_port": 9999,
374            "dogstatsd_tags": ["env:prod", "team:core"],
375            "additional_endpoints": { "https://x.": ["k1", "k2"] },
376            "apm_config": { "obfuscation": { "credit_cards": { "enabled": true } } },
377        }))
378        .expect("small configuration deserializes");
379
380        let leaf = |key: &str| {
381            LEAVES
382                .iter()
383                .find(|l| l.key == key)
384                .unwrap_or_else(|| panic!("no leaf `{key}`"))
385        };
386
387        assert!(matches!(
388            (leaf("dogstatsd_non_local_traffic").get)(&config),
389            LeafValue::Bool(true)
390        ));
391        assert!(matches!((leaf("dogstatsd_port").get)(&config), LeafValue::I64(9999)));
392
393        match (leaf("dogstatsd_tags").get)(&config) {
394            LeafValue::StringList(tags) => assert_eq!(tags, ["env:prod", "team:core"]),
395            other => panic!("unexpected leaf value: {other:?}"),
396        }
397
398        match (leaf("additional_endpoints").get)(&config) {
399            LeafValue::StringListMap(map) => {
400                assert_eq!(map["https://x."], vec!["k1".to_string(), "k2".to_string()]);
401            }
402            other => panic!("unexpected leaf value: {other:?}"),
403        }
404
405        assert!(matches!(
406            (leaf("apm_config.obfuscation.credit_cards.enabled").get)(&config),
407            LeafValue::Bool(true)
408        ));
409
410        // A key the JSON above never set reads back as the leaf's serde default.
411        match (leaf("syslog_rfc").get)(&config) {
412            LeafValue::Bool(value) => assert_eq!(value, DatadogConfiguration::default().syslog_rfc),
413            other => panic!("unexpected leaf value: {other:?}"),
414        }
415    }
416}