Add Web 2 workspace and controlled deployment updates

This commit is contained in:
AttilaNet
2026-11-10 16:33:14 +08:00
parent 7fe4c0ffdf
commit dbb31707ea
58 changed files with 11283 additions and 0 deletions
+91
View File
@@ -0,0 +1,91 @@
# Web 2 Linux Docker 部署与更新
本目录对应 `develop/v2.0.0`、`2.0.0.dev1`,当前仍是开发版本。以下正式镜像命令仅在官方发布对应稳定 `v2.x.y` 后可用;没有 Web 2 正式发布时,更新检查明确返回“暂无正式版”,不会安装旧桌面 1.2.0。开发分支不发布稳定镜像,不自动更新服务器。
## 容器与持久化
需要 Linux、Docker Engine、带 `up --wait --wait-timeout` 和 `pull --policy` 的 Docker Compose v2。宿主机更新器另需 Python 3.12+(仅标准库)。镜像使用 Python 3.12,无 PySide6、Node 或 npm,单服务、单 Uvicorn worker;账号由应用内独立线程并行。
将审核后的项目源码放在 `/opt/ranch-web`,项目、Python 源码、Compose 及部署配置由 root 持有,且禁止其他用户写入。以下路径适用于全新部署,持久化账号目录使用单独的 UID/GID 10001:
```sh
cd /opt/ranch-web
sudo install -d -m 0700 -o 10001 -g 10001 /opt/ranch-web/data
sudo install -d -m 0755 -o root -g root /opt/ranch-web/updater-control
sudo install -m 0600 -o root -g root deploy/web/web.env.example .env
sudo install -m 0600 -o root -g root deploy/web/image.env.example .image.env
sudoedit .env .image.env
```
在 `.env` 填入独立的 `RANCH_WEB_PASSWORD`,这是 Web 管理密码,不是游戏密码;`.image.env` 填入已正式发布的完整镜像,例如 `RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.0`。Compose 默认只发布到宿主机 `127.0.0.1:8765`,容器内监听 `0.0.0.0:8765` 并强制管理密码。使用域名反代时,同时配置 `RANCH_WEB_ALLOWED_HOSTS` 与 `RANCH_WEB_ALLOWED_ORIGINS`;TLS 入口设置 `RANCH_WEB_SECURE_COOKIE=true`。代理保留正确的 Host,写请求依赖来源校验。
`/opt/ranch-web/data` 挂到容器 `/data`,包括账号、加密会话与密钥、配置、SQLite 统计和更新请求;独立于桌面数据。心跳控制目录独立只读挂到 `/run/ranch-updater`。使用 bind mount 的目录必须预先创建,Compose 不会悄悄创建 root 所有、容器无法写入的目录。默认容器用户 `10001:10001`,根文件系统只读,临时文件写到 `/tmp`。不要对现有账号目录重新初始化密钥。
正式版本启动:
```sh
sudo sh deploy/web/compose.sh pull --policy always web
sudo sh deploy/web/compose.sh up -d --no-build --wait --wait-timeout 180 web
sudo sh deploy/web/compose.sh ps
curl --fail http://127.0.0.1:8765/api/health
```
脚本固定读取 `.env` 与 `.image.env`,相当于 `docker compose --project-name ranch-web --env-file .env --env-file .image.env --file compose.yaml ...`。更新器会持久化已选镜像到 `.image.env`,之后也应通过此脚本启动,以免误用默认开发镜像。
GitHub 首次创建 GHCR 包可能为私有;仓库管理员可将 `myrzx_bot-web` 包设为 Public。私有包部署需操作者先在宿主机执行 `sudo docker login ghcr.io`,使用具备 `read:packages` 的凭据;不要把 registry 凭据交给 Web 容器。[GHCR 官方文档](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry)
若目前只在 Linux 上验证开发分支,将 `.image.env` 保持 `:dev`,本地构建后启动;这不会发布镜像:
```sh
sudo sh deploy/web/compose.sh build web
sudo sh deploy/web/compose.sh up -d --no-build --pull never --wait --wait-timeout 180 web
```
停止使用 `sudo sh deploy/web/compose.sh stop --timeout 120 web`。容器 SIGTERM 经应用 lifespan 关闭账号队列;Compose 给出 120 秒退出时间。保持单实例,不要用多个 worker、replica 或 `--scale web=...` 共享同一 `/data`。
## 手动检查与更新
Web 只读检查官方 GitHub Releases;默认只接受 `v2.MINOR.PATCH`,跳过草稿、预发布、1.x、3.x 和非法标签。数字不含前导零。`2.0.0.dev1 → v2.0.0` 可升级,`2.0.0 → v2.0.0` 不升级,拒绝降级。网络失败会明确显示检查失败,不使用虚构版本或下载脚本。
先安装 root 持有的配置(示例的所有自动化开关默认关闭):
```sh
sudo install -m 0600 -o root -g root deploy/web/updater.example.toml /etc/ranch-web-updater.toml
sudo python3 -B deploy/web/updater.py --config /etc/ranch-web-updater.toml --check
sudo python3 -B deploy/web/updater.py --config /etc/ranch-web-updater.toml --apply v2.0.0
```
`--apply` 不传版本时选比运行中版本更新的最新稳定 2.x。手动操作和定时任务共享排他锁。执行器固定官方仓库及镜像地址,重新查询 Releases 验证来源;Web 即使伪造 `update-request.json` 也不能指定命令、下载地址、路径或第三方镜像。
执行顺序:旧容器运行期间先 `compose pull --policy always web`;拉取失败则保持旧服务。然后停服,确认所有容器写入停止,为完整数据目录创建一致的快照(包含 SQLite 文件及 WAL、加密密钥);最后用新镜像 `compose up -d --no-build --pull never --wait --wait-timeout 180 web`。镜像已有 `/api/health` healthcheck,检查成功后才记录更新完成。
新服务健康失败时,更新器停止失败容器、恢复更新前数据、用旧镜像的准确本地 image ID 启动并检查健康。失败版本数据移入 `failed-data/`,快照保存在 `backups/`,均不自动删除。快照文件权限为 0600、备份目录 0700;不会打印账号数据、密钥、Compose 环境或容器日志。回滚也失败时保留恢复事务,下一次更新器运行会先恢复,需操作者检查服务状态。镜像拉取和停机发生在宿主机;Web 容器没有 Docker socket。
## 定时检查、Web 按钮与自动更新
```sh
sudo install -m 0644 deploy/web/ranch-web-updater.service /etc/systemd/system/
sudo install -m 0644 deploy/web/ranch-web-updater.timer /etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now ranch-web-updater.timer
sudo systemctl start ranch-web-updater.service
```
定时器每五分钟维护一次心跳;官方版本默认每小时检查一次。`auto_apply=false` 只显示可用更新,不主动更新。页面更新按钮还需操作者在 `/etc/ranch-web-updater.toml` 设置 `accept_web_requests=true`,再启动一次 service 刷新心跳;只有此时 Web 的 `can_apply` 才为 true。Web 点击后返回 `pending`,定时器独立验证并消费请求;这属于用户手动请求,不依赖 `auto_apply`。
若希望检测到新稳定版便自动安装,操作者显式设置 `auto_apply=true`;这可能在下次运行时开始升级。停用 Web 按钮或自动更新后,同样启动一次 service 刷新状态。停止 timer 后,15 分钟有效期到期的心跳会让 Web 显示执行器失效。可以用 `systemctl status ranch-web-updater.timer` 与 `journalctl -u ranch-web-updater.service` 查看脱敏状态。
Windows 或未安装执行器的 Docker 部署仍能检查版本,但按钮会显示“仅可检查更新”,不会伪装更新完成。公共 DTO、心跳、去重与请求字段见 [UPDATE_PROTOCOL.md](UPDATE_PROTOCOL.md)。
## CI 与验证范围
[web-image.yml](../../.github/workflows/web-image.yml) 仅对官方仓库的严格稳定 `v2.x.y` tag 推送 `ghcr.io/attilanet/myrzx_bot-web:v2.x.y`;校验 `ranch_web.__version__` 必须与 tag 一致,不能只改变镜像 label。PR 与手动运行只测试、构建,不推送。开发分支 push 不触发正式镜像发布,也没有 `latest` 滚动升级通道。CI 规划在无外网容器中检查 healthcheck、非 root 数据写权限、无 Qt 和正常停止;本轮没有触发 CI 或发布。
本机 Windows 没有 Docker,已能执行的验证是离线单元测试、临时数据的备份/回滚测试、启动脚本语法与配置静态核对、更新器 dry-run;不代表 Linux/Docker 实机验证通过。可在无 Docker 的机器上只打印计划(不联网、不写文件):
```sh
python -B deploy/web/updater.py --config deploy/web/updater.example.toml --apply v2.0.0 --dry-run
python -B -m unittest ranch_web.tests.test_updates ranch_web.tests.test_web_updater -v
```
命令参数依据 [Compose up](https://docs.docker.com/reference/cli/docker/compose/up/)、[Compose pull](https://docs.docker.com/reference/cli/docker/compose/pull/);发布权限与 GHCR 认证依据 [GitHub 镜像发布流程](https://docs.github.com/en/actions/tutorials/publish-packages/publish-docker-images)。检查使用 [GitHub Releases 列表 API](https://docs.github.com/en/rest/releases/releases#list-releases),不依赖可能指向桌面版的 `/latest`。
+45
View File
@@ -0,0 +1,45 @@
# Web 2 更新接口(协议 1)
供 API、前端、宿主机更新器与 Main 集成。`ranch_web.updates.UpdateService(root, current_version)` 只依赖 Python 标准库;构造和 `status()` 不联网,`check()` 才访问固定官方 GitHub Releases,`request_update(version=None)` 仅提交文件请求。API 可在线程池中调用检查,不能在事件循环里等待网络。
- 固定仓库:`attilanet/myrzx_bot`;固定镜像:`ghcr.io/attilanet/myrzx_bot-web`。
- 唯一可选发布 tag:`v2.MINOR.PATCH`(十进制、不许前导零、无任何后缀)。草稿、预发布、1.x、3.x、dev 分支全部跳过;按版本数值比较,不信任 GitHub latest 排序。
- `root` 为 Web 数据根(Docker `/data`),文件为 `update-check.json`、`update-request.json`、`updater-status.json`。账号数据与这些控制文件隔离。
- `RANCH_WEB_UPDATER_DIR` 指向宿主机心跳目录,Docker 固定 `/run/ranch-updater`,只读挂载,与 `/data` 分离。没有有效 `capability.json` 时 `can_apply=false`,仅检查可用;Windows 默认如此。
- 心跳由宿主机定时任务写入,含 `protocol=1, executor_id, enabled, auto_apply, heartbeat_at, expires_at`。执行器配置默认 `accept_web_requests=false, auto_apply=false`,操作者必须显式启用 Web 请求。心跳有效期 15 分钟、timer 每 5 分钟运行。
- `update-request.json` 仅含 `protocol=1, request_id`(32 位小写十六进制)、`executor_id`、`version`(官方 tag)、`requested_at`(UTC ISO 8601)。禁止镜像地址、命令、下载地址或路径。宿主机再次联网验证 tag、版本单调递增并去重;Web 写文件不等于部署成功。
三个方法返回同一公共 DTO,示例:
```json
{
"current_version": "2.0.0.dev1",
"latest_version": "v2.0.0",
"available": true,
"checked_at": "2026-11-10T00:00:00Z",
"release_url": "https://github.com/attilanet/myrzx_bot/releases/tag/v2.0.0",
"channel": "stable-2.x",
"repository": "attilanet/myrzx_bot",
"status": "available",
"message": "发现稳定 Web 2 更新。",
"error": null,
"can_apply": false,
"executor": {
"configured": false,
"enabled": false,
"auto_apply": false,
"state": "unconfigured",
"heartbeat_at": null
},
"request": null,
"host_status": null
}
```
`status`:`unchecked / no_release / up_to_date / available / check_failed / unavailable / pending / applying / succeeded / rolled_back / failed`。无 2.x 正式版时 `latest_version=null, available=false, status=no_release`,不可退到桌面 1.2。
提交成功返回 `status=pending`,`request={request_id,version,requested_at,status:"pending"}`;前端应显示“等待宿主机”,定时 GET 状态。宿主机结果 `host_status={request_id,status,version,updated_at,error}`,错误是固定脱敏说明,不含原始异常、文件路径或子进程输出。`request_update` 在缺少执行器时返回 `status=unavailable` 和具体 `message`;非法/非官方/倒退版本抛 `ValueError`,API 映射 400。API `/apply` 的 HTTP 接受响应不应宣称已经升级;更新完成由宿主机健康检查决定。
启动约定(对齐 API owner 已落地的 config.py):`python -m ranch_web`,读取 `RANCH_WEB_HOST`(默认 `127.0.0.1`)、`RANCH_WEB_PORT`(默认 `8765`)、`RANCH_WEB_DATA_DIR`(默认 `local_state/ranch_web`)、`RANCH_WEB_PASSWORD`。Docker 设置 `HOST=0.0.0.0, DATA_DIR=/data`,只运行一个 Uvicorn worker,正常 SIGTERM 经 lifespan 关闭 manager。
API 已在更新 DTO 专用上下文按以上限定字段保留公共 `request`、`request_id`;全局游戏凭据脱敏保持有效。按钮传 `latest_version` 的完整 `v2.x.y`,无 `v` 的版本不会作为镜像标签接受。
+53
View File
@@ -0,0 +1,53 @@
# Deploy owner 交接与冻结记录
分支 `develop/v2.0.0`,基线 `main v1.2.0 (7fe4c0f)`,Web 源码版本 `2.0.0.dev1`。本 owner 完成部署与更新范围,未 commit、push、合并、发布镜像或触发线上部署;未读取或修改桌面私有账户,未调用真实游戏 API 或真实 GitHub Releases。
## 文件
- 根目录:`Dockerfile`、`compose.yaml`、`.dockerignore`、`Start_Ranch_Web.cmd`、`start-web.sh`;`.gitignore` 仅追加 Web 虚拟环境、设计缓存与部署运行产物排除;根 `README.md` 仅增加 Web 开发/部署入口。
- `ranch_web/updates.py`:标准库发布检查、严格稳定 2.x 比较、只读宿主机心跳授权、原子 pending 请求与脱敏公共状态;包含 CI 的固定仓库/源码版本发布校验函数。
- `ranch_web/tests/test_updates.py` 与 `test_web_updater.py`:本 owner 独立测试文件。
- `ranch_web/README.md`:Windows/Linux Python 开发启动、数据隔离、环境设置与更新限制。
- `.github/workflows/web-image.yml`:PR/手动只测试与构建,官方严格 `v2.x.y` tag 且源码版本完全一致时才推固定 GHCR 镜像。仓库名称比较忽略大小写,覆盖 `AttilaNet/myrzx_bot`。
- `deploy/web/`:更新器、Compose 包装脚本、systemd service/timer、环境及 TOML 示例、部署文档与 [精确更新协议](UPDATE_PROTOCOL.md)。
## 已执行验证(部署专项)
Windows Python **3.13.15**:
```console
python -B -m unittest ranch_web.tests.test_updates ranch_web.tests.test_web_updater -q
```
**41 项通过,无跳过。** GitHub 和 Docker 为 mock,数据全部在独立 `TemporaryDirectory`。覆盖:
- 仅稳定 `v2.x.y`,过滤 1.x、3.x、草稿、预发布、前导零、命令/换行注入;数字版本排序;`2.0.0.dev1 → v2.0.0` 可升级,同版正式版本/降级拒绝。
- 未配置、过期、禁用、错误实例、未来时间的能力证明;Web 数据目录不能自行开启执行器;pending 去重;公共错误不泄露原始异常或私有数据。
- 宿主机独立从 fake 官方 Releases 复验,不信 Web 标签;operator opt-in;过期/额外命令字段/跨实例请求拒绝;自动安装默认关闭。
- 旧服务运行时 pull、停服后才快照;拉取失败不停止;备份失败恢复旧镜像;健康失败恢复 SQLite、密钥和准确旧镜像,保留失败版本数据;回滚失败保存事务,恢复可重试。
- 实际 `WebManager` 在全网络 connect 禁止条件下,以内置离线 demo 开启策略,然后关闭、快照、重启及还原:保留勾选偏好与相同加密密钥,但 `running=false`,不会自动恢复执行。
- 正式镜像 label 仍是 dev 或健康失败时不能宣告更新成功;官方仓库名称大小写、fork 拒绝、源码版本/tag 不一致拒绝。
- `--dry-run` 对 Windows 与随附 Linux 路径示例均有效,不联网、不执行 Docker、不创建文件。
另外已执行:
- `Start_Ranch_Web.cmd --version` 返回 `2.0.0.dev1`。
- 实际 Windows `python -m ranch_web --demo --no-browser` HTTP 启动烟测:临时数据、动态本地端口;导入钩子禁止 PySide6/桌面 GUI,禁止外部 DNS/connect;健康、离线账号与更新禁用状态正常,触发 SIGINT 后正常 lifespan 退出,exit 0。该测试不含页面浏览器验收。
- `start-web.sh` 与 `deploy/web/compose.sh` 通过 Git Bash `bash -n`;两个 YAML 解析通过;静态核对单服务、UID/GID 10001、`/data`、独立只读心跳挂载、无 Docker socket、120 秒停止宽限;`git diff --check` 通过。
- 官方 Docker/GitHub 文档已核对并在 [部署说明](README.md) 链接。必要的 `ranch_assistant/data/progression_battles.zip` 在 `.dockerignore` 中显式保留。
## Main/API/前端集成注意与未执行范围
1. 所有文档、容器与当前 API config 统一 `RANCH_WEB_DATA_DIR`、`RANCH_WEB_HOST`、`RANCH_WEB_PORT`;Docker `WEB_CONCURRENCY=1`,CLI 不打开浏览器。
2. API 已使用更新 DTO 专用序列化保留合法 `request` / `request_id`,游戏凭据脱敏保持有效;HTTP 与 meta 的 pending/applying 信息已对接。前端从 `latest_version` 原样传完整 `v2.x.y`。
3. `request_update()` 在无执行器时返回 `unavailable`,成功提交仅是 `pending`;不能把 HTTP 202 文案写成“已更新”。心跳目录只读,协议 1,timer 每五分钟;`accept_web_requests=false` 与 `auto_apply=false` 均为默认值。
4. 本机无 Docker 可执行程序;**没有**验证 Linux/Docker 构建、Compose 真实解析/拉取、UID bind mount 实机权限、systemd 或真实健康回滚,也未执行 CI。静态配置与 mock 测试不能替代上述实机验收。CI 已编写隔离网络的容器健康/权限/停止检查,等待父代理审核后在授权发布流程执行。
5. GHCR 首次包为私有的处理已记录:公共发布需设包 Public;私有部署由操作者 `docker login`,Web 无 registry 凭据或 Docker socket。更新器 systemd 允许只读访问 root 的 registry 登录配置。
## 最终集成与复核
Main 确认最终非浏览器后端 **185项:184通过、1跳过(Windows符号链接权限),0失败/错误,用时26.878秒**;执行前后69份源文件哈希一致,无外发尝试。浏览器 **13项通过,JS/CSP错误为0**,另以新 Edge 进程验证15页与主线/孵蛋子页。上述部署专项41项、定向复核与全量测试有重叠,不相加。
本 owner 对此前五项问题复核完成:编码后与 requests 发送前的停止检查有效;修改配置不误关运行开关;120个筛选后视图缓存32项、已完成任务索引归零;主线/孵蛋标签 key 完整;12个并发错误登录得到10个401和2个429。六项定向回归与原始复现均通过,未扩大审查或重跑整套测试。
完整后端及浏览器命令见 [Web 验证说明](../../ranch_web/README.md#离线验证)。未进行真实游戏 API、Linux Docker、systemd 或生产更新器实机验收,未发布镜像或触发部署。生产代码保持冻结,仅更新最终文档,交 Main 提交。
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
cd -- "$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)"
exec docker compose --project-name ranch-web --env-file .env --env-file .image.env --file compose.yaml "$@"
+2
View File
@@ -0,0 +1,2 @@
# Development builds are local only. Set a real published v2.x.y for production.
RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:dev
+25
View File
@@ -0,0 +1,25 @@
[Unit]
Description=Check or apply official stable Ranch Web 2 updates
Requires=docker.service
After=docker.service network-online.target
Wants=network-online.target
ConditionPathExists=/etc/ranch-web-updater.toml
[Service]
Type=oneshot
User=root
Group=root
WorkingDirectory=/opt/ranch-web
ExecStart=/usr/bin/python3 -B /opt/ranch-web/deploy/web/updater.py --config /etc/ranch-web-updater.toml --run
TimeoutStartSec=30min
TimeoutStopSec=180s
UMask=0077
NoNewPrivileges=true
PrivateTmp=true
# Allow read-only access to root's registry credentials for private GHCR pulls.
ProtectHome=read-only
ProtectSystem=strict
ReadWritePaths=/opt/ranch-web
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
StandardOutput=journal
StandardError=journal
+12
View File
@@ -0,0 +1,12 @@
[Unit]
Description=Ranch Web updater heartbeat and scheduled release checks
[Timer]
OnBootSec=2min
OnUnitInactiveSec=5min
AccuracySec=15s
Persistent=true
Unit=ranch-web-updater.service
[Install]
WantedBy=timers.target
+12
View File
@@ -0,0 +1,12 @@
# Root-owned operator configuration. Never put this file in /data.
project_dir = "/opt/ranch-web"
data_dir = "/opt/ranch-web/data"
control_dir = "/opt/ranch-web/updater-control"
backup_dir = "/opt/ranch-web/backups"
failed_data_dir = "/opt/ranch-web/failed-data"
compose_project = "ranch-web"
accept_web_requests = false
auto_apply = false
check_interval_seconds = 3600
wait_timeout_seconds = 180
shutdown_timeout_seconds = 120
+491
View File
@@ -0,0 +1,491 @@
#!/usr/bin/env python3
"""Root-owned Linux host updater; no shell, Docker socket, or code in Web.
Use --check for notification, --apply [v2.x.y] for an operator update, or
--run from the timer. --dry-run never contacts GitHub or Docker or writes files.
"""
from __future__ import annotations
import argparse
from contextlib import contextmanager
from dataclasses import dataclass, fields
from datetime import timedelta
import json
import os
from pathlib import Path, PurePosixPath
import re
import shutil
import signal
import stat
import subprocess
import sys
import tarfile
import tempfile
import tomllib
import uuid
# This import is standard-library-only; no FastAPI/Qt installation on the host.
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from ranch_web import updates # noqa: E402
_DIGEST = re.compile(r"sha256:[0-9a-f]{64}", re.ASCII)
_CONTAINER = re.compile(r"[0-9a-f]{12,64}", re.ASCII)
_CONTROL_FILES = {"update-check.json", "update-request.json", "updater-status.json"}
class UpdaterError(RuntimeError):
"""Only a fixed public error is printed by the CLI."""
@dataclass(frozen=True)
class Config:
project_dir: Path = Path("/opt/ranch-web")
data_dir: Path = Path("/opt/ranch-web/data")
control_dir: Path = Path("/opt/ranch-web/updater-control")
backup_dir: Path = Path("/opt/ranch-web/backups")
failed_data_dir: Path = Path("/opt/ranch-web/failed-data")
compose_project: str = "ranch-web"
accept_web_requests: bool = False
auto_apply: bool = False
check_interval_seconds: int = 3600
wait_timeout_seconds: int = 180
shutdown_timeout_seconds: int = 120
@classmethod
def load(cls, path, *, dry_run=False):
with open(path, "rb") as stream:
value = tomllib.load(stream)
if set(value) - {field.name for field in fields(cls)}:
raise UpdaterError("执行器配置包含未知字段。")
for key in ("project_dir", "data_dir", "control_dir", "backup_dir", "failed_data_dir"):
if key in value:
item = Path(value[key])
if not item.is_absolute() and not (dry_run and PurePosixPath(value[key]).is_absolute()):
raise UpdaterError("执行器目录必须为绝对路径。")
value[key] = item.resolve()
result = cls(**value)
if not re.fullmatch(r"[a-z0-9][a-z0-9_-]{0,62}", result.compose_project):
raise UpdaterError("Compose 项目名称无效。")
if type(result.accept_web_requests) is not bool or type(result.auto_apply) is not bool:
raise UpdaterError("执行器开关必须为布尔值。")
for key, lower, upper in (("check_interval_seconds", 300, 604800),
("wait_timeout_seconds", 30, 600),
("shutdown_timeout_seconds", 30, 600)):
if type(getattr(result, key)) is not int or not lower <= getattr(result, key) <= upper:
raise UpdaterError("执行器时间配置超出允许范围。")
directories = [result.data_dir, result.control_dir, result.backup_dir, result.failed_data_dir]
for index, directory in enumerate(directories):
if directory == result.project_dir or directory in result.project_dir.parents:
raise UpdaterError("数据与控制目录不能覆盖项目目录。")
for other in directories[index + 1:]:
if directory == other or directory in other.parents or other in directory.parents:
raise UpdaterError("数据、控制、备份及失败数据目录必须相互独立。")
return result
class Docker:
def __init__(self, config):
self.config = config
def run(self, arguments, *, image=None, timeout=120):
environment = {key: value for key, value in os.environ.items()
if not key.startswith("COMPOSE_") and key not in {
"DOCKER_HOST", "DOCKER_CONTEXT", "DOCKER_TLS_VERIFY", "DOCKER_CERT_PATH",
}}
if image:
environment["RANCH_WEB_IMAGE"] = image
try:
completed = subprocess.run(
["docker", "--context", "default", *arguments], cwd=self.config.project_dir,
env=environment, stdin=subprocess.DEVNULL, capture_output=True,
text=True, timeout=timeout, check=False,
)
except (OSError, subprocess.TimeoutExpired):
raise UpdaterError("Docker 命令不可用或超时。") from None
if completed.returncode:
# Never print compose config, environment, or container logs.
raise UpdaterError("Docker 操作失败;请在宿主机检查服务状态。")
return completed.stdout.strip()
def compose(self, arguments, *, image=None, timeout=120):
cfg = self.config
return self.run([
"compose", "--project-name", cfg.compose_project,
"--project-directory", str(cfg.project_dir),
"--env-file", str(cfg.project_dir / ".env"),
"--env-file", str(cfg.project_dir / ".image.env"),
"--file", str(cfg.project_dir / "compose.yaml"), *arguments,
], image=image, timeout=timeout)
def inspect_service(self, *, allow_missing=False):
identity = self.compose(["ps", "--all", "--quiet", "web"])
if not identity and allow_missing:
return None
if not _CONTAINER.fullmatch(identity):
raise UpdaterError("必须先部署且只运行一个 web 容器。")
try:
values = json.loads(self.run(["container", "inspect", identity]))
container = values[0] if len(values) == 1 else None
image = container["Image"]
version = container["Config"]["Labels"]["org.opencontainers.image.version"]
updates.current_version_key(version)
except (KeyError, ValueError, TypeError, IndexError):
raise UpdaterError("现有容器缺少有效的 Web 2 版本标记。") from None
if not _DIGEST.fullmatch(image):
raise UpdaterError("无法固定旧镜像用于回滚。")
mounts = {mount["Destination"]: mount for mount in container.get("Mounts", [])}
if Path(mounts.get("/data", {}).get("Source", "")).resolve() != self.config.data_dir:
raise UpdaterError("现有容器的数据挂载与更新器配置不一致。")
capability = mounts.get("/run/ranch-updater", {})
if Path(capability.get("Source", "")).resolve() != self.config.control_dir or capability.get("RW") is not False:
raise UpdaterError("执行器心跳必须使用独立的只读挂载。")
return {"image": image, "version": version, "running": container["State"]["Running"],
"health": container["State"].get("Health", {}).get("Status")}
def validate(self, image):
try:
config = json.loads(self.compose(["config", "--format", "json"], image=image))
services = config["services"]
service = services["web"]
volumes = {mount["target"]: mount for mount in service["volumes"]}
valid = (set(services) == {"web"} and service["image"] == image
and service.get("user") == "10001:10001" and not service.get("privileged")
and set(volumes) == {"/data", "/run/ranch-updater"}
and volumes["/data"].get("type") == "bind"
and Path(volumes["/data"]["source"]).resolve() == self.config.data_dir
and Path(volumes["/run/ranch-updater"]["source"]).resolve() == self.config.control_dir
and volumes["/run/ranch-updater"].get("read_only") is True)
except (KeyError, ValueError, TypeError):
valid = False
if not valid:
raise UpdaterError("Compose 必须是固定 web 单服务、非 root 用户和指定挂载。")
def pull(self, image):
self.compose(["pull", "--policy", "always", "web"], image=image, timeout=900)
def stop(self):
self.compose(["stop", "--timeout", str(self.config.shutdown_timeout_seconds), "web"],
timeout=self.config.shutdown_timeout_seconds + 30)
remaining = self.inspect_service(allow_missing=True)
if remaining and remaining["running"]:
raise UpdaterError("旧服务未停止,拒绝创建不一致的备份。")
def up(self, image):
self.compose(["up", "-d", "--no-build", "--pull", "never", "--wait", "--wait-timeout",
str(self.config.wait_timeout_seconds), "web"], image=image,
timeout=self.config.wait_timeout_seconds + self.config.shutdown_timeout_seconds + 60)
running = self.inspect_service()
if not running["running"] or running["health"] != "healthy":
raise UpdaterError("容器未通过 /api/health 健康检查。")
if image.startswith(f"{updates.IMAGE}:") and running["version"] != image[len(updates.IMAGE) + 2:]:
raise UpdaterError("新镜像版本标记与正式发布标签不一致。")
def snapshot_data(config, request_id):
"""Create a complete directory snapshot only while all app writers are stopped."""
config.backup_dir.mkdir(parents=True, mode=0o700, exist_ok=True)
destination = config.backup_dir / f"{request_id}.tar.gz"
if destination.exists():
raise UpdaterError("备份标识冲突,已停止更新。")
descriptor, temporary = tempfile.mkstemp(prefix=".snapshot-", dir=config.backup_dir)
try:
with os.fdopen(descriptor, "wb") as stream:
os.chmod(temporary, 0o600)
with tarfile.open(fileobj=stream, mode="w:gz", dereference=False) as archive:
for directory, subdirs, filenames in os.walk(config.data_dir, followlinks=False):
for name in sorted(subdirs + filenames):
path = Path(directory) / name
info = path.lstat()
if stat.S_ISLNK(info.st_mode) or not (stat.S_ISREG(info.st_mode) or stat.S_ISDIR(info.st_mode)):
raise UpdaterError("数据目录存在非普通文件,已中止备份并恢复旧服务。")
if stat.S_ISREG(info.st_mode) and info.st_nlink != 1:
raise UpdaterError("数据目录存在硬链接,已中止备份并恢复旧服务。")
# Control status is preserved live; application data and keys are backed up.
relative = path.relative_to(config.data_dir)
if len(relative.parts) == 1 and name in _CONTROL_FILES:
continue
archive.add(path, arcname=str(relative), recursive=False)
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, destination)
finally:
if os.path.exists(temporary):
os.unlink(temporary)
return destination
def restore_data(config, backup, request_id):
"""Swap in the snapshot, retaining failed-version data for operator inspection."""
if backup.parent != config.backup_dir or backup.name != f"{request_id}.tar.gz":
raise UpdaterError("回滚备份标识无效。")
temporary = Path(tempfile.mkdtemp(prefix=".restore-", dir=config.data_dir.parent))
try:
with tarfile.open(backup, "r:gz") as archive:
for member in archive.getmembers():
relative = Path(member.name)
if relative.is_absolute() or ".." in relative.parts or not (member.isfile() or member.isdir()):
raise UpdaterError("备份包含不安全路径,拒绝回滚。")
archive.extractall(temporary, filter="data")
for name in _CONTROL_FILES:
value = updates.read_json(config.data_dir / name)
if value is not None:
updates.atomic_json(temporary / name, value, mode=0o600 if name == "update-request.json" else 0o644)
# The runtime image always uses this UID/GID. Restore encrypted keys with it.
if hasattr(os, "chown"):
for directory, subdirs, filenames in os.walk(temporary):
for name in subdirs + filenames:
os.chown(Path(directory) / name, 10001, 10001)
os.chown(temporary, 10001, 10001)
config.failed_data_dir.mkdir(parents=True, mode=0o700, exist_ok=True)
failed = config.failed_data_dir / request_id
if failed.exists():
raise UpdaterError("失败数据隔离目录已存在,拒绝覆盖。")
os.replace(config.data_dir, failed)
try:
os.replace(temporary, config.data_dir)
except BaseException:
os.replace(failed, config.data_dir)
raise
finally:
if temporary.exists():
shutil.rmtree(temporary)
class HostUpdater:
def __init__(self, config, docker=None):
self.config = config
self.docker = docker or Docker(config)
self.journal = config.control_dir / "transaction.json"
def capability(self):
old = updates.read_json(self.config.control_dir / "capability.json")
old = old if isinstance(old, dict) else {}
identity = old.get("executor_id")
if not updates.valid_id(identity):
identity = uuid.uuid4().hex
now = updates.utc_now()
value = {"protocol": updates.PROTOCOL, "executor_id": identity,
"enabled": self.config.accept_web_requests, "auto_apply": self.config.auto_apply,
"heartbeat_at": updates.timestamp(now),
"expires_at": updates.timestamp(now + timedelta(minutes=15))}
updates.atomic_json(self.config.control_dir / "capability.json", value)
return value
def publish(self, request_id, version, status):
value = {"protocol": updates.PROTOCOL, "request_id": request_id, "version": version,
"status": status, "updated_at": updates.timestamp(), "error": None}
updates.atomic_json(self.config.data_dir / "updater-status.json", value)
return value
def check(self, current_version):
return updates.UpdateService(self.config.data_dir, current_version).check()
def persist_image(self, image):
if not (_DIGEST.fullmatch(image) or image.startswith(f"{updates.IMAGE}:")):
raise UpdaterError("只能保存官方镜像或已固定的本地回滚镜像。")
if not _DIGEST.fullmatch(image):
updates.stable_version(image[len(updates.IMAGE) + 1:])
descriptor, temporary = tempfile.mkstemp(prefix=".image-env-", dir=self.config.project_dir)
try:
with os.fdopen(descriptor, "w", encoding="ascii", newline="\n") as stream:
stream.write(f"RANCH_WEB_IMAGE={image}\n")
stream.flush()
os.fsync(stream.fileno())
os.replace(temporary, self.config.project_dir / ".image.env")
finally:
if os.path.exists(temporary):
os.unlink(temporary)
def rollback(self, transaction):
request_id, version = transaction["request_id"], transaction["version"]
old_image = transaction["old_image"]
if not _DIGEST.fullmatch(old_image) or not updates.valid_id(request_id):
raise UpdaterError("回滚事务记录无效。")
if transaction.get("backup_ready") and transaction.get("new_started"):
self.docker.stop()
restore_data(self.config, self.config.backup_dir / f"{request_id}.tar.gz", request_id)
transaction["new_started"] = False
updates.atomic_json(self.journal, transaction, mode=0o600)
self.persist_image(old_image)
self.docker.up(old_image)
self.journal.unlink(missing_ok=True)
return self.publish(request_id, version, "rolled_back")
def recover(self):
transaction = updates.read_json(self.journal)
if transaction is not None:
return self.rollback(transaction)
return None
def apply(self, version=None, *, request_id=None):
# Source and monotonicity are rechecked here, including Web requests.
old = self.docker.inspect_service()
if not old["running"]:
raise UpdaterError("现有服务未运行,请先由操作者处理。")
try:
tags = updates.official_tags(updates.github_releases())
except Exception:
raise UpdaterError("无法独立验证官方 GitHub 正式发布,保留现有服务。") from None
target = version or (max(tags, key=updates.stable_version) if tags else None)
if target is None:
return {"status": "no_release", "message": "官方尚无稳定 Web 2 正式版。"}
if target not in tags or updates.stable_version(target) <= updates.current_version_key(old["version"]):
raise UpdaterError("目标必须是官方已发布且比现有容器更新的稳定 v2.x.y。")
image = f"{updates.IMAGE}:{target}"
request_id = request_id or uuid.uuid4().hex
if not updates.valid_id(request_id):
raise UpdaterError("更新请求标识无效。")
self.docker.validate(image)
self.docker.pull(image) # Pull failure leaves the old container running.
transaction = {"protocol": 1, "request_id": request_id, "version": target,
"old_image": old["image"], "backup_ready": False, "new_started": False}
updates.atomic_json(self.journal, transaction, mode=0o600)
self.publish(request_id, target, "applying")
try:
self.docker.stop()
snapshot_data(self.config, request_id)
transaction["backup_ready"] = True
updates.atomic_json(self.journal, transaction, mode=0o600)
# Mark before startup, since failed startups can already migrate data.
transaction["new_started"] = True
updates.atomic_json(self.journal, transaction, mode=0o600)
self.docker.up(image)
self.persist_image(image)
except (Exception, KeyboardInterrupt):
try:
return self.rollback(transaction)
except Exception:
self.publish(request_id, target, "failed")
raise UpdaterError("更新及自动回滚失败;已保留备份、失败数据和恢复事务。") from None
self.journal.unlink(missing_ok=True)
return self.publish(request_id, target, "succeeded")
def run(self):
capability = self.capability()
recovery = self.recover()
if recovery:
return recovery
request = updates.read_json(self.config.data_dir / "update-request.json")
if self.config.accept_web_requests and request is not None:
if not isinstance(request, dict):
return {"status": "failed", "message": "更新请求无效,未执行。"}
previous = updates.read_json(self.config.data_dir / "updater-status.json")
previous = previous if isinstance(previous, dict) else {}
if previous.get("request_id") != request.get("request_id") or previous.get("status") not in {"succeeded", "failed", "rolled_back"}:
identity, target = request.get("request_id"), request.get("version")
try:
if set(request) != {"protocol", "request_id", "executor_id", "version", "requested_at"}:
raise ValueError
issued = updates.parse_time(request.get("requested_at"))
now = updates.utc_now()
if (request["protocol"] != updates.PROTOCOL or not updates.valid_id(identity)
or request["executor_id"] != capability["executor_id"] or issued is None
or not now - timedelta(hours=24) <= issued <= now + timedelta(seconds=60)):
raise ValueError
updates.stable_version(target)
return self.apply(target, request_id=identity)
except (ValueError, UpdaterError):
if updates.valid_id(identity):
try:
updates.stable_version(target)
except ValueError:
pass
else:
return self.publish(identity, target, "failed")
return {"status": "failed", "message": "更新请求无效,未执行。"}
current = self.docker.inspect_service()["version"]
cached = updates.read_json(self.config.data_dir / "update-check.json")
cached = cached if isinstance(cached, dict) else {}
checked = updates.parse_time(cached.get("checked_at"))
state = updates.UpdateService(self.config.data_dir, current).status()
if checked is None or updates.utc_now() - checked >= timedelta(seconds=self.config.check_interval_seconds):
state = self.check(current)
if self.config.auto_apply and state["available"]:
return self.apply(state["latest_version"])
return state
@contextmanager
def exclusive(config):
import fcntl
path = config.project_dir / ".web-updater.lock"
descriptor = os.open(path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
try:
try:
fcntl.flock(descriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
raise UpdaterError("已有宿主机更新任务正在执行。") from None
yield
finally:
os.close(descriptor)
def dry_run(config, mode, version):
if version:
updates.stable_version(version)
return {"dry_run": True, "mode": mode, "repository": updates.REPOSITORY,
"image": f"{updates.IMAGE}:{version or '<official-newer-v2.x.y>'}",
"auto_apply": config.auto_apply, "accept_web_requests": config.accept_web_requests,
"steps": ["verify official stable release and running version", "validate single-service mounts",
"compose pull while old service runs", "stop; snapshot all data and encrypted keys",
"compose up -d --no-build --pull never --wait --wait-timeout",
"on failure: stop, restore snapshot, start pinned old image"]}
def interrupt_update(signum, frame):
raise InterruptedError("宿主机正在停止更新任务。")
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--config", default="/etc/ranch-web-updater.toml")
mode = parser.add_mutually_exclusive_group(required=True)
mode.add_argument("--check", action="store_true")
mode.add_argument("--apply", nargs="?", const="", metavar="v2.x.y")
mode.add_argument("--run", action="store_true")
parser.add_argument("--dry-run", action="store_true")
args = parser.parse_args(argv)
try:
config = Config.load(args.config, dry_run=args.dry_run)
if args.dry_run:
result = dry_run(config, "check" if args.check else "run" if args.run else "apply", args.apply)
else:
if sys.platform != "linux" or os.geteuid() != 0:
raise UpdaterError("执行更新需要 Linux 宿主机上的受控 root 服务;Windows 仅支持 dry-run。")
operator_config = Path(args.config)
if (not operator_config.is_file() or operator_config.is_symlink()
or operator_config.stat().st_uid != 0 or operator_config.stat().st_mode & 0o022):
raise UpdaterError("执行器配置必须由 root 持有,且不能被其他用户写入。")
if config.project_dir.stat().st_uid != 0 or config.project_dir.stat().st_mode & 0o022:
raise UpdaterError("部署项目目录必须由 root 持有且禁止其他用户写入。")
for path in (config.project_dir / "compose.yaml", config.project_dir / ".env", config.project_dir / ".image.env"):
if not path.is_file() or path.is_symlink() or path.stat().st_uid != 0 or path.stat().st_mode & 0o022:
raise UpdaterError("部署配置必须由 root 持有,且不能被其他用户写入。")
if not config.data_dir.is_dir() or config.data_dir.is_symlink() or config.data_dir.stat().st_uid != 10001:
raise UpdaterError("请先建立 UID 10001 可读写的独立 Web 数据目录。")
if not config.control_dir.is_dir() or config.control_dir.is_symlink() or config.control_dir.stat().st_uid != 0 or config.control_dir.stat().st_mode & 0o022:
raise UpdaterError("执行器控制目录必须由 root 持有且禁止其他用户写入。")
signal.signal(signal.SIGTERM, interrupt_update)
with exclusive(config):
updater = HostUpdater(config)
recovery = updater.recover()
if recovery:
result = recovery
elif args.check:
result = updater.check(updater.docker.inspect_service()["version"])
elif args.run:
result = updater.run()
else:
result = updater.apply(args.apply or None)
print(json.dumps(result, ensure_ascii=False, indent=2))
return int(result.get("status") in {"failed", "check_failed", "rolled_back"})
except UpdaterError as error:
print(json.dumps({"status": "failed", "message": str(error)}, ensure_ascii=False))
return 1
except (OSError, ValueError, TypeError):
print(json.dumps({"status": "failed", "message": "执行器配置、发布验证或 Docker 操作失败;未输出凭据或私有路径。"}, ensure_ascii=False))
return 1
if __name__ == "__main__":
raise SystemExit(main())
+12
View File
@@ -0,0 +1,12 @@
# Copy to /opt/ranch-web/.env, chmod 600, set a unique management password.
RANCH_WEB_PASSWORD=
RANCH_WEB_DATA_DIR=/opt/ranch-web/data
RANCH_WEB_UPDATER_CONTROL_DIR=/opt/ranch-web/updater-control
RANCH_WEB_BIND=127.0.0.1
RANCH_WEB_PUBLISH_PORT=8765
# Include the actual reverse-proxy hostname, without a scheme or path.
RANCH_WEB_ALLOWED_HOSTS=localhost,127.0.0.1
# Example behind TLS: https://ranch.example.com
RANCH_WEB_ALLOWED_ORIGINS=
# Set true when a TLS reverse proxy is configured.
RANCH_WEB_SECURE_COOKIE=false