diff --git a/cmd/jeannie-core/main.go b/cmd/jeannie-core/main.go index 8dd2853..24e9a23 100644 --- a/cmd/jeannie-core/main.go +++ b/cmd/jeannie-core/main.go @@ -16,14 +16,32 @@ import ( ) type reportRow struct { - Status string `json:"status"` - Area string `json:"area"` - Check string `json:"check"` - Summary string `json:"summary"` - Detail string `json:"detail"` - Fix string `json:"fix"` - Graph string `json:"graph"` - Query string `json:"query"` + Status string `json:"status"` + Area string `json:"area"` + Check string `json:"check"` + Summary string `json:"summary"` + Detail string `json:"detail"` + Fix string `json:"fix"` + Graph string `json:"graph"` + Query string `json:"query"` + Cause string `json:"cause,omitempty"` + Mitigate string `json:"mitigate,omitempty"` + Redesign string `json:"redesign,omitempty"` + Evidence string `json:"evidence,omitempty"` + Impact string `json:"impact,omitempty"` + ImpactScore int `json:"impact_score,omitempty"` +} + +type reportDiagnosis struct { + Cause string + Mitigate string + Redesign string + Evidence string +} + +type reportImpact struct { + Label string + Score int } func main() { @@ -301,6 +319,16 @@ func parseReportRows(in io.Reader) ([]reportRow, error) { row.Graph = "" row.Query = "" } + if row.Status == "fail" || row.Status == "warn" { + diagnosis := diagnoseReportRow(row) + row.Cause = diagnosis.Cause + row.Mitigate = diagnosis.Mitigate + row.Redesign = diagnosis.Redesign + row.Evidence = diagnosis.Evidence + impact := assessReportImpact(row) + row.Impact = impact.Label + row.ImpactScore = impact.Score + } rows = append(rows, row) } return rows, nil @@ -363,6 +391,23 @@ func renderReportText(out io.Writer, title string, rows []reportRow, details boo return } + if focus, ok := highestImpactReportRow(rows); ok { + fmt.Fprintln(out, "\n== Highest Impact Focus ==") + fmt.Fprintf(out, "%s / %s: %s\n", focus.Area, focus.Check, focus.Summary) + if focus.Impact != "" { + fmt.Fprintf(out, "impact: %s\n", focus.Impact) + } + if focus.Cause != "" { + fmt.Fprintf(out, "likely: %s\n", focus.Cause) + } + if focus.Fix != "" { + fmt.Fprintf(out, "first action: %s\n", focus.Fix) + } + if focus.Mitigate != "" { + fmt.Fprintf(out, "mitigate: %s\n", focus.Mitigate) + } + } + for _, area := range orderedReportAreas(rows) { fmt.Fprintf(out, "\n== %s ==\n", area) areaRows := rowsForReportArea(rows, area) @@ -381,9 +426,24 @@ func renderReportText(out io.Writer, title string, rows []reportRow, details boo if row.Detail != "" { fmt.Fprintf(out, " detail: %s\n", row.Detail) } + if row.Evidence != "" { + fmt.Fprintf(out, " evidence: %s\n", row.Evidence) + } + if row.Impact != "" { + fmt.Fprintf(out, " impact: %s\n", row.Impact) + } + if row.Cause != "" { + fmt.Fprintf(out, " likely: %s\n", row.Cause) + } if row.Fix != "" { fmt.Fprintf(out, " fix: %s\n", row.Fix) } + if row.Mitigate != "" { + fmt.Fprintf(out, " mitigate: %s\n", row.Mitigate) + } + if row.Redesign != "" { + fmt.Fprintf(out, " redesign: %s\n", row.Redesign) + } if row.Graph != "" { fmt.Fprintf(out, " graph: %s\n", row.Graph) } @@ -407,6 +467,142 @@ func renderReportText(out io.Writer, title string, rows []reportRow, details boo } } +func highestImpactReportRow(rows []reportRow) (reportRow, bool) { + var focus reportRow + found := false + for _, row := range rows { + if row.Status != "fail" && row.Status != "warn" { + continue + } + if !found || row.ImpactScore > focus.ImpactScore || (row.ImpactScore == focus.ImpactScore && reportStatusRank(row.Status) < reportStatusRank(focus.Status)) { + focus = row + found = true + } + } + return focus, found +} + +func diagnoseReportRow(row reportRow) reportDiagnosis { + text := strings.ToLower(strings.Join([]string{row.Area, row.Check, row.Summary, row.Detail}, " ")) + diagnosis := reportDiagnosis{ + Evidence: evidenceFromRow(row), + } + + switch { + case containsAny(text, "connection refused", "connect: connection refused", "couldn't connect to server", "no route to host", "network is unreachable", "timed out", "i/o timeout"): + diagnosis.Cause = "The target is not accepting traffic from this network path. The usual break is service down, wrong backend IP/port, route advertisement, firewall/NAT, or MetalLB address ownership." + diagnosis.Mitigate = "Test the next hop directly from the host that failed, then restart or reapply the owning layer shown by the check. For public URL failures, compare Debian -> Traefik and OCI edge -> Traefik before changing app code." + diagnosis.Redesign = "Keep backend IPs and edge routes inventory-driven and prefer one routed entry point per service to reduce stale hardcoded targets." + case containsAny(text, "tls handshake timeout", "bad record mac", "certificate", "x509", "ssl"): + diagnosis.Cause = "TLS is failing before the application response is usable. Common causes are API server load, proxy/cache corruption, stale certificates, or HTTPS being attempted against an HTTP-only backend." + diagnosis.Mitigate = "Validate the same endpoint with a direct HTTP/TLS probe from the closest hop, then restart/reapply the proxy or control-plane component that owns TLS termination." + diagnosis.Redesign = "Terminate TLS at a single intentional layer and keep cache/proxy compression disabled for identity/control-plane paths." + case containsAny(text, "imagepullbackoff", "errimagepull", "server gave http response to https client", "failed to pull", "manifest unknown", "pull access denied"): + diagnosis.Cause = "A node cannot pull the image it was scheduled to run. Likely causes are unsigned/stale tag, missing image, insecure registry config drift, or the registry endpoint not reachable from Pimox workers." + diagnosis.Mitigate = "Run the apps pipeline to rebuild/sign/push the image, verify worker access to the registry, and restart only the affected deployment." + diagnosis.Redesign = "Make registry endpoint, insecure registry setup, signing policy, and image overrides generated from the same profile inputs." + case containsAny(text, "pending", "didn't match pod's node affinity", "insufficient", "taint", "unbound immediate persistentvolumeclaims"): + diagnosis.Cause = "The scheduler cannot place the pod. The usual cause is node affinity/selector drift, missing labels, taints, resource pressure, or storage claims not bound." + diagnosis.Mitigate = "Describe the pod and compare requested selectors/tolerations/resources with current node labels and capacity; reapply the profile/policy that owns those labels." + diagnosis.Redesign = "Keep node labels and workload placement policy generated per cluster profile so migration does not strand workloads." + case containsAny(text, "notready", "node(s) not ready", "node pressure", "diskpressure", "memorypressure", "pidpressure"): + diagnosis.Cause = "A Kubernetes node is unhealthy or under pressure. On Pimox this often points to VM health, CPU pinning, storage health, kubelet/containerd, or CNI readiness." + diagnosis.Mitigate = "Check the specific node condition, kubelet status, and Pimox VM state before restarting workloads; recover the node first." + diagnosis.Redesign = "Add capacity guardrails and profile-specific VM sizing/pinning so the cluster stays inside OPI5/Pimox limits." + case containsAny(text, "qemu guest agent is not running", "qm", "vm", "pimox", "storage", "input/output error"): + diagnosis.Cause = "The virtualization layer is unhealthy or unreachable. Likely causes are Pimox storage trouble, stopped/stuck VM, guest-agent failure, or CPU/storage pressure." + diagnosis.Mitigate = "Check Pimox storage and VM status first; avoid rebuilding Kubernetes until the VM and disk layer are healthy." + diagnosis.Redesign = "Keep VM CPU affinity, storage checks, and backup/restore drills as first-class profile checks." + case containsAny(text, "http 502", "http 503", "http 504", "no available server", "err_read_error"): + diagnosis.Cause = "A proxy reached the edge path but could not get a healthy backend response. This usually means stale cache/backend routing, dead upstream, or app ingress unavailable." + diagnosis.Mitigate = "Flush edge caches only after direct backend checks show healthy; if direct backend fails, fix Traefik/app first." + diagnosis.Redesign = "Separate cacheable website traffic from identity/API/control-plane traffic and generate edge backend targets from inventory." + case containsAny(text, "http 404", "not found"): + diagnosis.Cause = "The route exists but the requested path/host is not owned by the expected backend. Common causes are wrong host header, stale ingress, or provider/application path mismatch." + diagnosis.Mitigate = "Check ingress host/path and backend service target, then reapply the app or edge layer that owns routing." + diagnosis.Redesign = "Centralize public hostnames and callback/root URLs so app, ingress, and edge config cannot diverge." + case containsAny(text, "unauthorized", "forbidden", "permission denied", "authentication required"): + diagnosis.Cause = "The service is reachable, but credentials, RBAC, or token state does not authorize the operation." + diagnosis.Mitigate = "Rotate or re-sync the relevant SOPS/runner/API secret through the pipeline and validate the exact service account/user." + diagnosis.Redesign = "Prefer declarative secret inventory and automated restore drills over manual token creation." + case strings.Contains(text, "backup"): + diagnosis.Cause = "Backup freshness or restore validation is outside the expected window." + diagnosis.Mitigate = "Run the backup command and inspect the restore drill output before deleting old state." + diagnosis.Redesign = "Schedule profile-aware backup and restore-drill checks after each major topology change." + default: + diagnosis.Cause = "The check failed at this layer, but the output is not specific enough to isolate one root cause automatically." + diagnosis.Mitigate = "Run the suggested fix command with --verbose or use the related focused doctor to collect layer-specific evidence." + diagnosis.Redesign = "If this repeats, add a narrower check that verifies the dependency immediately upstream and downstream of this layer." + } + + return diagnosis +} + +func assessReportImpact(row reportRow) reportImpact { + text := strings.ToLower(strings.Join([]string{row.Area, row.Check, row.Summary, row.Detail}, " ")) + score := 10 + label := "low - limited or advisory impact" + + if row.Status == "fail" { + score += 30 + } else if row.Status == "warn" { + score += 10 + } + + switch { + case containsAny(text, "public", "edge", "website public", "gitea public", "grafana public", "argocd public", "dex public", "traefik loadbalancer", "no available server", "http 502", "http 503", "http 504"): + score += 45 + label = "critical - public access or edge ingress is affected" + case containsAny(text, "kubernetes", "api ready", "nodes ready", "notready", "control-plane", "pimox runtime"): + score += 40 + label = "critical - cluster control plane or node availability is affected" + case containsAny(text, "registry", "imagepullbackoff", "errimagepull", "failed to pull"): + score += 35 + label = "high - deployments cannot recover or roll out reliably" + case containsAny(text, "backup", "restore"): + score += 30 + label = "high - recovery confidence is reduced" + case containsAny(text, "gitea", "runner", "git"): + score += 25 + label = "medium - GitOps or CI/CD path may be degraded" + case containsAny(text, "dns", "pi-hole", "rpi"): + score += 25 + label = "medium - local name resolution or supporting services may be degraded" + case containsAny(text, "ollama", "n8n", "uptime kuma"): + score += 15 + label = "medium - optional application service is degraded" + } + + if score >= 80 { + label = "critical - fix first; downstream checks may be noisy until this is healthy" + } else if score >= 60 { + label = "high - fix before lower-priority application symptoms" + } else if score >= 35 { + label = "medium - investigate after critical path checks" + } + + return reportImpact{Label: label, Score: score} +} + +func containsAny(text string, needles ...string) bool { + for _, needle := range needles { + if strings.Contains(text, needle) { + return true + } + } + return false +} + +func evidenceFromRow(row reportRow) string { + if row.Detail != "" { + return truncate(row.Detail, 140) + } + if row.Summary != "" { + return truncate(row.Summary, 140) + } + return "" +} + func orderedReportAreas(rows []reportRow) []string { seen := map[string]bool{} var areas []string diff --git a/cmd/jeannie-core/main_test.go b/cmd/jeannie-core/main_test.go index 5958c74..1f8ba39 100644 --- a/cmd/jeannie-core/main_test.go +++ b/cmd/jeannie-core/main_test.go @@ -46,6 +46,22 @@ func TestReportRenderHidesOKGraphAndQuery(t *testing.T) { } } +func TestReportRenderAddsActionableDiagnosis(t *testing.T) { + input := "fail\tEdge\tWebsite public\tHTTP 502 from https://lab2025.duckdns.org/\tHTTP 502 from edge; x-squid-error ERR_READ_ERROR\t./jeannie doctor-edge\t\t\n" + + var output bytes.Buffer + if err := runReportRender([]string{"--title", "Unit Report", "--only", "problems", "--details"}, strings.NewReader(input), &output); err != nil { + t.Fatal(err) + } + + got := output.String() + for _, want := range []string{"likely:", "mitigate:", "redesign:", "proxy reached the edge path"} { + if !strings.Contains(got, want) { + t.Fatalf("report missing %q:\n%s", want, got) + } + } +} + func TestExecuteDAGRespectsDependencies(t *testing.T) { dir := t.TempDir() first := filepath.Join(dir, "first") diff --git a/scripts/report-ui b/scripts/report-ui index 4bdd64e..05becd2 100644 --- a/scripts/report-ui +++ b/scripts/report-ui @@ -3,6 +3,7 @@ REPORT_UI_ONLY="${REPORT_UI_ONLY:-problems}" REPORT_UI_DETAILS=false REPORT_UI_JSON=false +REPORT_UI_LOCAL_RCA="${REPORT_UI_LOCAL_RCA:-true}" # shellcheck disable=SC2034 REPORT_UI_VERBOSE=false REPORT_UI_ROWS_FILE="" @@ -13,6 +14,7 @@ Report UI flags: --all Show ok, skip, warning, and failing items. --details Show the compact report plus detail fields. --json Print structured JSON. + --no-local-rca Do not ask local Ollama for the focused RCA summary. --verbose Use the older full diagnostic output when supported. EOF } @@ -36,6 +38,10 @@ report_ui_parse_args() { REPORT_UI_JSON=true shift ;; + --no-local-rca) + REPORT_UI_LOCAL_RCA=false + shift + ;; --verbose) # shellcheck disable=SC2034 REPORT_UI_VERBOSE=true @@ -154,4 +160,69 @@ report_ui_render() { fi "${REPO_ROOT}/scripts/report-render" "${args[@]}" <"${REPORT_UI_ROWS_FILE}" + + if [[ "${REPORT_UI_JSON}" != "true" ]] && truthy "${REPORT_UI_LOCAL_RCA:-true}"; then + report_ui_local_rca "${title}" + fi +} + +report_ui_local_rca() { + local title="$1" + local ollama_url="${LAB_OLLAMA_URL:-http://127.0.0.1:11434}" + local model="${LAB_DOCTOR_LOCAL_MODEL:-${LAB_OLLAMA_MODEL:-llama3.2:3b}}" + local problems + local prompt + local payload + local response + local answer + + problems="$(awk -F'\t' ' + ($1 == "fail" || $1 == "warn") { + printf "- status=%s area=%s check=%s summary=%s detail=%s fix=%s\n", $1, $2, $3, $4, $5, $6 + count++ + if (count >= 12) exit + } + ' "${REPORT_UI_ROWS_FILE}")" + if [[ -z "${problems}" ]]; then + return 0 + fi + + printf '\n== Local Model RCA ==\n' + if ! command -v curl >/dev/null 2>&1 || ! command -v jq >/dev/null 2>&1; then + printf 'skipped: curl and jq are required to ask Ollama for local RCA.\n' + printf 'fix: install curl jq, or rerun with --no-local-rca.\n' + return 0 + fi + + prompt="$(cat </dev/null || true)" + answer="$(printf '%s' "${response}" | jq -r '.response // empty' 2>/dev/null || true)" + if [[ -z "${answer}" ]]; then + printf 'skipped: Ollama did not return a local RCA from %s using model %s.\n' "${ollama_url%/}" "${model}" + printf 'fix: start Ollama or set LAB_DOCTOR_LOCAL_MODEL to an installed local model.\n' + return 0 + fi + + printf '%s\n' "${answer}" }