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.

544 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. channel_codes = [str(ch.code) for ch in self.channel_set.all()]
  134. result = {
  135. "name": self.name,
  136. "ping_url": self.url(),
  137. "update_url": settings.SITE_ROOT + update_rel_url,
  138. "pause_url": settings.SITE_ROOT + pause_rel_url,
  139. "tags": self.tags,
  140. "grace": int(self.grace.total_seconds()),
  141. "n_pings": self.n_pings,
  142. "status": self.get_status(),
  143. "channels": ",".join(sorted(channel_codes))
  144. }
  145. if self.kind == "simple":
  146. result["timeout"] = int(self.timeout.total_seconds())
  147. elif self.kind == "cron":
  148. result["schedule"] = self.schedule
  149. result["tz"] = self.tz
  150. if self.last_ping:
  151. result["last_ping"] = isostring(self.last_ping)
  152. result["next_ping"] = isostring(self.get_grace_start())
  153. else:
  154. result["last_ping"] = None
  155. result["next_ping"] = None
  156. return result
  157. def ping(self, remote_addr, scheme, method, ua, body, is_fail=False):
  158. self.n_pings = models.F("n_pings") + 1
  159. self.last_ping = timezone.now()
  160. self.last_ping_was_fail = is_fail
  161. self.has_confirmation_link = "confirm" in str(body).lower()
  162. self.alert_after = self.get_alert_after()
  163. if self.status in ("new", "paused"):
  164. self.status = "up"
  165. self.save()
  166. self.refresh_from_db()
  167. ping = Ping(owner=self)
  168. ping.n = self.n_pings
  169. ping.fail = is_fail
  170. ping.remote_addr = remote_addr
  171. ping.scheme = scheme
  172. ping.method = method
  173. # If User-Agent is longer than 200 characters, truncate it:
  174. ping.ua = ua[:200]
  175. ping.body = body[:10000]
  176. ping.save()
  177. class Ping(models.Model):
  178. id = models.BigAutoField(primary_key=True)
  179. n = models.IntegerField(null=True)
  180. owner = models.ForeignKey(Check, models.CASCADE)
  181. created = models.DateTimeField(auto_now_add=True)
  182. fail = models.NullBooleanField(default=False)
  183. scheme = models.CharField(max_length=10, default="http")
  184. remote_addr = models.GenericIPAddressField(blank=True, null=True)
  185. method = models.CharField(max_length=10, blank=True)
  186. ua = models.CharField(max_length=200, blank=True)
  187. body = models.CharField(max_length=10000, blank=True, null=True)
  188. class Channel(models.Model):
  189. code = models.UUIDField(default=uuid.uuid4, editable=False)
  190. user = models.ForeignKey(User, models.CASCADE)
  191. created = models.DateTimeField(auto_now_add=True)
  192. kind = models.CharField(max_length=20, choices=CHANNEL_KINDS)
  193. value = models.TextField(blank=True)
  194. email_verified = models.BooleanField(default=False)
  195. checks = models.ManyToManyField(Check)
  196. def __str__(self):
  197. if self.kind == "email":
  198. return "Email to %s" % self.value
  199. elif self.kind == "sms":
  200. if self.sms_label:
  201. return "SMS to %s" % self.sms_label
  202. return "SMS to %s" % self.sms_number
  203. elif self.kind == "slack":
  204. return "Slack %s" % self.slack_channel
  205. elif self.kind == "telegram":
  206. return "Telegram %s" % self.telegram_name
  207. return self.get_kind_display()
  208. def assign_all_checks(self):
  209. checks = Check.objects.filter(user=self.user)
  210. self.checks.add(*checks)
  211. def make_token(self):
  212. seed = "%s%s" % (self.code, settings.SECRET_KEY)
  213. seed = seed.encode()
  214. return hashlib.sha1(seed).hexdigest()
  215. def send_verify_link(self):
  216. args = [self.code, self.make_token()]
  217. verify_link = reverse("hc-verify-email", args=args)
  218. verify_link = settings.SITE_ROOT + verify_link
  219. emails.verify_email(self.value, {"verify_link": verify_link})
  220. def get_unsub_link(self):
  221. args = [self.code, self.make_token()]
  222. verify_link = reverse("hc-unsubscribe-alerts", args=args)
  223. return settings.SITE_ROOT + verify_link
  224. @property
  225. def transport(self):
  226. if self.kind == "email":
  227. return transports.Email(self)
  228. elif self.kind == "webhook":
  229. return transports.Webhook(self)
  230. elif self.kind == "slack":
  231. return transports.Slack(self)
  232. elif self.kind == "hipchat":
  233. return transports.HipChat(self)
  234. elif self.kind == "pd":
  235. return transports.PagerDuty(self)
  236. elif self.kind == "pagertree":
  237. return transports.PagerTree(self)
  238. elif self.kind == "victorops":
  239. return transports.VictorOps(self)
  240. elif self.kind == "pushbullet":
  241. return transports.Pushbullet(self)
  242. elif self.kind == "po":
  243. return transports.Pushover(self)
  244. elif self.kind == "opsgenie":
  245. return transports.OpsGenie(self)
  246. elif self.kind == "discord":
  247. return transports.Discord(self)
  248. elif self.kind == "telegram":
  249. return transports.Telegram(self)
  250. elif self.kind == "sms":
  251. return transports.Sms(self)
  252. elif self.kind == "zendesk":
  253. return transports.Zendesk(self)
  254. elif self.kind == "trello":
  255. return transports.Trello(self)
  256. else:
  257. raise NotImplementedError("Unknown channel kind: %s" % self.kind)
  258. def notify(self, check):
  259. if self.transport.is_noop(check):
  260. return "no-op"
  261. n = Notification(owner=check, channel=self)
  262. n.check_status = check.status
  263. n.error = "Sending"
  264. n.save()
  265. if self.kind == "email":
  266. error = self.transport.notify(check, n.bounce_url()) or ""
  267. else:
  268. error = self.transport.notify(check) or ""
  269. n.error = error
  270. n.save()
  271. return error
  272. @property
  273. def po_value(self):
  274. assert self.kind == "po"
  275. user_key, prio = self.value.split("|")
  276. prio = int(prio)
  277. return user_key, prio, PO_PRIORITIES[prio]
  278. @property
  279. def url_down(self):
  280. assert self.kind == "webhook"
  281. if not self.value.startswith("{"):
  282. parts = self.value.split("\n")
  283. return parts[0]
  284. doc = json.loads(self.value)
  285. return doc.get("url_down")
  286. @property
  287. def url_up(self):
  288. assert self.kind == "webhook"
  289. if not self.value.startswith("{"):
  290. parts = self.value.split("\n")
  291. return parts[1] if len(parts) > 1 else ""
  292. doc = json.loads(self.value)
  293. return doc.get("url_up")
  294. @property
  295. def post_data(self):
  296. assert self.kind == "webhook"
  297. if not self.value.startswith("{"):
  298. parts = self.value.split("\n")
  299. return parts[2] if len(parts) > 2 else ""
  300. doc = json.loads(self.value)
  301. return doc.get("post_data")
  302. @property
  303. def headers(self):
  304. assert self.kind == "webhook"
  305. if not self.value.startswith("{"):
  306. return {}
  307. doc = json.loads(self.value)
  308. return doc.get("headers", {})
  309. @property
  310. def slack_team(self):
  311. assert self.kind == "slack"
  312. if not self.value.startswith("{"):
  313. return None
  314. doc = json.loads(self.value)
  315. return doc["team_name"]
  316. @property
  317. def slack_channel(self):
  318. assert self.kind == "slack"
  319. if not self.value.startswith("{"):
  320. return None
  321. doc = json.loads(self.value)
  322. return doc["incoming_webhook"]["channel"]
  323. @property
  324. def slack_webhook_url(self):
  325. assert self.kind == "slack"
  326. if not self.value.startswith("{"):
  327. return self.value
  328. doc = json.loads(self.value)
  329. return doc["incoming_webhook"]["url"]
  330. @property
  331. def discord_webhook_url(self):
  332. assert self.kind == "discord"
  333. doc = json.loads(self.value)
  334. return doc["webhook"]["url"]
  335. @property
  336. def discord_webhook_id(self):
  337. assert self.kind == "discord"
  338. doc = json.loads(self.value)
  339. return doc["webhook"]["id"]
  340. @property
  341. def telegram_id(self):
  342. assert self.kind == "telegram"
  343. doc = json.loads(self.value)
  344. return doc.get("id")
  345. @property
  346. def telegram_type(self):
  347. assert self.kind == "telegram"
  348. doc = json.loads(self.value)
  349. return doc.get("type")
  350. @property
  351. def telegram_name(self):
  352. assert self.kind == "telegram"
  353. doc = json.loads(self.value)
  354. return doc.get("name")
  355. def refresh_hipchat_access_token(self):
  356. assert self.kind == "hipchat"
  357. if not self.value.startswith("{"):
  358. return # Don't have OAuth credentials
  359. doc = json.loads(self.value)
  360. if time.time() < doc.get("expires_at", 0):
  361. return # Current access token is still valid
  362. url = "https://api.hipchat.com/v2/oauth/token"
  363. auth = (doc["oauthId"], doc["oauthSecret"])
  364. r = requests.post(url, auth=auth, data={
  365. "grant_type": "client_credentials",
  366. "scope": "send_notification"
  367. })
  368. doc.update(r.json())
  369. doc["expires_at"] = int(time.time()) + doc["expires_in"] - 300
  370. self.value = json.dumps(doc)
  371. self.save()
  372. @property
  373. def hipchat_webhook_url(self):
  374. assert self.kind == "hipchat"
  375. if not self.value.startswith("{"):
  376. return self.value
  377. doc = json.loads(self.value)
  378. tmpl = "https://api.hipchat.com/v2/room/%s/notification?auth_token=%s"
  379. return tmpl % (doc["roomId"], doc.get("access_token"))
  380. @property
  381. def pd_service_key(self):
  382. assert self.kind == "pd"
  383. if not self.value.startswith("{"):
  384. return self.value
  385. doc = json.loads(self.value)
  386. return doc["service_key"]
  387. @property
  388. def pd_account(self):
  389. assert self.kind == "pd"
  390. if self.value.startswith("{"):
  391. doc = json.loads(self.value)
  392. return doc["account"]
  393. @property
  394. def zendesk_token(self):
  395. assert self.kind == "zendesk"
  396. doc = json.loads(self.value)
  397. return doc["access_token"]
  398. @property
  399. def zendesk_subdomain(self):
  400. assert self.kind == "zendesk"
  401. doc = json.loads(self.value)
  402. return doc["subdomain"]
  403. def latest_notification(self):
  404. return Notification.objects.filter(channel=self).latest()
  405. @property
  406. def sms_number(self):
  407. assert self.kind == "sms"
  408. if self.value.startswith("{"):
  409. doc = json.loads(self.value)
  410. return doc["value"]
  411. return self.value
  412. @property
  413. def sms_label(self):
  414. assert self.kind == "sms"
  415. if self.value.startswith("{"):
  416. doc = json.loads(self.value)
  417. return doc["label"]
  418. @property
  419. def trello_token(self):
  420. assert self.kind == "trello"
  421. if self.value.startswith("{"):
  422. doc = json.loads(self.value)
  423. return doc["token"]
  424. @property
  425. def trello_board_list(self):
  426. assert self.kind == "trello"
  427. if self.value.startswith("{"):
  428. doc = json.loads(self.value)
  429. return doc["board_name"], doc["list_name"]
  430. @property
  431. def trello_list_id(self):
  432. assert self.kind == "trello"
  433. if self.value.startswith("{"):
  434. doc = json.loads(self.value)
  435. return doc["list_id"]
  436. class Notification(models.Model):
  437. class Meta:
  438. get_latest_by = "created"
  439. code = models.UUIDField(default=uuid.uuid4, null=True, editable=False)
  440. owner = models.ForeignKey(Check, models.CASCADE)
  441. check_status = models.CharField(max_length=6)
  442. channel = models.ForeignKey(Channel, models.CASCADE)
  443. created = models.DateTimeField(auto_now_add=True)
  444. error = models.CharField(max_length=200, blank=True)
  445. def bounce_url(self):
  446. return settings.SITE_ROOT + reverse("hc-api-bounce", args=[self.code])