|
| 1 | +# Copyright (c) 2026 LINE Corporation |
| 2 | +# These sources are released under the terms of the MIT license: see LICENSE |
| 3 | + |
| 4 | +""" |
| 5 | +Simple integration with PagerDuty Events V2 API. |
| 6 | +
|
| 7 | +Accepts alert json from Alert Manager and then POSTs individual alerts to PagerDuty. |
| 8 | +""" |
| 9 | + |
| 10 | +import logging |
| 11 | + |
| 12 | +from django import forms |
| 13 | + |
| 14 | +from promgen import settings, util, validators |
| 15 | +from promgen.notification import NotificationBase |
| 16 | +from promgen.shortcuts import resolve_domain |
| 17 | + |
| 18 | +logger = logging.getLogger(__name__) |
| 19 | + |
| 20 | + |
| 21 | +def _choices(): |
| 22 | + if not getattr(settings, "PAGERDUTY_URLS", None): |
| 23 | + yield "PagerDuty", "PagerDuty" |
| 24 | + else: |
| 25 | + for k, v in settings.PAGERDUTY_URLS.items(): |
| 26 | + yield (k, k) |
| 27 | + |
| 28 | + |
| 29 | +class FormPagerDuty(forms.Form): |
| 30 | + domain = forms.ChoiceField( |
| 31 | + required=True, |
| 32 | + label="PagerDuty Domain", |
| 33 | + choices=_choices(), |
| 34 | + ) |
| 35 | + integration_key = forms.CharField( |
| 36 | + required=True, |
| 37 | + label="Integration Key", |
| 38 | + help_text="The Integration Key (a.k.a. Routing Key) provided by PagerDuty.", |
| 39 | + validators=[validators.integration_key], |
| 40 | + widget=forms.PasswordInput(), |
| 41 | + ) |
| 42 | + alias = forms.CharField( |
| 43 | + label="Alias", |
| 44 | + help_text="Description for identifying this PagerDuty integration.", |
| 45 | + required=True, |
| 46 | + ) |
| 47 | + |
| 48 | + def clean(self): |
| 49 | + cleaned_data = super().clean() |
| 50 | + # The Sender model expects a single 'value' field. Therefore, we create it by combining |
| 51 | + # the domain and integration_key into a single string separated by a colon. |
| 52 | + cleaned_data["value"] = str.format( |
| 53 | + "{}:{}", cleaned_data.get("domain"), cleaned_data.get("integration_key") |
| 54 | + ) |
| 55 | + return cleaned_data |
| 56 | + |
| 57 | + |
| 58 | +class NotificationPagerDuty(NotificationBase): |
| 59 | + """ |
| 60 | + Trigger an alert event to PagerDuty. |
| 61 | + """ |
| 62 | + |
| 63 | + form = FormPagerDuty |
| 64 | + |
| 65 | + def _send(self, target, data): |
| 66 | + domain = target.split(":")[0] |
| 67 | + integration_key = target.split(":")[1] |
| 68 | + |
| 69 | + request_body = NotificationPagerDuty.build_request_body(data, integration_key) |
| 70 | + |
| 71 | + # Send event to PagerDuty Events V2 API |
| 72 | + # By default we send to the global endpoint unless overridden |
| 73 | + url = "https://events.pagerduty.com/v2/enqueue" |
| 74 | + if getattr(settings, "PAGERDUTY_URLS", None): |
| 75 | + url = settings.PAGERDUTY_URLS.get(domain) |
| 76 | + |
| 77 | + util.post(url, json=request_body).raise_for_status() |
| 78 | + |
| 79 | + @staticmethod |
| 80 | + def json_to_string(data): |
| 81 | + return "".join(f"\n - {k} = {v}" for k, v in data.items()) |
| 82 | + |
| 83 | + @staticmethod |
| 84 | + def build_request_body(data, integration_key): |
| 85 | + # Initialize request body |
| 86 | + request_body = { |
| 87 | + "routing_key": integration_key, |
| 88 | + "client": "Promgen", |
| 89 | + "client_url": resolve_domain("home"), |
| 90 | + } |
| 91 | + |
| 92 | + # Set event action |
| 93 | + if data["status"] == "resolved": |
| 94 | + request_body["event_action"] = "resolve" |
| 95 | + else: |
| 96 | + request_body["event_action"] = "trigger" |
| 97 | + |
| 98 | + # Set dedup key |
| 99 | + # We added "Promgen/" prefix to avoid collision with other systems |
| 100 | + request_body["dedup_key"] = str.format("Promgen/{}", util.fingerprint(data)) |
| 101 | + |
| 102 | + # If we are triggering an alert, set extra fields, otherwise just send the resolve event |
| 103 | + if request_body["event_action"] == "resolve": |
| 104 | + return request_body |
| 105 | + |
| 106 | + # Set link to Promgen alert |
| 107 | + if "externalURL" in data: |
| 108 | + request_body["links"] = [ |
| 109 | + { |
| 110 | + "href": data["externalURL"], |
| 111 | + "text": "View alert in Promgen", |
| 112 | + } |
| 113 | + ] |
| 114 | + |
| 115 | + # Initialize payload |
| 116 | + request_body.setdefault("payload", {}) |
| 117 | + request_body["payload"]["source"] = "Promgen" |
| 118 | + |
| 119 | + # Set severity |
| 120 | + PAGERDUTY_ACCEPTED_SEVERITIES = {"info", "warning", "error", "critical"} |
| 121 | + severity = data["commonLabels"].get("severity") |
| 122 | + if severity in PAGERDUTY_ACCEPTED_SEVERITIES: |
| 123 | + request_body["payload"]["severity"] = severity |
| 124 | + elif severity and severity in settings.PAGERDUTY_SEVERITY_MAP: |
| 125 | + request_body["payload"]["severity"] = settings.PAGERDUTY_SEVERITY_MAP[severity] |
| 126 | + else: |
| 127 | + request_body["payload"]["severity"] = "error" |
| 128 | + |
| 129 | + # Set summary with a max length of 1024 characters |
| 130 | + # https://developer.pagerduty.com/docs/ZG9jOjExMDI5NTgx-send-an-alert-event |
| 131 | + if "summary" in data["commonAnnotations"]: |
| 132 | + request_body["payload"]["summary"] = data["commonAnnotations"]["summary"][:1024] |
| 133 | + else: |
| 134 | + request_body["payload"]["summary"] = data["commonLabels"]["alertname"][:1024] |
| 135 | + |
| 136 | + # Set custom details |
| 137 | + custom_details = {} |
| 138 | + custom_details["firing"] = "Labels:{}\nAnnotations:{} \n".format( |
| 139 | + NotificationPagerDuty.json_to_string(data["commonLabels"]), |
| 140 | + NotificationPagerDuty.json_to_string(data["commonAnnotations"]), |
| 141 | + ) |
| 142 | + request_body["payload"]["custom_details"] = custom_details |
| 143 | + |
| 144 | + return request_body |
0 commit comments