Require declared data mounts and preserve registry volume identity across remounts
Homelab Main / validate (push) Waiting to run Details
Homelab Main / running-update (push) Blocked by required conditions Details
Homelab Main / debian-ops (push) Blocked by required conditions Details

This commit is contained in:
juvenal.diaz 2026-11-03 07:42:56 -06:00
parent 71cd0db9d3
commit 23932cd7e1
10 changed files with 136 additions and 1 deletions

View File

@ -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 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 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 ## Retire the accidental laptop K3s installation
On the Debian deployment laptop, after pulling the updated repository: On the Debian deployment laptop, after pulling the updated repository:

View File

@ -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. preserved locally and are not automatically restored into the new cluster.
See [registry migration](../bootstrap/apps/README.md). 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
Gitea is external bootstrap infrastructure. It runs on the Debian host as an Gitea is external bootstrap infrastructure. It runs on the Debian host as an

View File

@ -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. preserved locally and are not automatically restored into the new cluster.
See [registry migration](../bootstrap/apps/README.md). 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
Gitea is external bootstrap infrastructure. It runs on the Debian host as an Gitea is external bootstrap infrastructure. It runs on the Debian host as an

View File

@ -111,6 +111,8 @@ cluster:
calico_operator_node_name: opi5plus calico_operator_node_name: opi5plus
runtime: k3s runtime: k3s
allow_hypervisor_host: true allow_hypervisor_host: true
storage:
required_mount: /data
hosts: hosts:
debian: debian:

View File

@ -154,6 +154,7 @@ profile_mapping = {
"platform.calico_operator_node_name": ("LAB_CALICO_OPERATOR_NODE_NAME", None), "platform.calico_operator_node_name": ("LAB_CALICO_OPERATOR_NODE_NAME", None),
"runtime": ("LAB_CLUSTER_RUNTIME", "cluster.runtime"), "runtime": ("LAB_CLUSTER_RUNTIME", "cluster.runtime"),
"allow_hypervisor_host": ("LAB_K3S_ALLOW_HYPERVISOR_HOST", None), "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.host": ("LAB_CLUSTER_PIMOX_HOST", "hosts.opi5_pimox.lan_ip"),
"pimox.user": ("LAB_CLUSTER_PIMOX_USER", "hosts.opi5_pimox.user"), "pimox.user": ("LAB_CLUSTER_PIMOX_USER", "hosts.opi5_pimox.user"),
"pimox.bridge": ("LAB_CLUSTER_PIMOX_BRIDGE", "hosts.opi5_pimox.bridge"), "pimox.bridge": ("LAB_CLUSTER_PIMOX_BRIDGE", "hosts.opi5_pimox.bridge"),

View File

@ -7328,6 +7328,7 @@ reconcile_app_registry_storage() {
--destination-host "${LAB_CLUSTER_CONTROL_PLANE_LAN_IP}" \ --destination-host "${LAB_CLUSTER_CONTROL_PLANE_LAN_IP}" \
--destination-user "${LAB_CLUSTER_CONTROL_PLANE_USER}" \ --destination-user "${LAB_CLUSTER_CONTROL_PLANE_USER}" \
--destination-key "${LAB_CLUSTER_CONTROL_PLANE_SSH_KEY_PATH}" \ --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}" \ --destination-path "${LAB_REGISTRY_STORAGE_PATH:-/data/openebs/local/registry}" \
--source-host "${source_host}" --source-user "${source_user}" --source-key "${source_key}" \ --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}" \ --source-node "${source_node}" --source-path "${LAB_PIMOX_REGISTRY_STORAGE_PATH:-/data/openebs/local/registry}" \

View File

@ -3,6 +3,7 @@
import argparse import argparse
import fcntl import fcntl
import importlib.util
import json import json
import os import os
from pathlib import Path 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"): for variable in ("LAB_CLUSTER_RUNTIME", "TF_VAR_cluster_runtime"):
if os.environ.get(variable, runtime) != runtime: if os.environ.get(variable, runtime) != runtime:
raise RuntimeError(f"{variable} conflicts with profile {selected}; expected {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"] laptop = inventory["hosts"]["debian"]
hypervisor = inventory["hosts"]["opi5_pimox"] hypervisor = inventory["hosts"]["opi5_pimox"]
laptop_key = profiles["debian"]["control_plane"]["ssh_key_path"] laptop_key = profiles["debian"]["control_plane"]["ssh_key_path"]

View File

@ -58,6 +58,8 @@ def main():
registry = module("registry_transition", "registry-storage-reconcile.py") registry = module("registry_transition", "registry-storage-reconcile.py")
context = module("context_transition", "cluster-context.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) 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") architecture = remote("uname -m")
if architecture not in ("aarch64", "arm64"): if architecture not in ("aarch64", "arm64"):
raise RuntimeError("Native target is not ARM64; refusing to deploy on another laptop") 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"], source_path="/data/openebs/local/registry", hypervisor_host=control["lan_ip"],
hypervisor_user=control["user"], hypervisor_key=control["ssh_key_path"], hypervisor_user=control["user"], hypervisor_key=control["ssh_key_path"],
transfer_cipher="aes256-gcm@openssh.com", registry_endpoint=profiles["k3s"]["registry"]["endpoint"]) 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.require_no_local_writer("/data/openebs/local/registry")
registry.prepare_local(options, "/data/openebs/local/registry", False) registry.prepare_local(options, "/data/openebs/local/registry", False)
root.mkdir(parents=True, exist_ok=True, mode=0o700) root.mkdir(parents=True, exist_ok=True, mode=0o700)

View File

@ -57,6 +57,7 @@ def main():
parser.add_argument("--destination-host") parser.add_argument("--destination-host")
parser.add_argument("--destination-user") parser.add_argument("--destination-user")
parser.add_argument("--destination-key") parser.add_argument("--destination-key")
parser.add_argument("--required-data-mount", default="")
parser.add_argument("--registry-endpoint", required=True) parser.add_argument("--registry-endpoint", required=True)
parser.add_argument("--transfer-cipher", default=os.environ.get("LAB_REGISTRY_TRANSFER_CIPHER", "aes256-gcm@openssh.com"), 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")) 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"]): 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") 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 = 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"]: 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") 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) print(f"Preserving verified remote registry storage on {target}:{path}", flush=True)
else: else:
prepare_local(args, path, bool(raw_pv)) 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)) 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): def publish_remote(args, source_path, control, receipt):
"""Publish a verified offline copy without replacing existing remote data.""" """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) 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"): 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") raise RuntimeError("Remote K3s must remain stopped during registry publication")
path = "/data/openebs/local/registry" 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"), "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) 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") 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 = receipt.with_suffix(".tmp")
temporary.write_text(json.dumps({"node": control["node_name"], "destination_host": control["lan_ip"], temporary.write_text(json.dumps({"node": control["node_name"], "destination_host": control["lan_ip"],
"destination": path, "manifest_sha256": hashlib.sha256(expected.encode()).hexdigest()}) + "\n") "destination": path, "manifest_sha256": hashlib.sha256(expected.encode()).hexdigest()}) + "\n")

View File

@ -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()