#!/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)