Enforce exclusive cluster runtimes across all three profiles
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-02 22:18:12 -06:00
parent 4eeac3d33a
commit 0590838fc5
13 changed files with 305 additions and 39 deletions

View File

@ -76,10 +76,38 @@ errors, especially alongside TLS bad-record-MAC failures, require investigation
of the endpoints and network path; cipher selection alone does not prove that
the underlying issue is repaired.
The retained `k3s` profile targets the existing x86 Debian cluster at `.73`.
The prepared `opi5-k3s` profile targets the Orange Pi host at `.80` with separate
state, kubeconfig and enrollment. Its host currently runs Pimox: direct k3s
bootstrap refuses an active hypervisor, and this profile is not ready to deploy
until host OS preparation and registry placement for the new target are resolved.
Do not reinstall the hypervisor or erase its disks before securing registry and
other required VM data.
There are exactly three canonical profiles:
| Profile | Control plane | Workers | Conflicting runtime requirements |
| --- | --- | --- | --- |
| `debian` | Laptop `.73`, kubeadm | Pimox VMs 9010/9011 | Host K3s stopped; VM 9001 stopped |
| `pimox` | Pimox VM 9001 at `.65`, kubeadm | Pimox VMs 9010/9011 | Laptop control plane and host K3s stopped |
| `k3s` | Native Orange Pi `.80` | Same host | Laptop control plane and every Pimox VM stopped |
Pimox remains installed on the Orange Pi. The direct-host installation requires
the declared hypervisor-host capability and checks that all VMs are stopped.
It does not remove Pimox or rewrite `vmbr0`. Packaged K3s Traefik, ServiceLB and
metrics-server are disabled so platform charts own those components.
`./jeannie cluster-runtime check` performs read-only SSH probes of physical host
services, API listeners and VM state. Deploy/start pipelines and guarded Tofu
mutations refuse active conflicts or unverifiable host state. Stop commands
remain available to resolve conflicts; pipelines do not kill another cluster or
remove its identity/state. The same check is exposed by the API allowlist.
Top-level deployment/start pipelines hold a shared lock across profiles until
they exit, preventing concurrent Jeannie deployments on the same controller.
Starting an enrolled, stopped cluster checks its pinned endpoint and CA offline;
the live namespace UID is checked after startup and before deployment mutations.
Manual VM/service starts outside Jeannie are not covered by the pipeline lock.
The accidentally installed laptop K3s cluster is not profile 3. Its service must
be stopped and its identity/state retained separately before enrolling the
Orange Pi cluster. Existing `.73` identity/state under `clusters/k3s` is never
automatically rebound to `.80`; endpoint/CA/UID mismatch guards remain active.
The old laptop kubeconfig can be retained, while native K3s uses
`/home/jv/.kube/opi5-k3s-config`.
The registry copy must be secured before switching to host K3s: migration cannot
boot a source VM while host K3s is active. Moving registry storage onto a remote
control plane still requires a separate reviewed storage transition; the current
local-copy helper refuses to write storage on the wrong deployment host.

View File

