matrix-ops-bot/ops_bot/aws.py

75 lines
2.2 KiB
Python
Raw Normal View History

2022-11-30 15:52:04 +00:00
import json
import logging
2022-12-01 16:31:04 +00:00
from typing import Any, List, Tuple
from fastapi import Request
2022-11-30 15:21:09 +00:00
from ops_bot.common import COLOR_ALARM, COLOR_OK, COLOR_UNKNOWN
2022-12-01 16:31:04 +00:00
from ops_bot.config import RoutingKey
2022-11-30 15:21:09 +00:00
2022-12-01 16:31:04 +00:00
def handle_subscribe_confirm(payload: Any) -> List[Tuple[str, str]]:
2022-11-30 15:21:09 +00:00
message = payload.get("Message")
url = payload.get("SubscribeURL")
plain = f"{message}\n\n{url}"
2022-12-01 16:31:04 +00:00
return [(plain, plain)]
2022-11-30 15:21:09 +00:00
2022-12-01 16:31:04 +00:00
def handle_notification(payload: Any) -> List[Tuple[str, str]]:
2022-11-30 15:21:09 +00:00
message = payload.get("Message")
subject = payload.get("Subject")
plain = f"{subject}\n{message}"
formatted = (
f"<strong><font color={COLOR_ALARM}>{subject}</font></strong>\n<p>{message}</p>"
2022-11-30 15:21:09 +00:00
)
2022-12-01 16:31:04 +00:00
return [(plain, formatted)]
2022-11-30 15:21:09 +00:00
2022-12-01 16:31:04 +00:00
def handle_json_notification(payload: Any, body: Any) -> List[Tuple[str, str]]:
2022-11-30 15:52:04 +00:00
if "AlarmName" not in body:
msg = "Received unknown json payload type over AWS SNS"
logging.info(msg)
logging.info(payload.get("Message"))
2022-12-01 16:31:04 +00:00
return [(msg, msg)]
2022-11-30 15:52:04 +00:00
description = body.get("AlarmDescription")
subject = payload.get("Subject")
2022-11-30 16:30:29 +00:00
state_value = body.get("NewStateValue", "unknown")
2022-11-30 15:52:04 +00:00
if state_value == "ALARM":
color = COLOR_ALARM
elif state_value == "OK":
color = COLOR_OK
else:
color = COLOR_UNKNOWN
2022-11-30 16:11:09 +00:00
plain = f"{subject}"
formatted = f"<strong><font color={color}>{subject}</font></strong>\n"
if state_value == "OK":
plain += "\n(this alarm has been resolved!)"
formatted += "\n<p>(this alarm has been resolved!)</p>"
else:
plain += "\n{description}"
formatted += f"\n<p>{description}</p>"
2022-12-01 16:31:04 +00:00
return [(plain, formatted)]
2022-11-30 15:52:04 +00:00
2022-12-01 16:31:04 +00:00
async def parse_sns_event(
route: RoutingKey,
payload: Any,
request: Request,
) -> List[Tuple[str, str]]:
2022-11-30 15:21:09 +00:00
if payload.get("Type") == "SubscriptionConfirmation":
return handle_subscribe_confirm(payload)
elif payload.get("Type") == "UnsubscribeConfirmation":
return handle_subscribe_confirm(payload)
elif payload.get("Type") == "Notification":
2022-11-30 15:52:04 +00:00
try:
body = json.loads(payload.get("Message"))
return handle_json_notification(payload, body)
except Exception:
return handle_notification(payload)
2022-11-30 15:21:09 +00:00
raise Exception("Unnown SNS payload type")