Skip to main content

datadog_agent_commons/ipc/client/
mod.rs

1//! Helpers for interacting with the Datadog Agent.
2
3use std::time::Duration;
4
5use backon::{ConstantBuilder, Retryable as _};
6use datadog_protos::agent::v1::{
7    RefreshRemoteAgentRequest, RegisterRemoteAgentRequest, RegisterRemoteAgentResponse, ReportRemoteAgentEventRequest,
8    ReportRemoteAgentEventResponse,
9};
10use datadog_protos::agent::{
11    AgentClient, AgentSecureClient, AutodiscoveryStreamResponse, ConfigEvent, ConfigStreamRequest, EntityId,
12    FetchEntityRequest, HostTagReply, HostTagRequest, HostnameRequest, RemoteAgentClient as RemoteAgentServiceClient,
13    StreamTagsRequest, StreamTagsResponse, TagCardinality, WorkloadmetaEventType, WorkloadmetaFilter, WorkloadmetaKind,
14    WorkloadmetaSource, WorkloadmetaStreamRequest, WorkloadmetaStreamResponse,
15};
16use datadog_protos::remote_config::{ClientGetConfigsRequest, ClientGetConfigsResponse};
17use saluki_error::{generic_error, ErrorContext as _, GenericError};
18use saluki_io::net::client::http::HttpsCapableConnectorBuilder;
19use saluki_metadata::AppDetails;
20use tonic::{
21    service::interceptor::InterceptedService,
22    transport::{Channel, Endpoint},
23    Code, Request, Response, Status,
24};
25use tracing::warn;
26
27use crate::ipc::{config::RemoteAgentClientConfiguration, session::SessionId, tls::build_ipc_client_ipc_tls_config};
28
29mod agent_version;
30pub use self::agent_version::{fetch_agent_version, RunningAgentVersion};
31
32mod bearer_auth;
33use self::bearer_auth::BearerAuthInterceptor;
34
35mod streaming;
36pub use self::streaming::StreamingResponse;
37
38const CONNECT_RETRY_ATTEMPTS: usize = 10;
39const CONNECT_RETRY_BACKOFF: Duration = Duration::from_secs(2);
40
41/// Formats an application name for the Agent's configuration-update stream and Remote Configuration requests.
42///
43/// Converts the full name to lowercase and replaces spaces and underscores with hyphens.
44pub fn client_name(app_details: &AppDetails) -> String {
45    app_details
46        .full_name()
47        .replace(" ", "-")
48        .replace("_", "-")
49        .to_lowercase()
50}
51
52/// A client for interacting with the Datadog Agent's internal gRPC-based API.
53#[derive(Clone)]
54pub struct RemoteAgentClient {
55    client: AgentClient<InterceptedService<Channel, BearerAuthInterceptor>>,
56    secure_client: AgentSecureClient<InterceptedService<Channel, BearerAuthInterceptor>>,
57    remote_agent_client: RemoteAgentServiceClient<InterceptedService<Channel, BearerAuthInterceptor>>,
58}
59
60impl RemoteAgentClient {
61    /// Connects to the Core Agent's gRPC IPC endpoint using the given client configuration.
62    ///
63    /// # Errors
64    ///
65    /// If the connection can't be established, the authentication token or IPC certificate can't be read, or the
66    /// initial health-check RPC fails, an error will be returned. Each of these is retried first.
67    pub async fn connect(config: &RemoteAgentClientConfiguration) -> Result<Self, GenericError> {
68        // TODO: We need to write a Tower middleware service that allows applying a backoff between failed calls,
69        // specifically so that we can throttle reconnection attempts.
70        //
71        // When the remote Agent endpoint is not available -- Agent isn't running, etc -- the gRPC client will
72        // essentially freewheel, trying to reconnect as quickly as possible, which spams the logs, wastes resources, so
73        // on and so forth. We would want to essentially apply a backoff like any other client would for the RPC calls
74        // themselves, but use it with the _connector_ instead.
75        //
76        // We could potentially just use a retry middleware, but Tonic does have its own reconnection logic, so we'd
77        // have to test it out to make sure it behaves sensibly.
78        let service_builder = || async {
79            let auth_interceptor = BearerAuthInterceptor::from_file(config.auth.auth_token_file_path()).await?;
80            let ipc_cert_file_path = config.auth.ipc_cert_file_path();
81            let client_tls_config = build_ipc_client_ipc_tls_config(ipc_cert_file_path).await?;
82            let connector_builder = HttpsCapableConnectorBuilder::default();
83            #[cfg(target_os = "linux")]
84            let connector_builder = if let Some(addr) = config.vsock_addr() {
85                connector_builder.with_vsock_addr(addr)
86            } else {
87                connector_builder
88            };
89            let https_connector = connector_builder.build(client_tls_config)?;
90            let endpoint = config.endpoint();
91            let channel = Endpoint::from(endpoint.clone())
92                .connect_timeout(Duration::from_secs(2))
93                .connect_with_connector(https_connector)
94                .await
95                .with_error_context(|| format!("Failed to connect to Datadog Agent API at '{}'.", endpoint))?;
96
97            let service = InterceptedService::new(channel, auth_interceptor);
98
99            // Health check inside the retried region. A transient partition can let the TCP connect succeed but break
100            // this first RPC stream, so retrying here keeps a boot-time blip from failing client construction.
101            let mut secure_client =
102                AgentSecureClient::new(service.clone()).max_decoding_message_size(config.grpc_max_message_size);
103            try_query_agent_api(&mut secure_client).await?;
104
105            Ok::<_, GenericError>(service)
106        };
107
108        let service = service_builder
109            .retry(
110                ConstantBuilder::default()
111                    .with_delay(CONNECT_RETRY_BACKOFF)
112                    .with_max_times(CONNECT_RETRY_ATTEMPTS),
113            )
114            .notify(|e, delay| {
115                warn!(error = %e, "Failed to create Datadog Agent API client. Retrying in {:?}...", delay);
116            })
117            .await
118            .error_context("Failed to create Datadog Agent API client.")?;
119
120        let client = AgentClient::new(service.clone()).max_decoding_message_size(config.grpc_max_message_size);
121        let secure_client =
122            AgentSecureClient::new(service.clone()).max_decoding_message_size(config.grpc_max_message_size);
123        let remote_agent_client =
124            RemoteAgentServiceClient::new(service).max_decoding_message_size(config.grpc_max_message_size);
125
126        Ok(Self {
127            client,
128            secure_client,
129            remote_agent_client,
130        })
131    }
132
133    /// Gets the detected hostname from the Agent.
134    ///
135    /// # Errors
136    ///
137    /// If there is an error querying the Agent API, an error will be returned.
138    pub async fn get_hostname(&mut self) -> Result<String, GenericError> {
139        let response = self
140            .client
141            .get_hostname(HostnameRequest {})
142            .await
143            .map(|r| r.into_inner())?;
144
145        Ok(response.hostname)
146    }
147
148    /// Gets a stream of tagger entities at the given cardinality, optionally limited to a set of entity ID prefixes.
149    ///
150    /// When `prefixes` is given, the server only sends events for entities whose ID carries one of those prefixes,
151    /// which avoids paying the serialization and bandwidth cost of entities that the caller has no use for. Passing
152    /// `None` applies no filtering, and the server sends events for every prefix it knows about.
153    ///
154    /// If there is an error with the initial request, or an error occurs while streaming, the next message in the
155    /// stream will be `Some(Err(status))`, where the status indicates the underlying error.
156    pub fn get_tagger_stream(
157        &mut self, cardinality: TagCardinality, prefixes: Option<Vec<String>>,
158    ) -> StreamingResponse<StreamTagsResponse> {
159        let mut client = self.secure_client.clone();
160        StreamingResponse::from_response_future(async move {
161            client
162                .tagger_stream_entities(StreamTagsRequest {
163                    cardinality: cardinality.into(),
164                    prefixes: prefixes.unwrap_or_default(),
165                    ..Default::default()
166                })
167                .await
168        })
169    }
170
171    /// Gets a stream of all workloadmeta entities.
172    ///
173    /// If there is an error with the initial request, or an error occurs while streaming, the next message in the
174    /// stream will be `Some(Err(status))`, where the status indicates the underlying error.
175    pub fn get_workloadmeta_stream(&mut self) -> StreamingResponse<WorkloadmetaStreamResponse> {
176        let mut client = self.secure_client.clone();
177        StreamingResponse::from_response_future(async move {
178            client
179                .workloadmeta_stream_entities(WorkloadmetaStreamRequest {
180                    filter: Some(WorkloadmetaFilter {
181                        kinds: vec![
182                            WorkloadmetaKind::Container.into(),
183                            WorkloadmetaKind::KubernetesPod.into(),
184                            WorkloadmetaKind::EcsTask.into(),
185                        ],
186                        source: WorkloadmetaSource::All.into(),
187                        event_type: WorkloadmetaEventType::EventTypeAll.into(),
188                    }),
189                })
190                .await
191        })
192    }
193
194    /// Registers a Remote Agent with the Agent.
195    ///
196    /// `pid` is the OS process ID. `process_instance_id` identifies the process lifetime across RAR sessions, so a
197    /// restarted process must send a new ID even if it has the same PID.
198    ///
199    /// # Errors
200    ///
201    /// If there is an error sending the request to the Agent API, an error will be returned.
202    pub async fn register_remote_agent(
203        &mut self, pid: u32, process_instance_id: &str, display_name: &str, flavor: &str, api_endpoint: &str,
204        services: Vec<String>,
205    ) -> Result<Response<RegisterRemoteAgentResponse>, GenericError> {
206        let mut client = self.remote_agent_client.clone();
207        let response = client
208            .register_remote_agent(RegisterRemoteAgentRequest {
209                pid: pid.to_string(),
210                process_instance_id: process_instance_id.to_string(),
211                flavor: flavor.to_string(),
212                display_name: display_name.to_string(),
213                api_endpoint_uri: api_endpoint.to_string(),
214                services,
215            })
216            .await?;
217        Ok(response)
218    }
219
220    /// Refreshes the given remote agent session with the Agent.
221    ///
222    /// # Errors
223    ///
224    /// If there is an error sending the request to the Agent API, an error will be returned.
225    pub async fn refresh_remote_agent(&mut self, session_id: &SessionId) -> Result<Response<()>, GenericError> {
226        let mut client = self.remote_agent_client.clone();
227        let response = client
228            .refresh_remote_agent(RefreshRemoteAgentRequest {
229                session_id: session_id.to_string(),
230            })
231            .await?
232            .map(|_| ());
233        Ok(response)
234    }
235
236    /// Reports one or more operational events for a remote agent session to the Agent.
237    ///
238    /// # Errors
239    ///
240    /// If there is an error sending the request to the Agent API, an error will be returned.
241    pub async fn report_remote_agent_event(
242        &mut self, request: ReportRemoteAgentEventRequest,
243    ) -> Result<Response<ReportRemoteAgentEventResponse>, GenericError> {
244        let mut client = self.remote_agent_client.clone();
245        let response = client.report_remote_agent_event(request).await?;
246        Ok(response)
247    }
248
249    /// Gets the host tags from the Agent.
250    ///
251    /// # Errors
252    ///
253    /// If there is an error querying the Agent API, an error will be returned.
254    pub async fn get_host_tags(&self) -> Result<Response<HostTagReply>, GenericError> {
255        let mut client = self.secure_client.clone();
256        let response = client.get_host_tags(HostTagRequest {}).await?;
257        Ok(response)
258    }
259
260    /// Polls the Agent for the Remote Configuration assigned to a client.
261    ///
262    /// # Errors
263    ///
264    /// Returns the gRPC status unchanged, so that callers can distinguish `Unimplemented`, which the Agent returns when
265    /// Remote Configuration is disabled, from other failures.
266    pub async fn client_get_configs(
267        &self, request: ClientGetConfigsRequest,
268    ) -> Result<ClientGetConfigsResponse, Status> {
269        let mut client = self.secure_client.clone();
270        let response = client.client_get_configs(request).await?;
271        Ok(response.into_inner())
272    }
273
274    /// Gets a stream of autodiscovery config updates.
275    ///
276    /// If there is an error with the initial request, or an error occurs while streaming, the next message in the
277    /// stream will be `Some(Err(status))`, where the status indicates the underlying error.
278    pub fn get_autodiscovery_stream(&mut self) -> StreamingResponse<AutodiscoveryStreamResponse> {
279        let mut client = self.secure_client.clone();
280        StreamingResponse::from_response_future(async move { client.autodiscovery_stream_config(()).await })
281    }
282
283    /// Gets a stream of config events.
284    ///
285    /// If there is an error with the initial request, or an error occurs while streaming, the next message in the
286    /// stream will be `Some(Err(status))`, where the status indicates the underlying error.
287    pub fn stream_config_events(&mut self, session_id: &SessionId) -> StreamingResponse<ConfigEvent> {
288        let mut client = self.secure_client.clone();
289        let mut request = Request::new(ConfigStreamRequest {
290            name: client_name(saluki_metadata::get_app_details()),
291        });
292
293        request
294            .metadata_mut()
295            .insert("session_id", session_id.to_grpc_header_value());
296
297        StreamingResponse::from_response_future(async move { client.stream_config_events(request).await })
298    }
299}
300
301async fn try_query_agent_api(
302    client: &mut AgentSecureClient<InterceptedService<Channel, BearerAuthInterceptor>>,
303) -> Result<(), GenericError> {
304    let noop_fetch_request = FetchEntityRequest {
305        id: Some(EntityId {
306            prefix: "container_id".to_string(),
307            uid: "nonexistent".to_string(),
308        }),
309        cardinality: TagCardinality::High.into(),
310    };
311    match client.tagger_fetch_entity(noop_fetch_request).await {
312        Ok(_) => Ok(()),
313        Err(e) => match e.code() {
314            Code::Unauthenticated => Err(generic_error!(
315                "Failed to authenticate to Datadog Agent API. Check that the configured authentication token is correct."
316            )),
317            _ => Err(e.into()),
318        },
319    }
320}
321
322#[cfg(test)]
323mod tests {
324    use saluki_metadata::{AppDetails, Version};
325
326    use super::client_name;
327
328    #[test]
329    fn client_name_is_the_lowercased_hyphenated_full_name() {
330        let details = AppDetails::new("Agent Data_Plane", "data-plane", "adp", Version::new("1.0.0", 1, 0, 0));
331        assert_eq!(client_name(&details), "agent-data-plane");
332    }
333}