#!/usr/bin/env python3 """Retire only the obsolete operator fleet monitoring replica after live-mode acceptance.""" from __future__ import annotations import argparse import hashlib import json import os import shutil import sqlite3 import stat import subprocess import time import urllib.parse import urllib.request import uuid from contextlib import closing from pathlib import Path FILES = ("monitor.sqlite3-shm", "monitor.sqlite3-wal", "monitor.sqlite3") TABLES = { "samples": ["node", "source", "seq", "at", "body"], "minutes": ["node", "at", "body"], "events": ["node", "source", "seq", "at", "body"], "states": ["node", "source", "body", "received", "ack"], } def canonical(value): return json.dumps(value, sort_keys=True, separators=(",", ":")).encode() def stamp(s): return [s.st_dev, s.st_ino, s.st_size, s.st_mtime_ns, s.st_ctime_ns, s.st_nlink] def directory(root, relative): path = root for component in Path(relative).parts: path /= component if not stat.S_ISDIR(path.lstat().st_mode): raise ValueError("Monitor directory contains a link or special file") return path def identity(path): metadata = path.lstat() if not stat.S_ISREG(metadata.st_mode): raise ValueError("Monitor file is not a regular file") fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW) with os.fdopen(fd, "rb") as stream: if stamp(os.fstat(stream.fileno())) != stamp(metadata): raise ValueError("Monitor file changed while opening") digest = hashlib.file_digest(stream, "sha256").hexdigest() if stamp(os.fstat(stream.fileno())) != stamp(metadata): raise ValueError("Monitor file changed during verification") if stamp(path.lstat()) != stamp(metadata): raise ValueError("Monitor path changed during verification") return dict(name=path.name, sha256=digest, bytes=metadata.st_size, stamp=stamp(metadata)) def plan(root): root = Path(root).absolute() if root.is_symlink() or root != root.resolve(strict=True): raise ValueError("Use the canonical repository path") fleet = directory(root, ".runtime/mission-core/fleet") paths = [ fleet / name for name in FILES if (fleet / name).exists() or (fleet / name).is_symlink() ] main = fleet / "monitor.sqlite3" if paths and main not in paths: raise ValueError("Unexplained orphan monitoring sidecars") files = [identity(path) for path in paths] if files: # Immutable read checks the established schema without opening a writer, # checkpointing WAL, or creating sidecars. No raw samples are exported. uri = main.as_uri() + "?mode=ro&immutable=1" with closing(sqlite3.connect(uri, uri=True)) as database: tables = { row[0] for row in database.execute("SELECT name FROM sqlite_master WHERE type='table'") } if tables != set(TABLES): raise ValueError("Database contains unexpected tables") for table, expected in TABLES.items(): if [row[1] for row in database.execute(f"PRAGMA table_info({table})")] != expected: raise ValueError("Unexpected monitor table layout") if any(stamp((fleet / row["name"]).lstat()) != row["stamp"] for row in files): raise ValueError("Monitoring files changed during schema verification") result = dict( schema="missioncore.monitor-replica-retirement-plan/v1", root=str(root), files=files, logical_bytes_upper_bound=sum(row["bytes"] for row in files), ) result["plan_id"] = hashlib.sha256(canonical(result)).hexdigest() return result def live_acceptance(): def read(path): with urllib.request.urlopen("http://127.0.0.1:8000" + path, timeout=5) as response: data = response.read(2 * 1024**2 + 1) if len(data) > 2 * 1024**2: raise ValueError("Acceptance response budget") return json.loads(data) health = read("/api/health") if not health.get("readiness", {}).get("operational"): raise ValueError("Canonical Core is not operational") vehicles = read("/api/v1/fleet")["items"] if not vehicles: raise ValueError("No existing vehicle to verify live monitor contract") for vehicle in vehicles: value = read("/api/v1/fleet/" + urllib.parse.quote(vehicle["id"], safe="") + "/monitor") if value.get("mode") != "live" or value.get("history_available") is not False: raise ValueError("The running Core still exposes the archive contract") return {"core_operational": True, "mode": "live", "verified_vehicles": len(vehicles)} def assert_closed(paths): if not paths: return result = subprocess.run( ["lsof", "-t", *map(str, paths)], capture_output=True, text=True, timeout=10 ) if result.stdout.strip() or result.returncode not in (0, 1) or result.stderr.strip(): raise ValueError("Monitoring files may still be open; retirement refused") def save(path, receipt): temporary = path.with_suffix(".tmp") with temporary.open("xb") as stream: os.chmod(temporary, 0o600) stream.write(canonical(receipt) + b"\n") stream.flush() os.fsync(stream.fileno()) os.replace(temporary, path) def apply(expected, *, probe=live_acceptance, closed=assert_closed): proof = probe() current = plan(expected["root"]) if current != expected: raise ValueError("Stale or changed monitor retirement plan") root = Path(current["root"]) fleet = directory(root, ".runtime/mission-core/fleet") closed([fleet / row["name"] for row in current["files"]]) # The receipt is owned maintenance evidence, separate from operator telemetry. parent = directory(root, ".runtime") for name in ("storage-maintenance", "monitor-retirement"): parent /= name parent.mkdir(mode=0o700, exist_ok=True) if not stat.S_ISDIR(parent.lstat().st_mode): raise ValueError("Unsafe receipt directory") path = parent / (uuid.uuid4().hex + ".json") receipt = dict( schema="missioncore.monitor-replica-retirement-receipt/v1", plan=current, proof=proof, status="applying", removed=[], started_ns=time.time_ns(), free_before=shutil.disk_usage(root).free, ) save(path, receipt) try: # Sidecars go first, main last. A partial operation can be replanned # against the remaining known schema; unrelated fleet files are untouched. for row in current["files"]: candidate = fleet / row["name"] closed([candidate]) if identity(candidate) != row: raise ValueError("Monitor file changed before unlink") receipt["next"] = row["name"] save(path, receipt) candidate.unlink() receipt["removed"].append(row) save(path, receipt) receipt["status"] = "complete" except BaseException as error: receipt.update(status="interrupted", error=str(error)) raise finally: receipt.update(finished_ns=time.time_ns(), free_after=shutil.disk_usage(root).free) save(path, receipt) return dict(receipt, receipt=str(path)) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("action", choices=("plan", "apply")) parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1]) parser.add_argument("--plan", type=Path) args = parser.parse_args() if args.action == "plan": result = plan(args.root) else: if args.plan is None: parser.error("apply requires --plan") result = apply(json.loads(args.plan.read_text())) print(json.dumps(result, indent=2)) if __name__ == "__main__": main()