Diagnose RPi operating system and individual applications

This commit is contained in:
juvenal.diaz 2026-11-11 15:16:18 -06:00
parent f3a0fbe3bf
commit f9ee70d0bd
6 changed files with 183 additions and 18 deletions

View File

@ -12,7 +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 Orange Pi view reports its host and selected K3s checks.
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.
Existing `doctor-edge`, `doctor-gitea`, `doctor-rpi`, `doctor-cluster`, and
`doctor-k8s` remain available for their specialized investigations.
@ -21,6 +23,7 @@ Argo CD application name or Compose project/service:
```sh
./jeannie doctor cluster gitea-runner --details
./jeannie doctor gitea-runner
./jeannie doctor debian --item homelab-gitea/gitea --details
./jeannie remote doctor rpi --item homelab-rpi-services/pihole --ai
```
@ -30,10 +33,13 @@ 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
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
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
`--no-local-rca` to disable it. AI is enabled by default for a selected item,
and is off by default for a whole host or cluster scope. It does not perform
repairs. `--json` returns structured evidence without AI output. These are
read-only checks; any suggested remediation should be reviewed separately.

View File

@ -189,7 +189,7 @@ 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]
doctor {oci|rpi|opi5|debian|cluster|APPLICATION} [ITEM] [--ai|--json|--details]
Diagnose one area or named item.
doctor-edge [--all|--details|--verbose|--json]
Diagnose edge routing and public exposure.

View File

@ -2,13 +2,38 @@
"""Extract non-secret Argo CD application health evidence."""
import json
import re
import sys
try:
app = json.load(sys.stdin)
if len(sys.argv) > 1 and sys.argv[1] == "--deployment":
spec, current = app.get("spec") or {}, app.get("status") or {}
print("deployment replicas: desired={} ready={} available={}".format(
spec.get("replicas", 1), current.get("readyReplicas", 0), current.get("availableReplicas", 0)))
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)
status = app.get("status") or {}
health = status.get("health") or {}
operation = status.get("operationState") or {}
if len(sys.argv) > 1 and sys.argv[1] == "--deployments":
safe = re.compile(r"^[a-z0-9]([-a-z0-9.]*[a-z0-9])?$")
for resource in status.get("resources") or []:
namespace, name = resource.get("namespace", ""), resource.get("name", "")
if resource.get("kind") == "Deployment" and safe.fullmatch(namespace) and safe.fullmatch(name):
print(namespace, name)
sys.exit(0)
if len(sys.argv) > 1 and sys.argv[1] == "--report":
name = (app.get("metadata") or {}).get("name", "unknown")
health_state = health.get("status", "Unknown")
sync = (status.get("sync") or {}).get("status", "Unknown")
severity = "fail" if health_state in ("Degraded", "Missing") else (
"ok" if health_state == "Healthy" and sync == "Synced" else "warn")
print("\t".join((severity, "Kubernetes apps", name,
f"health={health_state}, sync={sync}", "", "kubectl get pods -A -o wide", "", "")))
sys.exit(0)
print("health:", health.get("status", "Unknown"))
if health.get("message"):
print("health message:", health["message"])

View File

@ -3,13 +3,15 @@
doctor_focus_usage() {
cat <<'EOF'
Usage: ./jeannie doctor {oci|rpi|opi5|debian|cluster} [ITEM] [--ai] [--json] [--details] [--all]
Usage: ./jeannie doctor {oci|rpi|opi5|debian|cluster} [ITEM] [options]
./jeannie doctor ARGOCD_APPLICATION [options]
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).
--ai Request an evidence-validated AI explanation (text only;
enabled by default when diagnosing an item).
--no-local-rca Disable the AI explanation.
--json Return the structured diagnostic report.
--details Show supporting evidence.
@ -18,6 +20,7 @@ shown by status. There is no all-area doctor.
Examples:
./jeannie doctor rpi
./jeannie doctor gitea-runner
./jeannie doctor cluster gitea-runner --ai
./jeannie remote doctor debian --item homelab-gitea/gitea
EOF
@ -27,11 +30,51 @@ 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
doctor_focus_application_fetch() {
local name="$1"
[[ "${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"
kubectl --kubeconfig "${KUBECONFIG_PATH}" --request-timeout=10s -n argocd get application "${name}" -o json 2>/dev/null
}
doctor_focus_application_evidence() {
local name="$1" snapshot deployments namespace deployment state count=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
while read -r namespace deployment; do
[[ -n "${namespace}" && -n "${deployment}" ]] || continue
((count < 8)) || { echo "Additional deployments omitted"; break; }
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
else
echo "unavailable"
fi
done <<<"${deployments}"
}
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}" '
export LC_ALL=C
printf "%s\n" __JEANNIE_RPI_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; }
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;
}
while IFS=$'\t' read -r severity name detail; do
[[ -n "${severity}" ]] || continue
report_ui_emit "${severity}" "RPi4 OS" "${name}" "${detail}" "${detail}" "./jeannie doctor-rpi"
done <<<"${rows}"
}
doctor_focus_compose_evidence() {
@ -64,6 +107,7 @@ 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
;;
@ -80,12 +124,14 @@ doctor_focus_extra() {
}
doctor_focus() {
local scope="${1:-}" item="" rc=0 selected area check
local scope="${1:-}" item="" rc=0 selected area check severity evidence snapshot direct=false
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 ;;
all|"") doctor_focus_usage >&2; return 2 ;;
-*) doctor_focus_usage >&2; return 2 ;;
*) item="${scope}"; scope=cluster; direct=true; shift ;;
esac
while (($#)); do
case "$1" in
@ -102,10 +148,21 @@ doctor_focus() {
# 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
[[ -z "${item}" ]] || REPORT_UI_LOCAL_RCA=true
report_ui_parse_args "${flags[@]}" || return 2
report_ui_begin
status_focus_collect "${scope}"
if [[ -z "${item}" ]]; then doctor_focus_extra "${scope}"; fi
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}"
else
status_focus_collect "${scope}"
if [[ -z "${item}" ]]; then doctor_focus_extra "${scope}"; fi
fi
report_ui_finish
if [[ -n "${item}" ]]; then
if ! selected="$(python3 "${REPO_ROOT}/scripts/doctor-filter.py" "${item}" <"${REPORT_UI_ROWS_FILE}")"; then
@ -114,13 +171,17 @@ doctor_focus() {
fi
printf '%s\n' "${selected}" >"${REPORT_UI_ROWS_FILE}"
REPORT_UI_FAILURES=0
IFS=$'\t' read -r _ area check _ <<<"${selected}"
IFS=$'\t' read -r severity 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}"
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"
fi
elif [[ "${area}" == *" Compose" ]]; then
# shellcheck disable=SC2034
REPORT_UI_PARALLEL=false

29
scripts/doctor-rpi-os.py Normal file
View File

@ -0,0 +1,29 @@
#!/usr/bin/env python3
"""Turn the marked read-only RPi OS snapshot into report rows."""
import sys
def emit(status, check, detail):
print("\t".join((status, check, detail.replace("\t", " ").replace("\n", " "))))
try:
lines = sys.stdin.read().splitlines()
start = lines.index("__JEANNIE_RPI_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"])
if memory_total <= 0 or not 0 <= memory_available <= memory_total or not 0 <= disk <= 100:
raise ValueError("invalid memory or disk values")
threshold = int(sys.argv[1])
emit("ok", "Kernel", data["kernel"])
emit("ok", "Uptime and load", data["uptime_load"])
emit("warn" if memory_available * 100 < memory_total * 10 else "ok",
"Memory available", f"{memory_available // 1024} MiB available of {memory_total // 1024} MiB")
emit("warn" if disk >= threshold else "ok", "Root filesystem usage", f"{disk}% used (threshold {threshold}%)")
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)
sys.exit(1)

