You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
1.9 KiB
Python
68 lines
1.9 KiB
Python
"""
|
|
Format the alert message.
|
|
"""
|
|
|
|
import asyncio
|
|
import dataclasses
|
|
import json
|
|
from typing import (
|
|
Any,
|
|
NoReturn,
|
|
Optional
|
|
)
|
|
from jinja2 import Environment, BaseLoader
|
|
|
|
template_raw = (
|
|
"{% if alert['labels']['severity'] == 'critical' and alert['status'] == 'firing' %}"
|
|
"@room<b><font color='red'>"
|
|
"{% elif alert['labels']['severity'] == 'warning' and alert['status'] == 'firing' %}"
|
|
"<b><font color='orange'>"
|
|
"{% elif alert['status'] == 'resolved' %}"
|
|
"<b><font color='green'> End of alert "
|
|
"{% else %}"
|
|
"<b><font>"
|
|
"{% endif %}"
|
|
"{{ alert['labels']['alertname'] }}: {{ alert['labels']['instance'] }} <br/>"
|
|
"</font></b>"
|
|
"{{ alert['annotations']['title'] }}<br/>"
|
|
"{{ alert['annotations']['description'] }}<br/>"
|
|
)
|
|
template = Environment(loader=BaseLoader).from_string(template_raw)
|
|
|
|
|
|
@dataclasses.dataclass
|
|
class Message:
|
|
body: str
|
|
formated_body: Optional[str]
|
|
|
|
def format_alert(
|
|
alert_json: dict[str, Any]
|
|
)->list[Message]:
|
|
"""
|
|
Format an alert in json format to a nice string.
|
|
"""
|
|
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]],
|
|
message_queue: asyncio.Queue[Message]
|
|
)->NoReturn:
|
|
"""
|
|
Read alerts from alert_queue, format them, and put them in message_queue.
|
|
"""
|
|
while True:
|
|
alert = await alert_queue.get()
|
|
messages = format_alert(alert)
|
|
for message in messages:
|
|
await message_queue.put(message)
|
|
alert_queue.task_done()
|
|
|