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.

424 lines
13 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 time
  5. import uuid
  6. from datetime import datetime, timedelta as td
  7. from croniter import croniter
  8. from django.conf import settings
  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. import requests
  16. STATUSES = (
  17. ("up", "Up"),
  18. ("down", "Down"),
  19. ("new", "New"),
  20. ("paused", "Paused")
  21. )
  22. DEFAULT_TIMEOUT = td(days=1)
  23. DEFAULT_GRACE = td(hours=1)
  24. CHECK_KINDS = (("simple", "Simple"),
  25. ("cron", "Cron"))
  26. CHANNEL_KINDS = (("email", "Email"),
  27. ("webhook", "Webhook"),
  28. ("hipchat", "HipChat"),
  29. ("slack", "Slack"),
  30. ("pd", "PagerDuty"),
  31. ("po", "Pushover"),
  32. ("pushbullet", "Pushbullet"),
  33. ("opsgenie", "OpsGenie"),
  34. ("victorops", "VictorOps"),
  35. ("discord", "Discord"),
  36. ("telegram", "Telegram"),
  37. ("sms", "SMS"))
  38. PO_PRIORITIES = {
  39. -2: "lowest",
  40. -1: "low",
  41. 0: "normal",
  42. 1: "high",
  43. 2: "emergency"
  44. }
  45. def isostring(dt):
  46. """Convert the datetime to ISO 8601 format with no microseconds. """
  47. return dt.replace(microsecond=0).isoformat()
  48. class Check(models.Model):
  49. class Meta:
  50. # sendalerts command will query using these
  51. index_together = ["status", "user", "alert_after"]
  52. name = models.CharField(max_length=100, blank=True)
  53. tags = models.CharField(max_length=500, blank=True)
  54. code = models.UUIDField(default=uuid.uuid4, editable=False, db_index=True)
  55. user = models.ForeignKey(User, models.CASCADE, blank=True, null=True)
  56. created = models.DateTimeField(auto_now_add=True)
  57. kind = models.CharField(max_length=10, default="simple",
  58. choices=CHECK_KINDS)
  59. timeout = models.DurationField(default=DEFAULT_TIMEOUT)
  60. grace = models.DurationField(default=DEFAULT_GRACE)
  61. schedule = models.CharField(max_length=100, default="* * * * *")
  62. tz = models.CharField(max_length=36, default="UTC")
  63. n_pings = models.IntegerField(default=0)
  64. last_ping = models.DateTimeField(null=True, blank=True)
  65. last_ping_body = models.CharField(max_length=10000, blank=True)
  66. alert_after = models.DateTimeField(null=True, blank=True, editable=False)
  67. status = models.CharField(max_length=6, choices=STATUSES, default="new")
  68. def name_then_code(self):
  69. if self.name:
  70. return self.name
  71. return str(self.code)
  72. def url(self):
  73. return settings.PING_ENDPOINT + str(self.code)
  74. def log_url(self):
  75. return settings.SITE_ROOT + reverse("hc-log", args=[self.code])
  76. def email(self):
  77. return "%s@%s" % (self.code, settings.PING_EMAIL_DOMAIN)
  78. def send_alert(self):
  79. if self.status not in ("up", "down"):
  80. raise NotImplementedError("Unexpected status: %s" % self.status)
  81. errors = []
  82. for channel in self.channel_set.all():
  83. error = channel.notify(self)
  84. if error not in ("", "no-op"):
  85. errors.append((channel, error))
  86. return errors
  87. def get_grace_start(self):
  88. """ Return the datetime when grace period starts. """
  89. # The common case, grace starts after timeout
  90. if self.kind == "simple":
  91. return self.last_ping + self.timeout
  92. # The complex case, next ping is expected based on cron schedule
  93. with timezone.override(self.tz):
  94. last_naive = timezone.make_naive(self.last_ping)
  95. it = croniter(self.schedule, last_naive)
  96. next_naive = it.get_next(datetime)
  97. return timezone.make_aware(next_naive, is_dst=False)
  98. def get_status(self, now=None):
  99. """ Return "up" if the check is up or in grace, otherwise "down". """
  100. if self.status in ("new", "paused"):
  101. return self.status
  102. if now is None:
  103. now = timezone.now()
  104. return "up" if self.get_grace_start() + self.grace > now else "down"
  105. def get_alert_after(self):
  106. """ Return the datetime when check potentially goes down. """
  107. return self.get_grace_start() + self.grace
  108. def in_grace_period(self):
  109. """ Return True if check is currently in grace period. """
  110. if self.status in ("new", "paused"):
  111. return False
  112. grace_start = self.get_grace_start()
  113. grace_end = grace_start + self.grace
  114. return grace_start < timezone.now() < grace_end
  115. def assign_all_channels(self):
  116. if self.user:
  117. channels = Channel.objects.filter(user=self.user)
  118. self.channel_set.add(*channels)
  119. def tags_list(self):
  120. return [t.strip() for t in self.tags.split(" ") if t.strip()]
  121. def matches_tag_set(self, tag_set):
  122. return tag_set.issubset(self.tags_list())
  123. def to_dict(self):
  124. update_rel_url = reverse("hc-api-update", args=[self.code])
  125. pause_rel_url = reverse("hc-api-pause", args=[self.code])
  126. result = {
  127. "name": self.name,
  128. "ping_url": self.url(),
  129. "update_url": settings.SITE_ROOT + update_rel_url,
  130. "pause_url": settings.SITE_ROOT + pause_rel_url,
  131. "tags": self.tags,
  132. "grace": int(self.grace.total_seconds()),
  133. "n_pings": self.n_pings,
  134. "status": self.get_status()
  135. }
  136. if self.kind == "simple":
  137. result["timeout"] = int(self.timeout.total_seconds())
  138. elif self.kind == "cron":
  139. result["schedule"] = self.schedule
  140. result["tz"] = self.tz
  141. if self.last_ping:
  142. result["last_ping"] = isostring(self.last_ping)
  143. result["next_ping"] = isostring(self.get_grace_start())
  144. else:
  145. result["last_ping"] = None
  146. result["next_ping"] = None
  147. return result
  148. def has_confirmation_link(self):
  149. return "confirm" in self.last_ping_body.lower()
  150. class Ping(models.Model):
  151. n = models.IntegerField(null=True)
  152. owner = models.ForeignKey(Check, models.CASCADE)
  153. created = models.DateTimeField(auto_now_add=True)
  154. scheme = models.CharField(max_length=10, default="http")
  155. remote_addr = models.GenericIPAddressField(blank=True, null=True)
  156. method = models.CharField(max_length=10, blank=True)
  157. ua = models.CharField(max_length=200, blank=True)
  158. class Channel(models.Model):
  159. code = models.UUIDField(default=uuid.uuid4, editable=False)
  160. user = models.ForeignKey(User, models.CASCADE)
  161. created = models.DateTimeField(auto_now_add=True)
  162. kind = models.CharField(max_length=20, choices=CHANNEL_KINDS)
  163. value = models.TextField(blank=True)
  164. email_verified = models.BooleanField(default=False)
  165. checks = models.ManyToManyField(Check)
  166. def assign_all_checks(self):
  167. checks = Check.objects.filter(user=self.user)
  168. self.checks.add(*checks)
  169. def make_token(self):
  170. seed = "%s%s" % (self.code, settings.SECRET_KEY)
  171. seed = seed.encode("utf8")
  172. return hashlib.sha1(seed).hexdigest()
  173. def send_verify_link(self):
  174. args = [self.code, self.make_token()]
  175. verify_link = reverse("hc-verify-email", args=args)
  176. verify_link = settings.SITE_ROOT + verify_link
  177. emails.verify_email(self.value, {"verify_link": verify_link})
  178. def get_unsub_link(self):
  179. args = [self.code, self.make_token()]
  180. verify_link = reverse("hc-unsubscribe-alerts", args=args)
  181. return settings.SITE_ROOT + verify_link
  182. @property
  183. def transport(self):
  184. if self.kind == "email":
  185. return transports.Email(self)
  186. elif self.kind == "webhook":
  187. return transports.Webhook(self)
  188. elif self.kind == "slack":
  189. return transports.Slack(self)
  190. elif self.kind == "hipchat":
  191. return transports.HipChat(self)
  192. elif self.kind == "pd":
  193. return transports.PagerDuty(self)
  194. elif self.kind == "victorops":
  195. return transports.VictorOps(self)
  196. elif self.kind == "pushbullet":
  197. return transports.Pushbullet(self)
  198. elif self.kind == "po":
  199. return transports.Pushover(self)
  200. elif self.kind == "opsgenie":
  201. return transports.OpsGenie(self)
  202. elif self.kind == "discord":
  203. return transports.Discord(self)
  204. elif self.kind == "telegram":
  205. return transports.Telegram(self)
  206. elif self.kind == "sms":
  207. return transports.Sms(self)
  208. else:
  209. raise NotImplementedError("Unknown channel kind: %s" % self.kind)
  210. def notify(self, check):
  211. if self.transport.is_noop(check):
  212. return "no-op"
  213. n = Notification(owner=check, channel=self)
  214. n.check_status = check.status
  215. n.error = "Sending"
  216. n.save()
  217. if self.kind == "email":
  218. error = self.transport.notify(check, n.bounce_url()) or ""
  219. else:
  220. error = self.transport.notify(check) or ""
  221. n.error = error
  222. n.save()
  223. return error
  224. @property
  225. def po_value(self):
  226. assert self.kind == "po"
  227. user_key, prio = self.value.split("|")
  228. prio = int(prio)
  229. return user_key, prio, PO_PRIORITIES[prio]
  230. @property
  231. def value_down(self):
  232. assert self.kind == "webhook"
  233. parts = self.value.split("\n")
  234. return parts[0]
  235. @property
  236. def value_up(self):
  237. assert self.kind == "webhook"
  238. parts = self.value.split("\n")
  239. return parts[1] if len(parts) > 1 else ""
  240. @property
  241. def post_data(self):
  242. assert self.kind == "webhook"
  243. parts = self.value.split("\n")
  244. return parts[2] if len(parts) > 2 else ""
  245. @property
  246. def slack_team(self):
  247. assert self.kind == "slack"
  248. if not self.value.startswith("{"):
  249. return None
  250. doc = json.loads(self.value)
  251. return doc["team_name"]
  252. @property
  253. def slack_channel(self):
  254. assert self.kind == "slack"
  255. if not self.value.startswith("{"):
  256. return None
  257. doc = json.loads(self.value)
  258. return doc["incoming_webhook"]["channel"]
  259. @property
  260. def slack_webhook_url(self):
  261. assert self.kind == "slack"
  262. if not self.value.startswith("{"):
  263. return self.value
  264. doc = json.loads(self.value)
  265. return doc["incoming_webhook"]["url"]
  266. @property
  267. def discord_webhook_url(self):
  268. assert self.kind == "discord"
  269. doc = json.loads(self.value)
  270. return doc["webhook"]["url"]
  271. @property
  272. def discord_webhook_id(self):
  273. assert self.kind == "discord"
  274. doc = json.loads(self.value)
  275. return doc["webhook"]["id"]
  276. @property
  277. def telegram_id(self):
  278. assert self.kind == "telegram"
  279. doc = json.loads(self.value)
  280. return doc.get("id")
  281. @property
  282. def telegram_type(self):
  283. assert self.kind == "telegram"
  284. doc = json.loads(self.value)
  285. return doc.get("type")
  286. @property
  287. def telegram_name(self):
  288. assert self.kind == "telegram"
  289. doc = json.loads(self.value)
  290. return doc.get("name")
  291. def refresh_hipchat_access_token(self):
  292. assert self.kind == "hipchat"
  293. if not self.value.startswith("{"):
  294. return # Don't have OAuth credentials
  295. doc = json.loads(self.value)
  296. if time.time() < doc.get("expires_at", 0):
  297. return # Current access token is still valid
  298. url = "https://api.hipchat.com/v2/oauth/token"
  299. auth = (doc["oauthId"], doc["oauthSecret"])
  300. r = requests.post(url, auth=auth, data={
  301. "grant_type": "client_credentials",
  302. "scope": "send_notification"
  303. })
  304. doc.update(r.json())
  305. doc["expires_at"] = int(time.time()) + doc["expires_in"] - 300
  306. self.value = json.dumps(doc)
  307. self.save()
  308. @property
  309. def hipchat_webhook_url(self):
  310. assert self.kind == "hipchat"
  311. if not self.value.startswith("{"):
  312. return self.value
  313. doc = json.loads(self.value)
  314. tmpl = "https://api.hipchat.com/v2/room/%s/notification?auth_token=%s"
  315. return tmpl % (doc["roomId"], doc.get("access_token"))
  316. @property
  317. def pd_service_key(self):
  318. assert self.kind == "pd"
  319. if not self.value.startswith("{"):
  320. return self.value
  321. doc = json.loads(self.value)
  322. return doc["service_key"]
  323. @property
  324. def pd_account(self):
  325. assert self.kind == "pd"
  326. if self.value.startswith("{"):
  327. doc = json.loads(self.value)
  328. return doc["account"]
  329. def latest_notification(self):
  330. return Notification.objects.filter(channel=self).latest()
  331. class Notification(models.Model):
  332. class Meta:
  333. get_latest_by = "created"
  334. code = models.UUIDField(default=uuid.uuid4, null=True, editable=False)
  335. owner = models.ForeignKey(Check, models.CASCADE)
  336. check_status = models.CharField(max_length=6)
  337. channel = models.ForeignKey(Channel, models.CASCADE)
  338. created = models.DateTimeField(auto_now_add=True)
  339. error = models.CharField(max_length=200, blank=True)
  340. def bounce_url(self):
  341. return settings.SITE_ROOT + reverse("hc-api-bounce", args=[self.code])