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.

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