From 8c154b04d1e4cc70c30c9e573ecb4783a659cbb9 Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Wed, 11 Nov 2026 15:28:54 -0600 Subject: [PATCH] Extend doctor across hosts and applications --- docs/doctor-overview.md | 13 +++-- scripts/doctor-application.py | 4 +- scripts/doctor-focus | 91 ++++++++++++++++++++++-------- scripts/doctor-rpi-os.py | 6 +- tests/jeannie/test_doctor_focus.py | 57 ++++++++++++++++++- 5 files changed, 135 insertions(+), 36 deletions(-) diff --git a/docs/doctor-overview.md b/docs/doctor-overview.md index 186ec15..578363d 100644 --- a/docs/doctor-overview.md +++ b/docs/doctor-overview.md @@ -12,9 +12,9 @@ Use the same inventory areas as `status`, selecting one at a time: 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 RPi view checks OS kernel, uptime/load, available memory, -root filesystem usage and systemd state as well as its services. The Orange -Pi view reports its host and selected K3s checks. +all-area mode. Each device view checks OS kernel, uptime/load, available memory, +root filesystem usage and systemd state as well as its services. Orange Pi +also reports its selected K3s checks. Remote OS checks use inventory SSH access. Existing `doctor-edge`, `doctor-gitea`, `doctor-rpi`, `doctor-cluster`, and `doctor-k8s` remain available for their specialized investigations. @@ -24,6 +24,7 @@ Argo CD application name or Compose project/service: ```sh ./jeannie doctor cluster gitea-runner --details ./jeannie doctor gitea-runner +./jeannie doctor homelab-gitea/gitea ./jeannie doctor debian --item homelab-gitea/gitea --details ./jeannie remote doctor rpi --item homelab-rpi-services/pihole --ai ``` @@ -33,9 +34,9 @@ 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 and deployment replica counts. An application name without a scope is -looked up directly in Argo CD on the selected cluster; Compose services still -need their host scope. It does not fetch container environment variables or Kubernetes +status and deployment replica counts. An item without a scope is looked up in +Argo CD and the inventoried Compose hosts. If any source is unavailable, or a +name is ambiguous, specify its scope explicitly. 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 diff --git a/scripts/doctor-application.py b/scripts/doctor-application.py index 5c2e80a..2248cda 100644 --- a/scripts/doctor-application.py +++ b/scripts/doctor-application.py @@ -14,7 +14,9 @@ try: for condition in current.get("conditions") or []: if condition.get("status") != "True" and condition.get("message"): print("deployment condition:", condition.get("type", "Unknown"), condition["message"]) - sys.exit(0) + desired = spec.get("replicas", 1) + ready = current.get("readyReplicas", 0) + sys.exit(1 if ready < desired else 0) status = app.get("status") or {} health = status.get("health") or {} operation = status.get("operationState") or {} diff --git a/scripts/doctor-focus b/scripts/doctor-focus index 25e0efa..6bd9a99 100644 --- a/scripts/doctor-focus +++ b/scripts/doctor-focus @@ -4,7 +4,7 @@ doctor_focus_usage() { cat <<'EOF' Usage: ./jeannie doctor {oci|rpi|opi5|debian|cluster} [ITEM] [options] - ./jeannie doctor ARGOCD_APPLICATION [options] + ./jeannie doctor ITEM [options] Diagnose one inventory area. Optionally select an exact check, Argo CD application, Compose project/service, or unambiguous Compose service name @@ -33,11 +33,24 @@ doctor_focus_https() { doctor_focus_application_fetch() { local name="$1" [[ "${name}" =~ ^[a-z0-9]([-a-z0-9.]*[a-z0-9])?$ ]] || { echo "Invalid application name" >&2; return 1; } - kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s -n argocd get application "${name}" -o json 2>/dev/null + kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s -n argocd get application "${name}" --ignore-not-found -o json 2>/dev/null +} + +doctor_focus_application_lookup() { + local name="$1" snapshot row + [[ "${name}" =~ ^[a-z0-9]([-a-z0-9.]*[a-z0-9])?$ ]] || return 0 + snapshot="$(report_ui_cached_probe doctor_focus_application_fetch "${name}")" || { + report_ui_emit warn "Item lookup" "Argo CD lookup" "Cannot query selected cluster" ""; return 0; + } + [[ -n "${snapshot}" ]] || return 0 + row="$(printf '%s' "${snapshot}" | python3 "${REPO_ROOT}/scripts/doctor-application.py" --report 2>&1)" || { + report_ui_emit warn "Item lookup" "Argo CD lookup" "Cannot interpret application" "${row}"; return 0; + } + printf '%s\n' "${row}" >>"${REPORT_UI_ROWS_FILE}" } doctor_focus_application_evidence() { - local name="$1" snapshot deployments namespace deployment state count=0 + local name="$1" snapshot deployments namespace deployment state count=0 failed=0 snapshot="$(report_ui_cached_probe doctor_focus_application_fetch "${name}")" || return 1 printf '%s' "${snapshot}" | python3 "${REPO_ROOT}/scripts/doctor-application.py" || return 1 deployments="$(printf '%s' "${snapshot}" | python3 "${REPO_ROOT}/scripts/doctor-application.py" --deployments)" || return 1 @@ -47,33 +60,48 @@ doctor_focus_application_evidence() { count=$((count + 1)) printf 'deployment %s/%s: ' "${namespace}" "${deployment}" if state="$(kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s -n "${namespace}" get deployment "${deployment}" -o json 2>/dev/null)"; then - printf '%s' "${state}" | python3 "${REPO_ROOT}/scripts/doctor-application.py" --deployment || return 1 + printf '%s' "${state}" | python3 "${REPO_ROOT}/scripts/doctor-application.py" --deployment || failed=1 else echo "unavailable" + failed=1 fi done <<<"${deployments}" + return "${failed}" } -doctor_focus_rpi_os_report() { - local host="${LAB_RPI_HOST:-}" user="${LAB_RPI_USER:-}" key="${LAB_RPI_SSH_KEY_PATH:-${HOME}/.ssh/id_ed25519}" - local snapshot rows severity name detail - [[ -n "${host}" && -n "${user}" ]] || { report_ui_emit warn "RPi4 OS" "OS snapshot" "Host or user missing from inventory" ""; return 0; } - snapshot="$(timeout 12 ssh -n -i "${key}" -o BatchMode=yes -o ConnectTimeout=3 \ - -o ConnectionAttempts=1 -o StrictHostKeyChecking=yes "${user}@${host}" ' +doctor_focus_host_os_report() { + local scope="$1" host="" user="" key="" area snapshot rows severity name detail command + case "${scope}" in + debian) area="Debian OS" ;; + rpi) area="RPi4 OS"; host="${LAB_RPI_HOST:-}"; user="${LAB_RPI_USER:-}"; key="${LAB_RPI_SSH_KEY_PATH:-${HOME}/.ssh/id_ed25519}" ;; + opi5) area="Orange Pi OS"; host="${LAB_PIMOX_HOST:-}"; user="${LAB_PIMOX_USER:-}"; key="${LAB_PIMOX_SSH_KEY_PATH:-${HOME}/.ssh/id_ed25519}" ;; + oci) area="OCI edge OS"; 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 + command=' export LC_ALL=C -printf "%s\n" __JEANNIE_RPI_OS_V1__ +printf "%s\n" __JEANNIE_HOST_OS_V1__ printf "kernel="; uname -sr printf "uptime_load="; uptime printf "memory_kib="; awk '\''/MemTotal:/ {t=$2} /MemAvailable:/ {a=$2} END {print t, a}'\'' /proc/meminfo printf "root_percent="; df -P / | awk '\''NR==2 {gsub(/%/, "", $5); print $5}'\'' printf "systemd="; systemctl is-system-running || true -' 2>&1)" || { report_ui_emit warn "RPi4 OS" "OS snapshot" "Cannot read RPi OS state" "${snapshot}" "./jeannie doctor-rpi"; return 0; } +' + if [[ "${scope}" == debian ]]; then + snapshot="$(timeout 12 bash -c "${command}" 2>&1)" || { report_ui_emit warn "${area}" "OS snapshot" "Cannot read OS state" "${snapshot}"; return 0; } + else + [[ -n "${host}" && -n "${user}" ]] || { report_ui_emit warn "${area}" "OS snapshot" "Host or user missing from inventory" ""; return 0; } + snapshot="$(timeout 12 ssh -n -i "${key}" -o BatchMode=yes -o ConnectTimeout=3 \ + -o ConnectionAttempts=1 -o StrictHostKeyChecking=yes "${user}@${host}" "${command}" 2>&1)" || { + report_ui_emit warn "${area}" "OS snapshot" "Cannot read host OS state" "${snapshot}"; return 0; + } + fi rows="$(printf '%s\n' "${snapshot}" | python3 "${REPO_ROOT}/scripts/doctor-rpi-os.py" "${LAB_STATUS_DISK_USE_THRESHOLD:-85}" 2>&1)" || { - report_ui_emit warn "RPi4 OS" "OS snapshot" "Cannot interpret RPi OS state" "${rows}" "./jeannie doctor-rpi"; return 0; + report_ui_emit warn "${area}" "OS snapshot" "Cannot interpret host OS state" "${rows}"; return 0; } while IFS=$'\t' read -r severity name detail; do [[ -n "${severity}" ]] || continue - report_ui_emit "${severity}" "RPi4 OS" "${name}" "${detail}" "${detail}" "./jeannie doctor-rpi" + report_ui_emit "${severity}" "${area}" "${name}" "${detail}" "${detail}" done <<<"${rows}" } @@ -100,6 +128,7 @@ doctor_focus_compose_evidence() { } doctor_focus_extra() { + case "$1" in oci|rpi|opi5|debian) report_ui_enqueue doctor_focus_host_os_report "$1" ;; esac case "$1" in oci) if [[ -n "${LAB_PUBLIC_URL:-}" ]]; then @@ -107,7 +136,6 @@ doctor_focus_extra() { fi ;; rpi) - report_ui_enqueue doctor_focus_rpi_os_report 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 ;; @@ -124,7 +152,7 @@ doctor_focus_extra() { } doctor_focus() { - local scope="${1:-}" item="" rc=0 selected area check severity evidence snapshot direct=false + local scope="${1:-}" item="" rc=0 selected area check severity evidence direct=false local -a flags=() case "${scope}" in -h|--help) doctor_focus_usage; return 0 ;; @@ -152,18 +180,21 @@ doctor_focus() { report_ui_parse_args "${flags[@]}" || return 2 report_ui_begin if [[ "${direct}" == true ]]; then - if ! snapshot="$(report_ui_cached_probe doctor_focus_application_fetch "${item}")" || - ! selected="$(printf '%s' "${snapshot}" | python3 "${REPO_ROOT}/scripts/doctor-application.py" --report)"; then - report_ui_cleanup - echo "Cannot read Argo CD application '${item}' in the selected cluster." >&2 - return 1 - fi - printf '%s\n' "${selected}" >"${REPORT_UI_ROWS_FILE}" + report_ui_enqueue doctor_focus_application_lookup "${item}" + report_ui_enqueue status_focus_compose_report "Debian Compose" local "" "" + report_ui_enqueue status_focus_compose_report "RPi4 Compose" "${LAB_RPI_HOST:-}" "${LAB_RPI_USER:-}" "${LAB_RPI_SSH_KEY_PATH:-${HOME}/.ssh/id_ed25519}" + report_ui_enqueue status_focus_compose_report "Orange Pi Compose" "${LAB_PIMOX_HOST:-}" "${LAB_PIMOX_USER:-}" "${LAB_PIMOX_SSH_KEY_PATH:-${HOME}/.ssh/id_ed25519}" + report_ui_enqueue status_focus_compose_report "OCI edge Compose" "${LAB_EDGE_TAILSCALE_IP:-}" "${LAB_EDGE_USER:-}" "${LAB_EDGE_SSH_KEY_PATH:-${LAB_OCI_SSH_PRIVATE_KEY:-${HOME}/.ssh/id_ed25519}}" else status_focus_collect "${scope}" if [[ -z "${item}" ]]; then doctor_focus_extra "${scope}"; fi fi report_ui_finish + if [[ "${direct}" == true ]] && awk -F '\t' '$1 == "warn" && ($2 == "Item lookup" || $3 == "Compose inventory") { found=1 } END { exit !found }' "${REPORT_UI_ROWS_FILE}"; then + report_ui_cleanup + echo "Some item sources are unavailable; specify a device or cluster scope to avoid an ambiguous match." >&2 + return 2 + fi if [[ -n "${item}" ]]; then if ! selected="$(python3 "${REPO_ROOT}/scripts/doctor-filter.py" "${item}" <"${REPORT_UI_ROWS_FILE}")"; then report_ui_cleanup @@ -180,12 +211,22 @@ doctor_focus() { if evidence="$(doctor_focus_application_evidence "${check}" 2>&1)"; then report_ui_emit "${severity}" "Kubernetes evidence" "${check} application details" "Application state and resources" "${evidence}" "kubectl get pods -A -o wide" else - report_ui_emit warn "Kubernetes evidence" "${check} application details" "Cannot read application evidence" "${evidence}" "kubectl get pods -A -o wide" + report_ui_emit warn "Kubernetes evidence" "${check} application details" "Application evidence indicates a problem or could not be read" "${evidence}" "kubectl get pods -A -o wide" fi elif [[ "${area}" == *" Compose" ]]; then + case "${area}" in + "Debian Compose") scope=debian ;; + "RPi4 Compose") scope=rpi ;; + "Orange Pi Compose") scope=opi5 ;; + "OCI edge Compose") scope=oci ;; + esac # 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}" + if evidence="$(doctor_focus_compose_evidence "${scope}" "${check}" 2>&1)"; then + report_ui_emit "${severity}" "Compose evidence" "${check} container details" "Container state and restarts" "${evidence}" + else + report_ui_emit warn "Compose evidence" "${check} container details" "Cannot read container evidence" "${evidence}" + fi fi fi ((REPORT_UI_FAILURES == 0)) || rc=1 diff --git a/scripts/doctor-rpi-os.py b/scripts/doctor-rpi-os.py index 6a72c9b..310a9b4 100644 --- a/scripts/doctor-rpi-os.py +++ b/scripts/doctor-rpi-os.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Turn the marked read-only RPi OS snapshot into report rows.""" +"""Turn a marked read-only host OS snapshot into report rows.""" import sys @@ -10,7 +10,7 @@ def emit(status, check, detail): try: lines = sys.stdin.read().splitlines() - start = lines.index("__JEANNIE_RPI_OS_V1__") + 1 + start = lines.index("__JEANNIE_HOST_OS_V1__") + 1 data = dict(line.split("=", 1) for line in lines[start:] if "=" in line) memory_total, memory_available = map(int, data["memory_kib"].split()) disk = int(data["root_percent"]) @@ -25,5 +25,5 @@ try: state = data["systemd"] emit("ok" if state == "running" else "warn", "Systemd state", state) except (ValueError, KeyError, IndexError) as exc: - print(f"Cannot interpret RPi OS snapshot: {exc}", file=sys.stderr) + print(f"Cannot interpret host OS snapshot: {exc}", file=sys.stderr) sys.exit(1) diff --git a/tests/jeannie/test_doctor_focus.py b/tests/jeannie/test_doctor_focus.py index bdd4a71..12985de 100644 --- a/tests/jeannie/test_doctor_focus.py +++ b/tests/jeannie/test_doctor_focus.py @@ -57,6 +57,13 @@ class DoctorFocusTests(unittest.TestCase): text=True, check=True) self.assertIn("desired=0 ready=0", result.stdout) + def test_deployment_unavailable_replicas_are_reported(self): + deployment = {"spec": {"replicas": 2}, "status": {"readyReplicas": 1}} + result = subprocess.run([sys.executable, str(APP), "--deployment"], + input=json.dumps(deployment), capture_output=True, text=True) + self.assertNotEqual(result.returncode, 0) + self.assertIn("desired=2 ready=1", result.stdout) + def test_selected_item_does_not_inherit_unrelated_failure(self): code = r''' source "$1" @@ -89,6 +96,8 @@ require_debian_server() { :; } report_ui_parse_args() { :; } report_ui_begin() { REPORT_UI_ROWS_FILE="$(mktemp)"; } report_ui_cached_probe() { printf '%s' "$APP_JSON"; } +report_ui_enqueue() { "$@"; } +status_focus_compose_report() { :; } report_ui_finish() { REPORT_UI_FAILURES=0; } doctor_focus_application_evidence() { printf 'desired=1 ready=0\n'; } report_ui_emit() { printf 'evidence:%s\n' "$5"; } @@ -107,7 +116,7 @@ doctor_focus gitea-runner self.assertIn("desired=1 ready=0", result.stdout) def test_rpi_os_snapshot_reports_disk_and_memory_pressure(self): - snapshot = ("login banner\n__JEANNIE_RPI_OS_V1__\nkernel=Linux 6.1\n" + snapshot = ("login banner\n__JEANNIE_HOST_OS_V1__\nkernel=Linux 6.1\n" "uptime_load=up 1 day, load 0.1\nmemory_kib=1000 80\n" "root_percent=90\nsystemd=degraded\n") result = subprocess.run([sys.executable, str(RPI_OS), "85"], input=snapshot, @@ -116,6 +125,52 @@ doctor_focus gitea-runner self.assertIn("warn\tRoot filesystem usage", result.stdout) self.assertIn("warn\tSystemd state", result.stdout) + def test_direct_compose_uses_detected_host_and_ai_evidence(self): + code = r''' +source "$1" +require_debian_server() { :; } +report_ui_parse_args() { :; } +report_ui_begin() { REPORT_UI_ROWS_FILE="$(mktemp)"; } +report_ui_cached_probe() { :; } +report_ui_enqueue() { "$@"; } +status_focus_compose_report() { + if [[ "$1" == "Debian Compose" ]]; then + printf 'warn\tDebian Compose\thomelab-gitea/gitea (homelab-gitea)\texited\t\t\t\t\n' >>"$REPORT_UI_ROWS_FILE" + fi +} +report_ui_finish() { REPORT_UI_FAILURES=0; } +doctor_focus_compose_evidence() { printf 'scope=%s restarts=2\n' "$1"; } +report_ui_emit() { printf 'evidence:%s %s\n' "$1" "$5"; } +report_ui_render() { cat "$REPORT_UI_ROWS_FILE"; } +report_ui_cleanup() { rm -f "$REPORT_UI_ROWS_FILE"; } +doctor_focus homelab-gitea/gitea +''' + 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("evidence:warn scope=debian restarts=2", result.stdout) + + def test_direct_lookup_refuses_unavailable_source(self): + code = r''' +source "$1" +require_debian_server() { :; } +report_ui_parse_args() { :; } +report_ui_begin() { REPORT_UI_ROWS_FILE="$(mktemp)"; } +report_ui_enqueue() { "$@"; } +doctor_focus_application_lookup() { :; } +status_focus_compose_report() { printf 'warn\tOCI edge Compose\tCompose inventory\tunavailable\t\t\t\t\n' >>"$REPORT_UI_ROWS_FILE"; } +report_ui_finish() { REPORT_UI_FAILURES=0; } +report_ui_cleanup() { rm -f "$REPORT_UI_ROWS_FILE"; } +doctor_focus example +''' + 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) + self.assertEqual(result.returncode, 2) + self.assertIn("specify a device or cluster scope", result.stderr) + if __name__ == "__main__": unittest.main()