312 lines
12 KiB
Python
312 lines
12 KiB
Python
"""Private, quiesced state transfer. Code and system configuration come from the installer."""
|
|
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
import re
|
|
import shutil
|
|
import sqlite3
|
|
import ssl
|
|
import subprocess
|
|
import tarfile
|
|
import tempfile
|
|
import time
|
|
import uuid
|
|
from pathlib import Path
|
|
|
|
SCHEMA = "missioncore.vps-portable-state/v1"
|
|
FILES = {"host.json", "tls.crt", "tls.key", "connect.key", "journal.sqlite3"}
|
|
MAX_BYTES = 2 * 1024**3
|
|
SERVICE = "ndc-mission-vps.service"
|
|
|
|
|
|
def sha(path):
|
|
with path.open("rb") as stream:
|
|
return hashlib.file_digest(stream, "sha256").hexdigest()
|
|
|
|
|
|
def sync_directory(path):
|
|
fd = os.open(path, os.O_RDONLY)
|
|
try:
|
|
os.fsync(fd)
|
|
finally:
|
|
os.close(fd)
|
|
|
|
|
|
def durable_json(path, value):
|
|
temporary = path.with_name(path.name + ".new")
|
|
with temporary.open("wb") as stream:
|
|
temporary.chmod(0o600)
|
|
stream.write(json.dumps(value, sort_keys=True, indent=2).encode())
|
|
stream.flush()
|
|
os.fsync(stream.fileno())
|
|
os.replace(temporary, path)
|
|
sync_directory(path.parent)
|
|
|
|
|
|
def options(config):
|
|
return argparse.Namespace(
|
|
host=config["public_host"],
|
|
api_port=config["api_port"],
|
|
tracker_port=config["tracker"]["port"],
|
|
expect=None,
|
|
)
|
|
|
|
|
|
def check_state(state):
|
|
config = json.loads((state / "host.json").read_text())
|
|
fingerprint = hashlib.sha256(
|
|
ssl.PEM_cert_to_DER_cert((state / "tls.crt").read_text())
|
|
).hexdigest()
|
|
if config["fingerprint"] != fingerprint or config["host_id"] != "vps_" + fingerprint:
|
|
raise ValueError("state TLS identity mismatch")
|
|
if (
|
|
config["endpoint"] != f"https://{config['public_host']}:{config['api_port']}"
|
|
or config["tracker"]["host"] != config["public_host"]
|
|
):
|
|
raise ValueError("inconsistent state endpoints")
|
|
cert = subprocess.run(
|
|
["openssl", "x509", "-in", str(state / "tls.crt"), "-pubkey", "-noout"],
|
|
capture_output=True,
|
|
check=True,
|
|
).stdout
|
|
key = subprocess.run(
|
|
["openssl", "pkey", "-in", str(state / "tls.key"), "-pubout"],
|
|
capture_output=True,
|
|
check=True,
|
|
).stdout
|
|
if cert != key:
|
|
raise ValueError("state private key mismatch")
|
|
with sqlite3.connect((state / "journal.sqlite3").as_uri() + "?mode=ro", uri=True) as db:
|
|
if db.execute("PRAGMA integrity_check").fetchall() != [("ok",)]:
|
|
raise ValueError("state journal integrity failure")
|
|
# Enforce the known state boundary without rewriting its IDs or deadlines.
|
|
for table in (
|
|
"state",
|
|
"devices",
|
|
"packages",
|
|
"receipts",
|
|
"commands",
|
|
"operations",
|
|
"operation_attempts",
|
|
"operation_stops",
|
|
):
|
|
db.execute(f'SELECT COUNT(*) FROM "{table}"').fetchone()
|
|
return config
|
|
|
|
|
|
def export_state(engine, destination):
|
|
if os.geteuid() != 0:
|
|
raise ValueError("root required")
|
|
destination = destination.absolute()
|
|
if destination.exists() or destination.is_symlink() or not destination.parent.is_dir():
|
|
raise ValueError("new archive path in an existing directory required")
|
|
config = json.loads((engine.STATE / "host.json").read_text())
|
|
proposal = engine.plan(options(config))
|
|
if not proposal["previous"] or Path(proposal["previous"]).name != proposal["artifact"]:
|
|
raise ValueError("install this exact release before exporting its state")
|
|
if (
|
|
"ConditionPathExists=!/opt/nodedc-mission-vps/migration-fence.json"
|
|
not in engine.UNIT.read_text()
|
|
):
|
|
raise ValueError("installed service has no persistent migration fence")
|
|
engine.healthy()
|
|
allowed = FILES | {"journal.sqlite3-wal", "journal.sqlite3-shm", "journal.sqlite3-journal"}
|
|
if any(
|
|
p.name not in allowed or p.is_symlink() or not p.is_file() for p in engine.STATE.iterdir()
|
|
):
|
|
raise ValueError("unrecognized private state; export refuses to omit it")
|
|
required = sum((engine.STATE / name).stat().st_size for name in FILES)
|
|
if (
|
|
required > MAX_BYTES
|
|
or shutil.disk_usage(destination.parent).free < required * 2 + 256 * 1024**2
|
|
):
|
|
raise ValueError("insufficient archive space or state exceeds portable limit")
|
|
fence = engine.ROOT / "migration-fence.json"
|
|
record = {
|
|
"schema": SCHEMA,
|
|
"migration_id": uuid.uuid4().hex,
|
|
"created_at": time.time(),
|
|
"monotonic": time.monotonic(),
|
|
"artifact": proposal["artifact"],
|
|
"status": "quiescing",
|
|
}
|
|
# Persistent unit condition blocks manual/automatic starts and host reboots.
|
|
# Failure after this point stays fenced; the operator can explicitly resume.
|
|
durable_json(fence, record)
|
|
engine.run("systemctl", "stop", SERVICE)
|
|
active = subprocess.run(["systemctl", "is-active", SERVICE], capture_output=True).stdout.strip()
|
|
if active not in (b"inactive", b"failed"):
|
|
raise ValueError("source did not stop; migration remains fenced")
|
|
with tempfile.TemporaryDirectory(prefix=".ndc-vps-export-", dir=destination.parent) as work:
|
|
work = Path(work)
|
|
state = work / "state"
|
|
state.mkdir(mode=0o700)
|
|
for name in FILES - {"journal.sqlite3"}:
|
|
shutil.copyfile(engine.STATE / name, state / name)
|
|
(state / name).chmod(0o600)
|
|
with (
|
|
sqlite3.connect(
|
|
(engine.STATE / "journal.sqlite3").as_uri() + "?mode=ro", uri=True
|
|
) as src,
|
|
sqlite3.connect(state / "journal.sqlite3") as dst,
|
|
):
|
|
src.backup(dst)
|
|
(state / "journal.sqlite3").chmod(0o600)
|
|
check_state(state)
|
|
record.update(
|
|
status="source_fenced",
|
|
files={
|
|
"state/" + name: {
|
|
"sha256": sha(state / name),
|
|
"size": (state / name).stat().st_size,
|
|
}
|
|
for name in sorted(FILES)
|
|
},
|
|
)
|
|
durable_json(work / "manifest.json", record)
|
|
archive = work / "state.tar.gz"
|
|
with tarfile.open(archive, "w:gz", format=tarfile.USTAR_FORMAT) as tar:
|
|
for name in ["manifest.json", *record["files"]]:
|
|
info = tar.gettarinfo(work / name, arcname=name)
|
|
info.mode = 0o600
|
|
info.mtime = int(info.mtime)
|
|
info.uid = info.gid = 0
|
|
info.uname = info.gname = ""
|
|
with (work / name).open("rb") as stream:
|
|
tar.addfile(info, stream)
|
|
archive.chmod(0o600)
|
|
with archive.open("rb") as stream:
|
|
os.fsync(stream.fileno())
|
|
# Atomic publication without ever overwriting an existing backup.
|
|
os.link(archive, destination)
|
|
sync_directory(destination.parent)
|
|
digest = sha(destination)
|
|
durable_json(fence, {**record, "archive_sha256": digest})
|
|
print(
|
|
json.dumps(
|
|
{
|
|
"status": "source_fenced",
|
|
"archive": str(destination),
|
|
"sha256": digest,
|
|
"migration_id": record["migration_id"],
|
|
}
|
|
)
|
|
)
|
|
|
|
|
|
def unpack(archive, expected, directory, artifact):
|
|
if not re.fullmatch(r"[a-f0-9]{64}", expected) or archive.is_symlink() or not archive.is_file():
|
|
raise ValueError("regular archive and exact SHA-256 required")
|
|
if archive.stat().st_size > MAX_BYTES or sha(archive) != expected:
|
|
raise ValueError("archive digest or size mismatch")
|
|
expected_names = {"manifest.json"} | {"state/" + name for name in FILES}
|
|
seen, total = set(), 0
|
|
# Never extract paths/links/modes supplied by an archive or deserialize code.
|
|
with tarfile.open(archive, "r:gz") as tar:
|
|
for member in tar:
|
|
if (
|
|
member.name not in expected_names
|
|
or member.name in seen
|
|
or not member.isfile()
|
|
or member.pax_headers
|
|
):
|
|
raise ValueError("invalid portable archive member")
|
|
total += member.size
|
|
limit = MAX_BYTES if member.name == "state/journal.sqlite3" else 1024 * 1024
|
|
if member.size > limit or total > MAX_BYTES:
|
|
raise ValueError("portable archive size limit")
|
|
seen.add(member.name)
|
|
target = directory / member.name
|
|
target.parent.mkdir(mode=0o700, exist_ok=True)
|
|
with target.open("xb") as stream, tar.extractfile(member) as source:
|
|
target.chmod(0o600)
|
|
shutil.copyfileobj(source, stream, 1024 * 1024)
|
|
if seen != expected_names:
|
|
raise ValueError("incomplete portable archive")
|
|
record = json.loads((directory / "manifest.json").read_text())
|
|
if (
|
|
record.get("schema") != SCHEMA
|
|
or record.get("status") != "source_fenced"
|
|
or record.get("artifact") != artifact
|
|
or set(record.get("files", {})) != expected_names - {"manifest.json"}
|
|
):
|
|
raise ValueError("archive requires its exact installer release and complete manifest")
|
|
for name, item in record["files"].items():
|
|
if item != {"sha256": sha(directory / name), "size": (directory / name).stat().st_size}:
|
|
raise ValueError("state integrity mismatch")
|
|
return record, check_state(directory / "state")
|
|
|
|
|
|
def import_state(engine, archive, expected):
|
|
if os.geteuid() != 0:
|
|
raise ValueError("root required")
|
|
for path in (engine.ROOT, engine.STATE, engine.UNIT):
|
|
if path.exists() or path.is_symlink():
|
|
raise ValueError("portable import requires an empty product installation")
|
|
if shutil.disk_usage(engine.STATE.parent).free < MAX_BYTES + 256 * 1024**2:
|
|
raise ValueError("portable import requires 2.25 GiB free staging space")
|
|
with tempfile.TemporaryDirectory(prefix=".ndc-vps-import-", dir=engine.STATE.parent) as work:
|
|
work = Path(work)
|
|
record, config = unpack(archive, expected, work, engine.digest())
|
|
args = options(config)
|
|
proposal = engine.plan(args) # OS, prerequisites, ports and firewall, before mutation.
|
|
args.expect = proposal["plan_sha256"]
|
|
# Install this shipped code and unit, creating the target's system account.
|
|
# Only identity/journal state crosses hosts; no old executable/unit/firewall does.
|
|
staged_state = work / "state"
|
|
staged_state.chmod(0o700)
|
|
for path in staged_state.iterdir():
|
|
with path.open("rb") as stream:
|
|
os.fsync(stream.fileno())
|
|
sync_directory(staged_state)
|
|
# Same-filesystem rename publishes all state at once. A failed copy
|
|
# must not leave a partial identity or require twice the journal space.
|
|
os.rename(staged_state, engine.STATE)
|
|
sync_directory(engine.STATE.parent)
|
|
engine.apply(args, proposal)
|
|
durable_json(
|
|
engine.ROOT / "imported-state.json",
|
|
{
|
|
"schema": SCHEMA,
|
|
"migration_id": record["migration_id"],
|
|
"archive_sha256": expected,
|
|
"imported_at": time.time(),
|
|
"endpoint_preserved": True,
|
|
},
|
|
)
|
|
print(
|
|
json.dumps(
|
|
{
|
|
"status": "imported",
|
|
"identity_preserved": True,
|
|
"migration_id": record["migration_id"],
|
|
"endpoint_preserved": True,
|
|
}
|
|
)
|
|
)
|
|
|
|
|
|
def resume_source(engine):
|
|
if os.geteuid() != 0:
|
|
raise ValueError("root required")
|
|
fence = engine.ROOT / "migration-fence.json"
|
|
record = json.loads(fence.read_text())
|
|
if record.get("schema") != SCHEMA or record.get("artifact") != engine.digest():
|
|
raise ValueError("source fence requires the same installer")
|
|
fence.unlink()
|
|
sync_directory(fence.parent)
|
|
try:
|
|
engine.run("systemctl", "start", SERVICE)
|
|
engine.healthy()
|
|
except Exception:
|
|
durable_json(fence, record)
|
|
engine.run("systemctl", "stop", SERVICE)
|
|
raise
|
|
durable_json(
|
|
engine.ROOT / "migration-cancelled.json",
|
|
{"migration_id": record["migration_id"], "resumed_at": time.time()},
|
|
)
|
|
print(json.dumps({"status": "source_resumed", "migration_id": record["migration_id"]}))
|