Keep the Proxmox host responsible only for container creation. Serve the private backend on port 5187 behind the operator's HTTPS proxy and install a self-updating in-container command. Preserve existing identity and history while migrating the old installer-owned proxy with listener rollback. Refs #21
This commit is contained in:
+23
-76
@@ -1,6 +1,5 @@
|
||||
"""Create/update an unprivileged Debian 13 LXC from a local FinalToken source snapshot."""
|
||||
"""Create an unprivileged Debian 13 LXC. Updates run inside the container."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
@@ -9,17 +8,14 @@ import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import tempfile
|
||||
import time
|
||||
from urllib.parse import urlsplit
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from source_policy import is_private_path
|
||||
from source_bundle import PROJECTS, snapshot
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PROJECTS = ("FinalToken.Core", "FinalToken.Fleet", "FinalToken.Web", "FinalToken.Worker")
|
||||
TEMPLATE = re.compile(r"debian-13-standard_[A-Za-z0-9.+_-]+_amd64\.tar\.(?:zst|xz|gz)\Z")
|
||||
|
||||
|
||||
@@ -55,8 +51,8 @@ def server_url(value):
|
||||
|
||||
def parser():
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("action", choices=("install", "update"))
|
||||
p.add_argument("--ctid", type=int, help="New CT id; defaults to Proxmox nextid. Required for update.")
|
||||
p.add_argument("action", choices=("install",), help="Create a CT. Run finaltoken-update inside an existing CT.")
|
||||
p.add_argument("--ctid", type=int, help="New CT id; defaults to Proxmox nextid.")
|
||||
p.add_argument("--source", type=Path, default=ROOT, help="Local checkout including uncommitted source")
|
||||
p.add_argument("--storage", help="Proxmox rootdir storage, e.g. local-lvm (required for install)")
|
||||
p.add_argument("--template-storage", default="local")
|
||||
@@ -68,9 +64,8 @@ def parser():
|
||||
p.add_argument("--memory", type=int, default=4096, help="MiB; builds need at least 4096")
|
||||
p.add_argument("--cores", type=int, default=2)
|
||||
p.add_argument("--disk", type=int, default=20, help="GiB")
|
||||
p.add_argument("--role", choices=("both", "server", "worker"), help="Install default: both; update preserves role")
|
||||
p.add_argument("--role", choices=("both", "server", "worker"), help="Install default: both")
|
||||
p.add_argument("--domain", help="Dashboard DNS name; required for server/both")
|
||||
p.add_argument("--tls", choices=("acme", "internal"), default="acme")
|
||||
p.add_argument("--email", help="Expected provider email for both selected providers")
|
||||
p.add_argument("--claude-email")
|
||||
p.add_argument("--codex-email")
|
||||
@@ -86,16 +81,10 @@ def parser():
|
||||
def validate(args):
|
||||
if args.ctid is not None and not 100 <= args.ctid <= 999999999:
|
||||
raise ValueError("CT id must be between 100 and 999999999")
|
||||
if args.action == "update" and args.ctid is None:
|
||||
raise ValueError("Update requires --ctid")
|
||||
args.source = args.source.resolve()
|
||||
for project in PROJECTS:
|
||||
if not (args.source / "src" / project / (project + ".csproj")).is_file():
|
||||
raise ValueError("Source must include the web/worker implementation: " + project)
|
||||
if args.action == "update":
|
||||
if args.role or args.domain or args.email or args.claude_email or args.codex_email or args.machine_id or args.server_url or args.worker_key_file:
|
||||
raise ValueError("Update preserves identity/configuration; pass only CT id and source (plus --dry-run)")
|
||||
return
|
||||
args.role = args.role or "both"
|
||||
for value in (args.storage or "", args.template_storage, args.bridge):
|
||||
if not re.fullmatch(r"[A-Za-z][A-Za-z0-9_-]{0,63}", value):
|
||||
@@ -116,7 +105,7 @@ def validate(args):
|
||||
raise ValueError("Template must be a Debian 13 standard amd64 template filename")
|
||||
if args.role != "worker":
|
||||
if not args.domain:
|
||||
raise ValueError("Server/both requires --domain for HTTPS; use --tls internal for a private CA")
|
||||
raise ValueError("Server/both requires the public hostname configured on your existing HTTPS reverse proxy")
|
||||
args.domain = domain_name(args.domain)
|
||||
else:
|
||||
if not args.server_url or not args.worker_key_file:
|
||||
@@ -153,37 +142,6 @@ def create_command(args, ctid, template):
|
||||
"--description", "FinalToken installer; retains configuration and CLI profiles on update"]
|
||||
|
||||
|
||||
def snapshot(source, destination):
|
||||
"""Allowlist source inputs, including uncommitted changes, excluding secrets, outputs and symlinks."""
|
||||
files = [source / n for n in ("Directory.Build.props", "Directory.Packages.props", "global.json", "LICENSE")]
|
||||
for project in PROJECTS:
|
||||
directory = source / "src" / project
|
||||
if directory.is_symlink() or directory.resolve() != directory.absolute():
|
||||
raise ValueError("Source snapshot refuses a symlinked project or parent: " + project)
|
||||
files.extend(directory.rglob("*"))
|
||||
total, count = 0, 0
|
||||
with tarfile.open(destination, "w:gz") as archive:
|
||||
for path in sorted(set(files)):
|
||||
relative = path.relative_to(source)
|
||||
if is_private_path(relative):
|
||||
continue # .gitignore does not apply to tarfile: do not copy local deployment data.
|
||||
if any(p in ("bin", "obj", "artifacts", ".git", "node_modules") or p.startswith(".") for p in relative.parts):
|
||||
continue
|
||||
if path.is_symlink():
|
||||
raise ValueError("Source snapshot refuses symlinks: " + str(relative))
|
||||
if path.is_dir():
|
||||
continue
|
||||
if not path.is_file():
|
||||
raise ValueError("Missing or non-regular source file: " + str(relative))
|
||||
size = path.stat().st_size
|
||||
total += size
|
||||
count += 1
|
||||
if size > 16 * 1024 * 1024 or total > 256 * 1024 * 1024 or count > 10000:
|
||||
raise ValueError("Source snapshot exceeds the guest archive bounds")
|
||||
archive.add(path, arcname=relative.as_posix(), recursive=False)
|
||||
return hashlib.sha256(destination.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def execute(args):
|
||||
if not sys.platform.startswith("linux") or os.geteuid() != 0:
|
||||
raise ValueError("Run as root on the Proxmox host; --dry-run works without Proxmox")
|
||||
@@ -203,32 +161,21 @@ def execute(args):
|
||||
def deploy(args, archive, sha):
|
||||
ctid = args.ctid or int(json.loads(run(["pvesh", "get", "/cluster/nextid", "--output-format", "json"], capture=True).stdout))
|
||||
status = run(["pct", "status", ctid], capture=True, check=False)
|
||||
if args.action == "install":
|
||||
if status.returncode == 0:
|
||||
raise ValueError("CT already exists; refusing to overwrite it. Use update for a managed installation.")
|
||||
run(["pveam", "update"])
|
||||
template = args.template
|
||||
if not template:
|
||||
available = run(["pveam", "available", "--section", "system"], capture=True).stdout
|
||||
candidates = [word for word in available.split() if TEMPLATE.fullmatch(word)]
|
||||
if not candidates:
|
||||
raise ValueError("No Debian 13 amd64 template found; pass --template explicitly")
|
||||
template = sorted(candidates, key=lambda s: [int(p) if p.isdigit() else p for p in re.split(r"(\d+)", s)])[-1]
|
||||
path = run(["pvesm", "path", f"{args.template_storage}:vztmpl/{template}"], capture=True, check=False)
|
||||
if path.returncode or not Path(path.stdout.strip()).is_file():
|
||||
run(["pveam", "download", args.template_storage, template])
|
||||
run(create_command(args, ctid, template))
|
||||
else:
|
||||
if status.returncode:
|
||||
raise ValueError("Cannot access selected CT")
|
||||
# Reject foreign CTs before starting them or installing packages.
|
||||
metadata = json.loads(run(["pct", "exec", ctid, "--", "cat", "/etc/finaltoken/install.json"], capture=True).stdout) if "running" in status.stdout else None
|
||||
if metadata is None:
|
||||
raise ValueError("Start the existing managed CT before updating; stopped CTs are not modified")
|
||||
if metadata.get("installer") != "finaltoken-proxmox-v1" or metadata.get("ctid") != ctid:
|
||||
raise ValueError("Selected CT is not managed by this installer")
|
||||
if args.action == "install":
|
||||
run(["pct", "start", ctid])
|
||||
if status.returncode == 0:
|
||||
raise ValueError("CT already exists; run finaltoken-update inside that container")
|
||||
run(["pveam", "update"])
|
||||
template = args.template
|
||||
if not template:
|
||||
available = run(["pveam", "available", "--section", "system"], capture=True).stdout
|
||||
candidates = [word for word in available.split() if TEMPLATE.fullmatch(word)]
|
||||
if not candidates:
|
||||
raise ValueError("No Debian 13 amd64 template found; pass --template explicitly")
|
||||
template = sorted(candidates, key=lambda s: [int(p) if p.isdigit() else p for p in re.split(r"(\d+)", s)])[-1]
|
||||
path = run(["pvesm", "path", f"{args.template_storage}:vztmpl/{template}"], capture=True, check=False)
|
||||
if path.returncode or not Path(path.stdout.strip()).is_file():
|
||||
run(["pveam", "download", args.template_storage, template])
|
||||
run(create_command(args, ctid, template))
|
||||
run(["pct", "start", ctid])
|
||||
for _ in range(30):
|
||||
if run(["pct", "exec", ctid, "--", "test", "-d", "/run/systemd/system"], capture=True, check=False).returncode == 0:
|
||||
break
|
||||
@@ -242,7 +189,7 @@ def deploy(args, archive, sha):
|
||||
tmp = Path(tmp)
|
||||
manifest = {"installer": "finaltoken-proxmox-v1", "ctid": ctid, "action": args.action, "sourceSha256": sha}
|
||||
if args.action == "install":
|
||||
manifest.update(role=args.role, domain=args.domain, tls=args.tls, machineId=args.machine_id or f"lxc_{ctid}",
|
||||
manifest.update(role=args.role, domain=args.domain, network="external", machineId=args.machine_id or f"lxc_{ctid}",
|
||||
timezone=args.timezone, providers=args.providers, serverUrl=args.server_url,
|
||||
emails={p: getattr(args, p + "_email") or args.email for p in args.providers})
|
||||
if args.role == "worker":
|
||||
@@ -274,7 +221,7 @@ def main(argv=None):
|
||||
print("Unprivileged Debian 13 amd64; build NativeAOT inside CT; preserve config, keys, history and CLI profiles.")
|
||||
if args.action == "install":
|
||||
print(f"Root storage={args.storage}; template storage={args.template_storage}; bridge={args.bridge}; IP={args.ip}")
|
||||
print(f"Dashboard={('https://' + args.domain) if args.domain else args.server_url}; TLS={args.tls}")
|
||||
print(f"Dashboard={('https://' + args.domain) if args.domain else args.server_url}; backend=HTTP :5187 behind your existing reverse proxy")
|
||||
return 0
|
||||
execute(args)
|
||||
return 0
|
||||
|
||||
Reference in New Issue
Block a user