@ -24,6 +24,7 @@ resource "null_resource" "k3s_control_plane" {
kubeconfig_path = var.kubeconfig_path
kubeconfig_owner = var.kubeconfig_owner
k3s_version = var.k3s_version
allow_hypervisor_host = var.k3s_allow_hypervisor_host
pod_network_cidr = var.pod_network_cidr
}
connection {
@ -37,8 +38,15 @@ resource "null_resource" "k3s_control_plane" {
inline = [<<EOT
set -euo pipefail
if command -v qm >/dev/null 2>&1 || sudo test -d /etc/pve; then
echo "This target is an active Proxmox/Pimox host. Prepare its Debian host OS before direct k3s installation; preserving VM disks and hypervisor networking." >&2
exit 1
if [ '${self.triggers.allow_hypervisor_host}' != true ]; then
echo "Direct K3s on a hypervisor requires the declared allow_hypervisor_host capability." >&2
exit 1
fi
running_vms="$(sudo -n qm list | awk 'NR > 1 && $3 != "stopped" {print $1}')"
if [ -n "$running_vms" ]; then
echo "K3s cannot start while Pimox VMs are running: $running_vms" >&2
exit 1
fi
fi
if sudo test -s /etc/kubernetes/manifests/kube-apiserver.yaml || sudo test -s /etc/kubernetes/admin.conf; then
echo "A kubeadm control plane is already present; refusing to install k3s over it." >&2
@ -49,7 +57,7 @@ if ! command -v k3s >/dev/null 2>&1; then
--node-name '${self.triggers.node_name}' \
--node-ip '${self.triggers.advertise_address}' \
--advertise-address '${self.triggers.advertise_address}' \
--flannel-backend=none --disable-network-policy --disable=traefik \
--flannel-backend=none --disable-network-policy --disable=traefik --disable=servicelb --disable=metrics-server \
--write-kubeconfig-mode=0644 --cluster-cidr '${self.triggers.pod_network_cidr}'
fi
sudo systemctl enable k3s >/dev/null

View File

@ -20,6 +20,12 @@ variable "k3s_version" {
default = "v1.31.5+k3s1"
}
variable "k3s_allow_hypervisor_host" {
description = "Permit direct K3s on the retained hypervisor OS only while all its VMs are stopped."
type = bool
default = false
}
variable "control_plane_node_labels" {
type = map(string)
default = {

View File

@ -27,7 +27,7 @@ const maxOutputBytes = 1 << 20
// recursive remote command are intentionally excluded.
var allowedCommands = map[string]bool{
"help": true, "up": true, "plan": true, "cluster": true, "cluster-context": true,
"cluster-profile": true, "rebuild-cluster": true, "stop-cluster": true,
"cluster-profile": true, "cluster-runtime": true, "rebuild-cluster": true, "stop-cluster": true,
"start-cluster": true, "cleanup-debian-k8s": true,
"shutdown": true, "start": true,
"status": true, "capacity": true, "capacity-advisor": true,

View File

@ -61,6 +61,7 @@ cluster:
repo_url: ssh://git@192.168.100.73:32222/jv/my-homelab-configs.git
platform:
calico_operator_node_name: debian
runtime: kubeadm
pimox:
control_plane:
node_name: pimox-cp-01
@ -80,6 +81,7 @@ cluster:
repo_url: ssh://git@192.168.100.73:32222/jv/my-homelab-configs.git
platform:
calico_operator_node_name: pimox-cp-01
runtime: kubeadm
pimox:
host: 192.168.100.80
user: jv
@ -88,28 +90,7 @@ cluster:
control_plane_vmid: 9001
worker_count: 2
worker_static_ips: 192.168.100.66 192.168.100.67
# Existing x86 cluster remains available with its pinned identity/state.
k3s:
control_plane:
node_name: debian
lan_ip: 192.168.100.73
user: jv
ssh_key_path: /home/jv/.ssh/id_ed25519
kubeconfig: /home/jv/.kube/k3s-config
kubeconfig_owner: jv:jv
registry:
endpoint: 192.168.100.73:30500
provisioning:
host: 192.168.100.73
user: jv
http:
host: 192.168.100.73
gitops:
repo_url: ssh://git@192.168.100.73:32222/jv/my-homelab-configs.git
platform:
calico_operator_node_name: debian
runtime: k3s
opi5-k3s:
control_plane:
node_name: opi5plus
lan_ip: 192.168.100.80
@ -129,6 +110,7 @@ cluster:
platform:
calico_operator_node_name: opi5plus
runtime: k3s
allow_hypervisor_host: true
hosts:
debian:

48
jeannie
View File

@ -50,6 +50,7 @@ Base, Inventory, And Planning
validate Run repo validation checks.
inventory-check Validate the canonical homelab inventory.
cluster-profile Print the resolved active cluster profile.
cluster-runtime check Verify other cluster profiles are stopped.
cluster-context {status|check|enroll|migrate} [--yes] [--stack NAME]
Review pinned cluster identity and scoped state.
preflight Run non-mutating infrastructure preflight checks.
@ -231,17 +232,53 @@ if [[ "${JEANNIE_LIBRARY_MODE:-false}" == "true" ]]; then
return 0 2>/dev/null || exit 0
fi
# Serialize top-level cluster pipelines, including callers from the API. The
# inherited descriptor keeps the lock until this pipeline exits. Internal DAG
# tasks perform read-only checks beneath their parent's lock.
runtime_pipeline=false
case "${1:-}" in
up|cluster|platform|apps|start-cluster) runtime_pipeline=true ;;
start) [[ "${2:-plan}" != apply ]] || runtime_pipeline=true ;;
esac
if "${runtime_pipeline}"; then
if [[ "${JEANNIE_RUNTIME_PIPELINE_LOCK:-}" != "${LAB_CLUSTER_PROFILE}" ||
! "${JEANNIE_RUNTIME_PIPELINE_LOCK_FD:-}" =~ ^[0-9]+$ ||
! -e "/proc/$$/fd/${JEANNIE_RUNTIME_PIPELINE_LOCK_FD:-invalid}" ]]; then
exec python3 "${REPO_ROOT}/scripts/cluster-runtime-guard.py" \
--profile "${LAB_CLUSTER_PROFILE}" run -- "${REPO_ROOT}/jeannie" "$@"
fi
fi
# Check conflicting runtimes before any cluster pipeline changes hosts.
case "${1:-}" in
up|cluster|platform|apps|start-cluster)
cluster_runtime_require || exit 1
;;
start)
if [[ "${2:-plan}" == apply ]]; then cluster_runtime_require || exit 1; fi
;;
__up-task)
cluster_runtime_require || exit 1
;;
esac
# Guard operations that also mutate hosts over SSH, beyond kubectl/Tofu.
case "${1:-}" in
up|stop-cluster|start-cluster|nuke|cleanup-debian-k8s|move-prometheus-stack-workers)
up|stop-cluster|nuke|cleanup-debian-k8s|move-prometheus-stack-workers)
cluster_context_require || exit 1
;;
start-cluster)
cluster_context_require_startup || exit 1
;;
rebuild-cluster)
cluster_context_require || exit 1
echo "Automatic rebuild changes the pinned cluster identity; refusing before destruction. A reviewed bootstrap/re-enrollment transition is required." >&2
exit 1
;;
start|shutdown)
start)
if [[ "${2:-plan}" == "apply" ]]; then cluster_context_require_startup || exit 1; fi
;;
shutdown)
if [[ "${2:-plan}" == "apply" ]]; then cluster_context_require || exit 1; fi
;;
__up-task)
@ -250,6 +287,13 @@ case "${1:-}" in
esac
case "${1:-}" in
cluster-runtime)
if [[ "${2:-}" != check ]]; then
echo "Usage: ./jeannie cluster-runtime check" >&2
exit 2
fi
python3 "${REPO_ROOT}/scripts/cluster-runtime-guard.py" "${@:2}"
;;
cluster-context)
python3 "${REPO_ROOT}/scripts/cluster-context.py" "${@:2}"
;;

