diff --git a/backend/tests/test_freight_rpa_worker.py b/backend/tests/test_freight_rpa_worker.py index 41f7d7c2..eda5a638 100644 --- a/backend/tests/test_freight_rpa_worker.py +++ b/backend/tests/test_freight_rpa_worker.py @@ -623,6 +623,155 @@ def test_rotate_log_file_deletes_current_when_backup_count_zero(monkeypatch, tmp assert not log_path.exists() +def _load_worker_disk_cleanup(): + """加载 scripts/rpa/common/worker_disk_cleanup.py 供单测直接断言。""" + module_path = _repo_root() / "scripts" / "rpa" / "common" / "worker_disk_cleanup.py" + spec = importlib.util.spec_from_file_location("worker_disk_cleanup_under_test", module_path) + assert spec is not None + assert spec.loader is not None + module = importlib.util.module_from_spec(spec) + # dataclass 在装饰阶段会查 sys.modules;动态加载须先登记。 + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +def test_worker_disk_cleanup_deletes_expired_archives_and_keeps_active(monkeypatch, tmp_path): + """ + 超过保留期的归档应删除;进行中的 trigger、会话 Profile、cleanup_queue 必须保留。 + + 断言意图:验证磁盘清理只碰“归档/临时物”,不误删业务进行中文件。 + """ + cleanup = _load_worker_disk_cleanup() + now = time.time() + old = now - (10 * 86400) + recent = now - 3600 + + inv_trigger = tmp_path / "inventory_triggers" + upload_trigger = tmp_path / "upload_triggers" + drop = tmp_path / "inventory_drop" + queue = tmp_path / "upload_queue" + profiles = tmp_path / "browser_profile" + logs = tmp_path / "logs" + for path in ( + inv_trigger / "processed", + inv_trigger / "failed", + upload_trigger / "processed", + drop / "processed", + drop / ".hxops_quarantine", + drop / ".cleanup_queue", + drop / ".cleanup_failed", + queue, + profiles, + logs, + ): + path.mkdir(parents=True) + + active_trigger = inv_trigger / "inventory_export_SN-ACTIVE.json" + active_trigger.write_text("{}", encoding="utf-8") + os.utime(active_trigger, (old, old)) + + stale_processed = inv_trigger / "processed" / "inventory_export_SN-OLD.json" + stale_processed.write_text("{}", encoding="utf-8") + os.utime(stale_processed, (old, old)) + + fresh_processed = inv_trigger / "processed" / "inventory_export_SN-NEW.json" + fresh_processed.write_text("{}", encoding="utf-8") + os.utime(fresh_processed, (recent, recent)) + + stale_drop = drop / "processed" / "inventory_OLD.xlsx" + stale_drop.write_bytes(b"xlsx") + os.utime(stale_drop, (old, old)) + + stale_root_drop = drop / "inventory_STALE.xlsx" + stale_root_drop.write_bytes(b"xlsx") + os.utime(stale_root_drop, (old, old)) + + cleanup_job = drop / ".cleanup_queue" / "move_abc.json" + cleanup_job.write_text("{}", encoding="utf-8") + os.utime(cleanup_job, (old, old)) + + stale_queue = queue / "upload_OLD.xlsx" + stale_queue.write_bytes(b"xlsx") + os.utime(stale_queue, (old, old)) + + log_path = logs / "worker.log" + log_path.write_text("current", encoding="utf-8") + stale_backup = Path(f"{log_path}.1") + stale_backup.write_text("old-backup", encoding="utf-8") + os.utime(stale_backup, (old, old)) + + session_profile = profiles / "dsv360__DEFAULT_session" + session_profile.mkdir() + (session_profile / "Cookies").write_text("keep", encoding="utf-8") + os.utime(session_profile, (old, old)) + + orphan_run = profiles / "run_orphan" + orphan_run.mkdir() + (orphan_run / "Cookies").write_text("drop", encoding="utf-8") + os.utime(orphan_run, (now - (48 * 3600), now - (48 * 3600))) + + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS", "7") + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24") + + stats = cleanup.run_worker_disk_cleanup( + inventory_trigger_dir=inv_trigger, + upload_trigger_dir=upload_trigger, + drop_dir=drop, + upload_queue_dir=queue, + browser_profile_dir=profiles, + log_file=log_path, + now_unix=now, + ) + + assert not stale_processed.exists() + assert fresh_processed.exists() + assert active_trigger.exists() + assert not stale_drop.exists() + assert not stale_root_drop.exists() + assert cleanup_job.exists() + assert not stale_queue.exists() + assert log_path.exists() + assert not stale_backup.exists() + assert session_profile.exists() + assert not orphan_run.exists() + assert stats.deleted_files >= 4 + assert stats.deleted_dirs >= 1 + + +def test_worker_disk_cleanup_skips_when_retention_disabled(monkeypatch, tmp_path): + """DISK_RETENTION_DAYS<=0 时不删归档;孤儿 Profile 仍可按独立配置清理。""" + cleanup = _load_worker_disk_cleanup() + now = time.time() + old = now - (10 * 86400) + + inv_trigger = tmp_path / "inventory_triggers" + processed = inv_trigger / "processed" + profiles = tmp_path / "browser_profile" + processed.mkdir(parents=True) + profiles.mkdir(parents=True) + + stale_processed = processed / "old.json" + stale_processed.write_text("{}", encoding="utf-8") + os.utime(stale_processed, (old, old)) + + orphan_run = profiles / "run_orphan" + orphan_run.mkdir() + os.utime(orphan_run, (now - (48 * 3600), now - (48 * 3600))) + + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS", "0") + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24") + + cleanup.run_worker_disk_cleanup( + inventory_trigger_dir=inv_trigger, + browser_profile_dir=profiles, + now_unix=now, + ) + + assert stale_processed.exists() + assert not orphan_run.exists() + + def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch): """未配置 profile 根目录时,应回退到 shipping_notice/freight_rpa/browser_profile。""" worker = _load_freight_rpa_worker() diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index b13169b1..e64ec82f 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -2064,6 +2064,9 @@ $env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = "C:\HxopsRpaTest\data\brow $env:SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = "C:\HxopsRpaTest\data\logs\worker.log" $env:SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES = "10485760" $env:SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT = "5" +$env:SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS = "7" +$env:SHIPPING_NOTICE_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS = "3600" +$env:SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS = "24" $env:SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME = "请替换为DSV账号" $env:SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD = "请替换为DSV密码" @@ -2319,6 +2322,8 @@ volumes: 库存导出默认复用浏览器 Profile:按 `connector_type + rpa_profile_code` 使用独立目录 `{connector}__{profile}_session`,长期保留(`SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE`,默认开启)。本地不以 TTL 强制清空;站点侧会话失效时回落现有登录流程。上传任务保持一次性 Profile。同一 WorkerRoot 只运行一个库存 Worker(串行消费 trigger,浏览器并发上限为 1)。关闭复用可传启动参数 `-NoSessionReuse`;旧参数 `-ReuseDsvSession` 仍兼容。 +Worker 本机磁盘保留(`SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS`,默认 7 天;每小时一轮):清理 trigger `processed/failed`、drop 归档与隔离目录、过期 drop 根导出文件、upload_queue 残留、日志备份,以及超过 24h 的孤儿 `run_*` 临时 Profile;会话 Profile 与进行中的 trigger 根 JSON、`.cleanup_queue` 不删。运行中日志同时按 `LOG_MAX_BYTES` 轮转,避免常驻进程单文件无限增长。 + Windows 如禁止运行 `.ps1`,仅对单次 Secret 创建使用临时 Bypass: ```powershell diff --git a/scripts/rpa/README.md b/scripts/rpa/README.md index 36cf190a..99ff11e4 100644 --- a/scripts/rpa/README.md +++ b/scripts/rpa/README.md @@ -38,6 +38,7 @@ Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA | `common/rpa_common.py` | 环境变量、通用 Playwright 点击/填充工具 | | `common/download_artifact_fallback.py` | 浏览器已落盘但 Playwright 未返回 Download 时的下载适配器 | | `common/rpa_heartbeat.py` | 向后端上报心跳 + 共享目录哨兵(原 `freight_rpa_heartbeat.py`) | +| `common/worker_disk_cleanup.py` | Worker 本机磁盘保留清理(日志备份 / trigger·drop 归档 / 孤儿 run_* Profile) | | `common/new_rpa_worker_secret.ps1` | 生成当前用户可解密的 DPAPI Secret 文件 | | `connectors/` | **登录网站 / 报表系统自动化**(库存与收料共用) | | `connectors/dsv/` | DSV 360 连接器:`dsv_driver` / `dsv_auth` / `dsv_auth_login_flow` / `dsv_session` / `dsv_navigation` / `dsv_report_export` / `dsv_debug` / `dsv_report_parameters` / `dsv_login_smoke` / `dsv_export_timeout_diagnostics` | @@ -78,6 +79,12 @@ Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA | `SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS` | 心跳间隔(默认 20s),test/prod 触发前检查依赖在线心跳 | | `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY` | Profile 凭据 Fernet 主密钥;必须与对应环境后端一致,只能由 Secret 渠道或部署脚本安全注入 | | `SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE` | 库存导出是否复用浏览器登录 Profile,默认 `true`;上传任务不受影响;站点会话失效时自动重登 | +| `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE` | Worker 文件日志路径(stdout/stderr tee) | +| `SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES` | 单日志文件大小上限(默认 10MB);启动与周期清理时按大小轮转 | +| `SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT` | 日志备份个数(默认 5) | +| `SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS` | 本机归档保留天数(默认 7);`<=0` 禁用按天清理。覆盖 trigger `processed/failed`、drop 归档/隔离、upload_queue、日志备份 | +| `SHIPPING_NOTICE_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS` | 磁盘清理周期秒数(默认 3600);Worker 启动时会立即清一轮 | +| `SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS` | 孤儿临时 `run_*` Profile 最大存活小时(默认 24);`*_session` 会话 Profile 永不删除 | 新部署只使用 `new_rpa_worker_secret.ps1` + `start_rpa_worker.ps1`:Secret 由 DPAPI 保护,环境变量只注入对应 Worker 子进程。 @@ -92,6 +99,11 @@ DSV/Crane 库存导出默认复用浏览器 Profile(按 `connector + rpa_profi 启动时加 `-NoSessionReuse`。旧参数 `-ReuseDsvSession` / `SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE` 仍兼容,但请改用 `SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE`。 +Worker 默认启用本机磁盘保留清理(`scripts/rpa/common/worker_disk_cleanup.py`):启动与每小时 +清理超过保留期的 `processed/failed` trigger、drop 归档(含 `processed` / +`.hxops_quarantine` / `.cleanup_failed`)、过期 drop 根导出文件、upload_queue 残留、 +日志备份,以及超过 24h 的孤儿 `run_*` 临时 Profile。**不删除**进行中的 trigger 根 JSON、 +可复用会话 Profile、以及活跃的 `.cleanup_queue`。 ### DSV WMS Upload Tool 已确认 DSV 上传页为 `WMS Upload Tool > Upload`,页面有 `Browse` 文件选择入口和 @@ -861,6 +873,9 @@ $env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = "C:\HxopsRpaTest\data\brow $env:SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = "C:\HxopsRpaTest\data\logs\worker.log" $env:SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES = "10485760" $env:SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT = "5" +$env:SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS = "7" +$env:SHIPPING_NOTICE_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS = "3600" +$env:SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS = "24" $env:SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME = "请替换为DSV账号" $env:SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD = "请替换为DSV密码" diff --git a/scripts/rpa/common/worker_disk_cleanup.py b/scripts/rpa/common/worker_disk_cleanup.py new file mode 100644 index 00000000..14e20ad0 --- /dev/null +++ b/scripts/rpa/common/worker_disk_cleanup.py @@ -0,0 +1,426 @@ +""" +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") +_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_*)最大存活秒数。 + + 核心逻辑:`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_*` 目录。 + + 核心逻辑:会话复用目录名以 `_session` 结尾或历史 `dsv360_session`,一律保留; + 仅删除 `run_*` 临时目录,避免异常中断后残留撑盘。 + """ + 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("run_"): + 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_*` 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}" + ) diff --git a/scripts/rpa/inventory/inventory_rpa_worker.py b/scripts/rpa/inventory/inventory_rpa_worker.py index 96ec886c..f3a5bdc9 100644 --- a/scripts/rpa/inventory/inventory_rpa_worker.py +++ b/scripts/rpa/inventory/inventory_rpa_worker.py @@ -27,6 +27,9 @@ Optional: SHIPPING_NOTICE_RPA_WORKER_LOG_FILE=C:\\HxopsRpaTest\\data\\logs\\worker.log SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES=10485760 SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT=5 + SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS=7 + SHIPPING_NOTICE_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS=3600 + SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS=24 SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME / SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME / SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED=false @@ -82,6 +85,7 @@ import dsv_report_export # noqa: E402 from dsv_report_export import NoInventoryDataError # noqa: E402 import dsv_session # noqa: E402 import rpa_heartbeat # noqa: E402 +import worker_disk_cleanup # noqa: E402 # 测试与 smoke 向后兼容 re-export _maybe_auto_login_dsv = dsv_session.maybe_auto_login_dsv @@ -143,7 +147,7 @@ class _TeeStream: 核心逻辑:保留原 stdout/stderr,避免计划任务改为日志模式后本地调试看不到输出; 每行完整输出前自动前缀本地时间戳;文件 flush 采用行级同步,RPA 异常退出时尽量 - 保留最后几行排障信息。 + 保留最后几行排障信息;支持运行中替换底层日志句柄以便按大小轮转。 """ def __init__(self, console: TextIO, log_file: TextIO) -> None: @@ -152,6 +156,23 @@ class _TeeStream: self._pending = "" self.encoding = getattr(console, "encoding", "utf-8") + def replace_log_file(self, log_file: TextIO) -> TextIO: + """ + 替换底层日志文件句柄(用于运行中轮转)。 + + 核心逻辑:先 flush 缓冲,再切换句柄;调用方负责关闭旧句柄与打开新文件。 + + Args: + log_file: 新的追加写日志句柄。 + + Returns: + TextIO: 被替换下来的旧日志句柄。 + """ + self.flush() + previous = self._log_file + self._log_file = log_file + return previous + def _emit_line(self, line: str, *, newline: bool) -> None: """将单行(可含时间戳前缀)写入控制台与日志文件。""" if line: @@ -181,6 +202,13 @@ class _TeeStream: return bool(getattr(self._console, "isatty", lambda: False)()) +# 运行中日志轮转需要持有 Tee 与路径;仅由 _configure_file_logging / _maybe_rotate_open_log 维护。 +_ACTIVE_LOG_PATH: Path | None = None +_ACTIVE_STDOUT_TEE: _TeeStream | None = None +_ACTIVE_STDERR_TEE: _TeeStream | None = None +_ACTIVE_LOG_HANDLE: TextIO | None = None + + def _configure_file_logging() -> Path | None: """ 按 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE 启用 worker 文件日志。 @@ -192,6 +220,7 @@ def _configure_file_logging() -> Path | None: Returns: Path | None: 已启用的日志路径;未配置时返回 None。 """ + global _ACTIVE_LOG_PATH, _ACTIVE_STDOUT_TEE, _ACTIVE_STDERR_TEE, _ACTIVE_LOG_HANDLE raw = _env("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE") if not raw: return None @@ -203,19 +232,71 @@ def _configure_file_logging() -> Path | None: log_file = path.open("a", encoding="utf-8", buffering=1) original_stdout = sys.stdout original_stderr = sys.stderr - sys.stdout = _TeeStream(original_stdout, log_file) # type: ignore[assignment] - sys.stderr = _TeeStream(original_stderr, log_file) # type: ignore[assignment] + stdout_tee = _TeeStream(original_stdout, log_file) + stderr_tee = _TeeStream(original_stderr, log_file) + sys.stdout = stdout_tee # type: ignore[assignment] + sys.stderr = stderr_tee # type: ignore[assignment] + _ACTIVE_LOG_PATH = path + _ACTIVE_STDOUT_TEE = stdout_tee + _ACTIVE_STDERR_TEE = stderr_tee + _ACTIVE_LOG_HANDLE = log_file def _close_log() -> None: + global _ACTIVE_LOG_PATH, _ACTIVE_STDOUT_TEE, _ACTIVE_STDERR_TEE, _ACTIVE_LOG_HANDLE sys.stdout = original_stdout sys.stderr = original_stderr - log_file.close() + handle = _ACTIVE_LOG_HANDLE or log_file + try: + handle.close() + except Exception: + pass + _ACTIVE_LOG_PATH = None + _ACTIVE_STDOUT_TEE = None + _ACTIVE_STDERR_TEE = None + _ACTIVE_LOG_HANDLE = None atexit.register(_close_log) print(f"[logging] tee enabled path={path}") return path +def _maybe_rotate_open_log() -> None: + """ + 常驻 Worker 运行中按大小轮转当前日志。 + + 核心逻辑:Windows 下无法对仍打开的文件 rename,须先关闭句柄 → 调用既有 + `_rotate_log_file_if_needed` → 再以追加模式打开新文件并挂回 TeeStream。 + 未启用文件日志或未超限时 no-op。 + """ + global _ACTIVE_LOG_HANDLE + path = _ACTIVE_LOG_PATH + stdout_tee = _ACTIVE_STDOUT_TEE + stderr_tee = _ACTIVE_STDERR_TEE + handle = _ACTIVE_LOG_HANDLE + if path is None or stdout_tee is None or stderr_tee is None or handle is None: + return + max_bytes = _log_int_env("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", 10 * 1024 * 1024, min_value=0) + if max_bytes <= 0: + return + try: + handle.flush() + if path.stat().st_size < max_bytes: + return + except OSError: + return + try: + handle.close() + except Exception: + pass + _ACTIVE_LOG_HANDLE = None + _rotate_log_file_if_needed(path) + new_handle = path.open("a", encoding="utf-8", buffering=1) + stdout_tee.replace_log_file(new_handle) + stderr_tee.replace_log_file(new_handle) + _ACTIVE_LOG_HANDLE = new_handle + print(f"[logging] rotated open log path={path}") + + def _log_int_env(name: str, default: int, *, min_value: int = 0) -> int: """读取日志相关整数环境变量;非法值回退默认值。""" try: @@ -2436,8 +2517,60 @@ def _scan_triggers(trigger_dir: Path, handler, extra_args: tuple = ()) -> None: rpa_heartbeat.set_worker_runtime_status("idle") +def _run_periodic_disk_cleanup( + *, + inv_trigger_dir: Path, + upload_trigger_dir: Path, + drop_dir: Path, + upload_queue_dir: Path, + force: bool = False, + last_cleanup_mono: float = 0.0, +) -> float: + """ + 按间隔执行本机磁盘保留清理,并尝试运行中日志轮转。 + + 核心逻辑:默认每 `DISK_CLEANUP_INTERVAL_SECONDS` 跑一轮;清理归档 trigger/drop、 + 日志备份、upload_queue 残留与孤儿 `run_*` Profile;同时按大小轮转打开中的 worker.log。 + + Args: + inv_trigger_dir: 库存 trigger 根目录。 + upload_trigger_dir: 上传 trigger 根目录。 + drop_dir: 库存 drop 根目录。 + upload_queue_dir: 上传队列目录。 + force: True 时忽略间隔立即执行(启动时)。 + last_cleanup_mono: 上次清理的 monotonic 时间戳。 + + Returns: + float: 更新后的 last_cleanup_mono(未执行则原样返回)。 + """ + interval = worker_disk_cleanup.cleanup_interval_seconds() + now_mono = time.monotonic() + if not force and (now_mono - last_cleanup_mono) < interval: + return last_cleanup_mono + try: + _maybe_rotate_open_log() + stats = worker_disk_cleanup.run_worker_disk_cleanup( + inventory_trigger_dir=inv_trigger_dir, + upload_trigger_dir=upload_trigger_dir, + drop_dir=drop_dir, + upload_queue_dir=upload_queue_dir, + browser_profile_dir=_browser_profile_root(), + log_file=_ACTIVE_LOG_PATH, + ) + print(worker_disk_cleanup.format_cleanup_summary(stats)) + except Exception as exc: + print(f"[disk-cleanup] failed: {exc}", file=sys.stderr) + return now_mono + + def main() -> None: - _configure_file_logging() + """ + 库存 RPA Worker 入口:启日志、心跳、周期磁盘清理,并串行消费 trigger。 + + 核心逻辑:主循环扫描库存/上传 trigger;空闲时按间隔清理本机归档与临时文件, + 防止长期运行撑爆 RPA 主机盘符。 + """ + log_path = _configure_file_logging() drop_dir = _require_path("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR") inv_trigger_dir = _require_path("SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR") upload_queue_dir = _require_path("SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR") @@ -2463,6 +2596,14 @@ def main() -> None: print(f" upload_triggers={upload_trigger_dir}") print(f" drop={drop_dir}") print(f" queue={upload_queue_dir}") + print(f" log={log_path or 'disabled'}") + print( + " disk_retention_days=" + f"{worker_disk_cleanup.retention_days()} " + f"cleanup_interval_seconds={worker_disk_cleanup.cleanup_interval_seconds()} " + f"orphan_profile_max_age_hours=" + f"{max(0, worker_disk_cleanup.orphan_profile_max_age_seconds() // 3600)}" + ) # 启动时立即上报一次,让管理端第一时间看到 Worker 上线。 rpa_heartbeat.maybe_send_heartbeat( @@ -2479,9 +2620,25 @@ def main() -> None: interval_seconds=heartbeat_seconds, ) + # [STEP 1] 启动即清一轮,避免重启前长期堆积的归档立刻撑盘 + last_cleanup_mono = _run_periodic_disk_cleanup( + inv_trigger_dir=inv_trigger_dir, + upload_trigger_dir=upload_trigger_dir, + drop_dir=drop_dir, + upload_queue_dir=upload_queue_dir, + force=True, + ) + while True: _scan_triggers(inv_trigger_dir, _handle_inventory_trigger, (drop_dir, inv_processed)) _scan_triggers(upload_trigger_dir, _handle_upload_trigger, (upload_processed,)) + last_cleanup_mono = _run_periodic_disk_cleanup( + inv_trigger_dir=inv_trigger_dir, + upload_trigger_dir=upload_trigger_dir, + drop_dir=drop_dir, + upload_queue_dir=upload_queue_dir, + last_cleanup_mono=last_cleanup_mono, + ) time.sleep(poll) diff --git a/scripts/rpa/inventory/start_inventory_worker.ps1 b/scripts/rpa/inventory/start_inventory_worker.ps1 index 806da8f6..5c12f833 100644 --- a/scripts/rpa/inventory/start_inventory_worker.ps1 +++ b/scripts/rpa/inventory/start_inventory_worker.ps1 @@ -10,6 +10,7 @@ 不从本机 Secret 文件读取。 默认开启库存会话复用(SESSION_REUSE,长期保留 Profile;站点会话失效才重登); 需要每次全新登录时传 -NoSessionReuse。 + 默认启用本机磁盘保留清理(7 天归档 / 每小时一轮 / 24h 孤儿 run_* Profile)。 #> param( [Parameter(Mandatory = $true)] @@ -93,6 +94,10 @@ $processVars = [ordered]@{ SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = Join-Path $dataRoot "logs\worker.log" SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES = "10485760" SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT = "5" + # 本机磁盘保留:归档 trigger/drop、日志备份、upload_queue、孤儿 run_* Profile;会话 Profile 不删。 + SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS = "7" + SHIPPING_NOTICE_RPA_WORKER_DISK_CLEANUP_INTERVAL_SECONDS = "3600" + SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS = "24" SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED = "false" SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT = "false" }