my-homelab-configs/scripts/cluster_runtime_context.py

121 lines
6.4 KiB
Python

#!/usr/bin/env python3
"""Resolve the selected cluster consistently for CLI, API and background tools."""
import argparse
import importlib.util
import json
import os
from pathlib import Path
import shlex
import tempfile
import sys
import yaml
REPO = Path(__file__).resolve().parents[1]
def state_root():
return Path(os.environ.get("HOMELAB_STATE_DIR", Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local/share")) / "homelab"))
def resolve(profile=None, follow_active=False):
inventory = yaml.safe_load(Path(os.environ.get("HOMELAB_INVENTORY_FILE", REPO / "homelab.yml")).read_text())
selection = state_root() / "active-cluster.json"
saved = json.loads(selection.read_text())["profile"] if not profile and selection.is_file() else None
background = os.environ.get("JEANNIE_REMOTE_SERVER") == "true" or os.environ.get("JEANNIE_SERVICE_CONTEXT") == "true"
inherited = None if follow_active else (os.environ.get("JEANNIE_CLUSTER_PROFILE_PIN") if background else os.environ.get("LAB_CLUSTER_PROFILE"))
selected = profile or inherited or saved or inventory["cluster"]["active_profile"]
if selected not in inventory["cluster"]["profiles"]:
raise ValueError(f"Undeclared cluster profile: {selected}")
settings = inventory["cluster"]["profiles"][selected]
control = settings["control_plane"]
root = state_root() / "clusters" / selected
binding = root / "identity.json"
identity = json.loads(binding.read_text()) if binding.is_file() else {}
return {"profile": selected, "runtime": settings.get("runtime", "kubeadm"),
"kubeconfig": str(Path(control["kubeconfig"]).expanduser()),
"node": control["node_name"], "host": control["lan_ip"],
"user": control.get("user", inventory.get("metadata", {}).get("owner_user", "jv")),
"key": control.get("ssh_key_path", str(Path.home() / ".ssh/id_ed25519")),
"required_mount": settings.get("storage", {}).get("required_mount", ""),
"runtime_path": settings.get("storage", {}).get("runtime_path", ""),
"root": str(root), "uid": identity.get("kube_system_uid", ""), "inventory": inventory}
def environment(profile=None):
selected = resolve(profile)
result = dict(os.environ)
result.update(LAB_CLUSTER_PROFILE=selected["profile"], LAB_CLUSTER_RUNTIME=selected["runtime"],
JEANNIE_CLUSTER_PROFILE_PIN=selected["profile"],
LAB_KUBECONFIG_PATH=selected["kubeconfig"], KUBECONFIG=selected["kubeconfig"],
KUBECONFIG_PATH=selected["kubeconfig"], TF_VAR_kubeconfig_path=selected["kubeconfig"],
TF_VAR_cluster_runtime=selected["runtime"], LAB_CONTROL_PLANE_NODE=selected["node"],
TF_VAR_cluster_profile=selected["profile"],
LAB_CLUSTER_IDENTITY_UID=selected["uid"], TF_VAR_cluster_identity_uid=selected["uid"],
LAB_CLUSTER_CONTROL_PLANE_NODE_NAME=selected["node"],
LAB_CLUSTER_CONTROL_PLANE_LAN_IP=selected["host"],
LAB_CLUSTER_CONTROL_PLANE_USER=selected["user"],
LAB_CLUSTER_CONTROL_PLANE_SSH_KEY_PATH=selected["key"],
TF_VAR_control_plane_node_name=selected["node"], TF_VAR_control_plane_host=selected["host"],
TF_VAR_control_plane_advertise_address=selected["host"],
TF_VAR_control_plane_user=selected["user"], TF_VAR_control_plane_ssh_key_path=selected["key"],
LAB_CLUSTER_REQUIRED_DATA_MOUNT=selected["required_mount"],
LAB_CLUSTER_RUNTIME_STORAGE_PATH=selected["runtime_path"])
return result
def persist(profile):
selected = resolve(profile)
spec = importlib.util.spec_from_file_location("selected_cluster_identity", REPO / "scripts/cluster-context.py")
context = importlib.util.module_from_spec(spec)
spec.loader.exec_module(context)
# Selection is also allowed for a stopped cluster so start-cluster can
# recover it. Mutations still require their own live namespace UID check.
context.Context(profile, selected["kubeconfig"]).observed(startup=True)
directory = state_root()
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
descriptor, temporary = tempfile.mkstemp(prefix=".active-cluster-", dir=directory)
try:
with os.fdopen(descriptor, "w") as handle:
json.dump({"profile": profile}, handle)
handle.write("\n")
os.replace(temporary, directory / "active-cluster.json")
finally:
if Path(temporary).exists():
Path(temporary).unlink()
return selected
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=("shell", "show", "select"), default="show", nargs="?")
parser.add_argument("profile", nargs="?")
args = parser.parse_args()
if args.action == "select":
if not args.profile:
parser.error("select requires a profile")
value = persist(args.profile)
else:
value = resolve(args.profile)
if args.action == "shell":
for key, value in environment(args.profile).items():
if key in {"LAB_CLUSTER_PROFILE", "LAB_CLUSTER_RUNTIME", "LAB_KUBECONFIG_PATH", "KUBECONFIG", "KUBECONFIG_PATH",
"TF_VAR_kubeconfig_path", "TF_VAR_cluster_runtime", "TF_VAR_cluster_profile", "LAB_CLUSTER_IDENTITY_UID", "TF_VAR_cluster_identity_uid", "LAB_CONTROL_PLANE_NODE",
"LAB_CLUSTER_CONTROL_PLANE_NODE_NAME", "LAB_CLUSTER_CONTROL_PLANE_LAN_IP",
"LAB_CLUSTER_CONTROL_PLANE_USER", "LAB_CLUSTER_CONTROL_PLANE_SSH_KEY_PATH",
"LAB_CLUSTER_REQUIRED_DATA_MOUNT", "LAB_CLUSTER_RUNTIME_STORAGE_PATH", "JEANNIE_CLUSTER_PROFILE_PIN"}:
print(f"export {key}={shlex.quote(value)}")
elif key.startswith("TF_VAR_control_plane_") and key in {"TF_VAR_control_plane_node_name", "TF_VAR_control_plane_host", "TF_VAR_control_plane_advertise_address", "TF_VAR_control_plane_user", "TF_VAR_control_plane_ssh_key_path"}:
print(f"export {key}={shlex.quote(value)}")
else:
print(json.dumps({key: item for key, item in value.items() if key != "inventory"}, indent=2))
if __name__ == "__main__":
try:
main()
except (OSError, ValueError, KeyError, RuntimeError) as error:
print(f"Cluster profile selection refused: {error}", file=sys.stderr)
raise SystemExit(1)