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.

517 lines
16 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
7 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. ("pagertree", "PagerTree"),
  32. ("po", "Pushover"),
  33. ("pushbullet", "Pushbullet"),
  34. ("opsgenie", "OpsGenie"),
  35. ("victorops", "VictorOps"),
  36. ("discord", "Discord"),
  37. ("telegram", "Telegram"),
  38. ("sms", "SMS"),
  39. ("zendesk", "Zendesk"))
  40. PO_PRIORITIES = {
  41. -2: "lowest",
  42. -1: "low",
  43. 0: "normal",
  44. 1: "high",
  45. 2: "emergency"
  46. }
  47. def isostring(dt):
  48. """Convert the datetime to ISO 8601 format with no microseconds. """
  49. return dt.replace(microsecond=0).isoformat()
  50. class Check(models.Model):
  51. name = models.CharField(max_length=100, blank=True)
  52. tags = models.CharField(max_length=500, blank=True)
  53. code = models.UUIDField(default=uuid.uuid4, editable=False, db_index=True)
  54. user = models.ForeignKey(User, models.CASCADE, blank=True, null=True)
  55. created = models.DateTimeField(auto_now_add=True)
  56. kind = models.CharField(max_length=10, default="simple",
  57. choices=CHECK_KINDS)
  58. timeout = models.DurationField(default=DEFAULT_TIMEOUT)
  59. grace = models.DurationField(default=DEFAULT_GRACE)
  60. schedule = models.CharField(max_length=100, default="* * * * *")
  61. tz = models.CharField(max_length=36, default="UTC")
  62. n_pings = models.IntegerField(default=0)
  63. last_ping = models.DateTimeField(null=True, blank=True)
  64. last_ping_was_fail = models.NullBooleanField(default=False)
  65. has_confirmation_link = models.BooleanField(default=False)
  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 self.last_ping_was_fail:
  103. return "down"
  104. if now is None:
  105. now = timezone.now()
  106. grace_start = self.get_grace_start()
  107. grace_end = grace_start + self.grace
  108. if now >= grace_end:
  109. return "down"
  110. if now >= grace_start:
  111. return "grace"
  112. return "up"
  113. def get_alert_after(self):
  114. """ Return the datetime when check potentially goes down. """
  115. # For "fail" pings, sendalerts should the check right
  116. # after receiving the ping, without waiting for the grace time:
  117. if self.last_ping_was_fail:
  118. return self.last_ping
  119. return self.get_grace_start() + self.grace
  120. def assign_all_channels(self):
  121. if self.user:
  122. channels = Channel.objects.filter(user=self.user)
  123. self.channel_set.add(*channels)
  124. def tags_list(self):
  125. return [t.strip() for t in self.tags.split(" ") if t.strip()]
  126. def matches_tag_set(self, tag_set):
  127. return tag_set.issubset(self.tags_list())
  128. def to_dict(self):
  129. update_rel_url = reverse("hc-api-update", args=[self.code])
  130. pause_rel_url = reverse("hc-api-pause", args=[self.code])
  131. result = {
  132. "name": self.name,
  133. "ping_url": self.url(),
  134. "update_url": settings.SITE_ROOT + update_rel_url,
  135. "pause_url": settings.SITE_ROOT + pause_rel_url,
  136. "tags": self.tags,
  137. "grace": int(self.grace.total_seconds()),
  138. "n_pings": self.n_pings,
  139. "status": self.get_status()
  140. }
  141. if self.kind == "simple":
  142. result["timeout"] = int(self.timeout.total_seconds())
  143. elif self.kind == "cron":
  144. result["schedule"] = self.schedule
  145. result["tz"] = self.tz
  146. if self.last_ping:
  147. result["last_ping"] = isostring(self.last_ping)
  148. result["next_ping"] = isostring(self.get_grace_start())
  149. else:
  150. result["last_ping"] = None
  151. result["next_ping"] = None
  152. return result
  153. def ping(self, remote_addr, scheme, method, ua, body, is_fail=False):
  154. self.n_pings = models.F("n_pings") + 1
  155. self.last_ping = timezone.now()
  156. self.last_ping_was_fail = is_fail
  157. self.has_confirmation_link = "confirm" in str(body).lower()
  158. self.alert_after = self.get_alert_after()
  159. if self.status in ("new", "paused"):
  160. self.status = "up"
  161. self.save()
  162. self.refresh_from_db()
  163. ping = Ping(owner=self)
  164. ping.n = self.n_pings
  165. ping.fail = is_fail
  166. ping.remote_addr = remote_addr
  167. ping.scheme = scheme
  168. ping.method = method
  169. # If User-Agent is longer than 200 characters, truncate it:
  170. ping.ua = ua[:200]
  171. ping.body = body[:10000]
  172. ping.save()
  173. class Ping(models.Model):
  174. id = models.BigAutoField(primary_key=True)
  175. n = models.IntegerField(null=True)
  176. owner = models.ForeignKey(Check, models.CASCADE)
  177. created = models.DateTimeField(auto_now_add=True)
  178. fail = models.NullBooleanField(default=False)
  179. scheme = models.CharField(max_length=10, default="http")
  180. remote_addr = models.GenericIPAddressField(blank=True, null=True)
  181. method = models.CharField(max_length=10, blank=True)
  182. ua = models.CharField(max_length=200, blank=True)
  183. body = models.CharField(max_length=10000, blank=True, null=True)
  184. class Channel(models.Model):
  185. code = models.UUIDField(default=uuid.uuid4, editable=False)
  186. user = models.ForeignKey(User, models.CASCADE)
  187. created = models.DateTimeField(auto_now_add=True)
  188. kind = models.CharField(max_length=20, choices=CHANNEL_KINDS)
  189. value = models.TextField(blank=True)
  190. email_verified = models.BooleanField(default=False)
  191. checks = models.ManyToManyField(Check)
  192. def __str__(self):
  193. if self.kind == "email":
  194. return "Email to %s" % self.value
  195. elif self.kind == "sms":
  196. if self.sms_label:
  197. return "SMS to %s" % self.sms_label
  198. return "SMS to %s" % self.sms_number
  199. elif self.kind == "slack":
  200. return "Slack %s" % self.slack_channel
  201. elif self.kind == "telegram":
  202. return "Telegram %s" % self.telegram_name
  203. return self.get_kind_display()
  204. def assign_all_checks(self):
  205. checks = Check.objects.filter(user=self.user)
  206. self.checks.add(*checks)
  207. def make_token(self):
  208. seed = "%s%s" % (self.code, settings.SECRET_KEY)
  209. seed = seed.encode()
  210. return hashlib.sha1(seed).hexdigest()
  211. def send_verify_link(self):
  212. args = [self.code, self.make_token()]
  213. verify_link = reverse("hc-verify-email", args=args)
  214. verify_link = settings.SITE_ROOT + verify_link
  215. emails.verify_email(self.value, {"verify_link": verify_link})
  216. def get_unsub_link(self):
  217. args = [self.code, self.make_token()]
  218. verify_link = reverse("hc-unsubscribe-alerts", args=args)
  219. return settings.SITE_ROOT + verify_link
  220. @property
  221. def transport(self):
  222. if self.kind == "email":
  223. return transports.Email(self)
  224. elif self.kind == "webhook":
  225. return transports.Webhook(self)
  226. elif self.kind == "slack":
  227. return transports.Slack(self)
  228. elif self.kind == "hipchat":
  229. return transports.HipChat(self)
  230. elif self.kind == "pd":
  231. return transports.PagerDuty(self)
  232. elif self.kind == "pagertree":
  233. return transports.PagerTree(self)
  234. elif self.kind == "victorops":
  235. return transports.VictorOps(self)
  236. elif self.kind == "pushbullet":
  237. return transports.Pushbullet(self)
  238. elif self.kind == "po":
  239. return transports.Pushover(self)
  240. elif self.kind == "opsgenie":
  241. return transports.OpsGenie(self)
  242. elif self.kind == "discord":
  243. return transports.Discord(self)
  244. elif self.kind == "telegram":
  245. return transports.Telegram(self)
  246. elif self.kind == "sms":
  247. return transports.Sms(self)
  248. elif self.kind == "zendesk":
  249. return transports.Zendesk(self)
  250. else:
  251. raise NotImplementedError("Unknown channel kind: %s" % self.kind)
  252. def notify(self, check):
  253. if self.transport.is_noop(check):
  254. return "no-op"
  255. n = Notification(owner=check, channel=self)
  256. n.check_status = check.status
  257. n.error = "Sending"
  258. n.save()
  259. if self.kind == "email":
  260. error = self.transport.notify(check, n.bounce_url()) or ""
  261. else:
  262. error = self.transport.notify(check) or ""
  263. n.error = error
  264. n.save()
  265. return error
  266. @property
  267. def po_value(self):
  268. assert self.kind == "po"
  269. user_key, prio = self.value.split("|")
  270. prio = int(prio)
  271. return user_key, prio, PO_PRIORITIES[prio]
  272. @property
  273. def url_down(self):
  274. assert self.kind == "webhook"
  275. if not self.value.startswith("{"):
  276. parts = self.value.split("\n")
  277. return parts[0]
  278. doc = json.loads(self.value)
  279. return doc.get("url_down")
  280. @property
  281. def url_up(self):
  282. assert self.kind == "webhook"
  283. if not self.value.startswith("{"):
  284. parts = self.value.split("\n")
  285. return parts[1] if len(parts) > 1 else ""
  286. doc = json.loads(self.value)
  287. return doc.get("url_up")
  288. @property
  289. def post_data(self):
  290. assert self.kind == "webhook"
  291. if not self.value.startswith("{"):
  292. parts = self.value.split("\n")
  293. return parts[2] if len(parts) > 2 else ""
  294. doc = json.loads(self.value)
  295. return doc.get("post_data")
  296. @property
  297. def headers(self):
  298. assert self.kind == "webhook"
  299. if not self.value.startswith("{"):
  300. return {}
  301. doc = json.loads(self.value)
  302. return doc.get("headers", {})
  303. @property
  304. def slack_team(self):
  305. assert self.kind == "slack"
  306. if not self.value.startswith("{"):
  307. return None
  308. doc = json.loads(self.value)
  309. return doc["team_name"]
  310. @property
  311. def slack_channel(self):
  312. assert self.kind == "slack"
  313. if not self.value.startswith("{"):
  314. return None
  315. doc = json.loads(self.value)
  316. return doc["incoming_webhook"]["channel"]
  317. @property
  318. def slack_webhook_url(self):
  319. assert self.kind == "slack"
  320. if not self.value.startswith("{"):
  321. return self.value
  322. doc = json.loads(self.value)
  323. return doc["incoming_webhook"]["url"]
  324. @property
  325. def discord_webhook_url(self):
  326. assert self.kind == "discord"
  327. doc = json.loads(self.value)
  328. return doc["webhook"]["url"]
  329. @property
  330. def discord_webhook_id(self):
  331. assert self.kind == "discord"
  332. doc = json.loads(self.value)
  333. return doc["webhook"]["id"]
  334. @property
  335. def telegram_id(self):
  336. assert self.kind == "telegram"
  337. doc = json.loads(self.value)
  338. return doc.get("id")
  339. @property
  340. def telegram_type(self):
  341. assert self.kind == "telegram"
  342. doc = json.loads(self.value)
  343. return doc.get("type")
  344. @property
  345. def telegram_name(self):
  346. assert self.kind == "telegram"
  347. doc = json.loads(self.value)
  348. return doc.get("name")
  349. def refresh_hipchat_access_token(self):
  350. assert self.kind == "hipchat"
  351. if not self.value.startswith("{"):
  352. return # Don't have OAuth credentials
  353. doc = json.loads(self.value)
  354. if time.time() < doc.get("expires_at", 0):
  355. return # Current access token is still valid
  356. url = "https://api.hipchat.com/v2/oauth/token"
  357. auth = (doc["oauthId"], doc["oauthSecret"])
  358. r = requests.post(url, auth=auth, data={
  359. "grant_type": "client_credentials",
  360. "scope": "send_notification"
  361. })
  362. doc.update(r.json())
  363. doc["expires_at"] = int(time.time()) + doc["expires_in"] - 300
  364. self.value = json.dumps(doc)
  365. self.save()
  366. @property
  367. def hipchat_webhook_url(self):
  368. assert self.kind == "hipchat"
  369. if not self.value.startswith("{"):
  370. return self.value
  371. doc = json.loads(self.value)
  372. tmpl = "https://api.hipchat.com/v2/room/%s/notification?auth_token=%s"
  373. return tmpl % (doc["roomId"], doc.get("access_token"))
  374. @property
  375. def pd_service_key(self):
  376. assert self.kind == "pd"
  377. if not self.value.startswith("{"):
  378. return self.value
  379. doc = json.loads(self.value)
  380. return doc["service_key"]
  381. @property
  382. def pd_account(self):
  383. assert self.kind == "pd"
  384. if self.value.startswith("{"):
  385. doc = json.loads(self.value)
  386. return doc["account"]
  387. @property
  388. def zendesk_token(self):
  389. assert self.kind == "zendesk"
  390. doc = json.loads(self.value)
  391. return doc["access_token"]
  392. @property
  393. def zendesk_subdomain(self):
  394. assert self.kind == "zendesk"
  395. doc = json.loads(self.value)
  396. return doc["subdomain"]
  397. def latest_notification(self):
  398. return Notification.objects.filter(channel=self).latest()
  399. @property
  400. def sms_number(self):
  401. assert self.kind == "sms"
  402. if self.value.startswith("{"):
  403. doc = json.loads(self.value)
  404. return doc["value"]
  405. return self.value
  406. @property
  407. def sms_label(self):
  408. assert self.kind == "sms"
  409. if self.value.startswith("{"):
  410. doc = json.loads(self.value)
  411. return doc["label"]
  412. class Notification(models.Model):
  413. class Meta:
  414. get_latest_by = "created"
  415. code = models.UUIDField(default=uuid.uuid4, null=True, editable=False)
  416. owner = models.ForeignKey(Check, models.CASCADE)
  417. check_status = models.CharField(max_length=6)
  418. channel = models.ForeignKey(Channel, models.CASCADE)
  419. created = models.DateTimeField(auto_now_add=True)
  420. error = models.CharField(max_length=200, blank=True)
  421. def bounce_url(self):
  422. return settings.SITE_ROOT + reverse("hc-api-bounce", args=[self.code])