From ecc64082b2d0ee8b124a93fea7815be59a3c757a Mon Sep 17 00:00:00 2001 From: "juvenal.diaz" Date: Thu, 22 Oct 2026 18:21:15 -0600 Subject: [PATCH] feat: add read-only mesh doctor --- cmd/jeannie-server/main.go | 1 + cmd/jeannie-server/main_test.go | 6 ++ jeannie | 4 + lib/jeannie/commands.sh | 17 ++++ scripts/mesh-doctor | 154 ++++++++++++++++++++++++++++++++ 5 files changed, 182 insertions(+) create mode 100755 scripts/mesh-doctor diff --git a/cmd/jeannie-server/main.go b/cmd/jeannie-server/main.go index aeb1e15..c69545a 100644 --- a/cmd/jeannie-server/main.go +++ b/cmd/jeannie-server/main.go @@ -32,6 +32,7 @@ var allowedCommands = map[string]bool{ "status": true, "capacity": true, "capacity-advisor": true, "capacity-limits": true, "recover-plan": true, "gitops-status": true, "storage": true, + "mesh": true, "platform": true, "edge": true, "edge-cache-flush": true, "promote": true, "cert-check": true, "release-snapshot": true, "backup-status": true, "synthetic-checks": true, "resource-budget": true, diff --git a/cmd/jeannie-server/main_test.go b/cmd/jeannie-server/main_test.go index fa3d3f0..d37216f 100644 --- a/cmd/jeannie-server/main_test.go +++ b/cmd/jeannie-server/main_test.go @@ -111,3 +111,9 @@ func TestStorageCommandIsRemotelyEnabled(t *testing.T) { t.Fatal("storage must be exposed through the remote API") } } + +func TestMeshCommandIsRemotelyEnabled(t *testing.T) { + if !allowedCommands["mesh"] { + t.Fatal("mesh must be exposed through the remote API") + } +} diff --git a/jeannie b/jeannie index 582c993..e07c907 100755 --- a/jeannie +++ b/jeannie @@ -117,6 +117,7 @@ Observability And GitOps gitea-runner-secret {migrate|apply|file} Convert/apply the Gitea runner SOPS secret. gitops-status Print focused Argo CD health and sync status. storage {status|cleanup|snapshot|expand|rebalance} Manage and inspect storage safely. + mesh doctor [--json] Run read-only Kubernetes, Calico, SSH, and Tailscale checks. platform [all|calico|metrics|dns|metallb|ingress|storage|argocd|security|logging|monitoring|tools] Deploy one platform component or the full platform stack. edge Deploy/check the OCI edge stack only. @@ -260,6 +261,9 @@ case "${1:-}" in storage) storage_manage "${@:2}" ;; + mesh) + mesh_doctor "${@:2}" + ;; platform) record_change_journal "platform" "$@" require_debian_server "platform" diff --git a/lib/jeannie/commands.sh b/lib/jeannie/commands.sh index a7fa353..878af70 100644 --- a/lib/jeannie/commands.sh +++ b/lib/jeannie/commands.sh @@ -3520,6 +3520,23 @@ EOF esac } +mesh_doctor() { + require_debian_server "mesh doctor" + local format="" + if [[ "${1:-}" == "doctor" ]]; then + shift + fi + if [[ "${1:-}" == "--json" ]]; then + format="--json" + shift + fi + if [[ $# -gt 0 ]]; then + echo "Usage: ./jeannie mesh doctor [--json]" >&2 + return 2 + fi + "${REPO_ROOT}/scripts/mesh-doctor" ${format} +} + cert_check() { "${REPO_ROOT}/scripts/cert-check" } diff --git a/scripts/mesh-doctor b/scripts/mesh-doctor new file mode 100755 index 0000000..477b585 --- /dev/null +++ b/scripts/mesh-doctor @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +"""Read-only connectivity and CNI checks for the homelab mesh.""" + +from __future__ import annotations + +import argparse +import json +import os +import shutil +import socket +import subprocess +from pathlib import Path + + +def run(command: list[str], timeout: int = 10) -> tuple[int, str, str]: + try: + completed = subprocess.run(command, text=True, capture_output=True, timeout=timeout) + except (OSError, subprocess.TimeoutExpired) as exc: + return 124, "", str(exc) + return completed.returncode, completed.stdout.strip(), completed.stderr.strip() + + +def row(status: str, check: str, summary: str, detail: str = "") -> dict[str, str]: + result = {"status": status, "check": check, "summary": summary} + if detail: + result["detail"] = detail + return result + + +def tcp_check(name: str, host: str, port: int = 22) -> dict[str, str]: + if not host: + return row("warn", name, "not configured") + try: + with socket.create_connection((host, port), timeout=5): + return row("pass", name, f"{host}:{port} reachable") + except OSError as exc: + return row("fail", name, f"{host}:{port} unreachable", str(exc)) + + +def kubectl(kubeconfig: str, *args: str) -> tuple[int, str, str]: + command = ["kubectl"] + if kubeconfig: + command += ["--kubeconfig", kubeconfig] + return run(command + list(args), timeout=15) + + +def inventory(repo_root: Path) -> list[tuple[str, str, str]]: + path = repo_root / ".lab" / "pimox-workers.tsv" + result = [] + if not path.is_file(): + return result + for line in path.read_text().splitlines(): + fields = line.split("\t") + if len(fields) >= 4 and fields[1] and fields[3]: + result.append((fields[3], fields[1], fields[2] or "")) + return result + + +def collect(repo_root: Path) -> dict: + rows: list[dict[str, str]] = [] + kubeconfig = os.environ.get("LAB_KUBECONFIG_PATH", os.environ.get("KUBECONFIG", "/home/jv/.kube/config")) + + code, output, error = kubectl(kubeconfig, "get", "--raw=/readyz") + if code == 0 and output: + rows.append(row("pass", "Kubernetes API", "ready", output.replace("\n", "; "))) + else: + rows.append(row("fail", "Kubernetes API", "not ready", error or output or "kubectl failed")) + + code, output, error = kubectl( + kubeconfig, + "get", + "nodes", + "-o", + "jsonpath={range .items[*]}{.metadata.name}{\"\\t\"}{.status.conditions[?(@.type==\"Ready\")].status}{\"\\n\"}{end}", + ) + if code == 0: + nodes = [line.split("\t", 1) for line in output.splitlines() if "\t" in line] + unhealthy = [name for name, ready in nodes if ready != "True"] + if unhealthy: + rows.append(row("warn", "Kubernetes nodes", f"{len(nodes) - len(unhealthy)}/{len(nodes)} Ready", ", ".join(unhealthy))) + else: + rows.append(row("pass", "Kubernetes nodes", f"{len(nodes)}/{len(nodes)} Ready")) + else: + rows.append(row("warn", "Kubernetes nodes", "unable to inspect", error or output or "kubectl failed")) + + code, output, error = kubectl(kubeconfig, "-n", "calico-system", "get", "pods", "-l", "k8s-app=calico-node", "-o", "json") + if code == 0: + try: + pods = json.loads(output).get("items", []) + ready = 0 + for pod in pods: + conditions = pod.get("status", {}).get("conditions", []) + if any(c.get("type") == "Ready" and c.get("status") == "True" for c in conditions): + ready += 1 + status = "pass" if pods and ready == len(pods) else "warn" + rows.append(row(status, "Calico node mesh", f"{ready}/{len(pods)} Ready")) + except json.JSONDecodeError: + rows.append(row("warn", "Calico node mesh", "invalid kubectl response")) + else: + rows.append(row("warn", "Calico node mesh", "unable to inspect", error or output or "kubectl failed")) + + control_plane = os.environ.get("LAB_CLUSTER_CONTROL_PLANE_LAN_IP", os.environ.get("LAB_DEBIAN_LAN_IP", "")) + rows.append(tcp_check("Control-plane SSH path", control_plane)) + for node, address, _user in inventory(repo_root): + rows.append(tcp_check(f"{node} SSH path", address)) + + tailscale = shutil.which("tailscale") + if not tailscale: + rows.append(row("warn", "Tailscale", "client not installed")) + else: + code, output, error = run([tailscale, "status", "--json"], timeout=10) + if code != 0: + rows.append(row("warn", "Tailscale", "status unavailable", error or output or "tailscale failed")) + else: + try: + status = json.loads(output) + backend = status.get("BackendState", "unknown") + peers = len(status.get("Peer", {}) or {}) + rows.append(row("pass" if backend == "Running" else "warn", "Tailscale", f"{backend}; peers={peers}")) + except json.JSONDecodeError: + rows.append(row("warn", "Tailscale", "invalid status response")) + targets = [item.strip() for item in os.environ.get("LAB_MESH_TAILSCALE_TARGETS", "").split(",") if item.strip()] + for target in targets: + code, output, error = run([tailscale, "ping", "--timeout=5s", target], timeout=8) + if code == 0: + path = "DERP relay" if "via DERP" in output else "direct path" + rows.append(row("pass", f"Tailscale ping {target}", path, output.splitlines()[-1] if output else "")) + else: + rows.append(row("fail", f"Tailscale ping {target}", "unreachable", error or output or "tailscale ping failed")) + + counts = {state: sum(1 for item in rows if item["status"] == state) for state in ("pass", "warn", "fail")} + overall = "fail" if counts["fail"] else "warn" if counts["warn"] else "pass" + return {"title": "Mesh Doctor", "status": overall, "rows": rows, "counts": counts} + + +def main() -> int: + parser = argparse.ArgumentParser(description="Read-only homelab mesh diagnostics") + parser.add_argument("--json", action="store_true", dest="as_json") + args = parser.parse_args() + report = collect(Path(__file__).resolve().parents[1]) + if args.as_json: + print(json.dumps(report, indent=2, sort_keys=False)) + else: + print(f"== {report['title']} ==") + for item in report["rows"]: + print(f"{item['status']:<4} {item['check']:<24} {item['summary']}") + if item.get("detail"): + print(f" detail: {item['detail']}") + print(f"Overall: {report['status']} ({report['counts']})") + return 1 if report["status"] == "fail" else 0 + + +if __name__ == "__main__": + raise SystemExit(main())