feat(rpa): 收料Worker能力对齐库存Worker并提取公共文件日志模块
- 新增 common/worker_logging:tee+时间戳+按大小轮转,库存 Worker 同步委托切换(纯等价重构) - 收料 Worker 接入文件日志+完整 banner+领取/归档/单元成败全路径留痕 - 心跳对齐:独立身份 <主机名>-receipt(ps1 注入 WORKER_ID/HEARTBEAT_SECONDS),busy/idle 运行态 - 磁盘保留清理启动+周期,孤儿 Profile 覆盖 receipt_* 前缀;清理失败不中断主循环 - README 能力对齐表与禁止共写日志规则;technical.md §1.9 收料部署事实同步(含身份口径修正)
This commit is contained in:
1 parent
051f80e1e9
commit
4d879dd8ea
11 files changed
+554
-235
No files matched your search
+15
-3
@@ -133,6 +133,18 @@ DSV Worker 默认使用 `#file2`,也可用 `SHIPPING_NOTICE_RPA_WORKER_UPLOAD_
|
||||
人工确认导出未完成则移回根目录重跑,已完成则人工补回调后归档。
|
||||
- 新增 Worker 一律复用 `common/trigger_consumer.py`,禁止再自建目录搬移逻辑。
|
||||
|
||||
## Worker 运行能力(库存 / 收料对齐)
|
||||
|
||||
| 能力 | 库存 Worker | 收料 Worker |
|
||||
| --- | --- | --- |
|
||||
| 文件日志(tee+时间戳+轮转) | `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE` | 同左(ps1 默认 `data\freight_receipt_rpa\logs\worker.log`) |
|
||||
| 启动 banner / 运行中轮转 | ✅ | ✅(同一 `worker_logging` 模块) |
|
||||
| 心跳上报 | `<hostname>-<pid>`(随进程重启变化,ps1 未注入 `WORKER_ID`) | `<hostname>-receipt`(独立身份,ps1 注入) |
|
||||
| 磁盘保留清理 | 周期 + 启动一轮 | 同左(清收料 processed/failed/drop 与共享 Profile 的孤儿 `run_*`/`receipt_*`) |
|
||||
|
||||
规则:**两个 Worker 禁止共写同一日志文件**(多进程写同一文件会交错且 Windows 轮转竞争);
|
||||
每个 Worker 的 `LOG_FILE` 必须指向各自根目录下的 `logs/worker.log`。
|
||||
|
||||
## 部署、启动与停止手册
|
||||
|
||||
本节说明库存 RPA 测试导出的三种运行方式:
|
||||
@@ -184,9 +196,9 @@ Linux HXOPS 后端 Windows RPA Worker
|
||||
2. 程序:整目录复制 `scripts\rpa` 时已包含 `receipt\`;`receipt_rpa_worker.py` 要求同级存在 `connectors/`、`common/`、`inventory/`、`receipt/` 四个子目录,不能单拷 `receipt\`。
|
||||
3. 依赖:在库存 Worker 依赖之上补 `cryptography`:`python -m pip install playwright openpyxl pyyaml cryptography`。
|
||||
4. Secret:与库存共用 `new_rpa_worker_secret.ps1` 生成的 `C:\HxopsRpaSecrets\test.xml` / `prod.xml`,无需新建。
|
||||
5. 启动:`scripts\rpa\receipt\start_receipt_worker.ps1`,参数与库存启动脚本一致(`-Environment`、`-ApiBase`、`-WorkerRoot`、`-SecretFile`,可选 `-Mock` / `-Headless`);成功输出 `[freight_receipt_rpa_worker] started trigger_dir=... drop_dir=...`。
|
||||
6. 心跳/哨兵:收料 Worker **不发心跳、不写哨兵**,不参与「RPA Worker 在线」检查;收料触发前无 fail-fast,Worker 停止只会让单元等到 `SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS`(默认 900 秒)超时回收。
|
||||
7. 日志:收料 Worker 只输出到控制台;计划任务用 `cmd.exe` 包装 `>>` 重定向到 `data\freight_receipt_rpa\logs\receipt_worker.log`(完整任务计划示例见 technical.md §1.9.2)。
|
||||
5. 启动:`scripts\rpa\receipt\start_receipt_worker.ps1`,参数与库存启动脚本一致(`-Environment`、`-ApiBase`、`-WorkerRoot`、`-SecretFile`,可选 `-Mock` / `-Headless`);成功输出 `[freight_receipt_rpa_worker] started` 独立行,后跟缩进字段块(` mock=...`、` api_base=...`、` trigger_dir=...`、` drop_dir=...`、` log=...` 等,完整字段以 `receipt_rpa_worker.py` 启动 banner 为准)。
|
||||
6. 心跳/哨兵:心跳已接——以独立身份 `<主机名>-receipt`(ps1 注入 `SHIPPING_NOTICE_RPA_WORKER_ID`)按 `SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS`(默认 20 秒)周期上报 `/api/shipping-notice/rpa/heartbeat`;仍不写 `.hxops_rpa_shared_mount` 哨兵、触发前无 fail-fast 在线检查,Worker 停止只会让单元等到 `SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS`(默认 900 秒)超时回收。
|
||||
7. 日志:文件日志已接——ps1 注入 `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE`,默认 `data\freight_receipt_rpa\logs\worker.log`(tee 控制台 + 时间戳 + 按大小轮转,与库存 Worker 同一 `worker_logging` 模块,两个 Worker 禁止共写同一日志文件);计划任务仍可用 `cmd.exe` 包装 `>>` 重定向控制台输出留档(完整任务计划示例见 technical.md §1.9.2)。
|
||||
8. 后端:`.env` 追加 `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR` / `SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR` 两个共享子路径(漏配会写容器本地默认路径,Windows 看不到);容器 bind mount 无需新增。收料文件回调后原样归档 MinIO 保留三年,到期清理由平台任务「货代收料归档到期清理」负责。
|
||||
|
||||
|
||||
|
||||
@@ -48,6 +48,9 @@ _PROTECTED_DROP_DIRNAMES = frozenset(
|
||||
)
|
||||
_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
|
||||
@@ -108,7 +111,7 @@ def cleanup_interval_seconds() -> int:
|
||||
|
||||
def orphan_profile_max_age_seconds() -> int:
|
||||
"""
|
||||
读取孤儿临时 Profile(run_*)最大存活秒数。
|
||||
读取孤儿临时 Profile(run_* / receipt_*)最大存活秒数。
|
||||
|
||||
核心逻辑:`SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS`,默认 24;
|
||||
`<=0` 禁用孤儿 Profile 清理。会话复用目录(*_session)永不删除。
|
||||
@@ -332,10 +335,11 @@ def cleanup_orphan_runtime_profiles(
|
||||
stats: DiskCleanupStats,
|
||||
) -> None:
|
||||
"""
|
||||
清理浏览器 Profile 根下过期的一次性 `run_*` 目录。
|
||||
清理浏览器 Profile 根下过期的一次性 `run_*` / `receipt_*` 目录。
|
||||
|
||||
核心逻辑:会话复用目录名以 `_session` 结尾或历史 `dsv360_session`,一律保留;
|
||||
仅删除 `run_*` 临时目录,避免异常中断后残留撑盘。
|
||||
仅删除 `run_*` / `receipt_*` 临时目录,避免异常中断后残留撑盘。
|
||||
收料 Worker 一次性 Profile 以 receipt_ 前缀创建,同属清理对象。
|
||||
"""
|
||||
if profile_root is None or not profile_root.is_dir():
|
||||
return
|
||||
@@ -350,7 +354,7 @@ def cleanup_orphan_runtime_profiles(
|
||||
if name.endswith("_session") or name == "dsv360_session":
|
||||
stats.skipped += 1
|
||||
continue
|
||||
if not name.startswith("run_"):
|
||||
if not name.startswith(_RUNTIME_PROFILE_TEMP_PREFIXES):
|
||||
stats.skipped += 1
|
||||
continue
|
||||
if not _is_older_than(path, cutoff_unix=cutoff_unix):
|
||||
@@ -375,7 +379,7 @@ def run_worker_disk_cleanup(
|
||||
【AI 触发时机】:Worker 启动后及主循环按 `DISK_CLEANUP_INTERVAL_SECONDS` 周期调用。
|
||||
|
||||
核心逻辑:按 `DISK_RETENTION_DAYS` 清理归档/日志备份/队列残留;按
|
||||
`ORPHAN_PROFILE_MAX_AGE_HOURS` 清理孤儿 `run_*` Profile。全部 best-effort。
|
||||
`ORPHAN_PROFILE_MAX_AGE_HOURS` 清理孤儿 `run_*` / `receipt_*` Profile。全部 best-effort。
|
||||
|
||||
Args:
|
||||
inventory_trigger_dir: 库存 trigger 根目录。
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
"""scripts/rpa/common/worker_logging.py
|
||||
|
||||
用途:RPA Worker 通用文件日志——stdout/stderr tee 落盘、行级本地时间戳、
|
||||
按大小轮转(启动前 + 运行中),供库存/收料等所有 Worker 复用。
|
||||
依赖:rpa_common._env(环境变量读取与历史名兼容)、标准库。
|
||||
逻辑:configure_file_logging 读 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE 启用;
|
||||
maybe_rotate_open_log 在主循环周期调用做运行中轮转;shutdown_logging 恢复标准流。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import atexit
|
||||
import sys
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import TextIO
|
||||
|
||||
from rpa_common import _env
|
||||
|
||||
|
||||
def _backend_dir() -> Path:
|
||||
"""返回仓库内 backend 根目录(本模块位于 <repo>/scripts/rpa/common/)。"""
|
||||
return Path(__file__).resolve().parents[3] / "backend"
|
||||
|
||||
|
||||
def log_line_timestamp() -> str:
|
||||
"""
|
||||
生成 worker 日志行首时间戳(本地时区)。
|
||||
|
||||
核心逻辑:RPA 批量导出常跨 1+ 小时,行级时间便于对照 DSV 页面卡顿与超时点。
|
||||
|
||||
Returns:
|
||||
str: `YYYY-MM-DD HH:MM:SS` 格式字符串。
|
||||
"""
|
||||
return datetime.now(UTC).astimezone().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def _log_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)
|
||||
|
||||
|
||||
class WorkerLogTee:
|
||||
"""
|
||||
同时写入控制台与日志文件的轻量 stream。
|
||||
|
||||
核心逻辑:保留原 stdout/stderr,避免计划任务改为日志模式后本地调试看不到输出;
|
||||
每行完整输出前自动前缀本地时间戳;文件 flush 采用行级同步,RPA 异常退出时尽量
|
||||
保留最后几行排障信息;支持运行中替换底层日志句柄以便按大小轮转。
|
||||
"""
|
||||
|
||||
def __init__(self, console: TextIO, log_file: TextIO) -> None:
|
||||
self._console = console
|
||||
self._log_file = log_file
|
||||
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:
|
||||
stamped = f"{log_line_timestamp()} {line}"
|
||||
self._console.write(stamped)
|
||||
self._log_file.write(stamped)
|
||||
if newline:
|
||||
self._console.write("\n")
|
||||
self._log_file.write("\n")
|
||||
|
||||
def write(self, text: str) -> int:
|
||||
self._pending += text
|
||||
while "\n" in self._pending:
|
||||
line, self._pending = self._pending.split("\n", 1)
|
||||
self._emit_line(line, newline=True)
|
||||
self.flush()
|
||||
return len(text)
|
||||
|
||||
def flush(self) -> None:
|
||||
if self._pending:
|
||||
self._emit_line(self._pending, newline=False)
|
||||
self._pending = ""
|
||||
self._console.flush()
|
||||
self._log_file.flush()
|
||||
|
||||
def isatty(self) -> bool:
|
||||
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: WorkerLogTee | None = None
|
||||
_ACTIVE_STDERR_TEE: WorkerLogTee | None = None
|
||||
_ACTIVE_LOG_HANDLE: TextIO | None = None
|
||||
|
||||
|
||||
def configure_file_logging() -> Path | None:
|
||||
"""
|
||||
按 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE 启用 worker 文件日志。
|
||||
|
||||
【AI 触发时机】:Windows 任务计划程序后台运行 RPA worker 时配置本变量,
|
||||
让所有 print/stdout/stderr 同时落盘,并在每行前自动加本地时间戳,便于排查
|
||||
登录、下载、回调失败与长批次耗时。
|
||||
|
||||
Returns:
|
||||
Path | None: 已启用的日志路径;未配置时返回 None。
|
||||
"""
|
||||
global _ACTIVE_LOG_PATH, _ACTIVE_STDOUT_TEE, _ACTIVE_STDERR_TEE, _ACTIVE_LOG_HANDLE
|
||||
if _ACTIVE_LOG_PATH is not None:
|
||||
return _ACTIVE_LOG_PATH
|
||||
raw = _env("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE")
|
||||
if not raw:
|
||||
return None
|
||||
path = Path(raw).expanduser()
|
||||
if not path.is_absolute():
|
||||
path = (_backend_dir() / path).resolve()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
rotate_log_file_if_needed(path)
|
||||
log_file = path.open("a", encoding="utf-8", buffering=1)
|
||||
original_stdout = sys.stdout
|
||||
original_stderr = sys.stderr
|
||||
stdout_tee = WorkerLogTee(original_stdout, log_file)
|
||||
stderr_tee = WorkerLogTee(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
|
||||
atexit.register(shutdown_logging)
|
||||
print(f"[logging] tee enabled path={path}")
|
||||
return path
|
||||
|
||||
|
||||
def shutdown_logging() -> None:
|
||||
"""
|
||||
恢复 stdout/stderr 并关闭日志句柄(原 _configure_file_logging 内 _close_log 逻辑公开化)。
|
||||
|
||||
核心逻辑:把标准流还原为启用 tee 前的原流,关闭当前日志句柄并清空 _ACTIVE_* 状态;
|
||||
由 configure_file_logging 注册到 atexit 兜底,进程退出时保证日志落盘完整。
|
||||
未启用文件日志时 no-op。
|
||||
"""
|
||||
global _ACTIVE_LOG_PATH, _ACTIVE_STDOUT_TEE, _ACTIVE_STDERR_TEE, _ACTIVE_LOG_HANDLE
|
||||
stdout_tee = _ACTIVE_STDOUT_TEE
|
||||
stderr_tee = _ACTIVE_STDERR_TEE
|
||||
if stdout_tee is not None:
|
||||
sys.stdout = stdout_tee._console
|
||||
if stderr_tee is not None:
|
||||
sys.stderr = stderr_tee._console
|
||||
handle = _ACTIVE_LOG_HANDLE
|
||||
try:
|
||||
handle.close()
|
||||
except Exception:
|
||||
pass
|
||||
_ACTIVE_LOG_PATH = None
|
||||
_ACTIVE_STDOUT_TEE = None
|
||||
_ACTIVE_STDERR_TEE = None
|
||||
_ACTIVE_LOG_HANDLE = None
|
||||
|
||||
|
||||
def active_log_path() -> Path | None:
|
||||
"""返回当前已启用的日志文件路径;未启用文件日志时返回 None。"""
|
||||
return _ACTIVE_LOG_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 rotate_log_file_if_needed(path: Path) -> None:
|
||||
"""
|
||||
在打开日志前做大小轮转,避免 Windows 常驻 worker 单个日志无限增长。
|
||||
|
||||
核心逻辑:当 `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE` 已存在且大小达到 `SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES`
|
||||
时,按 `.1`、`.2` ... 备份后缀向后滚动;超过 `SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT`
|
||||
的旧文件会被删除。`SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES<=0` 时禁用轮转。
|
||||
"""
|
||||
max_bytes = _log_int_env("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", 10 * 1024 * 1024, min_value=0)
|
||||
backup_count = _log_int_env("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", 5, min_value=0)
|
||||
if max_bytes <= 0 or not path.is_file():
|
||||
return
|
||||
try:
|
||||
if path.stat().st_size < max_bytes:
|
||||
return
|
||||
except OSError:
|
||||
return
|
||||
|
||||
if backup_count <= 0:
|
||||
path.unlink(missing_ok=True)
|
||||
return
|
||||
|
||||
oldest = Path(f"{path}.{backup_count}")
|
||||
oldest.unlink(missing_ok=True)
|
||||
for index in range(backup_count - 1, 0, -1):
|
||||
src = Path(f"{path}.{index}")
|
||||
if src.exists():
|
||||
src.replace(Path(f"{path}.{index + 1}"))
|
||||
path.replace(Path(f"{path}.1"))
|
||||
@@ -40,7 +40,6 @@ Optional:
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import atexit
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
import os
|
||||
@@ -53,7 +52,7 @@ import urllib.error
|
||||
import urllib.request
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, TextIO
|
||||
from typing import Any, Callable
|
||||
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
|
||||
@@ -91,6 +90,8 @@ from download_artifact_fallback import ( # noqa: E402
|
||||
wait_for_new_download_file as _wait_for_new_download_file,
|
||||
)
|
||||
from trigger_consumer import claim_trigger # noqa: E402
|
||||
# 日志实现已提取至公共模块(scripts/rpa/common/worker_logging.py),本 Worker 仅委托调用。
|
||||
from worker_logging import active_log_path, configure_file_logging, maybe_rotate_open_log # noqa: E402
|
||||
|
||||
# 测试与 smoke 向后兼容 re-export
|
||||
_maybe_auto_login_dsv = dsv_session.maybe_auto_login_dsv
|
||||
@@ -136,214 +137,6 @@ except ImportError:
|
||||
Workbook = None # type: ignore
|
||||
|
||||
|
||||
def _log_line_timestamp() -> str:
|
||||
"""
|
||||
生成 worker 日志行首时间戳(本地时区)。
|
||||
|
||||
核心逻辑:RPA 批量导出常跨 1+ 小时,行级时间便于对照 DSV 页面卡顿与超时点。
|
||||
|
||||
Returns:
|
||||
str: `YYYY-MM-DD HH:MM:SS` 格式字符串。
|
||||
"""
|
||||
return datetime.now(UTC).astimezone().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
class _TeeStream:
|
||||
"""
|
||||
同时写入控制台与日志文件的轻量 stream。
|
||||
|
||||
核心逻辑:保留原 stdout/stderr,避免计划任务改为日志模式后本地调试看不到输出;
|
||||
每行完整输出前自动前缀本地时间戳;文件 flush 采用行级同步,RPA 异常退出时尽量
|
||||
保留最后几行排障信息;支持运行中替换底层日志句柄以便按大小轮转。
|
||||
"""
|
||||
|
||||
def __init__(self, console: TextIO, log_file: TextIO) -> None:
|
||||
self._console = console
|
||||
self._log_file = log_file
|
||||
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:
|
||||
stamped = f"{_log_line_timestamp()} {line}"
|
||||
self._console.write(stamped)
|
||||
self._log_file.write(stamped)
|
||||
if newline:
|
||||
self._console.write("\n")
|
||||
self._log_file.write("\n")
|
||||
|
||||
def write(self, text: str) -> int:
|
||||
self._pending += text
|
||||
while "\n" in self._pending:
|
||||
line, self._pending = self._pending.split("\n", 1)
|
||||
self._emit_line(line, newline=True)
|
||||
self.flush()
|
||||
return len(text)
|
||||
|
||||
def flush(self) -> None:
|
||||
if self._pending:
|
||||
self._emit_line(self._pending, newline=False)
|
||||
self._pending = ""
|
||||
self._console.flush()
|
||||
self._log_file.flush()
|
||||
|
||||
def isatty(self) -> bool:
|
||||
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 文件日志。
|
||||
|
||||
【AI 触发时机】:Windows 任务计划程序后台运行 RPA worker 时配置本变量,
|
||||
让所有 print/stdout/stderr 同时落盘,并在每行前自动加本地时间戳,便于排查
|
||||
登录、下载、回调失败与长批次耗时。
|
||||
|
||||
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
|
||||
path = Path(raw).expanduser()
|
||||
if not path.is_absolute():
|
||||
path = (_backend_dir() / path).resolve()
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
_rotate_log_file_if_needed(path)
|
||||
log_file = path.open("a", encoding="utf-8", buffering=1)
|
||||
original_stdout = sys.stdout
|
||||
original_stderr = sys.stderr
|
||||
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
|
||||
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:
|
||||
value = int(_env(name, str(default)) or str(default))
|
||||
except ValueError:
|
||||
return default
|
||||
return max(value, min_value)
|
||||
|
||||
|
||||
def _rotate_log_file_if_needed(path: Path) -> None:
|
||||
"""
|
||||
在打开日志前做大小轮转,避免 Windows 常驻 worker 单个日志无限增长。
|
||||
|
||||
核心逻辑:当 `SHIPPING_NOTICE_RPA_WORKER_LOG_FILE` 已存在且大小达到 `SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES`
|
||||
时,按 `.1`、`.2` ... 备份后缀向后滚动;超过 `SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT`
|
||||
的旧文件会被删除。`SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES<=0` 时禁用轮转。
|
||||
"""
|
||||
max_bytes = _log_int_env("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", 10 * 1024 * 1024, min_value=0)
|
||||
backup_count = _log_int_env("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", 5, min_value=0)
|
||||
if max_bytes <= 0 or not path.is_file():
|
||||
return
|
||||
try:
|
||||
if path.stat().st_size < max_bytes:
|
||||
return
|
||||
except OSError:
|
||||
return
|
||||
|
||||
if backup_count <= 0:
|
||||
path.unlink(missing_ok=True)
|
||||
return
|
||||
|
||||
oldest = Path(f"{path}.{backup_count}")
|
||||
oldest.unlink(missing_ok=True)
|
||||
for index in range(backup_count - 1, 0, -1):
|
||||
src = Path(f"{path}.{index}")
|
||||
if src.exists():
|
||||
src.replace(Path(f"{path}.{index + 1}"))
|
||||
path.replace(Path(f"{path}.1"))
|
||||
|
||||
|
||||
def _backend_dir() -> Path:
|
||||
"""
|
||||
返回仓库内 backend 根目录。
|
||||
@@ -2732,14 +2525,14 @@ def _run_periodic_disk_cleanup(
|
||||
if not force and (now_mono - last_cleanup_mono) < interval:
|
||||
return last_cleanup_mono
|
||||
try:
|
||||
_maybe_rotate_open_log()
|
||||
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,
|
||||
log_file=active_log_path(),
|
||||
)
|
||||
print(worker_disk_cleanup.format_cleanup_summary(stats))
|
||||
except Exception as exc:
|
||||
@@ -2754,7 +2547,7 @@ def main() -> None:
|
||||
核心逻辑:主循环扫描库存/上传 trigger;空闲时按间隔清理本机归档与临时文件,
|
||||
防止长期运行撑爆 RPA 主机盘符。
|
||||
"""
|
||||
log_path = _configure_file_logging()
|
||||
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")
|
||||
|
||||
@@ -33,6 +33,10 @@ if _RPA_ROOT is not None:
|
||||
|
||||
from rpa_common import browser_timeout_ms, click_text, env, select_or_fill # noqa: E402
|
||||
from trigger_consumer import archive_trigger, claim_trigger # noqa: E402
|
||||
import rpa_heartbeat # noqa: E402
|
||||
import worker_logging # noqa: E402
|
||||
import worker_disk_cleanup # noqa: E402
|
||||
from worker_disk_cleanup import cleanup_interval_seconds, format_cleanup_summary, run_worker_disk_cleanup # noqa: E402
|
||||
import receipt_crane_export # noqa: E402
|
||||
import receipt_dbs_export # noqa: E402
|
||||
|
||||
@@ -42,6 +46,14 @@ def _backend_dir() -> Path:
|
||||
return _RPA_ROOT.parents[1] / 'backend'
|
||||
|
||||
|
||||
def _mask_secret(value: str | None) -> str:
|
||||
"""掩码打印密钥:保留前 4 后 4,其余以 .... 代替;缺失或过短返回占位。"""
|
||||
value = str(value or '').strip()
|
||||
if len(value) <= 8:
|
||||
return '***' if value else 'missing'
|
||||
return f'{value[:4]}....{value[-4:]}'
|
||||
|
||||
|
||||
def _require_dir(variable: str) -> Path:
|
||||
"""读取 receipt 专用目录;不回退至库存共享路径。"""
|
||||
value = env(variable)
|
||||
@@ -150,6 +162,7 @@ def _validate_unit(unit: dict[str, Any]) -> None:
|
||||
|
||||
def _report_failure(unit: dict[str, Any], exc: Exception) -> None:
|
||||
"""失败单元单独回调;callback 本身失败则由 trigger failed 目录留待人工处理。"""
|
||||
print(f'[receipt-unit] failed source={unit.get("source_code")} callback={unit.get("callback_id")} error={str(exc)[:200]}')
|
||||
_post_callback({'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit.get('callback_id'), 'status': 'failed', 'error_code': 'RPA.RECEIPT_EXPORT_FAILED', 'error_message': str(exc)[:2000]})
|
||||
|
||||
|
||||
@@ -165,6 +178,7 @@ def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
|
||||
_validate_unit(item)
|
||||
grouped.setdefault((str(item['connector_type']).lower(), str(item['rpa_profile_code']), str(item['login_url'])), []).append(dict(item))
|
||||
for (connector, _profile, login_url), group in grouped.items():
|
||||
print(f'[receipt-batch] connector={connector} profile={_profile} units={len(group)}')
|
||||
mock = env('SHIPPING_NOTICE_RPA_WORKER_MOCK', 'false').lower() == 'true'
|
||||
resources = (None, None, None, None)
|
||||
try:
|
||||
@@ -188,6 +202,10 @@ def _process_units(body: dict[str, Any], drop_dir: Path) -> None:
|
||||
else:
|
||||
download = receipt_crane_export.export_receipt_report(page, unit, env=env, browser_timeout_ms=browser_timeout_ms(), select_or_fill=select_or_fill, click_text=click_text, first_in_profile=index == 0)
|
||||
output = _save_download(download, drop_dir, unit)
|
||||
print(
|
||||
f'[receipt-unit] success source={unit["source_code"]} '
|
||||
f'callback={unit["callback_id"]} file={output.name} size={output.stat().st_size}'
|
||||
)
|
||||
_post_callback({'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit['callback_id'], 'status': 'success', 'file_path': str(output), 'original_filename': output.name, 'sha256': hashlib.sha256(output.read_bytes()).hexdigest()})
|
||||
except Exception as exc:
|
||||
_report_failure(unit, exc)
|
||||
@@ -210,28 +228,96 @@ def _claim_and_process(path: Path, drop_dir: Path) -> None:
|
||||
claimed = claim_trigger(path)
|
||||
if claimed is None:
|
||||
return
|
||||
print(f'[receipt-trigger] claimed {claimed.name}')
|
||||
# 心跳运行态对齐库存 Worker:领取成功即 busy,处理结束(含归档 failed 后 re-raise)
|
||||
# 由 finally 恢复 idle,保证 SystemExit 兜底路径也不会让监控长期挂 busy。
|
||||
rpa_heartbeat.set_worker_runtime_status('busy')
|
||||
try:
|
||||
_process_units(json.loads(claimed.read_text(encoding='utf-8')), drop_dir)
|
||||
archive_trigger(claimed, 'processed')
|
||||
print(f'[receipt-trigger] archived processed {claimed.name}')
|
||||
except (Exception, SystemExit):
|
||||
# SystemExit 也一并捕获:_require_dir 缺 env 会抛 SystemExit(非 Exception),
|
||||
# 若不捕获会静默退出进程、trigger 卡死在 processing/,无法归档到 failed/。
|
||||
archive_trigger(claimed, 'failed')
|
||||
print(f'[receipt-trigger] archived failed {claimed.name}')
|
||||
raise
|
||||
finally:
|
||||
rpa_heartbeat.set_worker_runtime_status('idle')
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""轮询收料专用 trigger 目录;不加载或扫描任何库存/upload 目录。"""
|
||||
worker_logging.configure_file_logging() # 未配置 LOG_FILE 时 no-op,仅 stdout
|
||||
drop_dir = _require_dir('SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR')
|
||||
trigger_dir = _require_dir('SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR')
|
||||
poll = max(1, int(env('SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS', '3') or '3'))
|
||||
print(f'[freight_receipt_rpa_worker] started trigger_dir={trigger_dir} drop_dir={drop_dir}')
|
||||
heartbeat_seconds = max(
|
||||
15,
|
||||
int(env('SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS', '20') or '20'),
|
||||
)
|
||||
last_cleanup_mono = 0.0
|
||||
cleanup_interval = cleanup_interval_seconds()
|
||||
# [STEP 1] 启动 banner:字段对齐库存 Worker,排查时一处看全运行配置。
|
||||
print(
|
||||
'[freight_receipt_rpa_worker] started\n'
|
||||
f' mock={env("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")}\n'
|
||||
f' api_base={env("HXOPS_API_BASE", "http://127.0.0.1:5052").rstrip("/")}\n'
|
||||
f' poll_seconds={poll}\n'
|
||||
f' heartbeat_seconds={heartbeat_seconds}\n'
|
||||
f' headless={env("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false")} '
|
||||
f'channel={env("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL") or "default-chromium"}\n'
|
||||
f' auth_key={_mask_secret(env("SHIPPING_NOTICE_TOOL_API_KEY") or env("INTEGRATION_API_KEY"))}\n'
|
||||
f' credential_key={_mask_secret(env("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY"))}\n'
|
||||
f' trigger_dir={trigger_dir}\n'
|
||||
f' drop_dir={drop_dir}\n'
|
||||
f' browser_profile_dir={env("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR") or "missing"}\n'
|
||||
f' log={worker_logging.active_log_path() or "stdout-only"}\n'
|
||||
f' disk_retention_days={worker_disk_cleanup.retention_days()} cleanup_interval_seconds={cleanup_interval}'
|
||||
)
|
||||
|
||||
def _run_cleanup_if_due(now_mono: float, *, force: bool = False) -> float:
|
||||
"""按间隔执行保留清理;启动时强制一轮。
|
||||
|
||||
best-effort 语义:清理失败仅打印告警,不中断主循环;且无论成败都推进
|
||||
上次清理时钟(返回 now_mono),避免持续性故障在每次 poll 后立刻重试刷屏。
|
||||
"""
|
||||
nonlocal last_cleanup_mono
|
||||
if not force and (now_mono - last_cleanup_mono) < cleanup_interval:
|
||||
return last_cleanup_mono
|
||||
profile_root_raw = str(env('SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR') or '').strip()
|
||||
try:
|
||||
stats = run_worker_disk_cleanup(
|
||||
inventory_trigger_dir=trigger_dir, # 该函数只清 processed/failed 归档,绝不碰根目录待领取 *.json
|
||||
drop_dir=drop_dir,
|
||||
browser_profile_dir=Path(profile_root_raw) if profile_root_raw else None,
|
||||
log_file=worker_logging.active_log_path(),
|
||||
)
|
||||
print(format_cleanup_summary(stats))
|
||||
except Exception as exc:
|
||||
print(f'[receipt-cleanup] failed: {exc}')
|
||||
return now_mono
|
||||
|
||||
# [STEP 2] 启动即清一轮(对齐库存节奏),避免重启前堆积的归档/孤儿 Profile 撑盘。
|
||||
last_cleanup_mono = _run_cleanup_if_due(time.monotonic(), force=True)
|
||||
# 启动时立即上报一次心跳(对齐库存 Worker),让监控端第一时间出现独立的
|
||||
# `<hostname>-receipt` 收料 Worker 卡片(WORKER_ID 由 ps1 注入,避免按 pid 抖动)。
|
||||
rpa_heartbeat.maybe_send_heartbeat(
|
||||
trigger_dir=str(trigger_dir), drop_dir=str(drop_dir), last_sent_mono=0.0, force=True,
|
||||
)
|
||||
# 心跳节奏交由独立守护线程承担:收料批量导出会长时间阻塞主循环,
|
||||
# 若由主循环发送心跳,执行期间会停发并被后端按 TTL 误判离线。
|
||||
rpa_heartbeat.start_heartbeat_loop(
|
||||
trigger_dir=str(trigger_dir), drop_dir=str(drop_dir), interval_seconds=heartbeat_seconds,
|
||||
)
|
||||
while True:
|
||||
for path in sorted(trigger_dir.glob('*.json')):
|
||||
worker_logging.maybe_rotate_open_log()
|
||||
try:
|
||||
_claim_and_process(path, drop_dir)
|
||||
except Exception as exc:
|
||||
print(f'[receipt-trigger] failed {path.name}: {exc}')
|
||||
last_cleanup_mono = _run_cleanup_if_due(time.monotonic())
|
||||
time.sleep(poll)
|
||||
|
||||
|
||||
|
||||
@@ -42,6 +42,10 @@ $processVars = [ordered]@{
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEADLESS = $(if ($Headless) { 'true' } else { 'false' })
|
||||
# 不设 BROWSER_CHANNEL:默认 Playwright 捆绑 Chromium(禁止默认 msedge,见库存 Worker 同因)。
|
||||
SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = '3'
|
||||
SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = Join-Path $dataRoot 'logs\worker.log'
|
||||
# 独立 Worker 身份:监控端按 worker_id 出独立收料卡片,固定后缀避免与库存 Worker/按 pid 的身份抖动。
|
||||
SHIPPING_NOTICE_RPA_WORKER_ID = "${env:COMPUTERNAME}-receipt"
|
||||
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS = '20'
|
||||
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR = Join-Path $dataRoot 'receipt_triggers'
|
||||
SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR = Join-Path $dataRoot 'receipt_drop'
|
||||
# 浏览器 Profile 目录复用既有标准变量(与库存 RPA Worker 一致),不另设 RECEIPT_* 冗余变量。
|
||||
|
||||
Reference in new issue
Block a user