2022-11-30 15:52:04 +00:00
|
|
|
import json
|
|
|
|
|
import logging
|
2022-11-30 15:21:09 +00:00
|
|
|
from typing import Any, Tuple
|
|
|
|
|
|
2022-11-30 16:05:39 +00:00
|
|
|
from ops_bot.common import COLOR_ALARM, COLOR_OK, COLOR_UNKNOWN
|
2022-11-30 15:21:09 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def handle_subscribe_confirm(payload: Any) -> Tuple[str, str]:
|
|
|
|
|
message = payload.get("Message")
|
|
|
|
|
url = payload.get("SubscribeURL")
|
|
|
|
|
plain = f"{message}\n\n{url}"
|
|
|
|
|
return plain, plain
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def handle_notification(payload: Any) -> Tuple[str, str]:
|
|
|
|
|
message = payload.get("Message")
|
|
|
|
|
subject = payload.get("Subject")
|
|
|
|
|
|
|
|
|
|
plain = f"{subject}\n{message}"
|
|
|
|
|
formatted = (
|
2022-11-30 16:05:39 +00:00
|
|
|
f"<strong><font color={COLOR_ALARM}>{subject}</font></strong>\n<p>{message}</p>"
|
2022-11-30 15:21:09 +00:00
|
|
|
)
|
|
|
|
|
return plain, formatted
|
|
|
|
|
|
|
|
|
|
|
2022-11-30 15:52:04 +00:00
|
|
|
def handle_json_notification(payload: Any, body: Any) -> Tuple[str, str]:
|
|
|
|
|
if "AlarmName" not in body:
|
|
|
|
|
msg = "Received unknown json payload type over AWS SNS"
|
|
|
|
|
logging.info(msg)
|
|
|
|
|
logging.info(payload.get("Message"))
|
|
|
|
|
return msg, msg
|
|
|
|
|
|
|
|
|
|
description = body.get("AlarmDescription")
|
|
|
|
|
subject = payload.get("Subject")
|
2022-11-30 16:05:39 +00:00
|
|
|
state_value = payload.get("NewStateValue", "unknown")
|
2022-11-30 15:52:04 +00:00
|
|
|
|
2022-11-30 16:05:39 +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-11-30 15:52:04 +00:00
|
|
|
return plain, formatted
|
|
|
|
|
|
|
|
|
|
|
2022-11-30 15:21:09 +00:00
|
|
|
def parse_sns_event(payload: Any) -> Tuple[str, str]:
|
|
|
|
|
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")
|