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.

595 lines
19 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
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. import pytz
  17. STATUSES = (
  18. ("up", "Up"),
  19. ("down", "Down"),
  20. ("new", "New"),
  21. ("paused", "Paused")
  22. )
  23. DEFAULT_TIMEOUT = td(days=1)
  24. DEFAULT_GRACE = td(hours=1)
  25. NEVER = datetime(3000, 1, 1, tzinfo=pytz.UTC)
  26. CHECK_KINDS = (("simple", "Simple"),
  27. ("cron", "Cron"))
  28. CHANNEL_KINDS = (("email", "Email"),
  29. ("webhook", "Webhook"),
  30. ("hipchat", "HipChat"),
  31. ("slack", "Slack"),
  32. ("pd", "PagerDuty"),
  33. ("pagertree", "PagerTree"),
  34. ("po", "Pushover"),
  35. ("pushbullet", "Pushbullet"),
  36. ("opsgenie", "OpsGenie"),
  37. ("victorops", "VictorOps"),
  38. ("discord", "Discord"),
  39. ("telegram", "Telegram"),
  40. ("sms", "SMS"),
  41. ("zendesk", "Zendesk"),
  42. ("trello", "Trello"))
  43. PO_PRIORITIES = {
  44. -2: "lowest",
  45. -1: "low",
  46. 0: "normal",
  47. 1: "high",
  48. 2: "emergency"
  49. }
  50. def isostring(dt):
  51. """Convert the datetime to ISO 8601 format with no microseconds. """
  52. if dt:
  53. return dt.replace(microsecond=0).isoformat()
  54. class Check(models.Model):
  55. name = models.CharField(max_length=100, blank=True)
  56. tags = models.CharField(max_length=500, blank=True)
  57. code = models.UUIDField(default=uuid.uuid4, editable=False, db_index=True)
  58. desc = models.TextField(blank=True)
  59. user = models.ForeignKey(User, models.CASCADE, blank=True, null=True)
  60. created = models.DateTimeField(auto_now_add=True)
  61. kind = models.CharField(max_length=10, default="simple",
  62. choices=CHECK_KINDS)
  63. timeout = models.DurationField(default=DEFAULT_TIMEOUT)
  64. grace = models.DurationField(default=DEFAULT_GRACE)
  65. schedule = models.CharField(max_length=100, default="* * * * *")
  66. tz = models.CharField(max_length=36, default="UTC")
  67. n_pings = models.IntegerField(default=0)
  68. last_ping = models.DateTimeField(null=True, blank=True)
  69. last_start = models.DateTimeField(null=True, blank=True)
  70. last_ping_was_fail = models.NullBooleanField(default=False)
  71. has_confirmation_link = models.BooleanField(default=False)
  72. alert_after = models.DateTimeField(null=True, blank=True, editable=False)
  73. status = models.CharField(max_length=6, choices=STATUSES, default="new")
  74. def name_then_code(self):
  75. if self.name:
  76. return self.name
  77. return str(self.code)
  78. def url(self):
  79. return settings.PING_ENDPOINT + str(self.code)
  80. def details_url(self):
  81. return settings.SITE_ROOT + reverse("hc-details", args=[self.code])
  82. def email(self):
  83. return "%s@%s" % (self.code, settings.PING_EMAIL_DOMAIN)
  84. def send_alert(self, flip):
  85. if flip.new_status == "up" and flip.old_status in ("new", "paused"):
  86. # Don't send alerts on new->up and paused->up transitions
  87. return []
  88. if flip.new_status not in ("up", "down"):
  89. raise NotImplementedError("Unexpected status: %s" % self.status)
  90. errors = []
  91. for channel in self.channel_set.all():
  92. error = channel.notify(self)
  93. if error not in ("", "no-op"):
  94. errors.append((channel, error))
  95. return errors
  96. def get_grace_start(self):
  97. """ Return the datetime when the grace period starts.
  98. If the check is currently new, paused or down, return None.
  99. """
  100. # NEVER is a constant sentinel value (year 3000).
  101. # Using None instead would make the logic clunky.
  102. result = NEVER
  103. if self.kind == "simple" and self.status == "up":
  104. result = self.last_ping + self.timeout
  105. elif self.kind == "cron" and self.status == "up":
  106. # The complex case, next ping is expected based on cron schedule.
  107. # Don't convert to naive datetimes (and so avoid ambiguities around
  108. # DST transitions). Croniter will handle the timezone-aware datetimes.
  109. zone = pytz.timezone(self.tz)
  110. last_local = timezone.localtime(self.last_ping, zone)
  111. it = croniter(self.schedule, last_local)
  112. result = it.next(datetime)
  113. if self.last_start:
  114. result = min(result, self.last_start)
  115. if result != NEVER:
  116. return result
  117. def is_down(self):
  118. """ Return True if the check is currently in alert state. """
  119. alert_after = self.get_alert_after()
  120. if alert_after is None:
  121. return False
  122. return timezone.now() >= self.get_alert_after()
  123. def get_status(self, now=None):
  124. """ Return current status for display. """
  125. if now is None:
  126. now = timezone.now()
  127. if self.last_start:
  128. if now >= self.last_start + self.grace:
  129. return "down"
  130. else:
  131. return "started"
  132. if self.status in ("new", "paused", "down"):
  133. return self.status
  134. grace_start = self.get_grace_start()
  135. grace_end = grace_start + self.grace
  136. if now >= grace_end:
  137. return "down"
  138. if now >= grace_start:
  139. return "grace"
  140. return "up"
  141. def get_alert_after(self):
  142. """ Return the datetime when check potentially goes down. """
  143. grace_start = self.get_grace_start()
  144. if grace_start is not None:
  145. return grace_start + self.grace
  146. def assign_all_channels(self):
  147. if self.user:
  148. channels = Channel.objects.filter(user=self.user)
  149. self.channel_set.add(*channels)
  150. def tags_list(self):
  151. return [t.strip() for t in self.tags.split(" ") if t.strip()]
  152. def matches_tag_set(self, tag_set):
  153. return tag_set.issubset(self.tags_list())
  154. def to_dict(self):
  155. update_rel_url = reverse("hc-api-update", args=[self.code])
  156. pause_rel_url = reverse("hc-api-pause", args=[self.code])
  157. channel_codes = [str(ch.code) for ch in self.channel_set.all()]
  158. result = {
  159. "name": self.name,
  160. "ping_url": self.url(),
  161. "update_url": settings.SITE_ROOT + update_rel_url,
  162. "pause_url": settings.SITE_ROOT + pause_rel_url,
  163. "tags": self.tags,
  164. "grace": int(self.grace.total_seconds()),
  165. "n_pings": self.n_pings,
  166. "status": self.get_status(),
  167. "channels": ",".join(sorted(channel_codes)),
  168. "last_ping": isostring(self.last_ping),
  169. "next_ping": isostring(self.get_grace_start())
  170. }
  171. if self.kind == "simple":
  172. result["timeout"] = int(self.timeout.total_seconds())
  173. elif self.kind == "cron":
  174. result["schedule"] = self.schedule
  175. result["tz"] = self.tz
  176. return result
  177. def ping(self, remote_addr, scheme, method, ua, body, action):
  178. if action == "start":
  179. # If we receive multiple start events in a row,
  180. # we remember the first one, not the last one
  181. if self.last_start is None:
  182. self.last_start = timezone.now()
  183. # DOn't update "last_ping" field.
  184. else:
  185. self.last_start = None
  186. self.last_ping = timezone.now()
  187. self.last_ping_was_fail = action == "fail"
  188. new_status = "down" if action == "fail" else "up"
  189. if self.status != new_status:
  190. flip = Flip(owner=self)
  191. flip.created = self.last_ping
  192. flip.old_status = self.status
  193. flip.new_status = new_status
  194. flip.save()
  195. self.status = new_status
  196. self.alert_after = self.get_alert_after()
  197. self.n_pings = models.F("n_pings") + 1
  198. self.has_confirmation_link = "confirm" in str(body).lower()
  199. self.save()
  200. self.refresh_from_db()
  201. ping = Ping(owner=self)
  202. ping.n = self.n_pings
  203. ping.start = action == "start"
  204. ping.fail = action == "fail"
  205. ping.remote_addr = remote_addr
  206. ping.scheme = scheme
  207. ping.method = method
  208. # If User-Agent is longer than 200 characters, truncate it:
  209. ping.ua = ua[:200]
  210. ping.body = body[:10000]
  211. ping.save()
  212. class Ping(models.Model):
  213. id = models.BigAutoField(primary_key=True)
  214. n = models.IntegerField(null=True)
  215. owner = models.ForeignKey(Check, models.CASCADE)
  216. created = models.DateTimeField(auto_now_add=True)
  217. start = models.NullBooleanField(default=False)
  218. fail = models.NullBooleanField(default=False)
  219. scheme = models.CharField(max_length=10, default="http")
  220. remote_addr = models.GenericIPAddressField(blank=True, null=True)
  221. method = models.CharField(max_length=10, blank=True)
  222. ua = models.CharField(max_length=200, blank=True)
  223. body = models.CharField(max_length=10000, blank=True, null=True)
  224. class Channel(models.Model):
  225. name = models.CharField(max_length=100, blank=True)
  226. code = models.UUIDField(default=uuid.uuid4, editable=False)
  227. user = models.ForeignKey(User, models.CASCADE)
  228. created = models.DateTimeField(auto_now_add=True)
  229. kind = models.CharField(max_length=20, choices=CHANNEL_KINDS)
  230. value = models.TextField(blank=True)
  231. email_verified = models.BooleanField(default=False)
  232. checks = models.ManyToManyField(Check)
  233. def __str__(self):
  234. if self.name:
  235. return self.name
  236. if self.kind == "email":
  237. return "Email to %s" % self.value
  238. elif self.kind == "sms":
  239. return "SMS to %s" % self.sms_number
  240. elif self.kind == "slack":
  241. return "Slack %s" % self.slack_channel
  242. elif self.kind == "telegram":
  243. return "Telegram %s" % self.telegram_name
  244. return self.get_kind_display()
  245. def to_dict(self):
  246. return {
  247. "id": str(self.code),
  248. "name": self.name,
  249. "kind": self.kind
  250. }
  251. def assign_all_checks(self):
  252. checks = Check.objects.filter(user=self.user)
  253. self.checks.add(*checks)
  254. def make_token(self):
  255. seed = "%s%s" % (self.code, settings.SECRET_KEY)
  256. seed = seed.encode()
  257. return hashlib.sha1(seed).hexdigest()
  258. def send_verify_link(self):
  259. args = [self.code, self.make_token()]
  260. verify_link = reverse("hc-verify-email", args=args)
  261. verify_link = settings.SITE_ROOT + verify_link
  262. emails.verify_email(self.value, {"verify_link": verify_link})
  263. def get_unsub_link(self):
  264. args = [self.code, self.make_token()]
  265. verify_link = reverse("hc-unsubscribe-alerts", args=args)
  266. return settings.SITE_ROOT + verify_link
  267. @property
  268. def transport(self):
  269. if self.kind == "email":
  270. return transports.Email(self)
  271. elif self.kind == "webhook":
  272. return transports.Webhook(self)
  273. elif self.kind == "slack":
  274. return transports.Slack(self)
  275. elif self.kind == "hipchat":
  276. return transports.HipChat(self)
  277. elif self.kind == "pd":
  278. return transports.PagerDuty(self)
  279. elif self.kind == "pagertree":
  280. return transports.PagerTree(self)
  281. elif self.kind == "victorops":
  282. return transports.VictorOps(self)
  283. elif self.kind == "pushbullet":
  284. return transports.Pushbullet(self)
  285. elif self.kind == "po":
  286. return transports.Pushover(self)
  287. elif self.kind == "opsgenie":
  288. return transports.OpsGenie(self)
  289. elif self.kind == "discord":
  290. return transports.Discord(self)
  291. elif self.kind == "telegram":
  292. return transports.Telegram(self)
  293. elif self.kind == "sms":
  294. return transports.Sms(self)
  295. elif self.kind == "trello":
  296. return transports.Trello(self)
  297. else:
  298. raise NotImplementedError("Unknown channel kind: %s" % self.kind)
  299. def notify(self, check):
  300. if self.transport.is_noop(check):
  301. return "no-op"
  302. n = Notification(owner=check, channel=self)
  303. n.check_status = check.status
  304. n.error = "Sending"
  305. n.save()
  306. if self.kind == "email":
  307. error = self.transport.notify(check, n.bounce_url()) or ""
  308. else:
  309. error = self.transport.notify(check) or ""
  310. n.error = error
  311. n.save()
  312. return error
  313. def icon_path(self):
  314. return 'img/integrations/%s.png' % self.kind
  315. @property
  316. def po_priority(self):
  317. assert self.kind == "po"
  318. parts = self.value.split("|")
  319. prio = int(parts[1])
  320. return PO_PRIORITIES[prio]
  321. @property
  322. def url_down(self):
  323. assert self.kind == "webhook"
  324. if not self.value.startswith("{"):
  325. parts = self.value.split("\n")
  326. return parts[0]
  327. doc = json.loads(self.value)
  328. return doc.get("url_down")
  329. @property
  330. def url_up(self):
  331. assert self.kind == "webhook"
  332. if not self.value.startswith("{"):
  333. parts = self.value.split("\n")
  334. return parts[1] if len(parts) > 1 else ""
  335. doc = json.loads(self.value)
  336. return doc.get("url_up")
  337. @property
  338. def post_data(self):
  339. assert self.kind == "webhook"
  340. if not self.value.startswith("{"):
  341. parts = self.value.split("\n")
  342. return parts[2] if len(parts) > 2 else ""
  343. doc = json.loads(self.value)
  344. return doc.get("post_data")
  345. @property
  346. def headers(self):
  347. assert self.kind == "webhook"
  348. if not self.value.startswith("{"):
  349. return {}
  350. doc = json.loads(self.value)
  351. return doc.get("headers", {})
  352. @property
  353. def slack_team(self):
  354. assert self.kind == "slack"
  355. if not self.value.startswith("{"):
  356. return None
  357. doc = json.loads(self.value)
  358. return doc["team_name"]
  359. @property
  360. def slack_channel(self):
  361. assert self.kind == "slack"
  362. if not self.value.startswith("{"):
  363. return None
  364. doc = json.loads(self.value)
  365. return doc["incoming_webhook"]["channel"]
  366. @property
  367. def slack_webhook_url(self):
  368. assert self.kind == "slack"
  369. if not self.value.startswith("{"):
  370. return self.value
  371. doc = json.loads(self.value)
  372. return doc["incoming_webhook"]["url"]
  373. @property
  374. def discord_webhook_url(self):
  375. assert self.kind == "discord"
  376. doc = json.loads(self.value)
  377. return doc["webhook"]["url"]
  378. @property
  379. def discord_webhook_id(self):
  380. assert self.kind == "discord"
  381. doc = json.loads(self.value)
  382. return doc["webhook"]["id"]
  383. @property
  384. def telegram_id(self):
  385. assert self.kind == "telegram"
  386. doc = json.loads(self.value)
  387. return doc.get("id")
  388. @property
  389. def telegram_type(self):
  390. assert self.kind == "telegram"
  391. doc = json.loads(self.value)
  392. return doc.get("type")
  393. @property
  394. def telegram_name(self):
  395. assert self.kind == "telegram"
  396. doc = json.loads(self.value)
  397. return doc.get("name")
  398. def refresh_hipchat_access_token(self):
  399. assert self.kind == "hipchat"
  400. if not self.value.startswith("{"):
  401. return # Don't have OAuth credentials
  402. doc = json.loads(self.value)
  403. if time.time() < doc.get("expires_at", 0):
  404. return # Current access token is still valid
  405. url = "https://api.hipchat.com/v2/oauth/token"
  406. auth = (doc["oauthId"], doc["oauthSecret"])
  407. r = requests.post(url, auth=auth, data={
  408. "grant_type": "client_credentials",
  409. "scope": "send_notification"
  410. })
  411. doc.update(r.json())
  412. doc["expires_at"] = int(time.time()) + doc["expires_in"] - 300
  413. self.value = json.dumps(doc)
  414. self.save()
  415. @property
  416. def hipchat_webhook_url(self):
  417. assert self.kind == "hipchat"
  418. if not self.value.startswith("{"):
  419. return self.value
  420. doc = json.loads(self.value)
  421. tmpl = "https://api.hipchat.com/v2/room/%s/notification?auth_token=%s"
  422. return tmpl % (doc["roomId"], doc.get("access_token"))
  423. @property
  424. def pd_service_key(self):
  425. assert self.kind == "pd"
  426. if not self.value.startswith("{"):
  427. return self.value
  428. doc = json.loads(self.value)
  429. return doc["service_key"]
  430. @property
  431. def pd_account(self):
  432. assert self.kind == "pd"
  433. if self.value.startswith("{"):
  434. doc = json.loads(self.value)
  435. return doc["account"]
  436. def latest_notification(self):
  437. return Notification.objects.filter(channel=self).latest()
  438. @property
  439. def sms_number(self):
  440. assert self.kind == "sms"
  441. if self.value.startswith("{"):
  442. doc = json.loads(self.value)
  443. return doc["value"]
  444. return self.value
  445. @property
  446. def sms_label(self):
  447. assert self.kind == "sms"
  448. if self.value.startswith("{"):
  449. doc = json.loads(self.value)
  450. return doc["label"]
  451. @property
  452. def trello_token(self):
  453. assert self.kind == "trello"
  454. if self.value.startswith("{"):
  455. doc = json.loads(self.value)
  456. return doc["token"]
  457. @property
  458. def trello_board_list(self):
  459. assert self.kind == "trello"
  460. if self.value.startswith("{"):
  461. doc = json.loads(self.value)
  462. return doc["board_name"], doc["list_name"]
  463. @property
  464. def trello_list_id(self):
  465. assert self.kind == "trello"
  466. if self.value.startswith("{"):
  467. doc = json.loads(self.value)
  468. return doc["list_id"]
  469. class Notification(models.Model):
  470. class Meta:
  471. get_latest_by = "created"
  472. code = models.UUIDField(default=uuid.uuid4, null=True, editable=False)
  473. owner = models.ForeignKey(Check, models.CASCADE)
  474. check_status = models.CharField(max_length=6)
  475. channel = models.ForeignKey(Channel, models.CASCADE)
  476. created = models.DateTimeField(auto_now_add=True)
  477. error = models.CharField(max_length=200, blank=True)
  478. def bounce_url(self):
  479. return settings.SITE_ROOT + reverse("hc-api-bounce", args=[self.code])
  480. class Flip(models.Model):
  481. owner = models.ForeignKey(Check, models.CASCADE)
  482. created = models.DateTimeField()
  483. processed = models.DateTimeField(null=True, blank=True, db_index=True)
  484. old_status = models.CharField(max_length=8, choices=STATUSES)
  485. new_status = models.CharField(max_length=8, choices=STATUSES)