From 23932cd7e159ac258fcdfffb899d03a7afae109c Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Tue, 3 Nov 2026 07:42:56 -0600 Subject: [PATCH] Require declared data mounts and preserve registry volume identity across remounts --- bootstrap/apps/README.md | 14 +++++ docs/app-ops.md | 7 +++ docs/templates/app-ops.md.tmpl | 7 +++ homelab.yml | 2 + lib/jeannie/env.sh | 1 + lib/jeannie/pipeline.sh | 1 + scripts/cluster-runtime-guard.py | 9 ++++ scripts/cluster-transition.py | 3 ++ scripts/registry-storage-reconcile.py | 55 +++++++++++++++++++- tests/jeannie/test_registry_storage_mount.py | 38 ++++++++++++++ 10 files changed, 136 insertions(+), 1 deletion(-) create mode 100644 tests/jeannie/test_registry_storage_mount.py diff --git a/bootstrap/apps/README.md b/bootstrap/apps/README.md index 9a2df3f..4588bc8 100644 --- a/bootstrap/apps/README.md +++ b/bootstrap/apps/README.md @@ -112,6 +112,20 @@ boot a source VM while host K3s is active. The transition below prepares the rem registry offline. Apps accepts it only when the receipt's host, node and path match the live cluster; before the PV exists it also verifies the complete file manifest. +The native profile declares `storage.required_mount: /data`. Runtime/start guards, +offline publication and remote registry reconciliation require that exact +writable mount; an empty `/data` directory on eMMC is not a valid fallback. +Profiles without a declared separate mount retain their existing storage model. +The registry check compares host and running-pod filesystem/inode identities, +refusing a stale volume binding after an unmount/remount. It never recreates +missing data or restarts that pod to conceal the mismatch. + +After these checks pass, Jeannie installs its own K3s systemd drop-in with +`RequiresMountsFor` and `ConditionPathIsMountPoint`, preserving other overrides. +It reloads unit metadata without restarting the live service. Future service +starts require the data mount; existing `/etc/fstab` device selection is not +rewritten. Missing, read-only or mismatched storage remains a blocking error. + ## Retire the accidental laptop K3s installation On the Debian deployment laptop, after pulling the updated repository: diff --git a/docs/app-ops.md b/docs/app-ops.md index 096941e..241cd29 100644 --- a/docs/app-ops.md +++ b/docs/app-ops.md @@ -96,6 +96,13 @@ retired before installing the selected route. Other laptop PVC contents are preserved locally and are not automatically restored into the new cluster. See [registry migration](../bootstrap/apps/README.md). +The native profile requires `/data` to be its declared writable mount, not a +directory on the eMMC root filesystem. After remounting a data disk, the pipeline +compares the host registry directory with the running pod's mounted directory +by filesystem and inode. A mismatch blocks changes so mounted data can be +preserved before any restart. Successful checks install a K3s mount dependency +for future service starts without restarting the live cluster. + ## Gitea Gitea is external bootstrap infrastructure. It runs on the Debian host as an diff --git a/docs/templates/app-ops.md.tmpl b/docs/templates/app-ops.md.tmpl index f6c58d8..89fce27 100644 --- a/docs/templates/app-ops.md.tmpl +++ b/docs/templates/app-ops.md.tmpl @@ -96,6 +96,13 @@ retired before installing the selected route. Other laptop PVC contents are preserved locally and are not automatically restored into the new cluster. See [registry migration](../bootstrap/apps/README.md). +The native profile requires `/data` to be its declared writable mount, not a +directory on the eMMC root filesystem. After remounting a data disk, the pipeline +compares the host registry directory with the running pod's mounted directory +by filesystem and inode. A mismatch blocks changes so mounted data can be +preserved before any restart. Successful checks install a K3s mount dependency +for future service starts without restarting the live cluster. + ## Gitea Gitea is external bootstrap infrastructure. It runs on the Debian host as an diff --git a/homelab.yml b/homelab.yml index bef353d..d7295cf 100644 --- a/homelab.yml +++ b/homelab.yml @@ -111,6 +111,8 @@ cluster: calico_operator_node_name: opi5plus runtime: k3s allow_hypervisor_host: true + storage: + required_mount: /data hosts: debian: diff --git a/lib/jeannie/env.sh b/lib/jeannie/env.sh index 4f3850f..1755f45 100644 --- a/lib/jeannie/env.sh +++ b/lib/jeannie/env.sh @@ -154,6 +154,7 @@ profile_mapping = { "platform.calico_operator_node_name": ("LAB_CALICO_OPERATOR_NODE_NAME", None), "runtime": ("LAB_CLUSTER_RUNTIME", "cluster.runtime"), "allow_hypervisor_host": ("LAB_K3S_ALLOW_HYPERVISOR_HOST", None), + "storage.required_mount": ("LAB_CLUSTER_REQUIRED_DATA_MOUNT", None), "pimox.host": ("LAB_CLUSTER_PIMOX_HOST", "hosts.opi5_pimox.lan_ip"), "pimox.user": ("LAB_CLUSTER_PIMOX_USER", "hosts.opi5_pimox.user"), "pimox.bridge": ("LAB_CLUSTER_PIMOX_BRIDGE", "hosts.opi5_pimox.bridge"), diff --git a/lib/jeannie/pipeline.sh b/lib/jeannie/pipeline.sh index 501d0bd..7d1f8a6 100644 --- a/lib/jeannie/pipeline.sh +++ b/lib/jeannie/pipeline.sh @@ -7328,6 +7328,7 @@ reconcile_app_registry_storage() { --destination-host "${LAB_CLUSTER_CONTROL_PLANE_LAN_IP}" \ --destination-user "${LAB_CLUSTER_CONTROL_PLANE_USER}" \ --destination-key "${LAB_CLUSTER_CONTROL_PLANE_SSH_KEY_PATH}" \ + --required-data-mount "${LAB_CLUSTER_REQUIRED_DATA_MOUNT:-}" \ --destination-path "${LAB_REGISTRY_STORAGE_PATH:-/data/openebs/local/registry}" \ --source-host "${source_host}" --source-user "${source_user}" --source-key "${source_key}" \ --source-node "${source_node}" --source-path "${LAB_PIMOX_REGISTRY_STORAGE_PATH:-/data/openebs/local/registry}" \ diff --git a/scripts/cluster-runtime-guard.py b/scripts/cluster-runtime-guard.py index 1fda6c6..71e6f7c 100644 --- a/scripts/cluster-runtime-guard.py +++ b/scripts/cluster-runtime-guard.py @@ -3,6 +3,7 @@ import argparse import fcntl +import importlib.util import json import os from pathlib import Path @@ -60,6 +61,14 @@ def check(profile=None, vm_start=False): for variable in ("LAB_CLUSTER_RUNTIME", "TF_VAR_cluster_runtime"): if os.environ.get(variable, runtime) != runtime: raise RuntimeError(f"{variable} conflicts with profile {selected}; expected {runtime}") + required_mount = profiles[selected].get("storage", {}).get("required_mount", "") + if required_mount: + control = profiles[selected]["control_plane"] + spec = importlib.util.spec_from_file_location("registry_storage_guard", REPO / "scripts/registry-storage-reconcile.py") + storage = importlib.util.module_from_spec(spec) + spec.loader.exec_module(storage) + storage.require_remote_data_mount( + lambda command: remote(control["lan_ip"], control["user"], control["ssh_key_path"], command), required_mount) laptop = inventory["hosts"]["debian"] hypervisor = inventory["hosts"]["opi5_pimox"] laptop_key = profiles["debian"]["control_plane"]["ssh_key_path"] diff --git a/scripts/cluster-transition.py b/scripts/cluster-transition.py index 5175cad..aaa17bc 100644 --- a/scripts/cluster-transition.py +++ b/scripts/cluster-transition.py @@ -58,6 +58,8 @@ def main(): registry = module("registry_transition", "registry-storage-reconcile.py") context = module("context_transition", "cluster-context.py") remote = lambda command, **kw: registry.run(registry.ssh(control["lan_ip"], control["user"], control["ssh_key_path"], command), **kw) + required_mount = profiles["k3s"].get("storage", {}).get("required_mount", "") + registry.require_remote_data_mount(remote, required_mount) architecture = remote("uname -m") if architecture not in ("aarch64", "arm64"): raise RuntimeError("Native target is not ARM64; refusing to deploy on another laptop") @@ -162,6 +164,7 @@ def main(): source_path="/data/openebs/local/registry", hypervisor_host=control["lan_ip"], hypervisor_user=control["user"], hypervisor_key=control["ssh_key_path"], transfer_cipher="aes256-gcm@openssh.com", registry_endpoint=profiles["k3s"]["registry"]["endpoint"]) + options.required_data_mount = required_mount registry.require_no_local_writer("/data/openebs/local/registry") registry.prepare_local(options, "/data/openebs/local/registry", False) root.mkdir(parents=True, exist_ok=True, mode=0o700) diff --git a/scripts/registry-storage-reconcile.py b/scripts/registry-storage-reconcile.py index e834715..41aac2e 100644 --- a/scripts/registry-storage-reconcile.py +++ b/scripts/registry-storage-reconcile.py @@ -57,6 +57,7 @@ def main(): parser.add_argument("--destination-host") parser.add_argument("--destination-user") parser.add_argument("--destination-key") + parser.add_argument("--required-data-mount", default="") parser.add_argument("--registry-endpoint", required=True) parser.add_argument("--transfer-cipher", default=os.environ.get("LAB_REGISTRY_TRANSFER_CIPHER", "aes256-gcm@openssh.com"), choices=("aes256-gcm@openssh.com", "aes128-gcm@openssh.com", "chacha20-poly1305@openssh.com")) @@ -101,9 +102,27 @@ def main(): a["type"] == "InternalIP" and a["address"] == args.destination_host for a in selected["status"]["addresses"]): raise RuntimeError("Remote registry target does not match the live destination node") remote = lambda command: run(ssh(args.destination_host, args.destination_user, args.destination_key, command), timeout=1800) - remote("sudo -n test -d " + shlex.quote(path)) + require_remote_data_mount(remote, args.required_data_mount) + present = remote("set -eu; sudo -n true; if sudo -n test -d " + shlex.quote(path) + + "; then echo present; else echo missing; fi") + if present != "present": + raise RuntimeError(f"Retained registry directory {path} is absent on the mounted host; " + "do not restart a running registry or create an empty replacement before recovering its data") + host_directory = remote("sudo -n stat -c %d:%i " + shlex.quote(path)) + pods = json.loads(run(kubectl + ["-n", "container-registry", "get", "pods", "-l", "app=local-registry", "-o", "json"])) + for pod in pods.get("items") or []: + if not any(status.get("name") == "registry" and status.get("state", {}).get("running") + for status in pod.get("status", {}).get("containerStatuses") or []): + continue + pod_directory = run(kubectl + ["-n", "container-registry", "exec", pod["metadata"]["name"], + "-c", "registry", "--", "stat", "-c", "%d:%i", "/var/lib/registry"]) + if pod_directory != host_directory: + raise RuntimeError("Running registry volume does not match the host directory's filesystem/inode; " + "preserve its mounted data before any pod restart or storage change") if not raw_pv and hashlib.sha256(remote_manifest(remote, path).encode()).hexdigest() != receipt["manifest_sha256"]: raise RuntimeError("Preseeded remote registry changed before its PV was created") + if os.environ.get("LAB_CLUSTER_RUNTIME") == "k3s": + ensure_k3s_data_mount_dependency(remote, args.required_data_mount) print(f"Preserving verified remote registry storage on {target}:{path}", flush=True) else: prepare_local(args, path, bool(raw_pv)) @@ -143,9 +162,42 @@ def remote_manifest(remote, path): return remote("sudo -n bash -o pipefail -c " + shlex.quote(command)) +def require_remote_data_mount(remote, mount): + if not mount: + return + if not re.fullmatch(r"/[A-Za-z0-9_./-]+", mount) or ".." in Path(mount).parts: + raise RuntimeError("Required data mount must be a specific absolute path without whitespace") + mounts = json.loads(remote("findmnt -J -T " + shlex.quote(mount) + " -o TARGET,SOURCE,OPTIONS")) + filesystems = mounts.get("filesystems") or [] + if len(filesystems) != 1 or filesystems[0].get("target") != mount: + raise RuntimeError(f"Required data filesystem is not mounted at {mount}; refusing root-filesystem fallback") + if "rw" not in str(filesystems[0].get("options", "")).split(","): + raise RuntimeError(f"Required data filesystem at {mount} is not writable") + + +def ensure_k3s_data_mount_dependency(remote, mount): + if not mount: + return + require_remote_data_mount(remote, mount) + # An owned drop-in adds ordering without replacing user overrides or + # restarting a live service. The same file can precede first installation. + filename = "/etc/systemd/system/k3s.service.d/20-jeannie-data-mount.conf" + content = f"[Unit]\nRequiresMountsFor={mount}\nConditionPathIsMountPoint={mount}\n" + result = remote("set -eu; sudo -n install -d -m 0755 /etc/systemd/system/k3s.service.d; " + "if printf %s " + shlex.quote(content) + " | sudo -n cmp -s - " + filename + "; then echo unchanged; " + "else if sudo -n test -e " + filename + "; then sudo -n cp -a " + filename + + " " + filename + f".before-{time.time_ns()}; fi; printf %s " + shlex.quote(content) + + " | sudo -n tee " + filename + ".tmp >/dev/null; sudo -n chmod 0644 " + filename + ".tmp; " + "sudo -n mv -T " + filename + ".tmp " + filename + "; sudo -n systemctl daemon-reload; echo installed; fi") + if result == "installed": + print(f"K3s now requires mounted storage at {mount} on future starts; live service left running", flush=True) + + def publish_remote(args, source_path, control, receipt): """Publish a verified offline copy without replacing existing remote data.""" remote = lambda command: run(ssh(control["lan_ip"], control["user"], control["ssh_key_path"], command), timeout=1800) + required_mount = getattr(args, "required_data_mount", "") + require_remote_data_mount(remote, required_mount) if remote("systemctl is-active k3s 2>/dev/null || true") not in ("inactive", "failed", "unknown"): raise RuntimeError("Remote K3s must remain stopped during registry publication") path = "/data/openebs/local/registry" @@ -209,6 +261,7 @@ def publish_remote(args, source_path, control, receipt): "sudo -n tee /etc/rancher/k3s/registries.yaml.jeannie-tmp >/dev/null"), input=yaml.safe_dump(config), text=True, capture_output=True, check=True, timeout=60) remote("sudo -n mv -T /etc/rancher/k3s/registries.yaml.jeannie-tmp /etc/rancher/k3s/registries.yaml") + ensure_k3s_data_mount_dependency(remote, required_mount) temporary = receipt.with_suffix(".tmp") temporary.write_text(json.dumps({"node": control["node_name"], "destination_host": control["lan_ip"], "destination": path, "manifest_sha256": hashlib.sha256(expected.encode()).hexdigest()}) + "\n") diff --git a/tests/jeannie/test_registry_storage_mount.py b/tests/jeannie/test_registry_storage_mount.py new file mode 100644 index 0000000..7ed678f --- /dev/null +++ b/tests/jeannie/test_registry_storage_mount.py @@ -0,0 +1,38 @@ +"""Storage prerequisites. Run on the Debian deployment host.""" + +import importlib.util +import json +from pathlib import Path +import unittest + + +SPEC = importlib.util.spec_from_file_location( + "registry_storage_mount", Path(__file__).resolve().parents[2] / "scripts/registry-storage-reconcile.py" +) +MODULE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(MODULE) + + +class RegistryStorageMountTests(unittest.TestCase): + def mount(self, target, options="rw,relatime"): + return lambda command: json.dumps({"filesystems": [{"target": target, "source": "/dev/example", "options": options}]}) + + def test_missing_data_mount_cannot_fall_back_to_root(self): + with self.assertRaisesRegex(RuntimeError, "refusing root-filesystem fallback"): + MODULE.require_remote_data_mount(self.mount("/"), "/data") + + def test_read_only_data_disk_is_refused(self): + with self.assertRaisesRegex(RuntimeError, "not writable"): + MODULE.require_remote_data_mount(self.mount("/data", "ro,relatime"), "/data") + + def test_writable_declared_mount_is_accepted(self): + MODULE.require_remote_data_mount(self.mount("/data"), "/data") + + def test_profile_without_separate_mount_requires_no_probe(self): + def unexpected_probe(command): + self.fail("A profile without a declared mount must not require /data to be a separate disk") + MODULE.require_remote_data_mount(unexpected_probe, "") + + +if __name__ == "__main__": + unittest.main()