diff --git a/setup.cfg b/setup.cfg index 583e008..88de4c7 100644 --- a/setup.cfg +++ b/setup.cfg @@ -12,6 +12,7 @@ packages = kassandra python_requires = >=3.9.2 package_dir = =src install_requires = + Jinja2>=3.0.2 PyYAML>=5.4.1 matrix-bot @ git+https://gitea.auro.re/histausse/matrix-bot.git diff --git a/src/kassandra/format.py b/src/kassandra/format.py index f298565..bef1adc 100644 --- a/src/kassandra/format.py +++ b/src/kassandra/format.py @@ -10,6 +10,25 @@ from typing import ( NoReturn, Optional ) +from jinja2 import Environment, BaseLoader + +template_raw = ( + "{% if alert['labels']['severity'] == 'critical' and alert['status'] == 'firing' %}" + "@room" + "{% elif alert['labels']['severity'] == 'warning' and alert['status'] == 'firing' %}" + "" + "{% elif alert['status'] == 'resolved' %}" + " End of alert " + "{% else %}" + "" + "{% endif %}" + "{{ alert['labels']['alertname'] }}: {{ alert['labels']['instance'] }}
" + "
" + "{{ alert['annotations']['title'] }}
" + "{{ alert['annotations']['description'] }}
" +) +template = Environment(loader=BaseLoader).from_string(template_raw) + @dataclasses.dataclass class Message: @@ -17,14 +36,20 @@ class Message: formated_body: Optional[str] def format_alert( - alert: dict[str, Any] -)->Message: + alert_json: dict[str, Any] +)->list[Message]: """ Format an alert in json format to a nice string. """ - body = json.dumps(alert, indent=4) - formated_body = f"
{body}
\n" - return Message(body, formated_body) + messages = [] + for alert in alert_json['alerts']: + formated_body = template.render(alert=alert, status=alert_json['status']) + body = f"{ alert['annotations']['title'] }:\n{ alert['annotations']['description'] }" + if '@room' in formated_body: + body = '@room ' + body + formated_body = formated_body.replace('@room', '') + messages.append(Message(body, formated_body)) + return messages async def format_alerts( alert_queue: asyncio.Queue[dict[str,Any]], @@ -35,7 +60,8 @@ async def format_alerts( """ while True: alert = await alert_queue.get() - message = format_alert(alert) - await message_queue.put(message) + messages = format_alert(alert) + for message in messages: + await message_queue.put(message) alert_queue.task_done()