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.

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