From 64eefb603cc8c77e129165fd41f4c8b8121cd07b Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Thu, 29 Oct 2026 20:38:25 -0600 Subject: [PATCH] Recover stale unscheduled Grafana pods during monitoring rollout --- bootstrap/platform/README.md | 12 +++ bootstrap/platform/main.tf | 2 +- lib/jeannie/pipeline.sh | 3 +- scripts/monitoring-readiness.py | 93 +++++++++++++++++++++- tests/jeannie/test_monitoring_readiness.py | 73 +++++++++++++++++ 5 files changed, 178 insertions(+), 5 deletions(-) diff --git a/bootstrap/platform/README.md b/bootstrap/platform/README.md index 7c36e89..17f3319 100644 --- a/bootstrap/platform/README.md +++ b/bootstrap/platform/README.md @@ -56,6 +56,18 @@ replicas still fail the check. The pipeline runs a live check even on an unchanged apply, and prints scheduling events, requests, and volume placement when the bounded readiness wait fails. +The pipeline also recovers Grafana's OrderedReady update deadlock: if its sole +pod is Pending and unscheduled on an old controller revision without the new +monitoring priority, readiness replaces that pod so the StatefulSet can create +the desired revision. Eligibility requires matching controller ownership, an +observed unpartitioned RollingUpdate, and the `homelab-monitoring` target +priority. The delete uses UID and resource-version preconditions; a replacement +or newly scheduled pod is preserved. Running, assigned, terminating, and +current-revision pods are never recycled, and PVCs are not deleted. +Calling `scripts/monitoring-readiness.py` directly remains read-only unless +`--recover-stale-pending` is explicitly supplied; the deployment pipeline +supplies that flag automatically. + After syncing the repository, run on Debian or through the remote API: ```bash diff --git a/bootstrap/platform/main.tf b/bootstrap/platform/main.tf index fec1a61..f799ba9 100644 --- a/bootstrap/platform/main.tf +++ b/bootstrap/platform/main.tf @@ -2315,7 +2315,7 @@ set -euo pipefail python3 "${path.module}/../../scripts/monitoring-readiness.py" \ --kubeconfig "${self.triggers.kubeconfig_path}" \ - --namespace "${self.triggers.namespace}" + --namespace "${self.triggers.namespace}" --recover-stale-pending EOT } } diff --git a/lib/jeannie/pipeline.sh b/lib/jeannie/pipeline.sh index a7a8ed6..5a219a9 100644 --- a/lib/jeannie/pipeline.sh +++ b/lib/jeannie/pipeline.sh @@ -8111,7 +8111,8 @@ platform_apply() { local monitoring_namespace monitoring_namespace="$(tofu -chdir="${REPO_ROOT}/bootstrap/platform" output -raw monitoring_namespace)" || return 1 python3 "${REPO_ROOT}/scripts/monitoring-readiness.py" \ - --kubeconfig "${KUBECONFIG_PATH}" --namespace "${monitoring_namespace}" || return 1 + --kubeconfig "${KUBECONFIG_PATH}" --namespace "${monitoring_namespace}" \ + --recover-stale-pending || return 1 fi } diff --git a/scripts/monitoring-readiness.py b/scripts/monitoring-readiness.py index e695870..37b36f1 100644 --- a/scripts/monitoring-readiness.py +++ b/scripts/monitoring-readiness.py @@ -1,11 +1,12 @@ #!/usr/bin/env python3 -"""Read-only readiness checks for Helm and Operator monitoring workloads.""" +"""Monitoring readiness checks with opt-in recovery of stale unscheduled Grafana pods.""" import argparse import json import subprocess import sys import time +from urllib.parse import quote def owned(name, release): @@ -62,11 +63,12 @@ def readiness_errors(items, release): return errors -def kubectl(args, *command): +def kubectl(args, *command, input_text=None): result = subprocess.run( ["kubectl", "--kubeconfig", args.kubeconfig, "--request-timeout=10s", *command], capture_output=True, text=True, + input=input_text, timeout=15, check=False, ) @@ -75,6 +77,87 @@ def kubectl(args, *command): return json.loads(result.stdout) +def stale_pending_grafana(statefulset, pod, release): + """Only an old, unscheduled pod of the single-replica Grafana is eligible.""" + metadata = statefulset.get("metadata", {}) + spec = statefulset.get("spec", {}) + status = statefulset.get("status", {}) + pod_meta = pod.get("metadata", {}) + pod_spec = pod.get("spec", {}) + pod_status = pod.get("status", {}) + strategy = spec.get("updateStrategy", {}) + target_revision = status.get("updateRevision") + old_revision = pod_meta.get("labels", {}).get("controller-revision-hash") + target_priority = spec.get("template", {}).get("spec", {}).get("priorityClassName") + return ( + statefulset.get("kind") == "StatefulSet" + and metadata.get("name") == release + "-grafana" + and bool(metadata.get("uid")) + and not metadata.get("deletionTimestamp") + and spec.get("replicas", 1) == 1 + and strategy.get("type", "RollingUpdate") == "RollingUpdate" + and strategy.get("rollingUpdate", {}).get("partition", 0) == 0 + and status.get("observedGeneration", 0) >= metadata.get("generation", 1) + and bool(target_revision) + and bool(old_revision) + and old_revision != target_revision + and target_priority == "homelab-monitoring" + and pod_spec.get("priorityClassName") != target_priority + and pod_meta.get("name") == release + "-grafana-0" + and bool(pod_meta.get("namespace")) + and pod_meta.get("namespace") == metadata.get("namespace") + and bool(pod_meta.get("uid")) + and bool(pod_meta.get("resourceVersion")) + and not pod_meta.get("deletionTimestamp") + and not pod_spec.get("nodeName") + and pod_status.get("phase") == "Pending" + and any(c.get("type") == "PodScheduled" and c.get("status") == "False" + and c.get("reason") == "Unschedulable" + for c in pod_status.get("conditions", [])) + and any(owner.get("kind") == "StatefulSet" and owner.get("controller") is True + and owner.get("uid") == metadata["uid"] + for owner in pod_meta.get("ownerReferences", [])) + ) + + +def recover_stale_grafana(args, items): + name = args.release + "-grafana" + statefulset = next((item for item in items if item.get("kind") == "StatefulSet" + and item.get("metadata", {}).get("name") == name), None) + if not statefulset: + return + status = statefulset.get("status", {}) + if not status.get("updateRevision") or status.get("currentRevision") == status["updateRevision"]: + return + pods = kubectl(args, "-n", args.namespace, "get", "pods", "--field-selector", + "metadata.name=" + name + "-0", "-o", "json")["items"] + if not pods: + return + # Re-read the StatefulSet so eligibility follows its latest desired state. + statefulset = kubectl(args, "-n", args.namespace, "get", "statefulset", name, "-o", "json") + pod = pods[0] + if not stale_pending_grafana(statefulset, pod, args.release): + return + metadata = pod["metadata"] + options = { + "apiVersion": "v1", + "kind": "DeleteOptions", + "preconditions": {"uid": metadata["uid"], "resourceVersion": metadata["resourceVersion"]}, + "propagationPolicy": "Orphan", + } + path = "/api/v1/namespaces/" + quote(args.namespace, safe="") + "/pods/" + quote(metadata["name"], safe="") + print(f"Recovering stale unscheduled Grafana pod {metadata['name']}; PVC preserved.", flush=True) + try: + # UID/RV preconditions prevent deleting a replacement or a pod that + # became scheduled after the eligibility check. No force deletion. + kubectl(args, "delete", "--raw", path, "-f", "-", input_text=json.dumps(options)) + except RuntimeError as exc: + if "(Conflict)" in str(exc) or "(NotFound)" in str(exc): + print("Grafana pod changed during recovery; rechecking controller state.", flush=True) + return + raise + + def diagnostics(args): """Print scheduling inputs without container environments or secret data.""" print("Monitoring scheduling diagnostics:", file=sys.stderr) @@ -139,6 +222,8 @@ def main(): parser.add_argument("--namespace", default="monitoring") parser.add_argument("--release", default="prometheus-stack") parser.add_argument("--timeout", type=int, default=300) + parser.add_argument("--recover-stale-pending", action="store_true", + help="Replace only a stale, unscheduled Grafana pod blocked on an old priority revision") args = parser.parse_args() if args.timeout < 1: parser.error("--timeout must be positive") @@ -148,8 +233,10 @@ def main(): try: items = kubectl(args, "-n", args.namespace, "get", "deployment,statefulset,daemonset", "-o", "json")["items"] errors = readiness_errors(items, args.release) + if errors and args.recover_stale_pending: + recover_stale_grafana(args, items) except (RuntimeError, subprocess.TimeoutExpired, ValueError, KeyError) as exc: - errors = [f"Unable to read monitoring controllers: {exc}"] + errors = [f"Unable to reconcile monitoring readiness: {exc}"] if not errors: print("Prometheus stack workloads are ready (including Prometheus and Grafana).") return 0 diff --git a/tests/jeannie/test_monitoring_readiness.py b/tests/jeannie/test_monitoring_readiness.py index 2085f88..db420f2 100644 --- a/tests/jeannie/test_monitoring_readiness.py +++ b/tests/jeannie/test_monitoring_readiness.py @@ -3,6 +3,8 @@ import importlib.util import unittest from pathlib import Path +from types import SimpleNamespace +from unittest.mock import patch MODULE_PATH = Path(__file__).resolve().parents[2] / "scripts/monitoring-readiness.py" @@ -63,5 +65,76 @@ class MonitoringReadinessTests(unittest.TestCase): self.assertTrue(MODULE.readiness_errors(self.items, "prometheus-stack")) +class StaleGrafanaRecoveryTests(unittest.TestCase): + def setUp(self): + self.sts = controller("StatefulSet", "prometheus-stack-grafana") + self.sts["metadata"].update(uid="grafana-controller", namespace="monitoring") + self.sts["spec"]["template"] = {"spec": {"priorityClassName": "homelab-monitoring"}} + self.sts["status"].update(currentRevision="old", updateRevision="new", readyReplicas=0) + self.pod = { + "kind": "Pod", + "metadata": { + "name": "prometheus-stack-grafana-0", + "namespace": "monitoring", + "uid": "old-pod-uid", + "resourceVersion": "42", + "labels": {"controller-revision-hash": "old"}, + "ownerReferences": [{"kind": "StatefulSet", "controller": True, "uid": "grafana-controller"}], + }, + "spec": {}, + "status": { + "phase": "Pending", + "conditions": [{"type": "PodScheduled", "status": "False", "reason": "Unschedulable"}], + }, + } + + def eligible(self): + return MODULE.stale_pending_grafana(self.sts, self.pod, "prometheus-stack") + + def test_confirmed_old_unscheduled_priority_revision_is_eligible(self): + self.assertTrue(self.eligible()) + + def test_running_or_assigned_pod_is_preserved(self): + self.pod["status"]["phase"] = "Running" + self.assertFalse(self.eligible()) + self.pod["status"]["phase"] = "Pending" + self.pod["spec"]["nodeName"] = "pimox-worker-01" + self.assertFalse(self.eligible()) + + def test_target_revision_pod_is_never_recycled(self): + self.pod["metadata"]["labels"]["controller-revision-hash"] = "new" + self.assertFalse(self.eligible()) + + def test_new_priority_pod_is_preserved_even_if_unschedulable(self): + self.pod["spec"]["priorityClassName"] = "homelab-monitoring" + self.assertFalse(self.eligible()) + + def test_unrelated_owner_is_preserved(self): + self.pod["metadata"]["ownerReferences"][0]["uid"] = "different-controller" + self.assertFalse(self.eligible()) + + def test_missing_precondition_metadata_is_rejected(self): + del self.pod["metadata"]["resourceVersion"] + self.assertFalse(self.eligible()) + + def test_partitioned_or_unobserved_rollout_is_preserved(self): + self.sts["spec"]["updateStrategy"] = {"type": "RollingUpdate", "rollingUpdate": {"partition": 1}} + self.assertFalse(self.eligible()) + self.sts["spec"].pop("updateStrategy") + self.sts["metadata"]["generation"] = 4 + self.assertFalse(self.eligible()) + + def test_only_pod_delete_with_uid_and_version_preconditions_is_sent(self): + import json + + args = SimpleNamespace(release="prometheus-stack", namespace="monitoring") + with patch.object(MODULE, "kubectl", side_effect=[{"items": [self.pod]}, self.sts, {}]) as call: + MODULE.recover_stale_grafana(args, [self.sts]) + request = call.call_args + self.assertEqual(request.args[1:], ("delete", "--raw", "/api/v1/namespaces/monitoring/pods/prometheus-stack-grafana-0", "-f", "-")) + self.assertEqual(json.loads(request.kwargs["input_text"])["preconditions"], + {"uid": "old-pod-uid", "resourceVersion": "42"}) + + if __name__ == "__main__": unittest.main()