feat(shipping-notice): 增加 RPA Worker 心跳上报与状态查询功能
This commit is contained in:
1 parent
c3f05ba96b
commit
5a147c4d85
49 files changed
+4032
-1500
No files matched your search
@@ -0,0 +1,201 @@
|
||||
"""
|
||||
scripts/rpa/freight_rpa_heartbeat.py
|
||||
|
||||
用途:货代 RPA Worker 向后端上报心跳(POST /api/shipping-notice/rpa/heartbeat)。
|
||||
依赖:rpa_common.env、urllib、socket。
|
||||
逻辑:由 freight_rpa_worker 主循环按 FREIGHT_RPA_HEARTBEAT_SECONDS 周期调用;同步写入共享目录哨兵文件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import socket
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from rpa_common import env as _env
|
||||
|
||||
_RUNTIME_STATUS = "idle"
|
||||
_LAST_HEARTBEAT_MONO = 0.0
|
||||
_DEFAULT_SENTINEL_NAME = ".hxops_rpa_shared_mount"
|
||||
|
||||
|
||||
def set_worker_runtime_status(status: str) -> None:
|
||||
"""更新 worker 运行态(idle / busy),供心跳上报。"""
|
||||
global _RUNTIME_STATUS
|
||||
normalized = str(status or "idle").strip().lower()
|
||||
_RUNTIME_STATUS = normalized if normalized in {"idle", "busy"} else "idle"
|
||||
|
||||
|
||||
def get_worker_runtime_status() -> str:
|
||||
return _RUNTIME_STATUS
|
||||
|
||||
|
||||
def _resolve_worker_environment() -> str:
|
||||
raw = (
|
||||
_env("FREIGHT_RPA_ENVIRONMENT")
|
||||
or _env("ENV_NAME")
|
||||
or _env("HXOPS_ENV")
|
||||
or "dev"
|
||||
)
|
||||
value = str(raw or "dev").strip().lower()
|
||||
if value in {"development", ""}:
|
||||
return "dev"
|
||||
if value in {"testing"}:
|
||||
return "test"
|
||||
if value in {"production"}:
|
||||
return "prod"
|
||||
return value
|
||||
|
||||
|
||||
def _resolve_shared_scope_id() -> str:
|
||||
raw = (
|
||||
_env("FREIGHT_RPA_SHARED_SCOPE_ID")
|
||||
or _env("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID")
|
||||
or ""
|
||||
)
|
||||
value = str(raw or "").strip()
|
||||
if value:
|
||||
return value
|
||||
trigger = str(_env("FREIGHT_RPA_INVENTORY_TRIGGER_DIR") or "").replace("\\", "/").lower()
|
||||
for token in ("hxops-rpa-test-data", "hxops-rpa-prod-data"):
|
||||
if token in trigger:
|
||||
return token
|
||||
return ""
|
||||
|
||||
|
||||
def _resolve_sentinel_name() -> str:
|
||||
return str(
|
||||
_env("FREIGHT_RPA_SHARED_SENTINEL_NAME")
|
||||
or _env("SHIPPING_NOTICE_RPA_SHARED_SENTINEL_NAME")
|
||||
or _DEFAULT_SENTINEL_NAME
|
||||
).strip() or _DEFAULT_SENTINEL_NAME
|
||||
|
||||
|
||||
def _resolve_worker_id(hostname: str) -> str:
|
||||
explicit = str(_env("FREIGHT_RPA_WORKER_ID") or "").strip()
|
||||
if explicit:
|
||||
return explicit
|
||||
pid = os.getpid()
|
||||
return f"{hostname}-{pid}"
|
||||
|
||||
|
||||
def write_shared_mount_sentinel(*, trigger_dir: str | Path, hostname: str | None = None) -> None:
|
||||
"""
|
||||
在 trigger 共享目录写入哨兵文件,供 Ubuntu 后端校验 CIFS 挂载与 scope 一致。
|
||||
核心逻辑:不创建 trigger 根目录,仅更新已存在目录下的哨兵文件。
|
||||
"""
|
||||
scope_id = _resolve_shared_scope_id()
|
||||
if not scope_id:
|
||||
return
|
||||
root = Path(trigger_dir)
|
||||
if not root.is_dir():
|
||||
return
|
||||
host = hostname or socket.gethostname()
|
||||
body = "\n".join([
|
||||
f"scope_id={scope_id}",
|
||||
f"updated_at={datetime.now(UTC).replace(tzinfo=None).isoformat()}",
|
||||
f"host={host}",
|
||||
f"worker_id={_resolve_worker_id(host)}",
|
||||
])
|
||||
sentinel_path = root / _resolve_sentinel_name()
|
||||
sentinel_path.write_text(body + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def build_heartbeat_payload(
|
||||
*,
|
||||
trigger_dir: str | Path,
|
||||
drop_dir: str | Path,
|
||||
status: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
组装心跳 payload。
|
||||
核心逻辑:capabilities 固定包含 inventory_export;shared_scope_id 用于跨平台路径对齐。
|
||||
"""
|
||||
hostname = socket.gethostname()
|
||||
return {
|
||||
"worker_id": _resolve_worker_id(hostname),
|
||||
"hostname": hostname,
|
||||
"environment": _resolve_worker_environment(),
|
||||
"capabilities": ["inventory_export"],
|
||||
"status": status or get_worker_runtime_status(),
|
||||
"trigger_dir": str(trigger_dir),
|
||||
"drop_dir": str(drop_dir),
|
||||
"shared_scope_id": _resolve_shared_scope_id(),
|
||||
"version": str(_env("FREIGHT_RPA_WORKER_VERSION", "rpa-poc") or "rpa-poc"),
|
||||
"timestamp": datetime.now(UTC).replace(tzinfo=None).isoformat(),
|
||||
}
|
||||
|
||||
|
||||
def post_heartbeat(payload: dict[str, Any]) -> bool:
|
||||
"""
|
||||
向后端上报心跳。
|
||||
Returns:
|
||||
bool: HTTP 2xx 时 True,否则 False(不中断 worker 主循环)。
|
||||
"""
|
||||
base = str(_env("HXOPS_API_BASE", "http://127.0.0.1:5052") or "http://127.0.0.1:5052").rstrip("/")
|
||||
key = (
|
||||
_env("SHIPPING_NOTICE_TOOL_API_KEY")
|
||||
or _env("INTEGRATION_API_KEY")
|
||||
or _env("HXOPS_TOOLS_API_KEY")
|
||||
)
|
||||
if not key:
|
||||
print("[heartbeat] skipped: missing SHIPPING_NOTICE_TOOL_API_KEY", file=sys.stderr)
|
||||
return False
|
||||
|
||||
url = f"{base}/api/shipping-notice/rpa/heartbeat"
|
||||
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"X-Integration-Key": key,
|
||||
"X-Shipping-Tool-Key": key,
|
||||
},
|
||||
method="POST",
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=8) as resp:
|
||||
return 200 <= int(resp.status) < 300
|
||||
except urllib.error.HTTPError as exc:
|
||||
body = ""
|
||||
try:
|
||||
body = exc.read().decode("utf-8", errors="replace")[:500]
|
||||
except Exception:
|
||||
body = ""
|
||||
print(f"[heartbeat] HTTP {exc.code} {body}", file=sys.stderr)
|
||||
return False
|
||||
except Exception as exc:
|
||||
print(f"[heartbeat] failed: {exc}", file=sys.stderr)
|
||||
return False
|
||||
|
||||
|
||||
def maybe_send_heartbeat(
|
||||
*,
|
||||
trigger_dir: str | Path,
|
||||
drop_dir: str | Path,
|
||||
last_sent_mono: float,
|
||||
force: bool = False,
|
||||
) -> float:
|
||||
"""
|
||||
按 FREIGHT_RPA_HEARTBEAT_SECONDS 节流发送心跳。
|
||||
Returns:
|
||||
float: 最近一次尝试后的 monotonic 时间戳(成功或失败均更新节流时钟)。
|
||||
"""
|
||||
global _LAST_HEARTBEAT_MONO
|
||||
interval = max(15, int(_env("FREIGHT_RPA_HEARTBEAT_SECONDS", "20") or "20"))
|
||||
now = time.monotonic()
|
||||
if not force and last_sent_mono and (now - last_sent_mono) < interval:
|
||||
return last_sent_mono
|
||||
write_shared_mount_sentinel(trigger_dir=trigger_dir)
|
||||
payload = build_heartbeat_payload(trigger_dir=trigger_dir, drop_dir=drop_dir)
|
||||
post_heartbeat(payload)
|
||||
_LAST_HEARTBEAT_MONO = now
|
||||
return now
|
||||
Reference in new issue
Block a user