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.

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