|
| 1 | +import json |
| 2 | +import logging |
| 3 | +import requests |
| 4 | +import socket |
| 5 | +from django.conf import settings |
| 6 | +from django.http import HttpResponseForbidden |
| 7 | +from django.http import JsonResponse |
| 8 | +from django.views.decorators.csrf import csrf_exempt |
| 9 | + |
| 10 | +logger = logging.getLogger(__name__) |
| 11 | + |
| 12 | + |
| 13 | +# todo: refactor this |
| 14 | + |
| 15 | + |
| 16 | +def allow_alertmanager_only(view_func): |
| 17 | + def _wrapped_view(request, *args, **kwargs): |
| 18 | + alertmanager_ip = socket.gethostbyname("alertmanager") |
| 19 | + |
| 20 | + client_ip = request.META["REMOTE_ADDR"] |
| 21 | + print("abcd", client_ip, alertmanager_ip) |
| 22 | + if client_ip == alertmanager_ip: |
| 23 | + return view_func(request, *args, **kwargs) |
| 24 | + |
| 25 | + return HttpResponseForbidden("Forbidden") |
| 26 | + |
| 27 | + return _wrapped_view |
| 28 | + |
| 29 | + |
| 30 | +@csrf_exempt |
| 31 | +@allow_alertmanager_only |
| 32 | +def alert_webhook(request): |
| 33 | + if request.method == "POST": |
| 34 | + try: |
| 35 | + payload = json.loads(request.body) |
| 36 | + for alert in payload["alerts"]: |
| 37 | + message = f"Alert: {alert['annotations']['summary']} - {alert['status']}" |
| 38 | + send_telegram_message(message) |
| 39 | + |
| 40 | + return JsonResponse({"status": "success"}) |
| 41 | + except Exception as exc: |
| 42 | + logger.error(f"Failed to process alert {exc}", exc_info=exc) |
| 43 | + return JsonResponse({"status": "error"}, status=400) |
| 44 | + |
| 45 | + return JsonResponse({"status": "method not allowed"}, status=400) |
| 46 | + |
| 47 | + |
| 48 | +def send_telegram_message(message): |
| 49 | + url = ( |
| 50 | + f"https://api.telegram.org/bot{settings.ALERTMANAGER_TELEGRAM_TOKEN}/sendMessage" |
| 51 | + ) |
| 52 | + data = {"chat_id": settings.ALERTMANAGER_TELEGRAM_CHAT_ID, "text": message} |
| 53 | + response = requests.post(url, data=data) |
| 54 | + return response.json() |
0 commit comments