Skip to main content

saluki_env/autodiscovery/providers/
local.rs

1use std::collections::BTreeMap;
2use std::collections::HashSet;
3use std::path::{Path, PathBuf};
4use std::sync::Arc;
5
6use async_trait::async_trait;
7use saluki_error::GenericError;
8use serde::{Deserialize, Deserializer};
9use stringtheory::MetaString;
10use tokio::fs;
11use tokio::sync::mpsc::{self, Receiver, Sender};
12use tokio::sync::{Mutex, OnceCell};
13use tokio::time::{interval, Duration};
14use tracing::{debug, info, warn};
15
16use crate::autodiscovery::{AutodiscoveryEvent, AutodiscoveryProvider, CheckConfig, Config, Data};
17
18const BG_MONITOR_INTERVAL: u64 = 30;
19
20type AutodiscoverySubscribers = Arc<Mutex<Vec<Sender<AutodiscoveryEvent>>>>;
21
22/// A local auto-discovery provider that uses the file system.
23pub struct LocalAutodiscoveryProvider {
24    search_paths: Vec<PathBuf>,
25    subscribers: AutodiscoverySubscribers,
26    listener_init: OnceCell<()>,
27}
28
29impl LocalAutodiscoveryProvider {
30    /// Creates a new `LocalAutodiscoveryProvider` that will monitor the specified paths.
31    pub fn new<P: AsRef<Path>>(paths: Vec<P>) -> Self {
32        let search_paths: Vec<PathBuf> = paths
33            .iter()
34            .filter_map(|p| {
35                if !p.as_ref().exists() {
36                    warn!("Skipping path '{}' as it does not exist", p.as_ref().display());
37                    return None;
38                }
39                if !p.as_ref().is_dir() {
40                    warn!("Skipping path '{}', it is not a directory.", p.as_ref().display());
41                    return None;
42                }
43                Some(p.as_ref().to_path_buf())
44            })
45            .collect();
46
47        Self {
48            search_paths,
49            subscribers: Arc::new(Mutex::new(Vec::new())),
50            listener_init: OnceCell::new(),
51        }
52    }
53
54    /// Starts a background task that periodically scans for configuration changes
55    async fn start_background_monitor(&self, interval_sec: u64) {
56        let mut interval = interval(Duration::from_secs(interval_sec));
57        let subscribers = self.subscribers.clone();
58        let search_paths = self.search_paths.clone();
59
60        info!(
61            "Scanning for local autodiscovery events every {} seconds.",
62            interval_sec
63        );
64
65        tokio::spawn(async move {
66            let mut known_configs = HashSet::new();
67            let mut configs = BTreeMap::new();
68            loop {
69                interval.tick().await;
70
71                // Scan for configurations and emit events for changes
72                if let Err(e) =
73                    scan_and_emit_events(&search_paths, &mut known_configs, &subscribers, &mut configs).await
74                {
75                    warn!("Error scanning for configurations: {}", e);
76                }
77            }
78        });
79    }
80}
81
82#[derive(Debug, Deserialize)]
83struct LocalCheckConfig {
84    #[serde(default, deserialize_with = "null_as_default")]
85    init_config: BTreeMap<String, serde_json::Value>,
86    #[serde(deserialize_with = "null_as_default")]
87    instances: Vec<Option<BTreeMap<String, serde_json::Value>>>,
88}
89
90/// Deserializes YAML null as the default value.
91///
92/// Check configurations commonly leave a value blank, as in `init_config:` or a bare `-` instance, and the Agent reads
93/// those as empty. serde-saphyr rejects null for maps and sequences, so they're read as `Option` instead.
94fn null_as_default<'de, D, T>(deserializer: D) -> Result<T, D::Error>
95where
96    D: Deserializer<'de>,
97    T: Deserialize<'de> + Default,
98{
99    Ok(Option::<T>::deserialize(deserializer)?.unwrap_or_default())
100}
101
102/// Parse a YAML file into a Config object.
103async fn parse_config_file(path: &PathBuf, check_name: &str) -> Result<(String, CheckConfig), GenericError> {
104    let content = fs::read_to_string(path).await?;
105
106    let check_config: LocalCheckConfig = match crate::autodiscovery::yaml_from_str(&content) {
107        Ok(read) => read,
108        Err(e) => {
109            return Err(GenericError::from(e).context("Failed to decode yaml as check configuration."));
110        }
111    };
112
113    let canonicalized_path = fs::canonicalize(&path).await?;
114
115    // Build config ID from the file path
116    let config_id = canonicalized_path.to_string_lossy().replace(['/', '\\'], "_");
117
118    let instances: Vec<Data> = check_config
119        .instances
120        .into_iter()
121        .map(|instance| {
122            let mut result = BTreeMap::new();
123            for (key, value) in instance.unwrap_or_default() {
124                result.insert(key.into(), value);
125            }
126            Data { value: result }
127        })
128        .collect();
129
130    let init_config = {
131        let mut result = BTreeMap::new();
132        for (key, value) in check_config.init_config {
133            result.insert(key.into(), value);
134        }
135        Data { value: result }
136    };
137
138    // Create a Config
139    let config = Config {
140        name: MetaString::from(check_name),
141        init_config,
142        instances,
143        metric_config: Data::default(),
144        logs_config: Data::default(),
145        ad_identifiers: Vec::new(),
146        provider: MetaString::empty(),
147        service_id: MetaString::empty(),
148        tagger_entity: MetaString::empty(),
149        cluster_check: false,
150        node_name: MetaString::empty(),
151        source: MetaString::from_static("local"),
152        ignore_autodiscovery_tags: false,
153        metrics_excluded: false,
154        logs_excluded: false,
155        advanced_ad_identifiers: Vec::new(),
156    };
157
158    let check_config = CheckConfig::from(config);
159
160    Ok((config_id, check_config))
161}
162
163/// Process a single YAML config file and record it in the tracking structures, emitting events as
164/// needed.
165async fn process_yaml_file(
166    path: PathBuf, check_name: &str, found_configs: &mut HashSet<String>, known_configs: &mut HashSet<String>,
167    subscribers: &AutodiscoverySubscribers, configs: &mut BTreeMap<String, CheckConfig>,
168) {
169    match parse_config_file(&path, check_name).await {
170        Ok((config_id, config)) => {
171            found_configs.insert(config_id.clone());
172
173            if !known_configs.contains(&config_id) {
174                debug!("New configuration found: {}", config_id);
175                let event = AutodiscoveryEvent::CheckSchedule { config: config.clone() };
176                send_to_subscribers(subscribers, event).await;
177                known_configs.insert(config_id.clone());
178                configs.insert(config_id, config);
179            } else {
180                // Config ID exists, but the content might have changed
181                let existing_config = configs.get(&config_id).unwrap();
182                if *existing_config != config {
183                    configs.insert(config_id.clone(), config.clone());
184                    debug!("Configuration updated: {}", config_id);
185                    let event = AutodiscoveryEvent::CheckSchedule { config };
186                    send_to_subscribers(subscribers, event).await;
187                }
188            }
189        }
190        Err(e) => {
191            warn!("Failed to parse config file {}: {}", path.display(), e);
192        }
193    }
194}
195
196/// Returns true if the path has a YAML extension (`yaml` or `yml`).
197fn is_yaml_file(path: &Path) -> bool {
198    matches!(path.extension().and_then(|e| e.to_str()), Some("yaml") | Some("yml"))
199}
200
201/// Scan and emit events based on configuration files in the directory.
202///
203/// Supports two layouts:
204/// - `<search-path>/<check-name>.yaml`—flat YAML files.
205/// - `<search-path>/<check-name>.d/*.yaml`—directory-based configs; the check name is derived
206///   from the directory stem (the `.d` suffix is stripped).
207async fn scan_and_emit_events(
208    paths: &[PathBuf], known_configs: &mut HashSet<String>, subscribers: &AutodiscoverySubscribers,
209    configs: &mut BTreeMap<String, CheckConfig>,
210) -> Result<(), GenericError> {
211    let mut found_configs = HashSet::new();
212
213    for path in paths {
214        let mut entries = fs::read_dir(path).await?;
215        while let Ok(Some(entry)) = entries.next_entry().await {
216            let path = entry.path();
217
218            if is_yaml_file(&path) {
219                // Flat YAML file: <check-name>.yaml
220                let check_name = path.file_stem().unwrap().to_string_lossy().into_owned();
221                process_yaml_file(
222                    path,
223                    &check_name,
224                    &mut found_configs,
225                    known_configs,
226                    subscribers,
227                    configs,
228                )
229                .await;
230            } else if path.is_dir() {
231                // Directory: only process if it matches the `<check-name>.d` convention
232                let dir_name = path.file_name().unwrap_or_default().to_string_lossy();
233                if let Some(check_name) = dir_name.strip_suffix(".d") {
234                    let Ok(mut sub_entries) = fs::read_dir(&path).await else {
235                        warn!("Failed to read directory {}", path.display());
236                        continue;
237                    };
238                    while let Ok(Some(sub_entry)) = sub_entries.next_entry().await {
239                        let sub_path = sub_entry.path();
240                        if is_yaml_file(&sub_path) {
241                            process_yaml_file(
242                                sub_path,
243                                check_name,
244                                &mut found_configs,
245                                known_configs,
246                                subscribers,
247                                configs,
248                            )
249                            .await;
250                        }
251                    }
252                }
253            }
254        }
255    }
256
257    // Clean up removed configurations
258    let to_remove: Vec<String> = known_configs
259        .iter()
260        .filter(|config_id| !found_configs.contains(*config_id))
261        .cloned()
262        .collect();
263
264    for config_id in to_remove {
265        debug!("Configuration removed: {}", config_id);
266        known_configs.remove(&config_id);
267
268        let config = configs.remove(&config_id).unwrap();
269
270        // Create an unschedule Config event
271        let event = AutodiscoveryEvent::CheckUnscheduled { config };
272        send_to_subscribers(subscribers, event).await;
273    }
274
275    Ok(())
276}
277
278async fn send_to_subscribers(subscribers: &AutodiscoverySubscribers, event: AutodiscoveryEvent) {
279    let mut subscribers = subscribers.lock().await;
280    let mut active_subscribers = Vec::with_capacity(subscribers.len());
281
282    for sender in subscribers.drain(..) {
283        if sender.send(event.clone()).await.is_ok() {
284            active_subscribers.push(sender);
285        }
286    }
287
288    *subscribers = active_subscribers;
289}
290
291#[async_trait]
292impl AutodiscoveryProvider for LocalAutodiscoveryProvider {
293    async fn subscribe(&self) -> Option<Receiver<AutodiscoveryEvent>> {
294        self.listener_init
295            .get_or_init(|| async {
296                self.start_background_monitor(BG_MONITOR_INTERVAL).await;
297            })
298            .await;
299
300        let (sender, receiver) = mpsc::channel::<AutodiscoveryEvent>(16);
301        self.subscribers.lock().await.push(sender);
302        Some(receiver)
303    }
304}
305
306#[cfg(test)]
307mod tests {
308    use std::path::Path;
309
310    use tempfile::tempdir;
311
312    use super::*;
313
314    // Get the path to the test_data directory
315    fn test_data_path() -> PathBuf {
316        let manifest_dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_else(|_| ".".to_string());
317        PathBuf::from(manifest_dir)
318            .join("src")
319            .join("autodiscovery")
320            .join("providers")
321            .join("test_data")
322    }
323
324    fn check_config(name: &'static str) -> CheckConfig {
325        CheckConfig {
326            name: MetaString::from_static(name),
327            init_config: Data::default(),
328            instances: Vec::new(),
329            metric_config: Data::default(),
330            logs_config: Data::default(),
331            ad_identifiers: Vec::new(),
332            advanced_ad_identifiers: Vec::new(),
333            provider: MetaString::default(),
334            service_id: MetaString::default(),
335            tagger_entity: MetaString::default(),
336            cluster_check: false,
337            node_name: MetaString::default(),
338            source: MetaString::from_static("local"),
339            ignore_autodiscovery_tags: false,
340            metrics_excluded: false,
341            logs_excluded: false,
342        }
343    }
344
345    // Copy a `<check>.d` directory from test_data into the temp directory, preserving the structure.
346    async fn copy_test_check_dir(check_dir_name: &str, temp_dir: &Path) {
347        let source_dir = test_data_path().join(check_dir_name);
348        let target_dir = temp_dir.join(check_dir_name);
349        fs::create_dir_all(&target_dir).await.unwrap();
350
351        let mut entries = fs::read_dir(&source_dir).await.unwrap();
352        while let Ok(Some(entry)) = entries.next_entry().await {
353            fs::copy(entry.path(), target_dir.join(entry.file_name()))
354                .await
355                .unwrap();
356        }
357    }
358
359    // Copy a file from test_data to the temp directory, preserving its name.
360    async fn copy_test_file(source_name: &str, temp_dir: &Path) -> PathBuf {
361        copy_test_file_as(source_name, source_name, temp_dir).await
362    }
363
364    // Copy a file from test_data to the temp directory with a different target name.
365    async fn copy_test_file_as(source_name: &str, target_name: &str, temp_dir: &Path) -> PathBuf {
366        let source_path = test_data_path().join(source_name);
367        let target_path = temp_dir.join(target_name);
368
369        let content = fs::read_to_string(&source_path)
370            .await
371            .unwrap_or_else(|_| panic!("Failed to read test file: {:?}", source_path));
372
373        fs::write(&target_path, content).await.unwrap();
374
375        target_path
376    }
377
378    #[tokio::test]
379    async fn test_parse_config_file() {
380        let test_file = test_data_path().join("test-config.yaml");
381
382        let (id, config) = parse_config_file(&test_file, "test-config").await.unwrap();
383
384        assert!(id.contains("saluki-env_src_autodiscovery_providers_test_data_test-config.yaml"));
385        assert_eq!(config.name, "test-config");
386        assert_eq!(
387            config.init_config.value.get("service"),
388            Some(&serde_json::Value::String("test-service".to_string()))
389        );
390        assert_eq!(config.source, "local");
391    }
392
393    #[tokio::test]
394    async fn test_parse_minimal_config_file() {
395        let test_file = test_data_path().join("test-minimal-config.yaml");
396
397        let (_, config) = parse_config_file(&test_file, "test-minimal-config").await.unwrap();
398
399        // Parsing a config without `init_config` yields an empty hash map for that field.
400        assert!(config.init_config.value.is_empty());
401    }
402
403    #[test]
404    fn test_null_values_read_as_empty() {
405        let cases = [
406            ("init_config:\ninstances:\n  -\n", 1),
407            ("init_config: ~\ninstances: [null, {}]\n", 2),
408            ("init_config: null\ninstances:\n", 0),
409        ];
410
411        for (yaml, instance_count) in cases {
412            let config: LocalCheckConfig = crate::autodiscovery::yaml_from_str(yaml).unwrap();
413            assert!(config.init_config.is_empty(), "{yaml:?}");
414            assert_eq!(config.instances.len(), instance_count, "{yaml:?}");
415            assert!(config.instances.into_iter().all(|i| i.unwrap_or_default().is_empty()));
416        }
417
418        assert!(crate::autodiscovery::yaml_from_str::<LocalCheckConfig>("init_config:\n").is_err());
419    }
420
421    #[tokio::test]
422    async fn test_scan_and_emit_events_new_config() {
423        let dir = tempdir().unwrap();
424        let _test_file = copy_test_file("config1.yaml", dir.path()).await;
425
426        let mut known_configs = HashSet::new();
427        let mut configs = BTreeMap::new();
428        let (sender, mut receiver) = mpsc::channel::<AutodiscoveryEvent>(10);
429        let subscribers = Arc::new(Mutex::new(vec![sender]));
430
431        scan_and_emit_events(
432            &[dir.path().to_path_buf()],
433            &mut known_configs,
434            &subscribers,
435            &mut configs,
436        )
437        .await
438        .unwrap();
439
440        assert_eq!(known_configs.len(), 1);
441
442        let event = receiver.try_recv().unwrap();
443        assert!(matches!(event, AutodiscoveryEvent::CheckSchedule { .. }));
444
445        if let AutodiscoveryEvent::Schedule { config } = event {
446            assert_eq!(config.name, "config1.yaml");
447            assert_eq!(config.instances.len(), 1);
448            assert_eq!(
449                config.instances[0].value.get("server"),
450                Some(&serde_json::Value::String("localhost".to_string()))
451            );
452            assert_eq!(
453                config.instances[0].value.get("port"),
454                Some(&serde_json::Value::Number(8080.into()))
455            );
456            assert_eq!(
457                config.instances[0].value.get("tags"),
458                Some(&serde_json::Value::Array(vec![
459                    serde_json::Value::String("test:true".to_string()),
460                    serde_json::Value::String("env:test".to_string())
461                ]))
462            );
463        }
464        assert!(receiver.try_recv().is_err());
465    }
466
467    #[tokio::test]
468    async fn test_scan_and_emit_events_preserves_bursts() {
469        let dir = tempdir().unwrap();
470        let _test_file1 = copy_test_file_as("config1.yaml", "config1.yaml", dir.path()).await;
471        let _test_file2 = copy_test_file_as("config1.yaml", "config2.yaml", dir.path()).await;
472
473        let (sender, mut receiver) = mpsc::channel::<AutodiscoveryEvent>(1);
474        let subscribers = Arc::new(Mutex::new(vec![sender]));
475        let search_path = dir.path().to_path_buf();
476
477        let scan = tokio::spawn(async move {
478            let mut known_configs = HashSet::new();
479            let mut configs = BTreeMap::new();
480
481            scan_and_emit_events(&[search_path], &mut known_configs, &subscribers, &mut configs).await
482        });
483
484        let event1 = tokio::time::timeout(Duration::from_secs(1), receiver.recv())
485            .await
486            .unwrap()
487            .unwrap();
488        let event2 = tokio::time::timeout(Duration::from_secs(1), receiver.recv())
489            .await
490            .unwrap()
491            .unwrap();
492
493        scan.await.unwrap().unwrap();
494
495        assert!(matches!(event1, AutodiscoveryEvent::CheckSchedule { .. }));
496        assert!(matches!(event2, AutodiscoveryEvent::CheckSchedule { .. }));
497        assert!(receiver.try_recv().is_err());
498    }
499
500    #[tokio::test]
501    async fn test_send_to_subscribers_fans_out_and_prunes_closed_receivers() {
502        let (sender1, mut receiver1) = mpsc::channel::<AutodiscoveryEvent>(10);
503        let (sender2, mut receiver2) = mpsc::channel::<AutodiscoveryEvent>(10);
504        let (closed_sender, closed_receiver) = mpsc::channel::<AutodiscoveryEvent>(10);
505        drop(closed_receiver);
506
507        let subscribers = Arc::new(Mutex::new(vec![sender1, sender2, closed_sender]));
508        let event = AutodiscoveryEvent::CheckSchedule {
509            config: check_config("test-check"),
510        };
511
512        send_to_subscribers(&subscribers, event).await;
513
514        assert_eq!(subscribers.lock().await.len(), 2);
515        assert!(matches!(
516            receiver1.try_recv().unwrap(),
517            AutodiscoveryEvent::CheckSchedule { .. }
518        ));
519        assert!(matches!(
520            receiver2.try_recv().unwrap(),
521            AutodiscoveryEvent::CheckSchedule { .. }
522        ));
523    }
524
525    #[tokio::test]
526    async fn test_scan_and_emit_events_removed_config() {
527        let dir = tempdir().unwrap();
528
529        let mut known_configs = HashSet::new();
530        known_configs.insert("removed-config".to_string());
531        let mut configs = BTreeMap::new();
532        configs.insert("removed-config".to_string(), check_config("removed-config"));
533
534        let (sender, mut receiver) = mpsc::channel::<AutodiscoveryEvent>(10);
535        let subscribers = Arc::new(Mutex::new(vec![sender]));
536
537        scan_and_emit_events(
538            &[dir.path().to_path_buf()],
539            &mut known_configs,
540            &subscribers,
541            &mut configs,
542        )
543        .await
544        .unwrap();
545
546        assert_eq!(known_configs.len(), 0);
547
548        let event = receiver.try_recv().unwrap();
549        assert!(matches!(event, AutodiscoveryEvent::CheckUnscheduled { config } if config.name == "removed-config"));
550
551        assert!(receiver.try_recv().is_err());
552    }
553
554    #[tokio::test]
555    async fn test_scan_and_emit_events_check_dir() {
556        let dir = tempdir().unwrap();
557        copy_test_check_dir("test-check.d", dir.path()).await;
558
559        let mut known_configs = HashSet::new();
560        let mut configs = BTreeMap::new();
561        let (sender, mut receiver) = mpsc::channel::<AutodiscoveryEvent>(10);
562        let subscribers = Arc::new(Mutex::new(vec![sender]));
563
564        scan_and_emit_events(
565            &[dir.path().to_path_buf()],
566            &mut known_configs,
567            &subscribers,
568            &mut configs,
569        )
570        .await
571        .unwrap();
572
573        // One config file inside test-check.d/
574        assert_eq!(known_configs.len(), 1);
575
576        let event = receiver.try_recv().unwrap();
577        assert!(
578            matches!(&event, AutodiscoveryEvent::CheckSchedule { config } if config.name == "test-check"),
579            "expected check name 'test-check', got: {:?}",
580            event
581        );
582
583        assert!(receiver.try_recv().is_err());
584    }
585}