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.

172 lines
5.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. PO_PRIORITIES = {
  24. -2: "lowest",
  25. -1: "low",
  26. 0: "normal",
  27. 1: "high",
  28. 2: "emergency"
  29. }
  30. class Check(models.Model):
  31. class Meta:
  32. # sendalerts command will query using these
  33. index_together = ["status", "user", "alert_after"]
  34. name = models.CharField(max_length=100, blank=True)
  35. tags = models.CharField(max_length=500, blank=True)
  36. code = models.UUIDField(default=uuid.uuid4, editable=False, db_index=True)
  37. user = models.ForeignKey(User, blank=True, null=True)
  38. created = models.DateTimeField(auto_now_add=True)
  39. timeout = models.DurationField(default=DEFAULT_TIMEOUT)
  40. grace = models.DurationField(default=DEFAULT_GRACE)
  41. n_pings = models.IntegerField(default=0)
  42. last_ping = models.DateTimeField(null=True, blank=True)
  43. alert_after = models.DateTimeField(null=True, blank=True, editable=False)
  44. status = models.CharField(max_length=6, choices=STATUSES, default="new")
  45. def name_then_code(self):
  46. if self.name:
  47. return self.name
  48. return str(self.code)
  49. def url(self):
  50. return settings.PING_ENDPOINT + str(self.code)
  51. def email(self):
  52. return "%s@%s" % (self.code, settings.PING_EMAIL_DOMAIN)
  53. def send_alert(self):
  54. if self.status not in ("up", "down"):
  55. raise NotImplementedError("Unexpected status: %s" % self.status)
  56. for channel in self.channel_set.all():
  57. channel.notify(self)
  58. def get_status(self):
  59. if self.status in ("new", "paused"):
  60. return self.status
  61. now = timezone.now()
  62. if self.last_ping + self.timeout > now:
  63. return "up"
  64. if self.last_ping + self.timeout + self.grace > now:
  65. return "grace"
  66. return "down"
  67. def assign_all_channels(self):
  68. if self.user:
  69. channels = Channel.objects.filter(user=self.user)
  70. self.channel_set.add(*channels)
  71. def tags_list(self):
  72. return [t.strip() for t in self.tags.split(" ") if t.strip()]
  73. class Ping(models.Model):
  74. n = models.IntegerField(null=True)
  75. owner = models.ForeignKey(Check)
  76. created = models.DateTimeField(auto_now_add=True)
  77. scheme = models.CharField(max_length=10, default="http")
  78. remote_addr = models.GenericIPAddressField(blank=True, null=True)
  79. method = models.CharField(max_length=10, blank=True)
  80. ua = models.CharField(max_length=200, blank=True)
  81. class Channel(models.Model):
  82. code = models.UUIDField(default=uuid.uuid4, editable=False)
  83. user = models.ForeignKey(User)
  84. created = models.DateTimeField(auto_now_add=True)
  85. kind = models.CharField(max_length=20, choices=CHANNEL_KINDS)
  86. value = models.CharField(max_length=200, blank=True)
  87. email_verified = models.BooleanField(default=False)
  88. checks = models.ManyToManyField(Check)
  89. def make_token(self):
  90. seed = "%s%s" % (self.code, settings.SECRET_KEY)
  91. seed = seed.encode("utf8")
  92. return hashlib.sha1(seed).hexdigest()
  93. def send_verify_link(self):
  94. args = [self.code, self.make_token()]
  95. verify_link = reverse("hc-verify-email", args=args)
  96. verify_link = settings.SITE_ROOT + verify_link
  97. emails.verify_email(self.value, {"verify_link": verify_link})
  98. @property
  99. def transport(self):
  100. if self.kind == "email":
  101. return transports.Email(self)
  102. elif self.kind == "webhook":
  103. return transports.Webhook(self)
  104. elif self.kind == "slack":
  105. return transports.Slack(self)
  106. elif self.kind == "hipchat":
  107. return transports.HipChat(self)
  108. elif self.kind == "pd":
  109. return transports.PagerDuty(self)
  110. elif self.kind == "po":
  111. return transports.Pushover()
  112. else:
  113. raise NotImplementedError("Unknown channel kind: %s" % self.kind)
  114. def notify(self, check):
  115. # Make 3 attempts--
  116. for x in range(0, 3):
  117. error = self.transport.notify(check) or ""
  118. if error in ("", "no-op"):
  119. break # Success!
  120. if error != "no-op":
  121. n = Notification(owner=check, channel=self)
  122. n.check_status = check.status
  123. n.error = error
  124. n.save()
  125. def test(self):
  126. return self.transport().test()
  127. @property
  128. def po_value(self):
  129. assert self.kind == "po"
  130. user_key, prio = self.value.split("|")
  131. prio = int(prio)
  132. return user_key, prio, PO_PRIORITIES[prio]
  133. class Notification(models.Model):
  134. owner = models.ForeignKey(Check)
  135. check_status = models.CharField(max_length=6)
  136. channel = models.ForeignKey(Channel)
  137. created = models.DateTimeField(auto_now_add=True)
  138. error = models.CharField(max_length=200, blank=True)