ariadne/ariadne/services/hermes_autotriage_repair.py
codex b2fcad4116 refactor(hermes-triage): repair the fixture in-process, not via a spawned Job
The repair action no longer creates a Kubernetes Job and polls it. Ariadne
patches the fixture ConfigMap directly through its own k8s client, which
removes roughly 40 seconds of pod scheduling from the loop, drops the two
failure modes that Job introduced (volume attach and node selection), and
turns an opaque pod log into an Ariadne event.

- execute_repair returns {action, target, succeeded, error} and issues one
  merge patch; no Job, no polling, no injectable clock, never raises
- the patch writes the same terminal value every time, so idempotency needs
  no duplicate guard; one action per incident is still enforced upstream
- orchestrator records {repair, target}; the state machine, rebuild trigger
  and failure path are unchanged
- retires the unused repair-image setting

Ariadne's service account now needs get+patch on that one ConfigMap by name
instead of Job create; the batch/jobs grant and the hermes-demo-repair
service account can be retired.

480 pass in the hermes suite.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-05 22:29:57 -03:00

155 lines
5.9 KiB
Python

"""Remediation executors for the Hermes auto-triage demo incident flow.
The fixture repair is an in-process Ariadne action, not a Kubernetes Job: it
merge-patches the demo fixture ConfigMap back to healthy over the cluster API
using Ariadne's own service account, which needs get/patch on that one
ConfigMap. Because the patch always writes the same terminal value, the
repair is naturally idempotent and needs no duplicate guard of its own; the
one-action-per-incident budget upstream (the prior-action-count check in the
authorization chain) remains the only limit on how often it runs.
"""
from __future__ import annotations
from typing import Any
import httpx
from ..k8s.client import patch_json
from ..utils.logging import get_logger
logger = get_logger(__name__)
HTTP_CREATED = 201
_REPAIR_ACTION = "configmap_patch"
_PARAMETERIZED_ENDPOINT = "buildWithParameters"
_PLAIN_ENDPOINT = "build"
_BUILD_PARAMETERS = {"SEED_FAILURE": "false"}
def execute_repair(cfg: dict, incident_id: str, build_number: int) -> dict[str, Any]:
"""Patch the demo fixture ConfigMap back to healthy in one API call.
Inputs: `cfg` with namespace and fixture_configmap, the incident id used
for the log line, and the failed build number (kept for the executor
signature; the patch is the same whatever built). Outputs: {"action",
"target", "succeeded", "error"}. No Job, no polling: a non-2xx response,
a transport error, or an incomplete target returns succeeded False with a
short reason. Never raises.
"""
namespace = str(cfg.get("namespace") or "").strip()
name = str(cfg.get("fixture_configmap") or "").strip()
target = f"{namespace}/{name}"
if not namespace or not name:
return _repair_result(target, False, "fixture target incomplete", incident_id)
try:
patch_json(f"/api/v1/namespaces/{namespace}/configmaps/{name}", {"data": {"state": "healthy"}})
except Exception as exc:
return _repair_result(target, False, _patch_error(exc), incident_id)
return _repair_result(target, True, None, incident_id)
def trigger_rebuild(config: Any, job: str) -> dict[str, Any]:
"""Trigger a Jenkins rebuild of `job` with the failure seed disabled.
Inputs: a settings-like object exposing jenkins_base_url,
jenkins_api_user, jenkins_api_token, and jenkins_api_timeout_sec, plus
the Jenkins job name. Outputs: {"requested", "error"}; only an HTTP 201
from buildWithParameters counts as success. Never raises.
"""
return _post_build(config, job, _PARAMETERIZED_ENDPOINT, dict(_BUILD_PARAMETERS), "rebuild")
def retry_build(config: Any, job: str, parameterized: bool) -> dict[str, Any]:
"""Re-run a Jenkins job that failed for a transient infrastructure reason.
Inputs: a settings-like object exposing jenkins_base_url,
jenkins_api_user, jenkins_api_token, and jenkins_api_timeout_sec; the
Jenkins job name; and whether that job declares build parameters.
Outputs: {"requested", "error"}; parameterized jobs are retried through
buildWithParameters with the demo failure seed disabled, every other job
through the plain build endpoint because posting parameters to an
unparameterized job is an error. Only an HTTP 201 counts as success.
Never raises.
"""
if parameterized:
return _post_build(config, job, _PARAMETERIZED_ENDPOINT, dict(_BUILD_PARAMETERS), "retry")
return _post_build(config, job, _PLAIN_ENDPOINT, None, "retry")
def _post_build(
config: Any, job: str, endpoint: str, data: dict[str, str] | None, label: str
) -> dict[str, Any]:
"""Post one Jenkins build trigger and map the response to a result dict."""
base_url = str(getattr(config, "jenkins_base_url", "") or "").strip().rstrip("/")
if not base_url:
return {"requested": False, "error": "jenkins base url is empty"}
try:
with httpx.Client(**_jenkins_client_kwargs(config)) as client:
response = client.post(f"{base_url}/job/{job}/{endpoint}", data=data)
except Exception as exc:
return {"requested": False, "error": f"{label} request failed: {exc}"}
if response.status_code == HTTP_CREATED:
return {"requested": True, "error": None}
return {"requested": False, "error": f"{label} http {response.status_code}"}
def _repair_result(target: str, succeeded: bool, error: str | None, incident_id: str) -> dict[str, Any]:
"""Log one repair outcome line and return the executor's result dict."""
logger.info(
"hermes demo fixture repair",
extra={
"event": "hermes_autotriage_repair",
"status": "ok" if succeeded else "error",
"target": target,
"incident_id": incident_id,
},
)
return {"action": _REPAIR_ACTION, "target": target, "succeeded": succeeded, "error": error}
def _patch_error(exc: Exception) -> str:
"""Render a short reason for a failed ConfigMap patch."""
code = _status_code(exc)
if code is not None:
return f"configmap patch http {code}"
return f"configmap patch failed: {exc}"
def _jenkins_client_kwargs(config: Any) -> dict[str, Any]:
"""Build httpx client kwargs from a settings-like Jenkins credential."""
kwargs: dict[str, Any] = {
"timeout": _number(getattr(config, "jenkins_api_timeout_sec", None), 10.0),
"follow_redirects": True,
}
username = str(getattr(config, "jenkins_api_user", "") or "").strip()
token = str(getattr(config, "jenkins_api_token", "") or "").strip()
if username and token:
kwargs["auth"] = (username, token)
return kwargs
def _status_code(exc: Exception) -> int | None:
"""Extract an HTTP status code from an httpx error, when present."""
code = getattr(getattr(exc, "response", None), "status_code", None)
return code if isinstance(code, int) else None
def _number(value: Any, default: float) -> float:
"""Coerce a value to float, falling back to the default."""
try:
return float(value)
except (TypeError, ValueError):
return default