HUB
Sign inSign up

jmrenouard/filecleaner

By jmrenouard

•Updated 9 days ago

Deterministic Rust directory retention engine with backup guardrails, hooks & daemon

Image
0

413

jmrenouard/filecleaner repository overview

FileCleaner — Deterministic Rust Retention Engine
FileCleaner Emblem

⁠FileCleaner — Deterministic Rust Retention, Backup-Guard & Lifecycle Engine

Stop trusting fragile find ... -delete one-liners and platform-locked logrotate jobs with critical backups and live spools: FileCleaner enforces a fail-closed 6-phase retention pipeline with dead-man's-switch backup guardrails, a 6-layer active-writer detection matrix, shell-injection-free pre-delete hooks, pure-Rust atomic transforms, and a cross-platform daemon.


⁠Table of Contents

  1. Documentation & Governance Hub⁠
  2. Why FileCleaner?⁠
  3. Architecture: The Fail-Closed 6-Phase Pipeline⁠
  4. Feature & Multi-Probe Matrix⁠
  5. CLI Quickstart (init, validate, plan, run, check-in-use, daemon)⁠
  6. Configuration Examples (TOML & YAML)⁠
  7. 9-Target Cross-Compilation Matrix⁠
  8. Contributing & Engineering Governance⁠

⁠Documentation & Governance Hub


⁠Why FileCleaner?

Traditional cleanup cron scripts and ad-hoc rotation utilities routinely cause silent production outages through four structural failure modes:

