use super::types::{CompressionAlgorithm, FileInfo, FileMatchMode};
use std::fs;
use std::path::Path;
use std::time::Duration;
use std::time::SystemTime;
use tracing::debug;
const LOG_COMPONENT_OBS: &str = "obs";
const LOG_SUBSYSTEM_LOG_CLEANER: &str = "log_cleaner";
const EVENT_LOG_CLEANER_SCAN_STATE: &str = "log_cleaner_scan_state";
const ORPHAN_TMP_GRACE_SECONDS: u64 = 60;
pub(super) struct LogScanResult {
pub logs: Vec<FileInfo>,
pub compressed_archives: Vec<FileInfo>,
}
#[allow(clippy::too_many_arguments)]
pub(super) fn scan_log_directory(
log_dir: &Path,
file_pattern: &str,
active_filename: Option<&str>,
match_mode: FileMatchMode,
exclude_patterns: &[glob::Pattern],
min_file_age_seconds: u64,
delete_empty_files: bool,
dry_run: bool,
) -> Result<LogScanResult, std::io::Error> {
let file_pattern = file_pattern.trim();
if file_pattern.is_empty() {
return Ok(LogScanResult {
logs: Vec::new(),
compressed_archives: Vec::new(),
});
}
let mut logs = Vec::new();
let mut compressed_archives = Vec::new();
let now = SystemTime::now();
let entries = match fs::read_dir(log_dir) {
Ok(entries) => entries,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
return Ok(LogScanResult {
logs,
compressed_archives,
});
}
Err(e) => return Err(e),
};
for entry in entries {
let entry = match entry {
Ok(e) => e,
Err(_) => continue, };
let path = entry.path();
let metadata = match fs::symlink_metadata(&path) {
Ok(md) => md,
Err(_) => continue,
};
let file_type = metadata.file_type();
if !file_type.is_file() {
continue;
}
let filename = match path.file_name().and_then(|n| n.to_str()) {
Some(f) => f,
None => continue,
};
if let Some(active) = active_filename
&& filename == active
{
continue;
}
if is_excluded(filename, exclude_patterns) {
debug!(event = EVENT_LOG_CLEANER_SCAN_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, state = "excluded", filename = %filename, "log cleaner scan state changed");
continue;
}
let matched_suffix = CompressionAlgorithm::compressed_suffixes()
.into_iter()
.find(|suffix| filename.ends_with(suffix));
let matched_tmp_suffix_len = compressed_tmp_suffix_len(filename);
let is_compressed = matched_suffix.is_some();
let is_tmp_archive = matched_tmp_suffix_len.is_some();
let name_to_match = if let Some(suffix) = matched_suffix {
&filename[..filename.len() - suffix.len()]
} else if let Some(len) = matched_tmp_suffix_len {
&filename[..filename.len() - len]
} else {
filename
};
let matches = match match_mode {
FileMatchMode::Prefix => name_to_match.starts_with(file_pattern),
FileMatchMode::Suffix => name_to_match.ends_with(file_pattern),
};
if !matches {
continue;
}
let file_size = metadata.len();
let modified = match metadata.modified() {
Ok(t) => t,
Err(_) => continue, };
let age = now.duration_since(modified).ok();
if is_tmp_archive {
if !is_old_enough_for_cleanup(age, ORPHAN_TMP_GRACE_SECONDS) {
continue;
}
if !dry_run {
if let Err(e) = fs::remove_file(&path) {
tracing::warn!(event = EVENT_LOG_CLEANER_SCAN_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, result = "tmp_archive_delete_failed", path = ?path, error = %e, "log cleaner scan state changed");
} else {
debug!(event = EVENT_LOG_CLEANER_SCAN_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, state = "tmp_archive_deleted", path = ?path, "log cleaner scan state changed");
}
} else {
tracing::info!(event = EVENT_LOG_CLEANER_SCAN_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, state = "dry_run_tmp_archive_delete", path = ?path, "log cleaner scan state changed");
}
continue;
}
if !is_compressed && file_size == 0 && delete_empty_files {
if !is_old_enough_for_cleanup(age, min_file_age_seconds) {
continue;
}
if !dry_run {
if let Err(e) = fs::remove_file(&path) {
tracing::warn!(event = EVENT_LOG_CLEANER_SCAN_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, result = "empty_file_delete_failed", path = ?path, error = %e, "log cleaner scan state changed");
} else {
debug!(event = EVENT_LOG_CLEANER_SCAN_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, state = "empty_file_deleted", path = ?path, "log cleaner scan state changed");
}
} else {
tracing::info!(event = EVENT_LOG_CLEANER_SCAN_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, state = "dry_run_empty_file_delete", path = ?path, "log cleaner scan state changed");
}
continue;
}
if !is_compressed && !is_old_enough_for_cleanup(age, min_file_age_seconds) {
continue;
}
let info = FileInfo {
path,
size: file_size,
projected_freed_bytes: file_size,
modified,
};
if is_compressed {
compressed_archives.push(info);
} else {
logs.push(info);
}
}
Ok(LogScanResult {
logs,
compressed_archives,
})
}
pub(super) fn is_excluded(filename: &str, patterns: &[glob::Pattern]) -> bool {
patterns.iter().any(|p| p.matches(filename))
}
fn compressed_tmp_suffix_len(filename: &str) -> Option<usize> {
CompressionAlgorithm::compressed_suffixes().into_iter().find_map(|suffix| {
let tmp_suffix = format!("{suffix}.tmp");
filename.ends_with(&tmp_suffix).then_some(tmp_suffix.len())
})
}
fn is_old_enough_for_cleanup(age: Option<Duration>, min_file_age_seconds: u64) -> bool {
min_file_age_seconds == 0 || age.is_some_and(|age| age.as_secs() >= min_file_age_seconds)
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::File;
use tempfile::TempDir;
fn create_empty_file(dir: &Path, name: &str) -> std::io::Result<()> {
File::create(dir.join(name)).map(|_| ())
}
#[test]
fn empty_pattern_matches_nothing() -> std::io::Result<()> {
let tmp = TempDir::new()?;
let dir = tmp.path();
create_empty_file(dir, "random.log")?;
let result = scan_log_directory(dir, "", Some("active.log"), FileMatchMode::Suffix, &[], 0, true, false)?;
assert!(result.logs.is_empty());
assert!(result.compressed_archives.is_empty());
Ok(())
}
#[test]
fn fresh_empty_file_respects_min_file_age() -> std::io::Result<()> {
let tmp = TempDir::new()?;
let dir = tmp.path();
let filename = "2026-07-08.rustfs.log";
create_empty_file(dir, filename)?;
let result = scan_log_directory(dir, ".rustfs.log", Some("active.log"), FileMatchMode::Suffix, &[], 3600, true, false)?;
assert!(dir.join(filename).exists());
assert!(result.logs.is_empty());
Ok(())
}
#[test]
fn orphan_tmp_archive_is_deleted() -> std::io::Result<()> {
let tmp = TempDir::new()?;
let dir = tmp.path();
let filename = "2026-07-08.rustfs.log.gz.tmp";
create_empty_file(dir, filename)?;
let old = SystemTime::now() - Duration::from_secs(ORPHAN_TMP_GRACE_SECONDS + 60);
File::options().write(true).open(dir.join(filename))?.set_modified(old)?;
let _ = scan_log_directory(dir, ".rustfs.log", Some("active.log"), FileMatchMode::Suffix, &[], 0, true, false)?;
assert!(!dir.join(filename).exists());
Ok(())
}
#[test]
fn fresh_orphan_tmp_kept_within_grace() -> std::io::Result<()> {
let tmp = TempDir::new()?;
let dir = tmp.path();
let filename = "2026-07-08.rustfs.log.zst.tmp";
create_empty_file(dir, filename)?;
let _ = scan_log_directory(dir, ".rustfs.log", Some("active.log"), FileMatchMode::Suffix, &[], 999_999, true, false)?;
assert!(dir.join(filename).exists(), "fresh orphan tmp should be kept within grace");
Ok(())
}
#[test]
fn cleanup_age_gate_requires_known_old_enough_age() {
assert!(!is_old_enough_for_cleanup(Some(Duration::from_secs(0)), 1));
assert!(is_old_enough_for_cleanup(Some(Duration::from_secs(1)), 1));
assert!(!is_old_enough_for_cleanup(None, 1));
assert!(is_old_enough_for_cleanup(None, 0));
}
}