#!/usr/bin/env python3 """Root-side, journaled relocation of the default K3s directory to a data disk.""" import argparse import hashlib import json import os from pathlib import Path import re import shutil import ssl import stat import subprocess import tempfile import time SOURCE = Path("/var/lib/rancher/k3s") UNIT = Path("/etc/systemd/system/var-lib-rancher-k3s.mount") DROPIN = Path("/etc/systemd/system/k3s.service.d/30-jeannie-runtime-storage.conf") EXPECTED = globals().get("EXPECTED", {}) STOP_SCRIPT = globals().get("STOP_SCRIPT", "") EXCLUDES = ["--exclude=/server/kine.sock"] def run(command, **kwargs): return subprocess.run(command, check=True, text=True, capture_output=True, timeout=kwargs.pop("timeout", 1800), **kwargs).stdout.strip() def save(path, value): temporary = path.with_suffix(path.suffix + ".tmp") temporary.write_text(json.dumps(value, indent=2) + "\n") temporary.chmod(0o600) os.replace(temporary, path) def validate_paths(target, mount): for path in (target, mount): if not re.fullmatch(r"/[A-Za-z0-9_./-]+", str(path)) or ".." in path.parts: raise RuntimeError("Runtime storage paths must be explicit safe absolute paths") if target == mount or not target.is_relative_to(mount) or target.is_relative_to(SOURCE) or SOURCE.is_relative_to(target): raise RuntimeError("SSD runtime directory must be below the data mount and separate from the default K3s directory") def mount_info(mount): filesystems = json.loads(run(["findmnt", "-J", "-T", str(mount), "-o", "TARGET,SOURCE,UUID,OPTIONS"]))["filesystems"] if len(filesystems) != 1 or filesystems[0]["target"] != str(mount) or "rw" not in filesystems[0]["options"].split(","): raise RuntimeError("The declared writable SSD mount is absent; root-filesystem fallback refused") return filesystems[0] def same_directory(left, right): if not left.is_dir() or not right.is_dir(): return False a, b = left.stat(), right.stat() return (a.st_dev, a.st_ino) == (b.st_dev, b.st_ino) def verify_copy(source, destination): differences = run(["rsync", "-aHAXnc", "--numeric-ids", "--one-file-system", "--delete", "--itemize-changes", *EXCLUDES, str(source) + "/", str(destination) + "/"], timeout=7200) if differences: raise RuntimeError("Offline runtime copy verification failed; original and staged copies retained") def copy_tree(source, destination): destination.mkdir(parents=True, exist_ok=True, mode=0o700) run(["rsync", "-aHAX", "--numeric-ids", "--one-file-system", "--delete", *EXCLUDES, str(source) + "/", str(destination) + "/"], timeout=7200) verify_copy(source, destination) def cold_digest(root): digest = hashlib.sha256() for path in sorted(root.rglob("*")): info = path.lstat() digest.update(json.dumps([str(path.relative_to(root)), info.st_mode, info.st_uid, info.st_gid, info.st_size, info.st_mtime_ns]).encode()) if stat.S_ISREG(info.st_mode): with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) elif path.is_symlink(): digest.update(os.readlink(path).encode()) return digest.hexdigest() def check_ca(paths): if not EXPECTED.get("ca_sha256"): raise RuntimeError("Existing-runtime migration requires the pinned cluster identity") found = False for path in paths: certificate = path / "server/tls/server-ca.crt" if certificate.exists(): certificates = re.findall(r"-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----", certificate.read_text(), re.S) if len(certificates) != 1 or hashlib.sha256(ssl.PEM_cert_to_DER_cert(certificates[0])).hexdigest() != EXPECTED["ca_sha256"]: raise RuntimeError("Runtime directory contains a different cluster CA; refusing relocation") found = True if not found: raise RuntimeError("No preserved server CA found for the enrolled cluster") def unit_contents(target, mount): unit = ("[Unit]\nDescription=Jeannie K3s runtime on declared data disk\n" f"RequiresMountsFor={mount}\nConditionPathIsMountPoint={mount}\nBefore=k3s.service\n\n[Mount]\nWhat={target}\n" f"Where={SOURCE}\nType=none\nOptions=bind\n\n[Install]\nWantedBy=multi-user.target\n") dropin = (f"[Unit]\nRequiresMountsFor={mount} {SOURCE}\n" f"ConditionPathIsMountPoint={mount}\nConditionPathIsMountPoint={SOURCE}\n") return unit, dropin def check_owned_units(target, mount): for path, content in zip((UNIT, DROPIN), unit_contents(target, mount)): if path.is_symlink() or path.exists() and path.read_text() != content: raise RuntimeError(f"Existing unmanaged unit configuration at {path}; refusing to replace it") def activate_mount(target, mount): mount_info(mount) check_owned_units(target, mount) for path, content in zip((UNIT, DROPIN), unit_contents(target, mount)): path.parent.mkdir(parents=True, exist_ok=True) path.write_text(content) path.chmod(0o644) SOURCE.mkdir(parents=True, exist_ok=True) run(["systemctl", "daemon-reload"]) run(["systemctl", "enable", "--now", UNIT.name], timeout=120) if not same_directory(SOURCE, target): raise RuntimeError("K3s runtime bind mount does not match the verified SSD directory") def snapshot_hidden_registry(destination): view = Path(tempfile.mkdtemp(prefix="jeannie-root-view-", dir="/run")) mounted = False try: # Nonrecursive bind exposes eMMC's /data beneath the SSD mount. Keep # this view private and read-only; never unmount or modify live /data. run(["mount", "--bind", "/", str(view)]) mounted = True run(["mount", "--make-private", str(view)]) run(["mount", "-o", "remount,bind,ro", str(view)]) hidden = view / "data/openebs/local/registry" if hidden.is_dir() and not hidden.is_symlink(): print("Preserving registry data hidden beneath the SSD mount...", flush=True) copy_tree(hidden, destination) return str(destination) return None finally: if mounted: run(["umount", str(view)], timeout=60) view.rmdir() def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("action", choices=("inspect", "prepare-fresh", "move", "finalize")) parser.add_argument("target", type=Path) parser.add_argument("mount", type=Path) args = parser.parse_args() if os.geteuid() != 0: raise RuntimeError("Root-side storage checks require sudo") target, mount = args.target, args.mount validate_paths(target, mount) filesystem = mount_info(mount) for path in (SOURCE, target, *target.parents): if path.is_symlink(): raise RuntimeError("Runtime storage paths must not traverse symlinks") on_ssd = same_directory(SOURCE, target) and os.path.ismount(SOURCE) if args.action == "inspect": print(json.dumps({"source": str(SOURCE), "destination": str(target), "mounted": on_ssd, "filesystem": filesystem["source"], "uuid": filesystem.get("uuid")})) return check_owned_units(target, mount) if args.action == "prepare-fresh": if on_ssd: activate_mount(target, mount) return if os.path.ismount(SOURCE) or SOURCE.exists() and any(SOURCE.iterdir()) or target.exists() and any(target.iterdir()): raise RuntimeError("Existing K3s data requires the reviewed k3s-runtime-to-ssd transition; no fresh directory created") target.mkdir(parents=True, mode=0o700, exist_ok=True) activate_mount(target, mount) return if not shutil.which("rsync"): raise RuntimeError("Install rsync on the runtime host before moving storage") journal_path = target.parent / (target.name + ".migration.json") journal = json.loads(journal_path.read_text()) if journal_path.exists() else None if journal and (journal["target"] != str(target) or journal["identity"] != EXPECTED or journal["uuid"] != filesystem.get("uuid")): raise RuntimeError("Storage migration journal belongs to a different directory, disk or identity") if journal and journal.get("phase") not in ("planned", "copied", "mounted", "active", "reclaiming", "complete"): raise RuntimeError("Unknown runtime storage migration phase") if journal is None: if on_ssd: activate_mount(target, mount) print("Runtime is already on its declared SSD directory; no data moved.", flush=True) return if args.action == "finalize" or os.path.ismount(SOURCE) or target.exists(): raise RuntimeError("Unrecorded runtime data/mount exists; refusing an automatic merge") check_ca([SOURCE]) pid = int(run(["systemctl", "show", "k3s", "-p", "MainPID", "--value"])) if pid < 1 or not same_directory(SOURCE, Path(f"/proc/{pid}/root") / str(SOURCE).lstrip("/")): raise RuntimeError("Cannot establish that the running K3s process uses this host runtime directory") size = int(run(["du", "-sx", "--block-size=1", str(SOURCE)]).split()[0]) if shutil.disk_usage(mount).free < 3 * size + 1024 ** 3: raise RuntimeError("SSD must have room for verified runtime, rollback and possible hidden registry copies") target.parent.mkdir(parents=True, exist_ok=True, mode=0o700) stamp = str(time.time_ns()) journal = {"identity": EXPECTED, "target": str(target), "uuid": filesystem.get("uuid"), "old": str(SOURCE) + ".before-ssd-" + stamp, "stage": str(target) + ".stage-" + stamp, "backup": str(target) + ".before-move-" + stamp, "registry_backup": str(target.parent / ("registry-underlay-" + stamp)), "phase": "planned"} save(journal_path, journal) old, stage, backup = (Path(journal[name]) for name in ("old", "stage", "backup")) if journal["phase"] == "planned": check_ca([SOURCE]) if not STOP_SCRIPT: raise RuntimeError("Runtime stop script was not supplied; no service stopped") print("Stopping only K3s and its private runtime before the verified copy...", flush=True) subprocess.run(["bash"], input=STOP_SCRIPT, text=True, check=True, timeout=1800) nested = [path for path in run(["findmnt", "-rn", "-o", "TARGET"]).splitlines() if path.startswith(str(SOURCE) + "/")] if nested: raise RuntimeError("Nested runtime mounts remain; refusing an inconsistent offline copy") journal["hidden_registry"] = snapshot_hidden_registry(Path(journal["registry_backup"])) print("Copying K3s datastore, credentials and image cache to SSD...", flush=True) copy_tree(SOURCE, stage) print("Preserving a second verified cold runtime copy on SSD...", flush=True) copy_tree(stage, backup) journal["phase"] = "copied" save(journal_path, journal) if journal["phase"] == "copied": check_ca([SOURCE, stage, old, target, backup]) if not target.exists(): os.rename(stage, target) if not old.exists(): verify_copy(SOURCE, backup) os.rename(SOURCE, old) elif SOURCE.exists() and any(SOURCE.iterdir()) and not same_directory(SOURCE, target): raise RuntimeError("Default runtime directory unexpectedly contains new data; original copies retained") activate_mount(target, mount) journal["phase"] = "mounted" save(journal_path, journal) if journal["phase"] == "mounted": check_ca([SOURCE, target, backup, old]) if not same_directory(SOURCE, target): activate_mount(target, mount) run(["systemctl", "start", "k3s"], timeout=180) journal["phase"] = "active" save(journal_path, journal) if args.action == "finalize" and journal["phase"] in ("active", "reclaiming"): uid = run(["k3s", "kubectl", "--request-timeout=15s", "get", "namespace", "kube-system", "-o", "jsonpath={.metadata.uid}"]) check_ca([SOURCE, backup, old]) if uid != EXPECTED["kube_system_uid"] or not same_directory(SOURCE, target): raise RuntimeError("Live cluster identity or SSD mount differs; eMMC rollback copy retained") if old.exists(): if journal["phase"] == "active": verify_copy(old, backup) journal["rollback_digest"] = cold_digest(backup) journal["phase"] = "reclaiming" save(journal_path, journal) if cold_digest(backup) != journal["rollback_digest"]: raise RuntimeError("Cold rollback copy changed; refusing eMMC cleanup") mounts = run(["findmnt", "-rn", "-o", "TARGET"]).splitlines() if old.is_symlink() or any(p == str(old) or p.startswith(str(old) + "/") for p in mounts) or not old.name.startswith("k3s.before-ssd-") or old.parent != SOURCE.parent: raise RuntimeError("Invalid eMMC duplicate path; refusing cleanup") print("Verified live identity and SSD rollback copy; reclaiming only the eMMC duplicate...", flush=True) shutil.rmtree(old) journal["phase"] = "complete" save(journal_path, journal) print(f"Runtime storage phase={journal['phase']}; cold rollback copy={backup}; hidden registry={journal.get('hidden_registry')}", flush=True) if __name__ == "__main__": try: main() except (RuntimeError, OSError, ValueError, KeyError, subprocess.SubprocessError) as error: raise SystemExit(f"Runtime storage stopped: {error}. Keep the journal and preserved copies; do not initialize a new cluster.")