From e8499a1312a30cac34b9ff82b11cbcf87525b949 Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Thu, 29 Oct 2026 20:02:15 -0600 Subject: [PATCH] Prioritize persistent monitoring and verify live controller readiness --- bootstrap/platform/README.md | 33 +++++ bootstrap/platform/main.tf | 82 ++++++----- lib/jeannie/pipeline.sh | 10 +- scripts/monitoring-readiness.py | 151 +++++++++++++++++++++ tests/jeannie/test_monitoring_readiness.py | 67 +++++++++ 5 files changed, 300 insertions(+), 43 deletions(-) create mode 100644 scripts/monitoring-readiness.py create mode 100644 tests/jeannie/test_monitoring_readiness.py diff --git a/bootstrap/platform/README.md b/bootstrap/platform/README.md index ae6356f..6e09bd4 100644 --- a/bootstrap/platform/README.md +++ b/bootstrap/platform/README.md @@ -20,3 +20,36 @@ Available components are `calico`, `metrics`, `dns`, `metallb`, `ingress`, Targeted applies skip the legacy existing-resource adoption pass, which avoids touching unrelated platform state during a small change. Use `platform all` for the full reconciliation and adoption path. + +## Monitoring during reduced CPU capacity + +`platform monitoring` creates the `homelab-monitoring` PriorityClass before +updating Prometheus, Grafana, and their Operator. These workloads have priority +100000, above ordinary workloads and below Kubernetes system-critical pods. +If their local-volume node has no unreserved CPU, the scheduler can preempt +lower-priority pods to admit monitoring. Those workloads may remain Pending +until capacity is restored; priority does not add CPU capacity. + +Prometheus requests 25m CPU plus 25m for its config reloader. It can run on a +one-core VM when that scheduling budget is available. Existing node selectors, +PVCs, and PV node affinity are retained: the pipeline does not move hostpath +data, delete claims, or schedule monitoring on the control plane to bypass +storage placement. + +Readiness checks follow Deployments, StatefulSets, and DaemonSets, including +the StatefulSets generated by Prometheus Operator (whose instance label can +differ from the Helm release). Old failed pods do not block a healthy replacement. +Missing Prometheus or Grafana workloads, incomplete rollouts, and unavailable +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. + +After syncing the repository, run on Debian or through the remote API: + +```bash +./jeannie remote platform monitoring +``` + +The monitoring target includes the scheduling priority dependency and the +repo-managed dashboard ConfigMaps; no separate pod deletion or dashboard +restart command is required. diff --git a/bootstrap/platform/main.tf b/bootstrap/platform/main.tf index 1100c11..cad94ae 100644 --- a/bootstrap/platform/main.tf +++ b/bootstrap/platform/main.tf @@ -1827,6 +1827,22 @@ EOT } } +output "monitoring_namespace" { + description = "Resolved namespace used for live monitoring readiness checks." + value = var.observability.namespace +} + +resource "kubernetes_priority_class_v1" "monitoring" { + metadata { + name = "homelab-monitoring" + } + + value = 100000 + global_default = false + preemption_policy = "PreemptLowerPriority" + description = "Keep Prometheus and Grafana schedulable on their local-volume nodes when homelab CPU capacity is degraded." +} + resource "helm_release" "prometheus_stack" { depends_on = [null_resource.prometheus_stack_helm_recovery] name = "prometheus-stack" @@ -1853,7 +1869,7 @@ resource "helm_release" "prometheus_stack" { expr = "up{job=\"oci-edge-node\"} == 0" "for" = "5m" labels = { - severity = "critical" + severity = "critical" host_group = "public-edge" } annotations = { @@ -1866,7 +1882,7 @@ resource "helm_release" "prometheus_stack" { expr = "up{job=\"oci-email-node\"} == 0" "for" = "5m" labels = { - severity = "critical" + severity = "critical" host_group = "email" } annotations = { @@ -1879,7 +1895,7 @@ resource "helm_release" "prometheus_stack" { expr = "100 - (avg by (instance) (rate(node_cpu_seconds_total{job=\"oci-edge-node\",mode=\"idle\"}[5m])) * 100) > 85" "for" = "15m" labels = { - severity = "warning" + severity = "warning" host_group = "public-edge" } annotations = { @@ -1892,7 +1908,7 @@ resource "helm_release" "prometheus_stack" { expr = "100 - (avg by (instance) (rate(node_cpu_seconds_total{job=\"oci-email-node\",mode=\"idle\"}[5m])) * 100) > 85" "for" = "15m" labels = { - severity = "warning" + severity = "warning" host_group = "email" } annotations = { @@ -1917,6 +1933,7 @@ resource "helm_release" "prometheus_stack" { enabled = false } prometheusOperator = { + priorityClassName = kubernetes_priority_class_v1.monitoring.metadata[0].name affinity = local.prometheus_operator_affinity nodeSelector = local.prometheus_stack_node_selector topologySpreadConstraints = local.prometheus_operator_topology_spread_constraints @@ -2010,8 +2027,9 @@ resource "helm_release" "prometheus_stack" { } prometheus = { prometheusSpec = { - nodeSelector = local.prometheus_stack_node_selector - retention = var.observability.prometheus.retention + priorityClassName = kubernetes_priority_class_v1.monitoring.metadata[0].name + nodeSelector = local.prometheus_stack_node_selector + retention = var.observability.prometheus.retention additionalScrapeConfigs = yamlencode(concat([ { job_name = "rpi-node" @@ -2074,27 +2092,27 @@ resource "helm_release" "prometheus_stack" { job_name = "oci-edge-node" static_configs = [{ targets = [var.oci_edge_metrics_target] - labels = { host_group = "public-edge" } + labels = { host_group = "public-edge" } }] metrics_path = "/metrics" - scheme = "http" - }], var.oci_edge_container_metrics_target == "" ? [] : [{ + scheme = "http" + }], var.oci_edge_container_metrics_target == "" ? [] : [{ job_name = "oci-edge-containers" static_configs = [{ targets = [var.oci_edge_container_metrics_target] - labels = { host_group = "public-edge" } + labels = { host_group = "public-edge" } }] metrics_path = "/metrics" - scheme = "http" - }], var.oci_email_metrics_target == "" ? [] : [{ + scheme = "http" + }], var.oci_email_metrics_target == "" ? [] : [{ job_name = "oci-email-node" static_configs = [{ targets = [var.oci_email_metrics_target] - labels = { host_group = "email" } + labels = { host_group = "email" } }] metrics_path = "/metrics" - scheme = "http" - }], var.jeannie_api_metrics_token == "" ? [] : [{ + scheme = "http" + }], var.jeannie_api_metrics_token == "" ? [] : [{ job_name = "jeannie-api" metrics_path = "/metrics" scheme = "https" @@ -2142,7 +2160,8 @@ resource "helm_release" "prometheus_stack" { } } grafana = { - nodeSelector = local.prometheus_stack_node_selector + priorityClassName = kubernetes_priority_class_v1.monitoring.metadata[0].name + nodeSelector = local.prometheus_stack_node_selector envValueFrom = var.grafana_sso_enabled ? { GF_AUTH_GENERIC_OAUTH_CLIENT_SECRET = { secretKeyRef = { @@ -2264,7 +2283,8 @@ resource "null_resource" "prometheus_stack_readiness" { kubeconfig_path = var.kubeconfig_path namespace = var.observability.namespace release_version = var.observability.prometheus.version - readiness_check = "2" + readiness_check = "3" + checker_sha = filesha256("${path.module}/../../scripts/monitoring-readiness.py") } provisioner "local-exec" { @@ -2272,31 +2292,9 @@ resource "null_resource" "prometheus_stack_readiness" { command = <&2 - kubectl --kubeconfig "$kubeconfig" -n "$namespace" get pods,sts,deploy,pvc -l "$selector" -o wide >&2 || true - kubectl --kubeconfig "$kubeconfig" -n "$namespace" get events --sort-by=.lastTimestamp | tail -n 80 >&2 || true -} - -trap dump_prometheus_debug ERR - -until kubectl --kubeconfig "$kubeconfig" -n "$namespace" get pods -l "$selector" -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\t"}{range .status.conditions[*]}{.type}={.status}{" "}{end}{"\n"}{end}' 2>/dev/null | - awk 'NF > 0 { count++ } ($2 == "Succeeded") || ($2 == "Running" && $0 ~ /Ready=True/) { next } { failed = 1 } END { exit !(count > 0 && !failed) }'; do - if [ "$elapsed" -ge "$timeout_seconds" ]; then - echo "Timed out waiting for Prometheus stack workloads after $${timeout_seconds}s." >&2 - exit 1 - fi - sleep 10 - elapsed=$((elapsed + 10)) -done - -echo "Prometheus stack workloads are ready." +python3 "${path.module}/../../scripts/monitoring-readiness.py" \ + --kubeconfig "${self.triggers.kubeconfig_path}" \ + --namespace "${self.triggers.namespace}" EOT } } diff --git a/lib/jeannie/pipeline.sh b/lib/jeannie/pipeline.sh index dddc3df..9360183 100644 --- a/lib/jeannie/pipeline.sh +++ b/lib/jeannie/pipeline.sh @@ -7970,7 +7970,15 @@ platform_apply() { ;; esac - run_tofu_stack "bootstrap/platform" "${targets[@]}" + run_tofu_stack "bootstrap/platform" "${targets[@]}" || return 1 + # Provisioners only execute when their triggers change. Verify live + # monitoring health even when OpenTofu reports an unchanged stack. + if [[ "${component}" == "all" || "${component}" == "monitoring" ]]; then + 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 + fi } edge_apply() { diff --git a/scripts/monitoring-readiness.py b/scripts/monitoring-readiness.py new file mode 100644 index 0000000..cd7667d --- /dev/null +++ b/scripts/monitoring-readiness.py @@ -0,0 +1,151 @@ +#!/usr/bin/env python3 +"""Read-only readiness checks for Helm and Operator monitoring workloads.""" + +import argparse +import json +import subprocess +import sys +import time + + +def owned(name, release): + return any( + name.startswith(prefix) + for prefix in (release + "-", "prometheus-" + release + "-", "alertmanager-" + release + "-") + ) + + +def readiness_errors(items, release): + """Check desired controller state, including Operator-created StatefulSets.""" + errors = [] + roles = set() + for item in items: + metadata = item.get("metadata", {}) + name = metadata.get("name", "") + if not owned(name, release): + continue + kind = item.get("kind", "") + if name.startswith("prometheus-" + release + "-") and kind == "StatefulSet": + roles.add("Prometheus") + if name == release + "-grafana": + roles.add("Grafana") + if name.endswith("-operator") and kind == "Deployment": + roles.add("Prometheus Operator") + + spec = item.get("spec", {}) + status = item.get("status", {}) + desired = spec.get("replicas", 1) + if kind == "DaemonSet": + desired = status.get("desiredNumberScheduled", 0) + ready = status.get("numberReady", 0) + updated = status.get("updatedNumberScheduled", 0) + else: + ready = status.get("readyReplicas", 0) + updated = status.get("updatedReplicas", 0) + observed = status.get("observedGeneration", 0) >= metadata.get("generation", 1) + complete = observed and ready >= desired and updated >= desired + if kind == "Deployment": + complete = complete and status.get("replicas", 0) == desired + if kind == "StatefulSet" and desired: + complete = complete and status.get("currentRevision") == status.get("updateRevision") + if kind == "DaemonSet" and not desired: + complete = False + if name == release + "-grafana" and not desired: + complete = False + if name.startswith("prometheus-" + release + "-") and not desired: + complete = False + if not complete: + errors.append(f"{kind}/{name}: ready={ready}/{desired} updated={updated} observed={observed}") + + for role in sorted({"Prometheus", "Grafana", "Prometheus Operator"} - roles): + errors.append(f"{role}: workload not created yet") + return errors + + +def kubectl(args, *command): + result = subprocess.run( + ["kubectl", "--kubeconfig", args.kubeconfig, "--request-timeout=10s", *command], + capture_output=True, + text=True, + timeout=15, + check=False, + ) + if result.returncode: + raise RuntimeError(result.stderr.strip()[:1500]) + return json.loads(result.stdout) + + +def diagnostics(args): + """Print scheduling inputs without container environments or secret data.""" + print("Monitoring scheduling diagnostics:", file=sys.stderr) + for resource in ("pods", "pvc", "events"): + try: + items = kubectl(args, "-n", args.namespace, "get", resource, "-o", "json")["items"] + if resource == "events": + items = sorted(items, key=lambda x: x.get("lastTimestamp") or x["metadata"].get("creationTimestamp", "")) + for item in items[-15:]: + print(f"event {item.get('reason')}: {item.get('message')}", file=sys.stderr) + continue + for item in items: + name = item["metadata"]["name"] + if not owned(name, args.release) and not name.startswith("storage-" + args.release + "-"): + continue + spec = item.get("spec", {}) + status = item.get("status", {}) + record = {"name": name, "phase": status.get("phase")} + if resource == "pods": + record.update( + node=spec.get("nodeName"), + selector=spec.get("nodeSelector"), + priority=spec.get("priorityClassName"), + conditions=status.get("conditions"), + requests=[c.get("resources", {}).get("requests", {}) for c in spec.get("containers", [])], + ) + else: + record["volume"] = spec.get("volumeName") + print(json.dumps(record), file=sys.stderr) + except (RuntimeError, subprocess.TimeoutExpired, ValueError, KeyError) as exc: + print(f"Cannot read {resource}: {exc}", file=sys.stderr) + try: + volumes = kubectl(args, "get", "pv", "-o", "json")["items"] + for volume in volumes: + claim = volume.get("spec", {}).get("claimRef", {}) + if claim.get("namespace") == args.namespace: + print(json.dumps({"claim": claim.get("name"), "nodeAffinity": volume["spec"].get("nodeAffinity")}), file=sys.stderr) + except (RuntimeError, subprocess.TimeoutExpired, ValueError, KeyError) as exc: + print(f"Cannot read volume placement: {exc}", file=sys.stderr) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--kubeconfig", required=True) + parser.add_argument("--namespace", default="monitoring") + parser.add_argument("--release", default="prometheus-stack") + parser.add_argument("--timeout", type=int, default=300) + args = parser.parse_args() + if args.timeout < 1: + parser.error("--timeout must be positive") + deadline = time.monotonic() + args.timeout + previous = None + while True: + try: + items = kubectl(args, "-n", args.namespace, "get", "deployment,statefulset,daemonset", "-o", "json")["items"] + errors = readiness_errors(items, args.release) + except (RuntimeError, subprocess.TimeoutExpired, ValueError, KeyError) as exc: + errors = [f"Unable to read monitoring controllers: {exc}"] + if not errors: + print("Prometheus stack workloads are ready (including Prometheus and Grafana).") + return 0 + if errors != previous: + print("Waiting for monitoring: " + "; ".join(errors), flush=True) + previous = errors + remaining = deadline - time.monotonic() + if remaining <= 0: + diagnostics(args) + print("Monitoring readiness timed out; PVC placement and resource requests were preserved.", file=sys.stderr) + return 1 + time.sleep(min(5, remaining)) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/jeannie/test_monitoring_readiness.py b/tests/jeannie/test_monitoring_readiness.py new file mode 100644 index 0000000..2085f88 --- /dev/null +++ b/tests/jeannie/test_monitoring_readiness.py @@ -0,0 +1,67 @@ +"""Regression checks for monitoring recovery; run on the Debian host.""" + +import importlib.util +import unittest +from pathlib import Path + + +MODULE_PATH = Path(__file__).resolve().parents[2] / "scripts/monitoring-readiness.py" +SPEC = importlib.util.spec_from_file_location("monitoring_readiness", MODULE_PATH) +MODULE = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(MODULE) + + +def controller(kind, name): + status = {"observedGeneration": 3, "replicas": 1, "readyReplicas": 1, "updatedReplicas": 1} + if kind == "StatefulSet": + status.update(currentRevision="ready-revision", updateRevision="ready-revision") + return { + "kind": kind, + "metadata": {"name": name, "generation": 3}, + "spec": {"replicas": 1}, + "status": status, + } + + +class MonitoringReadinessTests(unittest.TestCase): + def setUp(self): + self.items = [ + controller("Deployment", "prometheus-stack-kube-prom-operator"), + controller("StatefulSet", "prometheus-stack-grafana"), + controller("StatefulSet", "prometheus-prometheus-stack-kube-prom-prometheus"), + ] + + def test_operator_statefulset_is_checked_without_helm_instance_label(self): + self.items[-1]["status"]["readyReplicas"] = 0 + errors = MODULE.readiness_errors(self.items, "prometheus-stack") + self.assertTrue(any("StatefulSet/prometheus-prometheus-stack" in e for e in errors)) + + def test_missing_prometheus_cannot_pass_with_only_helm_workloads(self): + errors = MODULE.readiness_errors(self.items[:-1], "prometheus-stack") + self.assertIn("Prometheus: workload not created yet", errors) + + def test_unrelated_controller_does_not_block_monitoring(self): + self.items.append({ + "kind": "Deployment", + "metadata": {"name": "unrelated-deployment", "generation": 1}, + "spec": {"replicas": 2}, + "status": {}, + }) + self.assertEqual(MODULE.readiness_errors(self.items, "prometheus-stack"), []) + + def test_unobserved_new_spec_is_not_healthy(self): + self.items[0]["metadata"]["generation"] = 4 + self.assertTrue(MODULE.readiness_errors(self.items, "prometheus-stack")) + + def test_old_statefulset_revision_is_not_healthy(self): + self.items[1]["status"]["currentRevision"] = "old-revision" + self.assertTrue(MODULE.readiness_errors(self.items, "prometheus-stack")) + + def test_scaled_down_prometheus_is_not_healthy(self): + self.items[-1]["spec"]["replicas"] = 0 + self.items[-1]["status"].update(replicas=0, readyReplicas=0, updatedReplicas=0) + self.assertTrue(MODULE.readiness_errors(self.items, "prometheus-stack")) + + +if __name__ == "__main__": + unittest.main()