my-homelab-configs/scripts/report-ui

402 lines
14 KiB
Bash

#!/usr/bin/env bash
REPORT_UI_ONLY="${REPORT_UI_ONLY:-problems}"
REPORT_UI_DETAILS=false
REPORT_UI_JSON=false
REPORT_UI_LOCAL_RCA="${REPORT_UI_LOCAL_RCA:-false}"
# shellcheck disable=SC2034
REPORT_UI_VERBOSE=false
REPORT_UI_ROWS_FILE=""
REPORT_UI_WORK_DIR=""
REPORT_UI_FAILURES=0
report_ui_usage_flags() {
cat <<'EOF'
Report UI flags:
--all Show ok, informational, skip, warning, and failing items.
--details Show the compact report plus detail fields.
--json Print structured JSON.
--ai Ask the local AI gateway for an unverified explanation.
--no-local-rca Disable the AI explanation, including when enabled by environment.
--verbose Use the older full diagnostic output when supported.
EOF
}
report_ui_parse_args() {
REPORT_UI_ONLY="${REPORT_UI_ONLY:-problems}"
REPORT_UI_DETAILS=false
REPORT_UI_JSON=false
REPORT_UI_VERBOSE=false
while (($# > 0)); do
case "$1" in
--all)
REPORT_UI_ONLY="all"
shift
;;
--details)
REPORT_UI_DETAILS=true
shift
;;
--json)
REPORT_UI_JSON=true
shift
;;
--ai)
REPORT_UI_LOCAL_RCA=true
shift
;;
--no-local-rca)
REPORT_UI_LOCAL_RCA=false
shift
;;
--verbose)
# shellcheck disable=SC2034
REPORT_UI_VERBOSE=true
shift
;;
-h|--help)
report_ui_usage_flags
return 2
;;
*)
echo "unknown report option: $1" >&2
return 1
;;
esac
done
}
report_ui_begin() {
REPORT_UI_ROWS_FILE="$(mktemp "${TMPDIR:-/tmp}/jeannie-report-rows.XXXXXX")"
REPORT_UI_WORK_DIR="$(mktemp -d "${TMPDIR:-/tmp}/jeannie-report-work.XXXXXX")"
REPORT_UI_FAILURES=0
REPORT_UI_JOB_COUNT=0
REPORT_UI_JOB_WAITED=0
REPORT_UI_JOB_PIDS=()
REPORT_UI_STARTED_SECONDS=${SECONDS}
export REPORT_UI_WORK_DIR
}
report_ui_cleanup() {
if [[ -n "${REPORT_UI_ROWS_FILE:-}" && -f "${REPORT_UI_ROWS_FILE}" ]]; then
rm -f "${REPORT_UI_ROWS_FILE}"
fi
if [[ -n "${REPORT_UI_WORK_DIR:-}" && -d "${REPORT_UI_WORK_DIR}" ]]; then
rm -rf "${REPORT_UI_WORK_DIR}"
fi
REPORT_UI_ROWS_FILE=""
REPORT_UI_WORK_DIR=""
}
# Reuse only explicitly read-only probes, within this report. The lock avoids
# duplicate network checks when independent jobs request the same probe.
report_ui_cached_probe() {
if [[ -z "${REPORT_UI_WORK_DIR:-}" ]] || ! command -v flock >/dev/null 2>&1; then
"$@"
return $?
fi
local key lock_fd rc
key="$(printf '%s\0' "$@" | sha256sum | awk '{print $1}')"
exec {lock_fd}>"${REPORT_UI_WORK_DIR}/${key}.lock"
flock -x "${lock_fd}"
if [[ ! -f "${REPORT_UI_WORK_DIR}/${key}.status" ]]; then
rc=0
"$@" >"${REPORT_UI_WORK_DIR}/${key}.output" 2>&1 || rc=$?
printf '%s\n' "${rc}" >"${REPORT_UI_WORK_DIR}/${key}.status"
fi
cat "${REPORT_UI_WORK_DIR}/${key}.output"
rc="$(cat "${REPORT_UI_WORK_DIR}/${key}.status")"
flock -u "${lock_fd}"
exec {lock_fd}>&-
return "${rc}"
}
report_ui_enqueue() {
local limit="${LAB_REPORT_PARALLELISM:-4}" slot
[[ "${limit}" =~ ^[1-9][0-9]*$ ]] || limit=4
((limit <= 8)) || limit=8
while ((REPORT_UI_JOB_COUNT - REPORT_UI_JOB_WAITED >= limit)); do
wait "${REPORT_UI_JOB_PIDS[REPORT_UI_JOB_WAITED]}" || true
REPORT_UI_JOB_WAITED=$((REPORT_UI_JOB_WAITED + 1))
done
slot="$(printf '%06d' "${REPORT_UI_JOB_COUNT}")"
(
REPORT_UI_ROWS_FILE="${REPORT_UI_WORK_DIR}/row-${slot}"
: >"${REPORT_UI_ROWS_FILE}"
rc=0
"$@" || rc=$?
printf '%s\n' "${rc}" >"${REPORT_UI_WORK_DIR}/result-${slot}"
) &
REPORT_UI_JOB_PIDS+=("$!")
REPORT_UI_JOB_COUNT=$((REPORT_UI_JOB_COUNT + 1))
}
report_ui_finish() {
local index slot rc
for ((index=REPORT_UI_JOB_WAITED; index<REPORT_UI_JOB_COUNT; index++)); do
wait "${REPORT_UI_JOB_PIDS[index]}" || true
done
for ((index=0; index<REPORT_UI_JOB_COUNT; index++)); do
slot="$(printf '%06d' "${index}")"
if [[ ! -f "${REPORT_UI_WORK_DIR}/result-${slot}" ]]; then
report_ui_emit fail "Diagnostics" "Probe execution" "A report probe did not complete" "slot=${slot}"
REPORT_UI_FAILURES=$((REPORT_UI_FAILURES + 1))
continue
fi
cat "${REPORT_UI_WORK_DIR}/row-${slot}" >>"${REPORT_UI_ROWS_FILE}"
rc="$(cat "${REPORT_UI_WORK_DIR}/result-${slot}")"
((rc == 0)) || REPORT_UI_FAILURES=$((REPORT_UI_FAILURES + 1))
done
REPORT_UI_JOB_COUNT=0
REPORT_UI_JOB_WAITED=0
REPORT_UI_JOB_PIDS=()
if [[ "${LAB_REPORT_TIMING:-false}" == true ]]; then
printf 'Read-only report probes completed in %ss.\n' "$((SECONDS - REPORT_UI_STARTED_SECONDS))" >&2
fi
}
report_ui_one_line() {
local value="${1:-}"
value="${value//$'\t'/ }"
value="${value//$'\r'/ }"
value="${value//$'\n'/ | }"
printf '%s' "${value}"
}
report_ui_first_line() {
awk 'NF && $0 !~ /^\+/ { print; exit }'
}
report_ui_trim_detail() {
sed -n '1,20p'
}
report_ui_emit() {
local status="$1"
local area="$2"
local check="$3"
local summary="$4"
local detail="${5:-}"
local fix="${6:-}"
local graph="${7:-}"
local query="${8:-}"
if [[ -z "${REPORT_UI_ROWS_FILE:-}" ]]; then
echo "report_ui_begin was not called" >&2
return 1
fi
printf '%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \
"$(report_ui_one_line "${status}")" \
"$(report_ui_one_line "${area}")" \
"$(report_ui_one_line "${check}")" \
"$(report_ui_one_line "${summary}")" \
"$(report_ui_one_line "${detail}")" \
"$(report_ui_one_line "${fix}")" \
"$(report_ui_one_line "${graph}")" \
"$(report_ui_one_line "${query}")" >>"${REPORT_UI_ROWS_FILE}"
}
report_ui_check() {
if [[ "${REPORT_UI_PARALLEL:-false}" == true ]]; then
report_ui_enqueue report_ui_check_sync "$@"
else
report_ui_check_sync "$@"
fi
}
report_ui_check_sync() {
local severity="$1"
local area="$2"
local check="$3"
local fix="${4:-}"
local graph="${5:-}"
local query="${6:-}"
shift 6
local output
local status
local summary
local detail
set +e
case "${1:-}" in
status_container_running|status_http_ok|status_gitea_public_ok)
output="$(report_ui_cached_probe "$@" 2>&1)" ;;
*) output="$("$@" 2>&1)" ;;
esac
status=$?
set -e
if [[ "${status}" -eq 0 ]]; then
report_ui_emit ok "${area}" "${check}" "ok" "${output}"
return 0
fi
summary="$(printf '%s\n' "${output}" | report_ui_first_line)"
if [[ -z "${summary}" ]]; then
summary="check exited with status ${status}"
fi
detail="$(printf '%s\n' "${output}" | report_ui_trim_detail)"
if [[ "${severity}" == "fail" ]]; then
report_ui_emit fail "${area}" "${check}" "${summary}" "${detail}" "${fix}" "${graph}" "${query}"
return 1
fi
report_ui_emit warn "${area}" "${check}" "${summary}" "${detail}" "${fix}" "${graph}" "${query}"
return 0
}
report_ui_render() {
local title="$1"
local -a args=(--title "${title}" --only "${REPORT_UI_ONLY}")
if [[ "${REPORT_UI_DETAILS}" == "true" ]]; then
args+=(--details)
fi
if [[ "${REPORT_UI_JSON}" == "true" ]]; then
args+=(--json)
fi
"${REPO_ROOT}/scripts/report-render" "${args[@]}" <"${REPORT_UI_ROWS_FILE}"
if [[ "${REPORT_UI_JSON}" != "true" ]] && truthy "${REPORT_UI_LOCAL_RCA:-false}"; then
report_ui_local_rca "${title}"
fi
}
report_ui_local_rca() {
local title="$1"
local routes_file="${LAB_AI_STACK_MODEL_ROUTES_FILE:-/data/homelab-ai-stack/models.env}"
local provider="${LAB_DOCTOR_RCA_PROVIDER:-${LAB_AI_GATEWAY_PROVIDER:-}}"
local ollama_url="${LAB_OLLAMA_URL:-http://127.0.0.1:11434}"
local omniroute_url="${LAB_AI_GATEWAY_URL:-http://127.0.0.1:20128/v1}"
local omniroute_key="${LAB_AI_GATEWAY_API_KEY:-${OMNIROUTE_API_KEY:-${HERMES_OMNIROUTE_API_KEY:-sk_omniroute}}}"
local model
local problems
local prompt
local payload
local response
local answer
local error_message
local tags_response
local curl_status
local http_status
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
if [[ -s "${routes_file}" ]]; then
# shellcheck disable=SC1090
. "${routes_file}"
fi
if [[ -z "${provider}" ]]; then
if [[ -n "${AI_STACK_AGENT_SMART_MODEL:-}" ]]; then
provider="omniroute"
else
provider="ollama"
fi
fi
model="${LAB_DOCTOR_LOCAL_MODEL:-${LAB_AI_GATEWAY_MODEL:-${AI_STACK_AGENT_SMART_MODEL:-${LAB_OLLAMA_MODEL:-llama3.2:3b}}}}"
printf '\n== AI hypothesis (unverified) ==\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 the AI gateway for RCA.\n'
printf 'fix: install curl jq, or rerun with --no-local-rca.\n'
return 0
fi
prompt="$(cat <<EOF
You are Jeannie, a local homelab SRE assistant. Use only the evidence below.
Active cluster profile: ${LAB_CLUSTER_PROFILE:-unknown}; runtime: ${LAB_CLUSTER_RUNTIME:-unknown}. Debian hosts external services; OCI edge proxies public traffic; RPi provides DNS/support services.
Task:
1. Pick the single highest-impact issue to focus first.
2. Describe only evidence-supported causes; state when the cause is unknown. Give evidence, immediate mitigation, and long-term redesign. Never claim a past log proves a service is currently broken. Never invent service topology or commands.
3. Return exactly four bullets: Focus, Root cause, Mitigation, Redesign.
4. For Kubernetes pod/node issues, prefer read-only Holmes triage before mutation.
5. Keep it concise and practical. Do not invent commands not implied by the fix field.
Report title: ${title}
Problems:
${problems}
EOF
)"
case "${provider,,}" in
omniroute | openai)
http_status="$(curl -sS -o /dev/null -w '%{http_code}' --connect-timeout 2 --max-time 5 "${omniroute_url%/}/models" 2>/dev/null || true)"
if [[ "${http_status}" != "200" && "${http_status}" != "401" ]]; then
printf 'skipped: OmniRoute is not reachable at %s; deterministic focus above is still valid.\n' "${omniroute_url%/}"
return 0
fi
payload="$(jq -n \
--arg model "${model}" \
--arg prompt "${prompt}" \
'{model: $model, messages: [{role: "user", content: $prompt}], stream: false, temperature: 0.1}')"
set +e
response="$(curl -sS --connect-timeout 2 --max-time "${LAB_DOCTOR_LOCAL_RCA_TIMEOUT_SECONDS:-90}" \
-H "Authorization: Bearer ${omniroute_key}" \
-H 'Content-Type: application/json' \
-d "${payload}" \
"${omniroute_url%/}/chat/completions" 2>/dev/null)"
curl_status=$?
set -e
answer="$(printf '%s' "${response}" | jq -r '.choices[0].message.content // empty' 2>/dev/null || true)"
error_message="$(printf '%s' "${response}" | jq -r '.error.message // empty' 2>/dev/null || true)"
if [[ -z "${answer}" ]]; then
if [[ "${curl_status}" -eq 28 ]]; then
printf 'skipped: OmniRoute model %s timed out after %ss; deterministic focus above is still valid.\n' "${model}" "${LAB_DOCTOR_LOCAL_RCA_TIMEOUT_SECONDS:-90}"
elif [[ -n "${error_message}" ]]; then
printf 'skipped: OmniRoute returned no RCA using model %s: %s\n' "${model}" "${error_message}"
else
printf 'skipped: OmniRoute returned no RCA using model %s; deterministic focus above is still valid.\n' "${model}"
fi
return 0
fi
;;
*)
tags_response="$(curl -fsS --connect-timeout 2 --max-time 5 "${ollama_url%/}/api/tags" 2>/dev/null || true)"
if [[ -z "${tags_response}" ]]; then
printf 'skipped: Ollama is not reachable at %s; deterministic focus above is still valid.\n' "${ollama_url%/}"
return 0
fi
if ! printf '%s' "${tags_response}" | jq -e --arg model "${model}" '.models[]?.name == $model' >/dev/null 2>&1; then
printf 'skipped: model %s is not installed in Ollama; deterministic focus above is still valid.\n' "${model}"
printf 'hint: set LAB_DOCTOR_LOCAL_MODEL to one from `ollama list`, or pull %s.\n' "${model}"
return 0
fi
payload="$(jq -n \
--arg model "${model}" \
--arg prompt "${prompt}" \
'{model: $model, prompt: $prompt, stream: false, options: {temperature: 0.1}}')"
set +e
response="$(curl -fsS --connect-timeout 2 --max-time "${LAB_DOCTOR_LOCAL_RCA_TIMEOUT_SECONDS:-90}" \
-H 'Content-Type: application/json' \
-d "${payload}" \
"${ollama_url%/}/api/generate" 2>/dev/null)"
curl_status=$?
set -e
answer="$(printf '%s' "${response}" | jq -r '.response // empty' 2>/dev/null || true)"
if [[ -z "${answer}" ]]; then
if [[ "${curl_status}" -eq 28 ]]; then
printf 'skipped: model %s timed out after %ss; deterministic focus above is still valid.\n' "${model}" "${LAB_DOCTOR_LOCAL_RCA_TIMEOUT_SECONDS:-90}"
printf 'hint: use LAB_DOCTOR_LOCAL_MODEL=qwen2.5:0.5b or increase LAB_DOCTOR_LOCAL_RCA_TIMEOUT_SECONDS.\n'
else
printf 'skipped: Ollama returned no RCA using model %s; deterministic focus above is still valid.\n' "${model}"
fi
return 0
fi
;;
esac
printf '%s\n' "${answer}"
}