diff --git a/docs/doctor-overview.md b/docs/doctor-overview.md index 5558cbd..5bacdf7 100644 --- a/docs/doctor-overview.md +++ b/docs/doctor-overview.md @@ -47,15 +47,20 @@ read-only checks; any suggested remediation should be reviewed separately. For a selected Kubernetes application, Doctor also reads up to five pods selected by each deployment's simple match-label selector and the latest pod events. +For a container in CrashLoopBackOff with a previous restart, it also requests +bounded previous-container logs, and reports when those logs are unavailable. It extracts status, wait reasons, and bounded event messages without dumping pod specs. Unsupported selectors or failed reads are reported as unknown. When AI is enabled, focused Doctor invokes Holmes with the selected profile and this evidence, forbids Bash execution with `--bash-always-deny`, instructs Holmes not to call tools, and validates the citations and read-only command -against the collected report. Failed or rejected Holmes answers leave the +against the collected report. A single fenced JSON response is accepted; invalid +JSON is retried once, with both responses preserved. A syntactically valid answer +that fails evidence validation is rejected without retry. Failed or rejected Holmes answers leave the deterministic evidence available. Private evidence and logs are stored under the Doctor K8s artifact directory. Other Holmes toolsets and credentials must still -be restricted independently; event messages may contain sensitive details and +be restricted independently; logs and event messages may contain sensitive details. +Redaction is best effort, not a guarantee, and the configured OmniRoute model can be external. The dedicated Gitea runner text report remains deterministic and does not invoke Holmes. diff --git a/scripts/doctor-focus b/scripts/doctor-focus index db0b710..b436528 100644 --- a/scripts/doctor-focus +++ b/scripts/doctor-focus @@ -32,8 +32,19 @@ doctor_focus_https() { curl -fsS -o /dev/null --connect-timeout 3 --max-time 8 "${LAB_PUBLIC_URL%/}/edge-health" } +doctor_focus_holmes_call() { + local bin="$1" config="$2" prompt="$3" output="$4" error="$5" key="$6" model="$7" fast="$8" + timeout "${LAB_HOLMES_TRIAGE_TIMEOUT_SECONDS:-360}" env KUBECONFIG="${KUBECONFIG_PATH}" \ + OPENAI_BASE_URL="${OPENAI_BASE_URL:-http://127.0.0.1:20128/v1}" \ + OPENAI_API_BASE="${OPENAI_BASE_URL:-http://127.0.0.1:20128/v1}" OPENAI_API_KEY="${key}" \ + "${bin}" ask --config "${config}" --prompt-file "${prompt}" \ + --api-key "${key}" --model "${model}" --fast-model "${fast}" \ + --max-steps "${LAB_HOLMES_MAX_STEPS:-12}" --fast-mode --no-interactive --bash-always-deny \ + >"${output}" 2>"${error}" +} + doctor_focus_holmes() { - local title="$1" base artifact config bin model fast key status=0 + local title="$1" base artifact config bin model fast key output error status=0 local tools_env="${LAB_AI_STACK_TOOLS_ENV_FILE:-/data/homelab-ai-stack/ai-tools.env}" local AI_STACK_AGENT_SMART_MODEL="${AI_STACK_AGENT_SMART_MODEL:-}" AI_STACK_AGENT_FAST_MODEL="${AI_STACK_AGENT_FAST_MODEL:-}" local OPENAI_BASE_URL="${OPENAI_BASE_URL:-}" OPENAI_API_KEY="${OPENAI_API_KEY:-}" @@ -64,17 +75,25 @@ doctor_focus_holmes() { config="${artifact}/empty-config.yaml" fi echo "== Holmes analysis (hypotheses unverified) ==" - if timeout "${LAB_HOLMES_TRIAGE_TIMEOUT_SECONDS:-360}" env KUBECONFIG="${KUBECONFIG_PATH}" \ - OPENAI_BASE_URL="${OPENAI_BASE_URL:-http://127.0.0.1:20128/v1}" \ - OPENAI_API_BASE="${OPENAI_BASE_URL:-http://127.0.0.1:20128/v1}" OPENAI_API_KEY="${key}" \ - "${bin}" ask --config "${config}" --prompt-file "${artifact}/holmes-prompt.txt" \ - --api-key "${key}" --model "${model}" --fast-model "${fast}" \ - --max-steps "${LAB_HOLMES_MAX_STEPS:-12}" --fast-mode --no-interactive --bash-always-deny \ - >"${artifact}/holmes-raw-output.txt" 2>"${artifact}/holmes-error.txt"; then - if grep -Eiq 'validation error|invalid config|extra inputs are not permitted|traceback|exception|error:' "${artifact}/holmes-error.txt"; then - status=1 - elif ! python3 "${REPO_ROOT}/scripts/holmes-evidence.py" validate "${artifact}/holmes-evidence.json" "${artifact}/holmes-raw-output.txt"; then + output="${artifact}/holmes-raw-output.txt" + error="${artifact}/holmes-error.txt" + if doctor_focus_holmes_call "${bin}" "${config}" "${artifact}/holmes-prompt.txt" "${output}" "${error}" "${key}" "${model}" "${fast}"; then + if grep -Eiq 'validation error|invalid config|extra inputs are not permitted|traceback|exception|error:' "${error}"; then status=1 + else + if ! python3 "${REPO_ROOT}/scripts/holmes-evidence.py" check-json "${output}" >/dev/null; then + echo "Holmes returned invalid JSON; retrying once." + cp "${artifact}/holmes-prompt.txt" "${artifact}/holmes-retry-prompt.txt" + printf '\nThe previous response was invalid JSON. Return exactly one valid JSON object matching the schema.\n' >>"${artifact}/holmes-retry-prompt.txt" + output="${artifact}/holmes-retry-raw-output.txt" + error="${artifact}/holmes-retry-error.txt" + if ! doctor_focus_holmes_call "${bin}" "${config}" "${artifact}/holmes-retry-prompt.txt" "${output}" "${error}" "${key}" "${model}" "${fast}" || grep -Eiq 'validation error|invalid config|extra inputs are not permitted|traceback|exception|error:' "${error}"; then + status=1 + fi + fi + if ((status == 0)) && ! python3 "${REPO_ROOT}/scripts/holmes-evidence.py" validate "${artifact}/holmes-evidence.json" "${output}"; then + status=1 + fi fi else status=1 @@ -121,7 +140,7 @@ doctor_focus_application_lookup() { } doctor_focus_application_evidence() { - local name="$1" snapshot deployments namespace deployment state selector pods pod count=0 failed=0 + local name="$1" snapshot deployments namespace deployment state selector pods pod container count=0 failed=0 snapshot="$(report_ui_cached_probe doctor_focus_application_fetch "${name}")" || return 1 printf '$ kubectl --kubeconfig %q --request-timeout=10s -n argocd get application %q --ignore-not-found -o json | python3 %q\n' "${KUBECONFIG_PATH}" "${name}" "${REPO_ROOT}/scripts/doctor-application.py" printf '%s' "${snapshot}" | python3 "${REPO_ROOT}/scripts/doctor-application.py" || return 1 @@ -139,6 +158,14 @@ doctor_focus_application_evidence() { printf '%s' "${pods}" | python3 "${REPO_ROOT}/scripts/doctor-pod-evidence.py" pods || failed=1 while read -r pod; do [[ -n "${pod}" ]] || continue + while read -r container; do + [[ -n "${container}" ]] || continue + printf '$ kubectl --kubeconfig %q --request-timeout=10s -n %q logs %q -c %q --previous --tail=30 --limit-bytes=8192 | python3 %q logs\n' "${KUBECONFIG_PATH}" "${namespace}" "${pod}" "${container}" "${REPO_ROOT}/scripts/doctor-pod-evidence.py" + if ! kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s -n "${namespace}" logs "${pod}" -c "${container}" --previous --tail=30 --limit-bytes=8192 2>/dev/null | python3 "${REPO_ROOT}/scripts/doctor-pod-evidence.py" logs; then + echo "Previous container logs unavailable; cause remains unknown." + failed=1 + fi + done < <(printf '%s' "${pods}" | python3 "${REPO_ROOT}/scripts/doctor-pod-evidence.py" crashing-containers "${pod}") printf '$ kubectl --kubeconfig %q --request-timeout=10s -n %q get events --field-selector %q --sort-by=.lastTimestamp -o json | python3 %q events\n' "${KUBECONFIG_PATH}" "${namespace}" "involvedObject.kind=Pod,involvedObject.name=${pod}" "${REPO_ROOT}/scripts/doctor-pod-evidence.py" if ! kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s -n "${namespace}" get events --field-selector "involvedObject.kind=Pod,involvedObject.name=${pod}" --sort-by=.lastTimestamp -o json 2>/dev/null | python3 "${REPO_ROOT}/scripts/doctor-pod-evidence.py" events; then echo "Pod events unavailable." diff --git a/scripts/doctor-pod-evidence.py b/scripts/doctor-pod-evidence.py index 0bf9ef5..4d59bbb 100644 --- a/scripts/doctor-pod-evidence.py +++ b/scripts/doctor-pod-evidence.py @@ -5,23 +5,47 @@ 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): - return SECRET.sub(r"\1[REDACTED]", str(value)).replace("\n", " ").replace("\t", " ")[:500] + 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") + for line in data.splitlines()[-8:]: + print("previous log:", clean(line)[:200]) + if not data: + print("Previous container logs were empty.") + return data = json.load(sys.stdin) items = data.get("items") if not isinstance(items, list): raise ValueError("missing items") - mode = sys.argv[1] 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 == "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.") diff --git a/scripts/holmes-evidence.py b/scripts/holmes-evidence.py index 1b21aaa..6a71613 100644 --- a/scripts/holmes-evidence.py +++ b/scripts/holmes-evidence.py @@ -6,6 +6,7 @@ from collections import deque import importlib.util import json import os +import re from pathlib import Path SPEC = importlib.util.spec_from_file_location("report_ai_explain", Path(__file__).with_name("report-ai-explain.py")) @@ -59,12 +60,18 @@ def prepare(directory, api, nodes, pods, events): (directory / "holmes-prompt.txt").write_text(prompt + "\n", encoding="utf-8") -def validate(report_path, raw_path): - report = json.loads(Path(report_path).read_text(encoding="utf-8")) +def parse_response(raw_path): path = Path(raw_path) if path.stat().st_size > 1_048_576: raise ValueError("Holmes response exceeds size limit") - answer = json.loads(path.read_text(encoding="utf-8")) + text = path.read_text(encoding="utf-8").strip() + fenced = re.fullmatch(r"```(?:json)?[ \t]*\r?\n(.*?)\r?\n```", text, re.IGNORECASE | re.DOTALL) + return json.loads(fenced.group(1) if fenced else text) + + +def validate(report_path, raw_path): + report = json.loads(Path(report_path).read_text(encoding="utf-8")) + answer = parse_response(raw_path) EXPLAIN.render(EXPLAIN.validate(answer, report), report) @@ -93,11 +100,15 @@ def main(): verify = subparsers.add_parser("validate") verify.add_argument("report") verify.add_argument("response") + check = subparsers.add_parser("check-json") + check.add_argument("response") args = parser.parse_args() if args.action == "prepare": prepare(args.directory, args.api, args.nodes, args.pods, args.events) elif args.action == "prepare-focused": prepare_focused(args.directory, args.rows, args.title) + elif args.action == "check-json": + parse_response(args.response) else: validate(args.report, args.response) diff --git a/tests/jeannie/test_doctor_focus.py b/tests/jeannie/test_doctor_focus.py index aa6a715..7c986c5 100644 --- a/tests/jeannie/test_doctor_focus.py +++ b/tests/jeannie/test_doctor_focus.py @@ -23,6 +23,29 @@ def run_filter(item, rows): class DoctorFocusTests(unittest.TestCase): + def test_holmes_retries_invalid_json_once_and_preserves_outputs(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + binary = root / "jeannie-holmes" + binary.write_text("#!/bin/sh\ncase \" $* \" in *' --bash-always-deny '*) ;; *) exit 4;; esac\n" + "if [ ! -f \"$HOME/called\" ]; then touch \"$HOME/called\"; echo invalid; else " + "printf '%s\\n' '{\"observed_facts\":[\"C01\"],\"possible_causes\":[],\"missing_evidence\":[],\"next_command\":null}'; fi\n") + binary.chmod(0o755) + rows = root / "rows" + rows.write_text("warn\tKubernetes evidence\tn8n\tPending\tCrashLoopBackOff\tkubectl get pods -A -o wide\t\t\n") + env = os.environ.copy() + env.update(PATH=f"{root}:{env.get('PATH', '')}", REPO_ROOT=str(ROOT), HOME=str(root), + REPORT_UI_ROWS_FILE=str(rows), KUBECONFIG_PATH="/tmp/test-kubeconfig", + LAB_AI_STACK_TOOLS_ENV_FILE=str(root / "missing"), LAB_HOLMES_CONFIG_FILE=str(root / "missing-config"), + LAB_DOCTOR_K8S_ARTIFACT_DIR=str(root / "artifacts")) + result = subprocess.run(["bash", "-c", 'source "$1"; doctor_focus_holmes "Doctor n8n"', "test", str(DOCTOR)], + env=env, capture_output=True, text=True, check=True) + self.assertIn("retrying once", result.stdout) + self.assertNotIn("answer was rejected", result.stdout) + artifact = next((root / "artifacts").glob("focused.*")) + self.assertEqual((artifact / "holmes-raw-output.txt").read_text().strip(), "invalid") + self.assertTrue((artifact / "holmes-retry-raw-output.txt").exists()) + def test_focused_holmes_receives_evidence_and_denies_bash(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) @@ -210,6 +233,20 @@ doctor_runner_report self.assertNotIn("secret123", result.stdout) self.assertNotIn("do-not-print", result.stdout) + def test_crash_logs_are_selected_and_redacted(self): + script = str(ROOT / "scripts/doctor-pod-evidence.py") + pod = {"metadata": {"name": "n8n-pod"}, "status": {"containerStatuses": [ + {"name": "n8n", "restartCount": 2, "state": {"waiting": {"reason": "CrashLoopBackOff"}}}, + {"name": "other", "restartCount": 0, "state": {"waiting": {"reason": "ImagePullBackOff"}}}]}} + result = subprocess.run([sys.executable, script, "crashing-containers", "n8n-pod"], + input=json.dumps({"items": [pod]}), capture_output=True, text=True, check=True) + self.assertEqual(result.stdout.strip(), "n8n") + result = subprocess.run([sys.executable, script, "logs"], input='failure password=secret123\n{"token":"secret456"}\n', + capture_output=True, text=True, check=True) + self.assertIn("failure", result.stdout) + self.assertNotIn("secret123", result.stdout) + self.assertNotIn("secret456", result.stdout) + def test_selected_item_does_not_inherit_unrelated_failure(self): code = r''' source "$1" diff --git a/tests/jeannie/test_holmes_evidence.py b/tests/jeannie/test_holmes_evidence.py index 4c4dc96..5ff0b0f 100644 --- a/tests/jeannie/test_holmes_evidence.py +++ b/tests/jeannie/test_holmes_evidence.py @@ -17,6 +17,15 @@ SPEC.loader.exec_module(MODULE) class HolmesEvidenceTests(unittest.TestCase): + def test_single_json_fence_is_accepted_but_surrounding_prose_is_not(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "answer" + path.write_text('```json\n{"observed_facts": []}\n```\n') + self.assertEqual(MODULE.parse_response(path), {"observed_facts": []}) + path.write_text('explanation\n```json\n{}\n```') + with self.assertRaises(ValueError): + MODULE.parse_response(path) + def test_focused_report_preserves_profile_and_pod_event_evidence(self): with tempfile.TemporaryDirectory() as directory, patch.dict(os.environ, { "LAB_CLUSTER_PROFILE": "k3s", "LAB_CLUSTER_RUNTIME": "k3s"}):