release: prepare Web 2.0.1 automatic strategies and private updates
This commit is contained in:
+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