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.

505 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
  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. return "up" if self.get_grace_start() + self.grace > now else "down"
  107. def get_alert_after(self):
  108. """ Return the datetime when check potentially goes down. """
  109. # For "fail" pings, sendalerts should the check right
  110. # after receiving the ping, without waiting for the grace time:
  111. if self.last_ping_was_fail:
  112. return self.last_ping
  113. return self.get_grace_start() + self.grace
  114. def in_grace_period(self):
  115. """ Return True if check is currently in grace period. """
  116. if self.status in ("new", "paused"):
  117. return False
  118. grace_start = self.get_grace_start()
  119. grace_end = grace_start + self.grace
  120. return grace_start < timezone.now() < grace_end
  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 assign_all_checks(self):
  194. checks = Check.objects.filter(user=self.user)
  195. self.checks.add(*checks)
  196. def make_token(self):
  197. seed = "%s%s" % (self.code, settings.SECRET_KEY)
  198. seed = seed.encode()
  199. return hashlib.sha1(seed).hexdigest()
  200. def send_verify_link(self):
  201. args = [self.code, self.make_token()]
  202. verify_link = reverse("hc-verify-email", args=args)
  203. verify_link = settings.SITE_ROOT + verify_link
  204. emails.verify_email(self.value, {"verify_link": verify_link})
  205. def get_unsub_link(self):
  206. args = [self.code, self.make_token()]
  207. verify_link = reverse("hc-unsubscribe-alerts", args=args)
  208. return settings.SITE_ROOT + verify_link
  209. @property
  210. def transport(self):
  211. if self.kind == "email":
  212. return transports.Email(self)
  213. elif self.kind == "webhook":
  214. return transports.Webhook(self)
  215. elif self.kind == "slack":
  216. return transports.Slack(self)
  217. elif self.kind == "hipchat":
  218. return transports.HipChat(self)
  219. elif self.kind == "pd":
  220. return transports.PagerDuty(self)
  221. elif self.kind == "pagertree":
  222. return transports.PagerTree(self)
  223. elif self.kind == "victorops":
  224. return transports.VictorOps(self)
  225. elif self.kind == "pushbullet":
  226. return transports.Pushbullet(self)
  227. elif self.kind == "po":
  228. return transports.Pushover(self)
  229. elif self.kind == "opsgenie":
  230. return transports.OpsGenie(self)
  231. elif self.kind == "discord":
  232. return transports.Discord(self)
  233. elif self.kind == "telegram":
  234. return transports.Telegram(self)
  235. elif self.kind == "sms":
  236. return transports.Sms(self)
  237. elif self.kind == "zendesk":
  238. return transports.Zendesk(self)
  239. else:
  240. raise NotImplementedError("Unknown channel kind: %s" % self.kind)
  241. def notify(self, check):
  242. if self.transport.is_noop(check):
  243. return "no-op"
  244. n = Notification(owner=check, channel=self)
  245. n.check_status = check.status
  246. n.error = "Sending"
  247. n.save()
  248. if self.kind == "email":
  249. error = self.transport.notify(check, n.bounce_url()) or ""
  250. else:
  251. error = self.transport.notify(check) or ""
  252. n.error = error
  253. n.save()
  254. return error
  255. @property
  256. def po_value(self):
  257. assert self.kind == "po"
  258. user_key, prio = self.value.split("|")
  259. prio = int(prio)
  260. return user_key, prio, PO_PRIORITIES[prio]
  261. @property
  262. def url_down(self):
  263. assert self.kind == "webhook"
  264. if not self.value.startswith("{"):
  265. parts = self.value.split("\n")
  266. return parts[0]
  267. doc = json.loads(self.value)
  268. return doc.get("url_down")
  269. @property
  270. def url_up(self):
  271. assert self.kind == "webhook"
  272. if not self.value.startswith("{"):
  273. parts = self.value.split("\n")
  274. return parts[1] if len(parts) > 1 else ""
  275. doc = json.loads(self.value)
  276. return doc.get("url_up")
  277. @property
  278. def post_data(self):
  279. assert self.kind == "webhook"
  280. if not self.value.startswith("{"):
  281. parts = self.value.split("\n")
  282. return parts[2] if len(parts) > 2 else ""
  283. doc = json.loads(self.value)
  284. return doc.get("post_data")
  285. @property
  286. def headers(self):
  287. assert self.kind == "webhook"
  288. if not self.value.startswith("{"):
  289. return {}
  290. doc = json.loads(self.value)
  291. return doc.get("headers", {})
  292. @property
  293. def slack_team(self):
  294. assert self.kind == "slack"
  295. if not self.value.startswith("{"):
  296. return None
  297. doc = json.loads(self.value)
  298. return doc["team_name"]
  299. @property
  300. def slack_channel(self):
  301. assert self.kind == "slack"
  302. if not self.value.startswith("{"):
  303. return None
  304. doc = json.loads(self.value)
  305. return doc["incoming_webhook"]["channel"]
  306. @property
  307. def slack_webhook_url(self):
  308. assert self.kind == "slack"
  309. if not self.value.startswith("{"):
  310. return self.value
  311. doc = json.loads(self.value)
  312. return doc["incoming_webhook"]["url"]
  313. @property
  314. def discord_webhook_url(self):
  315. assert self.kind == "discord"
  316. doc = json.loads(self.value)
  317. return doc["webhook"]["url"]
  318. @property
  319. def discord_webhook_id(self):
  320. assert self.kind == "discord"
  321. doc = json.loads(self.value)
  322. return doc["webhook"]["id"]
  323. @property
  324. def telegram_id(self):
  325. assert self.kind == "telegram"
  326. doc = json.loads(self.value)
  327. return doc.get("id")
  328. @property
  329. def telegram_type(self):
  330. assert self.kind == "telegram"
  331. doc = json.loads(self.value)
  332. return doc.get("type")
  333. @property
  334. def telegram_name(self):
  335. assert self.kind == "telegram"
  336. doc = json.loads(self.value)
  337. return doc.get("name")
  338. def refresh_hipchat_access_token(self):
  339. assert self.kind == "hipchat"
  340. if not self.value.startswith("{"):
  341. return # Don't have OAuth credentials
  342. doc = json.loads(self.value)
  343. if time.time() < doc.get("expires_at", 0):
  344. return # Current access token is still valid
  345. url = "https://api.hipchat.com/v2/oauth/token"
  346. auth = (doc["oauthId"], doc["oauthSecret"])
  347. r = requests.post(url, auth=auth, data={
  348. "grant_type": "client_credentials",
  349. "scope": "send_notification"
  350. })
  351. doc.update(r.json())
  352. doc["expires_at"] = int(time.time()) + doc["expires_in"] - 300
  353. self.value = json.dumps(doc)
  354. self.save()
  355. @property
  356. def hipchat_webhook_url(self):
  357. assert self.kind == "hipchat"
  358. if not self.value.startswith("{"):
  359. return self.value
  360. doc = json.loads(self.value)
  361. tmpl = "https://api.hipchat.com/v2/room/%s/notification?auth_token=%s"
  362. return tmpl % (doc["roomId"], doc.get("access_token"))
  363. @property
  364. def pd_service_key(self):
  365. assert self.kind == "pd"
  366. if not self.value.startswith("{"):
  367. return self.value
  368. doc = json.loads(self.value)
  369. return doc["service_key"]
  370. @property
  371. def pd_account(self):
  372. assert self.kind == "pd"
  373. if self.value.startswith("{"):
  374. doc = json.loads(self.value)
  375. return doc["account"]
  376. @property
  377. def zendesk_token(self):
  378. assert self.kind == "zendesk"
  379. doc = json.loads(self.value)
  380. return doc["access_token"]
  381. @property
  382. def zendesk_subdomain(self):
  383. assert self.kind == "zendesk"
  384. doc = json.loads(self.value)
  385. return doc["subdomain"]
  386. def latest_notification(self):
  387. return Notification.objects.filter(channel=self).latest()
  388. @property
  389. def sms_number(self):
  390. assert self.kind == "sms"
  391. if self.value.startswith("{"):
  392. doc = json.loads(self.value)
  393. return doc["value"]
  394. return self.value
  395. @property
  396. def sms_label(self):
  397. assert self.kind == "sms"
  398. if self.value.startswith("{"):
  399. doc = json.loads(self.value)
  400. return doc["label"]
  401. class Notification(models.Model):
  402. class Meta:
  403. get_latest_by = "created"
  404. code = models.UUIDField(default=uuid.uuid4, null=True, editable=False)
  405. owner = models.ForeignKey(Check, models.CASCADE)
  406. check_status = models.CharField(max_length=6)
  407. channel = models.ForeignKey(Channel, models.CASCADE)
  408. created = models.DateTimeField(auto_now_add=True)
  409. error = models.CharField(max_length=200, blank=True)
  410. def bounce_url(self):
  411. return settings.SITE_ROOT + reverse("hc-api-bounce", args=[self.code])