Files
37duAutomation/desktop/webhost/backend/main.py
T
puddy c23c123fb8 feat: 新增壳子内置定时任务功能,支持配置备份与恢复
本次提交新增完整的定时任务系统:
1. 后端支持cron表达式调度插件执行,与手动运行共用执行链路
2. 前端新增定时任务管理页面,支持增删改查与启停操作
3. 实现配置自动备份到中心机,启动时自动从云端恢复任务
4. 配套新增数据库表与控制面API接口
5. 同时优化了考勤异常检查的规则细节
2026-09-19 12:11:49 +08:00

139 lines
6.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""webhost 宿主(组装层):创建 FastAPI app,装配各领域路由,执行重启初始化。
业务逻辑已按领域拆到 sibling 模块:
- config.py 环境配置 - state.py 共享可变状态 - session.py 统一账户会话
- cpapi.py 中心机代理 - runner.py run 执行 - meta.py 插件元数据/平台权限
- apis/ 路由子包(admin / dingtalk / meta / runs)
本文件仅承担:lifespan 初始化、创建 app、include_router、静态前端挂载、uvicorn 启动。
"""
from __future__ import annotations
import asyncio
import logging
import socket
import sys
import threading
from contextlib import asynccontextmanager
from pathlib import Path
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from webhost.backend import config
from webhost.backend import licensing
from webhost.backend import scheduler as _scheduler
from webhost.backend import state as _st
from webhost.backend.core.cpapi import _resolve_allowed, _sync_licensing
from webhost.backend.core.hub import HUB
from webhost.backend.plugins import load_plugins
from webhost.backend.apis import admin as api_admin
from webhost.backend.apis import dingtalk as api_dingtalk
from webhost.backend.apis import meta as api_meta
from webhost.backend.apis import plugin_ui as api_plugin_ui
from webhost.backend.apis import runs as api_runs
from webhost.backend.apis import schedules as api_schedules
_LOGGER = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(app: FastAPI):
try:
HUB.bind(asyncio.get_running_loop())
# 显式加载插件:默认全量;配置 controlplane 源则按账号权限白名单加载
_st.set_allowed(_resolve_allowed())
load_plugins(_st.ALLOWED)
# 产品化初始化:授权缓存 + 单活调度 + 启动即同步离线票据
licensing.init(config.CONTROLPLANE_URL, threading.Lock())
_scheduler.init_active()
if config.CONTROLPLANE_URL:
# 敏感凭证中心化下发:优先服务端在线拉取(RSA 解密),否则用本地缓存密文解密;
# 失败不阻断启动(.env 回退 / 等待下次登录后刷新)
try:
from webhost.backend.core import creds_sync
_creds = creds_sync.load()
if _creds:
config.apply_creds(_creds)
_LOGGER.info("中心机敏感凭证下发完成(%s 个键)", len(_creds))
except Exception as _exc: # noqa: BLE001 下发失败不影响启动
_LOGGER.warning("加载中心机敏感凭证失败:%s", _exc)
# 账号:.env 不再配置 CONTROLPLANE_ACCOUNT,取最近活跃的本机会话账号(重启恢复)
from webhost.backend.core.session import _sess_active_account
_acct = config.CONTROLPLANE_ACCOUNT or _sess_active_account()
if _acct:
try:
_sync_licensing(_acct)
_LOGGER.info("启动同步离线授权票据成功(账号 %s)", _acct)
except Exception as _exc: # noqa: BLE001 首启/断网时同步失败不阻断,离线用缓存兜底
_LOGGER.warning("启动同步离线授权票据失败:%s", _exc)
# 启动即检查插件更新:有恢复的会话账号时后台同步(每次启动确定是否更新,不阻塞启动)
try:
from webhost.backend.core.session import _SESS
_accts = {_a for _, (_a, _t) in _SESS.items()}
except Exception: # noqa: BLE001
_accts = set()
if _accts:
_acct = next(iter(_accts))
def _boot_sync() -> None:
try:
from webhost.backend.core.plugin_sync import sync_plugins, SYNC_LOCK
with SYNC_LOCK:
sync_plugins(_acct)
load_plugins(_st.ALLOWED, reload=True)
_LOGGER.info("启动插件更新完成(账号 %s)", _acct)
except Exception as _exc: # noqa: BLE001 更新失败不阻断启动
_LOGGER.warning("启动插件更新失败:%s", _exc)
threading.Thread(target=_boot_sync, daemon=True).start()
# 启动即检查壳子(主程序)更新:有新版本自动下载,前端提示后由用户点击重启升级;
# 并常驻周期检查(默认 30 分钟),壳子长开时也能自动发现新版本
from webhost.backend.core import shell_updater as _shell_updater
_shell_updater.start_check()
_shell_updater.start_periodic_check()
# 壳子内置定时任务:加载本地配置 + 启动后台触发线程 + 从中心机合并恢复(防丢失)
from webhost.backend.core import tasks as _boot_tasks
_boot_tasks.init()
yield
except BaseException:
# lifespan 失败会被 uvicorn 吞成 SystemExit(3);frozen 下 stderr 已重定向 devnull,
# 报错无处可看:崩溃现场记入 webhost.log,frozen 时并追加到 exe 同级 crash.log
import traceback
_tb = traceback.format_exc()
_LOGGER.error("启动初始化失败:\n%s", _tb)
if getattr(sys, "frozen", False):
try:
with open(Path(sys.executable).parent / "crash.log", "a", encoding="utf-8") as _f:
_f.write("\n[lifespan]\n" + _tb)
except OSError:
pass
raise
app = FastAPI(title="37du Web Host", lifespan=lifespan)
app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
app.include_router(api_admin.router)
app.include_router(api_dingtalk.router)
app.include_router(api_meta.router)
app.include_router(api_runs.router)
app.include_router(api_schedules.router)
app.include_router(api_plugin_ui.router)
if config.DIST.exists():
app.mount("/", StaticFiles(directory=str(config.DIST), html=True), name="web")
def _port_free(port: int) -> bool:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex(("127.0.0.1", port)) != 0
if __name__ == "__main__":
import uvicorn
print(f"[webhost] port {config.PORT} free = {_port_free(config.PORT)}")
uvicorn.run(app, host="127.0.0.1", port=config.PORT, log_level="info")