# -*- coding: utf-8 -*- """设备级单活调度器:整机同一时刻只运行一个插件进程。 - active.json 记录设备级当前运行 {userId, pluginId, version, status, startedAt}。 - 模块级锁 + 磁盘状态双重保证单活:同一时刻只有一个插件在跑,与用户无关。 - 用户切换插件/切换用户 = 停旧插件(整树终止) → 清理 → 启动新插件 → 健康检查 → 激活; 启动失败回滚到"空闲",不让半激活状态阻塞后续启动。 """ from __future__ import annotations import json import logging import os import subprocess import sys import threading import time from datetime import datetime from pathlib import Path _LOGGER = logging.getLogger(__name__) _APP_DATA = Path(os.getenv("LOCALAPPDATA") or os.getenv("APPDATA") or Path.home(), "37duAutomation") ACTIVE_PATH = _APP_DATA / "active.json" # 全局单活条件变量:同一时刻只能有一个插件进程。请求先等待当前插件执行完成(完全不能并发)。 _SCHED_COND = threading.Condition() def init_active() -> None: """初始化 active.json(无则写入空闲态),并确保数据目录可写。 进程启动时若残留 running/switching(上次异常退出/断电),复位为空闲, 防止 request_start 的死等条件永远不满足导致所有插件永久排队。""" _APP_DATA.mkdir(exist_ok=True) if not ACTIVE_PATH.is_file(): write_active(userId="", pluginId="", version="", status="idle") elif read_active().get("status") in ("running", "switching"): _LOGGER.warning("检测到上次异常退出残留的运行状态(running/switching),复位为空闲") write_active(status="idle", userId="", pluginId="", version="", runId="", startedAt="") def read_active() -> dict: try: d = json.loads(ACTIVE_PATH.read_text(encoding="utf-8")) if ACTIVE_PATH.is_file() else {} return d if isinstance(d, dict) else {} except Exception: # noqa: BLE001 return {} def _is_busy() -> bool: return read_active().get("status") in ("running", "switching") def write_active(**kw) -> None: """写回 active.json(保留既有键,仅更新传入字段)。""" d = read_active() d.update(kw) d.setdefault("userId", "") d.setdefault("pluginId", "") d.setdefault("version", "") d.setdefault("status", "idle") d.setdefault("startedAt", "") d.setdefault("runId", "") try: # 原子写:先写临时文件再 os.replace,避免写入中断留下半截 JSON 被误读 tmp = ACTIVE_PATH.with_suffix(".json.tmp") tmp.write_text(json.dumps(d, ensure_ascii=False), encoding="utf-8") os.replace(tmp, ACTIVE_PATH) except OSError as _exc: # noqa: BLE001 _LOGGER.warning("写 active.json 失败:%s", _exc) def current() -> dict: """当前活动插件(空闲则返回空映射)。""" return read_active() def is_active(plugin_id: str) -> bool: """当前设备是否正在跑该插件。""" a = read_active() return bool(a.get("status") == "running" and a.get("pluginId") == plugin_id) def request_start(user: str, plugin_id: str, version: str, start_fn) -> dict: """设备级单活启动:阻塞等待当前插件执行完成后再启动目标(完全不能并发)。 - 若设备正有插件在跑(running/switching),本请求会在此等待,直至该插件执行结束。 - `start_fn` 负责拉起子进程并返回 run_id(不可阻塞),即视为占用单活槽位。 - 启动失败回滚到"空闲"并唤醒等待者。 """ with _SCHED_COND: while _is_busy(): _SCHED_COND.wait() write_active(status="switching", startedAt=_now()) try: run_id = start_fn() except Exception as _exc: # noqa: BLE001 write_active(status="idle") _SCHED_COND.notify_all() return {"ok": False, "error": f"启动失败:{_exc}"} write_active(userId=user, pluginId=plugin_id, version=version, status="running", runId=run_id, startedAt=_now()) return {"ok": True, "run_id": run_id} def mark_done(plugin_id: str, run_id: str) -> None: """运行结束:若 active 仍是该插件则回空闲,并唤醒等待的后续请求(幂等)。""" with _SCHED_COND: a = read_active() if a.get("pluginId") == plugin_id and a.get("runId") == run_id: write_active(status="idle") _SCHED_COND.notify_all() elif a.get("pluginId") == plugin_id: write_active(status="idle") _SCHED_COND.notify_all() def _now() -> str: return datetime.now().strftime("%Y-%m-%d %H:%M:%S")