2016-03-13 15:28:44 +01:00
|
|
|
# Webhooks for external integrations.
|
2019-02-02 23:53:55 +01:00
|
|
|
from typing import Any, Dict, Iterable
|
2017-11-16 00:43:10 +01:00
|
|
|
|
|
|
|
from django.http import HttpRequest, HttpResponse
|
|
|
|
|
2020-08-20 00:32:15 +02:00
|
|
|
from zerver.decorator import webhook_view
|
2020-08-19 22:26:38 +02:00
|
|
|
from zerver.lib.exceptions import UnsupportedWebhookEventType
|
2017-10-31 04:25:48 +01:00
|
|
|
from zerver.lib.request import REQ, has_request_variables
|
2017-11-16 00:43:10 +01:00
|
|
|
from zerver.lib.response import json_success
|
2020-08-19 22:14:40 +02:00
|
|
|
from zerver.lib.webhooks.common import check_send_webhook_message
|
2019-02-02 23:53:55 +01:00
|
|
|
from zerver.models import UserProfile
|
2016-06-06 00:33:59 +02:00
|
|
|
|
2016-03-13 15:28:44 +01:00
|
|
|
PAGER_DUTY_EVENT_NAMES = {
|
|
|
|
'incident.trigger': 'triggered',
|
|
|
|
'incident.acknowledge': 'acknowledged',
|
|
|
|
'incident.unacknowledge': 'unacknowledged',
|
|
|
|
'incident.resolve': 'resolved',
|
|
|
|
'incident.assign': 'assigned',
|
|
|
|
'incident.escalate': 'escalated',
|
|
|
|
'incident.delegate': 'delineated',
|
|
|
|
}
|
|
|
|
|
2019-01-12 23:26:27 +01:00
|
|
|
PAGER_DUTY_EVENT_NAMES_V2 = {
|
|
|
|
'incident.trigger': 'triggered',
|
|
|
|
'incident.acknowledge': 'acknowledged',
|
|
|
|
'incident.resolve': 'resolved',
|
|
|
|
'incident.assign': 'assigned',
|
|
|
|
}
|
|
|
|
|
2019-01-13 00:41:51 +01:00
|
|
|
ASSIGNEE_TEMPLATE = '[{username}]({url})'
|
|
|
|
|
|
|
|
INCIDENT_WITH_SERVICE_AND_ASSIGNEE = (
|
|
|
|
'Incident [{incident_num}]({incident_url}) {action} by [{service_name}]'
|
2019-04-17 21:45:51 +02:00
|
|
|
'({service_url}) (assigned to {assignee_info}):\n\n``` quote\n{trigger_message}\n```'
|
2019-01-13 00:41:51 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
INCIDENT_WITH_ASSIGNEE = """
|
2019-04-17 21:45:51 +02:00
|
|
|
Incident [{incident_num}]({incident_url}) {action} by {assignee_info}:
|
2019-01-13 00:41:51 +01:00
|
|
|
|
|
|
|
``` quote
|
|
|
|
{trigger_message}
|
|
|
|
```
|
|
|
|
""".strip()
|
|
|
|
|
|
|
|
INCIDENT_ASSIGNED = """
|
2019-04-17 21:45:51 +02:00
|
|
|
Incident [{incident_num}]({incident_url}) {action} to {assignee_info}:
|
2019-01-13 00:41:51 +01:00
|
|
|
|
|
|
|
``` quote
|
|
|
|
{trigger_message}
|
|
|
|
```
|
|
|
|
""".strip()
|
|
|
|
|
|
|
|
INCIDENT_RESOLVED_WITH_AGENT = """
|
2019-04-17 21:45:51 +02:00
|
|
|
Incident [{incident_num}]({incident_url}) resolved by {resolving_agent_info}:
|
2016-03-13 15:28:44 +01:00
|
|
|
|
2019-01-13 00:41:51 +01:00
|
|
|
``` quote
|
|
|
|
{trigger_message}
|
|
|
|
```
|
|
|
|
""".strip()
|
|
|
|
|
|
|
|
INCIDENT_RESOLVED = """
|
2019-04-17 21:45:51 +02:00
|
|
|
Incident [{incident_num}]({incident_url}) resolved:
|
2019-01-13 00:41:51 +01:00
|
|
|
|
|
|
|
``` quote
|
|
|
|
{trigger_message}
|
|
|
|
```
|
|
|
|
""".strip()
|
|
|
|
|
|
|
|
def build_pagerduty_formatdict(message: Dict[str, Any]) -> Dict[str, Any]:
|
python: Convert assignment type annotations to Python 3.6 style.
This commit was split by tabbott; this piece covers the vast majority
of files in Zulip, but excludes scripts/, tools/, and puppet/ to help
ensure we at least show the right error messages for Xenial systems.
We can likely further refine the remaining pieces with some testing.
Generated by com2ann, with whitespace fixes and various manual fixes
for runtime issues:
- invoiced_through: Optional[LicenseLedger] = models.ForeignKey(
+ invoiced_through: Optional["LicenseLedger"] = models.ForeignKey(
-_apns_client: Optional[APNsClient] = None
+_apns_client: Optional["APNsClient"] = None
- notifications_stream: Optional[Stream] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
- signup_notifications_stream: Optional[Stream] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
+ notifications_stream: Optional["Stream"] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
+ signup_notifications_stream: Optional["Stream"] = models.ForeignKey('Stream', related_name='+', null=True, blank=True, on_delete=CASCADE)
- author: Optional[UserProfile] = models.ForeignKey('UserProfile', blank=True, null=True, on_delete=CASCADE)
+ author: Optional["UserProfile"] = models.ForeignKey('UserProfile', blank=True, null=True, on_delete=CASCADE)
- bot_owner: Optional[UserProfile] = models.ForeignKey('self', null=True, on_delete=models.SET_NULL)
+ bot_owner: Optional["UserProfile"] = models.ForeignKey('self', null=True, on_delete=models.SET_NULL)
- default_sending_stream: Optional[Stream] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
- default_events_register_stream: Optional[Stream] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
+ default_sending_stream: Optional["Stream"] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
+ default_events_register_stream: Optional["Stream"] = models.ForeignKey('zerver.Stream', null=True, related_name='+', on_delete=CASCADE)
-descriptors_by_handler_id: Dict[int, ClientDescriptor] = {}
+descriptors_by_handler_id: Dict[int, "ClientDescriptor"] = {}
-worker_classes: Dict[str, Type[QueueProcessingWorker]] = {}
-queues: Dict[str, Dict[str, Type[QueueProcessingWorker]]] = {}
+worker_classes: Dict[str, Type["QueueProcessingWorker"]] = {}
+queues: Dict[str, Dict[str, Type["QueueProcessingWorker"]]] = {}
-AUTH_LDAP_REVERSE_EMAIL_SEARCH: Optional[LDAPSearch] = None
+AUTH_LDAP_REVERSE_EMAIL_SEARCH: Optional["LDAPSearch"] = None
Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
2020-04-22 01:09:50 +02:00
|
|
|
format_dict: Dict[str, Any] = {}
|
2016-03-13 15:28:44 +01:00
|
|
|
format_dict['action'] = PAGER_DUTY_EVENT_NAMES[message['type']]
|
|
|
|
|
|
|
|
format_dict['incident_id'] = message['data']['incident']['id']
|
|
|
|
format_dict['incident_num'] = message['data']['incident']['incident_number']
|
|
|
|
format_dict['incident_url'] = message['data']['incident']['html_url']
|
|
|
|
|
|
|
|
format_dict['service_name'] = message['data']['incident']['service']['name']
|
|
|
|
format_dict['service_url'] = message['data']['incident']['service']['html_url']
|
|
|
|
|
|
|
|
if message['data']['incident'].get('assigned_to_user', None):
|
2017-11-05 02:48:25 +01:00
|
|
|
assigned_to_user = message['data']['incident']['assigned_to_user']
|
2019-01-13 00:41:51 +01:00
|
|
|
format_dict['assignee_info'] = ASSIGNEE_TEMPLATE.format(
|
|
|
|
username=assigned_to_user['email'].split('@')[0],
|
|
|
|
url=assigned_to_user['html_url'],
|
|
|
|
)
|
2016-03-13 15:28:44 +01:00
|
|
|
else:
|
2019-01-13 00:41:51 +01:00
|
|
|
format_dict['assignee_info'] = 'nobody'
|
2016-03-13 15:28:44 +01:00
|
|
|
|
|
|
|
if message['data']['incident'].get('resolved_by_user', None):
|
2017-11-05 02:48:25 +01:00
|
|
|
resolved_by_user = message['data']['incident']['resolved_by_user']
|
2019-01-13 00:41:51 +01:00
|
|
|
format_dict['resolving_agent_info'] = ASSIGNEE_TEMPLATE.format(
|
|
|
|
username=resolved_by_user['email'].split('@')[0],
|
|
|
|
url=resolved_by_user['html_url'],
|
|
|
|
)
|
2016-03-13 15:28:44 +01:00
|
|
|
|
|
|
|
trigger_message = []
|
2019-02-22 00:30:33 +01:00
|
|
|
trigger_summary_data = message['data']['incident']['trigger_summary_data']
|
|
|
|
if trigger_summary_data is not None:
|
|
|
|
trigger_subject = trigger_summary_data.get('subject', '')
|
|
|
|
if trigger_subject:
|
|
|
|
trigger_message.append(trigger_subject)
|
|
|
|
|
|
|
|
trigger_description = trigger_summary_data.get('description', '')
|
|
|
|
if trigger_description:
|
|
|
|
trigger_message.append(trigger_description)
|
|
|
|
|
2020-04-09 21:51:58 +02:00
|
|
|
format_dict['trigger_message'] = '\n'.join(trigger_message)
|
2016-03-13 15:28:44 +01:00
|
|
|
return format_dict
|
|
|
|
|
2019-01-12 23:26:27 +01:00
|
|
|
def build_pagerduty_formatdict_v2(message: Dict[str, Any]) -> Dict[str, Any]:
|
|
|
|
format_dict = {}
|
|
|
|
format_dict['action'] = PAGER_DUTY_EVENT_NAMES_V2[message['event']]
|
|
|
|
|
|
|
|
format_dict['incident_id'] = message['incident']['id']
|
|
|
|
format_dict['incident_num'] = message['incident']['incident_number']
|
|
|
|
format_dict['incident_url'] = message['incident']['html_url']
|
|
|
|
|
|
|
|
format_dict['service_name'] = message['incident']['service']['name']
|
|
|
|
format_dict['service_url'] = message['incident']['service']['html_url']
|
|
|
|
|
|
|
|
assignments = message['incident']['assignments']
|
|
|
|
if assignments:
|
|
|
|
assignee = assignments[0]['assignee']
|
2019-01-13 00:41:51 +01:00
|
|
|
format_dict['assignee_info'] = ASSIGNEE_TEMPLATE.format(
|
|
|
|
username=assignee['summary'], url=assignee['html_url'])
|
2019-01-12 23:26:27 +01:00
|
|
|
else:
|
2019-01-13 00:41:51 +01:00
|
|
|
format_dict['assignee_info'] = 'nobody'
|
2019-01-12 23:26:27 +01:00
|
|
|
|
|
|
|
last_status_change_by = message['incident'].get('last_status_change_by')
|
|
|
|
if last_status_change_by is not None:
|
2019-01-13 00:41:51 +01:00
|
|
|
format_dict['resolving_agent_info'] = ASSIGNEE_TEMPLATE.format(
|
|
|
|
username=last_status_change_by['summary'],
|
|
|
|
url=last_status_change_by['html_url'],
|
|
|
|
)
|
2019-01-12 23:26:27 +01:00
|
|
|
|
|
|
|
trigger_description = message['incident'].get('description')
|
|
|
|
if trigger_description is not None:
|
|
|
|
format_dict['trigger_message'] = trigger_description
|
|
|
|
return format_dict
|
2016-03-13 15:28:44 +01:00
|
|
|
|
2018-03-16 22:53:50 +01:00
|
|
|
def send_formated_pagerduty(request: HttpRequest,
|
|
|
|
user_profile: UserProfile,
|
2018-05-10 19:34:01 +02:00
|
|
|
message_type: str,
|
2018-03-16 22:53:50 +01:00
|
|
|
format_dict: Dict[str, Any]) -> None:
|
2016-03-13 15:28:44 +01:00
|
|
|
if message_type in ('incident.trigger', 'incident.unacknowledge'):
|
2019-01-13 00:41:51 +01:00
|
|
|
template = INCIDENT_WITH_SERVICE_AND_ASSIGNEE
|
|
|
|
elif message_type == 'incident.resolve' and format_dict.get('resolving_agent_info') is not None:
|
|
|
|
template = INCIDENT_RESOLVED_WITH_AGENT
|
|
|
|
elif message_type == 'incident.resolve' and format_dict.get('resolving_agent_info') is None:
|
|
|
|
template = INCIDENT_RESOLVED
|
2019-01-12 23:26:27 +01:00
|
|
|
elif message_type == 'incident.assign':
|
2019-01-13 00:41:51 +01:00
|
|
|
template = INCIDENT_ASSIGNED
|
2016-03-13 15:28:44 +01:00
|
|
|
else:
|
2019-01-13 00:41:51 +01:00
|
|
|
template = INCIDENT_WITH_ASSIGNEE
|
2016-03-13 15:28:44 +01:00
|
|
|
|
2020-04-09 21:51:58 +02:00
|
|
|
subject = 'Incident {incident_num}'.format(**format_dict)
|
2016-03-13 15:28:44 +01:00
|
|
|
body = template.format(**format_dict)
|
2018-03-16 22:53:50 +01:00
|
|
|
check_send_webhook_message(request, user_profile, subject, body)
|
2016-03-13 15:28:44 +01:00
|
|
|
|
2020-08-20 00:32:15 +02:00
|
|
|
@webhook_view('PagerDuty')
|
2016-03-13 15:28:44 +01:00
|
|
|
@has_request_variables
|
2018-03-16 22:53:50 +01:00
|
|
|
def api_pagerduty_webhook(
|
|
|
|
request: HttpRequest, user_profile: UserProfile,
|
|
|
|
payload: Dict[str, Iterable[Dict[str, Any]]]=REQ(argument_type='body'),
|
|
|
|
) -> HttpResponse:
|
2016-03-13 15:28:44 +01:00
|
|
|
for message in payload['messages']:
|
2019-01-12 23:26:27 +01:00
|
|
|
message_type = message.get('type')
|
|
|
|
|
|
|
|
# If the message has no "type" key, then this payload came from a
|
|
|
|
# Pagerduty Webhook V2.
|
|
|
|
if message_type is None:
|
2019-01-13 00:41:51 +01:00
|
|
|
break
|
2016-03-13 15:28:44 +01:00
|
|
|
|
|
|
|
if message_type not in PAGER_DUTY_EVENT_NAMES:
|
2020-08-20 00:50:06 +02:00
|
|
|
raise UnsupportedWebhookEventType(message_type)
|
2019-01-13 00:55:04 +01:00
|
|
|
|
|
|
|
format_dict = build_pagerduty_formatdict(message)
|
|
|
|
send_formated_pagerduty(request, user_profile, message_type, format_dict)
|
2016-03-13 15:28:44 +01:00
|
|
|
|
2019-01-12 23:26:27 +01:00
|
|
|
for message in payload['messages']:
|
|
|
|
event = message.get('event')
|
|
|
|
|
|
|
|
# If the message has no "event" key, then this payload came from a
|
|
|
|
# Pagerduty Webhook V1.
|
|
|
|
if event is None:
|
2019-01-13 00:41:51 +01:00
|
|
|
break
|
2019-01-12 23:26:27 +01:00
|
|
|
|
|
|
|
if event not in PAGER_DUTY_EVENT_NAMES_V2:
|
2020-08-20 00:50:06 +02:00
|
|
|
raise UnsupportedWebhookEventType(event)
|
2019-01-12 23:26:27 +01:00
|
|
|
|
|
|
|
format_dict = build_pagerduty_formatdict_v2(message)
|
|
|
|
send_formated_pagerduty(request, user_profile, event, format_dict)
|
|
|
|
|
2016-03-13 15:28:44 +01:00
|
|
|
return json_success()
|