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.

207 lines
6.3 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 in ("new", "paused"):
  67. return self.status
  68. now = timezone.now()
  69. if self.last_ping + self.timeout > now:
  70. return "up"
  71. if self.last_ping + self.timeout + self.grace > now:
  72. return "grace"
  73. return "down"
  74. def assign_all_channels(self):
  75. if self.user:
  76. channels = Channel.objects.filter(user=self.user)
  77. self.channel_set.add(*channels)
  78. def tags_list(self):
  79. return [t.strip() for t in self.tags.split(" ") if t.strip()]
  80. class Ping(models.Model):
  81. n = models.IntegerField(null=True)
  82. owner = models.ForeignKey(Check)
  83. created = models.DateTimeField(auto_now_add=True)
  84. scheme = models.CharField(max_length=10, default="http")
  85. remote_addr = models.GenericIPAddressField(blank=True, null=True)
  86. method = models.CharField(max_length=10, blank=True)
  87. ua = models.CharField(max_length=200, blank=True)
  88. class Channel(models.Model):
  89. code = models.UUIDField(default=uuid.uuid4, editable=False)
  90. user = models.ForeignKey(User)
  91. created = models.DateTimeField(auto_now_add=True)
  92. kind = models.CharField(max_length=20, choices=CHANNEL_KINDS)
  93. value = models.TextField(blank=True)
  94. email_verified = models.BooleanField(default=False)
  95. checks = models.ManyToManyField(Check)
  96. def assign_all_checks(self):
  97. checks = Check.objects.filter(user=self.user)
  98. self.checks.add(*checks)
  99. def make_token(self):
  100. seed = "%s%s" % (self.code, settings.SECRET_KEY)
  101. seed = seed.encode("utf8")
  102. return hashlib.sha1(seed).hexdigest()
  103. def send_verify_link(self):
  104. args = [self.code, self.make_token()]
  105. verify_link = reverse("hc-verify-email", args=args)
  106. verify_link = settings.SITE_ROOT + verify_link
  107. emails.verify_email(self.value, {"verify_link": verify_link})
  108. @property
  109. def transport(self):
  110. if self.kind == "email":
  111. return transports.Email(self)
  112. elif self.kind == "webhook":
  113. return transports.Webhook(self)
  114. elif self.kind == "slack":
  115. return transports.Slack(self)
  116. elif self.kind == "hipchat":
  117. return transports.HipChat(self)
  118. elif self.kind == "pd":
  119. return transports.PagerDuty(self)
  120. elif self.kind == "victorops":
  121. return transports.VictorOps(self)
  122. elif self.kind == "po":
  123. return transports.Pushover(self)
  124. else:
  125. raise NotImplementedError("Unknown channel kind: %s" % self.kind)
  126. def notify(self, check):
  127. # Make 3 attempts--
  128. for x in range(0, 3):
  129. error = self.transport.notify(check) or ""
  130. if error in ("", "no-op"):
  131. break # Success!
  132. if error != "no-op":
  133. n = Notification(owner=check, channel=self)
  134. n.check_status = check.status
  135. n.error = error
  136. n.save()
  137. return error
  138. def test(self):
  139. return self.transport().test()
  140. @property
  141. def po_value(self):
  142. assert self.kind == "po"
  143. user_key, prio = self.value.split("|")
  144. prio = int(prio)
  145. return user_key, prio, PO_PRIORITIES[prio]
  146. @property
  147. def value_down(self):
  148. assert self.kind == "webhook"
  149. parts = self.value.split("\n")
  150. return parts[0]
  151. @property
  152. def value_up(self):
  153. assert self.kind == "webhook"
  154. parts = self.value.split("\n")
  155. return parts[1] if len(parts) == 2 else ""
  156. def latest_notification(self):
  157. return Notification.objects.filter(channel=self).latest()
  158. class Notification(models.Model):
  159. class Meta:
  160. get_latest_by = "created"
  161. owner = models.ForeignKey(Check)
  162. check_status = models.CharField(max_length=6)
  163. channel = models.ForeignKey(Channel)
  164. created = models.DateTimeField(auto_now_add=True)
  165. error = models.CharField(max_length=200, blank=True)