Skip to main content

agent_data_plane_config_system/
compatibility.rs

1//! Compatibility checks against the merged configuration sources.
2//!
3//! The typed model is the Agent schema pruned to the keys ADP supports, so the unsupported keys this
4//! check exists to catch are absent from it by construction. It reads the by-key view of the merged
5//! sources instead, which holds every key any input supplied along with the provenance of each.
6
7use std::collections::HashSet;
8use std::sync::OnceLock;
9
10use agent_data_plane_config::Provenance;
11use datadog_agent_config::classifier::{ConfigClassifier, Pipeline, PipelineAffinity, Severity, SupportLevel};
12use saluki_error::{generic_error, GenericError};
13use tracing::{debug, error, trace, warn};
14
15use crate::ConfigurationSystem;
16
17/// Returns the compatibility classifier, built once for the process.
18pub(crate) fn classifier() -> &'static ConfigClassifier {
19    static CLASSIFIER: OnceLock<ConfigClassifier> = OnceLock::new();
20    CLASSIFIER.get_or_init(ConfigClassifier::new)
21}
22
23impl ConfigurationSystem {
24    /// Checks settings that an input set explicitly and that affect active pipelines, logging the
25    /// severity of each. A setting at its default value is skipped, unless the Agent's behavior
26    /// depends on whether the key is set.
27    ///
28    /// # Errors
29    ///
30    /// Returns an error if high-severity incompatibilities exist. All keys are checked before
31    /// returning, so the error includes the total count.
32    pub fn check_compatibility(&self, active_pipelines: &HashSet<Pipeline>) -> Result<(), GenericError> {
33        let mut high_severity_incompatibilities = 0u32;
34        debug!("Analyzing configuration.");
35        for (key, support_level) in self.compatibility_findings(active_pipelines) {
36            match support_level {
37                SupportLevel::Incompatible(Severity::Low) => {
38                    debug!("Low-severity incompatible key detected. Proceeding.")
39                }
40                SupportLevel::Partial => {
41                    warn!(key = %key, "Partially supported configuration key. See documentation for details. Proceeding.")
42                }
43                SupportLevel::Incompatible(Severity::Medium) => {
44                    warn!(key = %key, "Unsupported configuration key. Proceeding.")
45                }
46                SupportLevel::Incompatible(Severity::High) => {
47                    error!(key = %key, "Unsupported configuration key is set to a value other than its default. ADP \
48                    cannot run safely with this setting.");
49                    high_severity_incompatibilities += 1;
50                }
51                SupportLevel::Ignored | SupportLevel::Unrecognized => {
52                    trace!(key = %key, "Configuration key not-applicable. Silently ignoring.")
53                }
54            }
55        }
56
57        if high_severity_incompatibilities > 0 {
58            return Err(generic_error!(
59                "{high_severity_incompatibilities} incompatible configuration detected. ADP cannot start. Review error \
60                logs for details."
61            ));
62        }
63
64        Ok(())
65    }
66
67    /// Returns each classified key that an input set explicitly and that affects an active pipeline,
68    /// with its support level.
69    ///
70    /// A key set to its default value is left out, unless the Agent's behavior depends on whether the
71    /// key is set.
72    fn compatibility_findings(&self, active_pipelines: &HashSet<Pipeline>) -> Vec<(String, SupportLevel)> {
73        let classifier = classifier();
74        let mut findings = Vec::new();
75        for (key, value, provenance) in self.sources().flattened_keys() {
76            let Some(classification) = classifier.classify(&key, value) else {
77                continue;
78            };
79
80            let pipeline_is_active = match &classification.pipeline_affinity {
81                PipelineAffinity::Pipelines(affected) => affected.iter().any(|p| active_pipelines.contains(p)),
82                PipelineAffinity::CrossCutting => true,
83            };
84            if !pipeline_is_active {
85                continue;
86            }
87
88            // A producer publishes every key it knows about, the ones nobody configured included, so
89            // only a key an input set explicitly says anything about what the operator asked for.
90            if provenance == Provenance::Default {
91                trace!(key = %key, "Configuration key is not set by any input.");
92                continue;
93            }
94
95            // A key set explicitly to its schema default asks for the behavior ADP has when nobody
96            // sets it. The comparison can miss a default written in another form, such as a duration
97            // or a coerced scalar. A miss reports the key, so the check fails safe. A key whose
98            // presence alone changes the Agent's behavior is reported at its default too.
99            if classification.is_default && !classification.presence_matters {
100                trace!(key = %key, "Configuration key is set to its default value.");
101                continue;
102            }
103
104            findings.push((key, classification.support_level));
105        }
106
107        findings
108    }
109}
110
111#[cfg(test)]
112mod tests {
113    use std::collections::HashSet;
114
115    use datadog_agent_config::classifier::{Classification, Pipeline, PipelineAffinity, Severity, SupportLevel};
116    use saluki_config::dynamic::{ConfigSetting, Provenance as StreamProvenance};
117    use serde_json::{json, Value};
118
119    use super::classifier;
120    use crate::system::translate_strict;
121    use crate::{source::SourceTree, ConfigurationSystem};
122
123    /// Builds a system whose sources are a local configuration file, so every key present was set
124    /// explicitly.
125    fn system_with(file: Value) -> ConfigurationSystem {
126        system_from(SourceTree::all_explicit(file))
127    }
128
129    /// Builds a system whose sources are the settings a configuration producer published, each
130    /// carrying its own provenance.
131    fn system_from_settings(settings: &[(&str, Value, StreamProvenance)]) -> ConfigurationSystem {
132        let settings: Vec<_> = settings
133            .iter()
134            .map(|(key, value, provenance)| ConfigSetting::new(*key, value.clone(), *provenance))
135            .collect();
136
137        system_from(SourceTree::from_settings(&settings))
138    }
139
140    fn system_from(sources: SourceTree) -> ConfigurationSystem {
141        let config = translate_strict(&sources).expect("sources translate");
142        ConfigurationSystem::standalone(config, sources)
143    }
144
145    /// Classifies `key` as the compatibility check sees it among the merged sources.
146    fn classification_of(system: &ConfigurationSystem, key: &str) -> Option<Classification> {
147        system
148            .sources()
149            .flattened_keys()
150            .into_iter()
151            .find(|(flattened, _, _)| flattened == key)
152            .and_then(|(flattened, value, _)| classifier().classify(&flattened, value))
153    }
154
155    fn pipelines(active: &[Pipeline]) -> HashSet<Pipeline> {
156        active.iter().copied().collect()
157    }
158
159    fn otlp_tls_settings(cert_pem: &str, key_pem: &str) -> Value {
160        json!({
161            "otlp_config": {
162                "receiver": {
163                    "protocols": {
164                        "http": {
165                            "tls": { "cert_pem": cert_pem, "key_pem": key_pem }
166                        }
167                    }
168                }
169            }
170        })
171    }
172
173    #[test]
174    fn high_severity_keys_fail_the_check_and_are_all_counted() {
175        let system = system_with(otlp_tls_settings("/etc/adp/cert.pem", "/etc/adp/key.pem"));
176
177        let error = system
178            .check_compatibility(&pipelines(&[Pipeline::Otlp]))
179            .expect_err("a high-severity incompatible key should fail the check");
180
181        assert!(error.to_string().contains("2 incompatible configuration detected"));
182    }
183
184    #[test]
185    fn a_high_severity_key_nobody_set_is_skipped() {
186        // The Agent publishes every key it knows about, so a key it reports at its own default is a
187        // key nobody configured, whatever value it holds.
188        let system = system_from_settings(&[
189            (
190                "otlp_config.receiver.protocols.http.tls.cert_pem",
191                json!("/etc/adp/cert.pem"),
192                StreamProvenance::Default,
193            ),
194            (
195                "otlp_config.receiver.protocols.http.tls.key_pem",
196                json!("/etc/adp/key.pem"),
197                StreamProvenance::Default,
198            ),
199        ]);
200
201        system
202            .check_compatibility(&pipelines(&[Pipeline::Otlp]))
203            .expect("a key nobody set is not an incompatibility");
204    }
205
206    #[test]
207    fn a_high_severity_key_set_to_its_default_value_is_skipped() {
208        // A key written at its schema default asks for the behavior ADP has when nobody sets it, so
209        // it isn't an incompatibility.
210        let system = system_with(json!({ "heroku_dyno": false }));
211
212        system
213            .check_compatibility(&pipelines(&[]))
214            .expect("a key set to its default value is not an incompatibility");
215        assert!(system.compatibility_findings(&pipelines(&[])).is_empty());
216    }
217
218    #[test]
219    fn a_key_whose_presence_matters_is_reported_at_its_default_value() {
220        // Any value under `tls`, an empty one included, makes the Agent's OTLP receiver configure TLS.
221        let no_schema_default = system_with(otlp_tls_settings("", ""));
222        let error = no_schema_default
223            .check_compatibility(&pipelines(&[Pipeline::Otlp]))
224            .expect_err("a key without a schema default is checked whatever its value");
225        assert!(error.to_string().contains("2 incompatible configuration detected"));
226
227        // With additional endpoints, the Agent falls back to gzip only when `compression_kind` is not set.
228        let marked = system_with(json!({ "logs_config": { "compression_kind": "zstd" } }));
229        assert_eq!(
230            marked.compatibility_findings(&pipelines(&[Pipeline::Logs])),
231            vec![(
232                "logs_config.compression_kind".to_string(),
233                SupportLevel::Incompatible(Severity::Medium)
234            )]
235        );
236    }
237
238    #[test]
239    fn a_warning_key_set_to_its_default_value_is_skipped() {
240        let system = system_with(json!({
241            "min_tls_version": "tlsv1.2",
242            "dogstatsd_telemetry_enabled_listener_id": false,
243        }));
244
245        assert!(system
246            .compatibility_findings(&pipelines(&[Pipeline::DogStatsD]))
247            .is_empty());
248    }
249
250    #[test]
251    fn a_warning_key_set_to_a_non_default_value_is_reported() {
252        let system = system_with(json!({
253            "min_tls_version": "tlsv1.3",
254            "dogstatsd_telemetry_enabled_listener_id": true,
255        }));
256
257        let mut findings = system.compatibility_findings(&pipelines(&[Pipeline::DogStatsD]));
258        findings.sort_by(|a, b| a.0.cmp(&b.0));
259        assert_eq!(
260            findings,
261            vec![
262                (
263                    "dogstatsd_telemetry_enabled_listener_id".to_string(),
264                    SupportLevel::Incompatible(Severity::Medium)
265                ),
266                ("min_tls_version".to_string(), SupportLevel::Partial),
267            ]
268        );
269    }
270
271    #[test]
272    fn a_default_value_the_comparison_misses_is_still_reported() {
273        // The default comparison does not coerce a string to a boolean, or a float to integer
274        // nanoseconds. A value it can't match is reported, so a miss fails safe.
275        let coerced_scalar = system_with(json!({ "heroku_dyno": "false" }));
276        coerced_scalar
277            .check_compatibility(&pipelines(&[]))
278            .expect_err("a default value the comparison misses is still checked");
279
280        let duration = system_with(json!({ "dogstatsd_packet_buffer_flush_timeout": 100_000_000.0 }));
281        assert_eq!(
282            duration.compatibility_findings(&pipelines(&[Pipeline::DogStatsD])),
283            vec![(
284                "dogstatsd_packet_buffer_flush_timeout".to_string(),
285                SupportLevel::Incompatible(Severity::Low)
286            )]
287        );
288    }
289
290    #[test]
291    fn a_high_severity_key_affecting_no_active_pipeline_is_skipped() {
292        let system = system_with(otlp_tls_settings("/etc/adp/cert.pem", "/etc/adp/key.pem"));
293
294        system
295            .check_compatibility(&pipelines(&[Pipeline::DogStatsD]))
296            .expect("an inactive pipeline's keys are not incompatibilities");
297    }
298
299    #[test]
300    fn lower_severity_keys_pass_and_cross_cutting_keys_ignore_active_pipelines() {
301        let system = system_with(json!({ "dogstatsd_pipeline_count": 4, "min_tls_version": "tlsv1.3" }));
302        system
303            .check_compatibility(&pipelines(&[Pipeline::DogStatsD]))
304            .expect("only high-severity incompatibilities fail the check");
305
306        let cross_cutting = system_with(json!({ "heroku_dyno": true }));
307        cross_cutting
308            .check_compatibility(&pipelines(&[]))
309            .expect_err("a cross-cutting high-severity key fails the check with no pipeline active");
310    }
311
312    #[test]
313    fn an_unsupported_object_setting_is_classified_under_its_own_key() {
314        // `use_v3_api.distributions.endpoints` holds an object and no model describes it. The check must see
315        // it as the setting it is, whether it comes from a file or from the configuration stream.
316        let key = "use_v3_api.distributions.endpoints";
317        let endpoints = json!({ "https://example.test": ["api-key"] });
318        let from_file = system_with(json!({ "use_v3_api": { "distributions": { "endpoints": endpoints } } }));
319        let from_stream = system_from_settings(&[(key, endpoints.clone(), StreamProvenance::Explicit)]);
320
321        for system in [from_file, from_stream] {
322            let classification = classification_of(&system, key).expect("the setting is classified under its own key");
323            assert_eq!(
324                classification.support_level,
325                SupportLevel::Incompatible(Severity::Medium)
326            );
327            assert_eq!(
328                classification.pipeline_affinity,
329                PipelineAffinity::Pipelines(&[Pipeline::DogStatsD])
330            );
331        }
332    }
333
334    #[test]
335    fn keys_the_registry_does_not_know_are_ignored() {
336        let system = system_with(json!({ "not_a_real_agent_setting": true, "dogstatsd_port": 9125 }));
337
338        system
339            .check_compatibility(&pipelines(&[Pipeline::DogStatsD]))
340            .expect("unclassified keys are not incompatibilities");
341    }
342}