schedr_agent/
retention.rs1use 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
20pub const SWEEP_INTERVAL: Duration = Duration::from_hours(1);
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub struct LogRetention {
26 pub max_age: Duration,
28 pub max_size: Option<u64>,
30}
31
32#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
34pub struct Swept {
35 pub files: u64,
37 pub bytes: u64,
39 pub kept: u64,
41}
42
43struct LogFile {
44 path: PathBuf,
45 modified: SystemTime,
46 size: u64,
47}
48
49pub 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 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 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
124pub 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}