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.

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