Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
webhooks: Update NewRelic webhook for new format.
Max Zawisaf05a04e0008a
diff --git a/zerver/webhooks/newrelic/fixtures/alert.txt b/zerver/webhooks/newrelic/fixtures/alert.txtdeleted file mode 100644index 92d899dfa1d..00000000000--- a/zerver/webhooks/newrelic/fixtures/alert.txt+++ /dev/null@@ -1 +0,0 @@-alert=%7B%22created_at%22%3A%222013-07-23T20%3A14%3A15%2B00%3A00%22%2C%22application_name%22%3A%22Application%20name%22%2C%22account_name%22%3A%22Account%20name%22%2C%22severity%22%3A%22critical%22%2C%22message%22%3A%22Apdex%20score%20fell%20below%20critical%20level%20of%200.90%22%2C%22short_description%22%3A%22%5Bapplication%20name%5D%20alert%20opened%22%2C%22long_description%22%3A%22Alert%20opened%20on%20%5Bapplication%20name%5D%3A%20Apdex%20score%20fell%20below%20critical%20level%20of%200.90%22%2C%22alert_url%22%3A%22https%3A%2F%2Frpm.newrelc.com%2Faccounts%2F%5Baccount_id%5D%2Fapplications%2F%5Bapplication_id%5D%2Fincidents%2F%5Bincident_id%5D%22%7Ddiff --git a/zerver/webhooks/newrelic/fixtures/deployment.txt b/zerver/webhooks/newrelic/fixtures/deployment.txtdeleted file mode 100644index dceb7fc9f02..00000000000--- a/zerver/webhooks/newrelic/fixtures/deployment.txt+++ /dev/null@@ -1 +0,0 @@-deployment=%7B%22created_at%22%3A%222013-07-23T20%3A14%3A25Z%22%2C%22deployed_by%22%3A%22Zulip%20Test%22%2C%22revision%22%3A%221242%22%2C%22description%22%3A%22Description%20sent%20via%20curl%22%2C%22application_name%22%3A%22Test%20App%22%2C%22account_name%22%3A%22Zulip%20Test%22%2C%22changelog%22%3A%22Changelog%20string%22%2C%22deployment_url%22%3A%22https%3A%2F%2Frpm.newrelic.com%2Faccounts%2F382116%2Fapplications%2F2135922%2Fdeployments%2F679885%22%7Ddiff --git a/zerver/webhooks/newrelic/fixtures/incident_acknowledged.json b/zerver/webhooks/newrelic/fixtures/incident_acknowledged.jsonnew file mode 100644index 00000000000..d8d93a39105--- /dev/null+++ b/zerver/webhooks/newrelic/fixtures/incident_acknowledged.json@@ -0,0 +1,11 @@+{+ "incident_acknowledge_url": "https://alerts.newrelic.com/accounts/2941966/incidents/1234/acknowledge",+ "duration": 5,+ "incident_id": 1234,+ "details": "Violation description test.",+ "policy_name": "Test policy name",+ "condition_name": "Server Down",+ "timestamp": 1605133931151,+ "current_state": "acknowledged",+ "incident_url": "https://alerts.newrelic.com/accounts/2941966/incidents/1234"+}diff --git a/zerver/webhooks/newrelic/fixtures/incident_closed.json b/zerver/webhooks/newrelic/fixtures/incident_closed.jsonnew file mode 100644index 00000000000..56ec7095296--- /dev/null+++ b/zerver/webhooks/newrelic/fixtures/incident_closed.json@@ -0,0 +1,11 @@+{+ "incident_acknowledge_url": "https://alerts.newrelic.com/accounts/2941966/incidents/1234/acknowledge",+ "duration": 5,+ "incident_id": 1234,+ "details": "Violation description test.",+ "policy_name": "Test policy name",+ "condition_name": "Server Down",+ "timestamp": 1605133931151,+ "current_state": "closed",+ "incident_url": "https://alerts.newrelic.com/accounts/2941966/incidents/1234"+}diff --git a/zerver/webhooks/newrelic/fixtures/incident_default_fields.json b/zerver/webhooks/newrelic/fixtures/incident_default_fields.jsonnew file mode 100644index 00000000000..a8460403532--- /dev/null+++ b/zerver/webhooks/newrelic/fixtures/incident_default_fields.json@@ -0,0 +1,5 @@+{+ "duration": 5,+ "timestamp": 1605133931151,+ "current_state": "open"+}diff --git a/zerver/webhooks/newrelic/fixtures/incident_malformatted_time.json b/zerver/webhooks/newrelic/fixtures/incident_malformatted_time.jsonnew file mode 100644index 00000000000..eaedbceae60--- /dev/null+++ b/zerver/webhooks/newrelic/fixtures/incident_malformatted_time.json@@ -0,0 +1,11 @@+{+ "incident_acknowledge_url": "https://alerts.newrelic.com/accounts/2941966/incidents/1234/acknowledge",+ "duration": 5,+ "incident_id": 1234,+ "details": "Violation description test.",+ "policy_name": "Test policy name",+ "condition_name": "Server Down",+ "timestamp": "1969-12-31 23:59:55",+ "current_state": "open",+ "incident_url": "https://alerts.newrelic.com/accounts/2941966/incidents/1234"+}diff --git a/zerver/webhooks/newrelic/fixtures/incident_missing_current_state.json b/zerver/webhooks/newrelic/fixtures/incident_missing_current_state.jsonnew file mode 100644index 00000000000..9b3b9088f6b--- /dev/null+++ b/zerver/webhooks/newrelic/fixtures/incident_missing_current_state.json@@ -0,0 +1,10 @@+{+ "incident_acknowledge_url": "https://alerts.newrelic.com/accounts/2941966/incidents/1234/acknowledge",+ "duration": 5,+ "incident_id": 1234,+ "details": "Violation description test.",+ "policy_name": "Test policy name",+ "condition_name": "Server Down",+ "timestamp": 1605133931151,+ "incident_url": "https://alerts.newrelic.com/accounts/2941966/incidents/1234"+}diff --git a/zerver/webhooks/newrelic/fixtures/incident_missing_duration.json b/zerver/webhooks/newrelic/fixtures/incident_missing_duration.jsonnew file mode 100644index 00000000000..c9e32b7be6c--- /dev/null+++ b/zerver/webhooks/newrelic/fixtures/incident_missing_duration.json@@ -0,0 +1,10 @@+{+ "incident_acknowledge_url": "https://alerts.newrelic.com/accounts/2941966/incidents/1234/acknowledge",+ "incident_id": 1234,+ "details": "Violation description test.",+ "policy_name": "Test policy name",+ "condition_name": "Server Down",+ "timestamp": 1605133931151,+ "current_state": "open",+ "incident_url": "https://alerts.newrelic.com/accounts/2941966/incidents/1234"+}diff --git a/zerver/webhooks/newrelic/fixtures/incident_missing_timestamp.json b/zerver/webhooks/newrelic/fixtures/incident_missing_timestamp.jsonnew file mode 100644index 00000000000..4afd7f35047--- /dev/null+++ b/zerver/webhooks/newrelic/fixtures/incident_missing_timestamp.json@@ -0,0 +1,10 @@+{+ "incident_acknowledge_url": "https://alerts.newrelic.com/accounts/2941966/incidents/1234/acknowledge",+ "duration": 5,+ "incident_id": 1234,+ "details": "Violation description test.",+ "policy_name": "Test policy name",+ "condition_name": "Server Down",+ "current_state": "open",+ "incident_url": "https://alerts.newrelic.com/accounts/2941966/incidents/1234"+}diff --git a/zerver/webhooks/newrelic/fixtures/incident_opened.json b/zerver/webhooks/newrelic/fixtures/incident_opened.jsonnew file mode 100644index 00000000000..0c9be3e14fb--- /dev/null+++ b/zerver/webhooks/newrelic/fixtures/incident_opened.json@@ -0,0 +1,11 @@+{+ "incident_acknowledge_url": "https://alerts.newrelic.com/accounts/2941966/incidents/1234/acknowledge",+ "duration": 5,+ "incident_id": 1234,+ "details": "Violation description test.",+ "policy_name": "Test policy name",+ "condition_name": "Server Down",+ "timestamp": 1605133931151,+ "current_state": "open",+ "incident_url": "https://alerts.newrelic.com/accounts/2941966/incidents/1234"+}diff --git a/zerver/webhooks/newrelic/fixtures/incident_state_not_recognized.json b/zerver/webhooks/newrelic/fixtures/incident_state_not_recognized.jsonnew file mode 100644index 00000000000..f431cfd7b8a--- /dev/null+++ b/zerver/webhooks/newrelic/fixtures/incident_state_not_recognized.json@@ -0,0 +1,11 @@+{+ "incident_acknowledge_url": "https://alerts.newrelic.com/accounts/2941966/incidents/1234/acknowledge",+ "duration": 5,+ "incident_id": 1234,+ "details": "Violation description test.",+ "policy_name": "Test policy name",+ "condition_name": "Server Down",+ "timestamp": 1605133931151,+ "current_state": "hello world",+ "incident_url": "https://alerts.newrelic.com/accounts/2941966/incidents/1234"+}diff --git a/zerver/webhooks/newrelic/fixtures/incident_time_too_large.json b/zerver/webhooks/newrelic/fixtures/incident_time_too_large.jsonnew file mode 100644index 00000000000..201f800ec32--- /dev/null+++ b/zerver/webhooks/newrelic/fixtures/incident_time_too_large.json@@ -0,0 +1,11 @@+{+ "incident_acknowledge_url": "https://alerts.newrelic.com/accounts/2941966/incidents/1234/acknowledge",+ "duration": 5,+ "incident_id": 1234,+ "details": "Violation description test.",+ "policy_name": "Test policy name",+ "condition_name": "Server Down",+ "timestamp": 160513393115100000,+ "current_state": "open",+ "incident_url": "https://alerts.newrelic.com/accounts/2941966/incidents/1234"+}diff --git a/zerver/webhooks/newrelic/tests.py b/zerver/webhooks/newrelic/tests.pyindex bf090eaf05b..2f23317968c 100644--- a/zerver/webhooks/newrelic/tests.py+++ b/zerver/webhooks/newrelic/tests.py@@ -4,40 +4,122 @@ from zerver.lib.test_classes import WebhookTestCaseclass NewRelicHookTests(WebhookTestCase):STREAM_NAME = 'newrelic'URL_TEMPLATE = "/api/v1/external/newrelic?stream={stream}&api_key={api_key}"+ FIXTURE_DIR_NAME = 'newrelic'- def test_alert(self) -> None:- expected_topic = "Apdex score fell below critical level of 0.90"- expected_message = 'Alert opened on [application name]: Apdex score fell below critical level of 0.90 ([view alert](https://rpm.newrelc.com/accounts/[account_id]/applications/[application_id]/incidents/[incident_id])).'+ def test_open(self) -> None:+ expected_topic = "Test policy name (1234)"+ expected_message = """+[Incident](https://alerts.newrelic.com/accounts/2941966/incidents/1234) **opened** for condition: **Server Down** at <time:2020-11-11 22:32:11.146000>+``` quote+Violation description test.+```+""".strip()self.check_webhook(- "alert",+ "incident_opened",expected_topic,expected_message,- content_type="application/x-www-form-urlencoded",+ content_type="application/json",)- def test_deployment(self) -> None:- expected_topic = 'Test App deploy'+ def test_closed(self) -> None:+ expected_topic = "Test policy name (1234)"expected_message = """-**1242** deployed by **Zulip Test**:+[Incident](https://alerts.newrelic.com/accounts/2941966/incidents/1234) **closed** for condition: **Server Down**+""".strip()-``` quote-Description sent via curl-```+ self.check_webhook(+ "incident_closed",+ expected_topic,+ expected_message,+ content_type="application/json",+ )++ def test_acknowledged(self) -> None:+ expected_topic = "Test policy name (1234)"+ expected_message = """+[Incident](https://alerts.newrelic.com/accounts/2941966/incidents/1234) **acknowledged** for condition: **Server Down**+""".strip()++ self.check_webhook(+ "incident_acknowledged",+ expected_topic,+ expected_message,+ content_type="application/json",+ )-Changelog:+ def test_not_recognized(self) -> None:+ with self.assertRaises(AssertionError) as e:+ self.check_webhook(+ "incident_state_not_recognized",+ "",+ "",+ content_type="application/json",+ )+ self.assertIn("The newrelic webhook requires current_state be in [open|acknowledged|closed]", e.exception.args[0])+ def test_missing_fields(self) -> None:+ expected_topic = "Unknown Policy (Unknown ID)"+ expected_message = """+[Incident](https://alerts.newrelic.com) **opened** for condition: **Unknown condition** at <time:2020-11-11 22:32:11.146000>``` quote-Changelog string+No details.```""".strip()self.check_webhook(- "deployment",+ "incident_default_fields",expected_topic,expected_message,- content_type="application/x-www-form-urlencoded",+ content_type="application/json",)- def get_body(self, fixture_name: str) -> str:- return self.webhook_fixture_data("newrelic", fixture_name, file_type="txt")+ def test_missing_current_state(self) -> None:+ with self.assertRaises(AssertionError) as e:+ self.check_webhook(+ "incident_missing_current_state",+ "",+ "",+ content_type="application/json",+ )+ self.assertIn("The newrelic webhook requires current_state be in [open|acknowledged|closed]", e.exception.args[0])++ def test_missing_duration(self) -> None:+ with self.assertRaises(AssertionError) as e:+ self.check_webhook(+ "incident_missing_duration",+ "",+ "",+ content_type="application/json",+ )+ self.assertIn("The newrelic webhook requires duration in milliseconds", e.exception.args[0])++ def test_missing_timestamp(self) -> None:+ with self.assertRaises(AssertionError) as e:+ self.check_webhook(+ "incident_missing_timestamp",+ "",+ "",+ content_type="application/json",+ )+ self.assertIn("The newrelic webhook requires timestamp in milliseconds", e.exception.args[0])++ def test_malformatted_time(self) -> None:+ with self.assertRaises(AssertionError) as e:+ self.check_webhook(+ "incident_malformatted_time",+ "",+ "",+ content_type="application/json",+ )+ self.assertIn("The newrelic webhook expects timestamp and duration in milliseconds", e.exception.args[0])++ def test_time_too_large(self) -> None:+ with self.assertRaises(AssertionError) as e:+ self.check_webhook(+ "incident_time_too_large",+ "",+ "",+ content_type="application/json",+ )+ self.assertIn("The newrelic webhook expects timestamp and duration in milliseconds", e.exception.args[0])diff --git a/zerver/webhooks/newrelic/view.py b/zerver/webhooks/newrelic/view.pyindex 556781ce65a..12f062f4ba1 100644--- a/zerver/webhooks/newrelic/view.py+++ b/zerver/webhooks/newrelic/view.py@@ -1,49 +1,77 @@# Webhooks for external integrations.-from typing import Any, Dict, Optional+from datetime import datetime+from typing import Any, Dictfrom django.http import HttpRequest, HttpResponse+from django.utils.translation import ugettext as _from zerver.decorator import webhook_view-from zerver.lib.exceptions import UnsupportedWebhookEventTypefrom zerver.lib.request import REQ, has_request_variables-from zerver.lib.response import json_success-from zerver.lib.validator import check_dict+from zerver.lib.response import json_error, json_successfrom zerver.lib.webhooks.common import check_send_webhook_messagefrom zerver.models import UserProfile-ALERT_TEMPLATE = "{long_description} ([view alert]({alert_url}))."--DEPLOY_TEMPLATE = """-**{revision}** deployed by **{deployed_by}**:-+OPEN_TEMPLATE = """+[Incident]({incident_url}) **opened** for condition: **{condition_name}** at <time:{iso_timestamp}>``` quote-{description}+{details}```+""".strip()-Changelog:+DEFAULT_TEMPLATE = """[Incident]({incident_url}) **{status}** for condition: **{condition_name}**""".strip()-``` quote-{changelog}-```-""".strip()+TOPIC_TEMPLATE = """{policy_name} ({incident_id})""".strip()@webhook_view("NewRelic")@has_request_variables-def api_newrelic_webhook(request: HttpRequest, user_profile: UserProfile,- alert: Optional[Dict[str, Any]]=REQ(validator=check_dict([]), default=None),- deployment: Optional[Dict[str, Any]]=REQ(validator=check_dict([]), default=None),- ) -> HttpResponse:- if alert:- # Use the message as the subject because it stays the same for- # "opened", "acknowledged", and "closed" messages that should be- # grouped.- subject = alert['message']- content = ALERT_TEMPLATE.format(**alert)- elif deployment:- subject = "{} deploy".format(deployment['application_name'])- content = DEPLOY_TEMPLATE.format(**deployment)+def api_newrelic_webhook(+ request: HttpRequest,+ user_profile: UserProfile,+ payload: Dict[str, Any]=REQ(argument_type='body')+) -> HttpResponse:++ info = {+ "condition_name": payload.get('condition_name', 'Unknown condition'),+ "details": payload.get('details', 'No details.'),+ "incident_url": payload.get('incident_url', 'https://alerts.newrelic.com'),+ "incident_acknowledge_url": payload.get('incident_acknowledge_url', 'https://alerts.newrelic.com'),+ "status": payload.get('current_state', 'None'),+ "iso_timestamp": '',+ }++ unix_time = payload.get('timestamp', None)+ if unix_time is None:+ return json_error(_("The newrelic webhook requires timestamp in milliseconds"))++ duration = payload.get('duration', None)+ if duration is None:+ return json_error(_("The newrelic webhook requires duration in milliseconds"))++ try:+ # Timestamp - duration to get time alert started+ # timestamps from NewRelic are in ms+ iso_timestamp = datetime.fromtimestamp((unix_time - duration) / 1000)+ info['iso_timestamp'] = iso_timestamp+ except ValueError:+ return json_error(_("The newrelic webhook expects timestamp and duration in milliseconds"))+ except TypeError:+ return json_error(_("The newrelic webhook expects timestamp and duration in milliseconds"))++ # These are the three promised current_state values+ if 'open' in info['status']:+ content = OPEN_TEMPLATE.format(**info)+ elif 'acknowledged' in info['status']:+ content = DEFAULT_TEMPLATE.format(**info)+ elif 'closed' in info['status']:+ content = DEFAULT_TEMPLATE.format(**info)else:- raise UnsupportedWebhookEventType('Unknown Event Type')+ return json_error(_("The newrelic webhook requires current_state be in [open|acknowledged|closed]"))++ topic_info = {+ "policy_name": payload.get('policy_name', 'Unknown Policy'),+ "incident_id": payload.get('incident_id', 'Unknown ID'),+ }+ topic = TOPIC_TEMPLATE.format(**topic_info)- check_send_webhook_message(request, user_profile, subject, content)+ check_send_webhook_message(request, user_profile, topic, content)return json_success()