Files
FinalToken/tools/lxc_update.py
T
Florian Schmidt afa6d83f2a
agent-review agent review: pass
tools: register the updater in the normal command path
Install the container updater under /usr/local/bin so shells without sbin can discover it. Print the absolute installed path as a fallback for custom environments and retain existing managed links. Reproduce command discovery through a real Bash lookup before fixing registration.

Refs #23
2026-11-15 15:05:16 +01:00

85 lines
3.9 KiB
Python

#!/usr/bin/env python3
"""Run as root INSIDE a managed FinalToken LXC. Fetch, build and activate the update here."""
import argparse
from contextlib import contextmanager
import importlib.util
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
ETC = Path("/etc/finaltoken")
REPOSITORY = "https://git.finalfactory.de/FinalFactory/FinalToken.git"
LOCK = Path("/run/lock/finaltoken-update.lock")
def run(command, **kwargs):
env = {key: os.environ[key] for key in ("PATH", "SystemRoot", "ComSpec", "PATHEXT", "TEMP", "TMP", "LANG", "LC_ALL") if key in os.environ}
env.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull,
GIT_TERMINAL_PROMPT="0", GCM_INTERACTIVE="Never")
return subprocess.run(list(map(str, command)), check=True, text=True, capture_output=True,
timeout=300, env=env, **kwargs)
@contextmanager
def update_lock():
import fcntl
with LOCK.open("w") as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
yield
def load(name, path):
spec = importlib.util.spec_from_file_location(name, path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dry-run", action="store_true", help="Read metadata and print the plan; no fetch or changes")
args = parser.parse_args(argv)
if not sys.platform.startswith("linux") or os.geteuid() != 0:
raise ValueError("Run finaltoken-update as root INSIDE the FinalToken LXC, not on the Proxmox host")
if not (ETC / "install.json").is_file():
raise ValueError("No managed container marker; run finaltoken-update INSIDE the FinalToken LXC")
marker = json.loads((ETC / "install.json").read_text(encoding="utf-8"))
if marker.get("installer") != "finaltoken-proxmox-v1" or marker.get("role") not in ("server", "worker", "both") or not isinstance(marker.get("ctid"), int):
raise ValueError("This is not a managed FinalToken container")
if args.dry_run:
print("Plan: fetch public master, build and update inside this container; preserve keys, profiles and history.")
if marker["role"] != "worker":
print("Backend: HTTP :5187 behind your existing HTTPS proxy; disable only the old FinalToken proxy.")
return 0
with update_lock():
if not shutil.which("git"):
run(["apt-get", "update"])
run(["env", "DEBIAN_FRONTEND=noninteractive", "apt-get", "install", "-y", "git", "ca-certificates"])
with tempfile.TemporaryDirectory(prefix="finaltoken-update-") as directory:
directory = Path(directory)
source = directory / "source"
print("Fetching FinalToken master inside the container...", flush=True)
run(["git", "-c", "credential.helper=", "clone", "--depth", "1", "--branch", "master",
"--single-branch", REPOSITORY, source])
bundle = load("finaltoken_source_bundle", source / "tools/proxmox/source_bundle.py")
archive = directory / "source.tar.gz"
checksum = bundle.snapshot(source, archive)
guest = load("finaltoken_guest_update", source / "tools/proxmox/guest.py")
guest.provision({"installer": marker["installer"], "action": "update", "ctid": marker["ctid"],
"sourceSha256": checksum}, archive)
print("Update complete. Future updates: " + str(guest.UPDATER))
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except (ValueError, OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as error:
print("FinalToken update failed: " + (str(error) if isinstance(error, ValueError) else type(error).__name__), file=sys.stderr)
print("Existing data retained. Fix the cause and retry inside this container.", file=sys.stderr)
sys.exit(1)