test_tasks.py 6.8 KB

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