feat: 新增壳子内置定时任务功能,支持配置备份与恢复
本次提交新增完整的定时任务系统: 1. 后端支持cron表达式调度插件执行,与手动运行共用执行链路 2. 前端新增定时任务管理页面,支持增删改查与启停操作 3. 实现配置自动备份到中心机,启动时自动从云端恢复任务 4. 配套新增数据库表与控制面API接口 5. 同时优化了考勤异常检查的规则细节
This commit is contained in:
@@ -1,19 +1,18 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「运行」路由:登记并启动 run / 查询 run / /ws 广播连接。"""
|
||||
"""webhost 宿主「运行」路由:登记并启动 run / 查询 run / /ws 广播连接。
|
||||
|
||||
手动启动入口复用 runner.submit_run(与定时任务共用同一执行链路);
|
||||
本文件只承担:登录门槛 + 插件查找 + 授权校验(403 前置门禁)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, WebSocket
|
||||
|
||||
from webhost.backend import licensing
|
||||
from webhost.backend import scheduler as _scheduler
|
||||
from webhost.backend import state as _st
|
||||
from webhost.backend.core.runner import RunReq, _run_target, terminate_run
|
||||
from webhost.backend.core.runner import RunReq, submit_run, terminate_run
|
||||
from webhost.backend.core.hub import HUB
|
||||
from webhost.backend.plugins import PLUGINS
|
||||
from webhost.backend.core.session import _require_login, _sess_account
|
||||
@@ -36,51 +35,7 @@ def start_run(req: RunReq, request: Request) -> dict:
|
||||
if deny:
|
||||
_LOGGER.info("插件 %s 启动被拒(账号 %s):%s", plugin.id, account, deny)
|
||||
raise HTTPException(403, deny)
|
||||
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": "设备正有其他插件执行中,排队等待其完成后自动启动…"})
|
||||
|
||||
# start_fn 无参调用(scheduler 约定):run_id 由外层闭包捕获;
|
||||
# 之前签名带 _run_id 形参会因 TypeError 启动失败且被静默吞掉,运行记录永久卡 running
|
||||
def _start():
|
||||
threading.Thread(target=_run_target,
|
||||
args=(plugin, req.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()
|
||||
run_id = submit_run(account, plugin, req.fields or {})
|
||||
return {"run_id": run_id}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""webhost 宿主「定时任务」路由:增删改查 + 启停;变更后自动备份到中心机(防丢失)。
|
||||
|
||||
- 任务归属创建者账号(配置时登录账号),仅创建者可修改/删除/启停。
|
||||
- cron 为 5 段标准表达式(分 时 日 月 周),由 core.tasks 解析与触发。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel
|
||||
|
||||
from webhost.backend.core import tasks as _tasks
|
||||
from webhost.backend.core.session import _require_login
|
||||
from webhost.backend.plugins import PLUGINS
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class _SchedIn(BaseModel):
|
||||
name: str = ""
|
||||
plugin_id: str = ""
|
||||
fields: dict = {}
|
||||
cron: str = ""
|
||||
enabled: bool = True
|
||||
|
||||
|
||||
class _ToggleIn(BaseModel):
|
||||
enabled: bool
|
||||
|
||||
|
||||
def _find_owned(sid: str, account: str) -> dict:
|
||||
"""按 id 取任务并校验归属;不存在/非本人抛 HTTP 异常。"""
|
||||
s = _tasks.get_schedule(sid)
|
||||
if s is None:
|
||||
raise HTTPException(404, "任务不存在")
|
||||
if s.get("account") != account:
|
||||
raise HTTPException(403, "仅创建者可管理该任务")
|
||||
return s
|
||||
|
||||
|
||||
@router.get("/api/schedules")
|
||||
def sched_list(request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
return {"schedules": _tasks.list_schedules(account)}
|
||||
|
||||
|
||||
@router.post("/api/schedules", status_code=201)
|
||||
def sched_create(b: _SchedIn, request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
if not b.plugin_id:
|
||||
raise HTTPException(400, "请选择插件")
|
||||
try:
|
||||
PLUGINS.find(b.plugin_id)
|
||||
except KeyError:
|
||||
raise HTTPException(404, "插件不存在")
|
||||
try:
|
||||
rec = _tasks.create_schedule(account, b.model_dump())
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, f"cron 表达式无效:{e}")
|
||||
_tasks.push_backup_async(request, account)
|
||||
return rec
|
||||
|
||||
|
||||
@router.put("/api/schedules/{sid}")
|
||||
def sched_update(sid: str, b: _SchedIn, request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
_find_owned(sid, account)
|
||||
if b.plugin_id:
|
||||
try:
|
||||
PLUGINS.find(b.plugin_id)
|
||||
except KeyError:
|
||||
raise HTTPException(404, "插件不存在")
|
||||
try:
|
||||
rec = _tasks.update_schedule(sid, b.model_dump(exclude_unset=True))
|
||||
except ValueError as e:
|
||||
raise HTTPException(400, f"cron 表达式无效:{e}")
|
||||
if rec is None:
|
||||
raise HTTPException(404, "任务不存在")
|
||||
_tasks.push_backup_async(request, account)
|
||||
return rec
|
||||
|
||||
|
||||
@router.delete("/api/schedules/{sid}")
|
||||
def sched_delete(sid: str, request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
_find_owned(sid, account)
|
||||
if not _tasks.delete_schedule(sid):
|
||||
raise HTTPException(404, "任务不存在")
|
||||
_tasks.push_backup_async(request, account)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/api/schedules/{sid}/toggle")
|
||||
def sched_toggle(sid: str, b: _ToggleIn, request: Request) -> dict:
|
||||
account = _require_login(request)
|
||||
_find_owned(sid, account)
|
||||
rec = _tasks.toggle_schedule(sid, b.enabled)
|
||||
if rec is None:
|
||||
raise HTTPException(404, "任务不存在")
|
||||
_tasks.push_backup_async(request, account)
|
||||
return rec
|
||||
Reference in New Issue
Block a user