更新文件说明
This commit is contained in:
@@ -61,3 +61,5 @@ COLLECTOR_SCRIPT = os.getenv("HOTEL_COLLECTOR_SCRIPT", "酒店详情.py")
|
||||
COLLECTOR_PYTHON = os.getenv("HOTEL_COLLECTOR_PYTHON") or sys.executable
|
||||
COLLECTOR_PID_FILE = COLLECTOR_DIR / "logs" / "collector.pid"
|
||||
COLLECTOR_LOG_FILE = COLLECTOR_DIR / "logs" / "collector.out.log"
|
||||
# 采集脚本自己写的状态文件(最近一次退出原因:城市 / 平台返回 / 异常)
|
||||
COLLECTOR_STATE_FILE = COLLECTOR_DIR / "logs" / "collector_state.json"
|
||||
|
||||
@@ -9,7 +9,9 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
@@ -21,8 +23,12 @@ from ..config import (
|
||||
COLLECTOR_PID_FILE,
|
||||
COLLECTOR_PYTHON,
|
||||
COLLECTOR_SCRIPT,
|
||||
COLLECTOR_STATE_FILE,
|
||||
)
|
||||
|
||||
# 运行中超过这么久没有日志输出,判定为“疑似卡住”(典型是代理不回包)
|
||||
STALL_SECONDS = 180
|
||||
|
||||
# Windows 进程创建标志
|
||||
CREATE_NEW_PROCESS_GROUP = 0x00000200
|
||||
CREATE_NO_WINDOW = 0x08000000
|
||||
@@ -65,6 +71,39 @@ def _pid_alive(pid: int | None) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def read_state() -> dict:
|
||||
"""读采集脚本写的状态文件(最近一次启动/退出原因)。读不到返回空 dict。"""
|
||||
try:
|
||||
data = json.loads(COLLECTOR_STATE_FILE.read_text(encoding="utf-8"))
|
||||
return data if isinstance(data, dict) else {}
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
def _mark_user_stop() -> None:
|
||||
"""看板点「停止」时进程是被 taskkill 的,脚本来不及写 state —— 这里补一条,
|
||||
否则页面上会一直挂着上一次崩溃的原因。"""
|
||||
state = read_state()
|
||||
now = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
|
||||
state["last_exit"] = {
|
||||
"at": now,
|
||||
"reason": "stopped_by_user",
|
||||
"city": None,
|
||||
"city_name": None,
|
||||
"hd_id": None,
|
||||
"package_cities": None,
|
||||
"error": None,
|
||||
"platform_response": None,
|
||||
"traceback": None,
|
||||
}
|
||||
state["updated_at"] = now
|
||||
try:
|
||||
COLLECTOR_STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
COLLECTOR_STATE_FILE.write_text(json.dumps(state, ensure_ascii=False), encoding="utf-8")
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def read_pid() -> int | None:
|
||||
"""读 collector.pid(不存在 / 内容非法都返回 None)。"""
|
||||
try:
|
||||
@@ -93,27 +132,62 @@ def current_pid() -> int | None:
|
||||
return None
|
||||
|
||||
|
||||
def tail(lines: int = 12) -> list[str]:
|
||||
_ANSI = re.compile(r"\x1b\[[0-9;]*m")
|
||||
|
||||
|
||||
def tail(lines: int = 12, max_chars: int = 300) -> list[str]:
|
||||
"""只读日志末尾 128KB(日志可能几百 MB,不能整个读进内存),并去掉 ANSI 颜色码。"""
|
||||
try:
|
||||
with COLLECTOR_LOG_FILE.open("r", encoding="utf-8", errors="replace") as f:
|
||||
return [ln.rstrip() for ln in f.readlines()[-lines:]]
|
||||
size = COLLECTOR_LOG_FILE.stat().st_size
|
||||
with COLLECTOR_LOG_FILE.open("rb") as f:
|
||||
chunk = min(size, 128 * 1024)
|
||||
f.seek(size - chunk)
|
||||
data = f.read(chunk)
|
||||
text = data.decode("utf-8", errors="replace")
|
||||
out: list[str] = []
|
||||
for line in text.splitlines()[-lines:]:
|
||||
s = _ANSI.sub("", line).strip()
|
||||
if len(s) > max_chars:
|
||||
s = s[:max_chars] + "…"
|
||||
out.append(s)
|
||||
return out
|
||||
except OSError:
|
||||
return []
|
||||
|
||||
|
||||
def _state_started_at(state: dict) -> float | None:
|
||||
raw = state.get("started_at")
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
return time.mktime(time.strptime(str(raw), "%Y-%m-%dT%H:%M:%S"))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def status() -> dict:
|
||||
pid = current_pid()
|
||||
state = read_state()
|
||||
started: float | None = None
|
||||
if pid:
|
||||
if _proc is not None and _proc.pid == pid and _proc.poll() is None:
|
||||
started = _started_at
|
||||
else:
|
||||
if started is None:
|
||||
started = _state_started_at(state) # 控制台手动起的,脚本自己写了启动时间
|
||||
if started is None:
|
||||
try:
|
||||
started = COLLECTOR_PID_FILE.stat().st_mtime
|
||||
except OSError:
|
||||
started = None
|
||||
|
||||
try:
|
||||
log_age = int(time.time() - COLLECTOR_LOG_FILE.stat().st_mtime)
|
||||
except OSError:
|
||||
log_age = None
|
||||
|
||||
running = bool(pid)
|
||||
return {
|
||||
"running": bool(pid),
|
||||
"running": running,
|
||||
"pid": pid,
|
||||
"source": "api" if (pid and _proc is not None and _proc.pid == pid) else ("manual" if pid else None),
|
||||
"started_at": datetime.fromtimestamp(started).strftime("%Y-%m-%d %H:%M:%S") if started else None,
|
||||
@@ -123,6 +197,12 @@ def status() -> dict:
|
||||
"python": COLLECTOR_PYTHON,
|
||||
"log_file": str(COLLECTOR_LOG_FILE),
|
||||
"log_tail": tail(),
|
||||
# 诊断:最近一次启动/退出原因(脚本自己写 collector_state.json)
|
||||
"state_updated_at": state.get("updated_at"),
|
||||
"last_exit": state.get("last_exit"),
|
||||
# 卡死判定:还在跑,但日志已经 STALL_SECONDS 秒没动静
|
||||
"log_age_seconds": log_age,
|
||||
"stalled": bool(running and log_age is not None and log_age > STALL_SECONDS),
|
||||
}
|
||||
|
||||
|
||||
@@ -217,4 +297,5 @@ def stop() -> dict:
|
||||
COLLECTOR_PID_FILE.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
_mark_user_stop()
|
||||
return status()
|
||||
|
||||
Reference in New Issue
Block a user