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.

363 lines
11 KiB

10 years ago
10 years ago
10 years ago
8 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
  1. # coding: utf-8
  2. import hashlib
  3. import json
  4. import uuid
  5. from datetime import datetime, timedelta as td
  6. from croniter import croniter
  7. from django.conf import settings
  8. from django.core.checks import Warning
  9. from django.contrib.auth.models import User
  10. from django.db import models
  11. from django.urls import reverse
  12. from django.utils import timezone
  13. from hc.api import transports
  14. from hc.lib import emails
  15. STATUSES = (
  16. ("up", "Up"),
  17. ("down", "Down"),
  18. ("new", "New"),
  19. ("paused", "Paused")
  20. )
  21. DEFAULT_TIMEOUT = td(days=1)
  22. DEFAULT_GRACE = td(hours=1)
  23. CHECK_KINDS = (("simple", "Simple"),
  24. ("cron", "Cron"))
  25. CHANNEL_KINDS = (("email", "Email"),
  26. ("webhook", "Webhook"),
  27. ("hipchat", "HipChat"),
  28. ("slack", "Slack"),
  29. ("pd", "PagerDuty"),
  30. ("po", "Pushover"),
  31. ("pushbullet", "Pushbullet"),
  32. ("opsgenie", "OpsGenie"),
  33. ("victorops", "VictorOps"),
  34. ("discord", "Discord"))
  35. PO_PRIORITIES = {
  36. -2: "lowest",
  37. -1: "low",
  38. 0: "normal",
  39. 1: "high",
  40. 2: "emergency"
  41. }
  42. class Check(models.Model):
  43. class Meta:
  44. # sendalerts command will query using these
  45. index_together = ["status", "user", "alert_after"]
  46. name = models.CharField(max_length=100, blank=True)
  47. tags = models.CharField(max_length=500, blank=True)
  48. code = models.UUIDField(default=uuid.uuid4, editable=False, db_index=True)
  49. user = models.ForeignKey(User, blank=True, null=True)
  50. created = models.DateTimeField(auto_now_add=True)
  51. kind = models.CharField(max_length=10, default="simple",
  52. choices=CHECK_KINDS)
  53. timeout = models.DurationField(default=DEFAULT_TIMEOUT)
  54. grace = models.DurationField(default=DEFAULT_GRACE)
  55. schedule = models.CharField(max_length=100, default="* * * * *")
  56. tz = models.CharField(max_length=36, default="UTC")
  57. n_pings = models.IntegerField(default=0)
  58. last_ping = models.DateTimeField(null=True, blank=True)
  59. alert_after = models.DateTimeField(null=True, blank=True, editable=False)
  60. status = models.CharField(max_length=6, choices=STATUSES, default="new")
  61. def name_then_code(self):
  62. if self.name:
  63. return self.name
  64. return str(self.code)
  65. def url(self):
  66. return settings.PING_ENDPOINT + str(self.code)
  67. def log_url(self):
  68. return settings.SITE_ROOT + reverse("hc-log", args=[self.code])
  69. def email(self):
  70. return "%s@%s" % (self.code, settings.PING_EMAIL_DOMAIN)
  71. def send_alert(self):
  72. if self.status not in ("up", "down"):
  73. raise NotImplementedError("Unexpected status: %s" % self.status)
  74. errors = []
  75. for channel in self.channel_set.all():
  76. error = channel.notify(self)
  77. if error not in ("", "no-op"):
  78. errors.append((channel, error))
  79. return errors
  80. def get_grace_start(self):
  81. """ Return the datetime when grace period starts. """
  82. # The common case, grace starts after timeout
  83. if self.kind == "simple":
  84. return self.last_ping + self.timeout
  85. # The complex case, next ping is expected based on cron schedule
  86. with timezone.override(self.tz):
  87. last_naive = timezone.make_naive(self.last_ping)
  88. it = croniter(self.schedule, last_naive)
  89. next_naive = it.get_next(datetime)
  90. return timezone.make_aware(next_naive, is_dst=False)
  91. def get_status(self, now=None):
  92. """ Return "up" if the check is up or in grace, otherwise "down". """
  93. if self.status in ("new", "paused"):
  94. return self.status
  95. if now is None:
  96. now = timezone.now()
  97. return "up" if self.get_grace_start() + self.grace > now else "down"
  98. def get_alert_after(self):
  99. """ Return the datetime when check potentially goes down. """
  100. return self.get_grace_start() + self.grace
  101. def in_grace_period(self):
  102. """ Return True if check is currently in grace period. """
  103. if self.status in ("new", "paused"):
  104. return False
  105. grace_start = self.get_grace_start()
  106. grace_end = grace_start + self.grace
  107. return grace_start < timezone.now() < grace_end
  108. def assign_all_channels(self):
  109. if self.user:
  110. channels = Channel.objects.filter(user=self.user)
  111. self.channel_set.add(*channels)
  112. def tags_list(self):
  113. return [t.strip() for t in self.tags.split(" ") if t.strip()]
  114. def to_dict(self):
  115. update_rel_url = reverse("hc-api-update", args=[self.code])
  116. pause_rel_url = reverse("hc-api-pause", args=[self.code])
  117. result = {
  118. "name": self.name,
  119. "ping_url": self.url(),
  120. "update_url": settings.SITE_ROOT + update_rel_url,
  121. "pause_url": settings.SITE_ROOT + pause_rel_url,
  122. "tags": self.tags,
  123. "grace": int(self.grace.total_seconds()),
  124. "n_pings": self.n_pings,
  125. "status": self.get_status()
  126. }
  127. if self.kind == "simple":
  128. result["timeout"] = int(self.timeout.total_seconds())
  129. elif self.kind == "cron":
  130. result["schedule"] = self.schedule
  131. result["tz"] = self.tz
  132. if self.last_ping:
  133. result["last_ping"] = self.last_ping.isoformat()
  134. result["next_ping"] = (self.last_ping + self.timeout).isoformat()
  135. else:
  136. result["last_ping"] = None
  137. result["next_ping"] = None
  138. return result
  139. @classmethod
  140. def check(cls, **kwargs):
  141. errors = super(Check, cls).check(**kwargs)
  142. trigger_detected = False
  143. try:
  144. dummy = Check(last_ping=timezone.now())
  145. dummy.save()
  146. dummy.refresh_from_db()
  147. trigger_detected = bool(dummy.alert_after)
  148. dummy.delete()
  149. except:
  150. pass
  151. if trigger_detected:
  152. err = Warning(
  153. "Obsolete 'update_alert_after' trigger exists in database.",
  154. hint="Please remove the trigger with 'manage.py droptriggers'",
  155. id="hc.api.E001")
  156. errors.append(err)
  157. return errors
  158. class Ping(models.Model):
  159. n = models.IntegerField(null=True)
  160. owner = models.ForeignKey(Check)
  161. created = models.DateTimeField(auto_now_add=True)
  162. scheme = models.CharField(max_length=10, default="http")
  163. remote_addr = models.GenericIPAddressField(blank=True, null=True)
  164. method = models.CharField(max_length=10, blank=True)
  165. ua = models.CharField(max_length=200, blank=True)
  166. class Channel(models.Model):
  167. code = models.UUIDField(default=uuid.uuid4, editable=False)
  168. user = models.ForeignKey(User)
  169. created = models.DateTimeField(auto_now_add=True)
  170. kind = models.CharField(max_length=20, choices=CHANNEL_KINDS)
  171. value = models.TextField(blank=True)
  172. email_verified = models.BooleanField(default=False)
  173. checks = models.ManyToManyField(Check)
  174. def assign_all_checks(self):
  175. checks = Check.objects.filter(user=self.user)
  176. self.checks.add(*checks)
  177. def make_token(self):
  178. seed = "%s%s" % (self.code, settings.SECRET_KEY)
  179. seed = seed.encode("utf8")
  180. return hashlib.sha1(seed).hexdigest()
  181. def send_verify_link(self):
  182. args = [self.code, self.make_token()]
  183. verify_link = reverse("hc-verify-email", args=args)
  184. verify_link = settings.SITE_ROOT + verify_link
  185. emails.verify_email(self.value, {"verify_link": verify_link})
  186. def get_unsub_link(self):
  187. args = [self.code, self.make_token()]
  188. verify_link = reverse("hc-unsubscribe-alerts", args=args)
  189. return settings.SITE_ROOT + verify_link
  190. @property
  191. def transport(self):
  192. if self.kind == "email":
  193. return transports.Email(self)
  194. elif self.kind == "webhook":
  195. return transports.Webhook(self)
  196. elif self.kind == "slack":
  197. return transports.Slack(self)
  198. elif self.kind == "hipchat":
  199. return transports.HipChat(self)
  200. elif self.kind == "pd":
  201. return transports.PagerDuty(self)
  202. elif self.kind == "victorops":
  203. return transports.VictorOps(self)
  204. elif self.kind == "pushbullet":
  205. return transports.Pushbullet(self)
  206. elif self.kind == "po":
  207. return transports.Pushover(self)
  208. elif self.kind == "opsgenie":
  209. return transports.OpsGenie(self)
  210. elif self.kind == "discord":
  211. return transports.Discord(self)
  212. else:
  213. raise NotImplementedError("Unknown channel kind: %s" % self.kind)
  214. def notify(self, check):
  215. if self.transport.is_noop(check):
  216. return "no-op"
  217. n = Notification(owner=check, channel=self)
  218. n.check_status = check.status
  219. n.error = "Sending"
  220. n.save()
  221. if self.kind == "email":
  222. error = self.transport.notify(check, n.bounce_url()) or ""
  223. else:
  224. error = self.transport.notify(check) or ""
  225. n.error = error
  226. n.save()
  227. return error
  228. @property
  229. def po_value(self):
  230. assert self.kind == "po"
  231. user_key, prio = self.value.split("|")
  232. prio = int(prio)
  233. return user_key, prio, PO_PRIORITIES[prio]
  234. @property
  235. def value_down(self):
  236. assert self.kind == "webhook"
  237. parts = self.value.split("\n")
  238. return parts[0]
  239. @property
  240. def value_up(self):
  241. assert self.kind == "webhook"
  242. parts = self.value.split("\n")
  243. return parts[1] if len(parts) > 1 else ""
  244. @property
  245. def post_data(self):
  246. assert self.kind == "webhook"
  247. parts = self.value.split("\n")
  248. return parts[2] if len(parts) > 2 else ""
  249. @property
  250. def slack_team(self):
  251. assert self.kind == "slack"
  252. if not self.value.startswith("{"):
  253. return None
  254. doc = json.loads(self.value)
  255. return doc["team_name"]
  256. @property
  257. def slack_channel(self):
  258. assert self.kind == "slack"
  259. if not self.value.startswith("{"):
  260. return None
  261. doc = json.loads(self.value)
  262. return doc["incoming_webhook"]["channel"]
  263. @property
  264. def slack_webhook_url(self):
  265. assert self.kind == "slack"
  266. if not self.value.startswith("{"):
  267. return self.value
  268. doc = json.loads(self.value)
  269. return doc["incoming_webhook"]["url"]
  270. @property
  271. def discord_webhook_url(self):
  272. assert self.kind == "discord"
  273. doc = json.loads(self.value)
  274. return doc["webhook"]["url"]
  275. @property
  276. def discord_webhook_id(self):
  277. assert self.kind == "discord"
  278. doc = json.loads(self.value)
  279. return doc["webhook"]["id"]
  280. def latest_notification(self):
  281. return Notification.objects.filter(channel=self).latest()
  282. class Notification(models.Model):
  283. class Meta:
  284. get_latest_by = "created"
  285. code = models.UUIDField(default=uuid.uuid4, null=True, editable=False)
  286. owner = models.ForeignKey(Check)
  287. check_status = models.CharField(max_length=6)
  288. channel = models.ForeignKey(Channel)
  289. created = models.DateTimeField(auto_now_add=True)
  290. error = models.CharField(max_length=200, blank=True)
  291. def bounce_url(self):
  292. return settings.SITE_ROOT + reverse("hc-api-bounce", args=[self.code])