Skip to main content

datadog_agent_runtime/env/
mod.rs

1//! Environment providers backed by the Datadog Agent.
2//!
3//! [`RemoteAgentEnvironmentProvider`] gives a remote agent its hostname, autodiscovery events, and workload metadata.
4//! In connected mode, each of those comes from the Datadog Agent over its own connection. In standalone mode, the
5//! hostname is fixed and the rest is unavailable.
6
7use std::{future::Future, num::NonZeroUsize, path::PathBuf, time::Duration};
8
9use datadog_agent_commons::ipc::config::RemoteAgentClientConfiguration;
10use saluki_core::accounting::ComponentRegistry;
11use saluki_core::health::HealthRegistry;
12use saluki_core::runtime::Supervisor;
13use saluki_core::support::SubsystemIdentifier;
14use saluki_env::{
15    autodiscovery::providers::BoxedAutodiscoveryProvider,
16    host::providers::{BoxedHostProvider, FixedHostProvider},
17    EnvironmentProvider,
18};
19use saluki_error::GenericError;
20use tracing::warn;
21
22use crate::facade::AuthoritativeConfiguration;
23
24mod autodiscovery;
25pub use self::autodiscovery::RemoteAgentAutodiscoveryProvider;
26
27mod host;
28pub use self::host::RemoteAgentHostProvider;
29
30mod workload;
31pub use self::workload::RemoteAgentWorkloadProvider;
32
33// SAFETY: The value is demonstrably not zero.
34const DEFAULT_STRING_INTERNER_SIZE_BYTES: NonZeroUsize = NonZeroUsize::new(512 * 1024).unwrap();
35const DEFAULT_CONTAINERD_CONNECTION_TIMEOUT: Duration = Duration::from_secs(1);
36const DEFAULT_CONTAINERD_QUERY_TIMEOUT: Duration = Duration::from_secs(5);
37
38pub(crate) fn root_provider_id() -> SubsystemIdentifier {
39    SubsystemIdentifier::from_segments(["env_provider"])
40}
41
42/// Settings for the host provider.
43#[derive(Clone, Debug, Default)]
44#[non_exhaustive]
45pub struct HostSettings {
46    /// Hostname to report, if one is configured explicitly.
47    ///
48    /// Used only in standalone mode, where it's reported as-is. When it's absent or empty, the provider reports an
49    /// empty hostname and data is sent without a host, as the Datadog Agent does in sidecar deployments such as ECS
50    /// Fargate. In connected mode, the hostname comes from the Datadog Agent, which applies its own `hostname` setting,
51    /// so this is unused.
52    pub hostname: Option<String>,
53}
54
55/// Settings for the workload provider.
56#[derive(Clone, Debug)]
57#[non_exhaustive]
58pub struct WorkloadSettings {
59    /// Size, in bytes, of the string interner shared by the workload metadata collectors.
60    ///
61    /// The interner holds the entity IDs and tags received from the Datadog Agent and container runtimes. Hosts with
62    /// many containers may need to increase it. Defaults to 512 KiB.
63    pub string_interner_size_bytes: NonZeroUsize,
64
65    /// Path to the containerd gRPC socket, if one is configured explicitly.
66    ///
67    /// Defaults to `None`, which probes the well-known socket paths.
68    pub containerd_socket_path: Option<PathBuf>,
69
70    /// Timeout for establishing a containerd gRPC connection. Defaults to 1 second.
71    pub containerd_connection_timeout: Duration,
72
73    /// Per-RPC timeout for containerd API calls. Defaults to 5 seconds.
74    pub containerd_query_timeout: Duration,
75
76    /// Root of the procfs filesystem to read container processes from, if one is configured explicitly.
77    ///
78    /// Defaults to `None`, which detects the root automatically.
79    pub proc_root: Option<PathBuf>,
80
81    /// Root of the cgroupfs filesystem to read container cgroups from, if one is configured explicitly.
82    ///
83    /// Defaults to `None`, which detects the root automatically.
84    pub cgroup_root: Option<PathBuf>,
85}
86
87impl WorkloadSettings {
88    /// Creates a new `WorkloadSettings` with the given string interner size, and every other setting at its default.
89    pub fn new(string_interner_size_bytes: NonZeroUsize) -> Self {
90        Self {
91            string_interner_size_bytes,
92            ..Self::default()
93        }
94    }
95}
96
97impl Default for WorkloadSettings {
98    fn default() -> Self {
99        Self {
100            string_interner_size_bytes: DEFAULT_STRING_INTERNER_SIZE_BYTES,
101            containerd_socket_path: None,
102            containerd_connection_timeout: DEFAULT_CONTAINERD_CONNECTION_TIMEOUT,
103            containerd_query_timeout: DEFAULT_CONTAINERD_QUERY_TIMEOUT,
104            proc_root: None,
105            cgroup_root: None,
106        }
107    }
108}
109
110/// Environment provider for a remote agent.
111///
112/// This environment provider is designed for a remote agent's normal deployment environment, which is running alongside
113/// the Datadog Agent. The underlying providers communicate directly with the Datadog Agent to receive information such
114/// as the hostname, entity tags, workload metadata events, and more.
115///
116/// # Opting out for testing/benchmarking
117///
118/// In order to facilitate testing/benchmarking where running the Datadog Agent isn't desirable, the provider runs in
119/// standalone mode when the configuration is standalone.
120///
121/// This effectively disables origin enrichment (no entity tags) and causes metrics to be tagged with a fixed hostname.
122#[derive(Clone)]
123pub struct RemoteAgentEnvironmentProvider {
124    client_config: Option<RemoteAgentClientConfiguration>,
125    host_provider: BoxedHostProvider,
126    workload_provider: Option<RemoteAgentWorkloadProvider>,
127    autodiscovery_provider: Option<BoxedAutodiscoveryProvider>,
128    health_registry: HealthRegistry,
129}
130
131impl RemoteAgentEnvironmentProvider {
132    /// Creates a `RemoteAgentEnvironmentProvider` from the given configuration, along with the [`Supervisor`] that
133    /// drives the provider's background work, if it has any.
134    ///
135    /// In connected mode, the host, workload, and autodiscovery providers each open their own connection to the Datadog
136    /// Agent, and the supervisor drives them. The autodiscovery provider doesn't stream events from the Datadog Agent
137    /// until something subscribes to it. In standalone mode, the provider reports the configured hostname (empty if
138    /// none is configured), everything else is a no-op, and no supervisor is returned.
139    ///
140    /// # Errors
141    ///
142    /// If any of the underlying providers can't be created, an error is returned.
143    pub async fn from_authoritative<C>(
144        config: &C, component_registry: &ComponentRegistry, health_registry: &HealthRegistry,
145    ) -> Result<(Self, Option<Supervisor>), GenericError>
146    where
147        C: AuthoritativeConfiguration,
148    {
149        if config.is_standalone() {
150            let env = Self::standalone(&config.host(), health_registry);
151            Ok((env, None))
152        } else {
153            let client_config = config.client_configuration()?;
154            let (env, env_supervisor) =
155                Self::connected(&config.workload(), client_config, component_registry, health_registry).await?;
156            Ok((env, Some(env_supervisor)))
157        }
158    }
159
160    fn standalone(settings: &HostSettings, health_registry: &HealthRegistry) -> Self {
161        warn!("Running in standalone mode. Origin detection/enrichment and other features dependent upon the Datadog Agent will not be available.");
162
163        // An absent hostname and an empty one both mean "hostless". This matches the Datadog Agent in sidecar
164        // deployments, such as ECS Fargate, where the Agent resolves an empty hostname and sends data with no host. See
165        // `fromFargate` and `IsSidecar` in the Agent:
166        // https://github.com/DataDog/datadog-agent/blob/ecdf6b97d143dc18a922bebdec24f69058942fb4/pkg/util/hostname/common.go#L75-L82
167        // https://github.com/DataDog/datadog-agent/blob/ecdf6b97d143dc18a922bebdec24f69058942fb4/pkg/util/fargate/detection.go#L15-L29
168        let hostname = settings.hostname.clone().unwrap_or_default();
169
170        Self {
171            client_config: None,
172            host_provider: BoxedHostProvider::from_provider(FixedHostProvider::new(hostname)),
173            workload_provider: None,
174            autodiscovery_provider: None,
175            health_registry: health_registry.clone(),
176        }
177    }
178
179    async fn connected(
180        settings: &WorkloadSettings, client_config: RemoteAgentClientConfiguration,
181        component_registry: &ComponentRegistry, health_registry: &HealthRegistry,
182    ) -> Result<(Self, Supervisor), GenericError> {
183        let mut env_supervisor = Supervisor::new("env-provider")?;
184
185        let host_provider = RemoteAgentHostProvider::new(&client_config, component_registry).await?;
186
187        let (workload_provider, workload_supervisor) =
188            RemoteAgentWorkloadProvider::new(settings, &client_config, component_registry, health_registry).await?;
189        env_supervisor.add_worker(workload_supervisor);
190
191        let (autodiscovery_provider, autodiscovery_supervisor) =
192            RemoteAgentAutodiscoveryProvider::new(&client_config).await?;
193        env_supervisor.add_worker(autodiscovery_supervisor);
194
195        let env = Self {
196            client_config: Some(client_config),
197            host_provider: BoxedHostProvider::from_provider(host_provider),
198            workload_provider: Some(workload_provider),
199            autodiscovery_provider: Some(BoxedAutodiscoveryProvider::from_provider(autodiscovery_provider)),
200            health_registry: health_registry.clone(),
201        };
202
203        Ok((env, env_supervisor))
204    }
205
206    /// Returns the configuration for connecting to the Datadog Agent, or `None` in standalone mode.
207    pub fn client_configuration(&self) -> Option<&RemoteAgentClientConfiguration> {
208        self.client_config.as_ref()
209    }
210
211    /// Returns a future that resolves once the environment provider's background subsystems are ready.
212    ///
213    /// Specifically, this waits for the workload provider's metadata aggregator and collectors to become ready, which
214    /// ensures that origin detection and entity tagging are operational before the caller begins processing data. In
215    /// standalone mode -- where there is no workload provider -- the returned future resolves immediately.
216    pub fn wait_for_ready(&self) -> impl Future<Output = ()> + Send + 'static {
217        let health_registry = self.health_registry.clone();
218        let has_workload_provider = self.workload_provider.is_some();
219        async move {
220            if has_workload_provider {
221                health_registry.all_ready_under(root_provider_id()).await;
222            }
223        }
224    }
225}
226
227impl EnvironmentProvider for RemoteAgentEnvironmentProvider {
228    type Host = BoxedHostProvider;
229    type Workload = Option<RemoteAgentWorkloadProvider>;
230    type AutodiscoveryProvider = Option<BoxedAutodiscoveryProvider>;
231
232    fn host(&self) -> &Self::Host {
233        &self.host_provider
234    }
235
236    fn workload(&self) -> &Self::Workload {
237        &self.workload_provider
238    }
239
240    fn autodiscovery(&self) -> &Self::AutodiscoveryProvider {
241        &self.autodiscovery_provider
242    }
243}
244
245#[cfg(test)]
246mod tests {
247    use saluki_env::HostProvider as _;
248
249    use super::*;
250
251    async fn standalone_hostname(hostname: Option<&str>) -> String {
252        let settings = HostSettings {
253            hostname: hostname.map(String::from),
254        };
255        let env = RemoteAgentEnvironmentProvider::standalone(&settings, &HealthRegistry::new());
256        assert!(env.client_configuration().is_none());
257        env.host().get_hostname().await.unwrap()
258    }
259
260    #[tokio::test]
261    async fn standalone_reports_the_configured_hostname() {
262        assert_eq!(standalone_hostname(Some("standalone-host")).await, "standalone-host");
263    }
264
265    #[tokio::test]
266    async fn standalone_without_a_hostname_is_hostless() {
267        assert_eq!(standalone_hostname(None).await, "");
268    }
269
270    #[tokio::test]
271    async fn standalone_with_an_empty_hostname_is_hostless() {
272        assert_eq!(standalone_hostname(Some("")).await, "");
273    }
274}