Skip to main content

datadog_agent_runtime/control_plane/
config_runtime.rs

1//! Runtime configuration API handler.
2
3use std::sync::Arc;
4
5use async_trait::async_trait;
6use saluki_api::{
7    extract::State,
8    response::IntoResponse,
9    routing::{get, Router},
10    APIHandler, DynamicRoute, EndpointType, StatusCode,
11};
12use saluki_common::sync::shutdown::ShutdownHandle;
13use saluki_core::runtime::{state::DataspaceRegistry, InitializationError, Supervisable, SupervisorFuture};
14use saluki_error::generic_error;
15use serde::Serialize;
16
17/// Produces the current runtime configuration in its serialized JSON form.
18#[derive(Clone)]
19pub struct RuntimeConfigSnapshot {
20    serialize: Arc<dyn Fn() -> Result<String, serde_json::Error> + Send + Sync>,
21}
22
23impl RuntimeConfigSnapshot {
24    /// Creates a `RuntimeConfigSnapshot` that calls `load` once per request and serializes the returned configuration.
25    ///
26    /// The loader is retained for later requests. Each returned `Arc` keeps its version alive until serialization finishes.
27    pub fn from_loader<T, F>(load: F) -> Self
28    where
29        T: Serialize,
30        F: Fn() -> Arc<T> + Send + Sync + 'static,
31    {
32        Self {
33            serialize: Arc::new(move || serde_json::to_string(&*load())),
34        }
35    }
36
37    fn to_json(&self) -> Result<String, serde_json::Error> {
38        (self.serialize)()
39    }
40}
41
42/// State used for the runtime configuration API handler.
43#[derive(Clone)]
44pub struct ConfigRuntimeState {
45    snapshot: RuntimeConfigSnapshot,
46}
47
48/// An API handler for returning the translated runtime configuration.
49///
50/// This handler exposes a single route -- `/config/runtime` -- that returns the current
51/// translated configuration in its serialized JSON form. It reflects any dynamic updates
52/// applied to the configuration since startup.
53pub struct ConfigRuntimeAPIHandler {
54    state: ConfigRuntimeState,
55}
56
57impl ConfigRuntimeAPIHandler {
58    fn new(snapshot: RuntimeConfigSnapshot) -> Self {
59        Self {
60            state: ConfigRuntimeState { snapshot },
61        }
62    }
63
64    async fn config_handler(State(state): State<ConfigRuntimeState>) -> impl IntoResponse {
65        match state.snapshot.to_json() {
66            Ok(body) => (StatusCode::OK, body).into_response(),
67            Err(e) => (
68                StatusCode::INTERNAL_SERVER_ERROR,
69                format!("Failed to serialize configuration: {}", e),
70            )
71                .into_response(),
72        }
73    }
74}
75
76impl APIHandler for ConfigRuntimeAPIHandler {
77    type State = ConfigRuntimeState;
78
79    fn generate_initial_state(&self) -> Self::State {
80        self.state.clone()
81    }
82
83    fn generate_routes(&self) -> Router<Self::State> {
84        Router::new().route("/config/runtime", get(Self::config_handler))
85    }
86}
87
88/// A worker for exposing an endpoint that returns the translated runtime configuration.
89///
90/// When running, the worker asserts a route (based on `ConfigRuntimeAPIHandler`) that returns
91/// the current translated configuration. As the configuration may contain sensitive data, this
92/// route is only present on the privileged API endpoint.
93pub struct ConfigRuntimeWorker {
94    handler: ConfigRuntimeAPIHandler,
95}
96
97impl ConfigRuntimeWorker {
98    /// Creates a new [`ConfigRuntimeWorker`] serving the given configuration.
99    pub fn new(snapshot: RuntimeConfigSnapshot) -> Self {
100        Self {
101            handler: ConfigRuntimeAPIHandler::new(snapshot),
102        }
103    }
104}
105
106#[async_trait]
107impl Supervisable for ConfigRuntimeWorker {
108    fn name(&self) -> &str {
109        "config-runtime-api"
110    }
111
112    async fn initialize(&self, process_shutdown: ShutdownHandle) -> Result<SupervisorFuture, InitializationError> {
113        let config_route = DynamicRoute::http(EndpointType::Privileged, &self.handler);
114
115        Ok(Box::pin(async move {
116            let dataspace =
117                DataspaceRegistry::try_current().ok_or_else(|| generic_error!("Dataspace not available."))?;
118
119            dataspace.assert(config_route, "config-runtime-api");
120
121            process_shutdown.await;
122            Ok(())
123        }))
124    }
125}
126
127#[cfg(test)]
128mod tests {
129    use arc_swap::ArcSwap;
130
131    use super::*;
132
133    #[derive(Serialize)]
134    struct ExampleConfig {
135        log_level: String,
136    }
137
138    #[test]
139    fn snapshot_serializes_the_configuration_its_loader_returns_at_each_request() {
140        let current = Arc::new(ArcSwap::from_pointee(ExampleConfig {
141            log_level: "info".to_string(),
142        }));
143        let loaded = Arc::clone(&current);
144        let snapshot = RuntimeConfigSnapshot::from_loader(move || loaded.load_full());
145        assert_eq!(snapshot.to_json().unwrap(), r#"{"log_level":"info"}"#);
146
147        current.store(Arc::new(ExampleConfig {
148            log_level: "debug".to_string(),
149        }));
150        assert_eq!(snapshot.to_json().unwrap(), r#"{"log_level":"debug"}"#);
151    }
152}