feat: 新增壳子内置定时任务功能,支持配置备份与恢复
本次提交新增完整的定时任务系统: 1. 后端支持cron表达式调度插件执行,与手动运行共用执行链路 2. 前端新增定时任务管理页面,支持增删改查与启停操作 3. 实现配置自动备份到中心机,启动时自动从云端恢复任务 4. 配套新增数据库表与控制面API接口 5. 同时优化了考勤异常检查的规则细节
This commit is contained in:
@@ -13,6 +13,7 @@ import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
@@ -32,6 +33,61 @@ class RunReq(BaseModel):
|
||||
fields: dict = {}
|
||||
|
||||
|
||||
def submit_run(account: str, plugin, fields: dict) -> str:
|
||||
"""启动一次插件运行(手动 POST /api/runs 与定时任务共用入口)。
|
||||
|
||||
- 登记运行记录 + 广播 run_start + 上报 start;
|
||||
- 后台线程执行:命名空间并发闸(同平台串行)→ 设备级单活(排队等待当前插件结束)
|
||||
→ 拉起执行子进程;启动失败回滚单活槽位并广播 run_done(error)。
|
||||
返回 run_id。
|
||||
"""
|
||||
run_id = uuid.uuid4().hex
|
||||
with _st.RUN_LOCK:
|
||||
if len(_st.RUNS) >= _st.MAX_RUNS:
|
||||
_st.RUNS.pop(next(iter(_st.RUNS))) # dict 有序:弹出最老的记录
|
||||
_st.RUNS[run_id] = {"status": "running", "account": account,
|
||||
"version": getattr(plugin, "version", "0"),
|
||||
"started": time.time(),
|
||||
"result": None, "error": None}
|
||||
HUB.publish({"t": "run_start", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"at": datetime.now().strftime("%H:%M:%S")})
|
||||
licensing.report(account=account, device_id="", plugin_id=plugin.id,
|
||||
version=getattr(plugin, "version", "0"), status="start")
|
||||
|
||||
def _queued():
|
||||
# 平台命名空间并发闸:同平台任务串行,登录态 cookies 不被并发争抢
|
||||
gate = _st._ns_gate(plugin.platform)
|
||||
if gate.locked():
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": "INFO",
|
||||
"msg": f"同平台任务执行中,排队等待(命名空间 {plugin.platform or 'local'})…"})
|
||||
with gate:
|
||||
# 设备级单活(完全不能并发):若有插件在跑则先等它执行完成,再启动当前
|
||||
if _scheduler._is_busy():
|
||||
HUB.publish({"t": "log", "run_id": run_id, "plugin_id": plugin.id,
|
||||
"level": "INFO",
|
||||
"msg": "设备正有其他插件执行中,排队等待其完成后自动启动…"})
|
||||
|
||||
def _start():
|
||||
threading.Thread(target=_run_target,
|
||||
args=(plugin, fields, run_id),
|
||||
daemon=True, name=f"exec-{plugin.id}").start()
|
||||
return run_id
|
||||
|
||||
r = _scheduler.request_start(account, plugin.id,
|
||||
getattr(plugin, "version", "0"), _start)
|
||||
if not r.get("ok"):
|
||||
# 启动失败(回滚已发生):落地错误结果并广播,避免前端永久等待
|
||||
_st._set_run(run_id, status="error", result=None,
|
||||
error=r.get("error") or "启动失败")
|
||||
HUB.publish({"t": "run_done", "run_id": run_id, "ok": False,
|
||||
"error": r.get("error") or "启动失败"})
|
||||
|
||||
threading.Thread(target=_queued, daemon=True,
|
||||
name=f"run-{plugin.id}").start()
|
||||
return run_id
|
||||
|
||||
|
||||
# ==================== 手动强制停止 ====================
|
||||
# run_id → 执行中 Job 句柄(供 POST /api/runs/{id}/stop 整树强杀,含浏览器孙进程)
|
||||
_ACTIVE: dict = {}
|
||||
|
||||
@@ -0,0 +1,417 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主定时任务(壳子内置定时):按 cron 触发插件运行。
|
||||
|
||||
- 配置真源:%LOCALAPPDATA%\\37duAutomation\\schedules.json(按账号隔离,任务归属创建者账号)。
|
||||
- 触发链路与手动 POST /api/runs 完全一致(runner.submit_run):
|
||||
命名空间并发闸 + 设备级单活排队 + 授权/下架/禁用/强制更新校验(licensing.run_check_allowed)。
|
||||
- 变更即备份:增删改/启停后把该账号全量配置推送到中心机(/api/schedules/backup);
|
||||
本地缺失时启动按账号从服务端合并恢复(见 restore_from_cloud),配置不丢失。
|
||||
- 后台线程每 30s 检查一次,到点触发;last_run_at 记忆上次触发时刻,
|
||||
壳子重启后错过的触发点会立即补跑(last_run_at 之前的值保留,不重复触发同一时刻)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
_APP_DATA = Path(os.getenv("LOCALAPPDATA") or os.getenv("APPDATA")
|
||||
or Path.home(), "37duAutomation")
|
||||
_SCHED_FILE = _APP_DATA / "schedules.json"
|
||||
|
||||
_TICK_SECS = 30 # 后台检查周期(秒)
|
||||
_STARTED = False
|
||||
|
||||
_LOCK = threading.RLock()
|
||||
# 内存中的任务列表(dict 列表),持久化到 _SCHED_FILE
|
||||
_SCHEDULES: list = []
|
||||
|
||||
|
||||
# ==================== 标准 5 段 cron 解析 ====================
|
||||
# 字段顺序:分 时 日 月 周(minute hour day-of-month month day-of-week)
|
||||
def _parse_field(spec: str, lo: int, hi: int) -> set:
|
||||
"""解析单个 cron 字段为命中集合;支持 * ? */n a-b a-b/n 与逗号列表。非法抛 ValueError。"""
|
||||
if spec in ("*", "?"):
|
||||
return set(range(lo, hi + 1))
|
||||
out: set = set()
|
||||
for part in str(spec).split(","):
|
||||
part = part.strip()
|
||||
if not part:
|
||||
continue
|
||||
step = 1
|
||||
if "/" in part:
|
||||
part, _, step_s = part.partition("/")
|
||||
try:
|
||||
step = int(step_s)
|
||||
except ValueError:
|
||||
raise ValueError(f"无效步长:{step_s}")
|
||||
if step < 1:
|
||||
raise ValueError(f"无效步长:{step_s}")
|
||||
if part in ("*", "?"):
|
||||
rng = (lo, hi)
|
||||
elif "-" in part:
|
||||
a, _, b = part.partition("-")
|
||||
rng = (int(a), int(b))
|
||||
else:
|
||||
v = int(part)
|
||||
rng = (v, v)
|
||||
a, b = rng
|
||||
if not (lo <= a <= hi and lo <= b <= hi) or a > b:
|
||||
raise ValueError(f"字段越界:{part}")
|
||||
out.update(range(a, b + 1, step))
|
||||
if not out:
|
||||
raise ValueError("空字段")
|
||||
return out
|
||||
|
||||
|
||||
def parse_cron(expr: str) -> dict:
|
||||
"""解析 5 段 cron 表达式;非法抛 ValueError。返回 {minute,hour,dom,month,dow} 集合。"""
|
||||
parts = str(expr or "").strip().split()
|
||||
if len(parts) != 5:
|
||||
raise ValueError("cron 需为 5 段:分 时 日 月 周")
|
||||
minute = _parse_field(parts[0], 0, 59)
|
||||
hour = _parse_field(parts[1], 0, 23)
|
||||
dom = _parse_field(parts[2], 1, 31)
|
||||
month = _parse_field(parts[3], 1, 12)
|
||||
dow = _parse_field(parts[4], 0, 7)
|
||||
has7 = 7 in dow # 标准 cron 中 0 与 7 均表示周日
|
||||
dow.discard(7)
|
||||
if has7:
|
||||
dow.add(0)
|
||||
return {"minute": minute, "hour": hour, "dom": dom, "month": month, "dow": dow}
|
||||
|
||||
|
||||
def _cron_dow(dt: datetime) -> int:
|
||||
"""cron 周日编号:0=周日,1=周一 … 6=周六。"""
|
||||
return (dt.weekday() + 1) % 7
|
||||
|
||||
|
||||
def next_match(cron: dict, after: datetime) -> datetime | None:
|
||||
"""返回严格晚于 after 的最近一个匹配时刻;一年内无匹配返回 None(如 2 月 30 日)。"""
|
||||
minute, hour, dom, month, dow = (cron["minute"], cron["hour"], cron["dom"],
|
||||
cron["month"], cron["dow"])
|
||||
dom_any = dom == set(range(1, 32))
|
||||
dow_any = dow == set(range(0, 7))
|
||||
t = after.replace(second=0, microsecond=0) + timedelta(minutes=1)
|
||||
for _ in range(10000):
|
||||
if t.month not in month:
|
||||
y, m = (t.year + 1, 1) if t.month == 12 else (t.year, t.month + 1)
|
||||
t = datetime(y, m, 1)
|
||||
continue
|
||||
# 标准语义:dom 与 dow 均有限制时,命中其一即可;仅一方限制则只按该方
|
||||
if not dom_any and not dow_any:
|
||||
day_ok = (t.day in dom) or (_cron_dow(t) in dow)
|
||||
elif not dow_any:
|
||||
day_ok = _cron_dow(t) in dow
|
||||
elif not dom_any:
|
||||
day_ok = t.day in dom
|
||||
else:
|
||||
day_ok = True
|
||||
if not day_ok:
|
||||
t = (t + timedelta(days=1)).replace(hour=0, minute=0)
|
||||
continue
|
||||
if t.hour not in hour:
|
||||
t = (t + timedelta(hours=1)).replace(minute=0)
|
||||
continue
|
||||
if t.minute not in minute:
|
||||
t += timedelta(minutes=1)
|
||||
continue
|
||||
return t
|
||||
return None
|
||||
|
||||
|
||||
# ==================== 本地存储与 CRUD ====================
|
||||
def _load() -> None:
|
||||
global _SCHEDULES
|
||||
with _LOCK:
|
||||
if _SCHED_FILE.is_file():
|
||||
try:
|
||||
data = json.loads(_SCHED_FILE.read_text(encoding="utf-8"))
|
||||
_SCHEDULES = [s for s in (data or {}).get("schedules", [])
|
||||
if isinstance(s, dict)]
|
||||
except (OSError, ValueError):
|
||||
_LOGGER.warning("定时任务配置损坏,已忽略:%s", _SCHED_FILE)
|
||||
_SCHEDULES = []
|
||||
else:
|
||||
_SCHEDULES = []
|
||||
|
||||
|
||||
def _persist() -> None:
|
||||
with _LOCK:
|
||||
_SCHED_FILE.parent.mkdir(parents=True, exist_ok=True)
|
||||
_SCHED_FILE.write_text(
|
||||
json.dumps({"schedules": _SCHEDULES}, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8")
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
def _new_id() -> str:
|
||||
return f"{int(time.time() * 1000):x}{os.urandom(4).hex()}"
|
||||
|
||||
|
||||
def get_schedule(sid: str) -> dict | None:
|
||||
"""按 id 取原始记录(调用方须持锁前读取,路由层只读不持有引用长期使用)。"""
|
||||
with _LOCK:
|
||||
for s in _SCHEDULES:
|
||||
if s.get("id") == sid:
|
||||
return dict(s)
|
||||
return None
|
||||
|
||||
|
||||
def list_schedules(account: str) -> list:
|
||||
with _LOCK:
|
||||
return [_public(s) for s in _SCHEDULES if s.get("account") == account]
|
||||
|
||||
|
||||
def create_schedule(account: str, payload: dict) -> dict:
|
||||
"""新增定时任务(cron 非法抛 ValueError)。"""
|
||||
cron = (payload.get("cron") or "").strip()
|
||||
parse_cron(cron)
|
||||
rec = {
|
||||
"id": _new_id(),
|
||||
"name": (payload.get("name") or "").strip() or "定时任务",
|
||||
"account": account,
|
||||
"plugin_id": payload.get("plugin_id", ""),
|
||||
"fields": payload.get("fields") or {},
|
||||
"cron": cron,
|
||||
"enabled": bool(payload.get("enabled", True)),
|
||||
"last_run_at": "",
|
||||
"created_at": _now(),
|
||||
"updated_at": _now(),
|
||||
}
|
||||
with _LOCK:
|
||||
_SCHEDULES.append(rec)
|
||||
_persist()
|
||||
return dict(rec)
|
||||
|
||||
|
||||
def update_schedule(sid: str, payload: dict) -> dict | None:
|
||||
"""更新任务(仅覆盖 payload 中出现的字段;cron 非法抛 ValueError)。"""
|
||||
if payload.get("cron"):
|
||||
parse_cron(payload["cron"])
|
||||
with _LOCK:
|
||||
for s in _SCHEDULES:
|
||||
if s.get("id") != sid:
|
||||
continue
|
||||
if "name" in payload:
|
||||
s["name"] = (payload["name"] or "").strip() or "定时任务"
|
||||
if "plugin_id" in payload:
|
||||
s["plugin_id"] = payload["plugin_id"]
|
||||
if "fields" in payload:
|
||||
s["fields"] = payload["fields"] or {}
|
||||
if payload.get("cron"):
|
||||
s["cron"] = payload["cron"].strip()
|
||||
if "enabled" in payload:
|
||||
s["enabled"] = bool(payload["enabled"])
|
||||
s["updated_at"] = _now()
|
||||
_persist()
|
||||
return dict(s)
|
||||
return None
|
||||
|
||||
|
||||
def delete_schedule(sid: str) -> bool:
|
||||
with _LOCK:
|
||||
for i, s in enumerate(_SCHEDULES):
|
||||
if s.get("id") == sid:
|
||||
_SCHEDULES.pop(i)
|
||||
_persist()
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def toggle_schedule(sid: str, enabled: bool) -> dict | None:
|
||||
with _LOCK:
|
||||
for s in _SCHEDULES:
|
||||
if s.get("id") == sid:
|
||||
s["enabled"] = bool(enabled)
|
||||
s["updated_at"] = _now()
|
||||
_persist()
|
||||
return dict(s)
|
||||
return None
|
||||
|
||||
|
||||
def next_run_at(s: dict) -> datetime | None:
|
||||
"""该任务最近一次触发后的下一次触发时刻(未跑过则取首次未来触发)。"""
|
||||
try:
|
||||
cron = parse_cron(s.get("cron", ""))
|
||||
except ValueError:
|
||||
return None
|
||||
try:
|
||||
last = datetime.fromisoformat(s.get("last_run_at")) if s.get("last_run_at") else None
|
||||
except (TypeError, ValueError):
|
||||
last = None
|
||||
return next_match(cron, last if last else datetime.now())
|
||||
|
||||
|
||||
def _public(s: dict) -> dict:
|
||||
out = dict(s)
|
||||
out["enabled"] = bool(out.get("enabled"))
|
||||
out["last_run_at"] = out.get("last_run_at") or ""
|
||||
nxt = next_run_at(s)
|
||||
out["next_run_at"] = nxt.strftime("%Y-%m-%d %H:%M:%S") if nxt else ""
|
||||
return out
|
||||
|
||||
|
||||
def _export(account: str) -> list:
|
||||
with _LOCK:
|
||||
return [dict(s) for s in _SCHEDULES if s.get("account") == account]
|
||||
|
||||
|
||||
# ==================== 后台触发 ====================
|
||||
def start() -> None:
|
||||
"""启动后台定时检查线程(幂等)。"""
|
||||
global _STARTED
|
||||
with _LOCK:
|
||||
if _STARTED:
|
||||
return
|
||||
_STARTED = True
|
||||
threading.Thread(target=_loop, daemon=True, name="sched-tick").start()
|
||||
_LOGGER.info("定时任务后台检查已启动(每 %ds 一次)", _TICK_SECS)
|
||||
|
||||
|
||||
def _loop() -> None:
|
||||
while True:
|
||||
try:
|
||||
_tick()
|
||||
except Exception as _exc: # noqa: BLE001 单轮异常不影响后续检查
|
||||
_LOGGER.warning("定时任务检查异常:%s", _exc)
|
||||
time.sleep(_TICK_SECS)
|
||||
|
||||
|
||||
def _tick() -> None:
|
||||
now = datetime.now()
|
||||
due = []
|
||||
with _LOCK:
|
||||
for s in _SCHEDULES:
|
||||
if not s.get("enabled"):
|
||||
continue
|
||||
try:
|
||||
cron = parse_cron(s.get("cron", ""))
|
||||
except ValueError:
|
||||
continue
|
||||
try:
|
||||
last = (datetime.fromisoformat(s.get("last_run_at"))
|
||||
if s.get("last_run_at") else None)
|
||||
except (TypeError, ValueError):
|
||||
last = None
|
||||
nxt = next_match(cron, last if last else now)
|
||||
if nxt and nxt <= now:
|
||||
due.append((s, nxt))
|
||||
fired = False
|
||||
for s, nxt in due:
|
||||
if _fire(s):
|
||||
with _LOCK:
|
||||
s["last_run_at"] = nxt.strftime("%Y-%m-%d %H:%M:%S")
|
||||
fired = True
|
||||
if fired:
|
||||
_persist()
|
||||
|
||||
|
||||
def _fire(s: dict) -> bool:
|
||||
"""触发一次定时任务:授权校验通过后走 submit_run 启动;返回是否已启动。"""
|
||||
from webhost.backend.plugins import PLUGINS
|
||||
from webhost.backend.core import licensing
|
||||
from webhost.backend.core.runner import submit_run
|
||||
|
||||
try:
|
||||
plugin = PLUGINS.find(s.get("plugin_id", ""))
|
||||
except KeyError:
|
||||
_LOGGER.warning("定时任务「%s」的插件 %s 不存在,跳过触发",
|
||||
s.get("name"), s.get("plugin_id"))
|
||||
return False
|
||||
account = s.get("account", "")
|
||||
deny = licensing.run_check_allowed(plugin.id, account, licensing.is_online())
|
||||
if deny:
|
||||
_LOGGER.warning("定时任务「%s」触发被拒(账号 %s):%s",
|
||||
s.get("name"), account, deny)
|
||||
return False
|
||||
try:
|
||||
submit_run(account, plugin, s.get("fields") or {})
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.error("定时任务「%s」启动失败:%s", s.get("name"), _exc)
|
||||
return False
|
||||
_LOGGER.info("定时任务触发:「%s」(插件 %s,账号 %s)",
|
||||
s.get("name"), plugin.id, account)
|
||||
return True
|
||||
|
||||
|
||||
# ==================== 中心机备份(防丢失) ====================
|
||||
def push_backup_async(request, account: str) -> None:
|
||||
"""变更后把该账号全量配置异步备份到中心机;失败静默(不阻断用户操作)。"""
|
||||
from webhost.backend import config
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return
|
||||
|
||||
def _run():
|
||||
try:
|
||||
from webhost.backend.core.cpapi import _cp_headers, _cp_call
|
||||
headers = {**_cp_headers(request), "Content-Type": "application/json"}
|
||||
_cp_call("POST", "/api/schedules/backup",
|
||||
headers=headers,
|
||||
json={"data": {"schedules": _export(account)}})
|
||||
except Exception as _exc: # noqa: BLE001
|
||||
_LOGGER.warning("定时任务备份失败(账号 %s):%s", account, _exc)
|
||||
|
||||
threading.Thread(target=_run, daemon=True, name="sched-backup").start()
|
||||
|
||||
|
||||
def restore_from_cloud() -> None:
|
||||
"""启动时按当前活跃账号从中心机合并恢复缺失的任务(本地已有 id 不覆盖)。
|
||||
|
||||
仅作「防丢失」兜底:本地配置为真源,服务端备份只在本地缺失对应任务时补充。
|
||||
"""
|
||||
from webhost.backend import config
|
||||
if not config.CONTROLPLANE_URL:
|
||||
return
|
||||
from webhost.backend.core.session import _sess_active_account, _ACCT_CLOUD_TOKEN
|
||||
account = _sess_active_account()
|
||||
if not account:
|
||||
return
|
||||
headers = {"X-Admin-User": account}
|
||||
if config.CONTROLPLANE_TOKEN:
|
||||
headers["X-API-Token"] = config.CONTROLPLANE_TOKEN
|
||||
cloud_tok = (_ACCT_CLOUD_TOKEN or {}).get(account)
|
||||
if cloud_tok:
|
||||
headers["Authorization"] = f"Bearer {cloud_tok}"
|
||||
import requests
|
||||
try:
|
||||
r = requests.get(f"{config.CONTROLPLANE_URL}/api/schedules/backup",
|
||||
headers=headers, timeout=5)
|
||||
r.raise_for_status()
|
||||
remote = (r.json().get("data") or {}).get("schedules") or []
|
||||
except Exception as _exc: # noqa: BLE001 恢复失败不影响启动
|
||||
_LOGGER.warning("定时任务云端恢复失败(跳过):%s", _exc)
|
||||
return
|
||||
added = 0
|
||||
with _LOCK:
|
||||
local_ids = {s.get("id") for s in _SCHEDULES}
|
||||
for s in remote:
|
||||
if (not isinstance(s, dict) or s.get("id") in local_ids
|
||||
or s.get("account") != account):
|
||||
continue
|
||||
try:
|
||||
parse_cron(s.get("cron", ""))
|
||||
except ValueError:
|
||||
continue
|
||||
_SCHEDULES.append(s)
|
||||
added += 1
|
||||
if added:
|
||||
_persist()
|
||||
if added:
|
||||
_LOGGER.info("定时任务云端恢复 %d 条(账号 %s)", added, account)
|
||||
|
||||
|
||||
def init() -> None:
|
||||
"""启动初始化:加载本地配置 + 启动后台检查线程 + 云端补恢复。"""
|
||||
_load()
|
||||
start()
|
||||
restore_from_cloud()
|
||||
Reference in New Issue
Block a user