test_tasks.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. from copy import deepcopy
  2. from functools import cached_property
  3. from unittest import mock
  4. from uuid import uuid4
  5. from arroyo.utils import metrics
  6. from confluent_kafka import Producer
  7. from confluent_kafka.admin import AdminClient
  8. from django.conf import settings
  9. from django.core import mail
  10. from django.test.utils import override_settings
  11. from sentry.incidents.action_handlers import (
  12. EmailActionHandler,
  13. generate_incident_trigger_email_context,
  14. )
  15. from sentry.incidents.logic import (
  16. CRITICAL_TRIGGER_LABEL,
  17. create_alert_rule_trigger,
  18. create_alert_rule_trigger_action,
  19. )
  20. from sentry.incidents.models import (
  21. AlertRuleTriggerAction,
  22. Incident,
  23. IncidentActivity,
  24. IncidentStatus,
  25. IncidentType,
  26. TriggerStatus,
  27. )
  28. from sentry.incidents.tasks import INCIDENTS_SNUBA_SUBSCRIPTION_TYPE
  29. from sentry.runner.commands.run import DEFAULT_BLOCK_SIZE
  30. from sentry.snuba.dataset import Dataset
  31. from sentry.snuba.query_subscriptions.constants import topic_to_dataset
  32. from sentry.snuba.query_subscriptions.consumer import subscriber_registry
  33. from sentry.snuba.query_subscriptions.run import get_query_subscription_consumer
  34. from sentry.testutils.cases import TestCase
  35. from sentry.testutils.helpers.datetime import freeze_time
  36. from sentry.utils import json, kafka_config
  37. from sentry.utils.batching_kafka_consumer import create_topics
  38. @freeze_time()
  39. class HandleSnubaQueryUpdateTest(TestCase):
  40. def setUp(self):
  41. super().setUp()
  42. self.override_settings_cm = override_settings(
  43. KAFKA_TOPICS={self.topic: {"cluster": "default"}}
  44. )
  45. self.override_settings_cm.__enter__()
  46. self.orig_registry = deepcopy(subscriber_registry)
  47. cluster_options = kafka_config.get_kafka_admin_cluster_options(
  48. "default", {"allow.auto.create.topics": "true"}
  49. )
  50. self.admin_client = AdminClient(cluster_options)
  51. kafka_cluster = kafka_config.get_topic_definition(self.topic)["cluster"]
  52. create_topics(kafka_cluster, [self.topic])
  53. def tearDown(self):
  54. super().tearDown()
  55. self.override_settings_cm.__exit__(None, None, None)
  56. subscriber_registry.clear()
  57. subscriber_registry.update(self.orig_registry)
  58. self.admin_client.delete_topics([self.topic])
  59. metrics._metrics_backend = None
  60. @cached_property
  61. def subscription(self):
  62. return self.rule.snuba_query.subscriptions.get()
  63. @cached_property
  64. def rule(self):
  65. with self.tasks():
  66. rule = self.create_alert_rule(
  67. name="some rule",
  68. query="",
  69. aggregate="count()",
  70. time_window=1,
  71. threshold_period=1,
  72. resolve_threshold=10,
  73. )
  74. trigger = create_alert_rule_trigger(rule, CRITICAL_TRIGGER_LABEL, 100)
  75. create_alert_rule_trigger_action(
  76. trigger,
  77. AlertRuleTriggerAction.Type.EMAIL,
  78. AlertRuleTriggerAction.TargetType.USER,
  79. str(self.user.id),
  80. )
  81. return rule
  82. @cached_property
  83. def trigger(self):
  84. return self.rule.alertruletrigger_set.get()
  85. @cached_property
  86. def action(self):
  87. return self.trigger.alertruletriggeraction_set.get()
  88. @cached_property
  89. def producer(self):
  90. cluster_name = kafka_config.get_topic_definition(self.topic)["cluster"]
  91. conf = {
  92. "bootstrap.servers": settings.KAFKA_CLUSTERS[cluster_name]["common"][
  93. "bootstrap.servers"
  94. ],
  95. "session.timeout.ms": 6000,
  96. }
  97. return Producer(conf)
  98. @cached_property
  99. def topic(self):
  100. return uuid4().hex
  101. def run_test(self, consumer):
  102. # Full integration test to ensure that when a subscription receives an update
  103. # the `QuerySubscriptionConsumer` successfully retries the subscription and
  104. # calls the correct callback, which should result in an incident being created.
  105. message = {
  106. "version": 3,
  107. "payload": {
  108. "subscription_id": self.subscription.subscription_id,
  109. "result": {
  110. "data": [{"some_col": 101}],
  111. "meta": [{"name": "count", "type": "UInt64"}],
  112. },
  113. "request": {
  114. "some": "data",
  115. "query": """MATCH (metrics_counters) SELECT sum(value) AS value BY
  116. tags[3] WHERE org_id = 1 AND project_id IN tuple(1) AND metric_id = 16
  117. AND tags[3] IN tuple(13, 4)""",
  118. },
  119. "entity": "metrics_counters",
  120. "timestamp": "2020-01-01T01:23:45.1234",
  121. },
  122. }
  123. self.producer.produce(self.topic, json.dumps(message))
  124. self.producer.flush()
  125. def active_incident():
  126. return Incident.objects.filter(
  127. type=IncidentType.ALERT_TRIGGERED.value, alert_rule=self.rule
  128. ).exclude(status=IncidentStatus.CLOSED.value)
  129. original_callback = subscriber_registry[INCIDENTS_SNUBA_SUBSCRIPTION_TYPE]
  130. def shutdown_callback(*args, **kwargs):
  131. # We want to just exit after the callback so that we can see the result of
  132. # processing.
  133. original_callback(*args, **kwargs)
  134. consumer.signal_shutdown()
  135. subscriber_registry[INCIDENTS_SNUBA_SUBSCRIPTION_TYPE] = shutdown_callback
  136. with self.feature(["organizations:incidents", "organizations:performance-view"]):
  137. assert not active_incident().exists()
  138. with self.tasks(), self.capture_on_commit_callbacks(execute=True):
  139. consumer.run()
  140. assert active_incident().exists()
  141. assert len(mail.outbox) == 1
  142. handler = EmailActionHandler(self.action, active_incident().get(), self.project)
  143. incident_activity = (
  144. IncidentActivity.objects.filter(incident=handler.incident).order_by("-id").first()
  145. )
  146. message_builder = handler.build_message(
  147. generate_incident_trigger_email_context(
  148. handler.project,
  149. handler.incident,
  150. handler.action.alert_rule_trigger,
  151. TriggerStatus.ACTIVE,
  152. IncidentStatus.CRITICAL,
  153. notification_uuid=str(incident_activity.notification_uuid),
  154. ),
  155. TriggerStatus.ACTIVE,
  156. self.user.id,
  157. )
  158. out = mail.outbox[0]
  159. assert isinstance(out, mail.EmailMultiAlternatives)
  160. assert out.to == [self.user.email]
  161. assert out.subject == message_builder.subject
  162. built_message = message_builder.build(self.user.email)
  163. assert out.body == built_message.body
  164. def test_arroyo(self):
  165. with mock.patch.dict(topic_to_dataset, {self.topic: Dataset.Metrics}):
  166. consumer = get_query_subscription_consumer(
  167. self.topic,
  168. "hi",
  169. True,
  170. "earliest",
  171. 1,
  172. 1,
  173. 1,
  174. DEFAULT_BLOCK_SIZE,
  175. DEFAULT_BLOCK_SIZE,
  176. multi_proc=False,
  177. )
  178. self.run_test(consumer)