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.

212 lines
6.4 KiB

10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. # coding: utf-8
  2. import hashlib
  3. import uuid
  4. from datetime import timedelta as td
  5. from django.conf import settings
  6. from django.contrib.auth.models import User
  7. from django.core.urlresolvers import reverse
  8. from django.db import models
  9. from django.utils import timezone
  10. from hc.api import transports
  11. from hc.lib import emails
  12. STATUSES = (
  13. ("up", "Up"),
  14. ("down", "Down"),
  15. ("new", "New"),
  16. ("paused", "Paused")
  17. )
  18. DEFAULT_TIMEOUT = td(days=1)
  19. DEFAULT_GRACE = td(hours=1)
  20. CHANNEL_KINDS = (("email", "Email"), ("webhook", "Webhook"),
  21. ("hipchat", "HipChat"),
  22. ("slack", "Slack"), ("pd", "PagerDuty"), ("po", "Pushover"),
  23. ("victorops", "VictorOps"))
  24. PO_PRIORITIES = {
  25. -2: "lowest",
  26. -1: "low",
  27. 0: "normal",
  28. 1: "high",
  29. 2: "emergency"
  30. }
  31. class Check(models.Model):
  32. class Meta:
  33. # sendalerts command will query using these
  34. index_together = ["status", "user", "alert_after"]
  35. name = models.CharField(max_length=100, blank=True)
  36. tags = models.CharField(max_length=500, blank=True)
  37. code = models.UUIDField(default=uuid.uuid4, editable=False, db_index=True)
  38. user = models.ForeignKey(User, blank=True, null=True)
  39. created = models.DateTimeField(auto_now_add=True)
  40. timeout = models.DurationField(default=DEFAULT_TIMEOUT)
  41. grace = models.DurationField(default=DEFAULT_GRACE)
  42. n_pings = models.IntegerField(default=0)
  43. last_ping = models.DateTimeField(null=True, blank=True)
  44. alert_after = models.DateTimeField(null=True, blank=True, editable=False)
  45. status = models.CharField(max_length=6, choices=STATUSES, default="new")
  46. def name_then_code(self):
  47. if self.name:
  48. return self.name
  49. return str(self.code)
  50. def url(self):
  51. return settings.PING_ENDPOINT + str(self.code)
  52. def log_url(self):
  53. return settings.SITE_ROOT + reverse("hc-log", args=[self.code])
  54. def email(self):
  55. return "%s@%s" % (self.code, settings.PING_EMAIL_DOMAIN)
  56. def send_alert(self):
  57. if self.status not in ("up", "down"):
  58. raise NotImplementedError("Unexpected status: %s" % self.status)
  59. errors = []
  60. for channel in self.channel_set.all():
  61. error = channel.notify(self)
  62. if error not in ("", "no-op"):
  63. errors.append((channel, error))
  64. return errors
  65. def get_status(self):
  66. if self.status == "new":
  67. return self.status
  68. now = timezone.now()
  69. if self.last_ping + self.timeout + self.grace > now:
  70. return "up"
  71. return "down"
  72. def in_grace_period(self):
  73. if not self.last_ping:
  74. return False
  75. up_ends = self.last_ping + self.timeout
  76. grace_ends = up_ends + self.grace
  77. return up_ends < timezone.now() < grace_ends
  78. def assign_all_channels(self):
  79. if self.user:
  80. channels = Channel.objects.filter(user=self.user)
  81. self.channel_set.add(*channels)
  82. def tags_list(self):
  83. return [t.strip() for t in self.tags.split(" ") if t.strip()]
  84. class Ping(models.Model):
  85. n = models.IntegerField(null=True)
  86. owner = models.ForeignKey(Check)
  87. created = models.DateTimeField(auto_now_add=True)
  88. scheme = models.CharField(max_length=10, default="http")
  89. remote_addr = models.GenericIPAddressField(blank=True, null=True)
  90. method = models.CharField(max_length=10, blank=True)
  91. ua = models.CharField(max_length=200, blank=True)
  92. class Channel(models.Model):
  93. code = models.UUIDField(default=uuid.uuid4, editable=False)
  94. user = models.ForeignKey(User)
  95. created = models.DateTimeField(auto_now_add=True)
  96. kind = models.CharField(max_length=20, choices=CHANNEL_KINDS)
  97. value = models.TextField(blank=True)
  98. email_verified = models.BooleanField(default=False)
  99. checks = models.ManyToManyField(Check)
  100. def assign_all_checks(self):
  101. checks = Check.objects.filter(user=self.user)
  102. self.checks.add(*checks)
  103. def make_token(self):
  104. seed = "%s%s" % (self.code, settings.SECRET_KEY)
  105. seed = seed.encode("utf8")
  106. return hashlib.sha1(seed).hexdigest()
  107. def send_verify_link(self):
  108. args = [self.code, self.make_token()]
  109. verify_link = reverse("hc-verify-email", args=args)
  110. verify_link = settings.SITE_ROOT + verify_link
  111. emails.verify_email(self.value, {"verify_link": verify_link})
  112. @property
  113. def transport(self):
  114. if self.kind == "email":
  115. return transports.Email(self)
  116. elif self.kind == "webhook":
  117. return transports.Webhook(self)
  118. elif self.kind == "slack":
  119. return transports.Slack(self)
  120. elif self.kind == "hipchat":
  121. return transports.HipChat(self)
  122. elif self.kind == "pd":
  123. return transports.PagerDuty(self)
  124. elif self.kind == "victorops":
  125. return transports.VictorOps(self)
  126. elif self.kind == "po":
  127. return transports.Pushover(self)
  128. else:
  129. raise NotImplementedError("Unknown channel kind: %s" % self.kind)
  130. def notify(self, check):
  131. # Make 3 attempts--
  132. for x in range(0, 3):
  133. error = self.transport.notify(check) or ""
  134. if error in ("", "no-op"):
  135. break # Success!
  136. if error != "no-op":
  137. n = Notification(owner=check, channel=self)
  138. n.check_status = check.status
  139. n.error = error
  140. n.save()
  141. return error
  142. def test(self):
  143. return self.transport().test()
  144. @property
  145. def po_value(self):
  146. assert self.kind == "po"
  147. user_key, prio = self.value.split("|")
  148. prio = int(prio)
  149. return user_key, prio, PO_PRIORITIES[prio]
  150. @property
  151. def value_down(self):
  152. assert self.kind == "webhook"
  153. parts = self.value.split("\n")
  154. return parts[0]
  155. @property
  156. def value_up(self):
  157. assert self.kind == "webhook"
  158. parts = self.value.split("\n")
  159. return parts[1] if len(parts) == 2 else ""
  160. def latest_notification(self):
  161. return Notification.objects.filter(channel=self).latest()
  162. class Notification(models.Model):
  163. class Meta:
  164. get_latest_by = "created"
  165. owner = models.ForeignKey(Check)
  166. check_status = models.CharField(max_length=6)
  167. channel = models.ForeignKey(Channel)
  168. created = models.DateTimeField(auto_now_add=True)
  169. error = models.CharField(max_length=200, blank=True)