Files
NODEDC_MISSION_CORE/apps/vps-host/install.py
T

430 lines
16 KiB
Python

#!/usr/bin/env python3
"""Versioned Ubuntu 24.04 amd64 installer. Run plan, then apply its exact digest."""
import argparse
import hashlib
import json
import os
import platform
import pwd
import re
import shutil
import socket
import ssl
import subprocess
import sys
import time
import uuid
from pathlib import Path
import firewall
ROOT = Path("/opt/nodedc-mission-vps")
STATE = Path("/var/lib/ndc-mission-vps")
UNIT = Path("/etc/systemd/system/ndc-mission-vps.service")
USER = "ndc-mission-vps"
SOURCE = Path(__file__).resolve().parent
SERVICE = """# Managed by NODE.DC Mission VPS installer v1
[Unit]
Description=NODE.DC Mission VPS Host
After=network-online.target
Wants=network-online.target
ConditionPathExists=!/opt/nodedc-mission-vps/migration-fence.json
[Service]
Type=simple
User=ndc-mission-vps
Group=ndc-mission-vps
WorkingDirectory=/opt/nodedc-mission-vps/current
ExecStart=/usr/bin/python3 -m ndc_vps serve
Restart=on-failure
RestartSec=5
UMask=0077
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
ReadWritePaths=/var/lib/ndc-mission-vps
MemoryMax=192M
TasksMax=96
LimitNOFILE=2048
[Install]
WantedBy=multi-user.target
"""
def run(*args, **kwargs):
return subprocess.run(args, check=True, capture_output=True, **kwargs)
def digest():
manifest = json.loads((SOURCE / "manifest.json").read_text())
for name, expected in manifest["files"].items():
if name.startswith("/") or ".." in Path(name).parts:
raise ValueError("invalid manifest")
if hashlib.sha256((SOURCE / name).read_bytes()).hexdigest() != expected:
raise ValueError("artifact integrity mismatch")
return hashlib.sha256((SOURCE / "manifest.json").read_bytes()).hexdigest()
def predecessor():
return os.readlink(ROOT / "current") if (ROOT / "current").is_symlink() else None
def plan(args):
osrelease = dict(
line.split("=", 1)
for line in Path("/etc/os-release").read_text().splitlines()
if "=" in line
)
if (
osrelease.get("ID", "").strip('"') != "ubuntu"
or osrelease.get("VERSION_ID", "").strip('"') != "24.04"
or platform.machine() != "x86_64"
):
raise ValueError("supported environment: Ubuntu Server 24.04 amd64 only")
if sys.version_info[:2] != (3, 12):
raise ValueError("Python 3.12 required")
for command in ("openssl", "systemctl", "useradd", "runuser"):
if not shutil.which(command):
raise ValueError("missing OS prerequisite: " + command)
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9.-]{0,48}", args.host):
raise ValueError("public DNS name or IPv4 required (max 49 characters for B2)")
if UNIT.exists() and "Managed by NODE.DC Mission VPS installer v1" not in UNIT.read_text():
raise ValueError("foreign service conflict")
if ROOT.exists() and not (ROOT / "installed.json").exists():
raise ValueError("foreign installation root conflict")
if STATE.exists() and not (STATE / "host.json").exists():
raise ValueError("foreign state directory conflict")
if (ROOT / "migration-fence.json").exists():
raise ValueError("source fenced for migration; resume explicitly only with target stopped")
old = predecessor()
for port in (args.api_port, args.tracker_port):
if port < 1024 or port > 65535:
raise ValueError("ports must be 1024..65535")
if not old:
with socket.socket() as sock:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("0.0.0.0", port))
if args.api_port == args.tracker_port:
raise ValueError("ports must differ")
configuration = {
"public_host": args.host,
"api_port": args.api_port,
"tracker": {"host": args.host, "port": args.tracker_port},
}
if STATE.exists():
existing = json.loads((STATE / "host.json").read_text())
if any(existing[key] != val for key, val in configuration.items()):
raise ValueError(
"endpoint migration requires a separate planned operation; use stable DNS"
)
data = {
"schema": "missioncore.vps-install-plan/v1",
"firewall": firewall.plan(),
"artifact": digest(),
"previous": old,
"configuration": configuration,
"unit_sha256": hashlib.sha256(UNIT.read_bytes()).hexdigest() if UNIT.exists() else None,
"environment": "ubuntu-24.04-amd64",
"service": str(UNIT),
"root": str(ROOT),
"key_file": str(ROOT / "connect.key"),
}
data["plan_sha256"] = hashlib.sha256(json.dumps(data, sort_keys=True).encode()).hexdigest()
return data
def atomic(path, value, mode=0o600):
temporary = path.with_name(path.name + ".new")
temporary.write_bytes(value)
temporary.chmod(mode)
os.replace(temporary, path)
def select_release(release):
temporary = ROOT / ".current"
temporary.unlink(missing_ok=True)
temporary.symlink_to(release)
os.replace(temporary, ROOT / "current")
def healthy():
for _ in range(20):
if subprocess.run(["systemctl", "is-active", "--quiet", "ndc-mission-vps"]).returncode == 0:
try:
config = json.loads((STATE / "host.json").read_text())
ctx = ssl.create_default_context(cafile=str(STATE / "tls.crt"))
ctx.check_hostname = False
with (
socket.create_connection(("127.0.0.1", config["api_port"]), 2) as sock,
ctx.wrap_socket(sock) as secure,
):
secure.sendall(b"GET /health HTTP/1.1\r\nHost: localhost\r\n\r\n")
if b"200 Result" in secure.recv(4096):
return
except OSError:
pass
time.sleep(0.5)
raise ValueError("service health check failed")
def apply(args, proposal):
if os.geteuid() != 0 or args.expect != proposal["plan_sha256"]:
raise ValueError("root and exact current plan digest required")
old = proposal["previous"]
installed = ROOT / "installed.json"
if (
old
and Path(old).name == proposal["artifact"]
and installed.exists()
and json.loads(installed.read_text()).get("status") == "healthy"
):
healthy()
print(json.dumps({"status": "already_current", "artifact": proposal["artifact"]}))
return
release = ROOT / "releases" / proposal["artifact"]
ROOT.mkdir(mode=0o755, exist_ok=True)
(ROOT / "releases").mkdir(mode=0o755, exist_ok=True)
# mkdir's mode is filtered by the caller's umask. The unprivileged service
# must traverse these owned code directories even under root's umask 0077.
ROOT.chmod(0o755)
(ROOT / "releases").chmod(0o755)
old_unit = UNIT.read_bytes() if UNIT.exists() else None
# Pre-create the ownership record: a failed first install can be inspected/retried.
if not (ROOT / "installed.json").exists():
atomic(
ROOT / "installed.json",
json.dumps({"schema": "missioncore.vps-install/v1", "status": "preparing"}).encode(),
)
try:
pwd.getpwnam(USER)
except KeyError:
run("useradd", "--system", "--home-dir", str(STATE), "--shell", "/usr/sbin/nologin", USER)
user = pwd.getpwnam(USER)
if not release.exists():
shutil.copytree(SOURCE, release, ignore=shutil.ignore_patterns("__pycache__"))
release.chmod(0o755)
for item in release.rglob("*"):
item.chmod(0o755 if item.is_dir() else 0o644)
if not STATE.exists():
STATE.mkdir(mode=0o700)
configuration = proposal["configuration"].copy()
run(
"openssl",
"req",
"-x509",
"-newkey",
"ed25519",
"-nodes",
"-days",
"3650",
"-subj",
"/CN=NODE.DC Mission VPS Host",
"-keyout",
str(STATE / "tls.key"),
"-out",
str(STATE / "tls.crt"),
)
certificate = ssl.PEM_cert_to_DER_cert((STATE / "tls.crt").read_text())
fingerprint = hashlib.sha256(certificate).hexdigest()
configuration.update(
fingerprint=fingerprint,
host_id="vps_" + fingerprint,
endpoint=f"https://{args.host}:{args.api_port}",
)
atomic(STATE / "host.json", json.dumps(configuration, indent=2).encode())
os.chown(STATE, user.pw_uid, user.pw_gid)
for item in STATE.iterdir():
item.chmod(0o600)
os.chown(item, user.pw_uid, user.pw_gid)
if not (ROOT / "connect.key").is_symlink():
(ROOT / "connect.key").symlink_to(STATE / "connect.key")
firewall_added = False
try:
firewall_added = firewall.apply(
proposal["firewall"], args.api_port, args.tracker_port, atomic
)
select_release(release)
if not (STATE / "connect.key").exists():
run(
"runuser",
"-u",
USER,
"--",
"/usr/bin/python3",
"-m",
"ndc_vps",
"invitation",
cwd=release,
)
atomic(UNIT, SERVICE.encode(), 0o644)
run("systemctl", "daemon-reload")
run("systemctl", "enable", "ndc-mission-vps.service")
run("systemctl", "restart", "ndc-mission-vps.service")
healthy()
atomic(
ROOT / "installed.json",
json.dumps(
{
**proposal,
"status": "healthy",
"firewall_added": firewall_added,
"installed_at": time.time(),
},
indent=2,
).encode(),
)
print(
json.dumps(
{
"status": "healthy",
"artifact": proposal["artifact"],
"key_file": str(ROOT / "connect.key"),
}
)
)
except Exception:
if firewall_added:
firewall.rollback(atomic)
if old:
select_release(old)
if old_unit:
atomic(UNIT, old_unit, 0o644)
run("systemctl", "daemon-reload")
run("systemctl", "restart", "ndc-mission-vps.service")
healthy()
else:
subprocess.run(
["systemctl", "disable", "--now", "ndc-mission-vps.service"], capture_output=True
)
raise
def rollback(args):
record = json.loads((ROOT / "installed.json").read_text())
if os.geteuid() != 0 or args.expect != record["artifact"]:
raise ValueError("root and installed artifact digest required")
if record.get("firewall_added"):
firewall.rollback(atomic)
previous = record["previous"]
if previous:
path = Path(previous)
if path.parent != ROOT / "releases" or not path.is_dir():
raise ValueError("previous release unavailable")
select_release(path)
run("systemctl", "restart", "ndc-mission-vps.service")
healthy()
else:
run("systemctl", "disable", "--now", "ndc-mission-vps.service")
# Preserve state, keys and journal even when uninstalling the first release.
atomic(ROOT / "installed.json", json.dumps({**record, "status": "rolled_back"}).encode())
print(json.dumps({"status": "rolled_back", "state_preserved": True}))
BACKUPS = Path("/var/backups/ndc-mission-vps")
def restore(backup):
if os.geteuid() != 0 or backup.parent != BACKUPS or backup.is_symlink():
raise ValueError("root and an installer-owned backup required")
if (ROOT / "migration-fence.json").exists():
raise ValueError("source fenced for migration")
record = json.loads((backup / "backup.json").read_text())
if record.get("schema") != "missioncore.vps-backup/v1":
raise ValueError("invalid backup")
# Verify before stopping anything. Never overwrite a foreign service.
if UNIT.exists() and "Managed by NODE.DC Mission VPS installer v1" not in UNIT.read_text():
raise ValueError("foreign service conflict")
for name, expected in record["files"].items():
file = backup / name
if ".." in Path(name).parts or file.is_symlink():
raise ValueError("invalid backup file")
if hashlib.sha256(file.read_bytes()).hexdigest() != expected:
raise ValueError("backup integrity mismatch")
run("systemctl", "stop", "ndc-mission-vps.service")
recovery = backup / ("replaced-" + uuid.uuid4().hex)
recovery.mkdir(mode=0o700)
for name, target in (("root", ROOT), ("state", STATE), ("unit", UNIT)):
if target.exists():
shutil.move(str(target), recovery / name)
source = backup / name
if source.is_dir():
shutil.copytree(source, target, symlinks=True)
else:
shutil.copy2(source, target)
user = pwd.getpwnam(USER)
os.chown(STATE, user.pw_uid, user.pw_gid)
for file in STATE.iterdir():
os.chown(file, user.pw_uid, user.pw_gid)
run("systemctl", "daemon-reload")
run("systemctl", "enable", "ndc-mission-vps.service")
run("systemctl", "restart", "ndc-mission-vps.service")
healthy()
print(json.dumps({"status": "restored", "backup": str(backup)}))
def fresh(args, proposal):
if os.geteuid() != 0 or args.expect != proposal["plan_sha256"] or not proposal["previous"]:
raise ValueError("fresh replacement requires an exact plan of an installed product")
BACKUPS.mkdir(mode=0o700, parents=True, exist_ok=True)
backup = BACKUPS / (time.strftime("%Y%m%dT%H%M%SZ", time.gmtime()) + "-" + uuid.uuid4().hex[:8])
backup.mkdir(mode=0o700)
run("systemctl", "stop", "ndc-mission-vps.service")
try:
for name, path in (("root", ROOT), ("state", STATE)):
shutil.copytree(path, backup / name, symlinks=True)
shutil.copy2(UNIT, backup / "unit")
files = {
str(p.relative_to(backup)): hashlib.sha256(p.read_bytes()).hexdigest()
for p in backup.rglob("*")
if p.is_file() and not p.is_symlink()
}
atomic(
backup / "backup.json",
json.dumps(
{
"schema": "missioncore.vps-backup/v1",
"created_at": time.time(),
"monotonic": time.monotonic(),
"files": files,
}
).encode(),
)
except Exception:
run("systemctl", "start", "ndc-mission-vps.service")
raise
try:
# Complete verified private copy exists; move original trees too, never wildcard-delete.
shutil.move(str(ROOT), backup / "original-root")
shutil.move(str(STATE), backup / "original-state")
shutil.move(str(UNIT), backup / "original-unit")
new_plan = plan(args)
args.expect = new_plan["plan_sha256"]
apply(args, new_plan)
except Exception:
restore(backup)
raise
print(json.dumps({"status": "fresh_install", "backup": str(backup)}))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("action", choices=("plan", "apply", "rollback"))
parser.add_argument("--host", required=True)
parser.add_argument("--api-port", type=int, default=19443)
parser.add_argument("--tracker-port", type=int, default=9922)
parser.add_argument("--expect")
args = parser.parse_args()
try:
if args.action == "rollback":
rollback(args)
else:
proposal = plan(args)
if args.action == "plan":
print(json.dumps(proposal, indent=2))
else:
apply(args, proposal)
except Exception as error:
print("Installation stopped: " + str(error), file=sys.stderr)
sys.exit(1)