Skip to main content

schedr_agent/
retention.rs

1//! Log retention on the worker (see archive/PROJECT.md, Task logs): logs older than
2//! `[worker] log_retention` (30 days by default) are deleted, and beyond `[worker]
3//! log_max_size` (no limit by default) the oldest go first. A log whose attempt is in the
4//! journal (running, or its result not yet acknowledged) is never deleted, though it counts
5//! towards the size limit. Parse logs
6//! (`parse-<root>.log`) follow the same rules.
7//!
8//! A sweep runs when the worker starts and then every hour.
9
10use std::io;
11use std::path::{Path, PathBuf};
12use std::time::{Duration, SystemTime};
13
14use crate::journal::Journal;
15use crate::metrics::AgentMetrics;
16
17#[cfg(test)]
18mod tests;
19
20/// How often logs are swept.
21pub const SWEEP_INTERVAL: Duration = Duration::from_hours(1);
22
23/// What to keep.
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub struct LogRetention {
26    /// Logs older than this (by their last change) are deleted.
27    pub max_age: Duration,
28    /// Beyond this many bytes, the oldest logs are deleted; `None`: no limit.
29    pub max_size: Option<u64>,
30}
31
32/// What a sweep deleted.
33#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
34pub struct Swept {
35    /// Files deleted.
36    pub files: u64,
37    /// Their bytes.
38    pub bytes: u64,
39    /// The bytes of logs left.
40    pub kept: u64,
41}
42
43struct LogFile {
44    path: PathBuf,
45    modified: SystemTime,
46    size: u64,
47}
48
49/// Deletes from `log_dir` what `retention` doesn't keep at `now`, sparing the logs of
50/// attempts in `journal`. A file that can't be deleted is logged and counted as kept.
51///
52/// # Errors
53///
54/// An I/O error if the directory can't be read (a missing one has nothing to sweep).
55pub fn sweep(
56    log_dir: &Path,
57    journal: &Journal,
58    retention: LogRetention,
59    now: SystemTime,
60) -> io::Result<Swept> {
61    let kept: Vec<String> = match journal.records() {
62        Ok(records) => records
63            .into_iter()
64            .map(|(id, _)| format!("{id}.log"))
65            .collect(),
66        Err(e) if e.kind() == io::ErrorKind::NotFound => Vec::new(),
67        Err(e) => return Err(e),
68    };
69    let entries = match std::fs::read_dir(log_dir) {
70        Ok(entries) => entries,
71        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Swept::default()),
72        Err(e) => return Err(e),
73    };
74    let mut files = Vec::new();
75    // Spared logs count towards the size limit too: it is about the disk.
76    let mut spared: u64 = 0;
77    for entry in entries {
78        let entry = entry?;
79        let name = entry.file_name().to_string_lossy().into_owned();
80        let Ok(metadata) = entry.metadata() else {
81            continue;
82        };
83        let is_log = Path::new(&name).extension().is_some_and(|e| e == "log");
84        if !metadata.is_file() || !is_log {
85            continue;
86        }
87        if kept.contains(&name) {
88            spared += metadata.len();
89            continue;
90        }
91        files.push(LogFile {
92            path: entry.path(),
93            modified: metadata.modified().unwrap_or(now),
94            size: metadata.len(),
95        });
96    }
97    // Oldest first: deleted first when over the size limit.
98    files.sort_by_key(|f| f.modified);
99    let mut total: u64 = spared + files.iter().map(|f| f.size).sum::<u64>();
100    let mut swept = Swept::default();
101    for file in files {
102        let expired = now
103            .duration_since(file.modified)
104            .is_ok_and(|age| age > retention.max_age);
105        let over = retention.max_size.is_some_and(|max| total > max);
106        if !expired && !over {
107            continue;
108        }
109        match std::fs::remove_file(&file.path) {
110            Ok(()) => {
111                total -= file.size;
112                swept.files += 1;
113                swept.bytes += file.size;
114            }
115            Err(error) => {
116                tracing::warn!(path = %file.path.display(), %error, "can't delete an old log");
117            }
118        }
119    }
120    swept.kept = total;
121    Ok(swept)
122}
123
124/// Sweeps now and every `interval` until `stop` completes, recording the bytes kept
125/// and deleted in `metrics`.
126pub async fn sweep_logs(
127    log_dir: PathBuf,
128    journal: Journal,
129    retention: LogRetention,
130    metrics: AgentMetrics,
131    interval: Duration,
132    stop: impl Future<Output = ()>,
133) {
134    tokio::pin!(stop);
135    let mut tick = tokio::time::interval(interval);
136    tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
137    loop {
138        tokio::select! {
139            () = &mut stop => return,
140            _ = tick.tick() => {}
141        }
142        let (dir, journal) = (log_dir.clone(), journal.clone());
143        let swept = tokio::task::spawn_blocking(move || {
144            sweep(&dir, &journal, retention, SystemTime::now())
145        })
146        .await;
147        if let Ok(Ok(swept)) = &swept {
148            metrics
149                .log_bytes
150                .set(i64::try_from(swept.kept).unwrap_or(i64::MAX));
151            metrics.log_swept_bytes.inc_by(swept.bytes);
152        }
153        match swept {
154            Ok(Ok(swept)) if swept.files > 0 => tracing::info!(
155                files = swept.files,
156                bytes = swept.bytes,
157                "deleted logs past their retention"
158            ),
159            Ok(Ok(_)) => {}
160            Ok(Err(error)) => tracing::warn!(%error, "can't sweep the log directory"),
161            Err(error) => tracing::warn!(%error, "sweeping the logs failed"),
162        }
163    }
164}