test_tasks.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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.snuba.dataset import Dataset
  30. from sentry.snuba.query_subscription_consumer import (
  31. get_query_subscription_consumer,
  32. subscriber_registry,
  33. topic_to_dataset,
  34. )
  35. from sentry.testutils import TestCase
  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 = settings.KAFKA_TOPICS[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 = settings.KAFKA_TOPICS[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. message = handler.build_message(
  144. generate_incident_trigger_email_context(
  145. handler.project,
  146. handler.incident,
  147. handler.action.alert_rule_trigger,
  148. TriggerStatus.ACTIVE,
  149. IncidentStatus.CRITICAL,
  150. ),
  151. TriggerStatus.ACTIVE,
  152. self.user.id,
  153. )
  154. out = mail.outbox[0]
  155. assert out.to == [self.user.email]
  156. assert out.subject == message.subject
  157. built_message = message.build(self.user.email)
  158. assert out.body == built_message.body
  159. def test_arroyo(self):
  160. with mock.patch.dict(topic_to_dataset, {self.topic: Dataset.Metrics}):
  161. consumer = get_query_subscription_consumer(self.topic, "hi", True, "earliest")
  162. self.run_test(consumer)