Skip to main content

datadog_agent_runtime/facade/
mod.rs

1//! A staged facade that drives the whole startup sequence of a remote agent.
2//!
3//! [`RemoteAgent`] walks through the stages in [`stage`], each of which hands control back to the binary at the point
4//! where it has work of its own to do:
5//!
6//! 1. [`RemoteAgent::start`] registers with the Datadog Agent, waits for the initial configuration, and reloads logging
7//!    to match it. In the [`Started`] stage, the binary can check its configuration before anything else starts.
8//! 2. [`RemoteAgent::initialize`] creates the registries and the environment provider, which opens the connections for
9//!    the workload provider. In the [`Initialized`] stage, the binary builds its topology and its control plane
10//!    supervisor, and adds the supervisor from [`RemoteAgent::create_remote_agent_supervisor`] to its control plane.
11//!    The binary can also subscribe to Remote Configuration products through [`RemoteAgent::remote_config_client`].
12//! 3. [`RemoteAgent::run`] creates the internal supervisor around the binary's control plane, validates the memory
13//!    bounds of everything registered so far, and runs the supervision tree until the process is asked to shut down.
14//!
15//! The [crate documentation](crate#supervision-tree) shows the resulting supervision tree.
16
17use std::{
18    future::Future,
19    sync::Arc,
20    time::{Duration, Instant},
21};
22
23use datadog_agent_commons::ipc::{config::RemoteAgentClientConfiguration, session::SessionIdHandle};
24use datadog_agent_remote_config::RemoteConfigurationClient;
25use saluki_app::{
26    accounting::initialize_memory_bounds, bootstrap::BootstrapGuard, metrics::emit_startup_metrics,
27    util::wait_for_shutdown_signal,
28};
29use saluki_core::{
30    accounting::ComponentRegistry,
31    health::HealthRegistry,
32    observability::metrics::RemapperRule,
33    runtime::{self, state::ResourceRegistry, RestartMode, RestartStrategy, Supervisor, SupervisorError},
34    topology::TopologyBlueprint,
35};
36use saluki_error::{ErrorContext as _, GenericError};
37use tonic::service::Routes;
38use tracing::{info, warn};
39
40use crate::{
41    control_plane::ConfigUpdatesWorker,
42    env::RemoteAgentEnvironmentProvider,
43    logging::LoggingTranslator,
44    remote_agent::{RemoteAgentBootstrap, StatusSectionProvider},
45};
46
47mod config;
48pub use self::config::{AuthoritativeConfiguration, LocalConfiguration, RemoteAgentSpecification};
49
50mod remote_config;
51
52pub mod stage;
53pub use self::stage::{Initialized, Started, Unstarted};
54use self::stage::{InitializedData, Stage, StartedData, UnstartedData};
55
56/// The remote agent startup sequence.
57///
58/// `R` is the binary's [`RemoteAgentSpecification`], and `S` is the current [stage], which determines the methods
59/// available.
60pub struct RemoteAgent<R, S = Unstarted>
61where
62    R: RemoteAgentSpecification,
63    S: Stage,
64{
65    inner: S::Data<R>,
66}
67
68impl<R> RemoteAgent<R, Unstarted>
69where
70    R: RemoteAgentSpecification,
71{
72    /// Creates a new `RemoteAgent` from its local configuration.
73    ///
74    /// `translator` translates the authoritative logging settings once they're known.
75    pub fn new(local: R::LocalConfiguration, translator: LoggingTranslator) -> Self {
76        Self {
77            inner: UnstartedData {
78                local,
79                translator,
80                start_time: Instant::now(),
81            },
82        }
83    }
84
85    /// Sets the time the process started, which is used to report how long the topology took to become healthy.
86    ///
87    /// Defaults to the time the `RemoteAgent` was created.
88    pub fn with_start_time(mut self, start_time: Instant) -> Self {
89        self.inner.start_time = start_time;
90        self
91    }
92
93    /// Selects the configuration authority and reloads logging to match it.
94    ///
95    /// In connected mode, this registers with the Datadog Agent and waits for its initial configuration. In standalone
96    /// mode, the local configuration becomes authoritative.
97    ///
98    /// `bootstrap_supervisor` is the supervisor returned by the process bootstrap, which runs as the first child of the
99    /// root supervisor.
100    ///
101    /// # Errors
102    ///
103    /// If registration fails, or the configuration can't be loaded, an error is returned.
104    pub async fn start(
105        self, bootstrap_guard: &mut BootstrapGuard, bootstrap_supervisor: Supervisor,
106    ) -> Result<RemoteAgent<R, Started>, GenericError> {
107        let UnstartedData {
108            local,
109            translator,
110            start_time,
111        } = self.inner;
112        let app_details = saluki_metadata::get_app_details();
113        info!(
114            version = app_details.version().raw(),
115            git_hash = app_details.git_hash(),
116            target_arch = app_details.target_arch(),
117            build_time = app_details.build_time(),
118            process_id = std::process::id(),
119            "{} starting...",
120            app_details.full_name()
121        );
122
123        // Use local sources for decisions required before the Agent configuration stream is available.
124        let standalone = local.is_standalone();
125
126        // Resolve the authoritative configuration. Connected mode registers as a remote agent and takes the Core
127        // Agent's config stream as authority; standalone mode treats the local sources as authoritative. Both block
128        // until the first configuration is received and validated, failing the boot if it cannot be -- the strict
129        // startup gate.
130        let (config, ra_bootstrap, config_stream_worker, config_updates) = if standalone {
131            let config = local
132                .into_standalone()
133                .await
134                .error_context("Failed to load configuration.")?;
135            (config, None, None, None)
136        } else {
137            // Blocks until the Core Agent acknowledges registration.
138            let client_config = local.client_configuration()?;
139            let ra_bootstrap = async {
140                let secure_api_listen_address = local.advertised_secure_api_address()?;
141                RemoteAgentBootstrap::new(&client_config, &secure_api_listen_address, R::ADDITIONAL_SERVICE_NAMES).await
142            }
143            .await
144            .error_context("Failed to bootstrap remote agent state.")?;
145
146            // The configuration system owns the config stream. `ra_bootstrap` is kept to build the remote agent workers
147            // in `create_remote_agent_supervisor`, and the registration worker in `run_until`.
148            let (config_stream, config_stream_worker) = ra_bootstrap.create_config_stream();
149
150            info!("Waiting for initial configuration from Datadog Agent...");
151            let (config, config_updates) = local
152                .connect(config_stream)
153                .await
154                .error_context("Failed to load initial configuration from the Datadog Agent.")?;
155            info!("Initial configuration received.");
156
157            (
158                config,
159                Some(ra_bootstrap),
160                Some(config_stream_worker),
161                Some(config_updates),
162            )
163        };
164
165        // Connected mode may have replaced the bootstrap-phase settings with the Agent's authoritative config, so
166        // reload logging to match. Standalone resolves the same local sources seen at bootstrap, making a reload
167        // redundant.
168        if !standalone {
169            match translator.translate(config.logging()) {
170                Ok(logging_config) => {
171                    if let Err(e) = bootstrap_guard.logging_mut().reload(logging_config).await {
172                        warn!(
173                            error = %e,
174                            "Failed to reload logging from Agent configuration; continuing with bootstrap logging settings."
175                        );
176                    }
177                }
178                Err(e) => warn!(
179                    error = %e,
180                    "Failed to translate logging configuration from Agent; continuing with bootstrap logging settings."
181                ),
182            }
183        }
184
185        Ok(RemoteAgent {
186            inner: StartedData {
187                config,
188                ra_bootstrap,
189                config_stream_worker,
190                config_updates,
191                bootstrap_supervisor,
192                start_time,
193            },
194        })
195    }
196}
197
198impl<R> RemoteAgent<R, Started>
199where
200    R: RemoteAgentSpecification,
201{
202    /// Returns the authoritative configuration.
203    pub fn config(&self) -> &R::AuthoritativeConfiguration {
204        &self.inner.config
205    }
206
207    /// Returns `true` if the remote agent runs without the Datadog Agent.
208    pub fn is_standalone(&self) -> bool {
209        self.inner.config.is_standalone()
210    }
211
212    /// Creates the registries and the environment provider.
213    ///
214    /// In connected mode, the environment provider connects to the Datadog Agent for the hostname, autodiscovery, and
215    /// workload metadata. In standalone mode, it reports the configured hostname, and nothing else.
216    ///
217    /// # Errors
218    ///
219    /// If the environment provider can't be created, an error is returned.
220    pub async fn initialize(self) -> Result<RemoteAgent<R, Initialized>, GenericError> {
221        // Create the root supervisor up front so that the binary's control plane can serve a handle to the whole
222        // supervision tree. Nothing is added to it until the rest of the tree is built.
223        //
224        // The name can't be a bare `root`: it would collide with the built-in `root` resource group.
225        let root_supervisor_name = format!("{}-root", saluki_metadata::get_app_details().identifier());
226        let root_restart_strategy = RestartStrategy::new(RestartMode::OneForOne, 0, Duration::from_secs(5));
227        let root_supervisor = Supervisor::new(root_supervisor_name)?.with_restart_strategy(root_restart_strategy);
228
229        // Set up all of the building blocks for building topologies and launching internal processes.
230        let component_registry = ComponentRegistry::default();
231        let health_registry = HealthRegistry::new();
232        let resource_registry = ResourceRegistry::new();
233        let (env_provider, env_supervisor) = RemoteAgentEnvironmentProvider::from_authoritative(
234            &self.inner.config,
235            &component_registry,
236            &health_registry,
237        )
238        .await?;
239
240        Ok(RemoteAgent {
241            inner: InitializedData {
242                started: self.inner,
243                root_supervisor,
244                component_registry,
245                health_registry,
246                resource_registry,
247                env_provider,
248                env_supervisor,
249                remote_config: None,
250            },
251        })
252    }
253}
254
255impl<R> RemoteAgent<R, Initialized>
256where
257    R: RemoteAgentSpecification,
258{
259    /// Returns the authoritative configuration.
260    pub fn config(&self) -> &R::AuthoritativeConfiguration {
261        &self.inner.started.config
262    }
263
264    /// Returns `true` if the remote agent runs without the Datadog Agent.
265    pub fn is_standalone(&self) -> bool {
266        self.inner.started.config.is_standalone()
267    }
268
269    /// Returns the environment provider.
270    pub fn env_provider(&self) -> &RemoteAgentEnvironmentProvider {
271        &self.inner.env_provider
272    }
273
274    /// Returns the component registry, which the topology registers its components and memory bounds with.
275    pub fn component_registry(&self) -> &ComponentRegistry {
276        &self.inner.component_registry
277    }
278
279    /// Returns the health registry.
280    pub fn health_registry(&self) -> &HealthRegistry {
281        &self.inner.health_registry
282    }
283
284    /// Returns the configuration for connecting to the Datadog Agent, or `None` in standalone mode.
285    pub fn client_configuration(&self) -> Option<&RemoteAgentClientConfiguration> {
286        self.inner.env_provider.client_configuration()
287    }
288
289    /// Returns the Remote Configuration client, connecting to the Datadog Agent on the first call.
290    ///
291    /// The polling worker runs under the internal supervisor once the remote agent runs, so subscriptions made before
292    /// then are all included in its first poll. Binaries should only call this when they have products to subscribe
293    /// to, since connecting starts the worker polling.
294    ///
295    /// Returns `None` in standalone mode, or if Remote Configuration is turned off.
296    ///
297    /// # Errors
298    ///
299    /// If the client can't connect to the Datadog Agent, an error is returned.
300    pub async fn remote_config_client(&mut self) -> Result<Option<RemoteConfigurationClient>, GenericError> {
301        if let Some((client, _)) = &self.inner.remote_config {
302            return Ok(Some(client.clone()));
303        }
304
305        let Some(client_config) = self.inner.env_provider.client_configuration() else {
306            return Ok(None);
307        };
308        if !self.inner.started.config.remote_config_enabled() {
309            return Ok(None);
310        }
311
312        let (client, worker) = remote_config::connect(client_config).await?;
313        self.inner.remote_config = Some((client.clone(), worker));
314        Ok(Some(client))
315    }
316
317    /// Creates the supervisor for the parts of the control plane that only the facade can build.
318    ///
319    /// The supervisor is named `remote-agent`, and must be added to the binary's control plane supervisor. It serves the
320    /// supervision tree on the privileged API endpoint and, in connected mode, runs the remote agent workers from
321    /// [`RemoteAgentBootstrap`]: it serves the status, flare, and telemetry services, and reports diagnostic events to
322    /// the Datadog Agent.
323    ///
324    /// `status_sections`, `telemetry_rules`, and `extend_services` are passed to
325    /// [`RemoteAgentBootstrap::create_services_worker`]. In standalone mode, `extend_services` is not called.
326    ///
327    /// # Errors
328    ///
329    /// If the supervisor can't be created, an error is returned.
330    pub fn create_remote_agent_supervisor(
331        &self, status_sections: Vec<Arc<dyn StatusSectionProvider>>, telemetry_rules: Vec<RemapperRule>,
332        extend_services: impl FnOnce(Routes, SessionIdHandle) -> Routes,
333    ) -> Result<Supervisor, GenericError> {
334        let mut supervisor = Supervisor::new("remote-agent")?.with_restart_strategy(RestartStrategy::one_to_one());
335
336        supervisor.add_worker(self.inner.root_supervisor.tree_handle().worker());
337        if let Some(ra_bootstrap) = &self.inner.started.ra_bootstrap {
338            supervisor.add_worker(ra_bootstrap.create_dataspace_anchor());
339            supervisor.add_worker(ra_bootstrap.create_event_reporter());
340            supervisor.add_worker(ra_bootstrap.create_services_worker(
341                status_sections,
342                telemetry_rules,
343                extend_services,
344            ));
345        }
346
347        Ok(supervisor)
348    }
349
350    /// Runs the remote agent until the process receives a shutdown signal.
351    ///
352    /// See [`run_until`](Self::run_until) for the parameters.
353    ///
354    /// # Errors
355    ///
356    /// If the remote agent can't be assembled, or the supervision tree fails, an error is returned.
357    pub async fn run(self, blueprint: TopologyBlueprint, control_plane: Supervisor) -> Result<(), GenericError> {
358        self.run_until(blueprint, control_plane, wait_for_shutdown_signal())
359            .await
360    }
361
362    /// Runs the remote agent until `shutdown` resolves.
363    ///
364    /// This creates the internal supervisor around `control_plane`, validates the memory bounds, and then runs the
365    /// supervision tree with `blueprint` as the topology.
366    ///
367    /// `control_plane` is the binary's control plane supervisor, which must include the supervisor from
368    /// [`create_remote_agent_supervisor`](Self::create_remote_agent_supervisor). The memory bounds cover every
369    /// component registered with the component registry, so `blueprint` must be fully built.
370    ///
371    /// A shutdown in which some components had to be stopped forcefully, after exceeding their shutdown timeout, is
372    /// logged as a warning rather than returned as an error, since the process did stop.
373    ///
374    /// # Errors
375    ///
376    /// If the internal supervisor can't be created, the memory bounds can't be validated, or the supervision tree
377    /// fails, an error is returned.
378    pub async fn run_until<F>(
379        self, mut blueprint: TopologyBlueprint, control_plane: Supervisor, shutdown: F,
380    ) -> Result<(), GenericError>
381    where
382        F: Future<Output = ()> + Send + 'static,
383    {
384        let InitializedData {
385            started,
386            mut root_supervisor,
387            component_registry,
388            health_registry,
389            resource_registry,
390            env_provider,
391            env_supervisor,
392            remote_config,
393        } = self.inner;
394        let StartedData {
395            config,
396            ra_bootstrap,
397            config_stream_worker,
398            config_updates,
399            bootstrap_supervisor,
400            start_time,
401        } = started;
402        let full_name = saluki_metadata::get_app_details().full_name();
403
404        root_supervisor.add_worker(bootstrap_supervisor);
405
406        // Create the internal supervisor which drives the control plane and internal observability.
407        //
408        // The internal supervisor runs in ambient mode (the caller's runtime). The default restart strategy applies to
409        // its children as units.
410        let mut internal_supervisor =
411            Supervisor::new("internal-sup").error_context("Failed to create internal supervisor.")?;
412        internal_supervisor.add_worker(control_plane);
413        internal_supervisor.add_worker(resource_registry.worker());
414
415        if let Some(env_supervisor) = env_supervisor {
416            internal_supervisor.add_worker(env_supervisor);
417        }
418
419        if let Some(ra_bootstrap) = ra_bootstrap {
420            internal_supervisor.add_worker(ra_bootstrap.into_registration_worker());
421        }
422
423        if let Some(config_stream_worker) = config_stream_worker {
424            internal_supervisor.add_worker(config_stream_worker);
425        }
426
427        if let Some(config_updates) = config_updates {
428            internal_supervisor.add_worker(ConfigUpdatesWorker::new(config_updates));
429        }
430
431        // The worker shares the client's subscriptions, so dropping the client here ends none of them.
432        if let Some((_, worker)) = remote_config {
433            internal_supervisor.add_worker(remote_config::remote_config_child(worker)?);
434        }
435
436        root_supervisor.add_worker(internal_supervisor);
437
438        // Run memory bounds validation to ensure that the topology can launch within the configured memory limit, if
439        // any.
440        let memory_limiter = initialize_memory_bounds(config.memory_bounds(), component_registry.root())?;
441
442        // Configure our topology blueprint with all of the relevant registries and ambient capabilities, which
443        // ultimately get used when creating components, and sometimes exposed to them at runtime.
444        blueprint
445            .with_health_registry(health_registry.clone())
446            .with_memory_limiter(memory_limiter)
447            .with_resource_registry(resource_registry.clone())
448            .with_environment_readiness(env_provider.wait_for_ready());
449
450        // Spawn a simple task to report when the topology is healthy, which we have to do here before spawning
451        // the topology as it requires altering the blueprint state to attach itself to the ready signal.
452        spawn_topology_healthy_check(&mut blueprint, start_time);
453
454        root_supervisor.add_worker(runtime::supervisable(blueprint).needed().build());
455
456        info!("{full_name} running.");
457        match root_supervisor.run_with_shutdown(shutdown).await {
458            Ok(()) => {
459                info!("{full_name} shut down successfully.");
460                Ok(())
461            }
462            // The shutdown ran to completion, but one or more components ignored graceful shutdown and had to be
463            // forcefully aborted after exceeding the shutdown timeout. Surface that plainly instead of reporting
464            // success -- but don't treat it as a fatal error: the process did stop, and mapping it through the error
465            // path would mislabel it as a boot or setup failure.
466            Err(SupervisorError::ShutdownTimedOut { aborted }) => {
467                warn!(
468                    aborted,
469                    "{full_name} shut down uncleanly: {aborted} component(s) had to be forcefully stopped after \
470                     exceeding the shutdown timeout. Check the preceding warnings for which components were affected."
471                );
472                Ok(())
473            }
474            Err(e) => Err(e.into()),
475        }
476    }
477}
478
479fn spawn_topology_healthy_check(blueprint: &mut TopologyBlueprint, started: Instant) {
480    let topology_ready = blueprint.topology_ready();
481    tokio::spawn(async move {
482        // If the topology is torn down before it ever becomes ready (for example, shutdown during startup), `wait`
483        // returns `false` and we skip reporting readiness.
484        if topology_ready.wait().await {
485            info!(
486                topology_ready_ms = started.elapsed().as_millis(),
487                "Topology healthy. Waiting for interrupt..."
488            );
489
490            emit_startup_metrics();
491        }
492    });
493}
494
495#[cfg(test)]
496mod tests;