|
| 1 | +""" |
| 2 | +Slack error alerting -- best-effort, fire-and-forget notifications to the |
| 3 | +#aistudio-alerts channel. |
| 4 | +
|
| 5 | +Two alert shapes, matching exactly what the RCA agent needs to start digging |
| 6 | +in, and nothing more (no error text is sent -- the agent recovers that |
| 7 | +itself, from workload_events.message / workloads.error_message / task_logs, |
| 8 | +via the tools it already has): |
| 9 | +
|
| 10 | + 1. Workload failure -> Workload ID, Timestamp, Node IP |
| 11 | + Fired from app.worker._fail_workload() -- the single choke point every |
| 12 | + Celery task (validate_node / install_dependencies / execute_benchmark / |
| 13 | + launch_jupyter) already routes through on any failure, so one hook here |
| 14 | + covers every "error in benchmarking / starting the benchmark / etc" |
| 15 | + scenario without instrumenting each task individually. |
| 16 | +
|
| 17 | + 2. Service error -> Timestamp, Service IP |
| 18 | + Fired when the API process itself is in trouble: an unhandled exception |
| 19 | + (app.main's generic_exception_handler) or a degraded /health check |
| 20 | + (Postgres unreachable, i.e. "down, or erroring while trying to come back |
| 21 | + up"). No workload is involved here, so there's no workload ID to |
| 22 | + report -- just where the *service* is running. |
| 23 | +
|
| 24 | +Uses httpx (already a project dependency) against a Slack Incoming Webhook |
| 25 | +URL rather than the Slack SDK/bot token: an Incoming Webhook is a single |
| 26 | +POST of {"text": "..."} to a per-channel URL -- no bot token, no signing |
| 27 | +secret, no app-level OAuth needed on THIS side (that machinery only matters |
| 28 | +for the side that has to *read* Slack, which is the RCA agent, not here). |
| 29 | +
|
| 30 | +Every public function is wrapped so a Slack outage or missing/blank webhook |
| 31 | +URL can NEVER raise into the caller's real code path -- a Celery task |
| 32 | +failing to post an alert must still finish marking the workload FAILED, and |
| 33 | +a FastAPI request failing to post an alert must still return its error |
| 34 | +response to the client. |
| 35 | +""" |
| 36 | + |
| 37 | +from __future__ import annotations |
| 38 | + |
| 39 | +import logging |
| 40 | +import socket |
| 41 | +from datetime import datetime, timedelta, timezone |
| 42 | + |
| 43 | +import httpx |
| 44 | + |
| 45 | +from app.config import settings |
| 46 | + |
| 47 | +logger = logging.getLogger(__name__) |
| 48 | + |
| 49 | +_ISO_FMT = "%Y-%m-%dT%H:%M:%SZ" |
| 50 | + |
| 51 | + |
| 52 | +def _resolve_service_ip() -> str: |
| 53 | + """settings.SERVICE_HOST_IP if set, else a best-effort auto-detect. |
| 54 | +
|
| 55 | + NOTE: inside an unmodified Docker bridge network, gethostbyname(hostname()) |
| 56 | + resolves to the CONTAINER's internal IP, not a reachable host IP -- set |
| 57 | + SERVICE_HOST_IP explicitly in any deployment where that distinction matters |
| 58 | + (which is effectively every real deployment). |
| 59 | + """ |
| 60 | + if settings.SERVICE_HOST_IP: |
| 61 | + return settings.SERVICE_HOST_IP |
| 62 | + try: |
| 63 | + return socket.gethostbyname(socket.gethostname()) |
| 64 | + except OSError: |
| 65 | + return "unknown" |
| 66 | + |
| 67 | + |
| 68 | +def _fmt_ts(ts: datetime) -> str: |
| 69 | + return ts.astimezone(timezone.utc).strftime(_ISO_FMT) |
| 70 | + |
| 71 | + |
| 72 | +def _workload_failure_text(workload_id: str, node_ip: str | None, occurred_at: datetime) -> str: |
| 73 | + return ( |
| 74 | + "🚨 *Workload Failed*\n" |
| 75 | + f"Workload: `{workload_id}`\n" |
| 76 | + f"Time: `{_fmt_ts(occurred_at)}`\n" |
| 77 | + f"Node: `{node_ip or 'unknown'}`" |
| 78 | + ) |
| 79 | + |
| 80 | + |
| 81 | +def _service_error_text(occurred_at: datetime, service_ip: str) -> str: |
| 82 | + return ( |
| 83 | + "🔴 *aistudio-server error*\n" |
| 84 | + f"Time: `{_fmt_ts(occurred_at)}`\n" |
| 85 | + f"Service: `{service_ip}`" |
| 86 | + ) |
| 87 | + |
| 88 | + |
| 89 | +def _send_sync(text: str) -> None: |
| 90 | + """Post from a synchronous context (the Celery worker).""" |
| 91 | + if not settings.SLACK_ALERT_WEBHOOK_URL: |
| 92 | + return # alerting disabled -- no-op, not an error |
| 93 | + try: |
| 94 | + resp = httpx.post(settings.SLACK_ALERT_WEBHOOK_URL, json={"text": text}, timeout=5.0) |
| 95 | + resp.raise_for_status() |
| 96 | + except Exception as exc: # noqa: BLE001 -- alerting must never break the caller |
| 97 | + logger.warning("slack_notifier: failed to post alert: %s", exc) |
| 98 | + |
| 99 | + |
| 100 | +async def _send_async(text: str) -> None: |
| 101 | + """Post from an async context (FastAPI request handlers).""" |
| 102 | + if not settings.SLACK_ALERT_WEBHOOK_URL: |
| 103 | + return |
| 104 | + try: |
| 105 | + async with httpx.AsyncClient(timeout=5.0) as client: |
| 106 | + resp = await client.post(settings.SLACK_ALERT_WEBHOOK_URL, json={"text": text}) |
| 107 | + resp.raise_for_status() |
| 108 | + except Exception as exc: # noqa: BLE001 |
| 109 | + logger.warning("slack_notifier: failed to post alert: %s", exc) |
| 110 | + |
| 111 | + |
| 112 | +def notify_workload_failure( |
| 113 | + workload_id: str, |
| 114 | + node_ip: str | None, |
| 115 | + occurred_at: datetime | None = None, |
| 116 | +) -> None: |
| 117 | + """Fire a workload-failure alert. Call from a SYNCHRONOUS context (Celery tasks). |
| 118 | +
|
| 119 | + Args: |
| 120 | + workload_id: The human-readable workload id (e.g. 'wl-20260806-oom01'). |
| 121 | + node_ip: The GPU node the workload was running on, if known. |
| 122 | + occurred_at: When the failure was detected. Defaults to now() -- pass |
| 123 | + an explicit value if the caller already captured a more precise |
| 124 | + moment (e.g. right when the exception was caught). |
| 125 | + """ |
| 126 | + occurred_at = occurred_at or datetime.now(timezone.utc) |
| 127 | + _send_sync(_workload_failure_text(workload_id, node_ip, occurred_at)) |
| 128 | + |
| 129 | + |
| 130 | +# Service-level alert cooldown -- per-process only (see |
| 131 | +# SLACK_SERVICE_ALERT_COOLDOWN_SECONDS' docstring in config.py for why). |
| 132 | +_last_service_alert_at: datetime | None = None |
| 133 | + |
| 134 | + |
| 135 | +def _service_cooldown_active(now: datetime) -> bool: |
| 136 | + global _last_service_alert_at |
| 137 | + cooldown = timedelta(seconds=settings.SLACK_SERVICE_ALERT_COOLDOWN_SECONDS) |
| 138 | + if _last_service_alert_at is not None and (now - _last_service_alert_at) < cooldown: |
| 139 | + return True |
| 140 | + _last_service_alert_at = now |
| 141 | + return False |
| 142 | + |
| 143 | + |
| 144 | +async def notify_service_error(occurred_at: datetime | None = None) -> None: |
| 145 | + """Fire a service-level alert. Call from an ASYNC context (FastAPI). |
| 146 | +
|
| 147 | + Rate-limited by SLACK_SERVICE_ALERT_COOLDOWN_SECONDS so a Postgres outage |
| 148 | + being polled by /health every few seconds doesn't flood the channel with |
| 149 | + one alert per poll. |
| 150 | + """ |
| 151 | + now = occurred_at or datetime.now(timezone.utc) |
| 152 | + if _service_cooldown_active(now): |
| 153 | + return |
| 154 | + await _send_async(_service_error_text(now, _resolve_service_ip())) |
0 commit comments