release: prepare Web 2.0.1 automatic strategies and private updates
This commit is contained in:
+85
-11
@@ -1,6 +1,8 @@
|
||||
# Web 2.0.0 Linux Docker 部署与更新
|
||||
# Web 2 Linux Docker 部署与更新
|
||||
|
||||
本目录对应 Web 正式版本 `2.0.0`,源码入口 `main`;游戏资料基线为 `1.9.68`,桌面版保留 `1.2.0`。Docker 镜像以稳定 `v2.x.y` 标签流水线成功结果为准,以下 pull 命令仅在对应镜像已发布且可访问后可用。在线更新依赖对应 GitHub Release 条目;仅有 merge/tag 时可能仍显示“暂无正式版”,不会安装旧桌面 1.2.0。
|
||||
以下更新示例以 `v2.0.1` 为目标;游戏资料基线为 `1.9.68`,桌面版保留 `1.2.0`。镜像流水线成功、Git tag 与 GitHub Release 是不同的发布步骤:在线更新必须等对应镜像及非草稿、非预发布的 Release 均发布后才能使用。私有仓库未获授权返回 404 属于访问失败,不代表没有版本;只有成功读取列表且没有稳定 2.x 时才显示“暂无正式版”。
|
||||
|
||||
已有部署首次接入私有在线更新时,按下文“已有宿主机首次初始化”操作。旧应用和旧更新器需要先配置私有发布认证,再由新版独立更新器在线拉取 `v2.0.1` 镜像。
|
||||
|
||||
## 容器与持久化
|
||||
|
||||
@@ -17,7 +19,7 @@ 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`,需确认对应镜像已发布后再 pull。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,写请求依赖来源校验。
|
||||
在 `.env` 填入独立的 `RANCH_WEB_PASSWORD`,这是 Web 管理密码,不是游戏密码;`.image.env` 选择 `RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.1`,需确认对应镜像已发布后再 pull。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`。不要对现有账号目录重新初始化密钥。
|
||||
|
||||
@@ -32,7 +34,7 @@ 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)
|
||||
私有 GHCR 包由用户先在宿主机为运行更新器的 root 用户配置一次 `docker login ghcr.io --password-stdin`,见下文。仓库与镜像可以保持私有;registry 凭据由宿主机 Docker 管理,不交给 Web 容器,也不从开发机迁移。
|
||||
|
||||
若仅在 Linux 上验证审核后的 `main` 源码,可在本地构建后启动;这不会发布镜像,也不要求远端已有对应镜像:
|
||||
|
||||
@@ -47,22 +49,92 @@ sudo sh deploy/web/compose.sh up -d --no-build --pull never --wait --wait-timeou
|
||||
|
||||
Web 只读检查官方 GitHub Releases;默认只接受 `v2.MINOR.PATCH`,跳过草稿、预发布、1.x、3.x 和非法标签。数字不含前导零。`2.0.0.dev1 → v2.0.0` 可升级,`2.0.0 → v2.0.0` 不升级,拒绝降级。网络失败会明确显示检查失败,不使用虚构版本或下载脚本。
|
||||
|
||||
先安装 root 持有的配置(示例的所有自动化开关默认关闭):
|
||||
全新安装时,先安装 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
|
||||
python3 -B tools/build_web_updater.py --output /tmp/updater.pyz
|
||||
sudo install -m 0644 -o root -g root /tmp/updater.pyz /opt/ranch-web/updater.pyz
|
||||
python3 -B /opt/ranch-web/updater.pyz --version
|
||||
```
|
||||
|
||||
也可从对应 Release 下载 `updater.pyz` 及 `SHA256SUMS`,核对后安装,宿主机不需要完整 Python 源码或 pip 依赖。构建器只打包 `__main__.py`、`updater.py`、`ranch_web/__init__.py`、`ranch_web/updates.py`,版本取构建时的 `ranch_web.__version__`;维护者升版后需重新生成资产。原有 `python3 -B deploy/web/updater.py ...` CLI 仍可运行,本文的 service 默认使用 `/opt/ranch-web/updater.pyz`。
|
||||
|
||||
### 已有宿主机首次初始化(用户自行执行)
|
||||
|
||||
前提是原有 `/opt/ranch-web` Compose 部署、数据目录及 `/etc/ranch-web-updater.toml` 均已存在,配置仍由 root 持有。保留原有数据和配置,不重新初始化密钥;数据目录由 `10001:10001` 持有。以下仅初始化在线更新器,不需要复制项目源码或 Compose。
|
||||
|
||||
1. 用户登录有私有仓库读取权限的 GitHub 账号,从 [v2.0.1 Release](https://github.com/attilanet/myrzx_bot/releases/tag/v2.0.1) 下载 `updater.pyz` 和 `SHA256SUMS`,放到宿主机临时目录。确认 Release 已发布且镜像可读取,在下载目录执行 `sha256sum -c SHA256SUMS` 后安装:
|
||||
|
||||
```sh
|
||||
sudo install -m 0644 -o root -g root updater.pyz /opt/ranch-web/updater.pyz
|
||||
python3 -B /opt/ranch-web/updater.pyz --help
|
||||
python3 -B /opt/ranch-web/updater.pyz --version
|
||||
python3 -B /opt/ranch-web/updater.pyz --config /etc/ranch-web-updater.toml --apply v2.0.1 --dry-run
|
||||
```
|
||||
|
||||
`--version` 应显示 `ranch-web-updater 2.0.1`;`--help`、`--version` 和 `--dry-run` 均不联网、不读取 Token、不调用 Docker,dry-run 不创建文件。Python 需为 3.12+。
|
||||
|
||||
2. 用户创建只授予本仓库 Contents **read** 的 fine-grained GitHub Token,用交互终端输入;值不出现在 argv、shell 历史或更新状态中:
|
||||
|
||||
```sh
|
||||
sudo python3 -B /opt/ranch-web/updater.pyz --config /etc/ranch-web-updater.toml --set-github-token
|
||||
```
|
||||
|
||||
该命令只在本机原子保存 `<data_dir>/update-github-token`,不联网验证。默认宿主机路径 `/opt/ranch-web/data/update-github-token`,权限 `0600`、所有者 `10001:10001`;容器通过现有 `/data` 挂载读取同一文件 `/data/update-github-token`。文件为单个 ASCII Token(可带末尾换行、总长最多 4096 字节),拒绝软链接、硬链接及 POSIX 下非 `0600` 文件。更新器只向固定 `https://api.github.com/repos/attilanet/myrzx_bot/releases` 发送 Authorization,禁止重定向;错误、DTO 与日志不输出 Token。
|
||||
|
||||
默认文件不存在时继续匿名访问,兼容公共仓库。可显式设置环境变量 `RANCH_WEB_UPDATE_GITHUB_TOKEN_FILE` 为绝对**文件路径**,不可填 Token;显式路径缺失或文件不安全会失败,不会回退匿名。宿主机和容器的覆盖路径需各自可见,现有 Compose 不透传这个可选环境变量,通常应直接用默认共享文件。不要将 Token 写入 TOML、请求 JSON 或 Web 表单。[GitHub Releases 权限说明](https://docs.github.com/en/rest/releases/releases#list-releases)
|
||||
|
||||
3. GHCR 使用另一份凭据:有镜像读取权限的用户创建 PAT **classic**,授予 `read:packages`(组织要求时授权 SSO)。Releases 的 fine-grained Token 不保证能用于 Docker。以下 Bash 命令由用户在宿主机终端执行一次,Token 通过 stdin 传给 root 的 Docker,不放入命令参数:
|
||||
|
||||
```bash
|
||||
sudo -v
|
||||
read -r -p 'GitHub username: ' ranch_ghcr_user
|
||||
read -r -s -p 'GHCR read:packages PAT (hidden): ' ranch_ghcr_pat
|
||||
printf '\n'
|
||||
printf '%s' "$ranch_ghcr_pat" | sudo docker --context default login ghcr.io --username "$ranch_ghcr_user" --password-stdin
|
||||
unset ranch_ghcr_pat ranch_ghcr_user
|
||||
```
|
||||
|
||||
Docker 保存的宿主机登录配置供更新器拉镜像使用;不要复制开发机的 Git/registry 凭据,也不要把 Docker 凭据放进 GitHub Token 文件或 Web 容器。[GHCR 官方认证说明](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry)
|
||||
|
||||
4. 使用新包先检查再由用户明确发起在线更新:
|
||||
|
||||
```sh
|
||||
sudo python3 -B /opt/ranch-web/updater.pyz --config /etc/ranch-web-updater.toml --check
|
||||
sudo python3 -B /opt/ranch-web/updater.pyz --config /etc/ranch-web-updater.toml --apply v2.0.1
|
||||
```
|
||||
|
||||
新更新器会独立复验官方 Release、严格版本递增、固定官方镜像,并执行原有备份、健康检查与失败回滚。旧 Web 即使尚不能查询私有发布,此命令仍可启动更新;更新到含新私有支持的镜像后,Web 的检查/请求才会读取共享 Token。只有 tag 或镜像、尚无 2.x Release 时仍不能更新;不要把旧页面的匿名 404 当成“已是最新”。
|
||||
|
||||
5. 让原有 systemd timer 执行新包。用户运行 `sudo systemctl edit ranch-web-updater.service`,只添加一次覆盖:
|
||||
|
||||
```ini
|
||||
[Service]
|
||||
ExecStart=
|
||||
ExecStart=/usr/bin/python3 -B /opt/ranch-web/updater.pyz --config /etc/ranch-web-updater.toml --run
|
||||
```
|
||||
|
||||
随后执行:
|
||||
|
||||
```sh
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now ranch-web-updater.timer
|
||||
sudo systemctl start ranch-web-updater.service
|
||||
```
|
||||
|
||||
原有 service 的 root、目录保护和 Docker 登录访问保持有效。新包成功初始化后,未来 Web 请求及 timer 都使用相同私有查询逻辑;未来要升级独立更新器本身时,仍由用户下载并替换受信任的 `updater.pyz`。`auto_apply=false` 继续默认关闭,允许 Web 按钮需另外显式设置 `accept_web_requests=true`。
|
||||
|
||||
`--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。
|
||||
新服务健康失败时,更新器停止失败容器、恢复更新前数据、用旧镜像的准确本地 image ID 启动并检查健康。失败版本数据移入 `failed-data/`,快照保存在 `backups/`,均不自动删除。快照包含默认共享 Token 文件以及应用密钥,快照文件权限为 0600、备份目录 0700;不会打印账号数据、密钥、Compose 环境或容器日志。回滚也失败时保留恢复事务,下一次更新器运行会先恢复,需操作者检查服务状态。镜像拉取和停机发生在宿主机;Web 容器没有 Docker socket。
|
||||
|
||||
## 定时检查、Web 按钮与自动更新
|
||||
|
||||
全新部署确认已按上文生成或下载安装 `/opt/ranch-web/updater.pyz` 后,再安装以下 service;已有部署使用上文的一次性 override。
|
||||
|
||||
```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/
|
||||
@@ -79,13 +151,15 @@ Windows 或未安装执行器的 Docker 部署仍能检查版本,但按钮会
|
||||
|
||||
## 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 或发布。
|
||||
[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 和正常停止;镜像发布状态以对应 tag 的工作流结果为准。
|
||||
|
||||
本机 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
|
||||
python -B tools/build_web_updater.py --output test-artifacts/updater.pyz
|
||||
python -B test-artifacts/updater.pyz --version
|
||||
python -B test-artifacts/updater.pyz --config deploy/web/updater.example.toml --apply v2.0.1 --dry-run
|
||||
python -B -m unittest ranch_web.tests.test_updates ranch_web.tests.test_web_updater ranch_web.tests.test_private_updates ranch_web.tests.test_web_updater_package -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`。
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Web 2 更新接口(协议 1)
|
||||
|
||||
供 API、前端、宿主机更新器与 Main 集成。`ranch_web.updates.UpdateService(root, current_version)` 只依赖 Python 标准库;构造和 `status()` 不联网,`check()` 才访问固定官方 GitHub Releases,`request_update(version=None)` 仅提交文件请求。API 可在线程池中调用检查,不能在事件循环里等待网络。
|
||||
供 API、前端、宿主机更新器与 Main 集成。`ranch_web.updates.UpdateService(root, current_version)` 只依赖 Python 标准库;构造和 `status()` 不联网,`check()` 访问固定官方 GitHub Releases,`request_update(version=None)` 再次联网验证后仅提交文件请求。宿主机 `HostUpdater.apply()` 独立再次验证发布。API 可在线程池中调用检查,不能在事件循环里等待网络。
|
||||
|
||||
- 固定仓库:`attilanet/myrzx_bot`;固定镜像:`ghcr.io/attilanet/myrzx_bot-web`。
|
||||
- 唯一可选发布 tag:`v2.MINOR.PATCH`(十进制、不许前导零、无任何后缀)。草稿、预发布、1.x、3.x、dev 分支全部跳过;按版本数值比较,不信任 GitHub latest 排序。
|
||||
@@ -9,6 +9,12 @@
|
||||
- 心跳由宿主机定时任务写入,含 `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 写文件不等于部署成功。
|
||||
|
||||
私有发布凭据只来自服务端 `<root>/update-github-token`,宿主机使用配置中的 `data_dir`;Docker 默认通过既有挂载共享同一文件。POSIX 权限必须为 `0600`,普通文件、非软/硬链接、最多 4096 字节;部署所有者为 `10001:10001`。可选 `RANCH_WEB_UPDATE_GITHUB_TOKEN_FILE` 仅接受绝对文件路径,显式无效路径直接失败。未提供覆盖且默认文件缺失时保持匿名公共访问;不读取 Git 凭据、不接收原始 Token 环境变量/TOML/Web 参数。低层 `github_releases(data_dir=None)` 保留无参数公共调用形式,服务与宿主机均传入自己的数据目录,每次查询重新读文件。
|
||||
|
||||
GitHub Authorization 只发往固定 `https://api.github.com/repos/attilanet/myrzx_bot/releases`,不跟随任何重定向。`401/403/404` 为 `check_failed`,固定 `message/error` 提醒检查私有仓库访问权限;凭据文件失效同样返回 `check_failed` 与固定文件权限提示,不能当作 `no_release`。本地 `update-check.json` 可记录白名单 `failure` 代码 `access_denied/token_file_invalid/check_failed`;公共 DTO 字段和协议号不变,不返回 Token、Token 路径、响应原文或原始异常。`request_update` 与宿主机复验遇到访问失败则拒绝请求/更新,保持原服务。
|
||||
|
||||
GitHub Releases 可使用限定仓库、Contents read 的 fine-grained Token;GHCR 由用户另用 PAT classic 的 `read:packages` 权限通过 `docker login --password-stdin` 配置。两份凭据分别管理,不假定 fine-grained Token 能拉私有镜像。独立 `updater.pyz` 构建/运行 CLI 及已有宿主机的一次性初始化、systemd override 见 [README.md](README.md);旧应用必须先经用户安装新宿主机更新器并升级镜像,才具有私有 Web 更新能力。
|
||||
|
||||
三个方法返回同一公共 DTO,示例:
|
||||
|
||||
```json
|
||||
@@ -36,7 +42,7 @@
|
||||
}
|
||||
```
|
||||
|
||||
`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`:`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。镜像构建成功或存在 tag 均不能替代正式 Release。
|
||||
|
||||
提交成功返回 `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 接受响应不应宣称已经升级;更新完成由宿主机健康检查决定。
|
||||
|
||||
|
||||
@@ -1,2 +1,2 @@
|
||||
# Pull only after the v2.0.0 image publishing workflow succeeds and the image is available.
|
||||
RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.0
|
||||
# Pull only after the v2.0.1 image publishing workflow succeeds and the image is available.
|
||||
RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.1
|
||||
|
||||
@@ -10,7 +10,7 @@ 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
|
||||
ExecStart=/usr/bin/python3 -B /opt/ranch-web/updater.pyz --config /etc/ranch-web-updater.toml --run
|
||||
TimeoutStartSec=30min
|
||||
TimeoutStopSec=180s
|
||||
UMask=0077
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
# Root-owned operator configuration. Never put this file in /data.
|
||||
project_dir = "/opt/ranch-web"
|
||||
data_dir = "/opt/ranch-web/data"
|
||||
# Optional private GitHub releases: data_dir/update-github-token, mode 0600,
|
||||
# owned by 10001:10001 (same file is /data/update-github-token in the app).
|
||||
# Set with: sudo python3 -B /opt/ranch-web/updater.pyz --config /etc/ranch-web-updater.toml --set-github-token
|
||||
# Optional ENV RANCH_WEB_UPDATE_GITHUB_TOKEN_FILE is an absolute PATH, not a token.
|
||||
# Private GHCR access is configured separately by the operator via docker login --password-stdin.
|
||||
control_dir = "/opt/ranch-web/updater-control"
|
||||
backup_dir = "/opt/ranch-web/backups"
|
||||
failed_data_dir = "/opt/ranch-web/failed-data"
|
||||
|
||||
+58
-14
@@ -2,7 +2,8 @@
|
||||
"""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.
|
||||
--run from the timer. --set-github-token prompts for a local credential file.
|
||||
--dry-run never contacts GitHub or Docker or writes files.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -10,6 +11,7 @@ import argparse
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass, fields
|
||||
from datetime import timedelta
|
||||
import getpass
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path, PurePosixPath
|
||||
@@ -23,10 +25,12 @@ import tarfile
|
||||
import tempfile
|
||||
import tomllib
|
||||
import uuid
|
||||
import warnings
|
||||
|
||||
# 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
|
||||
if __name__ == "__main__":
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
from ranch_web import __version__, 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)
|
||||
@@ -323,7 +327,9 @@ class HostUpdater:
|
||||
if not old["running"]:
|
||||
raise UpdaterError("现有服务未运行,请先由操作者处理。")
|
||||
try:
|
||||
tags = updates.official_tags(updates.github_releases())
|
||||
tags = updates.official_tags(updates.github_releases(self.config.data_dir))
|
||||
except updates.GitHubReleaseError as error:
|
||||
raise UpdaterError(str(error)) from None
|
||||
except Exception:
|
||||
raise UpdaterError("无法独立验证官方 GitHub 正式发布,保留现有服务。") from None
|
||||
target = version or (max(tags, key=updates.stable_version) if tags else None)
|
||||
@@ -436,19 +442,54 @@ def interrupt_update(signum, frame):
|
||||
raise InterruptedError("宿主机正在停止更新任务。")
|
||||
|
||||
|
||||
def set_github_token(config):
|
||||
"""Operator-only local setup: no argv secret, network, or credential discovery."""
|
||||
try:
|
||||
# getpass must not fall back to echoed input on a non-interactive console.
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", getpass.GetPassWarning)
|
||||
token = getpass.getpass("GitHub read-only release token (hidden): ")
|
||||
token = updates._validate_token((token + "\n").encode("ascii"))
|
||||
path = updates.github_token_path(config.data_dir)
|
||||
if path.is_symlink():
|
||||
raise updates.GitHubReleaseError("token_file_invalid")
|
||||
descriptor, temporary = tempfile.mkstemp(prefix=".update-token-", dir=path.parent)
|
||||
try:
|
||||
with os.fdopen(descriptor, "w", encoding="ascii", newline="\n") as stream:
|
||||
os.chmod(temporary, 0o600)
|
||||
if hasattr(os, "chown"):
|
||||
os.chown(temporary, 10001, 10001)
|
||||
stream.write(token + "\n")
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
if os.path.exists(temporary):
|
||||
os.unlink(temporary)
|
||||
except (OSError, UnicodeError, updates.GitHubReleaseError, EOFError, getpass.GetPassWarning, KeyboardInterrupt):
|
||||
raise UpdaterError("GitHub Token 未保存;请使用交互终端并检查服务端文件与数据目录权限。") from None
|
||||
return {"status": "configured", "message": "GitHub 只读 Token 已保存为 0600 文件;尚未联网验证权限。"}
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--version", action="version", version=f"ranch-web-updater {__version__}")
|
||||
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")
|
||||
mode.add_argument("--set-github-token", action="store_true", help="interactively save a server-side token file")
|
||||
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)
|
||||
if args.set_github_token:
|
||||
result = {"dry_run": True, "mode": "set-github-token",
|
||||
"steps": ["prompt for read-only GitHub token; atomically save 0600 file owned by UID/GID 10001"]}
|
||||
else:
|
||||
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。")
|
||||
@@ -467,16 +508,19 @@ def main(argv=None):
|
||||
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()
|
||||
if args.set_github_token:
|
||||
result = set_github_token(config)
|
||||
else:
|
||||
result = updater.apply(args.apply or None)
|
||||
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:
|
||||
|
||||
Reference in New Issue
Block a user