View File

@ -10,6 +10,7 @@ ROOT = Path(__file__).resolve().parents[2]
FILTER = ROOT / "scripts" / "doctor-filter.py"
APP = ROOT / "scripts" / "doctor-application.py"
DOCTOR = ROOT / "scripts" / "doctor-focus"
RPI_OS = ROOT / "scripts" / "doctor-rpi-os.py"
def run_filter(item, rows):
@ -49,6 +50,13 @@ class DoctorFocusTests(unittest.TestCase):
self.assertIn("Deployment", result.stdout)
self.assertNotIn("do-not-print", result.stdout)
def test_deployment_evidence_reports_actual_desired_replicas(self):
deployment = {"spec": {"replicas": 0}, "status": {"readyReplicas": 0}}
result = subprocess.run([sys.executable, str(APP), "--deployment"],
input=json.dumps(deployment), capture_output=True,
text=True, check=True)
self.assertIn("desired=0 ready=0", result.stdout)
def test_selected_item_does_not_inherit_unrelated_failure(self):
code = r'''
source "$1"
@ -59,7 +67,8 @@ 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"; }
doctor_focus_application_evidence() { printf 'deployment replicas: desired=1 ready=0\n'; }
report_ui_emit() { printf 'evidence-requested:%s %s\n' "$3" "$5"; }
report_ui_render() { cat "$REPORT_UI_ROWS_FILE"; }
report_ui_cleanup() { rm -f "$REPORT_UI_ROWS_FILE"; }
doctor_focus cluster runner
@ -68,10 +77,45 @@ doctor_focus cluster runner
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("runner application details", result.stdout)
self.assertIn("desired=1 ready=0", result.stdout)
self.assertIn("Progressing", result.stdout)
self.assertNotIn("other", result.stdout)
def test_direct_application_uses_single_target_and_ai_by_default(self):
code = r'''
source "$1"
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_finish() { REPORT_UI_FAILURES=0; }
doctor_focus_application_evidence() { printf 'desired=1 ready=0\n'; }
report_ui_emit() { printf 'evidence:%s\n' "$5"; }
report_ui_render() { printf 'ai=%s\n' "$REPORT_UI_LOCAL_RCA"; cat "$REPORT_UI_ROWS_FILE"; }
report_ui_cleanup() { rm -f "$REPORT_UI_ROWS_FILE"; }
doctor_focus gitea-runner
'''
env = os.environ.copy()
env.update(REPO_ROOT=str(ROOT), APP_JSON=json.dumps({
"metadata": {"name": "gitea-runner"}, "status": {
"health": {"status": "Progressing"}, "sync": {"status": "Synced"}}}))
result = subprocess.run(["bash", "-c", code, "test", str(DOCTOR)],
env=env, capture_output=True, text=True, check=True)
self.assertIn("ai=true", result.stdout)
self.assertIn("gitea-runner", result.stdout)
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"
"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,
capture_output=True, text=True, check=True)
self.assertIn("warn\tMemory available", result.stdout)
self.assertIn("warn\tRoot filesystem usage", result.stdout)
self.assertIn("warn\tSystemd state", result.stdout)
if __name__ == "__main__":
unittest.main()