Skip to main content

datadog_agent_runtime/env/
autodiscovery.rs

1use std::sync::Arc;
2use std::time::Duration;
3
4use async_trait::async_trait;
5use datadog_agent_commons::ipc::{
6    client::{RemoteAgentClient, StreamingResponse},
7    config::RemoteAgentClientConfiguration,
8};
9use datadog_protos::agent::AutodiscoveryStreamResponse;
10use futures::{Stream, StreamExt};
11use saluki_common::sync::shutdown::ShutdownHandle;
12use saluki_core::runtime::{InitializationError, Supervisable, Supervisor, SupervisorFuture};
13use saluki_env::autodiscovery::AutodiscoveryEvent;
14use saluki_env::AutodiscoveryProvider;
15use saluki_error::GenericError;
16use tokio::select;
17use tokio::sync::mpsc::{self, Receiver, Sender};
18use tokio::sync::{Mutex, Notify};
19use tokio::time::sleep;
20use tonic::Status;
21use tracing::{debug, warn};
22
23/// Datadog Agent-based autodiscovery provider.
24///
25/// This provider is based primarily on the remote autodiscovery API exposed by the Datadog Agent, which handles the
26/// bulk of the work by detecting changes to underlying environment (such as containers starting and stopping), and
27/// determining if they have services associated with them that require checks to be run against them. The remote
28/// autodiscovery API operates in a streaming fashion, which the provider uses to then broadcast updates to subscribers.
29///
30/// # Subscribers
31///
32/// Each autodiscovery stream starts with a snapshot of the configurations that the Datadog Agent has already
33/// scheduled, followed by changes as they happen. The provider doesn't open the stream until the first subscriber
34/// exists, so that subscriber receives the snapshot. If nothing ever subscribes, the stream is never opened.
35///
36/// Once the stream is open, it stays open even if every subscriber goes away. A subscriber that arrives after that
37/// only receives the events that follow, and misses the snapshot. After a reconnect, the new stream starts with the
38/// snapshot again, so subscribers that already received it receive it again.
39#[derive(Clone)]
40pub struct RemoteAgentAutodiscoveryProvider {
41    subscribers: Arc<AutodiscoverySubscribers>,
42}
43
44impl RemoteAgentAutodiscoveryProvider {
45    /// Creates a new `RemoteAgentAutodiscoveryProvider` based on the given configuration, along with a [`Supervisor`] that
46    /// drives the collection and broadcasting of autodiscovery events.
47    ///
48    /// # Errors
49    ///
50    /// If the remote agent client couldn't be created, an error is returned.
51    pub async fn new(client_config: &RemoteAgentClientConfiguration) -> Result<(Self, Supervisor), GenericError> {
52        let client = RemoteAgentClient::connect(client_config).await?;
53        Self::from_source(client)
54    }
55
56    fn from_source<S: AutodiscoveryStreamSource>(source: S) -> Result<(Self, Supervisor), GenericError> {
57        let subscribers = Arc::new(AutodiscoverySubscribers::default());
58
59        let provider = Self {
60            subscribers: Arc::clone(&subscribers),
61        };
62
63        let mut supervisor = Supervisor::new("autodiscovery")?;
64        supervisor.add_worker(AutodiscoveryEventBroadcaster { source, subscribers });
65
66        Ok((provider, supervisor))
67    }
68}
69
70#[async_trait]
71impl AutodiscoveryProvider for RemoteAgentAutodiscoveryProvider {
72    async fn subscribe(&self) -> Option<Receiver<AutodiscoveryEvent>> {
73        let (sender, receiver) = mpsc::channel::<AutodiscoveryEvent>(16);
74        self.subscribers.add(sender).await;
75        Some(receiver)
76    }
77}
78
79#[derive(Default)]
80struct AutodiscoverySubscribers {
81    senders: Mutex<Vec<Sender<AutodiscoveryEvent>>>,
82    added: Notify,
83}
84
85impl AutodiscoverySubscribers {
86    async fn add(&self, sender: Sender<AutodiscoveryEvent>) {
87        self.senders.lock().await.push(sender);
88        self.added.notify_one();
89    }
90
91    async fn wait_for_first(&self) {
92        // `notify_one` keeps a permit when nothing is waiting, so a subscriber added after the check isn't missed.
93        while self.senders.lock().await.is_empty() {
94            self.added.notified().await;
95        }
96    }
97
98    async fn send(&self, event: AutodiscoveryEvent) {
99        let mut senders = self.senders.lock().await;
100        let mut active_senders = Vec::with_capacity(senders.len());
101
102        for sender in senders.drain(..) {
103            if sender.send(event.clone()).await.is_ok() {
104                active_senders.push(sender);
105            }
106        }
107
108        *senders = active_senders;
109    }
110}
111
112/// Opens autodiscovery streams, so that tests can stand in for the Datadog Agent.
113trait AutodiscoveryStreamSource: Clone + Send + Sync + 'static {
114    type Stream: Stream<Item = Result<AutodiscoveryStreamResponse, Status>> + Send + Unpin;
115
116    fn open_stream(&mut self) -> Self::Stream;
117}
118
119impl AutodiscoveryStreamSource for RemoteAgentClient {
120    type Stream = StreamingResponse<AutodiscoveryStreamResponse>;
121
122    fn open_stream(&mut self) -> Self::Stream {
123        self.get_autodiscovery_stream()
124    }
125}
126
127struct AutodiscoveryEventBroadcaster<S> {
128    source: S,
129    subscribers: Arc<AutodiscoverySubscribers>,
130}
131
132#[async_trait]
133impl<S: AutodiscoveryStreamSource> Supervisable for AutodiscoveryEventBroadcaster<S> {
134    fn name(&self) -> &str {
135        "ad-event-broadcaster"
136    }
137
138    async fn initialize(&self, process_shutdown: ShutdownHandle) -> Result<SupervisorFuture, InitializationError> {
139        let source = self.source.clone();
140        let subscribers = Arc::clone(&self.subscribers);
141
142        Ok(Box::pin(async move {
143            select! {
144                _ = process_shutdown => {},
145                _ = run_ad_event_broadcaster(source, subscribers) => {},
146            }
147            Ok(())
148        }))
149    }
150}
151
152async fn run_ad_event_broadcaster<S: AutodiscoveryStreamSource>(
153    mut source: S, subscribers: Arc<AutodiscoverySubscribers>,
154) {
155    debug!("Waiting for the first autodiscovery subscriber.");
156    subscribers.wait_for_first().await;
157
158    debug!("Listening to autodiscovery events from remote agent.");
159
160    loop {
161        let mut autodiscovery_stream = source.open_stream();
162
163        debug!("Polling autodiscovery event stream.");
164
165        while let Some(result) = autodiscovery_stream.next().await {
166            match result {
167                Ok(response) => {
168                    for proto_config in response.configs {
169                        let event = AutodiscoveryEvent::from(proto_config);
170                        subscribers.send(event).await;
171                    }
172                }
173                Err(status) => {
174                    warn!(
175                        ?status,
176                        "Encountered error while listening for autodiscovery events. Retrying in 1 second...",
177                    );
178                    sleep(Duration::from_secs(1)).await;
179                    break;
180                }
181            }
182        }
183
184        debug!("Autodiscovery event stream ended. Reconnecting...");
185    }
186}
187
188#[cfg(test)]
189mod tests {
190    use std::sync::atomic::{AtomicUsize, Ordering};
191
192    use datadog_protos::agent::Config as ProtoConfig;
193    use futures::stream::{self, BoxStream};
194    use saluki_core::runtime::test_util::TestSupervisor;
195    use tokio::sync::broadcast;
196    use tokio::time::timeout;
197
198    use super::*;
199
200    /// Stands in for the Datadog Agent: each stream yields the snapshot, then the updates pushed while it's open.
201    #[derive(Clone)]
202    struct FakeAgent {
203        snapshot: Vec<&'static str>,
204        opens: Arc<AtomicUsize>,
205        // `None` ends the open stream.
206        updates: broadcast::Sender<Option<&'static str>>,
207    }
208
209    impl FakeAgent {
210        fn new(snapshot: &[&'static str]) -> Self {
211            Self {
212                snapshot: snapshot.to_vec(),
213                opens: Arc::new(AtomicUsize::new(0)),
214                updates: broadcast::channel(16).0,
215            }
216        }
217
218        fn opens(&self) -> usize {
219            self.opens.load(Ordering::SeqCst)
220        }
221
222        fn push_update(&self, name: &'static str) {
223            self.updates.send(Some(name)).expect("no open stream");
224        }
225
226        fn end_stream(&self) {
227            self.updates.send(None).expect("no open stream");
228        }
229    }
230
231    fn response(names: &[&'static str]) -> AutodiscoveryStreamResponse {
232        let configs = names
233            .iter()
234            .map(|name| ProtoConfig {
235                name: name.to_string(),
236                ..Default::default()
237            })
238            .collect();
239        AutodiscoveryStreamResponse { configs }
240    }
241
242    impl AutodiscoveryStreamSource for FakeAgent {
243        type Stream = BoxStream<'static, Result<AutodiscoveryStreamResponse, Status>>;
244
245        fn open_stream(&mut self) -> Self::Stream {
246            self.opens.fetch_add(1, Ordering::SeqCst);
247            let updates = stream::unfold(self.updates.subscribe(), |mut updates| async move {
248                match updates.recv().await {
249                    Ok(Some(name)) => Some((Ok(response(&[name])), updates)),
250                    _ => None,
251                }
252            });
253            stream::iter([Ok(response(&self.snapshot))]).chain(updates).boxed()
254        }
255    }
256
257    async fn start(agent: &FakeAgent) -> (RemoteAgentAutodiscoveryProvider, TestSupervisor) {
258        let (provider, supervisor) = RemoteAgentAutodiscoveryProvider::from_source(agent.clone()).unwrap();
259        let supervisor = TestSupervisor::start_with("test-root", |root| root.add_worker(supervisor)).await;
260        (provider, supervisor)
261    }
262
263    async fn next_scheduled_config(events: &mut Receiver<AutodiscoveryEvent>) -> String {
264        let event = timeout(Duration::from_secs(5), events.recv())
265            .await
266            .expect("timed out waiting for an autodiscovery event")
267            .expect("broadcaster dropped the subscriber");
268        match event {
269            AutodiscoveryEvent::Schedule { config } => config.name.to_string(),
270            other => panic!("expected a schedule event, got {other:?}"),
271        }
272    }
273
274    // Regression test: the broadcaster used to open the stream as soon as its worker started, and dropped the snapshot
275    // while nothing had subscribed. It now waits for the first subscriber before opening the stream.
276    #[tokio::test(start_paused = true)]
277    async fn subscriber_after_worker_start_receives_initial_snapshot() {
278        let agent = FakeAgent::new(&["redis", "nginx"]);
279        let (provider, supervisor) = start(&agent).await;
280
281        // Let the worker start and settle before anything subscribes.
282        sleep(Duration::from_secs(1)).await;
283
284        let mut events = provider.subscribe().await.expect("provider should be configured");
285        assert_eq!(next_scheduled_config(&mut events).await, "redis");
286        assert_eq!(next_scheduled_config(&mut events).await, "nginx");
287        assert_eq!(agent.opens(), 1);
288
289        supervisor.shutdown().await.unwrap();
290    }
291
292    #[tokio::test(start_paused = true)]
293    async fn shutdown_while_waiting_for_first_subscriber_is_clean() {
294        let agent = FakeAgent::new(&["redis"]);
295        let (_provider, supervisor) = start(&agent).await;
296
297        sleep(Duration::from_secs(1)).await;
298        assert_eq!(agent.opens(), 0, "stream opened before anything subscribed");
299
300        supervisor.shutdown().await.unwrap();
301    }
302
303    #[tokio::test(start_paused = true)]
304    async fn subscriber_after_stream_opens_misses_snapshot() {
305        let agent = FakeAgent::new(&["redis"]);
306        let (provider, supervisor) = start(&agent).await;
307
308        let mut first = provider.subscribe().await.expect("provider should be configured");
309        assert_eq!(next_scheduled_config(&mut first).await, "redis");
310
311        let mut late = provider.subscribe().await.expect("provider should be configured");
312        agent.push_update("nginx");
313        assert_eq!(next_scheduled_config(&mut first).await, "nginx");
314        assert_eq!(next_scheduled_config(&mut late).await, "nginx");
315        assert_eq!(agent.opens(), 1);
316
317        supervisor.shutdown().await.unwrap();
318    }
319
320    #[tokio::test(start_paused = true)]
321    async fn reconnect_delivers_snapshot_again() {
322        let agent = FakeAgent::new(&["redis"]);
323        let (provider, supervisor) = start(&agent).await;
324
325        let mut events = provider.subscribe().await.expect("provider should be configured");
326        assert_eq!(next_scheduled_config(&mut events).await, "redis");
327
328        agent.end_stream();
329        assert_eq!(next_scheduled_config(&mut events).await, "redis");
330        assert_eq!(agent.opens(), 2);
331
332        supervisor.shutdown().await.unwrap();
333    }
334}