Reuse Kubernetes resource snapshots in diagnostics
This commit is contained in:
parent
1bd3cba8d2
commit
d721c4cea9
|
|
@ -7,6 +7,10 @@ parallel (four at a time by default, capped at eight). Set
|
|||
`LAB_REPORT_PARALLELISM=1` to serialize them or `LAB_REPORT_TIMING=true` to
|
||||
print probe elapsed time. Identical selected HTTP/container probes reuse results
|
||||
only within that report. Healing performs its own live identity checks.
|
||||
Compact reports also share one nodes, pods, Deployments, and StatefulSets list
|
||||
per resource type as needed; snapshots are point-in-time, may differ across
|
||||
resource types, and are discarded when the report ends. API readiness, logs,
|
||||
identity checks, and healing verification continue to query live services.
|
||||
|
||||
Status examines Gitea and Traefik logs from the last five minutes by default;
|
||||
`LAB_STATUS_LOG_SINCE` overrides the interval. A few Gitea client disconnects
|
||||
|
|
|
|||
|
|
@ -7,6 +7,10 @@ parallel (four at a time by default, capped at eight). Set
|
|||
`LAB_REPORT_PARALLELISM=1` to serialize them or `LAB_REPORT_TIMING=true` to
|
||||
print probe elapsed time. Identical selected HTTP/container probes reuse results
|
||||
only within that report. Healing performs its own live identity checks.
|
||||
Compact reports also share one nodes, pods, Deployments, and StatefulSets list
|
||||
per resource type as needed; snapshots are point-in-time, may differ across
|
||||
resource types, and are discarded when the report ends. API readiness, logs,
|
||||
identity checks, and healing verification continue to query live services.
|
||||
|
||||
Status examines Gitea and Traefik logs from the last five minutes by default;
|
||||
`LAB_STATUS_LOG_SINCE` overrides the interval. A few Gitea client disconnects
|
||||
|
|
|
|||
|
|
@ -1522,7 +1522,28 @@ status_kubernetes_api_ok() {
|
|||
kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s get --raw=/readyz >/dev/null
|
||||
}
|
||||
|
||||
status_kubernetes_snapshot_fetch() {
|
||||
local resource="$1"
|
||||
local -a scope=()
|
||||
[[ "${resource}" == nodes ]] || scope=(-A)
|
||||
kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=15s get "${resource}" "${scope[@]}" -o json
|
||||
}
|
||||
|
||||
status_kubernetes_snapshot_check() {
|
||||
local resource="$1" action="$2" snapshot
|
||||
shift 2
|
||||
if ! snapshot="$(report_ui_cached_probe status_kubernetes_snapshot_fetch "${resource}")"; then
|
||||
printf 'Cannot read %s snapshot: %s\n' "${resource}" "${snapshot}" >&2
|
||||
return 1
|
||||
fi
|
||||
printf '%s' "${snapshot}" | python3 "${REPO_ROOT}/scripts/report-kubernetes.py" "${action}" "$@"
|
||||
}
|
||||
|
||||
status_kubernetes_nodes_ready() {
|
||||
if [[ "${REPORT_UI_PARALLEL:-false}" == true && -n "${REPORT_UI_WORK_DIR:-}" ]]; then
|
||||
status_kubernetes_snapshot_check nodes nodes-ready
|
||||
return
|
||||
fi
|
||||
local nodes
|
||||
local not_ready
|
||||
|
||||
|
|
@ -1542,6 +1563,11 @@ status_kubernetes_deployment_ready() {
|
|||
local namespace="$1"
|
||||
local deployment="$2"
|
||||
|
||||
if [[ "${REPORT_UI_PARALLEL:-false}" == true && -n "${REPORT_UI_WORK_DIR:-}" ]]; then
|
||||
status_kubernetes_snapshot_check deployments deployment-ready "${namespace}" "${deployment}"
|
||||
return
|
||||
fi
|
||||
|
||||
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" rollout status "deployment/${deployment}" --timeout=5s >/dev/null
|
||||
}
|
||||
|
||||
|
|
@ -1549,6 +1575,11 @@ status_kubernetes_statefulset_ready() {
|
|||
local namespace="$1"
|
||||
local statefulset="$2"
|
||||
|
||||
if [[ "${REPORT_UI_PARALLEL:-false}" == true && -n "${REPORT_UI_WORK_DIR:-}" ]]; then
|
||||
status_kubernetes_snapshot_check statefulsets statefulset-ready "${namespace}" "${statefulset}"
|
||||
return
|
||||
fi
|
||||
|
||||
kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" rollout status "statefulset/${statefulset}" --timeout=5s >/dev/null
|
||||
}
|
||||
|
||||
|
|
@ -1558,6 +1589,11 @@ status_kubernetes_deployment_image_not_bootstrap() {
|
|||
local container="$3"
|
||||
local image
|
||||
|
||||
if [[ "${REPORT_UI_PARALLEL:-false}" == true && -n "${REPORT_UI_WORK_DIR:-}" ]]; then
|
||||
status_kubernetes_snapshot_check deployments image "${namespace}" "${deployment}" "${container}"
|
||||
return
|
||||
fi
|
||||
|
||||
image="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" -n "${namespace}" get deployment "${deployment}" \
|
||||
-o "jsonpath={.spec.template.spec.containers[?(@.name==\"${container}\")].image}" 2>/dev/null || true)"
|
||||
if [[ -z "${image}" ]]; then
|
||||
|
|
@ -1573,6 +1609,11 @@ status_kubernetes_deployment_image_not_bootstrap() {
|
|||
status_no_problem_pods() {
|
||||
local rows
|
||||
|
||||
if [[ "${REPORT_UI_PARALLEL:-false}" == true && -n "${REPORT_UI_WORK_DIR:-}" ]]; then
|
||||
status_kubernetes_snapshot_check pods pods-problems
|
||||
return
|
||||
fi
|
||||
|
||||
rows="$(
|
||||
kubectl --kubeconfig "${KUBECONFIG_PATH}" get pods -A --no-headers 2>/dev/null |
|
||||
awk '$4 != "Running" && $4 != "Completed" { print $1 "/" $2 ":" $4 }'
|
||||
|
|
@ -1586,6 +1627,11 @@ status_no_problem_pods() {
|
|||
status_recent_deployments() {
|
||||
local rows
|
||||
|
||||
if [[ "${REPORT_UI_PARALLEL:-false}" == true && -n "${REPORT_UI_WORK_DIR:-}" ]]; then
|
||||
status_kubernetes_snapshot_check deployments deployments
|
||||
return
|
||||
fi
|
||||
|
||||
rows="$(
|
||||
kubectl --kubeconfig "${KUBECONFIG_PATH}" get deployments -A \
|
||||
-o custom-columns='NAMESPACE:.metadata.namespace,NAME:.metadata.name,READY:.status.readyReplicas,DESIRED:.spec.replicas,UPDATED:.status.updatedReplicas,AVAILABLE:.status.availableReplicas,AGE:.metadata.creationTimestamp' \
|
||||
|
|
@ -1602,6 +1648,11 @@ status_pod_restart_pressure() {
|
|||
local threshold="${LAB_STATUS_RESTART_THRESHOLD:-3}"
|
||||
local rows
|
||||
|
||||
if [[ "${REPORT_UI_PARALLEL:-false}" == true && -n "${REPORT_UI_WORK_DIR:-}" ]]; then
|
||||
status_kubernetes_snapshot_check pods pod-restarts "${threshold}"
|
||||
return
|
||||
fi
|
||||
|
||||
rows="$(
|
||||
kubectl --kubeconfig "${KUBECONFIG_PATH}" get pods -A --no-headers 2>/dev/null |
|
||||
awk -v threshold="${threshold}" '$5 + 0 >= threshold { print $1 "/" $2 ": restarts=" $5 " age=" $6 }'
|
||||
|
|
@ -1615,6 +1666,11 @@ status_pod_restart_pressure() {
|
|||
status_node_pressure() {
|
||||
local rows
|
||||
|
||||
if [[ "${REPORT_UI_PARALLEL:-false}" == true && -n "${REPORT_UI_WORK_DIR:-}" ]]; then
|
||||
status_kubernetes_snapshot_check nodes node-pressure
|
||||
return
|
||||
fi
|
||||
|
||||
rows="$(
|
||||
kubectl --kubeconfig "${KUBECONFIG_PATH}" get nodes -o jsonpath='{range .items[*]}{.metadata.name}{" "}{range .status.conditions[*]}{.type}{"="}{.status}{" "}{end}{"\n"}{end}' 2>/dev/null |
|
||||
awk '/MemoryPressure=True|DiskPressure=True|PIDPressure=True|NetworkUnavailable=True/ { print }'
|
||||
|
|
|
|||
|
|
@ -0,0 +1,97 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Evaluate one report check against a Kubernetes list snapshot on stdin."""
|
||||
|
||||
import json
|
||||
import sys
|
||||
|
||||
|
||||
def main():
|
||||
action, *args = sys.argv[1:]
|
||||
document = json.load(sys.stdin)
|
||||
items = document.get("items")
|
||||
if not isinstance(items, list):
|
||||
raise ValueError("Kubernetes snapshot does not contain an items list")
|
||||
|
||||
if action == "nodes-ready":
|
||||
if not items:
|
||||
raise ValueError("no Kubernetes nodes found")
|
||||
bad = [item["metadata"]["name"] for item in items if not any(
|
||||
condition.get("type") == "Ready" and condition.get("status") == "True"
|
||||
for condition in item.get("status", {}).get("conditions", []))]
|
||||
if bad:
|
||||
raise ValueError("not ready: " + ", ".join(bad))
|
||||
elif action == "node-pressure":
|
||||
bad = [f"{item['metadata']['name']}: {condition['type']}=True" for item in items
|
||||
for condition in item.get("status", {}).get("conditions", [])
|
||||
if condition.get("status") == "True" and condition.get("type") in
|
||||
{"DiskPressure", "MemoryPressure", "PIDPressure", "NetworkUnavailable"}]
|
||||
if bad:
|
||||
raise ValueError("; ".join(bad))
|
||||
elif action in {"pods-problems", "pod-restarts"}:
|
||||
issues = []
|
||||
for item in items:
|
||||
meta, status = item["metadata"], item.get("status", {})
|
||||
name = f"{meta.get('namespace')}/{meta.get('name')}"
|
||||
if action == "pods-problems":
|
||||
containers = status.get("initContainerStatuses", []) + status.get("containerStatuses", [])
|
||||
states = [container.get("state", {}).get("waiting", {}).get("reason") or
|
||||
container.get("state", {}).get("terminated", {}).get("reason") for container in containers]
|
||||
reason = ("Terminating" if meta.get("deletionTimestamp") else None) or status.get("reason") or next((value for value in states if value and value != "Completed"), None) or status.get("phase", "Unknown")
|
||||
if reason not in {"Running", "Completed", "Succeeded"}:
|
||||
issues.append(f"{name}:{reason}")
|
||||
else:
|
||||
count = sum(container.get("restartCount", 0) for container in
|
||||
status.get("initContainerStatuses", []) + status.get("containerStatuses", []))
|
||||
if count >= int(args[0]):
|
||||
issues.append(f"{name}: restarts={count}")
|
||||
if issues:
|
||||
raise ValueError("\n".join(issues))
|
||||
elif action == "deployments":
|
||||
bad = []
|
||||
for item in items:
|
||||
meta, spec, status = item["metadata"], item.get("spec", {}), item.get("status", {})
|
||||
desired = spec.get("replicas", 1)
|
||||
if any((status.get(field) or 0) != desired for field in ("readyReplicas", "updatedReplicas", "availableReplicas")):
|
||||
bad.append(f"{meta.get('namespace')}/{meta.get('name')}: ready={status.get('readyReplicas', 0) or 0}/{desired} updated={status.get('updatedReplicas', 0) or 0} available={status.get('availableReplicas', 0) or 0}")
|
||||
if bad:
|
||||
raise ValueError("\n".join(bad))
|
||||
elif action in {"deployment-ready", "statefulset-ready", "image"}:
|
||||
namespace, name = args[:2]
|
||||
item = next((entry for entry in items if entry.get("metadata", {}).get("namespace") == namespace
|
||||
and entry.get("metadata", {}).get("name") == name), None)
|
||||
if item is None:
|
||||
raise ValueError(f"{namespace}/{name} not found in snapshot")
|
||||
meta, spec, status = item["metadata"], item.get("spec", {}), item.get("status", {})
|
||||
if action == "image":
|
||||
container = next((entry for entry in spec.get("template", {}).get("spec", {}).get("containers", [])
|
||||
if entry.get("name") == args[2]), None)
|
||||
image = container.get("image", "") if container else ""
|
||||
if not image or image.endswith(":bootstrap"):
|
||||
raise ValueError(f"{namespace}/{name}: missing or bootstrap image for {args[2]}")
|
||||
return
|
||||
desired = spec.get("replicas", 1)
|
||||
generation = meta.get("generation", 0)
|
||||
if (status.get("observedGeneration") or 0) < generation:
|
||||
raise ValueError(f"{namespace}/{name}: controller has not observed generation {generation}")
|
||||
if action == "deployment-ready":
|
||||
if spec.get("paused") or any((status.get(field) or 0) != desired for field in ("updatedReplicas", "availableReplicas", "replicas")):
|
||||
raise ValueError(f"{namespace}/{name}: rollout incomplete (desired={desired}, updated={status.get('updatedReplicas', 0)}, available={status.get('availableReplicas', 0)})")
|
||||
else:
|
||||
strategy = spec.get("updateStrategy", {})
|
||||
partition = (strategy.get("rollingUpdate") or {}).get("partition", 0)
|
||||
rolling = strategy.get("type", "RollingUpdate") == "RollingUpdate"
|
||||
revisions_differ = (rolling and not partition and status.get("currentRevision") and
|
||||
status.get("updateRevision") and status["currentRevision"] != status["updateRevision"])
|
||||
if (status.get("readyReplicas") or 0) < desired or (rolling and
|
||||
(status.get("updatedReplicas") or 0) < max(0, desired - partition)) or revisions_differ:
|
||||
raise ValueError(f"{namespace}/{name}: rollout incomplete (desired={desired}, ready={status.get('readyReplicas', 0)}, updated={status.get('updatedReplicas', 0)})")
|
||||
else:
|
||||
raise ValueError(f"unknown snapshot check: {action}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (ValueError, KeyError, TypeError, json.JSONDecodeError) as error:
|
||||
print(f"Kubernetes snapshot check: {error}", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
"""Snapshot diagnostic regressions; run on the Debian deployment host."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[2] / "scripts/report-kubernetes.py"
|
||||
|
||||
|
||||
def check(action, items, *args):
|
||||
return subprocess.run([sys.executable, str(SCRIPT), action, *args],
|
||||
input=json.dumps({"items": items}), text=True, capture_output=True)
|
||||
|
||||
|
||||
class KubernetesReportTests(unittest.TestCase):
|
||||
def test_scaled_down_deployment_is_healthy(self):
|
||||
deployment = {"metadata": {"namespace": "gitea-runner", "name": "runner", "generation": 1},
|
||||
"spec": {"replicas": 0}, "status": {"observedGeneration": 1}}
|
||||
self.assertEqual(check("deployments", [deployment]).returncode, 0)
|
||||
self.assertEqual(check("deployment-ready", [deployment], "gitea-runner", "runner").returncode, 0)
|
||||
|
||||
def test_incomplete_rollout_and_missing_workload_fail(self):
|
||||
deployment = {"metadata": {"namespace": "app", "name": "web", "generation": 2},
|
||||
"spec": {"replicas": 1}, "status": {"observedGeneration": 1, "availableReplicas": 1}}
|
||||
self.assertNotEqual(check("deployment-ready", [deployment], "app", "web").returncode, 0)
|
||||
self.assertNotEqual(check("deployment-ready", [], "app", "web").returncode, 0)
|
||||
|
||||
def test_crashloop_and_notready_are_not_hidden(self):
|
||||
pod = {"metadata": {"namespace": "app", "name": "web"}, "status": {"phase": "Running",
|
||||
"containerStatuses": [{"restartCount": 5, "state": {"waiting": {"reason": "CrashLoopBackOff"}}}]}}
|
||||
node = {"metadata": {"name": "node"}, "status": {"conditions": [{"type": "Ready", "status": "False"}]}}
|
||||
self.assertIn("CrashLoopBackOff", check("pods-problems", [pod]).stderr)
|
||||
self.assertNotEqual(check("pod-restarts", [pod], "3").returncode, 0)
|
||||
self.assertNotEqual(check("nodes-ready", [node]).returncode, 0)
|
||||
|
||||
def test_partitioned_statefulset_requires_ready_replicas(self):
|
||||
workload = {"metadata": {"namespace": "app", "name": "db", "generation": 1},
|
||||
"spec": {"replicas": 2, "updateStrategy": {"rollingUpdate": {"partition": 1}}},
|
||||
"status": {"observedGeneration": 1, "readyReplicas": 1, "updatedReplicas": 1}}
|
||||
self.assertNotEqual(check("statefulset-ready", [workload], "app", "db").returncode, 0)
|
||||
Loading…
Reference in New Issue