diff --git a/cmd/jeannie-server/main.go b/cmd/jeannie-server/main.go index 1224d03..34084a3 100644 --- a/cmd/jeannie-server/main.go +++ b/cmd/jeannie-server/main.go @@ -31,7 +31,7 @@ var allowedCommands = map[string]bool{ "cluster-profile": true, "cluster-runtime": true, "cluster-transition": true, "rebuild-cluster": true, "stop-cluster": true, "start-cluster": true, "cleanup-debian-k8s": true, "shutdown": true, "start": true, - "status": true, "capacity": true, "capacity-advisor": true, + "status": true, "doctor": true, "capacity": true, "capacity-advisor": true, "capacity-limits": true, "recover-plan": true, "gitops-status": true, "gitops": true, "storage": true, diff --git a/docs/doctor-overview.md b/docs/doctor-overview.md new file mode 100644 index 0000000..c1bec97 --- /dev/null +++ b/docs/doctor-overview.md @@ -0,0 +1,39 @@ +# Focused Jeannie doctor + +Use the same inventory areas as `status`, selecting one at a time: + +```sh +./jeannie doctor oci +./jeannie doctor rpi +./jeannie doctor opi5 +./jeannie doctor debian +./jeannie doctor cluster +``` + +The doctor reuses the selected area's status checks and adds focused +diagnostics for the OCI edge, RPi, Debian, and cluster. It does not offer an +all-area mode. The Orange Pi view reports its host and selected K3s checks. +Existing `doctor-edge`, `doctor-gitea`, `doctor-rpi`, `doctor-cluster`, and +`doctor-k8s` remain available for their specialized investigations. + +To investigate one item, copy its full check name from status, or provide an +Argo CD application name or Compose project/service: + +```sh +./jeannie doctor cluster gitea-runner --details +./jeannie doctor debian --item homelab-gitea/gitea --details +./jeannie remote doctor rpi --item homelab-rpi-services/pihole --ai +``` + +Matching is exact and case-insensitive. A short Compose service name is +accepted only when unambiguous. Jeannie collects the area's snapshots before +selecting the item; it reports an error if the name cannot be resolved. For a +selected Compose container it reads state, restart count, exit code and health; +for an Argo CD application it reads health, operation and unhealthy resource +status. It does not fetch container environment variables or Kubernetes +Secret contents. Remote Compose checks require noninteractive SSH and sudo. + +Use `--ai` to request the existing evidence-validated AI explanation, or +`--no-local-rca` to disable it. AI is off by default and does not perform +repairs. `--json` returns structured evidence without AI output. These are +read-only checks; any suggested remediation should be reviewed separately. diff --git a/jeannie b/jeannie index 89ac013..3c31b08 100755 --- a/jeannie +++ b/jeannie @@ -27,6 +27,7 @@ JEANNIE_STEP_TOTAL=0 # shellcheck disable=SC1091 source "${REPO_ROOT}/scripts/report-ui" source "${REPO_ROOT}/scripts/status-focus" +source "${REPO_ROOT}/scripts/doctor-focus" source "${REPO_ROOT}/lib/jeannie/core.sh" source "${REPO_ROOT}/lib/jeannie/env.sh" source "${REPO_ROOT}/lib/jeannie/cluster-context.sh" @@ -188,6 +189,8 @@ Recovery And State pimox {status [VMID]|console VMID} Inspect Pimox VMs or open a serial emergency console. Focused Doctors + doctor {oci|rpi|opi5|debian|cluster} [ITEM] [--ai|--json|--details] + Diagnose one area or named item. doctor-edge [--all|--details|--verbose|--json] Diagnose edge routing and public exposure. doctor-homelab [--all|--details|--verbose|--json] @@ -721,6 +724,9 @@ case "${1:-}" in move-prometheus-stack-workers) move_prometheus_stack_workers ;; + doctor) + doctor_focus "${@:2}" + ;; doctor-versions) doctor_versions "${@:2}" ;; diff --git a/scripts/doctor-application.py b/scripts/doctor-application.py new file mode 100644 index 0000000..4e25c9b --- /dev/null +++ b/scripts/doctor-application.py @@ -0,0 +1,26 @@ +#!/usr/bin/env python3 +"""Extract non-secret Argo CD application health evidence.""" + +import json +import sys + +try: + app = json.load(sys.stdin) + status = app.get("status") or {} + health = status.get("health") or {} + operation = status.get("operationState") or {} + print("health:", health.get("status", "Unknown")) + if health.get("message"): + print("health message:", health["message"]) + if operation.get("phase"): + print("last operation:", operation["phase"]) + if operation.get("message"): + print("operation message:", operation["message"]) + for resource in status.get("resources") or []: + resource_health = (resource.get("health") or {}).get("status", "") + if resource_health and resource_health != "Healthy": + print("resource:", resource.get("kind", "?"), resource.get("namespace", ""), + resource.get("name", "?"), resource_health) +except (ValueError, TypeError, AttributeError) as exc: + print("Cannot parse application evidence:", exc, file=sys.stderr) + sys.exit(1) diff --git a/scripts/doctor-filter.py b/scripts/doctor-filter.py new file mode 100644 index 0000000..9a38bbb --- /dev/null +++ b/scripts/doctor-filter.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +"""Select one exact status check or Compose service from report rows.""" + +import sys + + +def main(): + if len(sys.argv) != 2 or not sys.argv[1].strip(): + print("A nonempty item name is required", file=sys.stderr) + return 2 + target = sys.argv[1].casefold() + rows = [] + for line in sys.stdin: + parts = line.rstrip("\n").split("\t") + if len(parts) < 3: + continue + name = parts[2] + service = name.split(" (", 1)[0] + candidates = {name.casefold(), service.casefold()} + if "/" in service: + candidates.add(service.rsplit("/", 1)[1].casefold()) + if target in candidates: + rows.append(line) + if len(rows) != 1: + print("Item not found or ambiguous; use the exact name shown by status", file=sys.stderr) + return 2 + sys.stdout.write(rows[0]) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/doctor-focus b/scripts/doctor-focus new file mode 100644 index 0000000..5dcee94 --- /dev/null +++ b/scripts/doctor-focus @@ -0,0 +1,134 @@ +#!/usr/bin/env bash +# Sourced by Jeannie; all probes are read-only. + +doctor_focus_usage() { + cat <<'EOF' +Usage: ./jeannie doctor {oci|rpi|opi5|debian|cluster} [ITEM] [--ai] [--json] [--details] [--all] + +Diagnose one inventory area. Optionally select an exact check, Argo CD +application, Compose project/service, or unambiguous Compose service name +shown by status. There is no all-area doctor. + + --ai Request an evidence-validated AI explanation (text only). + --no-local-rca Disable the AI explanation. + --json Return the structured diagnostic report. + --details Show supporting evidence. + --all Include healthy checks (default). + --item NAME Alternative to positional ITEM. + +Examples: + ./jeannie doctor rpi + ./jeannie doctor cluster gitea-runner --ai + ./jeannie remote doctor debian --item homelab-gitea/gitea +EOF +} + +doctor_focus_https() { + curl -fsS -o /dev/null --connect-timeout 3 --max-time 8 "${LAB_PUBLIC_URL%/}/edge-health" +} + +doctor_focus_application_evidence() { + local name="$1" snapshot + [[ "${name}" =~ ^[a-z0-9]([-a-z0-9.]*[a-z0-9])?$ ]] || { echo "Invalid application name" >&2; return 1; } + snapshot="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s -n argocd get application "${name}" -o json)" || return 1 + printf '%s' "${snapshot}" | python3 "${REPO_ROOT}/scripts/doctor-application.py" +} + +doctor_focus_compose_evidence() { + local scope="$1" check="$2" name host user key + name="${check##* (}" + name="${name%)}" + [[ "${name}" =~ ^[a-zA-Z0-9][a-zA-Z0-9_.-]*$ ]] || { echo "Invalid container name" >&2; return 1; } + local format='{{.State.Status}} restarts={{.RestartCount}} exit={{.State.ExitCode}} health={{if .State.Health}}{{.State.Health.Status}}{{else}}not-configured{{end}}' + if [[ "${scope}" == debian ]]; then + timeout 10 sudo -n docker inspect --format "${format}" "${name}" + return + fi + case "${scope}" in + rpi) host="${LAB_RPI_HOST:-}"; user="${LAB_RPI_USER:-}"; key="${LAB_RPI_SSH_KEY_PATH:-${HOME}/.ssh/id_ed25519}" ;; + opi5) host="${LAB_PIMOX_HOST:-}"; user="${LAB_PIMOX_USER:-}"; key="${LAB_PIMOX_SSH_KEY_PATH:-${HOME}/.ssh/id_ed25519}" ;; + oci) host="${LAB_EDGE_TAILSCALE_IP:-}"; user="${LAB_EDGE_USER:-}"; key="${LAB_EDGE_SSH_KEY_PATH:-${LAB_OCI_SSH_PRIVATE_KEY:-${HOME}/.ssh/id_ed25519}}" ;; + *) return 2 ;; + esac + [[ -n "${host}" && -n "${user}" ]] || { echo "Host or user is missing from inventory" >&2; return 1; } + timeout 10 ssh -n -i "${key}" -o BatchMode=yes -o ConnectTimeout=3 \ + -o ConnectionAttempts=1 -o StrictHostKeyChecking=yes "${user}@${host}" \ + "sudo -n docker inspect --format '${format}' '${name}'" +} + +doctor_focus_extra() { + case "$1" in + oci) + if [[ -n "${LAB_PUBLIC_URL:-}" ]]; then + report_ui_check warn "OCI edge diagnostics" "Public HTTPS certificate and health" "curl -v --max-time 8 '${LAB_PUBLIC_URL%/}/edge-health'" "" "" doctor_focus_https + fi + ;; + rpi) + report_ui_check warn "RPi4 diagnostics" "Docker root state" "./jeannie doctor-rpi --details" "" "" check_rpi_docker_root_state + report_ui_check warn "RPi4 diagnostics" "Tailscale IP" "./jeannie doctor-rpi --details" "" "" check_rpi_tailscale_ip + ;; + debian) + report_ui_check warn "Debian diagnostics" "Gitea runner service" "systemctl status homelab-gitea-runner.service --no-pager" "" "" check_systemd_active homelab-gitea-runner + report_ui_check warn "Debian diagnostics" "Gitea SSH" "./jeannie doctor-gitea --details" "" "" check_gitea_ssh + ;; + cluster) + report_ui_check warn "Kubernetes diagnostics" "Problem pods" "kubectl get pods -A -o wide" "" "" status_no_problem_pods + report_ui_check warn "Kubernetes diagnostics" "Recent deployments" "kubectl get deployments -A" "" "" status_recent_deployments + ;; + opi5) ;; + esac +} + +doctor_focus() { + local scope="${1:-}" item="" rc=0 selected area check + local -a flags=() + case "${scope}" in + -h|--help) doctor_focus_usage; return 0 ;; + oci|rpi|opi5|debian|cluster) shift ;; + *) doctor_focus_usage >&2; return 2 ;; + esac + while (($#)); do + case "$1" in + -h|--help) doctor_focus_usage; return 0 ;; + --item) + if (($# < 2)) || [[ -z "$2" || "$2" == --* || -n "${item}" ]]; then echo "Provide exactly one item name." >&2; return 2; fi + item="$2"; shift 2 ;; + --ai|--no-local-rca|--json|--details|--all) flags+=("$1"); shift ;; + -*) echo "Unknown doctor option: $1" >&2; return 2 ;; + *) if [[ -n "${item}" ]]; then echo "Provide exactly one item name." >&2; return 2; fi; item="$1"; shift ;; + esac + done + require_debian_server "doctor" + # These variables are consumed by the dynamically scoped report helpers. + # shellcheck disable=SC2034 + local REPORT_UI_ONLY=all REPORT_UI_LOCAL_RCA=false REPORT_UI_PARALLEL=true REPORT_UI_STATUS_SUMMARY=false + report_ui_parse_args "${flags[@]}" || return 2 + report_ui_begin + status_focus_collect "${scope}" + if [[ -z "${item}" ]]; then doctor_focus_extra "${scope}"; fi + report_ui_finish + if [[ -n "${item}" ]]; then + if ! selected="$(python3 "${REPO_ROOT}/scripts/doctor-filter.py" "${item}" <"${REPORT_UI_ROWS_FILE}")"; then + report_ui_cleanup + return 2 + fi + printf '%s\n' "${selected}" >"${REPORT_UI_ROWS_FILE}" + REPORT_UI_FAILURES=0 + IFS=$'\t' read -r _ area check _ <<<"${selected}" + [[ "${selected}" != fail$'\t'* ]] || REPORT_UI_FAILURES=1 + if [[ "${area}" == "Kubernetes apps" ]]; then + # Application evidence is a separate read-only request for the selected item. + # shellcheck disable=SC2034 + REPORT_UI_PARALLEL=false + report_ui_check warn "Kubernetes evidence" "${check} application evidence retrieved" "kubectl -n argocd get application ${check} -o yaml" "" "" doctor_focus_application_evidence "${check}" + elif [[ "${area}" == *" Compose" ]]; then + # shellcheck disable=SC2034 + REPORT_UI_PARALLEL=false + report_ui_check warn "Compose evidence" "${check} container state retrieved" "docker ps -a --filter label=com.docker.compose.project" "" "" doctor_focus_compose_evidence "${scope}" "${check}" + fi + fi + ((REPORT_UI_FAILURES == 0)) || rc=1 + report_ui_render "Jeannie Doctor: ${scope}${item:+ / ${item}}" + report_ui_cleanup + return "${rc}" +} diff --git a/scripts/validate-homelab b/scripts/validate-homelab index a67f5a6..75fecc7 100755 --- a/scripts/validate-homelab +++ b/scripts/validate-homelab @@ -125,6 +125,7 @@ validate_unit_tests() { python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_status_focus.py' python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_status_app_snapshot.py' python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_go_launchers.py' + python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_doctor_focus.py' } main() { diff --git a/tests/jeannie/test_doctor_focus.py b/tests/jeannie/test_doctor_focus.py new file mode 100644 index 0000000..263d38a --- /dev/null +++ b/tests/jeannie/test_doctor_focus.py @@ -0,0 +1,77 @@ +import json +import subprocess +import sys +import os +import unittest +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[2] +FILTER = ROOT / "scripts" / "doctor-filter.py" +APP = ROOT / "scripts" / "doctor-application.py" +DOCTOR = ROOT / "scripts" / "doctor-focus" + + +def run_filter(item, rows): + return subprocess.run([sys.executable, str(FILTER), item], input=rows, + text=True, capture_output=True) + + +class DoctorFocusTests(unittest.TestCase): + def test_select_exact_application_or_compose_service(self): + rows = ("warn\tKubernetes apps\tgitea-runner\tProgressing\t\t\t\t\n" + "ok\tDebian Compose\thomelab-gitea/gitea (homelab-gitea)\tUp\t\t\t\t\n") + self.assertIn("gitea-runner", run_filter("gitea-runner", rows).stdout) + self.assertIn("homelab-gitea/gitea", run_filter("homelab-gitea/gitea", rows).stdout) + self.assertNotEqual(run_filter("missing", rows).returncode, 0) + + def test_ambiguous_short_name_is_rejected(self): + rows = ("ok\tA\tone/web (one-web)\tUp\t\t\t\t\n" + "ok\tB\ttwo/web (two-web)\tUp\t\t\t\t\n") + self.assertNotEqual(run_filter("web", rows).returncode, 0) + self.assertEqual(run_filter("one/web", rows).returncode, 0) + + def test_all_area_is_rejected_and_help_succeeds(self): + for args, expected in ((["all"], 2), (["--help"], 0), (["oci", "--help"], 0)): + result = subprocess.run(["bash", "-c", 'source "$1"; shift; doctor_focus "$@"', + "test", str(DOCTOR), *args], capture_output=True, text=True) + self.assertEqual(result.returncode, expected) + self.assertIn("oci|rpi|opi5|debian|cluster", result.stdout + result.stderr) + + def test_application_evidence_excludes_spec_and_secrets(self): + app = {"spec": {"secret": "do-not-print"}, "status": { + "health": {"status": "Progressing", "message": "waiting"}, + "operationState": {"phase": "Running"}, + "resources": [{"kind": "Deployment", "name": "runner", "health": {"status": "Progressing"}}]}} + result = subprocess.run([sys.executable, str(APP)], input=json.dumps(app), + capture_output=True, text=True, check=True) + self.assertIn("health: Progressing", result.stdout) + self.assertIn("Deployment", result.stdout) + self.assertNotIn("do-not-print", result.stdout) + + def test_selected_item_does_not_inherit_unrelated_failure(self): + code = r''' +source "$1" +require_debian_server() { :; } +report_ui_parse_args() { :; } +report_ui_begin() { REPORT_UI_ROWS_FILE="$(mktemp)"; } +status_focus_collect() { + printf 'fail\tKubernetes apps\tother\tdown\t\t\t\t\nwarn\tKubernetes apps\trunner\tProgressing\t\t\t\t\n' >"$REPORT_UI_ROWS_FILE" +} +report_ui_finish() { REPORT_UI_FAILURES=1; } +report_ui_check() { printf 'evidence-requested:%s\n' "$3"; } +report_ui_render() { cat "$REPORT_UI_ROWS_FILE"; } +report_ui_cleanup() { rm -f "$REPORT_UI_ROWS_FILE"; } +doctor_focus cluster runner +''' + env = os.environ.copy() + env["REPO_ROOT"] = str(ROOT) + result = subprocess.run(["bash", "-c", code, "test", str(DOCTOR)], + env=env, capture_output=True, text=True, check=True) + self.assertIn("runner application evidence retrieved", result.stdout) + self.assertIn("Progressing", result.stdout) + self.assertNotIn("other", result.stdout) + + +if __name__ == "__main__": + unittest.main()