feat: add read-only mesh doctor
This commit is contained in:
parent
e831cf2705
commit
ecc64082b2
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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")
|
||||
}
|
||||
}
|
||||
|
|
|
|||
4
jeannie
4
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"
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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())
|
||||
Loading…
Reference in New Issue