Page MenuHomePhabricator
Paste P96252

poller.py
ActivePublic

Authored by fnegri on Aug 25 2026, 2:54 PM.
Referenced Files
F100054653: poller.py
Aug 25 2026, 3:32 PM
F100051489: poller.py
Aug 25 2026, 2:54 PM
Subscribers
None
"""
PoC: the 'Alertmanager replacement' core of the Toolforge Alerting Service.
This was generated with Claude AI as a proof of concept, to verify how much of
alertmanager we would need to reimplement if we polled directly the Prometheus
API instead of relying on Alertmanager webhooks.
The parts of Alertmanager that this is reimplementing are:
* merging alerts from multiple prometheus instances
* repeat interval
* resolve notifications
The parts that we would still need even if we relied on Alertmanager webhooks:
* keeping track of emails sent with an in-memory structure, because if
alertmanager is restarted, it would send a bunch of duplicate webhooks
"""
import json
import time
import urllib.request
from datetime import datetime, timedelta, timezone
PROMETHEUS_URLS = [
"https://prometheus.svc.toolforge.org/tools/api/v1/alerts",
"https://prometheus.svc.toolforge.org/tools/api/v1/alerts", # 2nd replica
]
REPEAT_INTERVAL = timedelta(hours=24) # re-notification cadence for still-firing alerts
# Boot reconstruction margin: an alert that started *firing* (activeAt + its
# rule's "for:" duration, fetched from the rules API) more than this long
# before we saw it is assumed handled by a previous incarnation of this pod.
BOOT_MARGIN = timedelta(minutes=5)
RESOLVE_DEBOUNCE_POLLS = 2
ledger = {} # (tool, alertname) -> {"first_seen", "last_emailed", "labels", "annotations", "missing_polls"}
def tool_of(labels):
ns = labels.get("namespace") or labels.get("destination_service_namespace") or ""
return ns.removeprefix("tool-")
def opted_in(tool):
return tool in {"fnegri-test"} # stub: will call the tool-config endpoint (T433690)
def send_email(kind, tool, entry):
print(f"EMAIL [{kind}] to tools.{tool}@toolforge.org: "
f"{entry['labels']['alertname']} ({entry['annotations'].get('summary', '')})")
def fetch_durations():
"""alertname -> "for:" duration, from the rules API (no duplicated constants)."""
url = PROMETHEUS_URLS[0].replace("/alerts", "/rules?type=alert")
with urllib.request.urlopen(url, timeout=10) as resp:
groups = json.load(resp)["data"]["groups"]
return {r["name"]: timedelta(seconds=r.get("duration", 0))
for g in groups for r in g.get("rules", [])}
def fetch_firing():
"""Poll all replicas, union by (tool, alertname), earliest activeAt wins."""
union = {}
for url in PROMETHEUS_URLS:
with urllib.request.urlopen(url, timeout=10) as resp:
alerts = json.load(resp)["data"]["alerts"]
for a in alerts:
if a["state"] != "firing" or a["labels"].get("audience") != "tool-maintainers":
continue
key = (tool_of(a["labels"]), a["labels"]["alertname"])
active_at = datetime.fromisoformat(a["activeAt"].replace("Z", "+00:00"))
if key not in union or active_at < union[key]["active_at"]:
union[key] = {"active_at": active_at, "labels": a["labels"],
"annotations": a["annotations"]}
return union
def poll_cycle(now=None):
now = now or datetime.now(timezone.utc)
firing = fetch_firing()
durations = fetch_durations()
for (tool, alertname), alert in firing.items():
if not opted_in(tool):
continue
entry = ledger.get((tool, alertname))
if entry is None:
entry = {"first_seen": alert["active_at"], "last_emailed": None,
"labels": alert["labels"], "annotations": alert["annotations"],
"missing_polls": 0}
fired_at = alert["active_at"] + durations.get(alertname, timedelta(0))
if now - fired_at > BOOT_MARGIN: # boot reconstruction
entry["last_emailed"] = now # assume a previous incarnation notified
ledger[(tool, alertname)] = entry
entry["missing_polls"] = 0
if entry["last_emailed"] is None or now - entry["last_emailed"] > REPEAT_INTERVAL:
send_email("firing", tool, entry)
entry["last_emailed"] = now
for key, entry in list(ledger.items()):
if key not in firing:
entry["missing_polls"] += 1
if entry["missing_polls"] >= RESOLVE_DEBOUNCE_POLLS:
send_email("resolved", key[0], entry)
del ledger[key]
POLL_INTERVAL_SECONDS = 5 # in prod this can be longer (e.g. 60s)
def main():
while True:
started = time.monotonic()
try:
poll_cycle()
except Exception as e: # keep polling: one failed cycle is retried next tick
print(f"poll cycle failed: {e!r}")
time.sleep(max(0.0, POLL_INTERVAL_SECONDS - (time.monotonic() - started)))
if __name__ == "__main__":
main()