Production Failure ModeFragile find / Shell / logrotate BehaviorFileCleaner v1.0.1 Guarantee
The Silent Stale-Backup WipeWhen a pg_dump or mysqldump job fails silently for two weeks, find -mtime +14 -delete deletes the last surviving valid backup, leaving an empty vault or 0-byte error stubs.Backup Safety Guards: Filters out corrupt stubs below min_valid_backup_bytes, locks the newest min_keep_files floor, and triggers a staleness dead-man's-switch freeze (require_newer_within / freeze_if_newest_older_than) when no fresh valid backup exists.
Mid-Write File Truncation & CorruptionCron sweeps unlink or move incoming transfers, rotating logs, or dumps still held open by rsync, tar, mysqldump, or an application process.6-Layer In-Use Detection Matrix: Combines sidecar lock/temp suffixes, Unix flock(LOCK_EX | LOCK_NB), Linux /proc/*/fd inode matching, Windows share_mode(0), min_idle_age cooldown, and a batched two-point (size, mtime) stability window.
Dry-Run Drift & Non-Atomic MovesPreview scripts diverge from live execution, cross-filesystem mv leaves half-written files on power loss, and shell hooks (sh -c) break or inject commands on special characters in filenames.Strict Dry-Run Parity & Atomic Staging: plan and run --dry-run compute the identical SweepPlan; transforms write to .fc-tmp with sync_all(), restore mtime, verify SHA-256 on cross-FS move, and run hooks via direct Command::new (argv, never a shell).
Windows / macOS / musl Portability GapsGNU find, lsof, and logrotate scripts break across Linux containers, macOS workstations, and Windows servers or require fragile C -sys toolchain dependencies.100% Pure-Rust Single Binary: Zero C -sys bindings (miniz_oxide, lz4_flex, brotli, pure-Rust zip, sha2, notify), compiling deterministically across 9 Linux, macOS, and Windows targets.

⁠Architecture: The Fail-Closed 6-Phase Pipeline

Every filecleaner run, filecleaner plan, and daemon sweep processes each enabled rule through six strictly ordered, fail-closed phases:

flowchart LR
    P1["1. Scan & Sort<br/>walkdir + filters<br/>TimeBasis ordering"] --> P2["2. InUseProbe<br/>6-layer lock matrix<br/>Partition S_busy"]
    P2 --> P3["3. BackupGuard<br/>min_valid_backup_bytes<br/>Staleness freeze + floor"]
    P3 --> P4["4. RetentionEval<br/>max_files / max_age / size<br/>Deterministic SweepPlan"]
    P4 --> P5["5. PreHook<br/>Direct argv + FILECLEANER_*<br/>Exit 0 / 42 / policy"]
    P5 --> P6["6. Action Pipeline<br/>Atomic .fc-tmp + SHA-256<br/>Or zero-mutation DryRun"]
    P6 --> AUD["JSONL Audit Log<br/>& Daemon State JSON"]
  1. Safety Invariants Always Win: InUseProbe ($S_{\text{busy}}$) and BackupGuard ($P_{\text{floor}}$ and staleness freezes) execute before retention pruning and cannot be overridden by max_files, max_age, or max_total_size. If safety guards prevent meeting a cap, the rule finishes cleanly as Constrained (with structured diagnostics, optional strict exit code 3 via --strict-constraints).
  2. Fail-Closed Defaults: Symbolic links are skipped (follow_symlinks = false), internal *.fc-tmp* staging files are excluded, unparseable filename_date names are skipped rather than deleted, and missing Created (birthtime) support errors explicitly rather than silently falling back to mtime.

⁠Feature & Multi-Probe Matrix

⁠6-Layer In-Use File Detection Matrix (in_use)
LayerMechanismOS ScopeWhat It Catches
1Sidecar & Temp-Suffix MarkersLinux, macOS, WindowsFiles ending in .lock, .lck, .part, .tmp, .processing or accompanied by <file><suffix> sidecars.
2Advisory File Lock (flock)Unix (Linux, macOS)Cooperative exclusive/shared flock(LOCK_EX | LOCK_NB) holders via O_RDONLY without altering mtime.
3Open Descriptor Scan (/proc/*/fd)LinuxUn-flocked active writers (pg_dump, mysqldump, rsync, app loggers) matched by (st_dev, st_ino).
4Exclusive Share-Mode ProbeWindowsAny external open handle incompatible with share_mode(0) (ERROR_SHARING_VIOLATION / ERROR_LOCK_VIOLATION).
5Minimum Idle Age (min_idle_age)Linux, macOS, WindowsFiles modified too recently (now - mtime < min_idle_age) or with future-skewed timestamps.
6Two-Point Stability WindowLinux, macOS, WindowsFiles actively growing or changing (size, mtime) across a single batched stability_window wait.
⁠Retention, Guardrails, Hooks & Transforms
SubsystemCapabilities
Selection & Time BasisGlob & Rust regex include/exclude filters, min_file_size / max_file_size, recursive + max_depth, follow_symlinks = false default, modified / created / filename_date (regex + chrono strftime).
Retention Policiesmax_files, max_age, max_total_size, combine_mode (any | all), eviction_order (oldest_first | largest_first), human byte units (B, KB/KiB..PB/PiB), human durations (ms, s, m, h, d, w).
Backup Guardrailsmin_keep_files, min_valid_backup_bytes (excludes corrupt/0-byte stubs), require_newer_within (dead-man's-switch), freeze_if_newest_older_than, freeze_on_empty_valid.
Pre-Delete HooksDirect Command::new (argv token expansion {path}, {name}, {size}, {mtime_iso}, {rule}), FILECLEANER_* env vars, timeout kill/reap, exit 42 benign veto (skip_exit_code), abort_file / abort_rule / warn_and_continue.
Lifecycle ActionsComposable ordered pipelines: rename_by_date, compress (pure-Rust gzip, lz4, brotli, zip), move (atomic rename + cross-FS SHA-256 verification + move_date_subdir), copy_truncate (explicit opt-in), trash, delete.
Daemon & Observabilityinterval, notify (debounced FS watcher), and hybrid modes; atomic PID, live JSON state_file, cooperative stop_file, SIGINT/SIGTERM graceful shutdown, --max-sweeps, systemd/launchd/windows-task templates, and synchronous JSONL audit logs.

⁠CLI Quickstart

⁠Install from Prebuilt Release, Cargo, or Docker Hub
# Option 1: Run multi-arch container directly from Docker Hub (linux/amd64 & linux/arm64)
docker run --rm jmrenouard/filecleaner:latest --version
docker run --rm -v "$(pwd)/data:/data" jmrenouard/filecleaner:latest plan --dir /data --max-age 14d

# Option 2: Build & install with Cargo (Rust >= 1.75 / Edition 2021)
cargo install --git https://github.com/jmrenouard/FileCleaner --tag v1.0.1 --locked

# Option 3: Download a prebuilt archive from GitHub Releases (example: Linux x86_64 musl)
curl -LO https://github.com/jmrenouard/FileCleaner/releases/download/v1.0.1/filecleaner-v1.0.1-x86_64-unknown-linux-musl.tar.gz
tar -xzf filecleaner-v1.0.1-x86_64-unknown-linux-musl.tar.gz
sudo install -m 0755 filecleaner /usr/local/bin/filecleaner
⁠Day-1 Safe Workflow (init $\rightarrow$ validate $\rightarrow$ plan $\rightarrow$ run)
# 1. Generate a safe annotated starter config (profiles: backups | logs | spool; dry_run = true)
filecleaner init --output filecleaner.toml --profile backups --format toml

# 2. Validate TOML/YAML syntax, regex/globs, units, and all INV-CFG-* safety invariants
filecleaner validate filecleaner.toml

# 3. Preview exact deterministic decisions (strictly read-only, zero mutations)
filecleaner plan -c filecleaner.toml --json

# Or run ad-hoc directly on a folder without writing a config file first:
filecleaner plan --dir /var/backups/postgres --include "*.sql" --max-age 14d --min-keep 3 --compress gzip

# 4. Probe one or more active files across all 6 in-use layers (exit 0 = safe, exit 10 = busy)
filecleaner check-in-use /var/backups/postgres/pg_20261120_020000.sql --idle-age 10s --stability 2s

# 5. Execute a live sweep (alias: `clean`; escalate freezes/constraints to exit 3 for monitoring)
filecleaner run -c filecleaner.toml --fail-on-freeze --strict-constraints

# 6. Run as a managed daemon or generate an OS service unit
filecleaner daemon run -c filecleaner.toml --mode hybrid
filecleaner daemon status -c filecleaner.toml --json
filecleaner daemon stop -c filecleaner.toml --timeout 30s
filecleaner daemon service-template --init-system systemd -c /etc/filecleaner/filecleaner.toml

Zero-config quick one-liner (preview before live cleanup, no config file required):

filecleaner plan --dir /var/log/app --include "*.log" --max-age 14d
filecleaner run --dir /var/log/app --include "*.log" --max-age 14d

Start with the 5-Minute HOWTO⁠ for copy-paste one-liners, backup_guard recipes, and Bash/PowerShell hooks, see the User Guide⁠ for every CLI flag and exit code (0, 1, 2, 3, 4, 10), and check the Cookbook Examples⁠ for production deployments. Note: plan / --dry-run acquires non-exclusive checks and generated files use strict 0600 Unix permissions.


⁠Configuration Examples (TOML & YAML)

Both .toml and .yaml/.yml are supported natively and auto-detected by file extension.

⁠TOML (filecleaner.toml)
dry_run = false
global_trash_dir = "/var/tmp/filecleaner-trash"

[daemon]
mode = "hybrid"
interval = "5m"
watch = true
debounce = "2s"
sweep_on_start = true
pid_file = "/run/filecleaner/filecleaner.pid"
state_file = "/run/filecleaner/state.json"
stop_file = "/run/filecleaner/filecleaner.stop"

[audit]
log_path = "/var/log/filecleaner/audit.jsonl"
jsonl = true

[[rules]]
name = "pg-backups"
path = "/var/backups/postgres"
recursive = true
max_depth = 2
follow_symlinks = false
include_globs = ["*.sql", "*.sql.gz", "*.dump"]
exclude_globs = ["pinned/**"]
min_file_size = "1KiB"
time_basis = "filename_date"
filename_date_regex = 'pg_(\d{8}_\d{6})'
filename_date_format = "%Y%m%d_%H%M%S"
max_files = 14
max_age = "30d"
max_total_size = "50GiB"
combine_mode = "any"
eviction_order = "oldest_first"
actions = ["compress", "move"]
compression = "gzip"
compress_remove_source = true
compress_overwrite = false
move_to = "/mnt/cold-archive/postgres"
move_date_subdir = "%Y/%m"
move_overwrite = false

[rules.backup_guard]
enabled = true
min_keep_files = 3
min_valid_backup_bytes = "1MiB"
require_newer_within = "36h"
freeze_on_empty_valid = true

[rules.in_use]
enabled = true
min_idle_age = "10s"
stability_window = "2s"

[rules.pre_delete_hook]
command = "/usr/local/bin/verify-offsite-copy"
args = ["--file", "{path}", "--rule", "{rule}"]
timeout = "15s"
on_failure = "abort_file"
skip_exit_code = 42
run_in_dry_run = false
⁠YAML (filecleaner.yaml)
dry_run: true

daemon:
  mode: interval
  interval: 10m
  watch: false
  debounce: 2s
  sweep_on_start: true

audit:
  log_path: /var/log/filecleaner/audit.jsonl
  jsonl: true

rules:
  - name: app-logs
    path: /var/log/myapp
    recursive: false
    dry_run: true
    include_globs:
      - "*.log"
    time_basis: modified
    max_age: 7d
    max_total_size: 2GiB
    combine_mode: any
    eviction_order: oldest_first
    in_use:
      enabled: true
      check_os_locks: false
      check_proc_fd: false
      min_idle_age: 5s
      stability_window: 0s
    actions:
      - copy_truncate
    copy_truncate_to: /var/log/myapp/rotated
    compression: lz4

⁠9-Target Cross-Compilation Matrix

FileCleaner depends exclusively on pure-Rust crates (miniz_oxide, lz4_flex, brotli, zip pure-Rust deflate, sha2), requiring zero C/C++ -sys libraries or external cross-compilers across all 9 official release targets:

Operating SystemArchitectureTarget TripleArtifact FormatNotes
Linuxx86_64x86_64-unknown-linux-gnu.tar.gzStandard glibc Linux servers (cargo-zigbuild)
Linux (Static)x86_64x86_64-unknown-linux-musl.tar.gzZero-dependency static binary for Alpine/scratch containers
LinuxARM64aarch64-unknown-linux-gnu.tar.gzAWS Graviton, Ampere, Raspberry Pi OS 64-bit
Linux (Static)ARM64aarch64-unknown-linux-musl.tar.gzStatic ARM64 containers & embedded appliances
Linux (Hard-Float)ARMv7armv7-unknown-linux-gnueabihf.tar.gz32-bit ARM SBCs & industrial gateways
Windowsx86_64x86_64-pc-windows-msvc.zipNative Windows Server & Windows 10/11 (MSVC)
WindowsARM64aarch64-pc-windows-msvc.zipWindows on ARM64 (MSVC)
macOSApple Siliconaarch64-apple-darwin.tar.gzM1/M2/M3/M4 Macs
macOSIntel x86_64x86_64-apple-darwin.tar.gzIntel Macs (macOS 12+)

⁠Contributing & Engineering Governance

All FileCleaner changes follow strict engineering traceability and verified quality gates (Issue #20 / branch feat/issue-20-audit-tests-simple-howto baseline: cargo fmt --all -- --check clean, cargo clippy --all-targets -- -D warnings 0 warnings across Linux/Windows/macOS targets, 124 tests passed [64 unit + 60 integration across 9 suites], and 94.31% line coverage / 92.45% region coverage across 9,098 lines via cargo llvm-cov --fail-under-lines 90 with every src/*.rs module >= 90.21%):

Licensed under the Apache License 2.0⁠.

Tag summary

Content type

Image

Digest

sha256:d1da40a32…

Size

29.5 MB

Last updated

9 days ago

docker pull jmrenouard/filecleaner