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

171 lines
10 KiB
Python

#!/usr/bin/env python3
"""Extract bounded pod status and events without dumping pod specs or secrets."""
import json
import re
import sys
import shlex
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 recovery_candidate(items, name, namespace, pvc, pv, mounts, node_host=None):
"""Suggest, never execute, a normal recreation for an identified stale bind."""
pod = next((p for p in items if p.get('metadata', {}).get('name') == name), {})
meta = pod.get('metadata', {})
uid = meta.get('uid', '')
owners = [o for o in meta.get('ownerReferences', []) if o.get('controller') is True]
claims = [v['persistentVolumeClaim']['claimName'] for v in pod.get('spec', {}).get('volumes', []) if 'persistentVolumeClaim' in v]
pm, ps = pvc.get('metadata', {}), pvc.get('spec', {})
vm, vs = pv.get('metadata', {}), pv.get('spec', {})
ref = vs.get('claimRef', {})
path = vs.get('local', {}).get('path', '')
containers = pod.get('status', {}).get('containerStatuses', [])
failing = any(c.get('ready') is not True and c.get('restartCount', 0) > 0 and
(c.get('state', {}).get('waiting', {}).get('reason') == 'CrashLoopBackOff' or
c.get('state', {}).get('terminated', {}).get('exitCode', 0) != 0 or
c.get('lastState', {}).get('terminated', {}).get('exitCode', 0) != 0) for c in containers)
if not (re.fullmatch(r'[a-z0-9]([-a-z0-9.]*[a-z0-9])?', name) and
re.fullmatch(r'[a-z0-9]([-a-z0-9.]*[a-z0-9])?', namespace) and
re.fullmatch(r'[0-9a-f-]{36}', uid) and meta.get('namespace') == namespace and
failing and len(owners) == 1 and owners[0].get('kind') == 'ReplicaSet' and
not any(v.get('persistentVolumeClaim', {}).get('readOnly') for v in pod.get('spec', {}).get('volumes', [])) and
claims == [pm.get('name')] and pm.get('namespace') == namespace and
pvc.get('status', {}).get('phase') == 'Bound' and pv.get('status', {}).get('phase') == 'Bound' and
ps.get('volumeName') == vm.get('name') and ref.get('uid') == pm.get('uid') and
ref.get('name') == pm.get('name') and ref.get('namespace') == namespace and
path.startswith('/data/') and '..' not in path.split('/')):
return None
target = f"/var/lib/kubelet/pods/{uid}/volumes/kubernetes.io~local-volume/{vm['name']}"
rows = [line.split() for line in mounts.splitlines()]
data = [r for r in rows if len(r) == 4 and r[0] == '/data']
bound = [r for r in rows if len(r) == 4 and r[0] == target]
if not (len(data) == len(bound) == 1 and 'rw' in data[0][3].split(',') and
'ro' in bound[0][3].split(',') and data[0][2] != bound[0][2] and
bound[0][1].endswith('[' + path.removeprefix('/data') + ']')):
return None
checks = [shlex.join(['kubectl', '--request-timeout=10s', '-n', namespace, 'get', 'pod', name,
'-o', 'custom-columns=UID:.metadata.uid,OWNER:.metadata.ownerReferences[0].name,OWNER_UID:.metadata.ownerReferences[0].uid,CONTROLLER:.metadata.ownerReferences[0].controller', '--no-headers']),
shlex.join(['kubectl', '--request-timeout=10s', '-n', namespace, 'get', 'replicaset', owners[0]['name'],
'-o', 'custom-columns=UID:.metadata.uid,DESIRED:.spec.replicas', '--no-headers'])]
if node_host:
remote = ' && '.join('sudo -n test ' + flag + ' ' + shlex.quote(path) for flag in ('-d', '-r', '-w'))
checks.append(shlex.join(['ssh', '-o', 'BatchMode=yes', node_host,
remote + " && echo Backing-directory-accessible"]))
return {'observation': 'The pod local-volume bind is read-only on a different device from current read-write /data.',
'pod_uid': uid, 'owner': owners[0].get('name'), 'pv': vm['name'], 'backing_path': path,
'verification_command': ' && '.join(checks),
'before_repair': 'Recheck this pod UID and controller, and confirm backing_path is accessible. Preserve existing data and keys.',
'candidate_command': shlex.join(['kubectl', '--request-timeout=10s', '-n', namespace, 'delete', 'pod', name, '--wait=false']),
'validation': 'Wait for a replacement UID, verify its mount is read-write on the current device and container readiness. Accepted deletion is not recovery.'}
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 == 'recovery-candidate':
candidate = recovery_candidate(items, sys.argv[2], sys.argv[3], json.loads(sys.argv[4] or '{}'), json.loads(sys.argv[5] or '{}'), sys.argv[6], sys.argv[7] if len(sys.argv) > 7 else None)
if candidate:
print('Conditional recovery candidate (not executed):', json.dumps(candidate))
elif 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)