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.

651 lines
20 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
6 years ago
7 years ago
6 years ago
  1. # coding: utf-8
  2. import hashlib
  3. import json
  4. import uuid
  5. from datetime import datetime, timedelta as td
  6. from croniter import croniter
  7. from django.conf import settings
  8. from django.db import models
  9. from django.urls import reverse
  10. from django.utils import timezone
  11. from hc.accounts.models import Project
  12. from hc.api import transports
  13. from hc.lib import emails
  14. import pytz
  15. STATUSES = (
  16. ("up", "Up"),
  17. ("down", "Down"),
  18. ("new", "New"),
  19. ("paused", "Paused")
  20. )
  21. DEFAULT_TIMEOUT = td(days=1)
  22. DEFAULT_GRACE = td(hours=1)
  23. NEVER = datetime(3000, 1, 1, tzinfo=pytz.UTC)
  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. ("pagerteam", "Pager Team"),
  33. ("po", "Pushover"),
  34. ("pushbullet", "Pushbullet"),
  35. ("opsgenie", "OpsGenie"),
  36. ("victorops", "VictorOps"),
  37. ("discord", "Discord"),
  38. ("telegram", "Telegram"),
  39. ("sms", "SMS"),
  40. ("zendesk", "Zendesk"),
  41. ("trello", "Trello"),
  42. ("matrix", "Matrix"))
  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, unique=True)
  58. desc = models.TextField(blank=True)
  59. project = models.ForeignKey(Project, models.CASCADE)
  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. subject = models.CharField(max_length=100, blank=True)
  68. n_pings = models.IntegerField(default=0)
  69. last_ping = models.DateTimeField(null=True, blank=True)
  70. last_start = models.DateTimeField(null=True, blank=True)
  71. last_ping_was_fail = models.NullBooleanField(default=False)
  72. has_confirmation_link = models.BooleanField(default=False)
  73. alert_after = models.DateTimeField(null=True, blank=True, editable=False)
  74. status = models.CharField(max_length=6, choices=STATUSES, default="new")
  75. def __str__(self):
  76. return "%s (%d)" % (self.name or self.code, self.id)
  77. def name_then_code(self):
  78. if self.name:
  79. return self.name
  80. return str(self.code)
  81. def url(self):
  82. return settings.PING_ENDPOINT + str(self.code)
  83. def details_url(self):
  84. return settings.SITE_ROOT + reverse("hc-details", args=[self.code])
  85. def email(self):
  86. return "%s@%s" % (self.code, settings.PING_EMAIL_DOMAIN)
  87. def get_grace_start(self):
  88. """ Return the datetime when the grace period starts.
  89. If the check is currently new, paused or down, return None.
  90. """
  91. # NEVER is a constant sentinel value (year 3000).
  92. # Using None instead would make the logic clunky.
  93. result = NEVER
  94. if self.kind == "simple" and self.status == "up":
  95. result = self.last_ping + self.timeout
  96. elif self.kind == "cron" and self.status == "up":
  97. # The complex case, next ping is expected based on cron schedule.
  98. # Don't convert to naive datetimes (and so avoid ambiguities around
  99. # DST transitions). Croniter will handle the timezone-aware datetimes.
  100. zone = pytz.timezone(self.tz)
  101. last_local = timezone.localtime(self.last_ping, zone)
  102. it = croniter(self.schedule, last_local)
  103. result = it.next(datetime)
  104. if self.last_start and self.status != "down":
  105. result = min(result, self.last_start)
  106. if result != NEVER:
  107. return result
  108. def going_down_after(self):
  109. """ Return the datetime when the check goes down.
  110. If the check is new or paused, and not currently running, return None.
  111. If the check is already down, also return None.
  112. """
  113. grace_start = self.get_grace_start()
  114. if grace_start is not None:
  115. return grace_start + self.grace
  116. def get_status(self, now=None, with_started=True):
  117. """ Return current status for display. """
  118. if now is None:
  119. now = timezone.now()
  120. if self.last_start:
  121. if now >= self.last_start + self.grace:
  122. return "down"
  123. elif with_started:
  124. return "started"
  125. if self.status in ("new", "paused", "down"):
  126. return self.status
  127. grace_start = self.get_grace_start()
  128. grace_end = grace_start + self.grace
  129. if now >= grace_end:
  130. return "down"
  131. if now >= grace_start:
  132. return "grace"
  133. return "up"
  134. def assign_all_channels(self):
  135. channels = Channel.objects.filter(project=self.project)
  136. self.channel_set.set(channels)
  137. def tags_list(self):
  138. return [t.strip() for t in self.tags.split(" ") if t.strip()]
  139. def matches_tag_set(self, tag_set):
  140. return tag_set.issubset(self.tags_list())
  141. def to_dict(self):
  142. update_rel_url = reverse("hc-api-update", args=[self.code])
  143. pause_rel_url = reverse("hc-api-pause", args=[self.code])
  144. channel_codes = [str(ch.code) for ch in self.channel_set.all()]
  145. result = {
  146. "name": self.name,
  147. "ping_url": self.url(),
  148. "update_url": settings.SITE_ROOT + update_rel_url,
  149. "pause_url": settings.SITE_ROOT + pause_rel_url,
  150. "tags": self.tags,
  151. "grace": int(self.grace.total_seconds()),
  152. "n_pings": self.n_pings,
  153. "status": self.get_status(),
  154. "channels": ",".join(sorted(channel_codes)),
  155. "last_ping": isostring(self.last_ping),
  156. "next_ping": isostring(self.get_grace_start()),
  157. "desc": self.desc
  158. }
  159. if self.kind == "simple":
  160. result["timeout"] = int(self.timeout.total_seconds())
  161. elif self.kind == "cron":
  162. result["schedule"] = self.schedule
  163. result["tz"] = self.tz
  164. return result
  165. def ping(self, remote_addr, scheme, method, ua, body, action):
  166. if action == "start":
  167. self.last_start = timezone.now()
  168. # Don't update "last_ping" field.
  169. elif action == "ign":
  170. pass
  171. else:
  172. self.last_start = None
  173. self.last_ping = timezone.now()
  174. new_status = "down" if action == "fail" else "up"
  175. if self.status != new_status:
  176. flip = Flip(owner=self)
  177. flip.created = self.last_ping
  178. flip.old_status = self.status
  179. flip.new_status = new_status
  180. flip.save()
  181. self.status = new_status
  182. self.alert_after = self.going_down_after()
  183. self.n_pings = models.F("n_pings") + 1
  184. self.has_confirmation_link = "confirm" in str(body).lower()
  185. self.save()
  186. self.refresh_from_db()
  187. ping = Ping(owner=self)
  188. ping.n = self.n_pings
  189. if action in ("start", "fail", "ign"):
  190. ping.kind = action
  191. ping.remote_addr = remote_addr
  192. ping.scheme = scheme
  193. ping.method = method
  194. # If User-Agent is longer than 200 characters, truncate it:
  195. ping.ua = ua[:200]
  196. ping.body = body[:10000]
  197. ping.save()
  198. class Ping(models.Model):
  199. id = models.BigAutoField(primary_key=True)
  200. n = models.IntegerField(null=True)
  201. owner = models.ForeignKey(Check, models.CASCADE)
  202. created = models.DateTimeField(auto_now_add=True)
  203. kind = models.CharField(max_length=6, blank=True, null=True)
  204. scheme = models.CharField(max_length=10, default="http")
  205. remote_addr = models.GenericIPAddressField(blank=True, null=True)
  206. method = models.CharField(max_length=10, blank=True)
  207. ua = models.CharField(max_length=200, blank=True)
  208. body = models.CharField(max_length=10000, blank=True, null=True)
  209. class Channel(models.Model):
  210. name = models.CharField(max_length=100, blank=True)
  211. code = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
  212. project = models.ForeignKey(Project, models.CASCADE)
  213. created = models.DateTimeField(auto_now_add=True)
  214. kind = models.CharField(max_length=20, choices=CHANNEL_KINDS)
  215. value = models.TextField(blank=True)
  216. email_verified = models.BooleanField(default=False)
  217. checks = models.ManyToManyField(Check)
  218. def __str__(self):
  219. if self.name:
  220. return self.name
  221. if self.kind == "email":
  222. return "Email to %s" % self.email_value
  223. elif self.kind == "sms":
  224. return "SMS to %s" % self.sms_number
  225. elif self.kind == "slack":
  226. return "Slack %s" % self.slack_channel
  227. elif self.kind == "telegram":
  228. return "Telegram %s" % self.telegram_name
  229. return self.get_kind_display()
  230. def to_dict(self):
  231. return {
  232. "id": str(self.code),
  233. "name": self.name,
  234. "kind": self.kind
  235. }
  236. def assign_all_checks(self):
  237. checks = Check.objects.filter(project=self.project)
  238. self.checks.add(*checks)
  239. def make_token(self):
  240. seed = "%s%s" % (self.code, settings.SECRET_KEY)
  241. seed = seed.encode()
  242. return hashlib.sha1(seed).hexdigest()
  243. def send_verify_link(self):
  244. args = [self.code, self.make_token()]
  245. verify_link = reverse("hc-verify-email", args=args)
  246. verify_link = settings.SITE_ROOT + verify_link
  247. emails.verify_email(self.email_value, {"verify_link": verify_link})
  248. def get_unsub_link(self):
  249. args = [self.code, self.make_token()]
  250. verify_link = reverse("hc-unsubscribe-alerts", args=args)
  251. return settings.SITE_ROOT + verify_link
  252. @property
  253. def transport(self):
  254. if self.kind == "email":
  255. return transports.Email(self)
  256. elif self.kind == "webhook":
  257. return transports.Webhook(self)
  258. elif self.kind == "slack":
  259. return transports.Slack(self)
  260. elif self.kind == "hipchat":
  261. return transports.HipChat(self)
  262. elif self.kind == "pd":
  263. return transports.PagerDuty(self)
  264. elif self.kind == "pagertree":
  265. return transports.PagerTree(self)
  266. elif self.kind == "pagerteam":
  267. return transports.PagerTeam(self)
  268. elif self.kind == "victorops":
  269. return transports.VictorOps(self)
  270. elif self.kind == "pushbullet":
  271. return transports.Pushbullet(self)
  272. elif self.kind == "po":
  273. return transports.Pushover(self)
  274. elif self.kind == "opsgenie":
  275. return transports.OpsGenie(self)
  276. elif self.kind == "discord":
  277. return transports.Discord(self)
  278. elif self.kind == "telegram":
  279. return transports.Telegram(self)
  280. elif self.kind == "sms":
  281. return transports.Sms(self)
  282. elif self.kind == "trello":
  283. return transports.Trello(self)
  284. elif self.kind == "matrix":
  285. return transports.Matrix(self)
  286. else:
  287. raise NotImplementedError("Unknown channel kind: %s" % self.kind)
  288. def notify(self, check):
  289. if self.transport.is_noop(check):
  290. return "no-op"
  291. n = Notification(owner=check, channel=self)
  292. n.check_status = check.status
  293. n.error = "Sending"
  294. n.save()
  295. if self.kind == "email":
  296. error = self.transport.notify(check, n.bounce_url()) or ""
  297. else:
  298. error = self.transport.notify(check) or ""
  299. n.error = error
  300. n.save()
  301. return error
  302. def icon_path(self):
  303. return 'img/integrations/%s.png' % self.kind
  304. @property
  305. def po_priority(self):
  306. assert self.kind == "po"
  307. parts = self.value.split("|")
  308. prio = int(parts[1])
  309. return PO_PRIORITIES[prio]
  310. @property
  311. def url_down(self):
  312. assert self.kind == "webhook"
  313. if not self.value.startswith("{"):
  314. parts = self.value.split("\n")
  315. return parts[0]
  316. doc = json.loads(self.value)
  317. return doc.get("url_down")
  318. @property
  319. def url_up(self):
  320. assert self.kind == "webhook"
  321. if not self.value.startswith("{"):
  322. parts = self.value.split("\n")
  323. return parts[1] if len(parts) > 1 else ""
  324. doc = json.loads(self.value)
  325. return doc.get("url_up")
  326. @property
  327. def post_data(self):
  328. assert self.kind == "webhook"
  329. if not self.value.startswith("{"):
  330. parts = self.value.split("\n")
  331. return parts[2] if len(parts) > 2 else ""
  332. doc = json.loads(self.value)
  333. return doc.get("post_data")
  334. @property
  335. def headers(self):
  336. assert self.kind == "webhook"
  337. if not self.value.startswith("{"):
  338. return {}
  339. doc = json.loads(self.value)
  340. return doc.get("headers", {})
  341. @property
  342. def slack_team(self):
  343. assert self.kind == "slack"
  344. if not self.value.startswith("{"):
  345. return None
  346. doc = json.loads(self.value)
  347. return doc["team_name"]
  348. @property
  349. def slack_channel(self):
  350. assert self.kind == "slack"
  351. if not self.value.startswith("{"):
  352. return None
  353. doc = json.loads(self.value)
  354. return doc["incoming_webhook"]["channel"]
  355. @property
  356. def slack_webhook_url(self):
  357. assert self.kind == "slack"
  358. if not self.value.startswith("{"):
  359. return self.value
  360. doc = json.loads(self.value)
  361. return doc["incoming_webhook"]["url"]
  362. @property
  363. def discord_webhook_url(self):
  364. assert self.kind == "discord"
  365. doc = json.loads(self.value)
  366. return doc["webhook"]["url"]
  367. @property
  368. def discord_webhook_id(self):
  369. assert self.kind == "discord"
  370. doc = json.loads(self.value)
  371. return doc["webhook"]["id"]
  372. @property
  373. def telegram_id(self):
  374. assert self.kind == "telegram"
  375. doc = json.loads(self.value)
  376. return doc.get("id")
  377. @property
  378. def telegram_type(self):
  379. assert self.kind == "telegram"
  380. doc = json.loads(self.value)
  381. return doc.get("type")
  382. @property
  383. def telegram_name(self):
  384. assert self.kind == "telegram"
  385. doc = json.loads(self.value)
  386. return doc.get("name")
  387. @property
  388. def pd_service_key(self):
  389. assert self.kind == "pd"
  390. if not self.value.startswith("{"):
  391. return self.value
  392. doc = json.loads(self.value)
  393. return doc["service_key"]
  394. @property
  395. def pd_account(self):
  396. assert self.kind == "pd"
  397. if self.value.startswith("{"):
  398. doc = json.loads(self.value)
  399. return doc["account"]
  400. def latest_notification(self):
  401. return Notification.objects.filter(channel=self).latest()
  402. @property
  403. def sms_number(self):
  404. assert self.kind == "sms"
  405. if self.value.startswith("{"):
  406. doc = json.loads(self.value)
  407. return doc["value"]
  408. return self.value
  409. @property
  410. def sms_label(self):
  411. assert self.kind == "sms"
  412. if self.value.startswith("{"):
  413. doc = json.loads(self.value)
  414. return doc["label"]
  415. @property
  416. def trello_token(self):
  417. assert self.kind == "trello"
  418. if self.value.startswith("{"):
  419. doc = json.loads(self.value)
  420. return doc["token"]
  421. @property
  422. def trello_board_list(self):
  423. assert self.kind == "trello"
  424. if self.value.startswith("{"):
  425. doc = json.loads(self.value)
  426. return doc["board_name"], doc["list_name"]
  427. @property
  428. def trello_list_id(self):
  429. assert self.kind == "trello"
  430. if self.value.startswith("{"):
  431. doc = json.loads(self.value)
  432. return doc["list_id"]
  433. @property
  434. def email_value(self):
  435. assert self.kind == "email"
  436. if not self.value.startswith("{"):
  437. return self.value
  438. doc = json.loads(self.value)
  439. return doc.get("value")
  440. @property
  441. def email_notify_up(self):
  442. assert self.kind == "email"
  443. if not self.value.startswith("{"):
  444. return True
  445. doc = json.loads(self.value)
  446. return doc.get("up")
  447. @property
  448. def email_notify_down(self):
  449. assert self.kind == "email"
  450. if not self.value.startswith("{"):
  451. return True
  452. doc = json.loads(self.value)
  453. return doc.get("down")
  454. class Notification(models.Model):
  455. class Meta:
  456. get_latest_by = "created"
  457. code = models.UUIDField(default=uuid.uuid4, null=True, editable=False)
  458. owner = models.ForeignKey(Check, models.CASCADE)
  459. check_status = models.CharField(max_length=6)
  460. channel = models.ForeignKey(Channel, models.CASCADE)
  461. created = models.DateTimeField(auto_now_add=True)
  462. error = models.CharField(max_length=200, blank=True)
  463. def bounce_url(self):
  464. return settings.SITE_ROOT + reverse("hc-api-bounce", args=[self.code])
  465. class Flip(models.Model):
  466. owner = models.ForeignKey(Check, models.CASCADE)
  467. created = models.DateTimeField()
  468. processed = models.DateTimeField(null=True, blank=True, db_index=True)
  469. old_status = models.CharField(max_length=8, choices=STATUSES)
  470. new_status = models.CharField(max_length=8, choices=STATUSES)
  471. def send_alerts(self):
  472. if self.new_status == "up" and self.old_status in ("new", "paused"):
  473. # Don't send alerts on new->up and paused->up transitions
  474. return []
  475. if self.new_status not in ("up", "down"):
  476. raise NotImplementedError("Unexpected status: %s" % self.status)
  477. errors = []
  478. for channel in self.owner.channel_set.all():
  479. error = channel.notify(self.owner)
  480. if error not in ("", "no-op"):
  481. errors.append((channel, error))
  482. return errors
  483. class TokenBucket(models.Model):
  484. value = models.CharField(max_length=80, unique=True)
  485. tokens = models.FloatField(default=1.0)
  486. updated = models.DateTimeField(default=timezone.now)
  487. @staticmethod
  488. def authorize(value, capacity, refill_time_secs):
  489. now = timezone.now()
  490. obj, created = TokenBucket.objects.get_or_create(value=value)
  491. if not created:
  492. # Top up the bucket:
  493. delta_secs = (now - obj.updated).total_seconds()
  494. obj.tokens = min(1.0, obj.tokens + delta_secs / refill_time_secs)
  495. obj.tokens -= 1.0 / capacity
  496. if obj.tokens < 0:
  497. # Not enough tokens
  498. return False
  499. # Race condition: two concurrent authorize calls can overwrite each
  500. # other's changes. It's OK to be a little inexact here for the sake
  501. # of simplicity.
  502. obj.updated = now
  503. obj.save()
  504. return True
  505. @staticmethod
  506. def authorize_login_email(email):
  507. # remove dots and alias:
  508. mailbox, domain = email.split("@")
  509. mailbox = mailbox.replace(".", "")
  510. mailbox = mailbox.split("+")[0]
  511. email = mailbox + "@" + domain
  512. salted_encoded = (email + settings.SECRET_KEY).encode()
  513. value = "em-%s" % hashlib.sha1(salted_encoded).hexdigest()
  514. # 20 login attempts for a single email per hour:
  515. return TokenBucket.authorize(value, 20, 3600)
  516. @staticmethod
  517. def authorize_invite(user):
  518. value = "invite-%d" % user.id
  519. # 20 invites per day
  520. return TokenBucket.authorize(value, 2, 3600 * 24)
  521. @staticmethod
  522. def authorize_login_password(email):
  523. salted_encoded = (email + settings.SECRET_KEY).encode()
  524. value = "pw-%s" % hashlib.sha1(salted_encoded).hexdigest()
  525. # 20 password attempts per day
  526. return TokenBucket.authorize(value, 20, 3600 * 24)