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.

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