Compare commits

...

3 Commits

@ -7,4 +7,22 @@ host: 127.0.0.1
alert_rooms:
- "#troy:matrix.org"
- "#ithaca:matrix.org"
templates:
"Test": |
{% 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/>
But this is a custom template for Cassandre, so, here is a warning:<br/>
<blockquote>Beware of greeks bearing gifts</blockquote>
...

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

@ -21,7 +21,8 @@ async def __main():
)
format_corout = format_alerts(
alert_queue,
message_queue
message_queue,
config
)
webhook_corout = run_webhook(
alert_queue,

@ -21,6 +21,8 @@ class Config:
tls_crt: Optional[str] = None
tls_key: Optional[str] = None
ca_crt: Optional[str] = None
default_template: Optional[str] = None
templates: dict[str, str] = dataclasses.field(default_factory=dict)
def check_integrity(self)->bool:
""" Check the integrity of the config.

@ -5,37 +5,102 @@ Format the alert message.
import asyncio
import dataclasses
import json
from collections import defaultdict
from typing import (
Any,
NoReturn,
Optional
)
from jinja2 import BaseLoader, Environment, Template
from .config import Config
@dataclasses.dataclass
class Message:
body: str
formated_body: Optional[str]
DEFAULT_TEMPLATE_RAW: str = (
"{% 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/>"
)
def load_templates(
config: Config
)->defaultdict[str, Template]:
"""
Create a dict mapping alert names to the template to use from
the config, with a default template either from the config file
or the default DEFAULT_TEMPLATE_RAW.
"""
if config.default_template is None:
default_template = Environment(
loader=BaseLoader
).from_string(
DEFAULT_TEMPLATE_RAW
)
else:
default_template = Environment(
loader=BaseLoader
).from_string(
config.default_template
)
templates = defaultdict(lambda: default_template)
for alert_name in config.templates:
templates[alert_name] = Environment(
loader=BaseLoader
).from_string(
config.templates[alert_name]
)
return templates
def format_alert(
alert: dict[str, Any]
)->Message:
alert_json: dict[str, Any],
templates: defaultdict[str, Template]
)->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']:
template = templates[alert['labels']['alertname']]
formated_body = template.render(alert=alert)
body = "alert {status}:\n{alertname} on {instance}".format(
status=alert['status'],
alertname=alert['labels']['alertname'],
instance=alert['labels']['instance']
)
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]
message_queue: asyncio.Queue[Message],
config: Config
)->NoReturn:
"""
Read alerts from alert_queue, format them, and put them in message_queue.
"""
templates = load_templates(config)
while True:
alert = await alert_queue.get()
message = format_alert(alert)
await message_queue.put(message)
messages = format_alert(alert, templates)
for message in messages:
await message_queue.put(message)
alert_queue.task_done()

Loading…
Cancel
Save