Skip to main content

datadog_agent_config/
env_reader.rs

1//! Builds the typed configuration base from environment variables.
2//!
3//! [`DATADOG_ENV_KEYS`] maps the Agent's declared variable names to nested configuration paths;
4//! paths are not inferred by splitting names. [`apply_datadog_env_vars`] decodes each key's first
5//! non-empty environment value using [`crate::env_decode`]. Callers choose precedence with `overwrite`.
6
7use std::collections::HashMap;
8
9use serde_json::{Map, Value};
10
11use crate::env_decode::{decode, EnvDecode};
12use crate::generated::env_keys::{DATADOG_ENV_KEYS, DATADOG_RENAMED_KEYS};
13
14/// One modeled configuration key and how to read it from the environment.
15#[derive(Clone, Copy, Debug)]
16pub struct EnvKey {
17    /// The environment variable names bound to this key, highest priority first. The first one
18    /// set to a non-empty value supplies the key's value, matching the Agent's per-key lookup; see
19    /// [`EnvSnapshot`] for how case is matched.
20    pub env_vars: &'static [&'static str],
21    /// The nested path the typed deserializer reads (for example, `["proxy", "http"]`).
22    pub path: &'static [&'static str],
23    /// How to decode the raw string into the schema-declared JSON shape.
24    pub decode: EnvDecode,
25}
26
27/// A former name of a Datadog schema setting, from the schema's `renamed_from`.
28#[derive(Clone, Copy, Debug)]
29pub struct RenamedKey {
30    /// The former nested path (for example, `["statsd_metric_blocklist"]`).
31    pub former: &'static [&'static str],
32    /// The nested path of the setting it was renamed to.
33    pub path: &'static [&'static str],
34    /// The environment variable derived from the former name, if the setting is read from the
35    /// environment. It is also in the setting's [`EnvKey::env_vars`].
36    pub env_var: Option<&'static str>,
37}
38
39/// Decodes process environment variables into modeled Datadog paths in `base`.
40///
41/// Same as [`apply_datadog_env_vars`], but reads the process environment.
42///
43/// # Errors
44///
45/// Returns a message naming the environment variable when its value is malformed for the key's
46/// declared shape.
47// This function is in use by action-check-runner, do not delete
48pub fn apply_datadog_env(base: &mut Value, overwrite: bool) -> Result<(), String> {
49    apply_env_snapshot(base, EnvSnapshot::capture(), overwrite).map(drop)
50}
51
52/// Decodes supplied environment variables into modeled Datadog paths in `base`, and returns the name
53/// of each variable that supplied a key of [`DATADOG_ENV_KEYS`], as written in `vars`.
54///
55/// Also applies `HTTP_PROXY`/`HTTPS_PROXY` as fallbacks for their `DD_` forms. When `overwrite` is
56/// true, environment values replace existing values; otherwise, only absent paths are filled. A
57/// variable that supplied a key is returned either way.
58///
59/// # Errors
60///
61/// Returns a message naming the environment variable when its value is malformed for the key's
62/// declared shape. At startup this aborts the boot rather than silently dropping the value.
63pub fn apply_datadog_env_vars(
64    base: &mut Value, vars: impl IntoIterator<Item = (String, String)>, overwrite: bool,
65) -> Result<Vec<String>, String> {
66    apply_env_snapshot(base, EnvSnapshot::from_vars(vars), overwrite)
67}
68
69fn apply_env_snapshot(base: &mut Value, env: EnvSnapshot, overwrite: bool) -> Result<Vec<String>, String> {
70    let Some(root) = base.as_object_mut() else {
71        return Ok(Vec::new());
72    };
73    let mut read = Vec::new();
74    for key in DATADOG_ENV_KEYS {
75        read.extend(apply_one(root, &env, key.env_vars, key.path, key.decode, overwrite)?);
76    }
77    apply_proxy_env(root, &env, overwrite);
78    Ok(read)
79}
80
81/// The nested path of every modeled Datadog key.
82///
83/// The merge that layers the Agent config stream over the base uses these to tell a schema section
84/// (an intermediate object it descends into) from a leaf (a value it replaces wholesale), so a
85/// map-typed leaf is never key-unioned across sources.
86pub fn datadog_leaf_paths() -> impl Iterator<Item = &'static [&'static str]> {
87    DATADOG_ENV_KEYS.iter().map(|key| key.path)
88}
89
90/// Every former name of a Datadog schema setting, modeled or not.
91///
92/// Entries for one setting are adjacent and highest priority first: the name deprecated earliest
93/// comes first, as in the Agent. No former path is a schema path, or contains or is contained by
94/// one.
95pub fn datadog_renamed_keys() -> &'static [RenamedKey] {
96    DATADOG_RENAMED_KEYS
97}
98
99/// Decodes one key from the process environment into `base` at the supplied path.
100///
101/// Reads the first non-empty variable named in `env_vars`. When `overwrite` is false, existing values
102/// win.
103///
104/// # Errors
105///
106/// Returns a message when the environment value is malformed for `decode`.
107pub fn apply_env_at_path(
108    base: &mut Value, env_vars: &[&str], path: &[&str], decode: EnvDecode, overwrite: bool,
109) -> Result<(), String> {
110    let Some(root) = base.as_object_mut() else {
111        return Ok(());
112    };
113    let env = EnvSnapshot::capture();
114    apply_one(root, &env, env_vars, path, decode, overwrite).map(drop)
115}
116
117/// Decodes one key from supplied environment variables into `base` at the supplied path.
118///
119/// Identical to [`apply_env_at_path`] except for where the variables come from. Callers that read
120/// the process environment once and reuse it pass it here, and tests pass their own variables so
121/// that they do not depend on the ambient process environment.
122///
123/// # Errors
124///
125/// Returns a message when the environment value is malformed for `decode`.
126pub fn apply_env_at_path_vars(
127    base: &mut Value, vars: impl IntoIterator<Item = (String, String)>, env_vars: &[&str], path: &[&str],
128    decode: EnvDecode, overwrite: bool,
129) -> Result<(), String> {
130    let Some(root) = base.as_object_mut() else {
131        return Ok(());
132    };
133    let env = EnvSnapshot::from_vars(vars);
134    apply_one(root, &env, env_vars, path, decode, overwrite).map(drop)
135}
136
137/// The canonical proxy variables that carry no `DD_` prefix.
138///
139/// `HTTP_PROXY` and `HTTPS_PROXY` are honored by the Datadog Agent but are not declared by the
140/// vendored schema (they are wired only by the Agent's bespoke proxy handling), so they are not in
141/// [`DATADOG_ENV_KEYS`] and are injected here by hand. They are a fallback below the schema's
142/// `DD_PROXY_HTTP`/`DD_PROXY_HTTPS`: when the `DD_`-prefixed form is set, the canonical form is
143/// ignored, matching the Agent's ordering. Canonical `NO_PROXY` is intentionally unsupported.
144///
145/// The canonical names are matched case-insensitively through [`EnvSnapshot`], so the common
146/// lowercase Unix convention (`http_proxy`/`https_proxy`) is honored alongside the uppercase form.
147fn apply_proxy_env(root: &mut Map<String, Value>, env: &EnvSnapshot, overwrite: bool) {
148    const PROXY: &[(&str, &str, &[&str])] = &[
149        ("DD_PROXY_HTTP", "HTTP_PROXY", &["proxy", "http"]),
150        ("DD_PROXY_HTTPS", "HTTPS_PROXY", &["proxy", "https"]),
151    ];
152    for (dd_var, canonical_var, path) in PROXY {
153        // The DD_-prefixed form is handled by the generated table and wins; only fill from the
154        // canonical form when the DD_ form is unset.
155        if env.contains(dd_var) {
156            continue;
157        }
158        if let Some((_, raw)) = env.lookup(&[canonical_var]) {
159            write_at_path(root, path, Value::String(raw.to_owned()), overwrite);
160        }
161    }
162}
163
164/// Reads, decodes, and writes one key, and returns the name of the variable read.
165fn apply_one(
166    root: &mut Map<String, Value>, env: &EnvSnapshot, env_vars: &[&str], path: &[&str], how: EnvDecode, overwrite: bool,
167) -> Result<Option<String>, String> {
168    let Some((name, raw)) = env.lookup(env_vars) else {
169        return Ok(None);
170    };
171    let value = decode(raw, how).map_err(|msg| format!("environment variable `{name}` ({}): {msg}", path.join(".")))?;
172    write_at_path(root, path, value, overwrite);
173    Ok(Some(name.to_owned()))
174}
175
176/// A snapshot of the non-empty process environment, with exact-case lookup and a case-insensitive
177/// fallback.
178///
179/// The Agent looks each bound name up with a case-sensitive `os.LookupEnv`, so an exact-case match
180/// wins. ADP also accepts other case spellings (`dd_dogstatsd_port` for `DD_DOGSTATSD_PORT`), which
181/// apply only when no bound name is set in its exact case.
182struct EnvSnapshot {
183    /// Non-empty values keyed by exact variable name.
184    exact: HashMap<String, String>,
185    /// The first-seen non-empty variable (name, value) for each lowercase name.
186    folded: HashMap<String, (String, String)>,
187}
188
189impl EnvSnapshot {
190    /// Captures the process environment, dropping empty values.
191    fn capture() -> Self {
192        Self::from_vars(std::env::vars())
193    }
194
195    /// Builds a snapshot from environment variable pairs.
196    ///
197    /// An empty string counts as unset, matching the Agent (`os.LookupEnv` plus an emptiness
198    /// check).
199    fn from_vars(vars: impl IntoIterator<Item = (String, String)>) -> Self {
200        let mut exact = HashMap::new();
201        let mut folded = HashMap::new();
202        for (name, value) in vars {
203            if value.is_empty() {
204                continue;
205            }
206            folded
207                .entry(name.to_lowercase())
208                .or_insert_with(|| (name.clone(), value.clone()));
209            exact.entry(name).or_insert(value);
210        }
211        Self { exact, folded }
212    }
213
214    /// Returns the actual name and value of the variable that supplies `names` (highest priority
215    /// first).
216    ///
217    /// Tries every name exactly, in order, then every name case-insensitively, in order. Among case
218    /// variants of one name, the first variable captured wins.
219    fn lookup(&self, names: &[&str]) -> Option<(&str, &str)> {
220        names
221            .iter()
222            .find_map(|name| self.exact.get_key_value(*name))
223            .map(|(name, value)| (name.as_str(), value.as_str()))
224            .or_else(|| {
225                names
226                    .iter()
227                    .find_map(|name| self.folded.get(&name.to_lowercase()))
228                    .map(|(name, value)| (name.as_str(), value.as_str()))
229            })
230    }
231
232    /// Whether any case variant of `name` is set to a non-empty value.
233    fn contains(&self, name: &str) -> bool {
234        self.folded.contains_key(&name.to_lowercase())
235    }
236}
237
238/// Writes `value` at `path`, creating intermediate objects. When `overwrite` is false, an existing
239/// value at the full path is left in place (the file wins).
240fn write_at_path(root: &mut Map<String, Value>, path: &[&str], value: Value, overwrite: bool) {
241    let Some((leaf, sections)) = path.split_last() else {
242        return;
243    };
244    if !overwrite && path_present(root, path) {
245        return;
246    }
247    let mut current = root;
248    for segment in sections {
249        let node = current
250            .entry((*segment).to_string())
251            .or_insert_with(|| Value::Object(Map::new()));
252        if !node.is_object() {
253            *node = Value::Object(Map::new());
254        }
255        current = node.as_object_mut().expect("node was just ensured to be an object");
256    }
257    current.insert((*leaf).to_string(), value);
258}
259
260/// Returns whether a leaf already exists at `path`, walking object nodes from `root`.
261fn path_present(root: &Map<String, Value>, path: &[&str]) -> bool {
262    let Some((first, rest)) = path.split_first() else {
263        return false;
264    };
265    let mut current = match root.get(*first) {
266        Some(v) => v,
267        None => return false,
268    };
269    for segment in rest {
270        match current.get(*segment) {
271            Some(v) => current = v,
272            None => return false,
273        }
274    }
275    true
276}
277
278#[cfg(test)]
279mod tests {
280    use serde_json::json;
281
282    use super::*;
283
284    fn vars(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
285        pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
286    }
287
288    fn at<'a>(base: &'a Value, path: &[&str]) -> Option<&'a Value> {
289        let mut cur = base;
290        for seg in path {
291            cur = cur.get(seg)?;
292        }
293        Some(cur)
294    }
295
296    #[test]
297    fn decodes_scalars_and_lists_to_shape() {
298        let env = vars(&[
299            ("DD_DOGSTATSD_PORT", "9125"),
300            ("DD_API_KEY", "00000"),
301            ("DD_DOGSTATSD_TAGS", "env:prod team:core"),
302        ]);
303
304        let mut base = json!({});
305        apply_datadog_env_vars(&mut base, env, true).unwrap();
306
307        // Numeric-looking API keys must remain strings.
308        assert_eq!(at(&base, &["dogstatsd_port"]), Some(&json!(9125)));
309        assert_eq!(at(&base, &["api_key"]), Some(&json!("00000")));
310        assert_eq!(at(&base, &["dogstatsd_tags"]), Some(&json!(["env:prod", "team:core"])));
311    }
312
313    #[test]
314    fn writes_at_nested_path() {
315        let mut base = json!({});
316        apply_datadog_env_vars(&mut base, vars(&[("DD_APM_ERROR_TPS", "12.5")]), true).unwrap();
317
318        assert_eq!(at(&base, &["apm_config", "errors_per_second"]), Some(&json!(12.5)));
319    }
320
321    #[test]
322    fn precedence_overwrite_versus_fill() {
323        let env = vars(&[("DD_DOGSTATSD_PORT", "9125")]);
324
325        let mut env_wins = json!({ "dogstatsd_port": 8125 });
326        apply_datadog_env_vars(&mut env_wins, env.clone(), true).unwrap();
327        assert_eq!(at(&env_wins, &["dogstatsd_port"]), Some(&json!(9125)));
328
329        let mut file_wins = json!({ "dogstatsd_port": 8125 });
330        apply_datadog_env_vars(&mut file_wins, env, false).unwrap();
331        assert_eq!(at(&file_wins, &["dogstatsd_port"]), Some(&json!(8125)));
332    }
333
334    #[test]
335    fn env_var_names_are_matched_case_insensitively() {
336        let env = EnvSnapshot::from_vars([
337            ("dd_dogstatsd_port".to_string(), "9125".to_string()),
338            ("Dd_Api_Key".to_string(), "00000".to_string()),
339        ]);
340
341        assert_eq!(env.lookup(&["DD_DOGSTATSD_PORT"]), Some(("dd_dogstatsd_port", "9125")));
342        assert_eq!(env.lookup(&["DD_API_KEY"]), Some(("Dd_Api_Key", "00000")));
343    }
344
345    fn apply_vars(pairs: &[(&str, &str)]) -> Result<Value, String> {
346        let mut base = json!({});
347        apply_datadog_env_vars(&mut base, vars(pairs), true)?;
348        Ok(base)
349    }
350
351    #[test]
352    fn the_first_alias_in_declared_order_wins() {
353        // `DD_APM_MAX_EPS` is declared before `DD_MAX_EPS`, whatever order the environment lists them in.
354        for pairs in [
355            [("DD_APM_MAX_EPS", "100"), ("DD_MAX_EPS", "200")],
356            [("DD_MAX_EPS", "200"), ("DD_APM_MAX_EPS", "100")],
357        ] {
358            let base = apply_vars(&pairs).unwrap();
359            assert_eq!(at(&base, &["apm_config", "max_events_per_second"]), Some(&json!(100.0)));
360        }
361
362        let base = apply_vars(&[("DD_MAX_EPS", "200")]).unwrap();
363        assert_eq!(at(&base, &["apm_config", "max_events_per_second"]), Some(&json!(200.0)));
364    }
365
366    #[test]
367    fn an_empty_first_alias_falls_through_to_the_next() {
368        let base = apply_vars(&[("DD_APM_MAX_EPS", ""), ("DD_MAX_EPS", "200")]).unwrap();
369        assert_eq!(at(&base, &["apm_config", "max_events_per_second"]), Some(&json!(200.0)));
370    }
371
372    #[test]
373    fn an_exact_case_name_beats_a_different_case_duplicate() {
374        // The Agent's case-sensitive lookup sees only the exact spelling.
375        for pairs in [
376            [("dd_dogstatsd_port", "2"), ("DD_DOGSTATSD_PORT", "1")],
377            [("DD_DOGSTATSD_PORT", "1"), ("dd_dogstatsd_port", "2")],
378        ] {
379            let base = apply_vars(&pairs).unwrap();
380            assert_eq!(at(&base, &["dogstatsd_port"]), Some(&json!(1)));
381        }
382    }
383
384    #[test]
385    fn an_exact_case_later_alias_beats_a_different_case_earlier_alias() {
386        let base = apply_vars(&[("dd_apm_max_eps", "100"), ("DD_MAX_EPS", "200")]).unwrap();
387        assert_eq!(at(&base, &["apm_config", "max_events_per_second"]), Some(&json!(200.0)));
388    }
389
390    #[test]
391    fn the_variables_read_are_returned_as_written() {
392        let read = |pairs: &[(&str, &str)]| apply_datadog_env_vars(&mut json!({}), vars(pairs), false).unwrap();
393
394        assert_eq!(read(&[("dd_apm_max_eps", "100")]), ["dd_apm_max_eps"]);
395        // A variable set in another case is not read when another bound name is set in its exact case.
396        assert_eq!(
397            read(&[("dd_apm_max_eps", "100"), ("DD_MAX_EPS", "200")]),
398            ["DD_MAX_EPS"]
399        );
400        assert_eq!(
401            read(&[("DD_APM_MAX_EPS", ""), ("DD_UNBOUND", "1")]),
402            Vec::<String>::new()
403        );
404    }
405
406    #[test]
407    fn a_former_name_is_read_before_the_current_one() {
408        let filterlist = &["metric_filterlist"];
409        let match_prefix = &["metric_filterlist_match_prefix"];
410        for pairs in [
411            [("DD_STATSD_METRIC_BLOCKLIST", "old"), ("DD_METRIC_FILTERLIST", "new")],
412            [("DD_METRIC_FILTERLIST", "new"), ("DD_STATSD_METRIC_BLOCKLIST", "old")],
413        ] {
414            assert_eq!(at(&apply_vars(&pairs).unwrap(), filterlist), Some(&json!(["old"])));
415        }
416        let base = apply_vars(&[
417            ("DD_STATSD_METRIC_BLOCKLIST_MATCH_PREFIX", "true"),
418            ("DD_METRIC_FILTERLIST_MATCH_PREFIX", "false"),
419        ])
420        .unwrap();
421        assert_eq!(at(&base, match_prefix), Some(&json!(true)));
422
423        // The former name is decoded as the current key: a space-separated list.
424        let base = apply_vars(&[("DD_STATSD_METRIC_BLOCKLIST", "a b")]).unwrap();
425        assert_eq!(at(&base, filterlist), Some(&json!(["a", "b"])));
426        assert_eq!(at(&base, &["statsd_metric_blocklist"]), None);
427
428        let base = apply_vars(&[("DD_METRIC_FILTERLIST", "new")]).unwrap();
429        assert_eq!(at(&base, filterlist), Some(&json!(["new"])));
430    }
431
432    #[test]
433    fn an_empty_former_name_falls_through_to_the_current_one() {
434        let base = apply_vars(&[("DD_STATSD_METRIC_BLOCKLIST", ""), ("DD_METRIC_FILTERLIST", "new")]).unwrap();
435        assert_eq!(at(&base, &["metric_filterlist"]), Some(&json!(["new"])));
436    }
437
438    #[test]
439    fn the_decode_error_names_the_variable_that_was_read() {
440        let error = apply_vars(&[("DD_MAX_EPS", "fast")]).unwrap_err();
441        assert!(error.starts_with("environment variable `DD_MAX_EPS` (apm_config.max_events_per_second): "));
442
443        // A case-insensitive match is reported under the name it was set with.
444        let error = apply_vars(&[("dd_max_eps", "fast")]).unwrap_err();
445        assert!(error.starts_with("environment variable `dd_max_eps` (apm_config.max_events_per_second): "));
446    }
447
448    #[test]
449    fn agent_integer_and_list_spellings_decode_to_shape() {
450        let base = apply_vars(&[
451            ("DD_DOGSTATSD_PORT", "0x10"),
452            ("DD_APM_OBFUSCATION_ELASTICSEARCH_KEEP_VALUES", r#"["cr-a","cr-b"]"#),
453        ])
454        .unwrap();
455        assert_eq!(at(&base, &["dogstatsd_port"]), Some(&json!(16)));
456        assert_eq!(
457            at(&base, &["apm_config", "obfuscation", "elasticsearch", "keep_values"]),
458            Some(&json!(["cr-a", "cr-b"]))
459        );
460    }
461
462    #[test]
463    fn ignore_resources_reads_a_csv_record() {
464        // Both variables reach the key, and a quoted pattern may contain a comma.
465        for name in ["DD_APM_IGNORE_RESOURCES", "DD_IGNORE_RESOURCE"] {
466            let base = apply_vars(&[(name, r#"GET /ping, "(GET|POST) /a,b""#)]).unwrap();
467            assert_eq!(
468                at(&base, &["apm_config", "ignore_resources"]),
469                Some(&json!(["GET /ping", "(GET|POST) /a,b"])),
470                "{name}"
471            );
472        }
473    }
474
475    #[test]
476    fn canonical_proxy_is_a_fallback_below_dd_form() {
477        let canonical = ("HTTP_PROXY", "http://canonical:3128");
478        let mut base = json!({});
479        apply_datadog_env_vars(&mut base, vars(&[canonical]), true).unwrap();
480        assert_eq!(at(&base, &["proxy", "http"]), Some(&json!("http://canonical:3128")));
481
482        let both = vars(&[canonical, ("DD_PROXY_HTTP", "http://prefixed:3128")]);
483        let mut base = json!({});
484        apply_datadog_env_vars(&mut base, both, true).unwrap();
485        assert_eq!(at(&base, &["proxy", "http"]), Some(&json!("http://prefixed:3128")));
486    }
487
488    #[test]
489    fn lowercase_proxy_env_is_honored() {
490        let env = EnvSnapshot::from_vars([("http_proxy".to_string(), "http://lower:3128".to_string())]);
491        let mut base = json!({});
492        apply_proxy_env(base.as_object_mut().unwrap(), &env, true);
493
494        assert_eq!(at(&base, &["proxy", "http"]), Some(&json!("http://lower:3128")));
495    }
496
497    #[test]
498    fn apply_datadog_env_signature_is_stable_at_crate_root() {
499        // Pins public API used outside Saluki.
500        let _: fn(&mut Value, bool) -> Result<(), String> = crate::apply_datadog_env;
501    }
502
503    #[test]
504    fn malformed_value_propagates() {
505        let mut base = json!({});
506        let result = apply_datadog_env_vars(&mut base, vars(&[("DD_DOGSTATSD_PORT", "not-a-number")]), true);
507        assert!(result.is_err());
508    }
509}