Move native K3s runtime storage to data disk
This commit is contained in:
parent
6a0be19881
commit
227fa04562
|
|
@ -135,6 +135,9 @@ rewritten. Missing, read-only or mismatched storage remains a blocking error.
|
|||
|
||||
## Retire the accidental laptop K3s installation
|
||||
|
||||
For the existing native K3s runtime's data disk transition, see
|
||||
[Move an existing K3s runtime to the data disk](../../docs/deployment.md#move-an-existing-k3s-runtime-to-the-data-disk).
|
||||
|
||||
On the Debian deployment laptop, after pulling the updated repository:
|
||||
|
||||
```sh
|
||||
|
|
|
|||
|
|
@ -25,6 +25,9 @@ resource "null_resource" "k3s_control_plane" {
|
|||
kubeconfig_owner = var.kubeconfig_owner
|
||||
k3s_version = var.k3s_version
|
||||
allow_hypervisor_host = var.k3s_allow_hypervisor_host
|
||||
runtime_storage_path = var.k3s_runtime_storage_path
|
||||
required_data_mount = var.k3s_required_data_mount
|
||||
runtime_storage_helper = filesha256("${path.module}/../../scripts/k3s-runtime-storage-host.py")
|
||||
pod_network_cidr = var.pod_network_cidr
|
||||
}
|
||||
connection {
|
||||
|
|
@ -53,6 +56,11 @@ if sudo test -s /etc/kubernetes/manifests/kube-apiserver.yaml || sudo test -s /e
|
|||
echo "A kubeadm control plane is already present; refusing to install k3s over it." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ -n '${self.triggers.runtime_storage_path}' ]; then
|
||||
sudo -n python3 - prepare-fresh '${self.triggers.runtime_storage_path}' '${self.triggers.required_data_mount}' <<'JEANNIE_K3S_STORAGE'
|
||||
${file("${path.module}/../../scripts/k3s-runtime-storage-host.py")}
|
||||
JEANNIE_K3S_STORAGE
|
||||
fi
|
||||
if ! command -v k3s >/dev/null 2>&1; then
|
||||
curl -sfL https://get.k3s.io | INSTALL_K3S_VERSION='${self.triggers.k3s_version}' sh -s - server \
|
||||
--node-name '${self.triggers.node_name}' \
|
||||
|
|
|
|||
|
|
@ -20,6 +20,26 @@ variable "k3s_version" {
|
|||
default = "v1.31.5+k3s1"
|
||||
}
|
||||
|
||||
variable "k3s_runtime_storage_path" {
|
||||
description = "Optional SSD directory bind-mounted at the default K3s runtime path. Existing data requires the storage transition."
|
||||
type = string
|
||||
default = ""
|
||||
validation {
|
||||
condition = var.k3s_runtime_storage_path == "" || can(regex("^/[A-Za-z0-9_./-]+$", var.k3s_runtime_storage_path))
|
||||
error_message = "Use an absolute storage path with safe characters."
|
||||
}
|
||||
}
|
||||
|
||||
variable "k3s_required_data_mount" {
|
||||
description = "Writable data mount required before preparing SSD runtime storage."
|
||||
type = string
|
||||
default = ""
|
||||
validation {
|
||||
condition = var.k3s_required_data_mount == "" || can(regex("^/[A-Za-z0-9_./-]+$", var.k3s_required_data_mount))
|
||||
error_message = "Use an absolute mount path with safe characters."
|
||||
}
|
||||
}
|
||||
|
||||
variable "k3s_allow_hypervisor_host" {
|
||||
description = "Permit direct K3s on the retained hypervisor OS only while all its VMs are stopped."
|
||||
type = bool
|
||||
|
|
|
|||
|
|
@ -72,6 +72,29 @@ is `~/.local/share/homelab/transitions/k3s-to-native.json`. Other laptop PVC dat
|
|||
stays on the laptop: this copies registry data, not all application databases.
|
||||
See [registry transition details](../bootstrap/apps/README.md).
|
||||
|
||||
## Move an existing K3s runtime to the data disk
|
||||
|
||||
The native profile declares `/data/jeannie/k3s-runtime` as its runtime storage.
|
||||
On the Debian deployment host, after pulling the repository, run:
|
||||
|
||||
```bash
|
||||
./jeannie cluster-transition k3s-runtime-to-ssd
|
||||
./jeannie cluster-transition k3s-runtime-to-ssd --yes
|
||||
```
|
||||
|
||||
The transition stops K3s and its private workloads, copies the runtime offline
|
||||
to the mounted data disk, and bind mounts it at `/var/lib/rancher/k3s`. It
|
||||
checks the enrolled identity and node readiness after restarting. It retains a
|
||||
verified cold rollback copy on the SSD before removing the original eMMC copy.
|
||||
It also preserves any registry directory hidden beneath the `/data` mount; that
|
||||
copy is retained for reconciliation and is not merged automatically. A failed
|
||||
transition keeps its journal and can be resumed with the same command. `rsync`
|
||||
and passwordless sudo are required on the Orange Pi. The service and mount units
|
||||
require `/data` to be mounted before K3s starts.
|
||||
|
||||
Afterward, resume the existing transition with `./jeannie cluster-transition
|
||||
k3s-to-native --yes`. Check the registry before assuming all images are present.
|
||||
|
||||
The native `opi5plus` node has reported Ready. Platform and apps completion
|
||||
remain separate checks. Do not run another deployment alongside the transition.
|
||||
|
||||
|
|
|
|||
|
|
@ -34,6 +34,10 @@ laptop K3s state, prepares verified registry storage on the declared ARM host,
|
|||
and then deploys cluster/platform/apps. It preserves the old data and refuses
|
||||
identity mismatches. Redeploy the API binary after updating its allowlist.
|
||||
|
||||
`cluster-transition k3s-runtime-to-ssd [--yes]` uses the same command boundary
|
||||
to move the enrolled native K3s runtime to its declared mounted data disk. The
|
||||
transition is journaled and preserves a verified rollback copy.
|
||||
|
||||
The authenticated `GET /metrics` endpoint exposes Prometheus-compatible HTTP
|
||||
request counters, request duration totals, and authentication-failure counts.
|
||||
It is served by the Debian API process, so metrics remain available while
|
||||
|
|
|
|||
|
|
@ -72,6 +72,29 @@ is `~/.local/share/homelab/transitions/k3s-to-native.json`. Other laptop PVC dat
|
|||
stays on the laptop: this copies registry data, not all application databases.
|
||||
See [registry transition details](../bootstrap/apps/README.md).
|
||||
|
||||
## Move an existing K3s runtime to the data disk
|
||||
|
||||
The native profile declares `/data/jeannie/k3s-runtime` as its runtime storage.
|
||||
On the Debian deployment host, after pulling the repository, run:
|
||||
|
||||
```bash
|
||||
./{{ main_script }} cluster-transition k3s-runtime-to-ssd
|
||||
./{{ main_script }} cluster-transition k3s-runtime-to-ssd --yes
|
||||
```
|
||||
|
||||
The transition stops K3s and its private workloads, copies the runtime offline
|
||||
to the mounted data disk, and bind mounts it at `/var/lib/rancher/k3s`. It
|
||||
checks the enrolled identity and node readiness after restarting. It retains a
|
||||
verified cold rollback copy on the SSD before removing the original eMMC copy.
|
||||
It also preserves any registry directory hidden beneath the `/data` mount; that
|
||||
copy is retained for reconciliation and is not merged automatically. A failed
|
||||
transition keeps its journal and can be resumed with the same command. `rsync`
|
||||
and passwordless sudo are required on the Orange Pi. The service and mount units
|
||||
require `/data` to be mounted before K3s starts.
|
||||
|
||||
Afterward, resume the existing transition with `./{{ main_script }} cluster-transition
|
||||
k3s-to-native --yes`. Check the registry before assuming all images are present.
|
||||
|
||||
The native `opi5plus` node has reported Ready. Platform and apps completion
|
||||
remain separate checks. Do not run another deployment alongside the transition.
|
||||
|
||||
|
|
|
|||
|
|
@ -113,6 +113,7 @@ cluster:
|
|||
allow_hypervisor_host: true
|
||||
storage:
|
||||
required_mount: /data
|
||||
runtime_path: /data/jeannie/k3s-runtime
|
||||
|
||||
hosts:
|
||||
debian:
|
||||
|
|
|
|||
1
jeannie
1
jeannie
|
|
@ -52,6 +52,7 @@ Base, Inventory, And Planning
|
|||
cluster-profile Print the resolved active cluster profile.
|
||||
cluster-runtime check Verify other cluster profiles are stopped.
|
||||
cluster-transition k3s-to-native [--yes] Move accidental laptop K3s to the native ARM host.
|
||||
cluster-transition k3s-runtime-to-ssd [--yes] Move native K3s runtime to declared SSD storage.
|
||||
cluster-context {status|check|enroll|migrate} [--yes] [--stack NAME]
|
||||
Review pinned cluster identity and scoped state.
|
||||
preflight Run non-mutating infrastructure preflight checks.
|
||||
|
|
|
|||
|
|
@ -155,6 +155,7 @@ profile_mapping = {
|
|||
"runtime": ("LAB_CLUSTER_RUNTIME", "cluster.runtime"),
|
||||
"allow_hypervisor_host": ("LAB_K3S_ALLOW_HYPERVISOR_HOST", None),
|
||||
"storage.required_mount": ("LAB_CLUSTER_REQUIRED_DATA_MOUNT", None),
|
||||
"storage.runtime_path": ("LAB_CLUSTER_RUNTIME_STORAGE_PATH", 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"),
|
||||
|
|
@ -271,6 +272,8 @@ export_homelab_inventory_tf_vars() {
|
|||
export_if_unset TF_VAR_pimox_host "${LAB_CLUSTER_PIMOX_HOST:-${LAB_PIMOX_HOST:-}}"
|
||||
export_if_unset TF_VAR_cluster_runtime "${LAB_CLUSTER_RUNTIME:-kubeadm}"
|
||||
export_if_unset TF_VAR_k3s_allow_hypervisor_host "${LAB_K3S_ALLOW_HYPERVISOR_HOST:-false}"
|
||||
export_if_unset TF_VAR_k3s_runtime_storage_path "${LAB_CLUSTER_RUNTIME_STORAGE_PATH:-}"
|
||||
export_if_unset TF_VAR_k3s_required_data_mount "${LAB_CLUSTER_REQUIRED_DATA_MOUNT:-}"
|
||||
export_if_unset TF_VAR_pimox_user "${LAB_CLUSTER_PIMOX_USER:-${LAB_PIMOX_USER:-}}"
|
||||
export_if_unset TF_VAR_pimox_worker_storage "${LAB_CLUSTER_PIMOX_STORAGE:-${LAB_PIMOX_WORKER_STORAGE:-}}"
|
||||
export_if_unset TF_VAR_pimox_template_bridge "${LAB_CLUSTER_PIMOX_BRIDGE:-${LAB_PIMOX_BRIDGE:-}}"
|
||||
|
|
|
|||
|
|
@ -37,10 +37,14 @@ def save(path, value):
|
|||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("action", choices=("k3s-to-native",))
|
||||
parser.add_argument("action", choices=("k3s-to-native", "k3s-runtime-to-ssd"))
|
||||
parser.add_argument("--yes", action="store_true")
|
||||
parser.add_argument("--source-kubeconfig", default=str(Path.home() / ".kube/k3s-config"))
|
||||
args = parser.parse_args()
|
||||
if args.action == "k3s-runtime-to-ssd":
|
||||
storage = module("runtime_storage_transition", "k3s-runtime-storage.py")
|
||||
storage.main(args.yes)
|
||||
return
|
||||
inventory = yaml.safe_load(Path(os.environ.get("HOMELAB_INVENTORY_FILE", REPO / "homelab.yml")).read_text())
|
||||
profiles = inventory["cluster"]["profiles"]
|
||||
control = profiles["k3s"]["control_plane"]
|
||||
|
|
|
|||
|
|
@ -0,0 +1,277 @@
|
|||
#!/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.")
|
||||
|
|
@ -0,0 +1,108 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Relocate an enrolled K3s runtime without changing its identity or data path."""
|
||||
|
||||
from contextlib import ExitStack
|
||||
import fcntl
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
import yaml
|
||||
|
||||
|
||||
REPO = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def module(name, filename):
|
||||
spec = importlib.util.spec_from_file_location(name, REPO / "scripts" / filename)
|
||||
value = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(value)
|
||||
return value
|
||||
|
||||
|
||||
def save(path, value):
|
||||
temporary = path.with_suffix(".tmp")
|
||||
temporary.write_text(json.dumps(value, indent=2) + "\n")
|
||||
temporary.chmod(0o600)
|
||||
os.replace(temporary, path)
|
||||
|
||||
|
||||
def main(yes=False):
|
||||
inventory = yaml.safe_load(Path(os.environ.get("HOMELAB_INVENTORY_FILE", REPO / "homelab.yml")).read_text())
|
||||
profile = inventory["cluster"]["profiles"]["k3s"]
|
||||
control = profile["control_plane"]
|
||||
storage = profile.get("storage", {})
|
||||
target, mount = storage.get("runtime_path"), storage.get("required_mount")
|
||||
if profile.get("runtime") != "k3s" or not target or not mount:
|
||||
raise RuntimeError("Declare the K3s runtime_path and required_mount before relocating storage")
|
||||
context = module("runtime_storage_context", "cluster-context.py")
|
||||
registry = module("runtime_storage_registry", "registry-storage-reconcile.py")
|
||||
guard = module("runtime_storage_guard", "cluster-runtime-guard.py")
|
||||
ctx = context.Context("k3s", control["kubeconfig"])
|
||||
binding = json.loads(ctx.binding.read_text())
|
||||
expected = {key: binding[key] for key in context.IDENTITY_FIELDS}
|
||||
root = ctx.root
|
||||
root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||
journal_path = root / "runtime-storage-transition.json"
|
||||
record = {"identity": expected, "host": control["lan_ip"], "target": target, "mount": mount}
|
||||
with ExitStack() as locks:
|
||||
lock = locks.enter_context((root.parent / ".runtime-pipeline.lock").open("a"))
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
for stack in ("cluster", "platform", "apps"):
|
||||
operation = locks.enter_context((root / f".{stack}.operation.lock").open("a"))
|
||||
fcntl.flock(operation, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
os.environ["LAB_CLUSTER_RUNTIME"] = "k3s"
|
||||
os.environ["TF_VAR_cluster_runtime"] = "k3s"
|
||||
guard.check("k3s")
|
||||
journal = json.loads(journal_path.read_text()) if journal_path.exists() else None
|
||||
if journal and any(journal.get(key) != value for key, value in record.items()):
|
||||
raise RuntimeError("Recorded storage transition belongs to a different host, disk path or identity")
|
||||
if journal is None or journal.get("phase") == "complete":
|
||||
ctx.check()
|
||||
else:
|
||||
# Only a previously verified transition may resume while its API
|
||||
# is deliberately stopped. Endpoint/CA remain pinned throughout.
|
||||
ctx.observed(startup=True)
|
||||
code = ("EXPECTED = " + repr(expected) + "\nSTOP_SCRIPT = "
|
||||
+ repr((REPO / "scripts/k3s-stop.sh").read_text()) + "\n"
|
||||
+ (REPO / "scripts/k3s-runtime-storage-host.py").read_text())
|
||||
|
||||
def remote(action, capture=False):
|
||||
command = "sudo -n python3 - " + shlex.join([action, target, mount])
|
||||
result = subprocess.run(registry.ssh(control["lan_ip"], control["user"], control["ssh_key_path"], command),
|
||||
input=code, text=True, check=True, timeout=21600,
|
||||
stdout=subprocess.PIPE if capture else None)
|
||||
return result.stdout
|
||||
|
||||
inspection = json.loads(remote("inspect", capture=True))
|
||||
print(json.dumps({**record, **inspection,
|
||||
"actions": ["stop K3s and its private containers", "preserve hidden registry data",
|
||||
"verify two cold SSD copies", "bind mount the original runtime path",
|
||||
"verify original live identity and node readiness",
|
||||
"reclaim verified eMMC duplicate; retain SSD rollback copy"]}, indent=2), flush=True)
|
||||
if not yes:
|
||||
print("Review, then repeat with --yes. No runtime or storage changes made.")
|
||||
return
|
||||
if journal is None:
|
||||
save(journal_path, {**record, "phase": "moving"})
|
||||
remote("move")
|
||||
print("Waiting up to 600s for the original cluster identity and Ready node...", flush=True)
|
||||
deadline = time.monotonic() + 600
|
||||
while True:
|
||||
try:
|
||||
ctx.check()
|
||||
node = json.loads(context.capture(ctx.client() + ["--request-timeout=10s", "get", "node", ctx.expected_node, "-o", "json"]))
|
||||
if not any(c.get("type") == "Ready" and c.get("status") == "True" for c in node["status"]["conditions"]):
|
||||
raise RuntimeError("Node is not Ready")
|
||||
break
|
||||
except (context.Refused, RuntimeError, subprocess.SubprocessError):
|
||||
if time.monotonic() >= deadline:
|
||||
raise RuntimeError("Original identity/readiness was not restored; eMMC and SSD rollback copies retained")
|
||||
time.sleep(5)
|
||||
remote("finalize")
|
||||
save(journal_path, {**record, "phase": "complete"})
|
||||
print("K3s runtime is on SSD; identity unchanged. Resume the existing apps transition.", flush=True)
|
||||
|
|
@ -39,8 +39,11 @@ for entry in Path("/proc").iterdir():
|
|||
arguments = (entry / "cmdline").read_bytes().split(b"\0")
|
||||
except (FileNotFoundError, ProcessLookupError):
|
||||
continue
|
||||
if (arguments and b"containerd-shim" in os.path.basename(arguments[0])
|
||||
and b"/run/k3s/containerd/containerd.sock" in arguments):
|
||||
private_shim = (arguments and b"containerd-shim" in os.path.basename(arguments[0])
|
||||
and b"/run/k3s/containerd/containerd.sock" in arguments)
|
||||
private_daemon = (arguments and os.path.basename(arguments[0]) == b"containerd"
|
||||
and b"/var/lib/rancher/k3s/agent/etc/containerd/config.toml" in arguments)
|
||||
if private_shim or private_daemon:
|
||||
roots.append(pid)
|
||||
wanted = set(roots)
|
||||
while True:
|
||||
|
|
@ -73,7 +76,7 @@ if any(alive(pid) for pid in wanted):
|
|||
raise SystemExit("K3s workload processes remain; runtime is not stopped")
|
||||
K3S_TASKS_PY
|
||||
for attempt in {1..10}; do
|
||||
if sudo -n pgrep -f '[c]ontainerd-shim.*[/]run/k3s' >/dev/null; then
|
||||
if sudo -n pgrep -f '[c]ontainerd-shim.*[/]run/k3s|[c]ontainerd .*[/]var/lib/rancher/k3s/agent/etc/containerd/config.toml' >/dev/null; then
|
||||
sleep 1
|
||||
else
|
||||
status=$?
|
||||
|
|
|
|||
Loading…
Reference in New Issue