— Implement gotify alerts. Fix #16

This commit is contained in:
Luc Didry 2023-11-28 16:10:29 +01:00
parent bb39e53845
commit abe4f418b7
No known key found for this signature in database
GPG key ID: EA868E12D0257E3C
2 changed files with 56 additions and 1 deletions

View file

@ -102,11 +102,17 @@ class Alert(BaseModel):
unknown: List[str] unknown: List[str]
class GotifyUrl(BaseModel):
url: HttpUrl
tokens: List[str]
class General(BaseModel): class General(BaseModel):
"""Frequency for the checks and alerts""" """Frequency for the checks and alerts"""
frequency: int frequency: int
alerts: Alert alerts: Alert
gotify: Optional[List[GotifyUrl]] = None
@field_validator("frequency", mode="before") @field_validator("frequency", mode="before")
def parse_frequency(cls, value): def parse_frequency(cls, value):

View file

@ -1,9 +1,58 @@
from typing import List
from argos.checks.base import Severity
from argos.logging import logger 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 mail alerts https://framagit.org/framasoft/framaspace/argos/-/issues/15
# XXX Implement gotify alerts https://framagit.org/framasoft/framaspace/argos/-/issues/16 # 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""" """Dispatch alert through configured alert channels"""
msg = f"task={task.id}, status={result.status}, {severity=}" msg = f"task={task.id}, status={result.status}, {severity=}"
logger.error("Alerting stub: %s", msg) 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)