Recover stale read-only registry pod mounts
This commit is contained in:
parent
387c0bedf4
commit
ce6ce42bed
|
|
@ -38,6 +38,16 @@ container with write access to the destination block automatic publication. Dest
|
|||
checksums must also remain stable throughout reconciliation. Existing data is
|
||||
never silently overwritten or discarded.
|
||||
|
||||
If a removable data disk reappears under a different Linux device name, a
|
||||
still-running registry pod can retain the disappeared filesystem through its
|
||||
mount namespace. Reconciliation automatically recreates that pod only when
|
||||
`findmnt` proves the old local-volume mount is read-only, the current backing
|
||||
mount is writable, their sources differ, and the current registry directory is
|
||||
readable. It then requires exactly one ready registry pod and verifies that its
|
||||
directory identity matches the current host path. Writable, ambiguous,
|
||||
unreadable, or still-mismatched mounts remain hard failures so potentially newer
|
||||
registry data is never discarded.
|
||||
|
||||
Successful copies write a profile-scoped `registry-migration.json` receipt.
|
||||
Subsequent runs preserve existing destination data. The storage and deployment
|
||||
placement are passed to Argo through `registry_placement` Kustomize patches;
|
||||
|
|
|
|||
|
|
@ -48,6 +48,52 @@ def registry_source_ssh(args, command, cipher=None):
|
|||
return [*target[:-2], "-o", "ProxyCommand=" + shlex.join(proxy), *target[-2:]]
|
||||
|
||||
|
||||
def mount_is_stale_readonly(pod_mount, host_mount):
|
||||
"""Return true only for a read-only orphan superseded by a writable mount."""
|
||||
pod_options = set(str(pod_mount.get("options", "")).split(","))
|
||||
host_options = set(str(host_mount.get("options", "")).split(","))
|
||||
return ("ro" in pod_options and "rw" in host_options and
|
||||
bool(pod_mount.get("source")) and bool(host_mount.get("source")) and
|
||||
pod_mount["source"] != host_mount["source"])
|
||||
|
||||
|
||||
def find_mount(remote, flag, target):
|
||||
document = json.loads(remote("findmnt -J " + flag + " " + shlex.quote(target) +
|
||||
" -o TARGET,SOURCE,OPTIONS"))
|
||||
filesystems = document.get("filesystems") or []
|
||||
if len(filesystems) != 1:
|
||||
raise RuntimeError(f"Expected exactly one mount record for {target}")
|
||||
return filesystems[0]
|
||||
|
||||
|
||||
def recover_stale_readonly_registry_mount(remote, kubectl, pod, pv_name, path):
|
||||
"""Recycle a pod only when its local PV is an obsolete read-only mount."""
|
||||
metadata = pod.get("metadata") or {}
|
||||
pod_name = metadata.get("name", "")
|
||||
pod_uid = metadata.get("uid", "")
|
||||
if not re.fullmatch(r"[a-z0-9.-]+", pod_name) or not re.fullmatch(r"[a-f0-9-]+", pod_uid):
|
||||
raise RuntimeError("Registry pod identity is invalid; refusing stale-mount recovery")
|
||||
if not re.fullmatch(r"[A-Za-z0-9.-]+", pv_name):
|
||||
raise RuntimeError("Registry PV identity is invalid; refusing stale-mount recovery")
|
||||
pod_target = f"/var/lib/kubelet/pods/{pod_uid}/volumes/kubernetes.io~local-volume/{pv_name}"
|
||||
pod_mount = find_mount(remote, "-M", pod_target)
|
||||
host_mount = find_mount(remote, "-T", path)
|
||||
if not mount_is_stale_readonly(pod_mount, host_mount):
|
||||
return False
|
||||
readable = remote("if sudo -n test -d " + shlex.quote(path) +
|
||||
" && sudo -n test -r " + shlex.quote(path) +
|
||||
"; then echo yes; else echo no; fi")
|
||||
if readable != "yes":
|
||||
raise RuntimeError("Current registry directory is not readable; refusing pod recovery")
|
||||
print(f"Registry pod {pod_name} retains obsolete read-only {pod_mount['source']}; "
|
||||
f"recreating it against current writable {host_mount['source']}", flush=True)
|
||||
run(kubectl + ["-n", "container-registry", "delete", "pod", pod_name,
|
||||
"--wait=true", "--timeout=90s"], timeout=110)
|
||||
run(kubectl + ["-n", "container-registry", "rollout", "status",
|
||||
"deployment/local-registry", "--timeout=180s"], timeout=210)
|
||||
return True
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
for name in ("kubeconfig", "destination-node", "destination-path", "source-host",
|
||||
|
|
@ -73,8 +119,10 @@ def main():
|
|||
raw_pv = run(kubectl + ["get", "pv", "registry-data-pimox-worker-01", "--ignore-not-found", "-o", "json"])
|
||||
path = args.destination_path
|
||||
target = args.destination_node
|
||||
pv_name = "registry-data-pimox-worker-01"
|
||||
if raw_pv:
|
||||
pv = json.loads(raw_pv)
|
||||
pv_name = pv["metadata"]["name"]
|
||||
terms = pv["spec"].get("nodeAffinity", {}).get("required", {}).get("nodeSelectorTerms", [])
|
||||
hosts = {host for term in terms for expr in term.get("matchExpressions", [])
|
||||
if expr.get("key") == "kubernetes.io/hostname" and expr.get("operator") == "In"
|
||||
|
|
@ -111,6 +159,7 @@ def main():
|
|||
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"]))
|
||||
running_registry = False
|
||||
recovered_stale_mount = False
|
||||
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 []):
|
||||
|
|
@ -119,8 +168,25 @@ def main():
|
|||
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:
|
||||
if recover_stale_readonly_registry_mount(
|
||||
remote, kubectl, pod, pv_name, path):
|
||||
recovered_stale_mount = True
|
||||
break
|
||||
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 recovered_stale_mount:
|
||||
pods = json.loads(run(kubectl + ["-n", "container-registry", "get", "pods", "-l", "app=local-registry", "-o", "json"]))
|
||||
running = [pod for pod in pods.get("items") or [] if any(
|
||||
status.get("name") == "registry" and status.get("ready")
|
||||
for status in pod.get("status", {}).get("containerStatuses") or [])]
|
||||
if len(running) != 1:
|
||||
raise RuntimeError("Registry stale-mount recovery did not produce exactly one ready pod")
|
||||
pod_directory = run(kubectl + ["-n", "container-registry", "exec", running[0]["metadata"]["name"],
|
||||
"-c", "registry", "--", "stat", "-c", "%d:%i", "/var/lib/registry"])
|
||||
if pod_directory != host_directory:
|
||||
raise RuntimeError("Recreated registry pod still does not use the current host directory")
|
||||
running_registry = True
|
||||
print("Registry pod now uses the current writable host directory", flush=True)
|
||||
if not raw_pv:
|
||||
current = remote_manifest(remote, path)
|
||||
if hashlib.sha256(current.encode()).hexdigest() != receipt["manifest_sha256"]:
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import importlib.util
|
|||
import json
|
||||
from pathlib import Path
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
|
||||
SPEC = importlib.util.spec_from_file_location(
|
||||
|
|
@ -33,6 +34,35 @@ class RegistryStorageMountTests(unittest.TestCase):
|
|||
self.fail("A profile without a declared mount must not require /data to be a separate disk")
|
||||
MODULE.require_remote_data_mount(unexpected_probe, "")
|
||||
|
||||
def test_stale_read_only_mount_is_safe_to_recreate(self):
|
||||
stale = {"source": "/dev/sda1[/openebs/local/registry]", "options": "ro,relatime"}
|
||||
current = {"source": "/dev/sdb1", "options": "rw,relatime"}
|
||||
self.assertTrue(MODULE.mount_is_stale_readonly(stale, current))
|
||||
|
||||
def test_writable_or_same_source_mount_is_not_auto_recreated(self):
|
||||
current = {"source": "/dev/sdb1", "options": "rw,relatime"}
|
||||
self.assertFalse(MODULE.mount_is_stale_readonly(current, current))
|
||||
self.assertFalse(MODULE.mount_is_stale_readonly(
|
||||
{"source": "/dev/sda1", "options": "rw,relatime"}, current
|
||||
))
|
||||
|
||||
def test_recovery_deletes_only_exact_stale_read_only_pod(self):
|
||||
pod = {"metadata": {"name": "local-registry-abc", "uid": "100112e5-ab6d-497a-8b96-f31c36749870"}}
|
||||
mounts = [
|
||||
{"source": "/dev/sda1[/openebs/local/registry]", "options": "ro,relatime"},
|
||||
{"source": "/dev/sdb1", "options": "rw,relatime"},
|
||||
]
|
||||
with mock.patch.object(MODULE, "find_mount", side_effect=mounts), \
|
||||
mock.patch.object(MODULE, "run") as run:
|
||||
recovered = MODULE.recover_stale_readonly_registry_mount(
|
||||
lambda command: "yes", ["kubectl"], pod,
|
||||
"registry-data-pimox-worker-01", "/data/openebs/local/registry"
|
||||
)
|
||||
self.assertTrue(recovered)
|
||||
self.assertEqual(run.call_count, 2)
|
||||
self.assertIn("delete", run.call_args_list[0].args[0])
|
||||
self.assertIn("rollout", run.call_args_list[1].args[0])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
|
|||
Loading…
Reference in New Issue