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.

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