Skip to main content

datadog_agent_config/classifier/
classifier.rs

1use std::collections::HashMap;
2
3use serde_json::Value;
4
5use super::{ClassifierEntry, DefaultValue, PipelineAffinity, SupportLevel, CLASSIFIER_ENTRIES};
6
7/// A key's support level, default-value comparison, and affected pipelines.
8pub struct Classification {
9    /// The level at which this config key is supported by Saluki.
10    pub support_level: SupportLevel,
11    /// Whether the value matches the schema default.
12    pub is_default: bool,
13    /// Whether the core Agent's behavior depends on whether the key is set, not only on its value.
14    ///
15    /// This is true when the overlay marks the key with `presence_matters`, and for every key without
16    /// a schema default: such a key exists in the Agent's configuration only when something sets it,
17    /// so its presence alone can change what the Agent does.
18    pub presence_matters: bool,
19    /// Which pipelines this key's incompatibility warning applies to.
20    pub pipeline_affinity: PipelineAffinity,
21}
22
23/// Classifies keys that can warrant compatibility warnings and compares values with schema defaults.
24///
25/// Keys without a warning entry return `None`, including fully supported and excluded keys.
26pub struct ConfigClassifier {
27    lookup: HashMap<&'static str, &'static ClassifierEntry>,
28}
29
30impl ConfigClassifier {
31    /// Builds a classifier from the generated compatibility-warning entries.
32    pub fn new() -> Self {
33        let mut lookup = HashMap::new();
34
35        for entry in CLASSIFIER_ENTRIES {
36            lookup.insert(entry.yaml_path, entry);
37        }
38
39        Self { lookup }
40    }
41
42    /// Returns `true` if `key` has a compatibility-warning entry.
43    pub fn contains(&self, key: &str) -> bool {
44        self.lookup.contains_key(key)
45    }
46
47    /// Classifies a key/value pair, returning `None` if the key has no compatibility-warning entry.
48    pub fn classify(&self, key: &str, value: &Value) -> Option<Classification> {
49        let entry = self.lookup.get(key)?;
50        Some(Classification {
51            support_level: entry.support_level,
52            is_default: is_default_value(entry.default, value),
53            presence_matters: entry.presence_matters || entry.default == DefaultValue::Missing,
54            pipeline_affinity: entry.pipeline_affinity,
55        })
56    }
57}
58
59fn is_default_value(default: DefaultValue, value: &Value) -> bool {
60    match default {
61        DefaultValue::Json(default_str) => serde_json::from_str::<Value>(default_str)
62            .map(|default_value| *value == default_value)
63            .unwrap_or(false),
64
65        // Duration defaults are canonicalized to nanoseconds at build time. The Agent transmits
66        // durations as integer nanoseconds (and occasionally as a Go duration string), so normalize
67        // the incoming value the same way before comparing.
68        DefaultValue::DurationNanos(default_ns) => duration_value_as_nanos(value)
69            .map(|value_ns| value_ns == default_ns)
70            .unwrap_or(false),
71
72        DefaultValue::Missing => match value {
73            Value::Null => true,
74            Value::String(s) => s.is_empty(),
75            _ => false,
76        },
77    }
78}
79
80/// Normalizes a duration-typed config value to nanoseconds.
81///
82/// Accepts a JSON number already expressed in nanoseconds (the form the Datadog Agent sends over
83/// the config stream) or a Go duration string (for example, `"10s"`). Returns `None` for any other
84/// shape or an out-of-range/invalid value.
85fn duration_value_as_nanos(value: &Value) -> Option<u64> {
86    match value {
87        Value::Number(n) => n.as_u64(),
88        Value::String(s) => go_duration::parse_duration(s).ok().map(|d| d.as_nanos() as u64),
89        _ => None,
90    }
91}
92
93#[cfg(test)]
94mod tests {
95    use super::*;
96    use crate::classifier::{Pipeline, Severity};
97
98    fn classifier() -> ConfigClassifier {
99        ConfigClassifier::new()
100    }
101
102    #[test]
103    fn full_support_keys_not_in_classifier() {
104        // Full-support keys are not actionable at the call site; the classifier omits them.
105        // The call site treats None identically to Full (silently continues).
106        let c = classifier();
107        assert!(c.classify("dogstatsd_port", &Value::Number(9999.into())).is_none());
108        assert!(c.classify("log_payloads", &Value::Bool(true)).is_none());
109    }
110
111    #[test]
112    fn presence_matters_for_overlay_marked_keys_and_keys_without_a_schema_default() {
113        let c = classifier();
114        // The overlay marks `logs_config.compression_kind`: the Agent falls back to gzip for
115        // additional endpoints only when the key is not set.
116        let marked = c
117            .classify("logs_config.compression_kind", &Value::String("zstd".into()))
118            .unwrap();
119        assert!(marked.is_default);
120        assert!(marked.presence_matters);
121
122        // An OTLP receiver TLS key has no schema default; any value creates the `tls` section.
123        let no_default = c
124            .classify(
125                "otlp_config.receiver.protocols.http.tls.cert_pem",
126                &Value::String("".into()),
127            )
128            .unwrap();
129        assert!(no_default.presence_matters);
130
131        let unmarked = c.classify("heroku_dyno", &Value::Bool(false)).unwrap();
132        assert!(!unmarked.presence_matters);
133    }
134
135    #[test]
136    fn dogstatsd_metrics_stats_enable_is_not_classified() {
137        // ADP writes the debug log and serves statistics either way, so neither value is a finding.
138        let c = classifier();
139        assert!(c
140            .classify("dogstatsd_metrics_stats_enable", &Value::Bool(true))
141            .is_none());
142        assert!(c
143            .classify("dogstatsd_metrics_stats_enable", &Value::Bool(false))
144            .is_none());
145    }
146
147    #[test]
148    fn partial_non_default() {
149        let c = classifier();
150        let result = c
151            .classify("min_tls_version", &Value::String("non_default_value".into()))
152            .unwrap();
153        assert_eq!(result.support_level, SupportLevel::Partial);
154    }
155
156    #[test]
157    fn incompatible_non_default() {
158        let c = classifier();
159        let result = c
160            .classify("dogstatsd_stats_buffer", &Value::Number(999.into()))
161            .unwrap();
162        assert!(matches!(result.support_level, SupportLevel::Incompatible(_)));
163        assert!(!result.is_default);
164    }
165
166    #[test]
167    fn incompatible_default() {
168        let c = classifier();
169        // config_id has schema default "" (empty string)
170        let result = c.classify("config_id", &Value::String("".into())).unwrap();
171        assert!(matches!(result.support_level, SupportLevel::Incompatible(_)));
172        assert!(result.is_default);
173    }
174
175    #[test]
176    fn logs_affinity_keys_are_classified_with_the_logs_pipeline() {
177        let c = classifier();
178        let result = c.classify("logs_config.pipelines", &Value::Number(8.into())).unwrap();
179        assert!(matches!(result.support_level, SupportLevel::Incompatible(_)));
180        assert_eq!(result.pipeline_affinity, PipelineAffinity::Pipelines(&[Pipeline::Logs]));
181    }
182
183    #[test]
184    fn partial_keys_without_warning_not_in_classifier() {
185        // A partial key whose difference is only documented has no entry, like a fully supported key.
186        let c = classifier();
187        assert!(c
188            .classify("additional_endpoints", &Value::Object(Default::default()))
189            .is_none());
190    }
191
192    #[test]
193    fn not_in_registry_returns_none() {
194        let c = classifier();
195        assert!(c.classify("totally_made_up_key", &Value::Bool(true)).is_none());
196        assert!(c.classify("GUI_host", &Value::String("localhost".into())).is_none());
197    }
198
199    #[test]
200    fn duration_default_null_is_not_default() {
201        let c = classifier();
202        // dogstatsd_packet_buffer_flush_timeout has a duration default (100ms); a null value can't be normalized.
203        let result = c
204            .classify("dogstatsd_packet_buffer_flush_timeout", &Value::Null)
205            .unwrap();
206        assert!(!result.is_default);
207    }
208
209    #[test]
210    fn duration_default_non_duration_string_is_not_default() {
211        let c = classifier();
212        // Neither an empty string nor arbitrary text parses as a duration, so neither matches.
213        assert!(
214            !c.classify("dogstatsd_packet_buffer_flush_timeout", &Value::String("".into()))
215                .unwrap()
216                .is_default
217        );
218        assert!(
219            !c.classify(
220                "dogstatsd_packet_buffer_flush_timeout",
221                &Value::String("something".into())
222            )
223            .unwrap()
224            .is_default
225        );
226    }
227
228    #[test]
229    fn duration_default_matches_go_duration_string() {
230        let c = classifier();
231        // The default is also matched when supplied as a Go duration string rather than nanoseconds.
232        let result = c
233            .classify("dogstatsd_packet_buffer_flush_timeout", &Value::String("100ms".into()))
234            .unwrap();
235        assert!(result.is_default);
236    }
237
238    #[test]
239    fn incompatible_severity_levels() {
240        let c = classifier();
241        let result = c.classify("dogstatsd_stats_buffer", &Value::Number(30.into())).unwrap();
242        assert!(matches!(
243            result.support_level,
244            SupportLevel::Incompatible(Severity::Medium)
245        ));
246    }
247
248    #[test]
249    fn duration_default_as_nanoseconds_is_default() {
250        let c = classifier();
251        // The Agent transmits dogstatsd_packet_buffer_flush_timeout (schema default "100ms") as integer
252        // nanoseconds. The classifier must recognize this as the default and not flag it as an override.
253        let result = c
254            .classify(
255                "dogstatsd_packet_buffer_flush_timeout",
256                &Value::Number(100_000_000i64.into()),
257            )
258            .unwrap();
259        assert!(result.is_default);
260    }
261
262    #[test]
263    fn duration_non_default_nanoseconds_is_not_default() {
264        let c = classifier();
265        // 5ms in nanoseconds is not the 100ms default.
266        let result = c
267            .classify(
268                "dogstatsd_packet_buffer_flush_timeout",
269                &Value::Number(5_000_000i64.into()),
270            )
271            .unwrap();
272        assert!(!result.is_default);
273    }
274
275    #[test]
276    fn is_default_value_by_variant() {
277        // Json: structural equality against the decoded JSON literal.
278        assert!(is_default_value(
279            DefaultValue::Json("\"tlsv1.2\""),
280            &Value::String("tlsv1.2".into())
281        ));
282        assert!(!is_default_value(
283            DefaultValue::Json("\"tlsv1.2\""),
284            &Value::String("tlsv1.3".into())
285        ));
286        assert!(is_default_value(DefaultValue::Json("1"), &Value::Number(1.into())));
287
288        // DurationNanos: matches both the nanosecond number and the equivalent Go duration string.
289        assert!(is_default_value(
290            DefaultValue::DurationNanos(10_000_000_000),
291            &Value::Number(10_000_000_000u64.into())
292        ));
293        assert!(is_default_value(
294            DefaultValue::DurationNanos(10_000_000_000),
295            &Value::String("10s".into())
296        ));
297        assert!(!is_default_value(
298            DefaultValue::DurationNanos(10_000_000_000),
299            &Value::Number(5_000_000_000u64.into())
300        ));
301        assert!(!is_default_value(
302            DefaultValue::DurationNanos(10_000_000_000),
303            &Value::String("nope".into())
304        ));
305
306        // Missing: only null or an empty string counts as "default".
307        assert!(is_default_value(DefaultValue::Missing, &Value::Null));
308        assert!(is_default_value(DefaultValue::Missing, &Value::String("".into())));
309        assert!(!is_default_value(DefaultValue::Missing, &Value::String("x".into())));
310    }
311}