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.

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