my-homelab-configs/scripts/doctor-k3s-storage-host.py

128 lines
6.0 KiB
Python

#!/usr/bin/env python3
"""Orange Pi side of stale K3s storage diagnosis and guarded recovery.
EXPECTED_CA, DATA_MOUNT, RUNTIME_PATH and STOP_SCRIPT are supplied by the
controller over SSH. This helper is never executed from untrusted inventory.
"""
import hashlib
import json
import os
from pathlib import Path
import re
import ssl
import subprocess
import sys
import tempfile
def run(command, check=True, timeout=30, input_text=None):
result = subprocess.run(command, input=input_text, text=True, capture_output=True, timeout=timeout)
if check and result.returncode:
raise RuntimeError(f"{command[0]} failed: {(result.stderr or result.stdout).strip()[-500:]}")
return result.stdout.strip()
def mount(target):
result = run(["findmnt", "-J", "-M", target, "-o", "TARGET,SOURCE,MAJ:MIN,OPTIONS"], check=False)
if not result:
return None
return (json.loads(result).get("filesystems") or [None])[0]
def disks():
# Bullseye's lsblk lacks MOUNTPOINTS. findmnt below checks every mount,
# since the older singular MOUNTPOINT column may show only one of them.
data = json.loads(run(["lsblk", "-J", "-o", "NAME,TYPE,MAJ:MIN,FSTYPE,UUID,MOUNTPOINT,TRAN"]))
return data.get("blockdevices") or []
def inspect():
data, runtime = mount(DATA_MOUNT), mount("/var/lib/rancher/k3s")
devices = disks()
mounted_devices = set(run(["findmnt", "-rn", "-o", "MAJ:MIN"]).split())
present = set()
candidates = []
def visit(device, transport=None):
transport = device.get("tran") or transport
present.add(device.get("maj:min"))
if (device.get("type") == "part" and transport == "usb" and device.get("fstype") == "ext4"
and device.get("uuid") and not device.get("mountpoint") and device.get("maj:min") not in mounted_devices):
candidates.append({"name": device.get("name"), "uuid": device["uuid"], "maj:min": device.get("maj:min")})
for child in device.get("children") or []:
visit(child, transport)
for device in devices:
visit(device)
service = run(["systemctl", "is-active", "k3s"], check=False) or "unknown"
journal = run(["journalctl", "-k", "-b", "-n", "500", "--no-pager", "-o", "cat"], check=False, timeout=15)
errors = [line for line in journal.splitlines() if re.search(r"EXT4-fs.*error|I/O error|usb.*(?:disconnect|reset)", line, re.I)][-3:]
stale = bool(data and runtime and data.get("maj:min") and
"ro" in data.get("options", "").split(",") and "ro" in runtime.get("options", "").split(",") and
data.get("maj:min") == runtime.get("maj:min") and data.get("maj:min") not in present)
return {"service": service, "data_mount": data, "runtime_mount": runtime,
"stale_readonly_mount": stale, "reappeared_usb_ext4": candidates, "recent_storage_errors": errors}
def ca_fingerprint(path):
pem = path.read_text()
blocks = re.findall(r"-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----", pem, flags=re.S)
if len(blocks) != 1:
raise RuntimeError("Expected exactly one K3s server CA certificate")
return hashlib.sha256(ssl.PEM_cert_to_DER_cert(blocks[0])).hexdigest()
def runtime_ca(root, relative):
root = Path(root).resolve()
runtime = (root / relative).resolve()
if not runtime.is_relative_to(root) or runtime == root:
raise RuntimeError("K3s runtime resolves outside the expected data mount")
return ca_fingerprint(runtime / "server/tls/server-ca.crt")
def repair(uuid):
if not re.fullmatch(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}", uuid):
raise RuntimeError("Candidate filesystem UUID is invalid")
before = inspect()
candidates = before["reappeared_usb_ext4"]
if (not before["stale_readonly_mount"] or before["service"] not in ("failed", "inactive") or
len(candidates) != 1 or candidates[0]["uuid"] != uuid):
raise RuntimeError("Stale mount or unique reappeared SSD no longer matches the reviewed evidence")
source = "/dev/disk/by-uuid/" + uuid
relative = Path(RUNTIME_PATH).relative_to(DATA_MOUNT)
with tempfile.TemporaryDirectory(prefix="jeannie-k3s-check-") as directory:
run(["mount", "-o", "ro,noload", source, directory])
try:
if runtime_ca(directory, relative) != EXPECTED_CA:
raise RuntimeError("Reappeared SSD does not contain the pinned K3s CA")
finally:
run(["umount", directory])
print("Verified the SSD contains the pinned K3s CA; stopping private K3s workloads.", flush=True)
run(["bash"], timeout=90, input_text=STOP_SCRIPT)
run(["umount", "/var/lib/rancher/k3s"], timeout=60)
run(["umount", DATA_MOUNT], timeout=60)
run(["mount", source, DATA_MOUNT], timeout=60)
current = mount(DATA_MOUNT)
if not current or "rw" not in current.get("options", "").split(","):
raise RuntimeError("SSD did not mount read-write; K3s remains stopped")
if runtime_ca(DATA_MOUNT, relative) != EXPECTED_CA:
raise RuntimeError("Mounted K3s CA differs from pinned identity; K3s remains stopped")
run(["mount", "--bind", RUNTIME_PATH, "/var/lib/rancher/k3s"], timeout=60)
source_stat, runtime_stat = os.stat(RUNTIME_PATH), os.stat("/var/lib/rancher/k3s")
if (source_stat.st_dev, source_stat.st_ino) != (runtime_stat.st_dev, runtime_stat.st_ino):
raise RuntimeError("K3s bind mount differs from the SSD runtime directory")
run(["systemctl", "reset-failed", "k3s"])
run(["systemctl", "start", "k3s"], timeout=300)
print("K3s started; verifying the pinned live cluster identity next.", flush=True)
if __name__ == "__main__":
try:
if sys.argv[1:] == ["inspect"]:
print(json.dumps(inspect()))
elif len(sys.argv) == 3 and sys.argv[1] == "repair":
repair(sys.argv[2])
else:
raise RuntimeError("Invalid storage doctor action")
except (OSError, ValueError, RuntimeError, subprocess.SubprocessError) as exc:
print(f"K3s storage recovery stopped: {exc}", file=sys.stderr)
sys.exit(1)