Skip to main content

saluki_components/destinations/dsd_debug_log/
mod.rs

1use std::{io::Write, path::PathBuf};
2
3use async_trait::async_trait;
4use saluki_common::collections::FastHashMap;
5use saluki_common::logging::RollingFileWriter;
6use saluki_common::sync::live::Live;
7use saluki_common::time::{Timestamp, TimestampFormat};
8use saluki_core::{
9    accounting::{MemoryBounds, MemoryBoundsBuilder},
10    components::{
11        destinations::{Destination, DestinationBuilder, DestinationContext},
12        BuildContext,
13    },
14    data_model::{
15        event::{metric::Metric, EventType},
16        tags::TagSet,
17    },
18};
19use saluki_error::{generic_error, GenericError};
20use stringtheory::MetaString;
21use tokio::select;
22use tracing::{debug, warn};
23use tracing_appender::non_blocking::{NonBlocking, NonBlockingBuilder, WorkerGuard};
24
25const DEBUG_LOG_WRITER_BUFFER_LINES: usize = 4096;
26
27/// Configuration for the DogStatsD debug log destination.
28pub struct DogStatsDDebugLogConfiguration {
29    /// Whether DogStatsD metric-level statistics are enabled.
30    ///
31    /// The destination drops metrics while this runtime setting is `false`.
32    pub metrics_stats_enabled: Live<bool>,
33
34    /// Path to the DogStatsD debug log file.
35    pub log_file: PathBuf,
36
37    /// Maximum size of the active debug log file before rotation, in bytes.
38    pub log_file_max_size: u64,
39
40    /// Number of rotated debug log files to keep.
41    pub log_file_max_rolls: usize,
42}
43
44/// DogStatsD destination that writes metric debug lines to a rotating file.
45struct DogStatsDDebugLog {
46    log_file: PathBuf,
47    log_file_max_size: u64,
48    log_file_max_rolls: usize,
49    writer: Option<DebugLogWriter>,
50    metrics_stats_enabled: Live<bool>,
51    stats: FastHashMap<ContextNoOrigin, MetricSample>,
52}
53
54struct DebugLogWriter {
55    writer: NonBlocking,
56    _guard: WorkerGuard,
57}
58
59#[derive(Debug, Default)]
60struct MetricSample {
61    count: u64,
62    last_seen: u64,
63}
64
65#[derive(Eq, Hash, PartialEq)]
66struct ContextNoOrigin {
67    name: MetaString,
68    tags: TagSet,
69}
70
71impl DogStatsDDebugLog {
72    fn new(config: &DogStatsDDebugLogConfiguration) -> Result<Self, GenericError> {
73        let mut destination = Self {
74            log_file: config.log_file.clone(),
75            log_file_max_size: config.log_file_max_size,
76            log_file_max_rolls: config.log_file_max_rolls,
77            writer: None,
78            metrics_stats_enabled: config.metrics_stats_enabled.clone(),
79            stats: FastHashMap::default(),
80        };
81
82        if *destination.metrics_stats_enabled {
83            destination.ensure_writer()?;
84        }
85
86        Ok(destination)
87    }
88
89    fn process_metric(&mut self, metric: &Metric) -> Result<(), GenericError> {
90        if !*self.metrics_stats_enabled {
91            return Ok(());
92        }
93
94        self.write_metric(metric)
95    }
96
97    fn write_metric(&mut self, metric: &Metric) -> Result<(), GenericError> {
98        self.ensure_writer()?;
99
100        let context = metric.context();
101        let metric_context = ContextNoOrigin {
102            name: context.name().clone(),
103            tags: context.tags().clone(),
104        };
105
106        let timestamp = saluki_common::time::get_coarse_unix_timestamp();
107        let sample = self.stats.entry(metric_context).or_default();
108        sample.count += 1;
109        sample.last_seen = timestamp;
110
111        // Format the line up front: the non-blocking writer forwards each write separately, so writing the line in
112        // pieces could split it across a roll-over, or drop part of it when the writer is full.
113        let line = format!(
114            "Metric Name: {} | Tags: {{{}}} | Count: {} | Last Seen: {}\n",
115            context.name(),
116            format_tags(context.tags()),
117            sample.count,
118            format_timestamp(sample.last_seen)
119        );
120
121        let writer = self.writer.as_mut().expect("writer should be initialized");
122        writer.writer.write_all(line.as_bytes()).map_err(|e| {
123            generic_error!(
124                "Failed to write to DogStatsD debug log file '{}': {}",
125                self.log_file.display(),
126                e
127            )
128        })
129    }
130
131    fn ensure_writer(&mut self) -> Result<(), GenericError> {
132        if self.writer.is_some() {
133            return Ok(());
134        }
135
136        let appender = RollingFileWriter::open(&self.log_file, self.log_file_max_size, self.log_file_max_rolls)
137            .map_err(|e| generic_error!("Failed to open dogstatsd_log_file '{}': {}", self.log_file.display(), e))?;
138
139        let (writer, guard) = NonBlockingBuilder::default()
140            .thread_name("dsd-dbg-writer")
141            .buffered_lines_limit(DEBUG_LOG_WRITER_BUFFER_LINES)
142            // Drop debug log lines rather than slow DogStatsD metric ingestion.
143            .lossy(true)
144            .finish(appender);
145
146        self.writer = Some(DebugLogWriter { writer, _guard: guard });
147
148        Ok(())
149    }
150}
151
152#[async_trait]
153impl Destination for DogStatsDDebugLog {
154    async fn run(mut self: Box<Self>, mut context: DestinationContext) -> Result<(), GenericError> {
155        let mut health = context.take_health_handle();
156        health.mark_ready();
157
158        loop {
159            select! {
160                _ = health.live() => continue,
161                maybe_events = context.events().next() => match maybe_events {
162                    Some(events) => {
163                        for metric in events.into_events::<Metric>() {
164                            if let Err(error) = self.process_metric(&metric) {
165                                warn!(error = %error, "Failed to write DogStatsD debug log line; continuing.");
166                            }
167                        }
168                    },
169                    None => break,
170                },
171                metrics_stats_enabled = self.metrics_stats_enabled.changed() => {
172                    debug!(metrics_stats_enabled, "Updated DogStatsD metrics stats debug logging gate.");
173                },
174            }
175        }
176
177        Ok(())
178    }
179}
180
181#[async_trait]
182impl DestinationBuilder for DogStatsDDebugLogConfiguration {
183    fn input_event_type(&self) -> EventType {
184        EventType::Metric
185    }
186
187    async fn build(&self, _context: BuildContext) -> Result<Box<dyn Destination + Send>, GenericError> {
188        DogStatsDDebugLog::new(self).map(|destination| Box::new(destination) as Box<dyn Destination + Send>)
189    }
190}
191
192impl MemoryBounds for DogStatsDDebugLogConfiguration {
193    fn specify_bounds(&self, builder: &mut MemoryBoundsBuilder) {
194        builder
195            .minimum()
196            .with_single_value::<DogStatsDDebugLog>("component struct");
197    }
198}
199
200fn format_tags(tags: &TagSet) -> String {
201    let mut formatted = String::new();
202
203    for tag in tags {
204        if !formatted.is_empty() {
205            formatted.push(' ');
206        }
207        formatted.push_str(tag.as_str());
208    }
209
210    formatted
211}
212
213fn format_timestamp(timestamp: u64) -> String {
214    i64::try_from(timestamp)
215        .ok()
216        .and_then(Timestamp::from_unix_seconds)
217        .map(|ts| ts.format(TimestampFormat::GoUtc).to_string())
218        .unwrap_or_else(|| timestamp.to_string())
219}
220
221#[cfg(test)]
222mod tests {
223    use std::{
224        fs,
225        path::{Path, PathBuf},
226        time::Duration,
227    };
228
229    use saluki_common::sync::live::Live;
230    use saluki_core::{
231        components::test_util::TestComponentDriver,
232        data_model::event::{
233            metric::{context::Context, Metric},
234            Event,
235        },
236    };
237    use tempfile::tempdir;
238
239    use super::{format_timestamp, DogStatsDDebugLog, DogStatsDDebugLogConfiguration};
240
241    fn test_config(log_file: PathBuf, max_size: u64, max_rolls: usize) -> DogStatsDDebugLogConfiguration {
242        DogStatsDDebugLogConfiguration {
243            metrics_stats_enabled: Live::new_fixed(true),
244            log_file,
245            log_file_max_size: max_size,
246            log_file_max_rolls: max_rolls,
247        }
248    }
249
250    fn read_log_files(log_file: &Path, max_rolls: usize) -> String {
251        let mut output = String::new();
252
253        for roll in (0..=max_rolls).rev() {
254            let path = rolled_path(log_file, roll);
255            if path.exists() {
256                output.push_str(&fs::read_to_string(&path).expect("debug log file should be readable"));
257            }
258        }
259
260        output
261    }
262
263    fn rolled_path(log_file: &Path, roll: usize) -> PathBuf {
264        if roll == 0 {
265            log_file.to_path_buf()
266        } else {
267            PathBuf::from(format!("{}.{}", log_file.display(), roll))
268        }
269    }
270
271    fn tagged_metric() -> Metric {
272        let context = Context::from_static_parts("custom.metric", &["env:prod", "service:web"]);
273        Metric::counter(context, 1.0)
274    }
275
276    #[test]
277    fn last_seen_timestamps_are_formatted_in_utc() {
278        let cases = [
279            (0, "1970-01-01 00:00:00 +0000 UTC"),
280            (1_700_499_303, "2023-11-20 16:55:03 +0000 UTC"),
281            (253_402_207_200, "9999-12-30 22:00:00 +0000 UTC"),
282            // Timestamps that can't be represented fall back to the raw number of seconds. `Timestamp` stops at
283            // 9999-12-30T22:00:00Z, while chrono, which earlier versions used, could represent dates up to the year
284            // 262142.
285            (253_402_207_201, "253402207201"),
286            (i64::MAX as u64, "9223372036854775807"),
287            (u64::MAX, "18446744073709551615"),
288        ];
289
290        for (timestamp, expected) in cases {
291            assert_eq!(format_timestamp(timestamp), expected, "timestamp {}", timestamp);
292        }
293    }
294
295    #[tokio::test]
296    async fn writes_metric_debug_lines_and_updates_count() {
297        let tempdir = tempdir().expect("temporary directory should be created");
298        let log_file = tempdir.path().join("dogstatsd-stats.log");
299        let config = test_config(log_file.clone(), 64_000, 3);
300        let metric = tagged_metric();
301
302        let mut destination = DogStatsDDebugLog::new(&config).expect("debug log destination should be built");
303        destination
304            .write_metric(&metric)
305            .expect("first metric should be written");
306        destination
307            .write_metric(&metric)
308            .expect("second metric should be written");
309        drop(destination);
310
311        let output = read_log_files(&log_file, config.log_file_max_rolls);
312        let lines = output.lines().collect::<Vec<_>>();
313
314        assert_eq!(lines.len(), 2);
315        assert!(lines[0].contains("Metric Name: custom.metric"));
316        assert!(lines[0].contains("Tags: {env:prod service:web}"));
317        assert!(lines[0].contains("Count: 1"));
318        assert!(lines[0].contains("Last Seen: "));
319        assert!(lines[1].contains("Count: 2"));
320    }
321
322    #[tokio::test]
323    async fn run_starts_and_stops_logging_with_metrics_stats_setting() {
324        let tempdir = tempdir().expect("temporary directory should be created");
325        let log_file = tempdir.path().join("dogstatsd-stats.log");
326        // Stands in for the shared source the setting is projected out of.
327        let (mut publisher, source) = saluki_common::sync::live::channel(false);
328        let mut config = test_config(log_file.clone(), 64_000, 3);
329        config.metrics_stats_enabled = source.live(|enabled| enabled);
330        let log_file_max_rolls = config.log_file_max_rolls;
331        let control = TestComponentDriver::destination(config)
332            .await
333            .expect("debug log destination should be built");
334
335        control.send_event(Event::Metric(tagged_metric())).await;
336        control.wait_until_input_drained().await;
337        assert!(!log_file.exists());
338
339        publisher.publish(true);
340
341        tokio::time::timeout(Duration::from_secs(2), async {
342            loop {
343                control.send_event(Event::Metric(tagged_metric())).await;
344                tokio::time::sleep(Duration::from_millis(10)).await;
345                if fs::read_to_string(&log_file).is_ok_and(|output| output.contains("Metric Name: custom.metric")) {
346                    break;
347                }
348            }
349        })
350        .await
351        .expect("metrics should be logged after the runtime setting is enabled");
352
353        publisher.publish(false);
354
355        let line_count_after_disable = tokio::time::timeout(Duration::from_secs(2), async {
356            let mut previous_line_count = read_log_files(&log_file, log_file_max_rolls).lines().count();
357            let mut unchanged_samples = 0;
358
359            loop {
360                control.send_event(Event::Metric(tagged_metric())).await;
361                control.wait_until_input_drained().await;
362                tokio::time::sleep(Duration::from_millis(20)).await;
363
364                let current_line_count = read_log_files(&log_file, log_file_max_rolls).lines().count();
365                if current_line_count == previous_line_count {
366                    unchanged_samples += 1;
367                    if unchanged_samples == 5 {
368                        break current_line_count;
369                    }
370                } else {
371                    previous_line_count = current_line_count;
372                    unchanged_samples = 0;
373                }
374            }
375        })
376        .await
377        .expect("metrics should stop being logged after the runtime setting is disabled");
378
379        for _ in 0..3 {
380            control.send_event(Event::Metric(tagged_metric())).await;
381        }
382        control.wait_until_input_drained().await;
383        tokio::time::sleep(Duration::from_millis(100)).await;
384
385        let output = read_log_files(&log_file, log_file_max_rolls);
386        assert_eq!(output.lines().count(), line_count_after_disable);
387
388        control.shutdown().await.expect("destination should stop cleanly");
389    }
390
391    #[tokio::test]
392    async fn rotates_log_file_at_configured_size() {
393        let tempdir = tempdir().expect("temporary directory should be created");
394        let log_file = tempdir.path().join("dogstatsd-stats.log");
395        let min_debug_line_len =
396            "Metric Name: custom.metric | Tags: {env:prod service:web} | Count: 1 | Last Seen: ".len();
397        let config = test_config(log_file.clone(), min_debug_line_len as u64, 2);
398        let metric = tagged_metric();
399
400        let mut destination = DogStatsDDebugLog::new(&config).expect("debug log destination should be built");
401        for _ in 0..12 {
402            destination.write_metric(&metric).expect("metric should be written");
403        }
404        drop(destination);
405
406        assert!(log_file.exists());
407        assert!(rolled_path(&log_file, 1).exists());
408        assert!(rolled_path(&log_file, 2).exists());
409        assert!(!rolled_path(&log_file, 3).exists());
410
411        // Every line is longer than the maximum size, so each file rolls over after one line, and a line that was
412        // written in pieces would end up split across two files.
413        for roll in 0..=config.log_file_max_rolls {
414            let output = fs::read_to_string(rolled_path(&log_file, roll)).expect("debug log file should be readable");
415            let lines = output.lines().collect::<Vec<_>>();
416            assert!(output.ends_with('\n'), "file {} ends mid-line: {:?}", roll, output);
417            assert_eq!(lines.len(), 1, "file {} should hold one line: {:?}", roll, output);
418            assert!(
419                lines[0].starts_with("Metric Name: custom.metric | Tags: {env:prod service:web} | Count: ")
420                    && lines[0].contains(" | Last Seen: "),
421                "file {} holds a partial line: {:?}",
422                roll,
423                lines[0]
424            );
425        }
426    }
427
428    #[tokio::test]
429    async fn build_error_mentions_log_file_config_key_and_path() {
430        let tempdir = tempdir().expect("temporary directory should be created");
431        let blocked_parent = tempdir.path().join("not-a-directory");
432        fs::write(&blocked_parent, "not a directory").expect("blocking file should be written");
433        let log_file = blocked_parent.join("dogstatsd-stats.log");
434        let config = test_config(log_file.clone(), 64_000, 3);
435
436        let err = match DogStatsDDebugLog::new(&config) {
437            Ok(_) => panic!("build should fail"),
438            Err(err) => err,
439        };
440        let err = err.to_string();
441
442        assert!(err.contains("dogstatsd_log_file"));
443        assert!(err.contains(&log_file.display().to_string()));
444    }
445}