test_tasks.py 6.8 KB

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