Skip to main content

datadog_agent_runtime/
agent_stream.rs

1//! Converts the Agent's config-stream wire events into `saluki_config` updates.
2//!
3//! The running process and the library's corpus replay tests share this path. Tests can construct
4//! the exact snapshot and update events the Agent sends without depending on the binary crate.
5
6use datadog_protos::agent::{config_event, ConfigEvent, ConfigSetting as AgentConfigSetting, ConfigSnapshot};
7use prost_types::value::Kind;
8use saluki_config::dynamic::{ConfigSetting, ConfigUpdate, Provenance};
9use serde_json::{Map, Value};
10use tracing::error;
11
12/// Sources that indicate the Agent supplied the value rather than an operator.
13pub const AGENT_DEFAULT_SOURCE: &str = "default";
14/// A value neither set by the user nor supplied with a schema default.
15pub const AGENT_DECLARED_ONLY_SOURCE: &str = "schema";
16/// The sources that mark a setting as an Agent-supplied default rather than an explicit value.
17pub const AGENT_UNSET_SOURCES: [&str; 2] = [AGENT_DEFAULT_SOURCE, AGENT_DECLARED_ONLY_SOURCE];
18
19/// Converts an Agent wire setting to a [`ConfigSetting`], preserving whether its source is a default.
20pub fn setting_to_config_setting(setting: &AgentConfigSetting) -> ConfigSetting {
21    let provenance = if AGENT_UNSET_SOURCES.contains(&setting.source.as_str()) {
22        Provenance::Default
23    } else {
24        Provenance::Explicit
25    };
26
27    ConfigSetting::new(
28        setting.key.clone(),
29        proto_value_to_serde_value(&setting.value),
30        provenance,
31    )
32}
33
34/// Converts a `ConfigSnapshot` into the settings it carries.
35pub fn snapshot_to_settings(snapshot: &ConfigSnapshot) -> Vec<ConfigSetting> {
36    snapshot.settings.iter().map(setting_to_config_setting).collect()
37}
38
39/// Converts one event from the Agent's config stream into the update it carries.
40///
41/// A snapshot event becomes [`ConfigUpdate::Snapshot`] and an update event becomes
42/// [`ConfigUpdate::Partial`]. Returns `None` for an update event that carries no setting, and logs an
43/// error and returns `None` for an event with no data at all.
44pub fn config_event_to_update(event: ConfigEvent) -> Option<ConfigUpdate> {
45    match event.event {
46        Some(config_event::Event::Snapshot(snapshot)) => Some(ConfigUpdate::Snapshot(snapshot_to_settings(&snapshot))),
47        Some(config_event::Event::Update(update)) => update
48            .setting
49            .as_ref()
50            .map(|setting| ConfigUpdate::Partial(setting_to_config_setting(setting))),
51        None => {
52            error!("Received a configuration update event with no data.");
53            None
54        }
55    }
56}
57
58/// Recursively converts a `google::protobuf::Value` into a `serde_json::Value`.
59pub fn proto_value_to_serde_value(proto_val: &Option<prost_types::Value>) -> Value {
60    let Some(kind) = proto_val.as_ref().and_then(|v| v.kind.as_ref()) else {
61        return Value::Null;
62    };
63
64    match kind {
65        Kind::NullValue(_) => Value::Null,
66        Kind::NumberValue(n) => {
67            if n.fract() == 0.0 && *n >= i64::MIN as f64 && *n <= i64::MAX as f64 {
68                Value::from(*n as i64)
69            } else {
70                Value::from(*n)
71            }
72        }
73        Kind::StringValue(s) => Value::String(s.clone()),
74        Kind::BoolValue(b) => Value::Bool(*b),
75        Kind::StructValue(s) => {
76            let json_map: Map<String, Value> = s
77                .fields
78                .iter()
79                .map(|(k, v)| (k.clone(), proto_value_to_serde_value(&Some(v.clone()))))
80                .collect();
81            Value::Object(json_map)
82        }
83        Kind::ListValue(l) => {
84            let json_list: Vec<Value> = l
85                .values
86                .iter()
87                .map(|v| proto_value_to_serde_value(&Some(v.clone())))
88                .collect();
89            Value::Array(json_list)
90        }
91    }
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97
98    fn agent_setting(source: &str, key: &str, value: &str) -> AgentConfigSetting {
99        AgentConfigSetting {
100            source: source.to_string(),
101            key: key.to_string(),
102            value: Some(prost_types::Value {
103                kind: Some(Kind::StringValue(value.to_string())),
104            }),
105            ..Default::default()
106        }
107    }
108
109    #[test]
110    fn an_agent_default_is_marked_as_a_default() {
111        let setting = setting_to_config_setting(&agent_setting(
112            AGENT_DEFAULT_SOURCE,
113            "dd_url",
114            "https://app.datadoghq.com",
115        ));
116
117        assert_eq!(setting.key, "dd_url");
118        assert_eq!(setting.value, Value::from("https://app.datadoghq.com"));
119        assert_eq!(setting.provenance, Provenance::Default);
120    }
121
122    #[test]
123    fn a_schema_setting_is_marked_as_a_default() {
124        let setting = setting_to_config_setting(&AgentConfigSetting {
125            source: "schema".to_string(),
126            key: "api_key".to_string(),
127            value: None,
128            ..Default::default()
129        });
130
131        assert_eq!(setting.value, Value::Null);
132        assert_eq!(setting.provenance, Provenance::Default);
133    }
134
135    #[test]
136    fn null_values_are_preserved_with_their_provenance() {
137        for source in [AGENT_DEFAULT_SOURCE, "schema", "file", "remote-config"] {
138            let setting = setting_to_config_setting(&AgentConfigSetting {
139                source: source.to_string(),
140                key: "api_key".to_string(),
141                value: Some(prost_types::Value {
142                    kind: Some(Kind::NullValue(0)),
143                }),
144                ..Default::default()
145            });
146
147            let expected_provenance = if [AGENT_DEFAULT_SOURCE, "schema"].contains(&source) {
148                Provenance::Default
149            } else {
150                Provenance::Explicit
151            };
152            assert_eq!(setting.value, Value::Null);
153            assert_eq!(setting.provenance, expected_provenance, "source {source}");
154        }
155    }
156
157    #[test]
158    fn an_empty_string_value_is_kept_with_its_provenance() {
159        // An empty string is still a value; provenance comes from its source, not its content.
160        for (source, provenance) in [
161            ("file", Provenance::Explicit),
162            ("default", Provenance::Default),
163            ("schema", Provenance::Default),
164        ] {
165            let setting = setting_to_config_setting(&agent_setting(source, "site", ""));
166
167            assert_eq!(setting.value, Value::from(""));
168            assert_eq!(setting.provenance, provenance);
169        }
170    }
171
172    #[test]
173    fn operator_supplied_sources_are_marked_as_explicit() {
174        // Unknown sources are treated as explicit inputs rather than defaults.
175        for source in [
176            "file",
177            "environment-variable",
178            "remote-config",
179            "cli",
180            "source-from-the-future",
181        ] {
182            let setting = setting_to_config_setting(&agent_setting(source, "dd_url", "https://app.datadoghq.eu"));
183
184            assert_eq!(
185                setting.provenance,
186                Provenance::Explicit,
187                "source {source} should be explicit"
188            );
189        }
190    }
191
192    #[test]
193    fn snapshot_settings_keep_order_values_and_provenance() {
194        let snapshot = ConfigSnapshot {
195            origin: "core-agent".to_string(),
196            sequence_id: 1,
197            settings: vec![
198                agent_setting("file", "site", "datadoghq.eu"),
199                agent_setting("default", "dd_url", "https://app.datadoghq.com"),
200                agent_setting(AGENT_DECLARED_ONLY_SOURCE, "api_key", ""),
201            ],
202        };
203
204        let settings = snapshot_to_settings(&snapshot);
205
206        assert_eq!(
207            settings,
208            vec![
209                ConfigSetting::explicit("site", Value::from("datadoghq.eu")),
210                ConfigSetting::new("dd_url", Value::from("https://app.datadoghq.com"), Provenance::Default),
211                ConfigSetting::new("api_key", Value::from(""), Provenance::Default),
212            ]
213        );
214    }
215}