diff --git a/bootstrap/platform/main.tf b/bootstrap/platform/main.tf index da488fc..d9779e2 100644 --- a/bootstrap/platform/main.tf +++ b/bootstrap/platform/main.tf @@ -2045,7 +2045,7 @@ resource "helm_release" "prometheus_stack" { routes = [ { receiver = "jeannie-self-heal" - matchers = ["alertname =~ \"HomelabNodeDiskPressure|HomelabHostFilesystemNearlyFull|FreeDiskSpaceFailed|HomelabStaleResidualPods|KubePodContainerStatusUnknown|KubePodEvicted|JeannieApiMetricsDown\""] + matchers = ["alertname =~ \"HomelabNodeDiskPressure|HomelabNodeImageFilesystemPressure|HomelabHostFilesystemNearlyFull|FreeDiskSpaceFailed|HomelabStaleResidualPods|KubePodContainerStatusUnknown|KubePodEvicted|JeannieApiMetricsDown|KubeNodeNotReady|KubeAPIDown|KubeletDown\""] repeat_interval = "1h" } ] @@ -2094,6 +2094,7 @@ resource "helm_release" "prometheus_stack" { } prometheus = { prometheusSpec = { + externalLabels = { cluster_profile = var.cluster_profile, cluster_uid = var.cluster_identity_uid } priorityClassName = kubernetes_priority_class_v1.monitoring.metadata[0].name nodeSelector = local.prometheus_stack_node_selector retention = var.observability.prometheus.retention diff --git a/bootstrap/platform/variables.tf b/bootstrap/platform/variables.tf index db20e28..4ef4870 100644 --- a/bootstrap/platform/variables.tf +++ b/bootstrap/platform/variables.tf @@ -330,6 +330,18 @@ variable "prometheus_stack_node_selector" { } } +variable "cluster_profile" { + description = "Selected cluster profile attached to monitoring alerts and diagnostics." + type = string + default = "unselected" +} + +variable "cluster_identity_uid" { + description = "Pinned kube-system UID attached to alerts to reject events from retired clusters." + type = string + default = "" +} + variable "tetragon_agent_enabled" { description = "Enable the Tetragon agent after the pipeline finds at least one node with kernel BTF." type = bool diff --git a/cmd/jeannie-core/main.go b/cmd/jeannie-core/main.go index b62230b..0fae7e5 100644 --- a/cmd/jeannie-core/main.go +++ b/cmd/jeannie-core/main.go @@ -275,7 +275,12 @@ func runReportRender(args []string, in io.Reader, out io.Writer) error { if *asJSON { encoder := json.NewEncoder(out) encoder.SetIndent("", " ") - return encoder.Encode(map[string]any{"title": *title, "rows": rows}) + return encoder.Encode(map[string]any{"title": *title, "rows": rows, "cluster": map[string]string{ + "profile": os.Getenv("LAB_CLUSTER_PROFILE"), + "runtime": os.Getenv("LAB_CLUSTER_RUNTIME"), + "kubeconfig": os.Getenv("KUBECONFIG_PATH"), + "uid": os.Getenv("LAB_CLUSTER_IDENTITY_UID"), + }}) } renderReportText(out, *title, rows, *details, *only) @@ -379,6 +384,9 @@ func renderReportText(out io.Writer, title string, rows []reportRow, details boo fmt.Fprintln(out, title) fmt.Fprintln(out, strings.Repeat("=", len(title))) + if profile := os.Getenv("LAB_CLUSTER_PROFILE"); profile != "" { + fmt.Fprintf(out, "profile=%s runtime=%s kubeconfig=%s\n", profile, os.Getenv("LAB_CLUSTER_RUNTIME"), os.Getenv("KUBECONFIG_PATH")) + } fmt.Fprintf(out, "fail=%d warn=%d ok=%d skip=%d\n", counts["fail"], counts["warn"], counts["ok"], counts["skip"]) if len(rows) == 0 { @@ -505,7 +513,7 @@ func diagnoseReportRow(row reportRow) reportDiagnosis { diagnosis.Mitigate = "Validate the same endpoint with a direct HTTP/TLS probe from the closest hop, then restart/reapply the proxy or control-plane component that owns TLS termination." diagnosis.Redesign = "Terminate TLS at a single intentional layer and keep cache/proxy compression disabled for identity/control-plane paths." case containsAny(text, "imagepullbackoff", "errimagepull", "server gave http response to https client", "failed to pull", "manifest unknown", "pull access denied"): - diagnosis.Cause = "A node cannot pull the image it was scheduled to run. Likely causes are unsigned/stale tag, missing image, insecure registry config drift, or the registry endpoint not reachable from Pimox workers." + diagnosis.Cause = "A node cannot pull the image it was scheduled to run. Likely causes are unsigned/stale tag, missing image, insecure registry config drift, or the registry endpoint not reachable from the selected cluster nodes." diagnosis.Mitigate = "Run the apps pipeline to rebuild/sign/push the image, verify worker access to the registry, and restart only the affected deployment." diagnosis.Redesign = "Make registry endpoint, insecure registry setup, signing policy, and image overrides generated from the same profile inputs." case containsAny(text, "containerstatusunknown", "evicted"): @@ -518,8 +526,8 @@ func diagnoseReportRow(row reportRow) reportDiagnosis { diagnosis.Redesign = "Keep node labels and workload placement policy generated per cluster profile so migration does not strand workloads." case containsAny(text, "notready", "node(s) not ready", "node pressure", "diskpressure", "memorypressure", "pidpressure"): diagnosis.Cause = "A Kubernetes node is unhealthy or under pressure. On Pimox this often points to VM health, CPU pinning, storage health, kubelet/containerd, or CNI readiness." - diagnosis.Mitigate = "Check the specific node condition, kubelet status, and Pimox VM state before restarting workloads; recover the node first." - diagnosis.Redesign = "Add capacity guardrails and profile-specific VM sizing/pinning so the cluster stays inside OPI5/Pimox limits." + diagnosis.Mitigate = "Run doctor-cluster for the selected profile. Check K3s service and its data mount for native nodes, or kubelet and VM state for virtual nodes; recover the node first." + diagnosis.Redesign = "Keep capacity and storage checks tied to the selected runtime, including native data mounts and VM sizing." case containsAny(text, "qemu guest agent is not running", "guest agent", "pimox", "input/output error"): diagnosis.Cause = "The virtualization layer is unhealthy or unreachable. Likely causes are Pimox storage trouble, stopped/stuck VM, guest-agent failure, or CPU/storage pressure." diagnosis.Mitigate = "Check Pimox storage and VM status first; avoid rebuilding Kubernetes until the VM and disk layer are healthy." diff --git a/cmd/jeannie-server/main.go b/cmd/jeannie-server/main.go index 0a2b905..ebb1cf4 100644 --- a/cmd/jeannie-server/main.go +++ b/cmd/jeannie-server/main.go @@ -30,7 +30,7 @@ var allowedCommands = map[string]bool{ "cluster-profile": true, "cluster-runtime": true, "cluster-transition": 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, + "status": true, "capacity": true, "capacity-advisor": true, "capacity-limits": true, "recover-plan": true, "gitops-status": true, "gitops": true, "storage": true, @@ -288,7 +288,7 @@ func (s *server) run(item *execution) { args := append([]string{item.Command}, item.Args...) command := exec.CommandContext(ctx, filepath.Join(s.repoRoot, "jeannie"), args...) command.Dir = s.repoRoot - command.Env = append(os.Environ(), "JEANNIE_REMOTE_SERVER=true") + command.Env = jeannieworkflow.CommandEnvironment() output, err := command.CombinedOutput() if len(output) > maxOutputBytes { output = append(output[:maxOutputBytes], []byte("\n[output truncated]\n")...) diff --git a/docs/app-ops.md b/docs/app-ops.md index 1befa62..db5d6f0 100644 --- a/docs/app-ops.md +++ b/docs/app-ops.md @@ -1,5 +1,30 @@ # Application Operations +## Profile-aware diagnostics and healing + +Persist the operational cluster on the Debian deployment host with +`./jeannie cluster-profile select k3s` (also supports `debian` and `pimox`). +CLI, API/Temporal jobs, and self-healing share this selection. Remote/service +commands replace stale kubeconfig/runtime variables; local commands can select +another declared profile with `LAB_CLUSTER_PROFILE`. Selection does not start +or stop runtimes. Reports print the chosen profile and kubeconfig. + +`status`, `doctor-cluster`, `doctor-homelab`, mesh, capacity, GitOps, and recovery +tools use the selected control plane. Native K3s checks the Orange Pi service, +SSD mount, nodes, and bundled CRI. Stopped Pimox VMs are expected in that profile; +VM restart and singleton drain actions are refused. Kubeadm profiles retain VM +checks and worker recovery. `./jeannie workers disk-status control-plane` inspects +native runtime storage; `disk-cleanup control-plane --yes` prunes unused images +and host journals after identity, data-mount, and registry checks. + +After updating, run `./jeannie platform monitoring` and +`./jeannie self-heal install-service --apply`. Prometheus attaches profile and +namespace UID labels; automatic healing skips missing or mismatched labels. +Saved doctor reports also require matching cluster metadata. Audit logs and +healing cooldowns live under `clusters/` in the homelab state directory. +Native datastore/PVC backup coverage still needs separate verification; a VM +archive alone does not back up native K3s. + ## Tetragon kernel capability Platform applies probe `/sys/kernel/btf/vmlinux` over SSH on each live node diff --git a/docs/jeannie-remote-api.md b/docs/jeannie-remote-api.md index 75c4621..bfa5681 100644 --- a/docs/jeannie-remote-api.md +++ b/docs/jeannie-remote-api.md @@ -77,3 +77,37 @@ LAN address or a local DNS override. Direct backend testing remains: Through the canonical gateway, use the API hostname and the OCI edge address. For a controlled test without changing DNS, use `curl --resolve` with the edge public IP. + +### Operational cluster selection + +CLI diagnostics, remote API/Temporal jobs, and the self-heal webhook share the +inventory profile resolver. Persist the intended enrolled cluster on Debian: + +```bash +./jeannie cluster-profile select k3s +./jeannie cluster-context check +``` + +The selection is stored in `~/.local/share/homelab/active-cluster.json` under the +execution user's state directory. API and service commands read it for each +operation and replace stale inherited kubeconfig/runtime variables. One operation +keeps its selected profile throughout execution. Local interactive commands may +override it using `LAB_CLUSTER_PROFILE`; successful cluster startup, platform, +and apps runs remember that selection. Selecting a profile does not switch the +running runtime; runtime exclusivity and pinned identity checks still apply. + +The same selection command is available through the API allowlist: + +```bash +./jeannie remote cluster-profile select k3s +./jeannie remote status +./jeannie remote doctor-cluster +``` + +`status` and doctor reports include profile, runtime, kubeconfig, and enrolled +namespace UID. Healing refuses reports from a different cluster incarnation. +After updating this code, redeploy `./jeannie platform monitoring` and reinstall +`./jeannie self-heal install-service --apply` to activate matching alert identity +labels and the updated webhook. Rebuild/redeploy the API once with +`./jeannie deploy-api` to update both Go execution paths. After that, changing +the saved selection requires no API or Temporal restart. diff --git a/docs/templates/app-ops.md.tmpl b/docs/templates/app-ops.md.tmpl index 9299f82..acebc40 100644 --- a/docs/templates/app-ops.md.tmpl +++ b/docs/templates/app-ops.md.tmpl @@ -1,5 +1,30 @@ # Application Operations +## Profile-aware diagnostics and healing + +Persist the operational cluster on the Debian deployment host with +`./jeannie cluster-profile select k3s` (also supports `debian` and `pimox`). +CLI, API/Temporal jobs, and self-healing share this selection. Remote/service +commands replace stale kubeconfig/runtime variables; local commands can select +another declared profile with `LAB_CLUSTER_PROFILE`. Selection does not start +or stop runtimes. Reports print the chosen profile and kubeconfig. + +`status`, `doctor-cluster`, `doctor-homelab`, mesh, capacity, GitOps, and recovery +tools use the selected control plane. Native K3s checks the Orange Pi service, +SSD mount, nodes, and bundled CRI. Stopped Pimox VMs are expected in that profile; +VM restart and singleton drain actions are refused. Kubeadm profiles retain VM +checks and worker recovery. `./jeannie workers disk-status control-plane` inspects +native runtime storage; `disk-cleanup control-plane --yes` prunes unused images +and host journals after identity, data-mount, and registry checks. + +After updating, run `./jeannie platform monitoring` and +`./jeannie self-heal install-service --apply`. Prometheus attaches profile and +namespace UID labels; automatic healing skips missing or mismatched labels. +Saved doctor reports also require matching cluster metadata. Audit logs and +healing cooldowns live under `clusters/` in the homelab state directory. +Native datastore/PVC backup coverage still needs separate verification; a VM +archive alone does not back up native K3s. + ## Tetragon kernel capability Platform applies probe `/sys/kernel/btf/vmlinux` over SSH on each live node diff --git a/infra/jeannie-eventd/README.md b/infra/jeannie-eventd/README.md index 78aceb5..64d394e 100644 --- a/infra/jeannie-eventd/README.md +++ b/infra/jeannie-eventd/README.md @@ -3,12 +3,17 @@ Install or reconcile the webhook from the checkout used for operations: ```bash -LAB_CLUSTER_PROFILE=pimox ./jeannie self-heal install-service --apply +./jeannie cluster-profile select k3s +./jeannie platform monitoring +./jeannie self-heal install-service --apply ``` -The installer records the selected profile, explicit kubeconfig, and current -checkout path in the systemd unit. It restarts the webhook so new source and -environment settings take effect. Without `--apply`, installation defaults to +Use `debian`, `pimox`, or `k3s` as declared in inventory. Selection verifies the +enrolled endpoint and CA and persists the operational profile; it does not start +or stop a cluster. The service resolves that selection for each incoming event, +then pins it for the complete operation. Stale profile/kubeconfig environment +variables in existing systemd overrides do not choose the target. The installer +restarts the webhook to load new source. Without `--apply`, installation defaults to dry-run mode unless `LAB_SELF_HEAL_APPLY=true` is explicitly supplied. The rendered file is staged with its `.service` filename and checked using `systemd-analyze verify --man=no` on Debian before replacing the installed unit. @@ -19,11 +24,22 @@ An invalid rendered unit therefore leaves the existing unit file untouched. They do not invoke the broad doctor planner or choose unrelated VM restarts. The cleanup only selects supported residual states on controller-owned pods; Completed/Succeeded and ordinary Pending pods are not cleanup targets. It does -not delete PVCs or change worker CPU configuration. Debian automatic disk -cleanup remains disabled. +not delete PVCs or change worker CPU configuration. Native K3s disk alerts use +the declared host and bundled `k3s crictl`, never worker VM operations. Cleanup +requires a live pinned identity, the data mount, and reachable registry, then +prunes unused images and vacuums host journals. Debian laptop automatic disk +cleanup remains disabled. A native single-node cluster cannot be drained through +the worker maintenance command. + +Automatic actions require every alert to carry matching `cluster_profile` and +`cluster_uid` labels. Deploy `platform monitoring` to publish these external +labels before enabling automatic healing. Retired-cluster alerts are skipped. +Node/API alerts can use the guarded runtime startup action; an offline startup +check validates the enrolled endpoint and CA, followed by a live UID check after +startup. Mutations such as pod cleanup always require the live UID. Doctor stdout and stderr are stored separately under -`~/.local/share/homelab/self-heal-events//`. The `.log` file contains +`~/.local/share/homelab/clusters//self-heal-events//`. The `.log` file contains stdout (JSON for the doctor), `.stderr.log` contains diagnostics, and `result.json` records the chosen command and outcome. Generic cleanup verification checks eligible residual records rather than requiring all @@ -34,7 +50,8 @@ Read-only validation: ```bash systemctl is-active jeannie-eventd systemctl show jeannie-eventd -p Environment --value -LAB_CLUSTER_PROFILE=pimox ./jeannie heal cleanup-stale-pods +./jeannie heal cleanup-stale-pods +./jeannie workers disk-status control-plane # native K3s ``` Alertmanager repeats matching firing alerts according to its configured route diff --git a/infra/jeannie-eventd/alertmanager-route.example.yaml b/infra/jeannie-eventd/alertmanager-route.example.yaml index 53305be..ee66234 100644 --- a/infra/jeannie-eventd/alertmanager-route.example.yaml +++ b/infra/jeannie-eventd/alertmanager-route.example.yaml @@ -2,7 +2,7 @@ route: receiver: default routes: - matchers: - - alertname =~ "HomelabNodeDiskPressure|HomelabHostFilesystemNearlyFull|FreeDiskSpaceFailed|HomelabStaleResidualPods|KubePodContainerStatusUnknown|KubePodEvicted|JeannieApiMetricsDown" + - alertname =~ "HomelabNodeDiskPressure|HomelabNodeImageFilesystemPressure|HomelabHostFilesystemNearlyFull|FreeDiskSpaceFailed|HomelabStaleResidualPods|KubePodContainerStatusUnknown|KubePodEvicted|JeannieApiMetricsDown|KubeNodeNotReady|KubeAPIDown|KubeletDown" receiver: jeannie-self-heal repeat_interval: 1h diff --git a/infra/jeannie-eventd/jeannie-eventd.service b/infra/jeannie-eventd/jeannie-eventd.service index 32dc262..ffabafd 100644 --- a/infra/jeannie-eventd/jeannie-eventd.service +++ b/infra/jeannie-eventd/jeannie-eventd.service @@ -7,9 +7,7 @@ Wants=network-online.target Type=simple User=jv WorkingDirectory=/home/jv/my-homelab-configs -Environment=LAB_CLUSTER_PROFILE=pimox -Environment=KUBECONFIG=/home/jv/.kube/pimox-config -Environment=LAB_KUBECONFIG_PATH=/home/jv/.kube/pimox-config +Environment=JEANNIE_SERVICE_CONTEXT=true Environment=LAB_SELF_HEAL_HOST=0.0.0.0 Environment=LAB_SELF_HEAL_PORT=18081 Environment=LAB_SELF_HEAL_APPLY=false diff --git a/internal/jeannieworkflow/environment_test.go b/internal/jeannieworkflow/environment_test.go new file mode 100644 index 0000000..54e7ed1 --- /dev/null +++ b/internal/jeannieworkflow/environment_test.go @@ -0,0 +1,22 @@ +package jeannieworkflow + +import ( + "strings" + "testing" +) + +func TestNewExecutionDropsInheritedProfilePin(t *testing.T) { + t.Setenv("JEANNIE_CLUSTER_PROFILE_PIN", "pimox") + t.Setenv("JEANNIE_REMOTE_SERVER", "false") + t.Setenv("JEANNIE_SERVER_ADDR", "127.0.0.1:8787") + environment := CommandEnvironment() + for _, entry := range environment { + if strings.HasPrefix(entry, "JEANNIE_CLUSTER_PROFILE_PIN=") { + t.Fatal("new operation retained the previous operation's profile pin") + } + } + joined := strings.Join(environment, "\n") + if !strings.Contains(joined, "JEANNIE_REMOTE_SERVER=true") || !strings.Contains(joined, "JEANNIE_SERVER_ADDR=127.0.0.1:8787") { + t.Fatal("new operation lost its remote flag or unrelated configuration") + } +} diff --git a/internal/jeannieworkflow/workflow.go b/internal/jeannieworkflow/workflow.go index 452e55a..9b9b009 100644 --- a/internal/jeannieworkflow/workflow.go +++ b/internal/jeannieworkflow/workflow.go @@ -5,6 +5,7 @@ import ( "os" "os/exec" "path/filepath" + "strings" "time" "go.temporal.io/sdk/temporal" @@ -27,6 +28,19 @@ type CommandResult struct { ExitCode int } +// A new API/Temporal execution follows the saved selection. Only descendants +// of that execution inherit its resolved profile pin. +func CommandEnvironment() []string { + var result []string + for _, entry := range os.Environ() { + if strings.HasPrefix(entry, "JEANNIE_CLUSTER_PROFILE_PIN=") || strings.HasPrefix(entry, "JEANNIE_REMOTE_SERVER=") { + continue + } + result = append(result, entry) + } + return append(result, "JEANNIE_REMOTE_SERVER=true") +} + func Workflow(ctx workflow.Context, input CommandInput) (CommandResult, error) { options := workflow.ActivityOptions{ StartToCloseTimeout: 30 * time.Minute, @@ -46,7 +60,7 @@ func Run(ctx context.Context, input CommandInput) (CommandResult, error) { args := append([]string{input.Command}, input.Args...) command := exec.CommandContext(ctx, filepath.Join(input.RepoRoot, "jeannie"), args...) command.Dir = input.RepoRoot - command.Env = append(os.Environ(), "JEANNIE_REMOTE_SERVER=true") + command.Env = CommandEnvironment() output, err := command.CombinedOutput() result := CommandResult{Output: string(output)} if err == nil { diff --git a/jeannie b/jeannie index 69fc16d..189f227 100755 --- a/jeannie +++ b/jeannie @@ -37,8 +37,9 @@ trap 'rm -f "${BUILDX_CONFIG}"' EXIT # edge VM's public IP takes precedence over the static bootstrap inventory. oci_foundation_load_config load_homelab_inventory_defaults +source "${REPO_ROOT}/scripts/cluster-env.sh" export_homelab_inventory_tf_vars -KUBECONFIG_PATH="${KUBECONFIG_PATH:-${TF_VAR_kubeconfig_path:-${LAB_KUBECONFIG_PATH:-/home/jv/.kube/config}}}" +export KUBECONFIG_PATH="${LAB_KUBECONFIG_PATH}" cluster_context_enable print_usage() { @@ -49,7 +50,7 @@ Base, Inventory, And Planning help | -h | --help Show this grouped help. validate Run repo validation checks. inventory-check Validate the canonical homelab inventory. - cluster-profile Print the resolved active cluster profile. + cluster-profile [select NAME] Show or persist the operational profile for CLI/API/self-healing. 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. @@ -319,7 +320,11 @@ case "${1:-}" in plan_homelab "${2:-all}" ;; cluster-profile) - cluster_profile_report + if [[ "${2:-}" == select ]]; then + python3 "${REPO_ROOT}/scripts/cluster_runtime_context.py" select "${3:?Select a declared profile}" + else + cluster_profile_report + fi ;; rebuild-cluster) record_change_journal "rebuild-cluster" "$@" diff --git a/lib/jeannie/cluster-context.sh b/lib/jeannie/cluster-context.sh index 25c44b2..7586d53 100644 --- a/lib/jeannie/cluster-context.sh +++ b/lib/jeannie/cluster-context.sh @@ -21,6 +21,10 @@ retire_debian_service_hooks() { python3 "${REPO_ROOT}/scripts/retire-debian-service-hooks.py" } +remember_cluster_profile() { + python3 "${REPO_ROOT}/scripts/cluster_runtime_context.py" select "${LAB_CLUSTER_PROFILE}" >/dev/null +} + cluster_context_enable() { export HOMELAB_STATE_DIR LAB_CLUSTER_PROFILE KUBECONFIG_PATH case ":${PATH}:" in diff --git a/lib/jeannie/commands.sh b/lib/jeannie/commands.sh index 16b34de..08b23d6 100644 --- a/lib/jeannie/commands.sh +++ b/lib/jeannie/commands.sh @@ -1088,6 +1088,7 @@ start_cluster() { '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 + remember_cluster_profile || return 1 return 0 fi cluster_worker_targets @@ -1118,6 +1119,7 @@ start_cluster() { 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." + remember_cluster_profile || return 1 } cleanup_debian_k8s_after_pimox_offload() { @@ -1515,7 +1517,7 @@ status_kubernetes_api_ok() { echo "kubeconfig missing: ${KUBECONFIG_PATH}" >&2 return 1 fi - kubectl --kubeconfig "${KUBECONFIG_PATH}" get --raw=/readyz >/dev/null + kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s get --raw=/readyz >/dev/null } status_kubernetes_nodes_ready() { @@ -1692,8 +1694,8 @@ status_registry_from_pimox_workers() { local key_path local output - if [[ "${LAB_CLUSTER_PROFILE:-debian}" != "pimox" ]]; then - echo "cluster profile is ${LAB_CLUSTER_PROFILE:-debian}; Pimox worker registry probe is not applicable" >&2 + if [[ "${LAB_CLUSTER_RUNTIME:-kubeadm}" == k3s ]]; then + echo "native K3s uses its control-plane registry probe" >&2 return 1 fi if [[ ! -s "${spec_file}" ]]; then @@ -1740,6 +1742,10 @@ status_rpi_uptime_kuma_ok() { } status_pimox_workers_running() { + if [[ "${LAB_CLUSTER_RUNTIME:-kubeadm}" == k3s ]]; then + echo "Native K3s uses the Orange Pi host; worker VMs are expected to be stopped." + return 0 + fi 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}}" @@ -1789,13 +1795,51 @@ status_pimox_control_plane_running() { pimox_ssh "${pimox_host}" "${pimox_user}" "${pimox_key}" "sudo '${qm_bin}' status '${vmid}' | grep -q 'status: running'" } -status_cluster_profile_pimox() { - if [[ "${LAB_CLUSTER_PROFILE:-debian}" != "pimox" ]]; then - echo "active cluster profile is ${LAB_CLUSTER_PROFILE:-debian}; expected pimox for post-migration doctor" >&2 +status_cluster_profile_valid() { + cluster_context_require_startup +} + +status_cluster_control_runtime() { + local unit=kubelet + [[ "${LAB_CLUSTER_RUNTIME:-kubeadm}" != k3s ]] || unit=k3s + ssh -n -i "${LAB_CLUSTER_CONTROL_PLANE_SSH_KEY_PATH}" \ + -o BatchMode=yes -o ConnectTimeout=8 -o StrictHostKeyChecking=accept-new \ + "${LAB_CLUSTER_CONTROL_PLANE_USER}@${LAB_CLUSTER_CONTROL_PLANE_LAN_IP}" \ + "systemctl is-active ${unit}" +} + +status_cluster_storage() { + if [[ "${LAB_CLUSTER_RUNTIME:-kubeadm}" != k3s ]]; then + check_pimox_storage + return + fi + local mount="${LAB_CLUSTER_REQUIRED_DATA_MOUNT:-}" + local runtime_check='mountpoint -q /var/lib/rancher/k3s && ' + [[ "${1:-runtime}" != bootstrap ]] || runtime_check='' + if [[ -n "${mount}" && "${mount}" =~ ^/[a-zA-Z0-9_./-]+$ && "${mount}" != *..* ]]; then + ssh -n -i "${LAB_CLUSTER_CONTROL_PLANE_SSH_KEY_PATH}" \ + -o BatchMode=yes -o ConnectTimeout=8 -o StrictHostKeyChecking=accept-new \ + "${LAB_CLUSTER_CONTROL_PLANE_USER}@${LAB_CLUSTER_CONTROL_PLANE_LAN_IP}" \ + "mountpoint -q '${mount}' && ${runtime_check}findmnt -n -M '${mount}' -o OPTIONS | grep -E '(^|,)rw(,|$)'" + else + echo "Native K3s data mount is not declared." >&2 return 1 fi } +status_registry_from_cluster_nodes() { + if [[ "${LAB_CLUSTER_RUNTIME:-kubeadm}" != k3s ]]; then + status_registry_from_pimox_workers + return + fi + local endpoint="${LAB_REGISTRY_ENDPOINT}" + [[ "${endpoint}" =~ ^[a-zA-Z0-9.:-]+$ ]] || return 1 + ssh -n -i "${LAB_CLUSTER_CONTROL_PLANE_SSH_KEY_PATH}" \ + -o BatchMode=yes -o ConnectTimeout=8 -o StrictHostKeyChecking=accept-new \ + "${LAB_CLUSTER_CONTROL_PLANE_USER}@${LAB_CLUSTER_CONTROL_PLANE_LAN_IP}" \ + "curl -fsS --connect-timeout 5 --max-time 10 'http://${endpoint}/v2/' >/dev/null" +} + status_external_services_host_declared() { if [[ -z "${LAB_SERVICES_HOST_LAN_IP:-${LAB_DEBIAN_LAN_IP:-}}" ]]; then echo "external services host LAN IP is not resolved from homelab.yml" >&2 @@ -1835,10 +1879,15 @@ status_cascade_report() { status_cascade_warn "RPi Tailscale IP" check_rpi_tailscale_ip status_cascade_warn "Uptime Kuma HTTP" status_rpi_uptime_kuma_ok - status_section "Pimox And Cluster" - status_cascade_check "Pimox storage" check_pimox_storage || failures=$((failures + 1)) - status_cascade_check "Pimox workers running" status_pimox_workers_running || failures=$((failures + 1)) + status_section "Cluster (${LAB_CLUSTER_PROFILE} / ${LAB_CLUSTER_RUNTIME})" + status_cascade_check "Cluster storage" status_cluster_storage || failures=$((failures + 1)) + status_cascade_check "Control-plane runtime" status_cluster_control_runtime || failures=$((failures + 1)) + status_cascade_check "Inactive profiles stopped" cluster_runtime_require || failures=$((failures + 1)) + if [[ "${LAB_CLUSTER_RUNTIME}" != k3s ]]; then + status_cascade_check "Pimox workers running" status_pimox_workers_running || failures=$((failures + 1)) + fi status_cascade_check "Kubernetes API" status_kubernetes_api_ok || failures=$((failures + 1)) + status_cascade_check "Cluster identity" cluster_context_require || failures=$((failures + 1)) status_cascade_check "Kubernetes nodes Ready" status_kubernetes_nodes_ready || failures=$((failures + 1)) status_cascade_warn "No problem pods" status_no_problem_pods @@ -2076,6 +2125,12 @@ status_kubernetes_problem_pods() { } status_pimox_workers() { + if [[ "${LAB_CLUSTER_RUNTIME:-kubeadm}" == k3s ]]; then + status_section "Native K3s" + status_run "K3s service" status_cluster_control_runtime + status_run "K3s data mount" status_cluster_storage + return + fi 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}}" @@ -2546,14 +2601,18 @@ doctor_cluster() { if [[ "${REPORT_UI_VERBOSE}" != "true" ]]; then report_ui_begin - report_ui_check fail "Host Runtime" "kubelet" "./jeannie start-cluster" "" "" check_systemd_active kubelet || failures=$((failures + 1)) - report_ui_check fail "Host Runtime" "containerd" "sudo systemctl restart containerd" "" "" check_systemd_active containerd || failures=$((failures + 1)) + report_ui_check fail "Cluster Runtime" "Control-plane runtime" "./jeannie start-cluster" "" "" status_cluster_control_runtime || failures=$((failures + 1)) + report_ui_check fail "Cluster Runtime" "Cluster storage" "./jeannie workers disk-status control-plane" "" "" status_cluster_storage || failures=$((failures + 1)) + report_ui_check fail "Cluster Runtime" "Inactive profiles stopped" "./jeannie cluster-runtime check" "" "" cluster_runtime_require || failures=$((failures + 1)) report_ui_check warn "Host Runtime" "docker" "sudo systemctl restart docker" "" "" check_systemd_active docker report_ui_check fail "Kubernetes" "API" "./jeannie start-cluster" "" "" status_kubernetes_api_ok || failures=$((failures + 1)) + report_ui_check fail "Kubernetes" "Cluster identity" "./jeannie cluster-context check" "" "" cluster_context_require || failures=$((failures + 1)) report_ui_check fail "Kubernetes" "Nodes Ready" "kubectl get nodes -o wide" "" "" status_kubernetes_nodes_ready || failures=$((failures + 1)) report_ui_check warn "Kubernetes" "Problem pods" "kubectl get pods -A -o wide" "" "" status_no_problem_pods - report_ui_check fail "Pimox" "Workers running" "./jeannie start-cluster" "" "" status_pimox_workers_running || failures=$((failures + 1)) - report_ui_check fail "Pimox" "Worker tailnet egress" "./jeannie workers tailnet" "" "" check_pimox_worker_tailnet_egress || failures=$((failures + 1)) + if [[ "${LAB_CLUSTER_RUNTIME}" != k3s ]]; then + report_ui_check fail "Pimox" "Workers running" "./jeannie start-cluster" "" "" status_pimox_workers_running || failures=$((failures + 1)) + report_ui_check fail "Pimox" "Worker tailnet egress" "./jeannie workers tailnet" "" "" check_pimox_worker_tailnet_egress || failures=$((failures + 1)) + fi report_ui_check fail "Networking" "Traefik LoadBalancer" "./jeannie doctor-edge" "" "" status_http_reachable "http://${LAB_TRAEFIK_LB_IP:?LAB_TRAEFIK_LB_IP is required from homelab.yml}/" || failures=$((failures + 1)) report_ui_render "Doctor Cluster" report_ui_cleanup @@ -2561,17 +2620,22 @@ doctor_cluster() { fi status_section "Doctor Cluster" - status_systemd_units kubelet containerd docker + status_run "selected control-plane runtime" status_cluster_control_runtime + status_run "selected cluster storage" status_cluster_storage status_kubernetes status_pimox_workers - status_run "pimox worker tailnet egress" check_pimox_worker_tailnet_egress + if [[ "${LAB_CLUSTER_RUNTIME}" != k3s ]]; then + status_run "pimox worker tailnet egress" check_pimox_worker_tailnet_egress + else + python3 "${REPO_ROOT}/scripts/k3s-node-diagnostics.py" status || failures=$((failures + 1)) + fi status_http "traefik lb" "http://${LAB_TRAEFIK_LB_IP:?LAB_TRAEFIK_LB_IP is required from homelab.yml}/" - printf '\n-- local CRI containers\n' - if command -v crictl >/dev/null 2>&1; then - sudo crictl ps -a | head -50 || true - else - printf 'crictl not installed\n' + if [[ "${LAB_CLUSTER_RUNTIME}" != k3s ]]; then + status_run "selected control-plane CRI" ssh -n -i "${LAB_CLUSTER_CONTROL_PLANE_SSH_KEY_PATH}" \ + -o BatchMode=yes -o ConnectTimeout=8 -o StrictHostKeyChecking=accept-new \ + "${LAB_CLUSTER_CONTROL_PLANE_USER}@${LAB_CLUSTER_CONTROL_PLANE_LAN_IP}" \ + 'sudo -n crictl ps -a | head -15' fi cat <<'EOF' @@ -2884,12 +2948,18 @@ doctor_homelab() { if [[ "${REPORT_UI_VERBOSE}" != "true" ]]; then report_ui_begin - report_ui_check fail "Architecture Boundary" "Pimox cluster profile" "LAB_CLUSTER_PROFILE=pimox ./jeannie up" "" "" status_cluster_profile_pimox || failures=$((failures + 1)) + report_ui_check fail "Architecture Boundary" "Selected cluster identity" "./jeannie cluster-context check" "" "" cluster_context_require || failures=$((failures + 1)) report_ui_check fail "Architecture Boundary" "External services host resolved" "./jeannie cluster-profile" "" "" status_external_services_host_declared || failures=$((failures + 1)) - report_ui_check fail "Pimox Runtime" "Pimox storage" "./jeannie doctor-cluster" "" "" check_pimox_storage || failures=$((failures + 1)) - report_ui_check fail "Pimox Runtime" "Control-plane VM running" "./jeannie start-cluster" "" "" status_pimox_control_plane_running || failures=$((failures + 1)) - report_ui_check fail "Pimox Runtime" "Worker VMs running" "./jeannie start-cluster" "" "" status_pimox_workers_running || failures=$((failures + 1)) + report_ui_check fail "Cluster Runtime" "Cluster storage" "./jeannie doctor-cluster" "" "" status_cluster_storage || failures=$((failures + 1)) + report_ui_check fail "Cluster Runtime" "Control-plane runtime" "./jeannie start-cluster" "" "" status_cluster_control_runtime || failures=$((failures + 1)) + report_ui_check fail "Cluster Runtime" "Inactive profiles stopped" "./jeannie cluster-runtime check" "" "" cluster_runtime_require || failures=$((failures + 1)) + if [[ "${LAB_CLUSTER_PROFILE}" == pimox ]]; then + report_ui_check fail "Pimox Runtime" "Control-plane VM running" "./jeannie start-cluster" "" "" status_pimox_control_plane_running || failures=$((failures + 1)) + fi + if [[ "${LAB_CLUSTER_RUNTIME}" != k3s ]]; then + report_ui_check fail "Pimox Runtime" "Worker VMs running" "./jeannie start-cluster" "" "" status_pimox_workers_running || failures=$((failures + 1)) + fi report_ui_check fail "Kubernetes" "API ready" "./jeannie start-cluster" "" "" status_kubernetes_api_ok || failures=$((failures + 1)) report_ui_check fail "Kubernetes" "Nodes Ready" "kubectl get nodes -o wide" "" "" status_kubernetes_nodes_ready || failures=$((failures + 1)) @@ -2909,7 +2979,7 @@ doctor_homelab() { report_ui_check fail "Applications" "n8n deployment" "./jeannie apps" "" "" status_kubernetes_deployment_ready n8n n8n || failures=$((failures + 1)) report_ui_check fail "Registry" "Registry HTTP" "./jeannie apps" "" "" status_registry_ok || failures=$((failures + 1)) - report_ui_check fail "Registry" "Registry reachable from Pimox workers" "./jeannie apps" "" "" status_registry_from_pimox_workers || failures=$((failures + 1)) + report_ui_check fail "Registry" "Registry reachable from cluster nodes" "./jeannie apps" "" "" status_registry_from_cluster_nodes || failures=$((failures + 1)) report_ui_check fail "Debian Services" "Docker service" "sudo systemctl restart docker" "" "" check_systemd_active docker || failures=$((failures + 1)) report_ui_check fail "Debian Services" "Gitea container" "./jeannie deploy-gitea" "" "" status_container_running "${GITEA_CONTAINER_NAME:-homelab-gitea}" || failures=$((failures + 1)) @@ -2943,15 +3013,15 @@ doctor_homelab() { status_section "Post-Migration Homelab Doctor" cluster_profile_report - status_section "Pimox Kubernetes" - status_run "pimox storage" check_pimox_storage - status_run "control-plane VM running" status_pimox_control_plane_running + status_section "Selected Cluster: ${LAB_CLUSTER_PROFILE}" + status_run "cluster storage" status_cluster_storage + status_run "control-plane runtime" status_cluster_control_runtime status_pimox_workers status_kubernetes status_section "Platform And Apps" status_run "registry HTTP" status_registry_ok - status_run "registry from Pimox workers" status_registry_from_pimox_workers + status_run "registry from cluster nodes" status_registry_from_cluster_nodes status_run "traefik deployment" kubectl --kubeconfig "${KUBECONFIG_PATH}" -n traefik get deploy,svc,pod -o wide status_run "website image" kubectl --kubeconfig "${KUBECONFIG_PATH}" -n website-production get deployment php-website-deployment -o jsonpath='{.spec.template.spec.containers[0].image}{"\n"}' status_run "demos image" kubectl --kubeconfig "${KUBECONFIG_PATH}" -n demos-static get deployment demos-static -o jsonpath='{.spec.template.spec.containers[0].image}{"\n"}' @@ -2981,7 +3051,7 @@ doctor_homelab() { Next steps: - If a Kubernetes check fails, run ./jeannie doctor-cluster --verbose. - If a public URL fails but local backends pass, run ./jeannie doctor-edge --verbose. -- If a registry/image check fails, run LAB_CLUSTER_PROFILE=pimox ./jeannie apps. +- If a registry/image check fails, run ./jeannie apps with the selected cluster profile. - If Debian service checks fail, rerun the matching deploy command rather than moving the service into Kubernetes. EOF } @@ -3623,7 +3693,7 @@ model_observe() { heal() { require_debian_server "heal" export LAB_CLUSTER_PROFILE - export KUBECONFIG="${KUBECONFIG:-${KUBECONFIG_PATH}}" + export KUBECONFIG="${KUBECONFIG_PATH}" export LAB_KUBECONFIG_PATH="${KUBECONFIG}" "${REPO_ROOT}/scripts/heal" "${@:2}" } @@ -3631,7 +3701,7 @@ heal() { self_heal() { require_debian_server "self-heal" export LAB_CLUSTER_PROFILE - export KUBECONFIG="${KUBECONFIG:-${KUBECONFIG_PATH}}" + export KUBECONFIG="${KUBECONFIG_PATH}" export LAB_KUBECONFIG_PATH="${KUBECONFIG}" if [ "${2:-}" = "install-service" ]; then local apply_mode @@ -3698,6 +3768,7 @@ PY echo "Self-heal unit validation failed; existing service preserved." >&2 return 1 fi + remember_cluster_profile || return 1 sudo install -m 0644 "${service_file}" /etc/systemd/system/jeannie-eventd.service rm -f "${service_file}" rmdir "${service_stage}" diff --git a/lib/jeannie/env.sh b/lib/jeannie/env.sh index 59038d8..392a6cc 100644 --- a/lib/jeannie/env.sh +++ b/lib/jeannie/env.sh @@ -8,7 +8,7 @@ load_homelab_inventory_defaults() { return 0 fi - rendered_defaults="$(python3 - "${inventory_file}" <<'PY' + rendered_defaults="$(python3 - "${inventory_file}" "${REPO_ROOT}" <<'PY' import re import json import os @@ -136,8 +136,10 @@ for path, env_name in mapping.items(): if value: print(f": ${{{env_name}:={shlex.quote(value)}}}") -cluster_profile = os.environ.get("LAB_CLUSTER_PROFILE") or values.get("cluster.active_profile") or "debian" -print(f": ${{LAB_CLUSTER_PROFILE:={shlex.quote(cluster_profile)}}}") +sys.path.insert(0, str(__import__("pathlib").Path(sys.argv[2]) / "scripts")) +from cluster_runtime_context import resolve +cluster_profile = resolve()["profile"] +print(f"export LAB_CLUSTER_PROFILE={shlex.quote(cluster_profile)}") profile_prefix = f"cluster.profiles.{cluster_profile}" profile_mapping = { "control_plane.node_name": ("LAB_CLUSTER_CONTROL_PLANE_NODE_NAME", None), @@ -176,8 +178,12 @@ for relative_path, (env_name, fallback_path) in profile_mapping.items(): value = values.get(f"{profile_prefix}.control_plane.node_name") if not value and cluster_profile == "debian": value = "debian" + if values.get(f"{profile_prefix}.runtime") == "k3s" and relative_path == "pimox.worker_count": + value = "0" if value: - print(f": ${{{env_name}:={shlex.quote(value)}}}") + print(f"export {env_name}={shlex.quote(value)}") + else: + print(f"unset {env_name}") def host_value(host_key, address_kind="lan_ip"): if not host_key: diff --git a/lib/jeannie/pipeline.sh b/lib/jeannie/pipeline.sh index 791c2b7..19805f9 100644 --- a/lib/jeannie/pipeline.sh +++ b/lib/jeannie/pipeline.sh @@ -8113,6 +8113,7 @@ apps() { fi echo "Application deployment successfully completed." + remember_cluster_profile || return 1 } platform_apply() { @@ -8230,6 +8231,7 @@ platform_apply() { --kubeconfig "${KUBECONFIG_PATH}" --namespace "${monitoring_namespace}" \ --recover-stale-pending || return 1 fi + remember_cluster_profile || return 1 } edge_apply() { diff --git a/lib/jeannie/preflight.sh b/lib/jeannie/preflight.sh index 11ed58f..cf1880e 100644 --- a/lib/jeannie/preflight.sh +++ b/lib/jeannie/preflight.sh @@ -30,7 +30,7 @@ homelab_preflight() { preflight_check "RPi Docker root is NVMe or fallback" check_rpi_docker_root_state || failures=$((failures + 1)) fi preflight_warn "RPi Tailscale IP ${LAB_RPI_TAILSCALE_IP:-unset}" check_rpi_tailscale_ip - preflight_check "Pimox storage ${LAB_PIMOX_WORKER_STORAGE:-${TF_VAR_pimox_worker_storage:-opi5_ssd}} is active" check_pimox_storage || failures=$((failures + 1)) + preflight_check "Selected cluster storage" status_cluster_storage bootstrap || failures=$((failures + 1)) preflight_check "OCI edge SSH ${LAB_EDGE_USER:-ubuntu}@${LAB_EDGE_HOST:?LAB_EDGE_HOST is required from homelab.yml}" check_edge_ssh || failures=$((failures + 1)) if ((failures > 0)); then @@ -52,7 +52,7 @@ doctor_preapply() { preflight_check "Docker is active" check_systemd_active docker || failures=$((failures + 1)) preflight_check "containerd is active" check_systemd_active containerd || failures=$((failures + 1)) preflight_check "RPi Docker root is writable" check_rpi_docker_writable || failures=$((failures + 1)) - preflight_check "Pimox storage ${LAB_PIMOX_WORKER_STORAGE:-${TF_VAR_pimox_worker_storage:-opi5_ssd}} is active" check_pimox_storage || failures=$((failures + 1)) + preflight_check "Selected cluster storage" status_cluster_storage bootstrap || failures=$((failures + 1)) preflight_check "OCI edge / has at least ${LAB_PREFLIGHT_EDGE_MIN_FREE_GIB:-2} GiB free" check_edge_disk_free || failures=$((failures + 1)) preflight_check "Pi-hole DNS query resolves" check_pihole_dns_query || failures=$((failures + 1)) diff --git a/scripts/access-audit b/scripts/access-audit index d9e2210..e9315d5 100755 --- a/scripts/access-audit +++ b/scripts/access-audit @@ -2,6 +2,7 @@ set -euo pipefail REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "${REPO_ROOT}/scripts/cluster-env.sh" KUBECONFIG="${KUBECONFIG:-${HOME}/.kube/config}" section() { diff --git a/scripts/backup-status b/scripts/backup-status index 2774fc2..8a4fc37 100755 --- a/scripts/backup-status +++ b/scripts/backup-status @@ -2,6 +2,7 @@ set -euo pipefail REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "${REPO_ROOT}/scripts/cluster-env.sh" HOMELAB_STATE_DIR="${HOMELAB_STATE_DIR:-${XDG_DATA_HOME:-${HOME}/.local/share}/homelab}" GITEA_BACKUP_DIR="${LAB_GITEA_BACKUP_DIR:-/home/jv/backups/gitea}" GITEA_DRILL_DIR="${GITEA_RESTORE_DRILL_DIR:-/home/jv/backups/gitea-restore-drills}" @@ -82,7 +83,12 @@ check_latest() { section "Backup Freshness" check_latest "Gitea backup" "$GITEA_BACKUP_DIR" 'gitea-*.zip' "$MAX_GITEA_AGE_HOURS" fail check_latest "OpenTofu state backup" "$TOFU_BACKUP_DIR" 'tofu-state-*.tgz' "$MAX_TOFU_AGE_HOURS" warn -check_latest "Pimox profile backup" "$PROFILE_BACKUP_DIR" 'homelab-pimox-profile-*.tgz.age' "$MAX_PROFILE_AGE_HOURS" fail +if [[ "${LAB_CLUSTER_RUNTIME}" == k3s ]]; then + echo "Native K3s backup coverage: verify a datastore and /data volume backup; a Pimox VM archive does not cover this node." + warnings=$((warnings + 1)) +else + check_latest "Pimox profile backup" "$PROFILE_BACKUP_DIR" 'homelab-pimox-profile-*.tgz.age' "$MAX_PROFILE_AGE_HOURS" fail +fi check_latest "Restore drill report" "$GITEA_DRILL_DIR" 'gitea-restore-drill-*.txt' "$MAX_DRILL_AGE_HOURS" warn if [ -n "${LAB_OCI_BACKUP_BUCKET:-}" ] && [ -x "${REPO_ROOT}/scripts/oci-backup-freshness" ]; then printf '%-30s ' "OCI Object Storage backup" diff --git a/scripts/capacity-advisor b/scripts/capacity-advisor index 369dcfb..039ee5f 100755 --- a/scripts/capacity-advisor +++ b/scripts/capacity-advisor @@ -2,6 +2,7 @@ set -euo pipefail REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "${REPO_ROOT}/scripts/cluster-env.sh" run_check() { local name="$1" @@ -25,9 +26,11 @@ trap 'rm -f "$tmp_file"' EXIT python3 - "$tmp_file" <<'PY' import re +import os import sys text = open(sys.argv[1], encoding="utf-8").read() +native = os.environ.get("LAB_CLUSTER_RUNTIME") == "k3s" lowered = text.lower() missing_match = re.search(r"(\d+)\s+pods missing requests/limits", text) @@ -73,7 +76,9 @@ if legacy_control_plane_pods: "cluster cleanup: active ARR state is infra/arr-stack, not archive/apps/arr-stack", ) ) -if app_control_plane_pods and control_plane_tainted: +if native and control_plane_tainted: + recommendations.append(("Keep the native node schedulable", "A single-node cluster must host platform and app pods.", "./jeannie control-plane untaint", "Remove the control-plane NoSchedule taint after verifying the selected profile.")) +elif app_control_plane_pods and control_plane_tainted: count = len(app_control_plane_pods) namespaces = ", ".join(sorted({namespace for namespace, _, _ in app_control_plane_pods})) recommendations.append( @@ -84,7 +89,7 @@ if app_control_plane_pods and control_plane_tainted: "scheduling: restart or drain selected workloads; if they return to Debian, check tolerations, node selectors, affinity, and worker readiness", ) ) -elif app_control_plane_pods: +elif app_control_plane_pods and not native: recommendations.append( ( "Keep app/data-plane pods off Debian", @@ -93,7 +98,9 @@ elif app_control_plane_pods: "scheduling: taint Debian after Pimox workers are Ready", ) ) -if pressure or worker_storage_warn: +if native and pressure: + recommendations.append(("Inspect native K3s resource pressure", "The single Orange Pi runs both control plane and apps.", "./jeannie workers disk-status control-plane", "Review /data, root space and workload requests; keep Pimox VMs stopped.")) +elif pressure or worker_storage_warn: recommendations.append( ( "Consider adding or recreating Pimox worker capacity", @@ -106,7 +113,7 @@ if pressure or worker_storage_warn: if not recommendations: recommendations.append( ( - "No new Pimox VM needed from current signals", + "No additional cluster capacity indicated by current signals", "No capacity warning, node pressure, or control-plane placement issue was detected in the sampled reports.", "./jeannie capacity", "watch: rerun after adding workloads", @@ -121,6 +128,10 @@ for index, (title, why, command, fix) in enumerate(recommendations, start=1): print("\nRule of thumb") print("- Add requests before deciding you need more VMs.") -print("- Taint Debian once Pimox workers are stable.") -print("- Add a Pimox VM only when real pressure remains after placement and requests are cleaned up.") +if native: + print("- Keep platform and app workloads schedulable on the single K3s node.") + print("- Keep Pimox VMs stopped while native K3s is active.") +else: + print("- Taint the control plane only when worker placement is healthy.") + print("- Add a Pimox VM only when pressure remains after placement and requests are cleaned up.") PY diff --git a/scripts/capacity-limits b/scripts/capacity-limits index f0ae2e8..5ed8897 100755 --- a/scripts/capacity-limits +++ b/scripts/capacity-limits @@ -2,6 +2,7 @@ set -euo pipefail REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "${REPO_ROOT}/scripts/cluster-env.sh" KUBECONFIG_PATH="${KUBECONFIG:-${LAB_KUBECONFIG_PATH:-/home/jv/.kube/config}}" PROFILE_FILE="${HOMELAB_RESOURCE_RECOMMENDATIONS:-${REPO_ROOT}/infra/resource-recommendations.yml}" NAMESPACE="${1:-}" diff --git a/scripts/capacity-report b/scripts/capacity-report index 3a340ab..0cc22b6 100755 --- a/scripts/capacity-report +++ b/scripts/capacity-report @@ -1,8 +1,8 @@ #!/usr/bin/env bash set -euo pipefail -KUBECONFIG="${KUBECONFIG:-${KUBECONFIG_PATH:-${HOME}/.kube/config}}" REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "${REPO_ROOT}/scripts/cluster-env.sh" GRAFANA_BASE_URL="${LAB_GRAFANA_URL:-https://grafana.${LAB_DOMAIN:-lab2025.duckdns.org}}" GRAFANA_CAPACITY_URL="${GRAFANA_BASE_URL%/}/d/homelab-capacity/homelab-capacity?orgId=1" GRAFANA_AVAILABILITY_URL="${GRAFANA_BASE_URL%/}/d/homelab-availability/homelab-availability?orgId=1" @@ -123,6 +123,10 @@ kubernetes_capacity() { } pimox_capacity() { + if [[ "${LAB_CLUSTER_RUNTIME}" == k3s ]]; then + python3 "${REPO_ROOT}/scripts/k3s-node-diagnostics.py" status + return + fi 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}/.ssh/id_ed25519}}" @@ -175,6 +179,10 @@ sudo docker system df 2>/dev/null || true summary() { section "Capacity Guidance" + if [[ "${LAB_CLUSTER_RUNTIME}" == k3s ]]; then + echo "Single-node K3s shares the Orange Pi CPU/RAM. Keep platform workloads on that node, monitor /data and root separately, and keep Pimox VMs stopped." + return + fi cat <<'EOF' Use this report to decide placement: - Prefer Kubernetes app workloads on Pimox workers with SSD-backed storage. @@ -302,6 +310,17 @@ compact_kubernetes_capacity() { } compact_pimox_capacity() { + if [[ "${LAB_CLUSTER_RUNTIME}" == k3s ]]; then + local native_output + if native_output="$(ssh -n -i "${LAB_CLUSTER_CONTROL_PLANE_SSH_KEY_PATH}" -o BatchMode=yes -o ConnectTimeout=8 \ + -o StrictHostKeyChecking=accept-new "${LAB_CLUSTER_CONTROL_PLANE_USER}@${LAB_CLUSTER_CONTROL_PLANE_LAN_IP}" \ + 'free -m; df -hP / /data /var/lib/rancher/k3s' 2>&1)"; then + emit ok "Native K3s" "Host capacity" "Orange Pi host resources" "${native_output//$'\n'/; }" + else + emit warn "Native K3s" "Host capacity" "unreachable" "${native_output//$'\n'/; }" "./jeannie doctor-cluster" + fi + return + fi 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}/.ssh/id_ed25519}}" @@ -391,6 +410,11 @@ echo "docker_root_used=${docker_root_used:-unknown}" } compact_guidance() { + if [[ "${LAB_CLUSTER_RUNTIME}" == k3s ]]; then + emit ok "Guidance" "Placement" "Single-node K3s runs platform and apps together" "Use live allocatable resources and requests; leave Pimox VMs stopped." + emit ok "Guidance" "Storage" "K3s runtime and local volumes use /data" "Monitor root and SSD separately and retain backups." + return + fi emit ok "Guidance" "Placement" "Prefer app workloads on Pimox workers" "Keep Debian headroom for Gitea, registry, Docker, kubeadm, and Ollama." emit ok "Guidance" "Storage" "Treat Pimox VM disks as rebuildable" "Durable data still needs explicit backup/restore paths." } diff --git a/scripts/cluster-context.py b/scripts/cluster-context.py index f2ed188..911d030 100644 --- a/scripts/cluster-context.py +++ b/scripts/cluster-context.py @@ -18,6 +18,8 @@ import time from pathlib import Path from urllib.parse import urlsplit +sys.path.insert(0, str(Path(__file__).resolve().parent)) + REPO = Path(__file__).resolve().parents[1] STACKS = {"cluster", "platform", "apps"} @@ -166,7 +168,8 @@ class Context: if os.environ.get("KUBERNETES_MASTER"): raise Refused("KUBERNETES_MASTER connection overrides are refused") cluster = inventory.get("cluster", {}) - self.profile = profile or os.environ.get("LAB_CLUSTER_PROFILE") or cluster.get("active_profile") + from cluster_runtime_context import resolve + self.profile = profile or resolve()["profile"] if not self.profile or not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}", self.profile): raise Refused("Select a valid, declared LAB_CLUSTER_PROFILE") control = cluster.get("profiles", {}).get(self.profile, {}).get("control_plane") diff --git a/scripts/cluster-env.sh b/scripts/cluster-env.sh new file mode 100644 index 0000000..d31dbe9 --- /dev/null +++ b/scripts/cluster-env.sh @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# Shared context for standalone diagnostic scripts as well as Jeannie children. +cluster_env_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cluster_env_values="$(python3 "${cluster_env_root}/scripts/cluster_runtime_context.py" shell)" || return 1 +eval "${cluster_env_values}" +unset cluster_env_root cluster_env_values diff --git a/scripts/cluster-runtime-guard.py b/scripts/cluster-runtime-guard.py index 71e6f7c..2c5ca36 100644 --- a/scripts/cluster-runtime-guard.py +++ b/scripts/cluster-runtime-guard.py @@ -11,6 +11,8 @@ import subprocess import sys import yaml +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from cluster_runtime_context import resolve REPO = Path(__file__).resolve().parents[1] @@ -54,7 +56,7 @@ fi 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"] + selected = profile or resolve()["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") diff --git a/scripts/cluster_runtime_context.py b/scripts/cluster_runtime_context.py new file mode 100644 index 0000000..d48a51e --- /dev/null +++ b/scripts/cluster_runtime_context.py @@ -0,0 +1,120 @@ +#!/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) diff --git a/scripts/control-plane b/scripts/control-plane index de23daf..6eab272 100755 --- a/scripts/control-plane +++ b/scripts/control-plane @@ -1,8 +1,11 @@ #!/usr/bin/env bash set -euo pipefail +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "${REPO_ROOT}/scripts/cluster-env.sh" + KUBECONFIG_PATH="${KUBECONFIG:-${LAB_KUBECONFIG_PATH:-/home/jv/.kube/config}}" -CONTROL_PLANE_NODE="${LAB_CONTROL_PLANE_NODE:-debian}" +CONTROL_PLANE_NODE="${LAB_CLUSTER_CONTROL_PLANE_NODE_NAME}" TAINT_KEY="${LAB_CONTROL_PLANE_TAINT_KEY:-node-role.kubernetes.io/control-plane}" TAINT_EFFECT="${LAB_CONTROL_PLANE_TAINT_EFFECT:-NoSchedule}" @@ -66,6 +69,11 @@ case "${1:-status}" in ;; taint) require_kubectl + node_count="$(kubectl --kubeconfig "$KUBECONFIG_PATH" get nodes -o name | wc -l)" + if ((node_count < 2)); then + echo "Refusing NoSchedule taint on a single-node cluster; platform and apps need this node." >&2 + exit 1 + fi kubectl --kubeconfig "$KUBECONFIG_PATH" taint node "$CONTROL_PLANE_NODE" "${TAINT_KEY}:${TAINT_EFFECT}" --overwrite echo echo "Current taints:" diff --git a/scripts/gitops-diff b/scripts/gitops-diff index 7c3220e..127d307 100755 --- a/scripts/gitops-diff +++ b/scripts/gitops-diff @@ -1,6 +1,9 @@ #!/usr/bin/env bash set -euo pipefail +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "${REPO_ROOT}/scripts/cluster-env.sh" + NAMESPACE="${ARGOCD_NAMESPACE:-argocd}" KUBECONFIG_PATH="${KUBECONFIG_PATH:-${LAB_KUBECONFIG_PATH:-${KUBECONFIG:-/home/jv/.kube/config}}}" APP="${1:-}" diff --git a/scripts/gitops-refresh b/scripts/gitops-refresh index cf3ebdf..80fdced 100755 --- a/scripts/gitops-refresh +++ b/scripts/gitops-refresh @@ -1,6 +1,9 @@ #!/usr/bin/env bash set -euo pipefail +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "${REPO_ROOT}/scripts/cluster-env.sh" + NAMESPACE="${ARGOCD_NAMESPACE:-argocd}" KUBECONFIG_PATH="${KUBECONFIG_PATH:-${LAB_KUBECONFIG_PATH:-${KUBECONFIG:-/home/jv/.kube/config}}}" if [[ $# -ne 1 ]]; then diff --git a/scripts/gitops-status b/scripts/gitops-status index cfccb41..cea7678 100755 --- a/scripts/gitops-status +++ b/scripts/gitops-status @@ -1,6 +1,9 @@ #!/usr/bin/env bash set -euo pipefail +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "${REPO_ROOT}/scripts/cluster-env.sh" + NAMESPACE="${ARGOCD_NAMESPACE:-argocd}" LOG_PATTERN="${GITOPS_LOG_PATTERN:-error|failed|denied|timeout|authentication|unauthorized}" diff --git a/scripts/grafana-dashboards b/scripts/grafana-dashboards index 1a01262..d9ca30d 100755 --- a/scripts/grafana-dashboards +++ b/scripts/grafana-dashboards @@ -2,6 +2,7 @@ set -euo pipefail REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "${REPO_ROOT}/scripts/cluster-env.sh" DASHBOARD_DIR="${HOMELAB_GRAFANA_DASHBOARD_DIR:-${REPO_ROOT}/bootstrap/platform/grafana-dashboards}" NAMESPACE="${HOMELAB_GRAFANA_NAMESPACE:-monitoring}" KUBECONFIG_PATH="${KUBECONFIG:-${LAB_KUBECONFIG_PATH:-${HOME}/.kube/config}}" diff --git a/scripts/heal b/scripts/heal index c4c7d94..bbef5c2 100755 --- a/scripts/heal +++ b/scripts/heal @@ -12,15 +12,13 @@ import sys import time from dataclasses import dataclass from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from cluster_runtime_context import resolve, environment REPO_ROOT = Path(__file__).resolve().parents[1] -DEFAULT_KUBECONFIG = Path( - os.environ.get("KUBECONFIG") - or os.environ.get("LAB_KUBECONFIG_PATH") - or Path.home() / ".kube" / ( - "pimox-config" if os.environ.get("LAB_CLUSTER_PROFILE") == "pimox" else "config" - ) -) +CLUSTER = resolve() +os.environ.update(environment(CLUSTER["profile"])) +DEFAULT_KUBECONFIG = Path(CLUSTER["kubeconfig"]) STATE_DIR = Path( os.environ.get( "HOMELAB_STATE_DIR", @@ -28,7 +26,7 @@ STATE_DIR = Path( ) ) HEAL_STATE_FILE = Path( - os.environ.get("LAB_HEAL_STATE_FILE", STATE_DIR / "heal-state.json") + os.environ.get("LAB_HEAL_STATE_FILE", Path(CLUSTER["root"]) / "heal-state.json") ) HEAL_COOLDOWN_SECONDS = int(os.environ.get("LAB_HEAL_COOLDOWN_SECONDS", "1800")) @@ -48,7 +46,7 @@ RULES = [ "Kubernetes API", "./jeannie start-cluster", "low", - "API is down; start-cluster starts kubelet/containerd and worker VMs without destroying state.", + "API is down; start-cluster starts the selected runtime without destroying state.", True, 100, ), @@ -213,6 +211,13 @@ def status_rows(status: dict[str, object]) -> list[dict[str, str]]: def rule_for(row: dict[str, str]) -> HealRule | None: check = str(row.get("check", "")) + if CLUSTER["runtime"] == "k3s" and ("Pimox" in check or "VM" in check): + return None + check = {"API ready": "Kubernetes API", "API": "Kubernetes API", + "Problem pods": "No problem pods", + "Nodes Ready": "Kubernetes nodes Ready", "Control-plane runtime": "Kubernetes API", + "Workers running": "Pimox workers running", "Worker VMs running": "Pimox workers running", + "Control-plane VM running": "Kubernetes API"}.get(check, check) for rule in RULES: if rule.check == check: return rule @@ -230,7 +235,7 @@ def pimox_worker_index(row: dict[str, str]) -> int | None: def command_for(row: dict[str, str], rule: HealRule) -> tuple[str, str, int]: if rule.check == "Kubernetes nodes Ready": index = pimox_worker_index(row) - if index is not None: + if index is not None and CLUSTER["runtime"] != "k3s": return ( f"./jeannie workers restart {index}", f"Restart Pimox VM for pimox-worker-{index:02d}; a running VM with a NotReady kubelet can be wedged.", @@ -250,6 +255,10 @@ def command_for(row: dict[str, str], rule: HealRule) -> tuple[str, str, int]: def build_plan(status: dict[str, object]) -> list[dict[str, object]]: + report_cluster = status.get("cluster") or {} + if (report_cluster.get("profile") != CLUSTER["profile"] or report_cluster.get("kubeconfig") != CLUSTER["kubeconfig"] + or not CLUSTER["uid"] or report_cluster.get("uid") != CLUSTER["uid"]): + raise SystemExit("Heal refused: status report cluster context is missing or differs from the selected profile; collect a fresh status report") planned: list[dict[str, object]] = [] seen_commands: set[str] = set() blocked = recent_failed_commands() @@ -333,6 +342,7 @@ def print_plan(plan: list[dict[str, object]], ai: bool) -> None: print("Jeannie Heal Plan") print("=================") print("mode: one-at-a-time") + print(f"profile={CLUSTER['profile']} runtime={CLUSTER['runtime']} kubeconfig={DEFAULT_KUBECONFIG}") print(f"findings={len(plan)}") print() if target: @@ -413,7 +423,7 @@ def apply_plan(plan: list[dict[str, object]], yes: bool) -> int: if not yes: print(f"would run: {command}") else: - if not cluster_identity_ok(): + if not cluster_identity_ok(startup=command == "./jeannie start-cluster"): return 1 print(f"run: {command}") process = subprocess.run(command.split(), cwd=REPO_ROOT, text=True, check=False) @@ -586,9 +596,9 @@ def cleanup_stale_pods(yes: bool) -> int: return 0 -def cluster_identity_ok() -> bool: +def cluster_identity_ok(startup=False) -> bool: result = subprocess.run( - [sys.executable, str(REPO_ROOT / "scripts/cluster-context.py"), "check", "--kubeconfig", str(DEFAULT_KUBECONFIG)], + [sys.executable, str(REPO_ROOT / "scripts/cluster-context.py"), "check-startup" if startup else "check", "--profile", CLUSTER["profile"], "--kubeconfig", str(DEFAULT_KUBECONFIG)], cwd=REPO_ROOT, text=True, stdout=subprocess.DEVNULL, check=False, ) return result.returncode == 0 diff --git a/scripts/homelab-backup b/scripts/homelab-backup index 703b588..eb05378 100755 --- a/scripts/homelab-backup +++ b/scripts/homelab-backup @@ -2,6 +2,7 @@ set -euo pipefail REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "${REPO_ROOT}/scripts/cluster-env.sh" HOMELAB_STATE_DIR="${HOMELAB_STATE_DIR:-${XDG_DATA_HOME:-${HOME}/.local/share}/homelab}" BACKUP_DIR="${HOMELAB_PROFILE_BACKUP_DIR:-${HOMELAB_STATE_DIR}/profile-backups}" HOMELAB_BACKUP_STAGE="" diff --git a/scripts/jeannie-eventd b/scripts/jeannie-eventd index aa527c2..a6d337f 100755 --- a/scripts/jeannie-eventd +++ b/scripts/jeannie-eventd @@ -14,6 +14,8 @@ import sys from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from typing import Any +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from cluster_runtime_context import resolve, environment REPO_ROOT = Path(__file__).resolve().parents[1] STATE_DIR = Path( @@ -26,6 +28,9 @@ EVENT_DIR = Path(os.environ.get("LAB_SELF_HEAL_EVENT_DIR", STATE_DIR / "self-hea DEFAULT_DOCTOR = ["./jeannie", "doctor-homelab", "--json", "--no-local-rca"] SUPPORTED_ALERTS = { + "KubeNodeNotReady", + "KubeAPIDown", + "KubeletDown", "JeannieApiMetricsDown", "HomelabNodeDiskPressure", "HomelabNodeImageFilesystemPressure", @@ -126,7 +131,7 @@ def api_self_heal_command(names: set[str]) -> list[str] | None: return None -def disk_self_heal_command(payload: dict[str, Any], names: set[str]) -> list[str] | None: +def disk_self_heal_command(payload: dict[str, Any], names: set[str], cluster=None) -> list[str] | None: if not names & DISK_SELF_HEAL_ALERTS: return None labels_list: list[dict[str, Any]] = [] @@ -137,6 +142,7 @@ def disk_self_heal_command(payload: dict[str, Any], names: set[str]) -> list[str if isinstance(common_labels, dict): labels_list.append(common_labels) + cluster = cluster or resolve(follow_active=True) for labels in labels_list: host_values = ( labels.get("node"), @@ -152,12 +158,18 @@ def disk_self_heal_command(payload: dict[str, Any], names: set[str]) -> list[str if normalized_hosts & DISK_SELF_HEAL_DISABLED_HOSTS: return None node = str(labels.get("node") or "") + if cluster["runtime"] == "k3s": + if node == cluster["node"] or normalized_hosts & {cluster["node"], cluster["host"]}: + return ["./jeannie", "workers", "disk-cleanup", "control-plane", "--yes"] + continue if re.fullmatch(r"pimox-cp(?:-\d+)?", node): return ["./jeannie", "workers", "disk-cleanup", "control-plane", "--yes"] match = re.fullmatch(r"pimox-worker-(\d{1,2})", node) if match: return ["./jeannie", "workers", "disk-cleanup", str(int(match.group(1))), "--yes"] + if cluster["runtime"] == "k3s": + return None spec_file = REPO_ROOT / ".lab" / "pimox-workers.tsv" if spec_file.is_file(): for labels in labels_list: @@ -185,15 +197,17 @@ def write_text(path: Path, text: str) -> None: path.write_text(text, encoding="utf-8") -def run_command(command: list[str], audit_dir: Path, name: str) -> subprocess.CompletedProcess[str]: +def run_command(command: list[str], audit_dir: Path, name: str, env=None) -> subprocess.CompletedProcess[str]: + env = env or environment(resolve(follow_active=True)["profile"]) if name in {"disk-heal", "api-heal", "pod-heal", "heal-apply"}: - guard_command = [sys.executable, str(REPO_ROOT / "scripts/cluster-context.py"), "check"] - kubeconfig = os.environ.get("KUBECONFIG") or os.environ.get("LAB_KUBECONFIG_PATH") + guard_command = [sys.executable, str(REPO_ROOT / "scripts/cluster-context.py"), "check-startup" if name == "heal-apply" else "check"] + guard_command.extend(["--profile", env["LAB_CLUSTER_PROFILE"]]) + kubeconfig = env["KUBECONFIG"] if kubeconfig: guard_command.extend(["--kubeconfig", kubeconfig]) guard = subprocess.run( guard_command, - cwd=REPO_ROOT, text=True, capture_output=True, check=False, + cwd=REPO_ROOT, text=True, capture_output=True, check=False, env=env, ) if guard.returncode: write_text(audit_dir / f"{name}.stderr.log", guard.stderr) @@ -208,6 +222,7 @@ def run_command(command: list[str], audit_dir: Path, name: str) -> subprocess.Co stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False, + env=env, ) write_text(audit_dir / f"{name}.cmd", " ".join(command) + "\n") write_text(audit_dir / f"{name}.log", process.stdout) @@ -227,14 +242,33 @@ def planned_command(plan_output: str) -> str: def handle_payload(payload: dict[str, Any], *, apply: bool) -> dict[str, Any]: + cluster = resolve(follow_active=True) + event_env = environment(cluster["profile"]) key = event_key(payload) - audit_dir = EVENT_DIR / f"{utc_stamp()}-{key}" + event_dir = Path(os.environ.get("LAB_SELF_HEAL_EVENT_DIR", Path(cluster["root"]) / "self-heal-events")) + audit_dir = event_dir / f"{utc_stamp()}-{key}" audit_dir.mkdir(parents=True, exist_ok=True) + write_text(audit_dir / "cluster.json", json.dumps({key: cluster[key] for key in ("profile", "runtime", "host", "node", "kubeconfig", "uid")}, indent=2) + "\n") (audit_dir / "alertmanager.json").write_text( json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8" ) names = sorted(alert_names(payload)) + labelled_profiles = {str(alert.get("labels", {}).get("cluster_profile")) + for alert in payload.get("alerts") or [] if alert.get("labels", {}).get("cluster_profile")} + labelled_uids = {str(alert.get("labels", {}).get("cluster_uid")) + for alert in payload.get("alerts") or [] if alert.get("labels", {}).get("cluster_uid")} + incomplete_identity = any( + alert.get("labels", {}).get("cluster_profile") != cluster["profile"] + or alert.get("labels", {}).get("cluster_uid") != cluster["uid"] + for alert in payload.get("alerts") or [] + ) + if ((labelled_profiles and labelled_profiles != {cluster["profile"]}) + or (labelled_uids and labelled_uids != {cluster["uid"]}) + or (apply and (incomplete_identity or labelled_profiles != {cluster["profile"]} or not cluster["uid"] or labelled_uids != {cluster["uid"]}))): + result = {"status": "skipped", "reason": "alert cluster identity is absent or differs from the selected cluster; deploy monitoring labels before automatic healing", "audit_dir": str(audit_dir)} + write_text(audit_dir / "result.json", json.dumps(result) + "\n") + return result if not supported(payload): result = { "status": "skipped", @@ -245,7 +279,7 @@ def handle_payload(payload: dict[str, Any], *, apply: bool) -> dict[str, Any]: write_text(audit_dir / "result.json", json.dumps(result, indent=2) + "\n") return result - disk_command = disk_self_heal_command(payload, set(names)) + disk_command = disk_self_heal_command(payload, set(names), cluster=cluster) api_command = api_self_heal_command(set(names)) # An eviction cleanup alert must not select an unrelated host restart from # the broad doctor report. Cleanup performs its own ownership/state checks. @@ -256,13 +290,13 @@ def handle_payload(payload: dict[str, Any], *, apply: bool) -> dict[str, Any]: direct_command = disk_command or api_command or pod_command # Disk alerts are deliberately target-specific. Do not fall through to # the generic doctor/heal planner when the alert does not identify a - # Pimox node that Jeannie can clean safely. A generic heal action could + # selected cluster node that Jeannie can clean safely. A generic heal action could # clean stale pods while leaving the actual filesystem pressure untouched # and would produce a misleading "applied" result. if set(names) & DISK_SELF_HEAL_ALERTS and not disk_command and not api_command: result = { "status": "skipped", - "reason": "disk alert target is not a recognized Pimox node", + "reason": "disk alert target is not a recognized node in the selected cluster profile", "alerts": names, "audit_dir": str(audit_dir), } @@ -281,6 +315,7 @@ def handle_payload(payload: dict[str, Any], *, apply: bool) -> dict[str, Any]: direct_command, audit_dir, "disk-heal" if disk_command else "api-heal" if api_command else "pod-heal", + env=event_env, ) result["status"] = "applied" if apply_result.returncode == 0 else "apply_failed" result["mode"] = "apply" @@ -288,7 +323,7 @@ def handle_payload(payload: dict[str, Any], *, apply: bool) -> dict[str, Any]: write_text(audit_dir / "result.json", json.dumps(result, indent=2, sort_keys=True) + "\n") return result - doctor = run_command(DEFAULT_DOCTOR, audit_dir, "doctor-homelab") + doctor = run_command(DEFAULT_DOCTOR, audit_dir, "doctor-homelab", env=event_env) if doctor.returncode != 0 and not doctor.stdout.strip(): result = { "status": "failed", @@ -304,6 +339,7 @@ def handle_payload(payload: dict[str, Any], *, apply: bool) -> dict[str, Any]: ["./scripts/heal", "plan", "--status-json", str(status_json)], audit_dir, "heal-plan", + env=event_env, ) result: dict[str, Any] = { "status": "planned", @@ -319,6 +355,7 @@ def handle_payload(payload: dict[str, Any], *, apply: bool) -> dict[str, Any]: ["./scripts/heal", "apply", "--status-json", str(status_json), "--yes"], audit_dir, "heal-apply", + env=event_env, ) result["status"] = "applied" if apply_result.returncode == 0 else "apply_failed" result["mode"] = "apply" @@ -330,9 +367,9 @@ def handle_payload(payload: dict[str, Any], *, apply: bool) -> dict[str, Any]: def result_documents() -> list[tuple[Path, dict[str, Any]]]: documents: list[tuple[Path, dict[str, Any]]] = [] - if not EVENT_DIR.is_dir(): - return documents - for path in sorted(EVENT_DIR.glob("*/result.json")): + paths = set(EVENT_DIR.glob("*/result.json")) + paths.update((STATE_DIR / "clusters").glob("*/self-heal-events/*/result.json")) + for path in sorted(paths): try: document = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): diff --git a/scripts/k3s-node-diagnostics.py b/scripts/k3s-node-diagnostics.py new file mode 100644 index 0000000..044af80 --- /dev/null +++ b/scripts/k3s-node-diagnostics.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +"""Inspect or reclaim unused K3s images on the selected native node.""" + +import argparse +import importlib.util +from pathlib import Path +import re +import shlex +import subprocess + +from cluster_runtime_context import resolve, environment + +REPO = Path(__file__).resolve().parents[1] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=("status", "cleanup")) + parser.add_argument("--yes", action="store_true") + args = parser.parse_args() + cluster = resolve() + if cluster["runtime"] != "k3s": + raise RuntimeError("Native K3s diagnostics require the selected K3s runtime") + spec = importlib.util.spec_from_file_location("native_disk_context", REPO / "scripts/cluster-context.py") + context = importlib.util.module_from_spec(spec) + spec.loader.exec_module(context) + ctx = context.Context(cluster["profile"], cluster["kubeconfig"]) + if args.action == "cleanup" and args.yes: + ctx.check() + else: + ctx.observed(startup=True) + ssh = ["ssh", "-T", "-i", cluster["key"], "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes", + "-o", "ConnectTimeout=10", "-o", "StrictHostKeyChecking=accept-new", f"{cluster['user']}@{cluster['host']}"] + inspection = """set -eu +echo '-- K3s service' +systemctl is-active k3s || true +echo '-- filesystems' +df -hP / /data /var/lib/rancher/k3s +findmnt -T /var/lib/rancher/k3s -o TARGET,SOURCE,FSTYPE +echo '-- K3s image filesystem' +sudo -n k3s crictl imagefsinfo || true +echo '-- recent K3s errors' +sudo -n journalctl -u k3s --since '30 minutes ago' --no-pager -o cat | grep -Ei 'no space|diskpressure|evict|imagegc|failed|error' | tail -12 || true +""" + if args.action == "cleanup" and args.yes: + mount = cluster["required_mount"] + endpoint = cluster["inventory"]["cluster"]["profiles"][cluster["profile"]]["registry"]["endpoint"] + if not mount or not re.fullmatch(r"/[A-Za-z0-9_./-]+", mount) or ".." in Path(mount).parts: + raise RuntimeError("Native runtime requires a declared data mount before disk healing") + script = ("set -eu\nmountpoint -q " + shlex.quote(mount) + "\n" + + "curl -fsS --connect-timeout 5 --max-time 10 " + shlex.quote("http://" + endpoint + "/v2/") + " >/dev/null\n" + + "sudo -n k3s crictl rmi --prune\n" + + "sudo -n journalctl --vacuum-time=7d --vacuum-size=200M\n" + inspection) + else: + script = inspection + if args.action == "cleanup": + print("Dry run: --yes prunes unused K3s images after a registry reachability check and vacuums host journals. PV data is not a cleanup target.", flush=True) + print(f"Native K3s node: {cluster['node']} ({cluster['host']}); profile={cluster['profile']}", flush=True) + subprocess.run([*ssh, "bash -s"], input=script, text=True, check=True, timeout=600, + env=environment(cluster["profile"])) + + +if __name__ == "__main__": + try: + main() + except (RuntimeError, OSError, ValueError, KeyError, subprocess.SubprocessError) as error: + raise SystemExit(f"Native K3s disk operation refused: {error}") diff --git a/scripts/kubeconfig-readonly b/scripts/kubeconfig-readonly index 5b151c5..70cc691 100755 --- a/scripts/kubeconfig-readonly +++ b/scripts/kubeconfig-readonly @@ -1,10 +1,13 @@ #!/usr/bin/env bash set -euo pipefail +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "${REPO_ROOT}/scripts/cluster-env.sh" + ADMIN_KUBECONFIG="${KUBECONFIG:-${KUBECONFIG_PATH:-${HOME}/.kube/config}}" READONLY_NAMESPACE="${READONLY_NAMESPACE:-homelab-access}" READONLY_SERVICE_ACCOUNT="${READONLY_SERVICE_ACCOUNT:-homelab-readonly}" -READONLY_KUBECONFIG="${READONLY_KUBECONFIG:-${HOME}/.kube/homelab-readonly.conf}" +READONLY_KUBECONFIG="${READONLY_KUBECONFIG:-${HOME}/.kube/${LAB_CLUSTER_PROFILE}-readonly.conf}" READONLY_TOKEN_DURATION="${READONLY_TOKEN_DURATION:-24h}" usage() { diff --git a/scripts/mesh-doctor b/scripts/mesh-doctor index 477b585..955835d 100755 --- a/scripts/mesh-doctor +++ b/scripts/mesh-doctor @@ -9,7 +9,10 @@ import os import shutil import socket import subprocess +import sys from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from cluster_runtime_context import resolve def run(command: list[str], timeout: int = 10) -> tuple[int, str, str]: @@ -45,6 +48,8 @@ def kubectl(kubeconfig: str, *args: str) -> tuple[int, str, str]: def inventory(repo_root: Path) -> list[tuple[str, str, str]]: + if resolve()["runtime"] == "k3s": + return [] path = repo_root / ".lab" / "pimox-workers.tsv" result = [] if not path.is_file(): @@ -58,7 +63,8 @@ def inventory(repo_root: Path) -> list[tuple[str, str, str]]: def collect(repo_root: Path) -> dict: rows: list[dict[str, str]] = [] - kubeconfig = os.environ.get("LAB_KUBECONFIG_PATH", os.environ.get("KUBECONFIG", "/home/jv/.kube/config")) + cluster = resolve() + kubeconfig = cluster["kubeconfig"] code, output, error = kubectl(kubeconfig, "get", "--raw=/readyz") if code == 0 and output: @@ -99,7 +105,7 @@ def collect(repo_root: Path) -> dict: else: rows.append(row("warn", "Calico node mesh", "unable to inspect", error or output or "kubectl failed")) - control_plane = os.environ.get("LAB_CLUSTER_CONTROL_PLANE_LAN_IP", os.environ.get("LAB_DEBIAN_LAN_IP", "")) + control_plane = cluster["host"] rows.append(tcp_check("Control-plane SSH path", control_plane)) for node, address, _user in inventory(repo_root): rows.append(tcp_check(f"{node} SSH path", address)) diff --git a/scripts/recover-plan b/scripts/recover-plan index 4413566..25e8f71 100755 --- a/scripts/recover-plan +++ b/scripts/recover-plan @@ -2,6 +2,7 @@ set -euo pipefail REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "${REPO_ROOT}/scripts/cluster-env.sh" KUBECONFIG="${KUBECONFIG:-${KUBECONFIG_PATH:-${HOME}/.kube/config}}" check() { @@ -46,14 +47,14 @@ main() { ./jeannie doctor-rpi ./jeannie drill-pihole-restore -4. Verify Pimox template and worker storage. +4. Verify the selected cluster's runtime and storage. Commands: - ./jeannie preflight - ./jeannie doctor-preapply + ./jeannie cluster-profile + ./jeannie doctor-cluster 5. Rebuild or start Kubernetes. If state exists and nodes are stopped: ./jeannie start-cluster - If cluster must be rebuilt: ./jeannie rebuild-cluster + A rebuild changes cluster identity and needs an explicit recreation/enrollment procedure. 6. Restore platform and apps from GitOps. Commands: diff --git a/scripts/recover-power b/scripts/recover-power index e3f6637..e8aa5c8 100755 --- a/scripts/recover-power +++ b/scripts/recover-power @@ -2,6 +2,7 @@ set -euo pipefail REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "${REPO_ROOT}/scripts/cluster-env.sh" DRY_RUN=false if [ "${1:-}" = "--dry-run" ]; then @@ -34,7 +35,7 @@ Power-loss recovery order ========================= This sequence restores dependencies before dependents: -Debian runtime -> Gitea -> RPi DNS -> Pimox workers -> Kubernetes -> GitOps/apps -> edge/public URLs. +Debian services -> Gitea -> RPi DNS -> selected cluster (${LAB_CLUSTER_PROFILE}/${LAB_CLUSTER_RUNTIME}) -> GitOps/apps -> edge/public URLs. EOF run_optional "Debian runtime status" systemctl is-active docker containerd diff --git a/scripts/resource-budget b/scripts/resource-budget index 3625ef4..8f4ae69 100755 --- a/scripts/resource-budget +++ b/scripts/resource-budget @@ -2,6 +2,7 @@ set -euo pipefail REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "${REPO_ROOT}/scripts/cluster-env.sh" BUDGET_FILE="${HOMELAB_RESOURCE_BUDGET_FILE:-${REPO_ROOT}/infra/resource-budgets.yml}" KUBECONFIG_PATH="${KUBECONFIG:-${LAB_KUBECONFIG_PATH:-/home/jv/.kube/config}}" DETAILS=false @@ -90,6 +91,7 @@ kubernetes_budget() { python3 - "$BUDGET_FILE" "$KUBECONFIG_PATH" "$DETAILS" "$MAX_EXAMPLES" <<'PY' import json +import os import subprocess import sys from collections import Counter, defaultdict @@ -222,7 +224,10 @@ if missing: print("next_steps:") print(" 1. Add requests before limits for app workloads you own.") print(" 2. Leave kube-system/control-plane static pods for a separate pass.") - print(" 3. Use ./jeannie control-plane taint after Pimox workers are Ready.") + if os.environ.get("LAB_CLUSTER_RUNTIME") == "k3s": + print(" 3. Keep the single native node schedulable; review requests against its allocatable resources.") + else: + print(" 3. Use ./jeannie control-plane taint only after worker placement is healthy.") exit_code = 1 raise SystemExit(exit_code) diff --git a/scripts/restore-drill b/scripts/restore-drill index 19bf3d6..70c4a38 100755 --- a/scripts/restore-drill +++ b/scripts/restore-drill @@ -1,6 +1,8 @@ #!/usr/bin/env bash set -euo pipefail +source "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/cluster-env.sh" + REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" HOMELAB_STATE_DIR="${HOMELAB_STATE_DIR:-${XDG_DATA_HOME:-${HOME}/.local/share}/homelab}" KUBECONFIG="${KUBECONFIG:-${KUBECONFIG_PATH:-${HOME}/.kube/config}}" diff --git a/scripts/route-inventory b/scripts/route-inventory index be27220..27350f8 100755 --- a/scripts/route-inventory +++ b/scripts/route-inventory @@ -1,6 +1,9 @@ #!/usr/bin/env bash set -euo pipefail +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "${REPO_ROOT}/scripts/cluster-env.sh" + KUBECONFIG_PATH="${KUBECONFIG:-${LAB_KUBECONFIG_PATH:-/home/jv/.kube/config}}" KUMA_MONITORS_FILE="${LAB_UPTIME_KUMA_MONITORS_FILE:-infra/rpi-services/uptime-kuma-monitors.json}" INGRESS_JSON="" diff --git a/scripts/scorecard b/scripts/scorecard index fd7d709..d33dcd1 100755 --- a/scripts/scorecard +++ b/scripts/scorecard @@ -2,6 +2,7 @@ set -euo pipefail REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "${REPO_ROOT}/scripts/cluster-env.sh" failures=0 warnings=0 diff --git a/scripts/security-attack-path b/scripts/security-attack-path index ba2aa23..571bbf9 100755 --- a/scripts/security-attack-path +++ b/scripts/security-attack-path @@ -1,6 +1,9 @@ #!/usr/bin/env bash set -euo pipefail +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "${REPO_ROOT}/scripts/cluster-env.sh" + KUBECONFIG="${KUBECONFIG:-${HOME}/.kube/config}" ATTACK_NAMESPACE="${1:-${SECURITY_ATTACK_NAMESPACE:-website-production}}" ATTACK_WORKLOAD="${2:-${SECURITY_ATTACK_WORKLOAD:-deployment/php-website-deployment}}" diff --git a/scripts/security-logs b/scripts/security-logs index e7c4e97..9392308 100755 --- a/scripts/security-logs +++ b/scripts/security-logs @@ -1,6 +1,9 @@ #!/usr/bin/env bash set -euo pipefail +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "${REPO_ROOT}/scripts/cluster-env.sh" + HOMELAB_STATE_DIR="${HOMELAB_STATE_DIR:-${XDG_DATA_HOME:-${HOME}/.local/share}/homelab}" SECURITY_REPORT_DIR="${SECURITY_REPORT_DIR:-${HOMELAB_STATE_DIR}/security-reports}" SECURITY_LOG_SINCE="${SECURITY_LOG_SINCE:-24h}" diff --git a/scripts/state-status b/scripts/state-status index a40cd62..2315757 100755 --- a/scripts/state-status +++ b/scripts/state-status @@ -10,6 +10,10 @@ import re import subprocess import sys from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent)) +from cluster_runtime_context import environment + +os.environ.update(environment()) STACKS = { "provisioning": "bootstrap/provisioning", diff --git a/scripts/synthetic-checks b/scripts/synthetic-checks index 08cabf1..251c3a6 100755 --- a/scripts/synthetic-checks +++ b/scripts/synthetic-checks @@ -1,6 +1,9 @@ #!/usr/bin/env bash set -euo pipefail +REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "${REPO_ROOT}/scripts/cluster-env.sh" + KUBECONFIG_PATH="${KUBECONFIG:-${LAB_KUBECONFIG_PATH:-/home/jv/.kube/config}}" GITEA_HTTP_URL="${LAB_GITEA_ROOT_URL:-https://lab2025.duckdns.org/git/}" GITEA_LOCAL_URL="${LAB_GITEA_LOCAL_URL:-http://127.0.0.1:3000/}" diff --git a/scripts/workers b/scripts/workers index ad7c83a..c8e17cc 100755 --- a/scripts/workers +++ b/scripts/workers @@ -2,6 +2,7 @@ set -euo pipefail REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +source "${REPO_ROOT}/scripts/cluster-env.sh" export PATH="${REPO_ROOT}/scripts/guarded-bin:${PATH}" KUBECONFIG_PATH="${KUBECONFIG:-${LAB_KUBECONFIG_PATH:-/home/jv/.kube/config}}" PIMOX_HOST="${LAB_PIMOX_HOST:-192.168.100.80}" @@ -182,6 +183,11 @@ sudo '$PIMOX_QM_BIN' start '$vmid'" drain_node() { local node="${1:-}" + if [[ "${LAB_CLUSTER_RUNTIME:-}" == k3s ]]; then + echo "Native K3s has no alternate worker; use stop-cluster for host maintenance." >&2 + return 2 + fi + if [ -z "$node" ]; then echo "workers drain requires a node name." >&2 exit 1 @@ -439,6 +445,30 @@ PY "${cmd[@]}" } +if [[ "${LAB_CLUSTER_RUNTIME}" == k3s ]]; then + case "${1:-}" in + list) + kubectl --kubeconfig "${KUBECONFIG_PATH}" get nodes -o wide + exit + ;; + disk-status|disk-cleanup) + case "${2:-all}" in + all|control-plane|cp|"${LAB_CLUSTER_CONTROL_PLANE_NODE_NAME}") ;; + *) echo "The native profile has no Pimox worker indexes; use control-plane." >&2; exit 2 ;; + esac + action=status + [[ "${1}" != disk-cleanup ]] || action=cleanup + args=() + [[ "${3:-}" != --yes ]] || args+=(--yes) + exec python3 "${REPO_ROOT}/scripts/k3s-node-diagnostics.py" "${action}" "${args[@]}" + ;; + start|stop|restart|tailnet|recreate-plan) + echo "VM worker operations are unavailable in native K3s. Use ./jeannie start-cluster or stop-cluster." >&2 + exit 2 + ;; + esac +fi + case "${1:-}" in list|disk-status|recreate-plan|help|-h|--help|"") ;; *) python3 "${REPO_ROOT}/scripts/cluster-context.py" check --kubeconfig "${KUBECONFIG_PATH}" >/dev/null || exit 1 ;; diff --git a/tests/jeannie/test_cluster_runtime_context.py b/tests/jeannie/test_cluster_runtime_context.py new file mode 100644 index 0000000..4a3ec7c --- /dev/null +++ b/tests/jeannie/test_cluster_runtime_context.py @@ -0,0 +1,68 @@ +"""Profile selection regressions; run on the Debian deployment host.""" + +import importlib.util +import json +import os +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch + + +SPEC = importlib.util.spec_from_file_location( + "runtime_context", Path(__file__).resolve().parents[2] / "scripts/cluster_runtime_context.py" +) +MODULE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(MODULE) + + +class ClusterRuntimeContextTests(unittest.TestCase): + def setUp(self): + temporary = tempfile.TemporaryDirectory() + self.addCleanup(temporary.cleanup) + self.root = Path(temporary.name) + profiles = { + name: {"runtime": "k3s" if name == "k3s" else "kubeadm", + "control_plane": {"node_name": name, "lan_ip": host, + "kubeconfig": f"/mock/{name}-config"}} + for name, host in (("debian", "192.0.2.1"), ("pimox", "192.0.2.2"), ("k3s", "192.0.2.3")) + } + inventory = self.root / "inventory.json" + inventory.write_text(json.dumps({"cluster": {"active_profile": "pimox", "profiles": profiles}})) + (self.root / "active-cluster.json").write_text(json.dumps({"profile": "k3s"})) + binding = self.root / "clusters/k3s/identity.json" + binding.parent.mkdir(parents=True) + binding.write_text(json.dumps({"kube_system_uid": "native-uid"})) + environment = patch.dict(os.environ, { + "HOMELAB_STATE_DIR": str(self.root), "HOMELAB_INVENTORY_FILE": str(inventory), + "LAB_CLUSTER_PROFILE": "debian", "KUBECONFIG": "/retired/config", + "TF_VAR_control_plane_host": "192.0.2.99", + }, clear=True) + environment.start() + self.addCleanup(environment.stop) + + def test_local_override_and_persisted_default(self): + self.assertEqual(MODULE.resolve()["profile"], "debian") + del os.environ["LAB_CLUSTER_PROFILE"] + self.assertEqual(MODULE.resolve()["profile"], "k3s") + + def test_api_ignores_stale_profile_and_kubeconfig(self): + os.environ["JEANNIE_REMOTE_SERVER"] = "true" + selected = MODULE.environment() + self.assertEqual(selected["LAB_CLUSTER_PROFILE"], "k3s") + self.assertEqual(selected["KUBECONFIG"], "/mock/k3s-config") + self.assertEqual(selected["TF_VAR_control_plane_host"], "192.0.2.3") + self.assertEqual(selected["TF_VAR_cluster_identity_uid"], "native-uid") + + def test_operation_pin_and_fresh_webhook_selection(self): + os.environ.update(JEANNIE_SERVICE_CONTEXT="true", JEANNIE_CLUSTER_PROFILE_PIN="pimox") + self.assertEqual(MODULE.resolve()["profile"], "pimox") + self.assertEqual(MODULE.resolve(follow_active=True)["profile"], "k3s") + + def test_unknown_selection_refused(self): + with self.assertRaises(ValueError): + MODULE.resolve("unknown") + + +if __name__ == "__main__": + unittest.main()