feat(rpa): 增加 Worker 本机磁盘保留清理
按保留天数定期清理归档 trigger/drop、日志备份与孤儿 run_* Profile, 并支持运行中按大小轮转日志,避免常驻 Worker 撑爆 RPA 主机盘符。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
a6edc4fe61
commit
f8368acb6f
6 files changed
+762
-5
No files matched your search
@@ -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)
|
||||
|
||||
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user