Files
37duAutomation/desktop/webhost/backend/core/shell_updater.py
T

339 lines
14 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 -*-
"""执行机壳子(主程序)自动更新:检查 → 用户确认下载(带进度)→ 点击重启升级。
流程(对应前端交互):
1. 检查:启动时/每 30 分钟/手动"检查更新",只比对控制面 /api/shell/version,
秒级返回"有新版/已是最新/不可达",不下载大包。发现新版后由前端提示用户,
由用户决定是否下载(不默默后台拉包)。
2. 下载:用户点击"立即下载" → 后台流式下载到
%LOCALAPPDATA%\\37duAutomation\\shell\\(先写 .part 临时文件,完成校验后改名),
进度(已下载/总量/百分比)写入状态供前端轮询展示。
3. 应用:下载完成后前端提示"重启更新",用户点击 → apply_update() 运行安装包
/VERYSILENT 静默覆盖安装,随后本进程退出,Inno CloseApplications 收尾,
安装完成由 [Run] 自动重启新版本主程序。
4. 离线/控制面不可达/校验失败:状态记录错误原因,前端提示,不影响使用。
并发控制:检查与下载各持独立锁(检查是 5s 的版本接口,下载是数百 MB 大包,
两者互不阻塞)。下载内部再防重入,避免重复拉包。
"""
from __future__ import annotations
import hashlib
import logging
import os
import subprocess
import sys
import threading
import time
from pathlib import Path
from webhost.backend import config
_LOGGER = logging.getLogger(__name__)
# 下载缓存的安装包目录:独立于程序目录(升级时不被覆盖/清理)
_SHELL_CACHE = Path(os.environ.get("LOCALAPPDATA", str(Path.home()))) / "37duAutomation" / "shell"
# 检查互斥锁:启动/周期/手动三入口共用,检查期间视为"检查中"(pending_status.checking)
_CHECK_LOCK = threading.Lock()
# 下载互斥锁:防止并发重复下载同一大包
_DL_LOCK = threading.Lock()
# 已下载待应用的新版本(模块内状态,供 update-status 查询)
_PENDING_VERSION = ""
_PENDING_NOTES = ""
# 运行态(供前端轮询 update-status)
_STATE: dict = {
# 版本检查
"checking": False, # 版本检查进行中(秒级,很快结束)
"check_at": 0.0, # 最近一次检查完成时间
"latest": "", # 云端最新版本
"notes": "", # 云端最新版本更新说明
"available": False, # 检测到可用新版本(当前 < 云端 且 尚未下载完成)
"check_error": "", # 检查失败原因(控制面不可达/源码模式等)
# 下载(流式,带进度)
"dl_version": "", # 正在下载/刚下载完成的版本
"dl_status": "idle", # idle | downloading | downloaded | failed
"dl_received": 0, # 已下载字节
"dl_total": 0, # 总字节(0 = 未知,无法算百分比)
"dl_pct": 0, # 0-100
"dl_error": "", # 下载失败原因
"applying": False, # 正在静默安装升级
}
_PERIODIC_INTERVAL = 30 * 60 # 周期检查间隔(秒)
def local_shell_version() -> str:
"""本机壳子版本:frozen 时读 exe 同级 shell.version;源码运行返回空(不参与自更新)。
用 utf-8-sig 读取:防文件带 UTF-8 BOM(记事本另存 UTF-8 时常见),否则会读到
"\\ufeff1.2.0" 导致版本比对永远判为"不大于"(P1 修复:壳子升级失效根因)。"""
if not getattr(sys, "frozen", False):
return ""
vf = Path(sys.executable).resolve().parent / "shell.version"
try:
return vf.read_text(encoding="utf-8-sig").strip() if vf.is_file() else ""
except OSError:
return ""
def _headers() -> dict:
h = {}
if config.CONTROLPLANE_TOKEN:
h["X-API-Token"] = config.CONTROLPLANE_TOKEN
return h
def _version_lt(a: str, b: str) -> bool:
def _key(v: str):
return [int(x) if x.isdigit() else x for x in str(v).split(".")]
try:
return _key(a) < _key(b)
except Exception: # noqa: BLE001
return a != b and a < b
def fetch_cloud_version() -> dict | None:
"""拉取控制面壳子版本信息;非打包运行/未配置/不可达返回 None(失败原因记入 _STATE)。"""
if not local_shell_version() or not config.CONTROLPLANE_URL:
_STATE["check_error"] = "源码开发模式,不参与自更新" if not local_shell_version() else "未配置中心机地址"
return None
import requests
try:
r = requests.get(f"{config.CONTROLPLANE_URL}/api/shell/version",
headers=_headers(), timeout=5)
r.raise_for_status()
return r.json()
except Exception as _exc: # noqa: BLE001 离线/不可达
_LOGGER.info("检查壳子更新失败(离线跳过):%s", _exc)
_STATE["check_error"] = f"控制面不可达({_exc.__class__.__name__})"
return None
# ===================== 检查(只比对版本,不下载) =====================
def check_update() -> None:
"""只检查版本:比对控制面最新版,写入 _STATE。秒级完成,不下载大包。"""
if not _CHECK_LOCK.acquire(blocking=False):
return # 已有检查在进行,沿用其状态
try:
_STATE["checking"] = True
cur = local_shell_version()
info = fetch_cloud_version()
_STATE["check_at"] = time.time()
if not cur:
_STATE["latest"] = ""
_STATE["notes"] = ""
_STATE["available"] = False
return
if not info:
_STATE["available"] = False
return
cloud = str(info.get("version") or "")
notes = str(info.get("notes") or "")
_STATE["latest"] = cloud
_STATE["notes"] = notes
_STATE["check_error"] = ""
if not cloud or not _version_lt(cur, cloud):
# 已是最新:清掉"待下载"占位(若之前处于 failed,供用户重试的 available 也置 False)
_STATE["available"] = False
return
_STATE["available"] = True
# 缓存中已有该版本安装包 → 恢复为"已下载待应用",提示重启更新
if cached_pkg(cloud) is not None:
_restore_pending(cloud, notes)
finally:
_STATE["checking"] = False
_CHECK_LOCK.release()
def _restore_pending(cloud: str, notes: str) -> None:
"""把已落盘的安装包恢复为待应用状态(重启后/下载完成后沿用)。"""
global _PENDING_VERSION, _PENDING_NOTES
_PENDING_VERSION = cloud
_PENDING_NOTES = notes
_STATE["dl_version"] = cloud
_STATE["dl_status"] = "downloaded"
_STATE["dl_pct"] = 100
_LOGGER.info("壳子新版本 %s 已在缓存中,等待用户重启更新", cloud)
def start_check() -> None:
"""后台线程触发一次检查(启动/手动入口):立即返回,结果经 pending_status 轮询获取。"""
threading.Thread(target=check_update, daemon=True, name="shell-check").start()
def start_periodic_check(interval: int = _PERIODIC_INTERVAL) -> None:
"""常驻周期检查:壳子长开时也能自动发现新版本(只比对版本,不自动下载)。"""
def _loop() -> None:
while True:
time.sleep(interval)
try:
check_update()
except Exception as _exc: # noqa: BLE001 周期失败不中断循环
_LOGGER.warning("周期检查壳子更新失败:%s", _exc)
threading.Thread(target=_loop, daemon=True, name="shell-check-loop").start()
# ===================== 下载(流式 + 进度) =====================
def start_download() -> None:
"""开始下载新版本安装包(后台线程)。已有下载/已完成则直接沿用,不重复拉包。"""
cur = local_shell_version()
if not cur:
return
if _STATE["dl_status"] == "downloading":
return
if _STATE["dl_status"] == "downloaded" and _PENDING_VERSION:
return
info = fetch_cloud_version()
if not info:
return
cloud = str(info.get("version") or "")
if not cloud or not _version_lt(cur, cloud):
return
if cached_pkg(cloud) is not None:
_restore_pending(cloud, str(info.get("notes") or ""))
return
# 占位防重入,随后后台流式下载
_STATE["dl_version"] = cloud
_STATE["dl_status"] = "downloading"
_STATE["dl_received"] = 0
_STATE["dl_total"] = 0
_STATE["dl_pct"] = 0
_STATE["dl_error"] = ""
threading.Thread(target=_download, args=(cloud, info), daemon=True,
name="shell-download").start()
_LOGGER.info("开始下载壳子新版本 %s", cloud)
def _download(cloud: str, info: dict) -> None:
try:
with _DL_LOCK:
_download_locked(cloud, info)
except Exception as _exc: # noqa: BLE001 下载异常兜底
_LOGGER.exception("下载壳子安装包异常")
_STATE["dl_status"] = "failed"
_STATE["dl_error"] = f"下载异常({_exc.__class__.__name__})"
_cleanup_part(cloud)
def _download_locked(cloud: str, info: dict) -> None:
import requests
# 中心机 version 接口新增 url 字段:有则直连内网文件服务器下载大包(无鉴权);
# 为空回退中心机 /api/shell/pkg(该路径带 X-API-Token)。
inner_url = (info.get("url") or "").strip()
if inner_url:
url = inner_url
dl_headers = {}
else:
url = f"{config.CONTROLPLANE_URL}/api/shell/pkg"
dl_headers = _headers()
expect = (info.get("sha256") or "").lower()
tmp = _SHELL_CACHE / f"setup-37du-host-{cloud}.exe.part"
pkg = _SHELL_CACHE / f"setup-37du-host-{cloud}.exe"
try:
_SHELL_CACHE.mkdir(parents=True, exist_ok=True)
with requests.get(url, headers=dl_headers, stream=True, timeout=600) as r:
r.raise_for_status()
_STATE["dl_total"] = int(r.headers.get("Content-Length") or 0)
sha = hashlib.sha256()
with open(tmp, "wb") as f:
for chunk in r.iter_content(256 * 1024):
if not chunk:
continue
f.write(chunk)
sha.update(chunk)
_STATE["dl_received"] = _STATE.get("dl_received", 0) + len(chunk)
total = _STATE["dl_total"]
_STATE["dl_pct"] = int(_STATE["dl_received"] * 100 / total) if total else 0
except Exception as _exc: # noqa: BLE001
_LOGGER.warning("下载壳子安装包失败:%s", _exc)
_STATE["dl_status"] = "failed"
_STATE["dl_error"] = f"安装包下载失败({_exc.__class__.__name__})"
_cleanup_part(cloud)
return
if expect and sha.hexdigest() != expect:
_LOGGER.error("壳子安装包 sha256 校验失败,放弃更新")
_STATE["dl_status"] = "failed"
_STATE["dl_error"] = "安装包校验失败,请重试"
_cleanup_part(cloud)
return
try:
os.replace(tmp, pkg)
except OSError as _exc: # noqa: BLE001
_LOGGER.warning("壳子安装包落盘失败:%s", _exc)
_STATE["dl_status"] = "failed"
_STATE["dl_error"] = "安装包保存失败"
_cleanup_part(cloud)
return
_STATE["dl_status"] = "downloaded"
_STATE["dl_pct"] = 100
_STATE["dl_received"] = _STATE["dl_total"]
_restore_pending(cloud, str(info.get("notes") or ""))
def _cleanup_part(cloud: str) -> None:
try:
(_SHELL_CACHE / f"setup-37du-host-{cloud}.exe.part").unlink(missing_ok=True)
except OSError:
pass
def cached_pkg(version: str) -> Path | None:
"""本地缓存的指定版本安装包路径;不存在返回 None。"""
p = _SHELL_CACHE / f"setup-37du-host-{version}.exe"
return p if p.is_file() else None
def pending_status() -> dict:
"""当前更新状态(供前端展示与轮询):兼容旧字段,并补充下载进度/可用版本。"""
global _PENDING_VERSION, _PENDING_NOTES
cur = local_shell_version()
downloaded = bool(_PENDING_VERSION) and cached_pkg(_PENDING_VERSION) is not None
if not downloaded:
_PENDING_VERSION = ""
_PENDING_NOTES = ""
return {
"current": cur,
"new": _PENDING_VERSION if downloaded else "",
"notes": _PENDING_NOTES if downloaded else "",
"downloaded": downloaded,
"available": bool(_STATE["available"]),
"latest": _STATE.get("latest", ""),
"checked_at": _STATE.get("check_at", 0),
"checking": bool(_STATE.get("checking", False)),
"error": _STATE.get("check_error", ""),
"applying": bool(_STATE.get("applying", False)),
"dl": {
"version": _STATE.get("dl_version", ""),
"status": _STATE.get("dl_status", "idle"),
"received": _STATE.get("dl_received", 0),
"total": _STATE.get("dl_total", 0),
"pct": _STATE.get("dl_pct", 0),
"error": _STATE.get("dl_error", ""),
},
}
def apply_update() -> None:
"""运行新版安装包静默覆盖安装并退出本进程(升级完成后由 Inno 重启新版本)。
注意:本函数在返回前 os._exit(0) 退出整个进程,调用方无需继续处理。
"""
version = _PENDING_VERSION
pkg = cached_pkg(version)
if not pkg:
raise FileNotFoundError(f"未找到已下载的安装包:setup-37du-host-{version}.exe")
_STATE["applying"] = True
_LOGGER.info("开始静默升级到 %s:%s", version, pkg)
subprocess.Popen(
[str(pkg), "/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART"],
cwd=str(pkg.parent), creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
time.sleep(1) # 给安装器接管进程,随后退出让 Inno CloseApplications 收尾
os._exit(0)