View File

@ -6,6 +6,17 @@ cluster_context_require() {
--kubeconfig "${KUBECONFIG_PATH}" >/dev/null
}
cluster_runtime_require() {
python3 "${REPO_ROOT}/scripts/cluster-runtime-guard.py" check \
--profile "${LAB_CLUSTER_PROFILE:?Missing active cluster profile}" "$@" >/dev/null
}
cluster_context_require_startup() {
python3 "${REPO_ROOT}/scripts/cluster-context.py" check-startup \
--profile "${LAB_CLUSTER_PROFILE:?Missing active cluster profile}" \
--kubeconfig "${KUBECONFIG_PATH}" >/dev/null
}
cluster_context_enable() {
export HOMELAB_STATE_DIR LAB_CLUSTER_PROFILE KUBECONFIG_PATH
case ":${PATH}:" in

View File

@ -560,6 +560,7 @@ sudo '${qm_bin}' destroy '${vmid}' --purge 1 >/dev/null 2>&1 || sudo '${qm_bin}'
}
start_pimox_worker_vms() {
cluster_runtime_require --vm-start || return 1
local pimox_host="${LAB_PIMOX_HOST:-${TF_VAR_pimox_host:-192.168.100.80}}"
local pimox_user="${LAB_PIMOX_USER:-${TF_VAR_pimox_user:-jv}}"
local pimox_key="${LAB_PIMOX_SSH_KEY_PATH:-${TF_VAR_pimox_ssh_key_path:-/home/jv/.ssh/id_ed25519}}"
@ -610,6 +611,7 @@ start_pimox_control_plane_vm() {
if [[ "${LAB_CLUSTER_PROFILE:-debian}" != "pimox" ]]; then
return 0
fi
cluster_runtime_require --vm-start || return 1
if [[ -z "${vmid}" ]]; then
echo "LAB_CLUSTER_PIMOX_CONTROL_PLANE_VMID is not configured; cannot start Pimox control-plane VM." >&2
return 1
@ -713,6 +715,13 @@ stop_cluster() {
require_debian_server "stop-cluster"
cluster_context_require || return 1
if [[ "${LAB_CLUSTER_RUNTIME:-kubeadm}" == k3s ]]; then
echo "Stopping direct-host K3s on ${LAB_CLUSTER_CONTROL_PLANE_LAN_IP}; preserving Pimox, VM disks and cluster data."
ssh -i "${LAB_CLUSTER_CONTROL_PLANE_SSH_KEY_PATH}" -o BatchMode=yes -o ConnectTimeout=10 \
"${LAB_CLUSTER_CONTROL_PLANE_USER}@${LAB_CLUSTER_CONTROL_PLANE_LAN_IP}" \
'sudo -n systemctl stop k3s' || return 1
return 0
fi
cluster_worker_targets
echo "Stopping Kubernetes cluster runtime without destroying state..."
@ -1070,7 +1079,17 @@ start_cluster() {
declare -a CLUSTER_WORKER_TARGETS=()
require_debian_server "start-cluster"
cluster_context_require || return 1
cluster_context_require_startup || return 1
cluster_runtime_require || return 1
if [[ "${LAB_CLUSTER_RUNTIME:-kubeadm}" == k3s ]]; then
echo "Starting direct-host K3s on ${LAB_CLUSTER_CONTROL_PLANE_LAN_IP}; Pimox VMs remain stopped."
ssh -i "${LAB_CLUSTER_CONTROL_PLANE_SSH_KEY_PATH}" -o BatchMode=yes -o ConnectTimeout=10 \
"${LAB_CLUSTER_CONTROL_PLANE_USER}@${LAB_CLUSTER_CONTROL_PLANE_LAN_IP}" \
'set -euo pipefail; vms="$(sudo -n qm list | awk '\''NR > 1 && $3 != "stopped" {print $1}'\'')"; test -z "$vms" || { echo "Pimox VMs are running: $vms" >&2; exit 1; }; sudo -n systemctl start k3s' || return 1
wait_for_kubernetes_api "${LAB_CLUSTER_START_WAIT_SECONDS:-360}" || return 1
cluster_context_require || return 1
return 0
fi
cluster_worker_targets
echo "Starting Kubernetes cluster runtime without rebuilding state..."
@ -1096,7 +1115,9 @@ start_cluster() {
start_remote_kubernetes_services "${target}"
done
fi
echo "Kubernetes runtime start requested. Use 'kubectl get nodes -o wide' to watch readiness."
wait_for_kubernetes_api "${LAB_CLUSTER_START_WAIT_SECONDS:-360}" || return 1
cluster_context_require || return 1
echo "Kubernetes runtime started and pinned cluster identity verified."
}
cleanup_debian_k8s_after_pimox_offload() {

View File

@ -153,6 +153,7 @@ profile_mapping = {
"gitops.repo_url": ("LAB_GITOPS_REPO_URL", "services.gitea.ssh_remote"),
"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),
"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"),
@ -163,6 +164,8 @@ profile_mapping = {
}
for relative_path, (env_name, fallback_path) in profile_mapping.items():
value = values.get(f"{profile_prefix}.{relative_path}")
if relative_path == "allow_hypervisor_host" and value:
value = value.lower()
if not value and fallback_path:
value = values.get(fallback_path)
if not value and relative_path == "control_plane.node_name" and cluster_profile == "debian":
@ -266,6 +269,7 @@ export_homelab_inventory_tf_vars() {
export_if_unset TF_VAR_http_host "${LAB_CLUSTER_HTTP_HOST:-${LAB_CLUSTER_CONTROL_PLANE_LAN_IP:-${LAB_DEBIAN_LAN_IP:-}}}"
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_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:-}}"

View File

@ -1034,6 +1034,10 @@ run_tofu_stack() {
local -a apply_args=()
local target
if [[ "${stack}" == bootstrap/cluster || "${stack}" == bootstrap/platform || "${stack}" == bootstrap/apps ]]; then
cluster_runtime_require || return 1
fi
# A new profile has no pinned identity until its control plane bootstrap
# completes. Platform/apps remain guarded by cluster-context as usual.
if [[ "${stack}" == "bootstrap/platform" || "${stack}" == "bootstrap/apps" ]] ||
@ -4057,6 +4061,7 @@ inventory_check() {
}
run_pimox_pipeline() {
cluster_runtime_require --vm-start || return 1
local mode="${LAB_PIMOX_PIPELINE:-true}"
local pimox_host="${LAB_PIMOX_HOST:-${TF_VAR_pimox_host:-192.168.100.80}}"
local pimox_user="${LAB_PIMOX_USER:-${TF_VAR_pimox_user:-jv}}"
@ -4446,6 +4451,7 @@ run_openwrt_pipeline() {
echo "LAB_OPENWRT_VM must be true or false." >&2
exit 1
fi
cluster_runtime_require --vm-start || return 1
if [[ -z "${image_url}" ]]; then
image_url="https://downloads.openwrt.org/releases/${version}/targets/armsr/armv8/openwrt-${version}-armsr-armv8-generic-ext4-combined-efi.img.gz"
@ -9238,12 +9244,16 @@ up_task() {
;;
pimox-workers)
if [[ "${LAB_CLUSTER_RUNTIME:-kubeadm}" == "k3s" ]]; then
echo "Skipping Pimox worker provisioning for the direct Debian k3s profile."
echo "Skipping Pimox worker provisioning for the direct-host K3s runtime."
return 0
fi
run_pimox_pipeline
;;
openwrt)
if [[ "${LAB_CLUSTER_RUNTIME:-kubeadm}" == k3s ]]; then
echo "Skipping OpenWrt VM startup while direct-host K3s is selected."
return 0
fi
run_openwrt_pipeline
;;
edge-host)

View File

@ -191,7 +191,7 @@ class Context:
command.extend(["--context", self.kube_context])
return command
def observed(self):
def observed(self, startup=False):
client = self.client()
config = json.loads(capture(client + ["config", "view", "--raw", "--minify", "--flatten", "-o", "json"]))
clusters = config.get("clusters", [])
@ -211,6 +211,13 @@ class Context:
bound = document(self.binding)
if bound.get("profile") != self.profile or bound.get("endpoint") != actual_endpoint or bound.get("ca_sha256") != ca:
raise Refused(f"Profile {self.profile}: pinned endpoint or CA fingerprint mismatch")
if startup:
if not self.binding.is_file() or not document(self.binding).get("kube_system_uid"):
raise Refused("Starting a stopped cluster requires its existing enrolled identity")
# Only host/VM startup may use this offline check. Apply, import,
# cleanup and healing still require the live kube-system UID.
return {"profile": self.profile, "endpoint": actual_endpoint, "ca_sha256": ca,
"startup_only": True, "live_uid_check_required_after_start": True}
request = client + ["--request-timeout=10s"]
namespace = json.loads(capture(request + ["get", "namespace", "kube-system", "-o", "json"]))
uid = namespace.get("metadata", {}).get("uid")
@ -463,6 +470,12 @@ def proxy_tofu(args):
if command == "init":
return 0
mutable = command in ("apply", "destroy", "import", "refresh", "force-unlock", "taint", "untaint") or command == "state" and len(args) > 1 and args[1] not in ("list", "show", "pull")
if mutable:
result = subprocess.run([sys.executable, str(REPO / "scripts/cluster-runtime-guard.py"),
"check", "--profile", context.profile], text=True,
capture_output=True, timeout=110)
if result.returncode:
raise Refused(result.stderr.strip() or "Other cluster runtime states could not be verified")
initial_k3s_bootstrap = (
name == "cluster"
and command == "apply"
@ -563,6 +576,8 @@ def manage(args):
context = Context(args.profile, args.kubeconfig)
if args.action == "check":
print(json.dumps(context.check(), sort_keys=True))
elif args.action == "check-startup":
print(json.dumps(context.observed(startup=True), sort_keys=True))
elif args.action == "check-local-host":
observed = context.check()
addresses = json.loads(capture([binary("ip"), "-j", "address", "show"]))
@ -646,7 +661,7 @@ def main():
proxy_client(tool, sys.argv[3:])
raise Refused("Unsupported guarded tool")
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=("status", "check", "check-local-host", "enroll", "migrate"))
parser.add_argument("action", choices=("status", "check", "check-startup", "check-local-host", "enroll", "migrate"))
parser.add_argument("--profile")
parser.add_argument("--kubeconfig")
parser.add_argument("--stack", choices=sorted(STACKS))

View File

@ -0,0 +1,134 @@
#!/usr/bin/env python3
"""Read-only mutual exclusion checks for the three homelab cluster modes."""
import argparse
import fcntl
import json
import os
from pathlib import Path
import subprocess
import sys
import yaml
REPO = Path(__file__).resolve().parents[1]
def remote(host, user, key, command):
result = subprocess.run(["ssh", "-T", "-i", key, "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes",
"-o", "ConnectTimeout=10", "-o", "StrictHostKeyChecking=accept-new",
f"{user}@{host}", command], text=True, capture_output=True, timeout=30)
if result.returncode:
raise RuntimeError(f"Cannot verify runtime on {host} (SSH exit {result.returncode}); refusing to assume it is stopped")
return result.stdout
def services(host, user, key):
output = remote(host, user, key, """set -eu
for unit in k3s kubelet; do
status="$(systemctl is-active "$unit" 2>/dev/null || true)"
case "$status" in
active|activating|reloading|deactivating) printf '%s=running\\n' "$unit" ;;
inactive|failed|unknown) printf '%s=stopped\\n' "$unit" ;;
*) echo "Cannot determine $unit state" >&2; exit 1 ;;
esac
done
listeners="$(ss -lntH 'sport = :6443')" || exit 1
if [ -n "$listeners" ]; then echo api=running; else echo api=stopped; fi
""")
values = dict(line.split("=", 1) for line in output.splitlines() if "=" in line)
if set(values) != {"k3s", "kubelet", "api"}:
raise RuntimeError(f"Ambiguous runtime probe on {host}")
return values
def check(profile=None, vm_start=False):
inventory = yaml.safe_load(Path(os.environ.get("HOMELAB_INVENTORY_FILE", REPO / "homelab.yml")).read_text())
profiles = inventory["cluster"]["profiles"]
selected = profile or os.environ.get("LAB_CLUSTER_PROFILE") or inventory["cluster"]["active_profile"]
if selected not in ("debian", "pimox", "k3s") or selected not in profiles:
raise RuntimeError("Select one of the canonical profiles: debian, pimox, k3s")
runtime = profiles[selected].get("runtime", "kubeadm")
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}")
laptop = inventory["hosts"]["debian"]
hypervisor = inventory["hosts"]["opi5_pimox"]
laptop_key = profiles["debian"]["control_plane"]["ssh_key_path"]
hyper_key = os.environ.get("LAB_PIMOX_SSH_KEY_PATH") or profiles["k3s"]["control_plane"]["ssh_key_path"]
laptop_state = services(laptop["lan_ip"], laptop["user"], laptop_key)
hyper_state = services(hypervisor["lan_ip"], hypervisor["user"], hyper_key)
output = remote(hypervisor["lan_ip"], hypervisor["user"], hyper_key, "sudo -n qm list")
vms = {}
for line in output.splitlines():
fields = line.split()
if fields and fields[0].isdigit():
if len(fields) < 3 or fields[2] not in ("running", "stopped", "paused", "suspended"):
raise RuntimeError("Cannot determine Pimox VM state")
vms[int(fields[0])] = fields[2]
if not output.strip() or "VMID" not in output:
raise RuntimeError("Cannot verify Pimox VM inventory")
cp_vmid = int(profiles["pimox"]["pimox"]["control_plane_vmid"])
conflicts = []
if laptop_state["k3s"] == "running":
conflicts.append("unexpected laptop k3s service is running on " + laptop["lan_ip"])
if hyper_state["kubelet"] == "running":
conflicts.append("unexpected host kubeadm kubelet is running on " + hypervisor["lan_ip"])
if runtime == "k3s":
if vm_start:
conflicts.append("VM startup is incompatible with the selected direct-host k3s profile")
if laptop_state["kubelet"] == "running" or laptop_state["api"] == "running":
conflicts.append("Debian laptop control plane is running")
active_vms = [str(vmid) for vmid, state in vms.items() if state != "stopped"]
if active_vms:
conflicts.append("Pimox VMs are not stopped: " + ", ".join(active_vms))
else:
if hyper_state["k3s"] == "running" or hyper_state["api"] == "running":
conflicts.append("Orange Pi host K3s/control-plane API is running")
if selected == "pimox" and (laptop_state["kubelet"] == "running" or laptop_state["api"] == "running"):
conflicts.append("Debian laptop control plane is running")
if selected == "debian" and vms.get(cp_vmid, "stopped") != "stopped":
conflicts.append(f"Pimox control-plane VM {cp_vmid} is not stopped")
if conflicts:
raise RuntimeError("; ".join(conflicts) + ". Stop the conflicting runtime before continuing; no runtime was changed.")
return {"profile": selected, "exclusive": True, "laptop": laptop_state,
"orange_pi": hyper_state, "vms": vms}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=("check", "run"))
parser.add_argument("--profile")
parser.add_argument("--vm-start", action="store_true")
arguments = sys.argv[1:]
command = []
if "--" in arguments:
separator = arguments.index("--")
command = arguments[separator + 1:]
arguments = arguments[:separator]
args = parser.parse_args(arguments)
try:
if args.action == "run":
state = Path(os.environ.get("HOMELAB_STATE_DIR", Path.home() / ".local/share/homelab"))
root = state / "clusters"
root.mkdir(parents=True, exist_ok=True)
lock = (root / ".runtime-pipeline.lock").open("a")
try:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
raise RuntimeError("Another cluster pipeline holds the global runtime lock; wait for it to finish")
selected = check(args.profile, args.vm_start)["profile"]
if not command:
raise RuntimeError("Runtime-guarded execution requires a command")
os.set_inheritable(lock.fileno(), True)
environment = dict(os.environ, JEANNIE_RUNTIME_PIPELINE_LOCK=selected,
JEANNIE_RUNTIME_PIPELINE_LOCK_FD=str(lock.fileno()))
os.execvpe(command[0], command, environment)
else:
if command:
raise RuntimeError("The check action does not accept a command")
print(json.dumps(check(args.profile, args.vm_start), sort_keys=True))
except (RuntimeError, OSError, ValueError, KeyError, yaml.YAMLError, subprocess.SubprocessError) as error:
print(f"Cluster runtime refused: {error}", file=sys.stderr)
sys.exit(1)

View File

@ -227,6 +227,9 @@ def prepare_local(args, path, existing_pv):
try:
run(source_ssh("true"), timeout=15)
except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
native_state = run(hyper_ssh("systemctl is-active k3s 2>/dev/null || true"), timeout=20)
if native_state not in ("inactive", "failed", "unknown"):
raise RuntimeError("Stop Orange Pi host K3s before temporarily starting a source VM for registry migration")
status = run(hyper_ssh(f"sudo -n qm status {args.source_vmid}"), timeout=20)
if status == "status: stopped":
config = run(hyper_ssh(f"sudo -n qm config {args.source_vmid}"), timeout=20)