""" scripts/rpa/common/worker_disk_cleanup.py 用途:RPA Worker 本机磁盘保留清理,防止 logs / 归档 trigger / drop 归档 / 孤儿临时 Profile 长期堆积撑爆盘符。 依赖:rpa_common.env、pathlib、shutil、time。 逻辑:由 inventory(及可复用的 receipt)Worker 主循环周期调用;只删超过保留期的归档与临时物, 绝不删除进行中的 trigger 根目录 JSON、可复用会话 Profile(*_session)、以及活跃 cleanup 队列。 """ from __future__ import annotations import sys as _sys from pathlib import Path as _Path _RPA_ROOT = next( ( _c for _c in _Path(__file__).resolve().parents if (_c / "connectors").is_dir() and (_c / "common").is_dir() and (_c / "inventory").is_dir() and (_c / "receipt").is_dir() ), None, ) if _RPA_ROOT is not None: for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"): _dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel) if _dir not in _sys.path: _sys.path.insert(0, _dir) import shutil import time from datetime import UTC, datetime from pathlib import Path from typing import Callable from rpa_common import env as _env _PROTECTED_DROP_DIRNAMES = frozenset( { "processed", ".hxops_quarantine", ".cleanup_queue", ".cleanup_failed", ".hxops_rpa_shared_mount", } ) _DROP_ROOT_SUFFIXES = frozenset({".xlsx", ".xls", ".csv", ".hxops_consumed"}) _TRIGGER_ARCHIVE_DIRNAMES = ("processed", "failed") # 一次性运行 Profile 前缀:库存 Worker 用 run_*,收料 Worker 用 receipt_*, # 两者均为浏览器崩溃/异常中断后可能残留的临时目录,超期统一清理。 _RUNTIME_PROFILE_TEMP_PREFIXES = ("run_", "receipt_") _DEFAULT_RETENTION_DAYS = 7 _DEFAULT_INTERVAL_SECONDS = 3600 _DEFAULT_ORPHAN_PROFILE_HOURS = 24 class DiskCleanupStats: """单次清理统计,便于日志汇总与单测断言。""" def __init__(self) -> None: self.deleted_files = 0 self.deleted_dirs = 0 self.skipped = 0 self.errors = 0 self.details: list[str] = [] def record_file(self, path: Path) -> None: self.deleted_files += 1 self.details.append(f"file:{path}") def record_dir(self, path: Path) -> None: self.deleted_dirs += 1 self.details.append(f"dir:{path}") def record_error(self, path: Path, exc: BaseException) -> None: self.errors += 1 self.details.append(f"error:{path}:{type(exc).__name__}") def retention_days() -> int: """ 读取归档保留天数。 核心逻辑:`SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS`,默认 7; `<=0` 表示禁用按天清理(仍可单独清理孤儿临时 Profile,见 orphan 配置)。 Returns: int: 保留天数;禁用时为 0。 """ return _int_env("SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS", _DEFAULT_RETENTION_DAYS, min_value=0) def cleanup_interval_seconds() -> int: """ 读取清理周期秒数。 核心逻辑:`SHIPPING_NOTICE_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS`,默认 3600; 最小值 60,避免主循环过于频繁扫盘。 Returns: int: 清理间隔秒数。 """ return _int_env( "SHIPPING_NOTICE_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS", _DEFAULT_INTERVAL_SECONDS, min_value=60, ) def orphan_profile_max_age_seconds() -> int: """ 读取孤儿临时 Profile(run_* / receipt_*)最大存活秒数。 核心逻辑:`SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS`,默认 24; `<=0` 禁用孤儿 Profile 清理。会话复用目录(*_session)永不删除。 Returns: int: 最大存活秒数;禁用时为 0。 """ hours = _int_env( "SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", _DEFAULT_ORPHAN_PROFILE_HOURS, min_value=0, ) return hours * 3600 def _int_env(name: str, default: int, *, min_value: int = 0) -> int: """读取整数环境变量;非法值回退默认,并钳制下限。""" try: value = int(_env(name, str(default)) or str(default)) except ValueError: return default return max(value, min_value) def _mtime_unix(path: Path) -> float | None: """读取 mtime;失败返回 None。""" try: return path.stat().st_mtime except OSError: return None def _is_older_than(path: Path, *, cutoff_unix: float) -> bool: """路径 mtime 早于 cutoff 时视为过期。""" mtime = _mtime_unix(path) if mtime is None: return False return mtime < cutoff_unix def _safe_unlink(path: Path, stats: DiskCleanupStats) -> None: """best-effort 删除文件。""" try: if path.is_file() or path.is_symlink(): path.unlink(missing_ok=True) stats.record_file(path) else: stats.skipped += 1 except OSError as exc: stats.record_error(path, exc) def _safe_rmtree(path: Path, stats: DiskCleanupStats) -> None: """best-effort 删除目录树。""" try: if path.is_dir(): shutil.rmtree(path, ignore_errors=False) stats.record_dir(path) else: stats.skipped += 1 except OSError as exc: stats.record_error(path, exc) def cleanup_files_older_than( directory: Path, *, cutoff_unix: float, stats: DiskCleanupStats, recursive: bool = False, name_predicate: Callable[[Path], bool] | None = None, suffix_allowlist: frozenset[str] | None = None, ) -> None: """ 删除目录中超过 cutoff 的文件(可选递归、文件名/后缀过滤)。 核心逻辑:只处理普通文件;目录本身不删(由调用方决定是否 rmtree)。 匹配失败或权限错误计入 stats,不中断整轮清理。 Args: directory: 目标目录;不存在则跳过。 cutoff_unix: 早于此 Unix 时间戳的文件可删。 stats: 累计统计。 recursive: 是否递归子目录。 name_predicate: 可选文件名过滤;返回 False 则跳过。 suffix_allowlist: 可选后缀白名单(小写,含点);None 表示不限制。 """ if not directory.is_dir(): return iterator = directory.rglob("*") if recursive else directory.iterdir() for path in iterator: try: if not path.is_file(): continue except OSError as exc: stats.record_error(path, exc) continue if name_predicate is not None and not name_predicate(path): stats.skipped += 1 continue if suffix_allowlist is not None and path.suffix.lower() not in suffix_allowlist: # 兼容 sidecar:`.xlsx.hxops_consumed` 的 suffix 是 `.hxops_consumed` if path.name.endswith(".hxops_consumed") and ".hxops_consumed" in suffix_allowlist: pass else: stats.skipped += 1 continue if not _is_older_than(path, cutoff_unix=cutoff_unix): stats.skipped += 1 continue _safe_unlink(path, stats) def cleanup_trigger_archives(trigger_dir: Path | None, *, cutoff_unix: float, stats: DiskCleanupStats) -> None: """ 清理 trigger 下 processed/failed 归档 JSON。 核心逻辑:绝不触碰 trigger 根目录进行中的 `*.json`。 """ if trigger_dir is None or not trigger_dir.is_dir(): return for dirname in _TRIGGER_ARCHIVE_DIRNAMES: cleanup_files_older_than( trigger_dir / dirname, cutoff_unix=cutoff_unix, stats=stats, recursive=False, suffix_allowlist=frozenset({".json"}), ) def cleanup_drop_archives(drop_dir: Path | None, *, cutoff_unix: float, stats: DiskCleanupStats) -> None: """ 清理 drop 区归档与隔离目录,以及根目录过期导出文件。 核心逻辑: - 清理 `processed` / `.hxops_quarantine` / `.cleanup_failed` 中过期文件; - 清理 drop 根目录过期的 Excel/CSV 与 `.hxops_consumed` sidecar; - 不碰 `.cleanup_queue`(活跃重试队列)。 """ if drop_dir is None or not drop_dir.is_dir(): return for dirname in ("processed", ".hxops_quarantine", ".cleanup_failed"): cleanup_files_older_than( drop_dir / dirname, cutoff_unix=cutoff_unix, stats=stats, recursive=False, ) # [STEP 1] drop 根:仅清理导出产物与消费标记,跳过受保护子目录与其它文件 for path in drop_dir.iterdir(): try: if path.is_dir(): if path.name in _PROTECTED_DROP_DIRNAMES or path.name.startswith("."): stats.skipped += 1 continue if not path.is_file(): continue except OSError as exc: stats.record_error(path, exc) continue suffix = path.suffix.lower() is_consumed_sidecar = path.name.endswith(".hxops_consumed") if suffix not in _DROP_ROOT_SUFFIXES and not is_consumed_sidecar: stats.skipped += 1 continue if not _is_older_than(path, cutoff_unix=cutoff_unix): stats.skipped += 1 continue _safe_unlink(path, stats) def cleanup_upload_queue(queue_dir: Path | None, *, cutoff_unix: float, stats: DiskCleanupStats) -> None: """ 清理 upload_queue 中过期文件。 核心逻辑:待上传文件正常应在数分钟内被消费;超过保留期视为残留,可删。 """ if queue_dir is None or not queue_dir.is_dir(): return cleanup_files_older_than(queue_dir, cutoff_unix=cutoff_unix, stats=stats, recursive=False) def cleanup_log_backups(log_file: Path | None, *, cutoff_unix: float, stats: DiskCleanupStats) -> None: """ 清理 worker 日志轮转备份(worker.log.1 / .2 ...)。 核心逻辑:不删当前 `worker.log`(由大小轮转负责);只删过期备份。 """ if log_file is None: return parent = log_file.parent if not parent.is_dir(): return prefix = f"{log_file.name}." for path in parent.iterdir(): try: if not path.is_file(): continue except OSError as exc: stats.record_error(path, exc) continue if path.name == log_file.name: stats.skipped += 1 continue if not path.name.startswith(prefix): continue suffix = path.name[len(prefix) :] if not suffix.isdigit(): continue if not _is_older_than(path, cutoff_unix=cutoff_unix): stats.skipped += 1 continue _safe_unlink(path, stats) def cleanup_orphan_runtime_profiles( profile_root: Path | None, *, cutoff_unix: float, stats: DiskCleanupStats, ) -> None: """ 清理浏览器 Profile 根下过期的一次性 `run_*` / `receipt_*` 目录。 核心逻辑:会话复用目录名以 `_session` 结尾或历史 `dsv360_session`,一律保留; 仅删除 `run_*` / `receipt_*` 临时目录,避免异常中断后残留撑盘。 收料 Worker 一次性 Profile 以 receipt_ 前缀创建,同属清理对象。 """ if profile_root is None or not profile_root.is_dir(): return for path in profile_root.iterdir(): try: if not path.is_dir(): continue except OSError as exc: stats.record_error(path, exc) continue name = path.name if name.endswith("_session") or name == "dsv360_session": stats.skipped += 1 continue if not name.startswith(_RUNTIME_PROFILE_TEMP_PREFIXES): stats.skipped += 1 continue if not _is_older_than(path, cutoff_unix=cutoff_unix): stats.skipped += 1 continue _safe_rmtree(path, stats) def run_worker_disk_cleanup( *, inventory_trigger_dir: Path | None = None, upload_trigger_dir: Path | None = None, drop_dir: Path | None = None, upload_queue_dir: Path | None = None, browser_profile_dir: Path | None = None, log_file: Path | None = None, now_unix: float | None = None, ) -> DiskCleanupStats: """ 执行一轮 Worker 本机磁盘保留清理。 【AI 触发时机】:Worker 启动后及主循环按 `DISK_CLEANUP_INTERVAL_SECONDS` 周期调用。 核心逻辑:按 `DISK_RETENTION_DAYS` 清理归档/日志备份/队列残留;按 `ORPHAN_PROFILE_MAX_AGE_HOURS` 清理孤儿 `run_*` / `receipt_*` Profile。全部 best-effort。 Args: inventory_trigger_dir: 库存 trigger 根目录。 upload_trigger_dir: 上传 trigger 根目录。 drop_dir: 库存 drop 根目录。 upload_queue_dir: 上传队列目录。 browser_profile_dir: 浏览器 Profile 根目录。 log_file: 当前 worker 日志文件路径。 now_unix: 可选当前时间(单测注入)。 Returns: DiskCleanupStats: 本轮删除/跳过/错误统计。 """ stats = DiskCleanupStats() now = float(now_unix if now_unix is not None else time.time()) days = retention_days() if days > 0: cutoff = now - (days * 86400) cleanup_trigger_archives(inventory_trigger_dir, cutoff_unix=cutoff, stats=stats) cleanup_trigger_archives(upload_trigger_dir, cutoff_unix=cutoff, stats=stats) cleanup_drop_archives(drop_dir, cutoff_unix=cutoff, stats=stats) cleanup_upload_queue(upload_queue_dir, cutoff_unix=cutoff, stats=stats) cleanup_log_backups(log_file, cutoff_unix=cutoff, stats=stats) orphan_age = orphan_profile_max_age_seconds() if orphan_age > 0: cleanup_orphan_runtime_profiles( browser_profile_dir, cutoff_unix=now - orphan_age, stats=stats, ) return stats def format_cleanup_summary(stats: DiskCleanupStats) -> str: """ 将清理统计格式化为单行日志。 Args: stats: 清理结果。 Returns: str: 适合 print 的摘要。 """ stamp = datetime.now(UTC).astimezone().strftime("%Y-%m-%d %H:%M:%S") return ( f"[disk-cleanup] at={stamp} deleted_files={stats.deleted_files} " f"deleted_dirs={stats.deleted_dirs} skipped={stats.skipped} errors={stats.errors}" )