Skip to main content

rustfs_obs/cleaner/
core.rs

1// Copyright 2024 RustFS Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Core log-file cleanup orchestration.
16//!
17//! This module connects scanning, retention selection, compression, and safe
18//! deletion into one reusable service object. The public surface is intentionally
19//! small: callers configure a [`LogCleaner`] once and then trigger discrete
20//! cleanup passes whenever log rotation or background maintenance requires it.
21
22use super::compress::{CompressionOptions, compress_file};
23use super::scanner::{LogScanResult, scan_log_directory};
24use super::types::{CompressionAlgorithm, FileInfo, FileMatchMode, default_parallel_workers};
25use crate::global::{
26    METRIC_LOG_CLEANER_COMPRESS_DURATION_SECONDS, METRIC_LOG_CLEANER_DELETED_FILES_TOTAL, METRIC_LOG_CLEANER_FREED_BYTES_TOTAL,
27    METRIC_LOG_CLEANER_STEAL_SUCCESS_RATE,
28};
29use crossbeam_channel::bounded;
30use crossbeam_deque::{Injector, Steal, Stealer, Worker};
31use crossbeam_utils::{Backoff, thread};
32use metrics::{counter, gauge, histogram};
33use rustfs_config::DEFAULT_LOG_KEEP_FILES;
34use std::path::PathBuf;
35use std::sync::Arc;
36use std::sync::atomic::{AtomicU64, Ordering};
37use std::time::{Duration, Instant, SystemTime};
38use tracing::{debug, error, info, warn};
39
40const LOG_COMPONENT_OBS: &str = "obs";
41const LOG_SUBSYSTEM_LOG_CLEANER: &str = "log_cleaner";
42const EVENT_LOG_CLEANER_STATE: &str = "log_cleaner_state";
43const SECONDS_PER_DAY: u64 = 24 * 60 * 60;
44/// Absolute ceiling on parallel compression workers, independent of config, so
45/// a misconfigured `parallel_workers` on a directory with thousands of rotated logs
46/// cannot spawn thousands of threads (each of which may also start codec
47/// threads).
48const MAX_PARALLEL_COMPRESS_WORKERS: usize = 64;
49const MAX_RETENTION_DAYS_BEFORE_SATURATION: u64 = u64::MAX / SECONDS_PER_DAY;
50
51fn compressed_file_retention_window(days: u64) -> Duration {
52    Duration::from_secs(days.saturating_mul(SECONDS_PER_DAY))
53}
54
55#[derive(Debug)]
56struct CompressionTaskResult {
57    /// Original file metadata so successful workers can be deleted later.
58    file: FileInfo,
59    /// Whether compression completed successfully for this file.
60    compressed: bool,
61}
62
63/// Log-file lifecycle manager.
64///
65/// A cleaner instance is immutable after construction and therefore safe to
66/// reuse across periodic background jobs. Each call to [`LogCleaner::cleanup`]
67/// performs a fresh directory scan and applies the configured retention rules.
68pub struct LogCleaner {
69    /// Directory containing the active and rotated log files.
70    pub(super) log_dir: PathBuf,
71    /// Pattern used to recognize relevant log generations.
72    pub(super) file_pattern: String,
73    /// The currently active log file that must never be touched.
74    pub(super) active_filename: String,
75    /// Whether `file_pattern` is interpreted as a prefix or suffix.
76    pub(super) match_mode: FileMatchMode,
77    /// Maximum number of newest regular log files to keep.
78    pub(super) keep_files: usize,
79    /// Optional cap for the cumulative size of regular logs.
80    pub(super) max_total_size_bytes: u64,
81    /// Optional cap for an individual regular log file.
82    pub(super) max_single_file_size_bytes: u64,
83    /// Whether selected regular logs should be compressed before deletion.
84    pub(super) compress_old_files: bool,
85    /// Gzip compression level used when gzip is selected or used as fallback.
86    pub(super) gzip_compression_level: u32,
87    /// Retention window for already compressed archives, expressed in days.
88    pub(super) compressed_file_retention_days: u64,
89    /// Glob patterns that are excluded before any cleanup decision is made.
90    pub(super) exclude_patterns: Vec<glob::Pattern>,
91    /// Whether zero-byte regular logs may be removed during scanning.
92    pub(super) delete_empty_files: bool,
93    /// Minimum age a regular log must reach before it becomes eligible.
94    pub(super) min_file_age_seconds: u64,
95    /// Dry-run mode reports intended actions without modifying files.
96    pub(super) dry_run: bool,
97    // Parallel compression controls while keeping backward compatibility with
98    // the original serial cleaner behavior.
99    /// Preferred archive codec for compression-enabled cleanup passes.
100    pub(super) compression_algorithm: CompressionAlgorithm,
101    /// Enables the work-stealing compression path when compression is active.
102    pub(super) parallel_compress: bool,
103    /// Number of worker threads used by the parallel compressor.
104    pub(super) parallel_workers: usize,
105    /// Zstd compression level when zstd is selected.
106    pub(super) zstd_compression_level: i32,
107    /// Whether a failed zstd attempt should retry with gzip.
108    pub(super) zstd_fallback_to_gzip: bool,
109    /// Number of internal threads requested from the zstd encoder.
110    pub(super) zstd_workers: usize,
111}
112
113impl LogCleaner {
114    /// Create a builder with the required path and filename matching inputs.
115    pub fn builder(
116        log_dir: impl Into<PathBuf>,
117        file_pattern: impl Into<String>,
118        active_filename: impl Into<String>,
119    ) -> LogCleanerBuilder {
120        LogCleanerBuilder::new(log_dir, file_pattern, active_filename)
121    }
122
123    /// Effective gzip level after clamping — what compression actually uses.
124    pub fn effective_gzip_level(&self) -> u32 {
125        self.gzip_compression_level
126    }
127
128    /// Effective zstd level after clamping — what compression actually uses.
129    pub fn effective_zstd_level(&self) -> i32 {
130        self.zstd_compression_level
131    }
132
133    /// Perform one full cleanup pass.
134    pub fn cleanup(&self) -> Result<(usize, u64), std::io::Error> {
135        if !self.log_dir.exists() {
136            debug!(
137                event = EVENT_LOG_CLEANER_STATE,
138                component = LOG_COMPONENT_OBS,
139                subsystem = LOG_SUBSYSTEM_LOG_CLEANER,
140                state = "log_dir_missing",
141                log_dir = ?self.log_dir,
142                "log cleaner state changed"
143            );
144            return Ok((0, 0));
145        }
146
147        let mut total_deleted = 0usize;
148        let mut total_freed = 0u64;
149
150        let LogScanResult {
151            mut logs,
152            mut compressed_archives,
153        } = scan_log_directory(
154            &self.log_dir,
155            &self.file_pattern,
156            Some(&self.active_filename),
157            self.match_mode,
158            &self.exclude_patterns,
159            self.min_file_age_seconds,
160            self.delete_empty_files,
161            self.dry_run,
162        )?;
163
164        if !logs.is_empty() {
165            logs.sort_by_key(|f| f.modified);
166            let total_size: u64 = logs.iter().map(|f| f.size).sum();
167
168            info!(
169                event = EVENT_LOG_CLEANER_STATE,
170                component = LOG_COMPONENT_OBS,
171                subsystem = LOG_SUBSYSTEM_LOG_CLEANER,
172                state = "scan_completed",
173                regular_log_files = logs.len(),
174                total_bytes = total_size,
175                total_megabytes = total_size as f64 / 1024.0 / 1024.0,
176                "log cleaner state changed"
177            );
178
179            // Select the oldest files first, then additionally trim any files
180            // that still violate configured size constraints.
181            let to_delete = self.select_files_to_process(&logs, total_size);
182            if !to_delete.is_empty() {
183                let (deleted, freed) = if self.parallel_compress && self.compress_old_files {
184                    self.parallel_stealing_compress(&to_delete)?
185                } else {
186                    self.serial_compress_and_delete(&to_delete)?
187                };
188                total_deleted += deleted;
189                total_freed += freed;
190            }
191        }
192
193        if !compressed_archives.is_empty() {
194            let to_delete = self.select_archives_to_delete(&mut compressed_archives);
195            if !to_delete.is_empty() {
196                let (d, f) = self.delete_files(&to_delete)?;
197                total_deleted += d;
198                total_freed += f;
199            }
200        }
201
202        if total_deleted > 0 || total_freed > 0 {
203            counter!(METRIC_LOG_CLEANER_DELETED_FILES_TOTAL).increment(total_deleted as u64);
204            counter!(METRIC_LOG_CLEANER_FREED_BYTES_TOTAL).increment(total_freed);
205            info!(
206                event = EVENT_LOG_CLEANER_STATE,
207                component = LOG_COMPONENT_OBS,
208                subsystem = LOG_SUBSYSTEM_LOG_CLEANER,
209                state = "cleanup_completed",
210                deleted_files = total_deleted,
211                freed_bytes = total_freed,
212                freed_megabytes = total_freed as f64 / 1024.0 / 1024.0,
213                "log cleaner state changed"
214            );
215        }
216
217        Ok((total_deleted, total_freed))
218    }
219
220    /// Choose regular log files that should be compressed and/or deleted.
221    ///
222    /// The `files` slice must already be sorted from oldest to newest. The
223    /// method first enforces the `keep_files` ceiling, then applies total-size
224    /// and per-file-size limits to the remaining tail.
225    pub(super) fn select_files_to_process(&self, files: &[FileInfo], total_size: u64) -> Vec<FileInfo> {
226        let mut to_delete = Vec::new();
227        if files.is_empty() {
228            return to_delete;
229        }
230
231        let must_delete_count = files.len().saturating_sub(self.keep_files);
232        let mut current_size = total_size;
233
234        for (idx, file) in files.iter().enumerate() {
235            if idx < must_delete_count {
236                current_size = current_size.saturating_sub(file.size);
237                to_delete.push(file.clone());
238                continue;
239            }
240
241            let over_total = self.max_total_size_bytes > 0 && current_size > self.max_total_size_bytes;
242            let over_single = self.max_single_file_size_bytes > 0 && file.size > self.max_single_file_size_bytes;
243
244            if over_total || over_single {
245                current_size = current_size.saturating_sub(file.size);
246                to_delete.push(file.clone());
247            }
248        }
249
250        to_delete
251    }
252
253    /// Select compressed archives to delete: those older than the retention
254    /// window, plus — regardless of retention — the oldest archives needed to
255    /// bring the archive set back under `max_total_size_bytes`.
256    ///
257    /// The byte cap is the crucial part: with `compressed_file_retention_days`
258    /// set to 0 (retention disabled) and compression enabled, age-based expiry
259    /// never fires, so without this cap archives would grow without bound (the
260    /// cap on regular logs does not cover them). Bounding the archive set by the
261    /// same byte budget keeps disk usage finite even when retention is off.
262    fn select_archives_to_delete(&self, files: &mut [FileInfo]) -> Vec<FileInfo> {
263        if self.compressed_file_retention_days > MAX_RETENTION_DAYS_BEFORE_SATURATION {
264            warn!(
265                event = EVENT_LOG_CLEANER_STATE,
266                component = LOG_COMPONENT_OBS,
267                subsystem = LOG_SUBSYSTEM_LOG_CLEANER,
268                result = "retention_days_saturated",
269                configured_days = self.compressed_file_retention_days,
270                fallback_days = MAX_RETENTION_DAYS_BEFORE_SATURATION,
271                "log cleaner state changed"
272            );
273        }
274
275        // Oldest first so both age expiry and the byte-cap trim evict the
276        // longest-retained archives before newer ones.
277        files.sort_by_key(|f| f.modified);
278        let now = SystemTime::now();
279        let retention = compressed_file_retention_window(self.compressed_file_retention_days);
280        let retention_active = self.compressed_file_retention_days > 0;
281
282        let mut selected = vec![false; files.len()];
283
284        // 1. Age-based expiry (only when retention is enabled).
285        if retention_active {
286            for (idx, file) in files.iter().enumerate() {
287                if let Ok(age) = now.duration_since(file.modified)
288                    && age > retention
289                {
290                    selected[idx] = true;
291                }
292            }
293        }
294
295        // 2. Byte-cap trim: drop the oldest surviving archives until the set
296        //    fits under the configured total. 0 means "no cap".
297        if self.max_total_size_bytes > 0 {
298            let mut remaining: u64 = files
299                .iter()
300                .enumerate()
301                .filter(|(idx, _)| !selected[*idx])
302                .map(|(_, file)| file.size)
303                .sum();
304            for (idx, file) in files.iter().enumerate() {
305                if remaining <= self.max_total_size_bytes {
306                    break;
307                }
308                if selected[idx] {
309                    continue;
310                }
311                selected[idx] = true;
312                remaining = remaining.saturating_sub(file.size);
313            }
314        }
315
316        files
317            .iter()
318            .enumerate()
319            .filter(|(idx, _)| selected[*idx])
320            .map(|(_, file)| file.clone())
321            .collect()
322    }
323
324    /// Parallel compressor with work stealing.
325    ///
326    /// The flow is intentionally split into "parallel compression" followed by
327    /// "serial deletion" to reduce cross-platform file-locking failures.
328    /// Compression workers only decide whether an archive was created; the main
329    /// thread remains responsible for actual source removal so deletion policy
330    /// and error reporting stay deterministic.
331    fn parallel_stealing_compress(&self, files: &[FileInfo]) -> Result<(usize, u64), std::io::Error> {
332        if files.len() <= 1 {
333            return self.serial_compress_and_delete(files);
334        }
335
336        let worker_count = self.parallel_workers.min(files.len()).clamp(1, MAX_PARALLEL_COMPRESS_WORKERS);
337        if worker_count <= 1 {
338            return self.serial_compress_and_delete(files);
339        }
340
341        let compression_options = self.compression_options();
342        let started_at = Instant::now();
343        let injector = Arc::new(Injector::new());
344        for file in files {
345            injector.push(file.clone());
346        }
347
348        let mut workers = Vec::with_capacity(worker_count);
349        let mut stealers = Vec::with_capacity(worker_count);
350        for _ in 0..worker_count {
351            let worker = Worker::new_fifo();
352            stealers.push(worker.stealer());
353            workers.push(worker);
354        }
355
356        let stealers = Arc::new(stealers);
357        let steal_attempts = Arc::new(AtomicU64::new(0));
358        let steal_successes = Arc::new(AtomicU64::new(0));
359        let (tx, rx) = bounded::<CompressionTaskResult>(worker_count.saturating_mul(2).max(8));
360
361        // Spawn a fixed-size worker set in a scoped region so panics are
362        // contained and can be downgraded to a serial fallback instead of
363        // leaking detached threads.
364        let scope_result = thread::scope(|scope| {
365            for (worker_id, local_worker) in workers.into_iter().enumerate() {
366                let tx = tx.clone();
367                let injector = Arc::clone(&injector);
368                let stealers = Arc::clone(&stealers);
369                let options = compression_options.clone();
370                let attempts = Arc::clone(&steal_attempts);
371                let successes = Arc::clone(&steal_successes);
372
373                scope.spawn(move |_| {
374                    let mut seed = (worker_id as u64 + 1)
375                        .wrapping_mul(6364136223846793005)
376                        .wrapping_add(1442695040888963407);
377
378                    // Escalating spin->yield backoff for the transient windows
379                    // where work is being redistributed, instead of a hot
380                    // `continue`/`yield_now` loop that burns CPU.
381                    let backoff = Backoff::new();
382
383                    loop {
384                        // Search order: local FIFO -> global injector batch ->
385                        // random victim stealers.
386                        let task = if let Some(file) = local_worker.pop() {
387                            Some(file)
388                        } else {
389                            match injector.steal_batch_and_pop(&local_worker) {
390                                Steal::Success(file) => {
391                                    Some(file)
392                                }
393                                Steal::Retry => {
394                                    backoff.snooze();
395                                    continue;
396                                }
397                                Steal::Empty => {
398                                    let stolen = Self::steal_from_victims(
399                                        worker_id,
400                                        &local_worker,
401                                        &stealers,
402                                        &attempts,
403                                        &successes,
404                                        &mut seed,
405                                    );
406                                    // Exit only when all task sources are empty.
407                                    if stolen.is_none()
408                                        && injector.is_empty()
409                                        && local_worker.is_empty()
410                                        && stealers.iter().all(Stealer::is_empty)
411                                    {
412                                        break;
413                                    }
414                                    stolen
415                                }
416                            }
417                        };
418
419                        let Some(file) = task else {
420                            backoff.snooze();
421                            continue;
422                        };
423
424                        // Got work: reset the backoff so the next idle spell
425                        // starts from a cheap spin again.
426                        backoff.reset();
427                        let mut file = file;
428                        let compressed = match compress_file(&file.path, &options) {
429                            Ok(output) => {
430                                debug!(
431                                    event = EVENT_LOG_CLEANER_STATE,
432                                    component = LOG_COMPONENT_OBS,
433                                    subsystem = LOG_SUBSYSTEM_LOG_CLEANER,
434                                    file = ?file.path,
435                                    archive = ?output.archive_path,
436                                    algorithm = %output.algorithm_used,
437                                    input_bytes = output.input_bytes,
438                                    output_bytes = output.output_bytes,
439                                    state = "parallel_compression_done",
440                                    "log cleaner state changed"
441                                );
442                                file.projected_freed_bytes = output.input_bytes.saturating_sub(output.output_bytes);
443                                true
444                            }
445                            Err(err) => {
446                                warn!(event = EVENT_LOG_CLEANER_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, file = ?file.path, error = %err, result = "parallel_compression_failed", "log cleaner state changed");
447                                false
448                            }
449                        };
450
451                        if tx.send(CompressionTaskResult { file, compressed }).is_err() {
452                            break;
453                        }
454                    }
455                });
456            }
457            drop(tx);
458
459            let mut deletable = Vec::with_capacity(files.len());
460            for result in rx {
461                if result.compressed {
462                    deletable.push(result.file);
463                }
464            }
465
466            deletable
467        });
468
469        // Any worker panic triggers deterministic fallback behavior.
470        let deletable = match scope_result {
471            Ok(deletable) => deletable,
472            Err(_) => {
473                warn!(
474                    event = EVENT_LOG_CLEANER_STATE,
475                    component = LOG_COMPONENT_OBS,
476                    subsystem = LOG_SUBSYSTEM_LOG_CLEANER,
477                    result = "parallel_worker_panicked",
478                    fallback = "serial",
479                    "log cleaner state changed"
480                );
481                return self.serial_compress_and_delete(files);
482            }
483        };
484
485        let (deleted, freed) = self.delete_files(&deletable)?;
486        let elapsed = started_at.elapsed().as_secs_f64();
487        // NOTE on metric scope: attempts/successes count only *victim* steals
488        // (not the injector `steal_batch_and_pop`), and a multi-task stolen
489        // batch counts as a single success. So this rate reflects inter-worker
490        // rebalancing efficiency, not total task acquisition — read it as a
491        // relative health signal, not an absolute throughput measure.
492        let attempts = steal_attempts.load(Ordering::Relaxed);
493        let successes = steal_successes.load(Ordering::Relaxed);
494        let success_rate = if attempts == 0 {
495            0.0
496        } else {
497            successes as f64 / attempts as f64
498        };
499
500        // Emit post-run cleanup metrics for monitoring and alerting.
501        histogram!(METRIC_LOG_CLEANER_COMPRESS_DURATION_SECONDS).record(elapsed);
502        gauge!(METRIC_LOG_CLEANER_STEAL_SUCCESS_RATE).set(success_rate);
503
504        info!(
505            event = EVENT_LOG_CLEANER_STATE,
506            component = LOG_COMPONENT_OBS,
507            subsystem = LOG_SUBSYSTEM_LOG_CLEANER,
508            workers = worker_count,
509            algorithm = %self.compression_algorithm,
510            deleted,
511            freed,
512            duration_seconds = elapsed,
513            steal_attempts = attempts,
514            steal_successes = successes,
515            steal_success_rate = success_rate,
516            state = "parallel_cleanup_finished",
517            "log cleaner state changed"
518        );
519
520        Ok((deleted, freed))
521    }
522
523    /// Attempt to steal a task from peer workers using randomized victim order.
524    fn steal_from_victims(
525        worker_id: usize,
526        local_worker: &Worker<FileInfo>,
527        stealers: &[Stealer<FileInfo>],
528        attempts: &AtomicU64,
529        successes: &AtomicU64,
530        seed: &mut u64,
531    ) -> Option<FileInfo> {
532        if stealers.len() <= 1 {
533            return None;
534        }
535
536        // Xorshift step to randomize victim polling order and avoid convoying.
537        *seed ^= *seed << 13;
538        *seed ^= *seed >> 7;
539        *seed ^= *seed << 17;
540        let start = (*seed as usize) % stealers.len();
541
542        let steal_result = Steal::from_iter((0..stealers.len()).map(|offset| {
543            let victim = (start + offset) % stealers.len();
544            if victim == worker_id {
545                return Steal::Empty;
546            }
547            attempts.fetch_add(1, Ordering::Relaxed);
548            stealers[victim].steal_batch_and_pop(local_worker)
549        }));
550
551        match steal_result {
552            Steal::Success(file) => {
553                successes.fetch_add(1, Ordering::Relaxed);
554                Some(file)
555            }
556            Steal::Retry | Steal::Empty => None,
557        }
558    }
559
560    /// Serial fallback path and non-parallel baseline.
561    ///
562    /// This path is also used whenever the task set is too small to benefit
563    /// from worker orchestration.
564    fn serial_compress_and_delete(&self, files: &[FileInfo]) -> Result<(usize, u64), std::io::Error> {
565        let started_at = Instant::now();
566        let mut deletable = Vec::with_capacity(files.len());
567
568        if self.compress_old_files {
569            let options = self.compression_options();
570            for file in files {
571                match compress_file(&file.path, &options) {
572                    Ok(output) => {
573                        debug!(
574                            event = EVENT_LOG_CLEANER_STATE,
575                            component = LOG_COMPONENT_OBS,
576                            subsystem = LOG_SUBSYSTEM_LOG_CLEANER,
577                            file = ?file.path,
578                            archive = ?output.archive_path,
579                            algorithm = %output.algorithm_used,
580                            input_bytes = output.input_bytes,
581                            output_bytes = output.output_bytes,
582                            state = "serial_compression_done",
583                            "log cleaner state changed"
584                        );
585                        let mut file = file.clone();
586                        file.projected_freed_bytes = output.input_bytes.saturating_sub(output.output_bytes);
587                        deletable.push(file);
588                    }
589                    Err(err) => {
590                        warn!(event = EVENT_LOG_CLEANER_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, file = ?file.path, error = %err, result = "serial_compression_failed", "log cleaner state changed");
591                    }
592                }
593            }
594        } else {
595            deletable.extend(files.iter().cloned());
596        }
597
598        let (deleted, freed) = self.delete_files(&deletable)?;
599        histogram!(METRIC_LOG_CLEANER_COMPRESS_DURATION_SECONDS).record(started_at.elapsed().as_secs_f64());
600
601        Ok((deleted, freed))
602    }
603
604    /// Snapshot compression-related configuration for a single cleanup pass.
605    fn compression_options(&self) -> CompressionOptions {
606        CompressionOptions {
607            algorithm: self.compression_algorithm,
608            gzip_level: self.gzip_compression_level,
609            zstd_level: self.zstd_compression_level,
610            zstd_workers: self.zstd_workers,
611            zstd_fallback_to_gzip: self.zstd_fallback_to_gzip,
612            dry_run: self.dry_run,
613        }
614    }
615
616    /// Delete a file while refusing symlinks and accommodating platform quirks.
617    fn secure_delete(&self, path: &PathBuf) -> std::io::Result<()> {
618        let meta = std::fs::symlink_metadata(path)?;
619        if meta.file_type().is_symlink() {
620            return Err(std::io::Error::new(
621                std::io::ErrorKind::InvalidData,
622                format!("Security: refusing to delete symlink: {:?}", path),
623            ));
624        }
625
626        #[cfg(windows)]
627        {
628            // Retry removes to mitigate transient handle races from external
629            // scanners/AV software.
630            let mut last_err: Option<std::io::Error> = None;
631            for _ in 0..3 {
632                match std::fs::remove_file(path) {
633                    Ok(()) => return Ok(()),
634                    Err(err) => {
635                        last_err = Some(err);
636                        std::thread::sleep(Duration::from_millis(20));
637                    }
638                }
639            }
640            if let Some(err) = last_err {
641                return Err(err);
642            }
643            Ok(())
644        }
645
646        #[cfg(not(windows))]
647        {
648            std::fs::remove_file(path)
649        }
650    }
651
652    /// Delete the supplied files and return `(deleted_count, freed_bytes)`.
653    ///
654    /// In dry-run mode the returned counters still reflect the projected work
655    /// so callers and metrics can report what would have happened.
656    pub(super) fn delete_files(&self, files: &[FileInfo]) -> Result<(usize, u64), std::io::Error> {
657        let mut deleted = 0usize;
658        let mut freed = 0u64;
659
660        for f in files {
661            if self.dry_run {
662                info!(event = EVENT_LOG_CLEANER_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, state = "dry_run_delete", file = ?f.path, bytes = f.size, "log cleaner state changed");
663                deleted += 1;
664                freed += f.projected_freed_bytes;
665                continue;
666            }
667
668            match self.secure_delete(&f.path) {
669                Ok(()) => {
670                    deleted += 1;
671                    freed += f.projected_freed_bytes;
672                    debug!(event = EVENT_LOG_CLEANER_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, state = "deleted", file = ?f.path, bytes = f.size, projected_freed_bytes = f.projected_freed_bytes, "log cleaner state changed");
673                }
674                Err(e) => {
675                    error!(event = EVENT_LOG_CLEANER_STATE, component = LOG_COMPONENT_OBS, subsystem = LOG_SUBSYSTEM_LOG_CLEANER, result = "delete_failed", file = ?f.path, error = %e, "log cleaner state changed");
676                }
677            }
678        }
679
680        // Durability: persist the directory entries so the unlinks cannot be
681        // reordered ahead of the archive data that justified them. Best-effort;
682        // opening a directory as a file is not portable (e.g. Windows).
683        if !self.dry_run
684            && deleted > 0
685            && let Ok(dir) = std::fs::File::open(&self.log_dir)
686        {
687            let _ = dir.sync_all();
688        }
689
690        Ok((deleted, freed))
691    }
692}
693
694/// Builder for [`LogCleaner`].
695///
696/// The builder keeps startup code readable when an application only needs to
697/// override a subset of retention knobs.
698pub struct LogCleanerBuilder {
699    log_dir: PathBuf,
700    file_pattern: String,
701    active_filename: String,
702    match_mode: FileMatchMode,
703    keep_files: usize,
704    max_total_size_bytes: u64,
705    max_single_file_size_bytes: u64,
706    compress_old_files: bool,
707    gzip_compression_level: u32,
708    compressed_file_retention_days: u64,
709    exclude_patterns: Vec<String>,
710    delete_empty_files: bool,
711    min_file_age_seconds: u64,
712    dry_run: bool,
713    compression_algorithm: CompressionAlgorithm,
714    parallel_compress: bool,
715    parallel_workers: usize,
716    zstd_compression_level: i32,
717    zstd_fallback_to_gzip: bool,
718    zstd_workers: usize,
719}
720
721impl LogCleanerBuilder {
722    /// Create a builder with conservative defaults.
723    pub fn new(log_dir: impl Into<PathBuf>, file_pattern: impl Into<String>, active_filename: impl Into<String>) -> Self {
724        Self {
725            log_dir: log_dir.into(),
726            file_pattern: file_pattern.into(),
727            active_filename: active_filename.into(),
728            match_mode: FileMatchMode::Prefix,
729            keep_files: DEFAULT_LOG_KEEP_FILES,
730            max_total_size_bytes: 0,
731            max_single_file_size_bytes: 0,
732            compress_old_files: false,
733            gzip_compression_level: 6,
734            compressed_file_retention_days: 0,
735            exclude_patterns: Vec::new(),
736            delete_empty_files: false,
737            min_file_age_seconds: 0,
738            dry_run: false,
739            compression_algorithm: CompressionAlgorithm::default(),
740            parallel_compress: true,
741            parallel_workers: default_parallel_workers(),
742            zstd_compression_level: 8,
743            zstd_fallback_to_gzip: true,
744            zstd_workers: 1,
745        }
746    }
747
748    /// Configure whether `file_pattern` is matched as a prefix or suffix.
749    pub fn match_mode(mut self, match_mode: FileMatchMode) -> Self {
750        self.match_mode = match_mode;
751        self
752    }
753
754    /// Keep at most this many newest regular log files.
755    pub fn keep_files(mut self, keep_files: usize) -> Self {
756        self.keep_files = keep_files;
757        self
758    }
759
760    /// Cap the aggregate size of retained regular log files.
761    pub fn max_total_size_bytes(mut self, max_total_size_bytes: u64) -> Self {
762        self.max_total_size_bytes = max_total_size_bytes;
763        self
764    }
765
766    /// Cap the size of any individual regular log file.
767    pub fn max_single_file_size_bytes(mut self, max_single_file_size_bytes: u64) -> Self {
768        self.max_single_file_size_bytes = max_single_file_size_bytes;
769        self
770    }
771
772    /// Enable archival compression before deleting selected source logs.
773    pub fn compress_old_files(mut self, compress_old_files: bool) -> Self {
774        self.compress_old_files = compress_old_files;
775        self
776    }
777
778    /// Set the gzip compression level used for gzip output or gzip fallback.
779    pub fn gzip_compression_level(mut self, gzip_compression_level: u32) -> Self {
780        self.gzip_compression_level = gzip_compression_level;
781        self
782    }
783
784    /// Set how long compressed archives may remain on disk.
785    pub fn compressed_file_retention_days(mut self, days: u64) -> Self {
786        self.compressed_file_retention_days = days;
787        self
788    }
789
790    /// Exclude files matching these glob patterns from every cleanup pass.
791    pub fn exclude_patterns(mut self, patterns: Vec<String>) -> Self {
792        self.exclude_patterns = patterns;
793        self
794    }
795
796    /// Allow the scanner to remove matching zero-byte regular logs immediately.
797    pub fn delete_empty_files(mut self, delete_empty_files: bool) -> Self {
798        self.delete_empty_files = delete_empty_files;
799        self
800    }
801
802    /// Require regular log files to be at least this old before processing.
803    pub fn min_file_age_seconds(mut self, seconds: u64) -> Self {
804        self.min_file_age_seconds = seconds;
805        self
806    }
807
808    /// Enable dry-run mode for scans, compression decisions, and deletion.
809    pub fn dry_run(mut self, dry_run: bool) -> Self {
810        self.dry_run = dry_run;
811        self
812    }
813
814    /// Set the preferred compression algorithm explicitly.
815    pub fn compression_algorithm(mut self, algorithm: CompressionAlgorithm) -> Self {
816        self.compression_algorithm = algorithm;
817        self
818    }
819
820    /// Parse and set the compression algorithm from configuration text.
821    pub fn compression_algorithm_str(mut self, algorithm: impl AsRef<str>) -> Self {
822        self.compression_algorithm = CompressionAlgorithm::from_config_str(algorithm.as_ref());
823        self
824    }
825
826    /// Enable or disable the parallel work-stealing compression path.
827    pub fn parallel_compress(mut self, enabled: bool) -> Self {
828        self.parallel_compress = enabled;
829        self
830    }
831
832    /// Set the number of compression workers, clamped to at least one.
833    pub fn parallel_workers(mut self, workers: usize) -> Self {
834        self.parallel_workers = workers.max(1);
835        self
836    }
837
838    /// Set the zstd compression level.
839    pub fn zstd_compression_level(mut self, level: i32) -> Self {
840        self.zstd_compression_level = level;
841        self
842    }
843
844    /// Retry compression with gzip when zstd encoding fails.
845    pub fn zstd_fallback_to_gzip(mut self, enabled: bool) -> Self {
846        self.zstd_fallback_to_gzip = enabled;
847        self
848    }
849
850    /// Set the number of internal worker threads requested from zstd.
851    pub fn zstd_workers(mut self, workers: usize) -> Self {
852        self.zstd_workers = workers.max(1);
853        self
854    }
855
856    /// Finalize the builder into an immutable [`LogCleaner`].
857    ///
858    /// Invalid glob patterns are ignored rather than failing construction, and
859    /// codec-related numeric values are clamped into safe ranges.
860    pub fn build(self) -> LogCleaner {
861        // Defense-in-depth for the active-file guard: the scanner protects the
862        // live log by exact filename equality against `active_filename`. An
863        // empty value silently disables that protection, so a non-empty
864        // `file_pattern` could then make the live log a deletion candidate.
865        // Warn instead of failing so misuse of the public builder is visible.
866        if self.active_filename.trim().is_empty() && !self.file_pattern.trim().is_empty() {
867            warn!(
868                event = EVENT_LOG_CLEANER_STATE,
869                component = LOG_COMPONENT_OBS,
870                subsystem = LOG_SUBSYSTEM_LOG_CLEANER,
871                result = "empty_active_filename",
872                "active log filename is empty; the active-file exclusion is disabled and the live log may become a deletion candidate"
873            );
874        }
875
876        // Surface, rather than silently drop, invalid exclude globs: a dropped
877        // pattern turns "protect this file" into "delete this file", so an
878        // operator's typo (or a literal comma splitting a char-class) must be
879        // visible instead of failing open.
880        let mut patterns = Vec::new();
881        for raw in self.exclude_patterns {
882            match glob::Pattern::new(&raw) {
883                Ok(pattern) => patterns.push(pattern),
884                Err(err) => warn!(
885                    event = EVENT_LOG_CLEANER_STATE,
886                    component = LOG_COMPONENT_OBS,
887                    subsystem = LOG_SUBSYSTEM_LOG_CLEANER,
888                    result = "invalid_exclude_pattern",
889                    pattern = %raw,
890                    error = %err,
891                    "log cleaner state changed"
892                ),
893            }
894        }
895
896        LogCleaner {
897            log_dir: self.log_dir,
898            file_pattern: self.file_pattern,
899            active_filename: self.active_filename,
900            match_mode: self.match_mode,
901            keep_files: self.keep_files,
902            max_total_size_bytes: self.max_total_size_bytes,
903            max_single_file_size_bytes: self.max_single_file_size_bytes,
904            compress_old_files: self.compress_old_files,
905            // gzip level 0 is a valid "store" (no compression) mode, so keep the
906            // lower bound at 0 rather than silently bumping it to 1.
907            gzip_compression_level: self.gzip_compression_level.clamp(0, 9),
908            compressed_file_retention_days: self.compressed_file_retention_days,
909            exclude_patterns: patterns,
910            delete_empty_files: self.delete_empty_files,
911            min_file_age_seconds: self.min_file_age_seconds,
912            dry_run: self.dry_run,
913            compression_algorithm: self.compression_algorithm,
914            parallel_compress: self.parallel_compress,
915            parallel_workers: self.parallel_workers.max(1),
916            // zstd level 0 means "codec default"; the real maximum is 22, not
917            // 21, so preserve both boundaries instead of silently narrowing.
918            zstd_compression_level: self.zstd_compression_level.clamp(0, 22),
919            zstd_fallback_to_gzip: self.zstd_fallback_to_gzip,
920            zstd_workers: self.zstd_workers.max(1),
921        }
922    }
923}
924
925#[cfg(test)]
926mod tests {
927    use super::{MAX_RETENTION_DAYS_BEFORE_SATURATION, SECONDS_PER_DAY, compressed_file_retention_window};
928    use std::time::Duration;
929
930    #[test]
931    fn compressed_file_retention_window_scales_days_without_wrap() {
932        assert_eq!(compressed_file_retention_window(3), Duration::from_secs(3 * SECONDS_PER_DAY));
933    }
934
935    #[test]
936    fn compressed_file_retention_window_saturates_on_large_values() {
937        assert_eq!(compressed_file_retention_window(u64::MAX), Duration::from_secs(u64::MAX));
938    }
939
940    #[test]
941    fn retention_day_saturation_boundary_is_safe() {
942        assert_eq!(
943            compressed_file_retention_window(MAX_RETENTION_DAYS_BEFORE_SATURATION),
944            Duration::from_secs(MAX_RETENTION_DAYS_BEFORE_SATURATION * SECONDS_PER_DAY)
945        );
946        assert_eq!(
947            compressed_file_retention_window(MAX_RETENTION_DAYS_BEFORE_SATURATION.saturating_add(1)),
948            Duration::from_secs(u64::MAX)
949        );
950    }
951}