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.

466 lines
14 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. ("po", "Pushover"),
  32. ("pushbullet", "Pushbullet"),
  33. ("opsgenie", "OpsGenie"),
  34. ("victorops", "VictorOps"),
  35. ("discord", "Discord"),
  36. ("telegram", "Telegram"),
  37. ("sms", "SMS"))
  38. PO_PRIORITIES = {
  39. -2: "lowest",
  40. -1: "low",
  41. 0: "normal",
  42. 1: "high",
  43. 2: "emergency"
  44. }
  45. def isostring(dt):
  46. """Convert the datetime to ISO 8601 format with no microseconds. """
  47. return dt.replace(microsecond=0).isoformat()
  48. class Check(models.Model):
  49. class Meta:
  50. # sendalerts command will query using these
  51. index_together = ["status", "user", "alert_after"]
  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. 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_body = models.CharField(max_length=10000, blank=True)
  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 now is None:
  103. now = timezone.now()
  104. return "up" if self.get_grace_start() + self.grace > now else "down"
  105. def get_alert_after(self):
  106. """ Return the datetime when check potentially goes down. """
  107. return self.get_grace_start() + self.grace
  108. def in_grace_period(self):
  109. """ Return True if check is currently in grace period. """
  110. if self.status in ("new", "paused"):
  111. return False
  112. grace_start = self.get_grace_start()
  113. grace_end = grace_start + self.grace
  114. return grace_start < timezone.now() < grace_end
  115. def assign_all_channels(self):
  116. if self.user:
  117. channels = Channel.objects.filter(user=self.user)
  118. self.channel_set.add(*channels)
  119. def tags_list(self):
  120. return [t.strip() for t in self.tags.split(" ") if t.strip()]
  121. def matches_tag_set(self, tag_set):
  122. return tag_set.issubset(self.tags_list())
  123. def to_dict(self):
  124. update_rel_url = reverse("hc-api-update", args=[self.code])
  125. pause_rel_url = reverse("hc-api-pause", args=[self.code])
  126. result = {
  127. "name": self.name,
  128. "ping_url": self.url(),
  129. "update_url": settings.SITE_ROOT + update_rel_url,
  130. "pause_url": settings.SITE_ROOT + pause_rel_url,
  131. "tags": self.tags,
  132. "grace": int(self.grace.total_seconds()),
  133. "n_pings": self.n_pings,
  134. "status": self.get_status()
  135. }
  136. if self.kind == "simple":
  137. result["timeout"] = int(self.timeout.total_seconds())
  138. elif self.kind == "cron":
  139. result["schedule"] = self.schedule
  140. result["tz"] = self.tz
  141. if self.last_ping:
  142. result["last_ping"] = isostring(self.last_ping)
  143. result["next_ping"] = isostring(self.get_grace_start())
  144. else:
  145. result["last_ping"] = None
  146. result["next_ping"] = None
  147. return result
  148. def has_confirmation_link(self):
  149. return "confirm" in self.last_ping_body.lower()
  150. def ping(self, remote_addr, scheme, method, ua, body):
  151. self.n_pings = models.F("n_pings") + 1
  152. self.last_ping = timezone.now()
  153. self.last_ping_body = body[:10000]
  154. self.alert_after = self.get_alert_after()
  155. if self.status in ("new", "paused"):
  156. self.status = "up"
  157. self.save()
  158. self.refresh_from_db()
  159. ping = Ping(owner=self)
  160. ping.n = self.n_pings
  161. ping.remote_addr = remote_addr
  162. ping.scheme = scheme
  163. ping.method = method
  164. # If User-Agent is longer than 200 characters, truncate it:
  165. ping.ua = ua[:200]
  166. ping.save()
  167. class Ping(models.Model):
  168. n = models.IntegerField(null=True)
  169. owner = models.ForeignKey(Check, models.CASCADE)
  170. created = models.DateTimeField(auto_now_add=True)
  171. scheme = models.CharField(max_length=10, default="http")
  172. remote_addr = models.GenericIPAddressField(blank=True, null=True)
  173. method = models.CharField(max_length=10, blank=True)
  174. ua = models.CharField(max_length=200, blank=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 == "victorops":
  212. return transports.VictorOps(self)
  213. elif self.kind == "pushbullet":
  214. return transports.Pushbullet(self)
  215. elif self.kind == "po":
  216. return transports.Pushover(self)
  217. elif self.kind == "opsgenie":
  218. return transports.OpsGenie(self)
  219. elif self.kind == "discord":
  220. return transports.Discord(self)
  221. elif self.kind == "telegram":
  222. return transports.Telegram(self)
  223. elif self.kind == "sms":
  224. return transports.Sms(self)
  225. else:
  226. raise NotImplementedError("Unknown channel kind: %s" % self.kind)
  227. def notify(self, check):
  228. if self.transport.is_noop(check):
  229. return "no-op"
  230. n = Notification(owner=check, channel=self)
  231. n.check_status = check.status
  232. n.error = "Sending"
  233. n.save()
  234. if self.kind == "email":
  235. error = self.transport.notify(check, n.bounce_url()) or ""
  236. else:
  237. error = self.transport.notify(check) or ""
  238. n.error = error
  239. n.save()
  240. return error
  241. @property
  242. def po_value(self):
  243. assert self.kind == "po"
  244. user_key, prio = self.value.split("|")
  245. prio = int(prio)
  246. return user_key, prio, PO_PRIORITIES[prio]
  247. @property
  248. def url_down(self):
  249. assert self.kind == "webhook"
  250. if not self.value.startswith("{"):
  251. parts = self.value.split("\n")
  252. return parts[0]
  253. doc = json.loads(self.value)
  254. return doc.get("url_down")
  255. @property
  256. def url_up(self):
  257. assert self.kind == "webhook"
  258. if not self.value.startswith("{"):
  259. parts = self.value.split("\n")
  260. return parts[1] if len(parts) > 1 else ""
  261. doc = json.loads(self.value)
  262. return doc.get("url_up")
  263. @property
  264. def post_data(self):
  265. assert self.kind == "webhook"
  266. if not self.value.startswith("{"):
  267. parts = self.value.split("\n")
  268. return parts[2] if len(parts) > 2 else ""
  269. doc = json.loads(self.value)
  270. return doc.get("post_data")
  271. @property
  272. def headers(self):
  273. assert self.kind == "webhook"
  274. if not self.value.startswith("{"):
  275. return {}
  276. doc = json.loads(self.value)
  277. return doc.get("headers", {})
  278. @property
  279. def slack_team(self):
  280. assert self.kind == "slack"
  281. if not self.value.startswith("{"):
  282. return None
  283. doc = json.loads(self.value)
  284. return doc["team_name"]
  285. @property
  286. def slack_channel(self):
  287. assert self.kind == "slack"
  288. if not self.value.startswith("{"):
  289. return None
  290. doc = json.loads(self.value)
  291. return doc["incoming_webhook"]["channel"]
  292. @property
  293. def slack_webhook_url(self):
  294. assert self.kind == "slack"
  295. if not self.value.startswith("{"):
  296. return self.value
  297. doc = json.loads(self.value)
  298. return doc["incoming_webhook"]["url"]
  299. @property
  300. def discord_webhook_url(self):
  301. assert self.kind == "discord"
  302. doc = json.loads(self.value)
  303. return doc["webhook"]["url"]
  304. @property
  305. def discord_webhook_id(self):
  306. assert self.kind == "discord"
  307. doc = json.loads(self.value)
  308. return doc["webhook"]["id"]
  309. @property
  310. def telegram_id(self):
  311. assert self.kind == "telegram"
  312. doc = json.loads(self.value)
  313. return doc.get("id")
  314. @property
  315. def telegram_type(self):
  316. assert self.kind == "telegram"
  317. doc = json.loads(self.value)
  318. return doc.get("type")
  319. @property
  320. def telegram_name(self):
  321. assert self.kind == "telegram"
  322. doc = json.loads(self.value)
  323. return doc.get("name")
  324. def refresh_hipchat_access_token(self):
  325. assert self.kind == "hipchat"
  326. if not self.value.startswith("{"):
  327. return # Don't have OAuth credentials
  328. doc = json.loads(self.value)
  329. if time.time() < doc.get("expires_at", 0):
  330. return # Current access token is still valid
  331. url = "https://api.hipchat.com/v2/oauth/token"
  332. auth = (doc["oauthId"], doc["oauthSecret"])
  333. r = requests.post(url, auth=auth, data={
  334. "grant_type": "client_credentials",
  335. "scope": "send_notification"
  336. })
  337. doc.update(r.json())
  338. doc["expires_at"] = int(time.time()) + doc["expires_in"] - 300
  339. self.value = json.dumps(doc)
  340. self.save()
  341. @property
  342. def hipchat_webhook_url(self):
  343. assert self.kind == "hipchat"
  344. if not self.value.startswith("{"):
  345. return self.value
  346. doc = json.loads(self.value)
  347. tmpl = "https://api.hipchat.com/v2/room/%s/notification?auth_token=%s"
  348. return tmpl % (doc["roomId"], doc.get("access_token"))
  349. @property
  350. def pd_service_key(self):
  351. assert self.kind == "pd"
  352. if not self.value.startswith("{"):
  353. return self.value
  354. doc = json.loads(self.value)
  355. return doc["service_key"]
  356. @property
  357. def pd_account(self):
  358. assert self.kind == "pd"
  359. if self.value.startswith("{"):
  360. doc = json.loads(self.value)
  361. return doc["account"]
  362. def latest_notification(self):
  363. return Notification.objects.filter(channel=self).latest()
  364. class Notification(models.Model):
  365. class Meta:
  366. get_latest_by = "created"
  367. code = models.UUIDField(default=uuid.uuid4, null=True, editable=False)
  368. owner = models.ForeignKey(Check, models.CASCADE)
  369. check_status = models.CharField(max_length=6)
  370. channel = models.ForeignKey(Channel, models.CASCADE)
  371. created = models.DateTimeField(auto_now_add=True)
  372. error = models.CharField(max_length=200, blank=True)
  373. def bounce_url(self):
  374. return settings.SITE_ROOT + reverse("hc-api-bounce", args=[self.code])