my-homelab-configs/scripts/doctor-pod-evidence.py

115 lines
5.6 KiB
Python

#!/usr/bin/env python3
"""Extract bounded pod status and events without dumping pod specs or secrets."""
import json
import re
import sys
SECRET = re.compile(r"(?i)(bearer\s+|(?:token|password|secret|api[_-]?key)\s*[=:]\s*)([^\s|,]+)")
JSON_SECRET = re.compile(r'''(?i)(["'](?:token|password|secret|api[_-]?key)["']\s*:\s*["'])([^"']*)''')
def clean(value):
value = JSON_SECRET.sub(r"\1[REDACTED]", str(value))
return SECRET.sub(r"\1[REDACTED]", value).replace("\n", " ").replace("\t", " ")[:500]
def main():
mode = sys.argv[1]
if mode == "logs":
data = sys.stdin.buffer.read(8193).decode("utf-8", errors="replace")
lines = data.splitlines()
selected = lines if len(lines) <= 8 else lines[:4] + lines[-4:]
for line in selected:
print("previous log:", clean(line)[:200])
if not data:
print("Previous container logs were empty.")
return
data = json.load(sys.stdin)
if mode in ("pvc-summary", "pvc-volume", "pv-summary"):
meta, spec = data.get("metadata") or {}, data.get("spec") or {}
if mode == "pvc-volume":
volume = spec.get("volumeName", "")
if re.fullmatch(r"[a-z0-9]([-a-z0-9.]*[a-z0-9])?", volume):
print(volume)
elif mode == "pvc-summary":
print("pvc", clean(meta.get("name", "unknown")), "phase=" + clean((data.get("status") or {}).get("phase", "unknown")),
"pv=" + clean(spec.get("volumeName", "unknown")), "storage_class=" + clean(spec.get("storageClassName", "unknown")))
else:
path = (spec.get("local") or {}).get("path") or (spec.get("hostPath") or {}).get("path") or "not local or hostPath"
claim = spec.get("claimRef") or {}
print("pv", clean(meta.get("name", "unknown")), "path=" + clean(path),
"claim=" + clean(claim.get("namespace", "unknown")) + "/" + clean(claim.get("name", "unknown")),
"phase=" + clean((data.get("status") or {}).get("phase", "unknown")))
return
items = data.get("items")
if not isinstance(items, list):
raise ValueError("missing items")
if mode == "names":
for pod in items[:5]:
name = (pod.get("metadata") or {}).get("name", "")
if re.fullmatch(r"[a-z0-9]([-a-z0-9.]*[a-z0-9])?", name):
print(name)
elif mode == "pvc-names":
selected = sys.argv[2]
for pod in items[:5]:
if (pod.get("metadata") or {}).get("name") != selected:
continue
names = []
for volume in (pod.get("spec") or {}).get("volumes") or []:
claim = (volume.get("persistentVolumeClaim") or {}).get("claimName", "")
if re.fullmatch(r"[a-z0-9]([-a-z0-9.]*[a-z0-9])?", claim) and claim not in names:
names.append(claim)
for name in names[:3]:
print(name)
elif mode == "identity":
selected = sys.argv[2]
for pod in items[:5]:
meta = pod.get("metadata") or {}
uid = meta.get("uid", "")
node = (pod.get("spec") or {}).get("nodeName", "")
if meta.get("name") == selected and re.fullmatch(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", uid) and re.fullmatch(r"[a-z0-9]([-a-z0-9.]*[a-z0-9])?", node):
print(uid, node)
elif mode == "crashing-containers":
selected = sys.argv[2]
for pod in items[:5]:
if (pod.get("metadata") or {}).get("name") != selected:
continue
statuses = (pod.get("status") or {})
containers = (statuses.get("initContainerStatuses") or []) + (statuses.get("containerStatuses") or [])
names = []
for container in containers:
name = container.get("name", "")
waiting = (container.get("state") or {}).get("waiting") or {}
if waiting.get("reason") == "CrashLoopBackOff" and container.get("restartCount", 0) > 0 and re.fullmatch(r"[a-z0-9]([-a-z0-9]*[a-z0-9])?", name):
names.append(name)
for name in names[:3]:
print(name)
elif mode == "pods":
if not items:
print("No pods matched the deployment selector.")
for pod in items[:5]:
status = pod.get("status") or {}
print("pod", clean((pod.get("metadata") or {}).get("name", "unknown")), "phase=" + clean(status.get("phase", "unknown")))
for owner in ((pod.get("metadata") or {}).get("ownerReferences") or []):
if owner.get("controller") is True:
print("controller", clean(owner.get("kind", "unknown")), clean(owner.get("name", "unknown")))
for container in (status.get("initContainerStatuses") or []) + (status.get("containerStatuses") or []):
state = container.get("state") or {}
current = state.get("waiting") or state.get("terminated") or {}
if current:
print("container", clean(container.get("name", "unknown")), "reason=" + clean(current.get("reason", "unknown")),
"message=" + clean(current.get("message", "")))
elif mode == "events":
for event in items[-8:]:
print("event", clean(event.get("type", "unknown")), clean(event.get("reason", "unknown")), clean(event.get("message", "")))
else:
raise ValueError("unknown mode")
if __name__ == "__main__":
try:
main()
except (ValueError, TypeError, KeyError, IndexError, AttributeError) as exc:
print(f"Pod evidence unavailable: {type(exc).__name__}", file=sys.stderr)
sys.exit(1)