add formating

This commit is contained in:
histausse 2021-10-08 15:17:45 +02:00
parent 42760490b9
commit d2f202c72c
Signed by: histausse
GPG key ID: 67486F107F62E9E9
2 changed files with 34 additions and 7 deletions

View file

@ -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

View file

@ -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)
messages = format_alert(alert)
for message in messages:
await message_queue.put(message)
alert_queue.task_done()