Files
FabledSteward/steward/core/notifications.py
T
bvandeusenandClaude Opus 5.5 c368e93e2c
CI / lint (push) Successful in 2s
CI / unit (push) Failing after 1m14s
CI / integration (push) Successful in 1m14s
CI / publish (push) Skipped
feat(alerts): silence is alertable — agent offline and no-data (#5062)
Agent offline is an ordinary rule now. The host_agent scheduler records
host_agent/<host>/seconds_since_seen every minute (from last_seen_at, or
registration time for an agent that never reported), replacing the task
that only logged stale agents. The catalog offers the metric, and picking
it on a new rule fills "> 180".

No data: each rule's state tracks its last sample and its usual gap,
smoothed so that an outage counts as at most three gaps. A core task,
alert_silence_check, runs every 60s and marks a rule no_data_since once its
series has had no sample for three usual gaps (at least 5 minutes; an hour
while the cadence is unknown). A never-sampled rule counts from when it
started watching. The mark sits beside the state, so a firing alert that
goes silent stays firing. Each silence records one event and sends one
notification (rule option notify_no_data, default on; muted in maintenance
windows). The next sample clears it with a "data resumed" event and
notification. Creating, changing, disabling or re-enabling a rule restarts
its watch.

Migration 0029 adds the columns and seeds each existing rule's last sample
and gap from its last day of data, so an upgrade does not flag every rule.

Shown on the Alerts page (a NO DATA badge with its start time), in MCP
list_alerts, list_alert_rules and get_host (state "no_data", no_data_since),
in get_overview findings (alert_no_data, or a firing alert marked silent)
and in the weekly report. The rule form has the notify option, and its
metric reference now matches what traefik records and lists host_agent.
Emails say "no data" and carry the event's note.

The metric-catalog guard also reads positional MetricBatch.add arguments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 13:06:54 -04:00

103 lines
3.3 KiB
Python

from __future__ import annotations
import asyncio
import json
import logging
import smtplib
import ssl
import types
from email.message import EmailMessage
import httpx
from jinja2 import Template
logger = logging.getLogger(__name__)
async def dispatch_notifications(
smtp_cfg: dict,
webhook_cfg: dict,
alert_data: dict,
) -> dict:
"""Dispatch all configured notification channels. Returns results dict."""
results = {}
if smtp_cfg.get("host") and smtp_cfg.get("recipients"):
results["email"] = await _send_email(smtp_cfg, alert_data)
if webhook_cfg.get("url"):
results["webhook"] = await _send_webhook(webhook_cfg, alert_data)
return results
async def _send_email(cfg: dict, alert: dict) -> dict:
try:
msg = EmailMessage()
msg["Subject"] = f"[Steward] {alert['state']} — {alert['rule_name']}"
msg["From"] = cfg.get("username", "steward@localhost")
msg["To"] = ", ".join(cfg["recipients"])
value = "no data" if alert.get("value") is None else alert["value"]
msg.set_content(
f"Alert: {alert['state']}\n"
f"Rule: {alert['rule_name']}\n"
f"Resource: {alert['resource']}\n"
f"Metric: {alert['metric']} = {value}\n"
f"Threshold: {alert['threshold']}\n"
+ (f"Note: {alert['note']}\n" if alert.get("note") else "")
+ f"Time: {alert['timestamp']}\n"
)
loop = asyncio.get_running_loop()
await loop.run_in_executor(None, _smtp_send_sync, cfg, msg)
return {"sent": True, "error": None}
except Exception as exc:
logger.error(f"Email notification failed: {exc}")
return {"sent": False, "error": str(exc)}
def _smtp_send_sync(cfg: dict, msg: EmailMessage) -> None:
ctx = ssl.create_default_context() if cfg.get("tls", True) else None
with smtplib.SMTP(cfg["host"], cfg.get("port", 587)) as smtp:
if ctx:
smtp.starttls(context=ctx)
if cfg.get("username"):
smtp.login(cfg["username"], cfg.get("password", ""))
smtp.send_message(msg)
async def _send_webhook(cfg: dict, alert: dict) -> dict:
template_str = cfg.get(
"template",
'{"content": "{{ alert.state }} — {{ alert.rule_name }}"}',
)
# Render Jinja2 template with alert as a namespace object (attribute access)
try:
alert_ns = types.SimpleNamespace(**alert)
rendered = Template(template_str).render(alert=alert_ns)
except Exception as exc:
error = f"Template render failed: {exc}"
logger.error(error)
return {"sent": False, "error": error}
# Validate JSON before sending
try:
json.loads(rendered)
except json.JSONDecodeError as exc:
error = f"Rendered webhook template is not valid JSON: {exc}"
logger.error(error)
return {"sent": False, "error": error}
try:
async with httpx.AsyncClient(timeout=10) as client:
response = await client.post(
cfg["url"],
content=rendered,
headers={"Content-Type": "application/json"},
)
response.raise_for_status()
return {"sent": True, "error": None}
except Exception as exc:
error = str(exc)
logger.error(f"Webhook notification failed: {error}")
return {"sent": False, "error": error}