test_tasks.py 6.7 KB

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