From abe4f418b7f7069dba451359fcb7ee005ed6aa71 Mon Sep 17 00:00:00 2001 From: Luc Didry Date: Tue, 28 Nov 2023 16:10:29 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20=E2=80=94=20Implement=20gotify=20al?= =?UTF-8?q?erts.=20Fix=20#16?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- argos/schemas/config.py | 6 +++++ argos/server/alerting.py | 51 +++++++++++++++++++++++++++++++++++++++- 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/argos/schemas/config.py b/argos/schemas/config.py index e7a7825..a28b771 100644 --- a/argos/schemas/config.py +++ b/argos/schemas/config.py @@ -102,11 +102,17 @@ class Alert(BaseModel): unknown: List[str] +class GotifyUrl(BaseModel): + url: HttpUrl + tokens: List[str] + + class General(BaseModel): """Frequency for the checks and alerts""" frequency: int alerts: Alert + gotify: Optional[List[GotifyUrl]] = None @field_validator("frequency", mode="before") def parse_frequency(cls, value): diff --git a/argos/server/alerting.py b/argos/server/alerting.py index 5f5821a..30ac3ba 100644 --- a/argos/server/alerting.py +++ b/argos/server/alerting.py @@ -1,9 +1,58 @@ +from typing import List + +from argos.checks.base import Severity from argos.logging import logger +from argos.schemas.config import Config, GotifyUrl + +import httpx +from urllib.parse import urlparse # XXX Implement mail alerts https://framagit.org/framasoft/framaspace/argos/-/issues/15 # XXX Implement gotify alerts https://framagit.org/framasoft/framaspace/argos/-/issues/16 -def handle_alert(config, result, task, severity): +def handle_alert(config: Config, result, task, severity): """Dispatch alert through configured alert channels""" msg = f"task={task.id}, status={result.status}, {severity=}" logger.error("Alerting stub: %s", msg) + + if config.general.gotify is not None: + logger.debug('Will send gotify notification') + + subject = f"{urlparse(task.url).netloc}: status {severity}" + msg = f"""\ +URL: {task.url} +Check: {task.check} +Status: {severity} +Time: {result.submitted_at} +""" + + priority = 9 + if severity == Severity.OK: + priority = 1 + elif severity == Severity.WARNING: + priority = 5 + + notify_with_gotify(subject, msg, priority, config.general.gotify) + + +def notify_with_gotify(subject: str, msg: str, priority: int, config: List[GotifyUrl]) -> None: + headers = {'accept': 'application/json', + 'content-type': 'application/json'} + + payload = {'title': subject, + 'message': msg, + 'priority': priority} + + for url in config: + logger.debug('Sending gotify message(s) to %s', url) + for token in url.tokens: + try: + res = httpx.post(f"{url.url}message", + params={'token': token}, + headers=headers, + json=payload) + res.raise_for_status() + except httpx.RequestError as exc: + logger.error('An error occurred while sending a message to %s with token %s', + exc.request.url, + token)