57 lines
1.8 KiB
Python
57 lines
1.8 KiB
Python
import logging
|
|
from typing import Any, Dict, List, Tuple
|
|
|
|
from fastapi import Request
|
|
|
|
from ops_bot.common import COLOR_ALARM, COLOR_OK, COLOR_UNKNOWN
|
|
from ops_bot.config import RoutingKey
|
|
|
|
|
|
def prometheus_alert_to_markdown(
|
|
alert_data: Dict, # type: ignore[type-arg]
|
|
) -> List[Tuple[str, str]]:
|
|
"""
|
|
Converts a prometheus alert json to markdown
|
|
"""
|
|
messages = []
|
|
known_labels = ["alertname", "instance", "job"]
|
|
for alert in alert_data["alerts"]:
|
|
title = (
|
|
alert["annotations"]["description"]
|
|
if hasattr(alert["annotations"], "description")
|
|
else alert["annotations"]["summary"]
|
|
)
|
|
severity = alert.get("severity", "critical")
|
|
if alert["status"] == "resolved":
|
|
color = COLOR_OK
|
|
elif severity == "critical":
|
|
color = COLOR_ALARM
|
|
else:
|
|
color = COLOR_UNKNOWN
|
|
|
|
status = alert["status"]
|
|
generatorURL = alert.get("generatorURL")
|
|
plain = f"{status}: {title}"
|
|
header_str = f"{status.upper()}[{status}]"
|
|
formatted = f"<strong><font color={color}>{header_str}</font></strong>: [{title}]({generatorURL})"
|
|
for label_name in known_labels:
|
|
try:
|
|
plain += "\n* **{0}**: {1}".format(
|
|
label_name.capitalize(), alert["labels"][label_name]
|
|
)
|
|
formatted += "\n* **{0}**: {1}".format(
|
|
label_name.capitalize(), alert["labels"][label_name]
|
|
)
|
|
except Exception as e:
|
|
logging.error("error parsing labels", exc_info=e)
|
|
pass
|
|
messages.append((plain, formatted))
|
|
return messages
|
|
|
|
|
|
async def parse_alertmanager_event(
|
|
route: RoutingKey,
|
|
payload: Any,
|
|
request: Request,
|
|
) -> List[Tuple[str, str]]:
|
|
return prometheus_alert_to_markdown(payload)
|