|
|
|
@ -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<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:
|
|
|
|
@ -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"<pre><code>{body}</code></pre>\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()
|
|
|
|
|
|
|
|
|
|