You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

158 lines
4.9 KiB

  1. from datetime import timedelta as td
  2. import time
  3. from threading import Thread
  4. from django.core.management.base import BaseCommand
  5. from django.utils import timezone
  6. from hc.api.models import Check, Flip
  7. from statsd.defaults.env import statsd
  8. SENDING_TMPL = "Sending alert, status=%s, code=%s\n"
  9. SEND_TIME_TMPL = "Sending took %.1fs, code=%s\n"
  10. def notify(flip_id, stdout):
  11. flip = Flip.objects.get(id=flip_id)
  12. check = flip.owner
  13. # Set the historic status here but *don't save it*.
  14. # It would be nicer to pass the status explicitly, as a separate parameter.
  15. check.status = flip.new_status
  16. # And just to make sure it doesn't get saved by a future coding accident:
  17. setattr(check, "save", None)
  18. stdout.write(SENDING_TMPL % (flip.new_status, check.code))
  19. # Set dates for followup nags
  20. if flip.new_status == "down":
  21. check.project.set_next_nag_date()
  22. # Send notifications
  23. send_start = timezone.now()
  24. errors = flip.send_alerts()
  25. for ch, error in errors:
  26. stdout.write("ERROR: %s %s %s\n" % (ch.kind, ch.value, error))
  27. # If sending took more than 5s, log it
  28. send_time = timezone.now() - send_start
  29. if send_time.total_seconds() > 5:
  30. stdout.write(SEND_TIME_TMPL % (send_time.total_seconds(), check.code))
  31. statsd.timing("hc.sendalerts.dwellTime", send_start - flip.created)
  32. statsd.timing("hc.sendalerts.sendTime", send_time)
  33. def notify_on_thread(flip_id, stdout):
  34. t = Thread(target=notify, args=(flip_id, stdout))
  35. t.start()
  36. class Command(BaseCommand):
  37. help = "Sends UP/DOWN email alerts"
  38. def add_arguments(self, parser):
  39. parser.add_argument(
  40. "--no-loop",
  41. action="store_false",
  42. dest="loop",
  43. default=True,
  44. help="Do not keep running indefinitely in a 2 second wait loop",
  45. )
  46. parser.add_argument(
  47. "--no-threads",
  48. action="store_false",
  49. dest="use_threads",
  50. default=False,
  51. help="Send alerts synchronously, without using threads",
  52. )
  53. def process_one_flip(self, use_threads=True):
  54. """ Find unprocessed flip, send notifications. """
  55. # Order by processed, otherwise Django will automatically order by id
  56. # and make the query less efficient
  57. q = Flip.objects.filter(processed=None).order_by("processed")
  58. flip = q.first()
  59. if flip is None:
  60. return False
  61. q = Flip.objects.filter(id=flip.id, processed=None)
  62. num_updated = q.update(processed=timezone.now())
  63. if num_updated != 1:
  64. # Nothing got updated: another worker process got there first.
  65. return True
  66. if use_threads:
  67. notify_on_thread(flip.id, self.stdout)
  68. else:
  69. notify(flip.id, self.stdout)
  70. return True
  71. def handle_going_down(self):
  72. """ Process a single check going down. """
  73. now = timezone.now()
  74. q = Check.objects.filter(alert_after__lt=now).exclude(status="down")
  75. # Sort by alert_after, to avoid unnecessary sorting by id:
  76. check = q.order_by("alert_after").first()
  77. if check is None:
  78. return False
  79. old_status = check.status
  80. q = Check.objects.filter(id=check.id, status=old_status)
  81. try:
  82. status = check.get_status()
  83. except Exception as e:
  84. # Make sure we don't trip on this check again for an hour:
  85. # Otherwise sendalerts may end up in a crash loop.
  86. q.update(alert_after=now + td(hours=1))
  87. # Then re-raise the exception:
  88. raise e
  89. if status != "down":
  90. # It is not down yet. Update alert_after
  91. q.update(alert_after=check.going_down_after())
  92. return True
  93. # Atomically update status
  94. flip_time = check.going_down_after()
  95. num_updated = q.update(alert_after=None, status="down")
  96. if num_updated != 1:
  97. # Nothing got updated: another worker process got there first.
  98. return True
  99. flip = Flip(owner=check)
  100. flip.created = flip_time
  101. flip.old_status = old_status
  102. flip.new_status = "down"
  103. flip.save()
  104. return True
  105. def handle(self, use_threads=True, loop=True, *args, **options):
  106. self.stdout.write("sendalerts is now running\n")
  107. i, sent = 0, 0
  108. while True:
  109. # Create flips for any checks going down
  110. while self.handle_going_down():
  111. pass
  112. # Process the unprocessed flips
  113. while self.process_one_flip(use_threads):
  114. sent += 1
  115. if not loop:
  116. break
  117. time.sleep(2)
  118. i += 1
  119. if i % 60 == 0:
  120. timestamp = timezone.now().isoformat()
  121. self.stdout.write("-- MARK %s --\n" % timestamp)
  122. return "Sent %d alert(s)" % sent