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.

882 lines
28 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
4 years ago
10 years ago
4 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.core.signing import TimestampSigner
  9. from django.db import models
  10. from django.urls import reverse
  11. from django.utils import timezone
  12. from hc.accounts.models import Project
  13. from hc.api import transports
  14. from hc.lib import emails
  15. from hc.lib.date import month_boundaries
  16. import pytz
  17. STATUSES = (("up", "Up"), ("down", "Down"), ("new", "New"), ("paused", "Paused"))
  18. DEFAULT_TIMEOUT = td(days=1)
  19. DEFAULT_GRACE = td(hours=1)
  20. NEVER = datetime(3000, 1, 1, tzinfo=pytz.UTC)
  21. CHECK_KINDS = (("simple", "Simple"), ("cron", "Cron"))
  22. # max time between start and ping where we will consider both events related:
  23. MAX_DELTA = td(hours=24)
  24. CHANNEL_KINDS = (
  25. ("email", "Email"),
  26. ("webhook", "Webhook"),
  27. ("hipchat", "HipChat"),
  28. ("slack", "Slack"),
  29. ("pd", "PagerDuty"),
  30. ("pagertree", "PagerTree"),
  31. ("pagerteam", "Pager Team"),
  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. ("trello", "Trello"),
  41. ("matrix", "Matrix"),
  42. ("whatsapp", "WhatsApp"),
  43. ("apprise", "Apprise"),
  44. ("mattermost", "Mattermost"),
  45. ("msteams", "Microsoft Teams"),
  46. ("shell", "Shell Command"),
  47. ("zulip", "Zulip"),
  48. ("spike", "Spike"),
  49. ("call", "Phone Call"),
  50. ("linenotify", "LINE Notify"),
  51. )
  52. PO_PRIORITIES = {-2: "lowest", -1: "low", 0: "normal", 1: "high", 2: "emergency"}
  53. def isostring(dt):
  54. """Convert the datetime to ISO 8601 format with no microseconds. """
  55. if dt:
  56. return dt.replace(microsecond=0).isoformat()
  57. class Check(models.Model):
  58. name = models.CharField(max_length=100, blank=True)
  59. tags = models.CharField(max_length=500, blank=True)
  60. code = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
  61. desc = models.TextField(blank=True)
  62. project = models.ForeignKey(Project, models.CASCADE)
  63. created = models.DateTimeField(auto_now_add=True)
  64. kind = models.CharField(max_length=10, default="simple", choices=CHECK_KINDS)
  65. timeout = models.DurationField(default=DEFAULT_TIMEOUT)
  66. grace = models.DurationField(default=DEFAULT_GRACE)
  67. schedule = models.CharField(max_length=100, default="* * * * *")
  68. tz = models.CharField(max_length=36, default="UTC")
  69. subject = models.CharField(max_length=100, blank=True)
  70. subject_fail = models.CharField(max_length=100, blank=True)
  71. methods = models.CharField(max_length=30, blank=True)
  72. manual_resume = models.BooleanField(default=False)
  73. n_pings = models.IntegerField(default=0)
  74. last_ping = models.DateTimeField(null=True, blank=True)
  75. last_start = models.DateTimeField(null=True, blank=True)
  76. last_duration = models.DurationField(null=True, blank=True)
  77. last_ping_was_fail = models.BooleanField(default=False)
  78. has_confirmation_link = models.BooleanField(default=False)
  79. alert_after = models.DateTimeField(null=True, blank=True, editable=False)
  80. status = models.CharField(max_length=6, choices=STATUSES, default="new")
  81. class Meta:
  82. indexes = [
  83. # Index for the alert_after field. Excludes rows with status=down.
  84. # Used in the sendalerts management command.
  85. models.Index(
  86. fields=["alert_after"],
  87. name="api_check_aa_not_down",
  88. condition=~models.Q(status="down"),
  89. )
  90. ]
  91. def __str__(self):
  92. return "%s (%d)" % (self.name or self.code, self.id)
  93. def name_then_code(self):
  94. if self.name:
  95. return self.name
  96. return str(self.code)
  97. def url(self):
  98. return settings.PING_ENDPOINT + str(self.code)
  99. def details_url(self):
  100. return settings.SITE_ROOT + reverse("hc-details", args=[self.code])
  101. def email(self):
  102. return "%s@%s" % (self.code, settings.PING_EMAIL_DOMAIN)
  103. def clamped_last_duration(self):
  104. if self.last_duration and self.last_duration < MAX_DELTA:
  105. return self.last_duration
  106. def get_grace_start(self, with_started=True):
  107. """ Return the datetime when the grace period starts.
  108. If the check is currently new, paused or down, return None.
  109. """
  110. # NEVER is a constant sentinel value (year 3000).
  111. # Using None instead would make the logic clunky.
  112. result = NEVER
  113. if self.kind == "simple" and self.status == "up":
  114. result = self.last_ping + self.timeout
  115. elif self.kind == "cron" and self.status == "up":
  116. # The complex case, next ping is expected based on cron schedule.
  117. # Don't convert to naive datetimes (and so avoid ambiguities around
  118. # DST transitions). Croniter will handle the timezone-aware datetimes.
  119. zone = pytz.timezone(self.tz)
  120. last_local = timezone.localtime(self.last_ping, zone)
  121. it = croniter(self.schedule, last_local)
  122. result = it.next(datetime)
  123. if with_started and self.last_start and self.status != "down":
  124. result = min(result, self.last_start)
  125. if result != NEVER:
  126. return result
  127. def going_down_after(self):
  128. """ Return the datetime when the check goes down.
  129. If the check is new or paused, and not currently running, return None.
  130. If the check is already down, also return None.
  131. """
  132. grace_start = self.get_grace_start()
  133. if grace_start is not None:
  134. return grace_start + self.grace
  135. def get_status(self, now=None, with_started=False):
  136. """ Return current status for display. """
  137. if now is None:
  138. now = timezone.now()
  139. if self.last_start:
  140. if now >= self.last_start + self.grace:
  141. return "down"
  142. elif with_started:
  143. return "started"
  144. if self.status in ("new", "paused", "down"):
  145. return self.status
  146. grace_start = self.get_grace_start(with_started=with_started)
  147. grace_end = grace_start + self.grace
  148. if now >= grace_end:
  149. return "down"
  150. if now >= grace_start:
  151. return "grace"
  152. return "up"
  153. def get_status_with_started(self):
  154. return self.get_status(with_started=True)
  155. def assign_all_channels(self):
  156. channels = Channel.objects.filter(project=self.project)
  157. self.channel_set.set(channels)
  158. def tags_list(self):
  159. return [t.strip() for t in self.tags.split(" ") if t.strip()]
  160. def matches_tag_set(self, tag_set):
  161. return tag_set.issubset(self.tags_list())
  162. def channels_str(self):
  163. """ Return a comma-separated string of assigned channel codes. """
  164. codes = self.channel_set.order_by("code").values_list("code", flat=True)
  165. return ",".join(map(str, codes))
  166. @property
  167. def unique_key(self):
  168. code_half = self.code.hex[:16]
  169. return hashlib.sha1(code_half.encode()).hexdigest()
  170. def to_dict(self, readonly=False):
  171. result = {
  172. "name": self.name,
  173. "tags": self.tags,
  174. "desc": self.desc,
  175. "grace": int(self.grace.total_seconds()),
  176. "n_pings": self.n_pings,
  177. "status": self.get_status(with_started=True),
  178. "last_ping": isostring(self.last_ping),
  179. "next_ping": isostring(self.get_grace_start()),
  180. "manual_resume": self.manual_resume,
  181. }
  182. if self.last_duration:
  183. result["last_duration"] = int(self.last_duration.total_seconds())
  184. if readonly:
  185. result["unique_key"] = self.unique_key
  186. else:
  187. update_rel_url = reverse("hc-api-single", args=[self.code])
  188. pause_rel_url = reverse("hc-api-pause", args=[self.code])
  189. result["ping_url"] = self.url()
  190. result["update_url"] = settings.SITE_ROOT + update_rel_url
  191. result["pause_url"] = settings.SITE_ROOT + pause_rel_url
  192. result["channels"] = self.channels_str()
  193. if self.kind == "simple":
  194. result["timeout"] = int(self.timeout.total_seconds())
  195. elif self.kind == "cron":
  196. result["schedule"] = self.schedule
  197. result["tz"] = self.tz
  198. return result
  199. def ping(self, remote_addr, scheme, method, ua, body, action):
  200. now = timezone.now()
  201. if self.status == "paused" and self.manual_resume:
  202. action = "ign"
  203. if action == "start":
  204. self.last_start = now
  205. # Don't update "last_ping" field.
  206. elif action == "ign":
  207. pass
  208. else:
  209. self.last_ping = now
  210. if self.last_start:
  211. self.last_duration = self.last_ping - self.last_start
  212. self.last_start = None
  213. else:
  214. self.last_duration = None
  215. new_status = "down" if action == "fail" else "up"
  216. if self.status != new_status:
  217. flip = Flip(owner=self)
  218. flip.created = self.last_ping
  219. flip.old_status = self.status
  220. flip.new_status = new_status
  221. flip.save()
  222. self.status = new_status
  223. self.alert_after = self.going_down_after()
  224. self.n_pings = models.F("n_pings") + 1
  225. self.has_confirmation_link = "confirm" in str(body).lower()
  226. self.save()
  227. self.refresh_from_db()
  228. ping = Ping(owner=self)
  229. ping.n = self.n_pings
  230. ping.created = now
  231. if action in ("start", "fail", "ign"):
  232. ping.kind = action
  233. ping.remote_addr = remote_addr
  234. ping.scheme = scheme
  235. ping.method = method
  236. # If User-Agent is longer than 200 characters, truncate it:
  237. ping.ua = ua[:200]
  238. ping.body = body[: settings.PING_BODY_LIMIT]
  239. ping.save()
  240. def downtimes(self, months=3):
  241. """ Calculate the number of downtimes and downtime minutes per month.
  242. Returns a list of (datetime, downtime_in_secs, number_of_outages) tuples.
  243. """
  244. def monthkey(dt):
  245. return dt.year, dt.month
  246. # Datetimes of the first days of months we're interested in. Ascending order.
  247. boundaries = month_boundaries(months=months)
  248. # Will accumulate totals here.
  249. # (year, month) -> [datetime, total_downtime, number_of_outages]
  250. totals = {monthkey(b): [b, td(), 0] for b in boundaries}
  251. # A list of flips and month boundaries
  252. events = [(b, "---") for b in boundaries]
  253. q = self.flip_set.filter(created__gt=min(boundaries))
  254. for pair in q.values_list("created", "old_status"):
  255. events.append(pair)
  256. # Iterate through flips and month boundaries in reverse order,
  257. # and for each "down" event increase the counters in `totals`.
  258. dt, status = timezone.now(), self.status
  259. for prev_dt, prev_status in sorted(events, reverse=True):
  260. if status == "down":
  261. delta = dt - prev_dt
  262. totals[monthkey(prev_dt)][1] += delta
  263. totals[monthkey(prev_dt)][2] += 1
  264. dt = prev_dt
  265. if prev_status != "---":
  266. status = prev_status
  267. return sorted(totals.values())
  268. class Ping(models.Model):
  269. id = models.BigAutoField(primary_key=True)
  270. n = models.IntegerField(null=True)
  271. owner = models.ForeignKey(Check, models.CASCADE)
  272. created = models.DateTimeField(default=timezone.now)
  273. kind = models.CharField(max_length=6, blank=True, null=True)
  274. scheme = models.CharField(max_length=10, default="http")
  275. remote_addr = models.GenericIPAddressField(blank=True, null=True)
  276. method = models.CharField(max_length=10, blank=True)
  277. ua = models.CharField(max_length=200, blank=True)
  278. body = models.TextField(blank=True, null=True)
  279. def to_dict(self):
  280. return {
  281. "type": self.kind or "success",
  282. "date": self.created.isoformat(),
  283. "n": self.n,
  284. "scheme": self.scheme,
  285. "remote_addr": self.remote_addr,
  286. "method": self.method,
  287. "ua": self.ua,
  288. }
  289. class Channel(models.Model):
  290. name = models.CharField(max_length=100, blank=True)
  291. code = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
  292. project = models.ForeignKey(Project, models.CASCADE)
  293. created = models.DateTimeField(auto_now_add=True)
  294. kind = models.CharField(max_length=20, choices=CHANNEL_KINDS)
  295. value = models.TextField(blank=True)
  296. email_verified = models.BooleanField(default=False)
  297. last_error = models.CharField(max_length=200, blank=True)
  298. checks = models.ManyToManyField(Check)
  299. def __str__(self):
  300. if self.name:
  301. return self.name
  302. if self.kind == "email":
  303. return "Email to %s" % self.email_value
  304. elif self.kind == "sms":
  305. return "SMS to %s" % self.phone_number
  306. elif self.kind == "slack":
  307. return "Slack %s" % self.slack_channel
  308. elif self.kind == "telegram":
  309. return "Telegram %s" % self.telegram_name
  310. elif self.kind == "zulip":
  311. if self.zulip_type == "stream":
  312. return "Zulip stream %s" % self.zulip_to
  313. if self.zulip_type == "private":
  314. return "Zulip user %s" % self.zulip_to
  315. return self.get_kind_display()
  316. def to_dict(self):
  317. return {"id": str(self.code), "name": self.name, "kind": self.kind}
  318. def assign_all_checks(self):
  319. checks = Check.objects.filter(project=self.project)
  320. self.checks.add(*checks)
  321. def make_token(self):
  322. seed = "%s%s" % (self.code, settings.SECRET_KEY)
  323. seed = seed.encode()
  324. return hashlib.sha1(seed).hexdigest()
  325. def send_verify_link(self):
  326. args = [self.code, self.make_token()]
  327. verify_link = reverse("hc-verify-email", args=args)
  328. verify_link = settings.SITE_ROOT + verify_link
  329. emails.verify_email(self.email_value, {"verify_link": verify_link})
  330. def get_unsub_link(self):
  331. signer = TimestampSigner(salt="alerts")
  332. signed_token = signer.sign(self.make_token())
  333. args = [self.code, signed_token]
  334. verify_link = reverse("hc-unsubscribe-alerts", args=args)
  335. return settings.SITE_ROOT + verify_link
  336. @property
  337. def transport(self):
  338. if self.kind == "email":
  339. return transports.Email(self)
  340. elif self.kind == "webhook":
  341. return transports.Webhook(self)
  342. elif self.kind in ("slack", "mattermost"):
  343. return transports.Slack(self)
  344. elif self.kind == "hipchat":
  345. return transports.HipChat(self)
  346. elif self.kind == "pd":
  347. return transports.PagerDuty(self)
  348. elif self.kind == "pagertree":
  349. return transports.PagerTree(self)
  350. elif self.kind == "pagerteam":
  351. return transports.PagerTeam(self)
  352. elif self.kind == "victorops":
  353. return transports.VictorOps(self)
  354. elif self.kind == "pushbullet":
  355. return transports.Pushbullet(self)
  356. elif self.kind == "po":
  357. return transports.Pushover(self)
  358. elif self.kind == "opsgenie":
  359. return transports.OpsGenie(self)
  360. elif self.kind == "discord":
  361. return transports.Discord(self)
  362. elif self.kind == "telegram":
  363. return transports.Telegram(self)
  364. elif self.kind == "sms":
  365. return transports.Sms(self)
  366. elif self.kind == "trello":
  367. return transports.Trello(self)
  368. elif self.kind == "matrix":
  369. return transports.Matrix(self)
  370. elif self.kind == "whatsapp":
  371. return transports.WhatsApp(self)
  372. elif self.kind == "apprise":
  373. return transports.Apprise(self)
  374. elif self.kind == "msteams":
  375. return transports.MsTeams(self)
  376. elif self.kind == "shell":
  377. return transports.Shell(self)
  378. elif self.kind == "zulip":
  379. return transports.Zulip(self)
  380. elif self.kind == "spike":
  381. return transports.Spike(self)
  382. elif self.kind == "call":
  383. return transports.Call(self)
  384. elif self.kind == "linenotify":
  385. return transports.LineNotify(self)
  386. else:
  387. raise NotImplementedError("Unknown channel kind: %s" % self.kind)
  388. def notify(self, check, is_test=False):
  389. if self.transport.is_noop(check):
  390. return "no-op"
  391. n = Notification(channel=self)
  392. if is_test:
  393. # When sending a test notification we leave the owner field null.
  394. # (the passed check is a dummy, unsaved Check instance)
  395. pass
  396. else:
  397. n.owner = check
  398. n.check_status = check.status
  399. n.error = "Sending"
  400. n.save()
  401. # These are not database fields. It is just a convenient way to pass
  402. # status_url to transport classes.
  403. check.status_url = n.status_url()
  404. error = self.transport.notify(check) or ""
  405. Notification.objects.filter(id=n.id).update(error=error)
  406. Channel.objects.filter(id=self.id).update(last_error=error)
  407. return error
  408. def icon_path(self):
  409. return "img/integrations/%s.png" % self.kind
  410. @property
  411. def json(self):
  412. return json.loads(self.value)
  413. @property
  414. def po_priority(self):
  415. assert self.kind == "po"
  416. parts = self.value.split("|")
  417. prio = int(parts[1])
  418. return PO_PRIORITIES[prio]
  419. def webhook_spec(self, status):
  420. assert self.kind == "webhook"
  421. doc = json.loads(self.value)
  422. if status == "down" and "method_down" in doc:
  423. return {
  424. "method": doc["method_down"],
  425. "url": doc["url_down"],
  426. "body": doc["body_down"],
  427. "headers": doc["headers_down"],
  428. }
  429. elif status == "up" and "method_up" in doc:
  430. return {
  431. "method": doc["method_up"],
  432. "url": doc["url_up"],
  433. "body": doc["body_up"],
  434. "headers": doc["headers_up"],
  435. }
  436. @property
  437. def down_webhook_spec(self):
  438. return self.webhook_spec("down")
  439. @property
  440. def up_webhook_spec(self):
  441. return self.webhook_spec("up")
  442. @property
  443. def url_down(self):
  444. return self.down_webhook_spec["url"]
  445. @property
  446. def url_up(self):
  447. return self.up_webhook_spec["url"]
  448. @property
  449. def cmd_down(self):
  450. assert self.kind == "shell"
  451. return self.json["cmd_down"]
  452. @property
  453. def cmd_up(self):
  454. assert self.kind == "shell"
  455. return self.json["cmd_up"]
  456. @property
  457. def slack_team(self):
  458. assert self.kind == "slack"
  459. if not self.value.startswith("{"):
  460. return None
  461. doc = json.loads(self.value)
  462. if "team_name" in doc:
  463. return doc["team_name"]
  464. if "team" in doc:
  465. return doc["team"]["name"]
  466. @property
  467. def slack_channel(self):
  468. assert self.kind == "slack"
  469. if not self.value.startswith("{"):
  470. return None
  471. doc = json.loads(self.value)
  472. return doc["incoming_webhook"]["channel"]
  473. @property
  474. def slack_webhook_url(self):
  475. assert self.kind in ("slack", "mattermost")
  476. if not self.value.startswith("{"):
  477. return self.value
  478. doc = json.loads(self.value)
  479. return doc["incoming_webhook"]["url"]
  480. @property
  481. def discord_webhook_url(self):
  482. assert self.kind == "discord"
  483. doc = json.loads(self.value)
  484. url = doc["webhook"]["url"]
  485. # Discord migrated to discord.com,
  486. # and is dropping support for discordapp.com on 7 November 2020
  487. if url.startswith("https://discordapp.com/"):
  488. url = "https://discord.com/" + url[23:]
  489. return url
  490. @property
  491. def discord_webhook_id(self):
  492. assert self.kind == "discord"
  493. doc = json.loads(self.value)
  494. return doc["webhook"]["id"]
  495. @property
  496. def telegram_id(self):
  497. assert self.kind == "telegram"
  498. doc = json.loads(self.value)
  499. return doc.get("id")
  500. @property
  501. def telegram_type(self):
  502. assert self.kind == "telegram"
  503. doc = json.loads(self.value)
  504. return doc.get("type")
  505. @property
  506. def telegram_name(self):
  507. assert self.kind == "telegram"
  508. doc = json.loads(self.value)
  509. return doc.get("name")
  510. @property
  511. def pd_service_key(self):
  512. assert self.kind == "pd"
  513. if not self.value.startswith("{"):
  514. return self.value
  515. doc = json.loads(self.value)
  516. return doc["service_key"]
  517. @property
  518. def pd_account(self):
  519. assert self.kind == "pd"
  520. if self.value.startswith("{"):
  521. doc = json.loads(self.value)
  522. return doc["account"]
  523. def latest_notification(self):
  524. return Notification.objects.filter(channel=self).latest()
  525. @property
  526. def phone_number(self):
  527. assert self.kind in ("call", "sms", "whatsapp")
  528. if self.value.startswith("{"):
  529. doc = json.loads(self.value)
  530. return doc["value"]
  531. return self.value
  532. @property
  533. def trello_token(self):
  534. assert self.kind == "trello"
  535. if self.value.startswith("{"):
  536. doc = json.loads(self.value)
  537. return doc["token"]
  538. @property
  539. def trello_board_list(self):
  540. assert self.kind == "trello"
  541. if self.value.startswith("{"):
  542. doc = json.loads(self.value)
  543. return doc["board_name"], doc["list_name"]
  544. @property
  545. def trello_list_id(self):
  546. assert self.kind == "trello"
  547. if self.value.startswith("{"):
  548. doc = json.loads(self.value)
  549. return doc["list_id"]
  550. @property
  551. def email_value(self):
  552. assert self.kind == "email"
  553. if not self.value.startswith("{"):
  554. return self.value
  555. return self.json["value"]
  556. @property
  557. def email_notify_up(self):
  558. assert self.kind == "email"
  559. if not self.value.startswith("{"):
  560. return True
  561. doc = json.loads(self.value)
  562. return doc.get("up")
  563. @property
  564. def email_notify_down(self):
  565. assert self.kind == "email"
  566. if not self.value.startswith("{"):
  567. return True
  568. doc = json.loads(self.value)
  569. return doc.get("down")
  570. @property
  571. def whatsapp_notify_up(self):
  572. assert self.kind == "whatsapp"
  573. doc = json.loads(self.value)
  574. return doc["up"]
  575. @property
  576. def whatsapp_notify_down(self):
  577. assert self.kind == "whatsapp"
  578. doc = json.loads(self.value)
  579. return doc["down"]
  580. @property
  581. def opsgenie_key(self):
  582. assert self.kind == "opsgenie"
  583. if not self.value.startswith("{"):
  584. return self.value
  585. doc = json.loads(self.value)
  586. return doc["key"]
  587. @property
  588. def opsgenie_region(self):
  589. assert self.kind == "opsgenie"
  590. if not self.value.startswith("{"):
  591. return "us"
  592. doc = json.loads(self.value)
  593. return doc["region"]
  594. @property
  595. def zulip_bot_email(self):
  596. assert self.kind == "zulip"
  597. doc = json.loads(self.value)
  598. return doc["bot_email"]
  599. @property
  600. def zulip_api_key(self):
  601. assert self.kind == "zulip"
  602. doc = json.loads(self.value)
  603. return doc["api_key"]
  604. @property
  605. def zulip_type(self):
  606. assert self.kind == "zulip"
  607. doc = json.loads(self.value)
  608. return doc["mtype"]
  609. @property
  610. def zulip_to(self):
  611. assert self.kind == "zulip"
  612. doc = json.loads(self.value)
  613. return doc["to"]
  614. @property
  615. def linenotify_token(self):
  616. assert self.kind == "linenotify"
  617. if not self.value.startswith("{"):
  618. return self.value
  619. doc = json.loads(self.value)
  620. return doc["token"]
  621. class Notification(models.Model):
  622. class Meta:
  623. get_latest_by = "created"
  624. code = models.UUIDField(default=uuid.uuid4, null=True, editable=False)
  625. owner = models.ForeignKey(Check, models.CASCADE, null=True)
  626. check_status = models.CharField(max_length=6)
  627. channel = models.ForeignKey(Channel, models.CASCADE)
  628. created = models.DateTimeField(auto_now_add=True)
  629. error = models.CharField(max_length=200, blank=True)
  630. def status_url(self):
  631. path = reverse("hc-api-notification-status", args=[self.code])
  632. return settings.SITE_ROOT + path
  633. class Flip(models.Model):
  634. owner = models.ForeignKey(Check, models.CASCADE)
  635. created = models.DateTimeField()
  636. processed = models.DateTimeField(null=True, blank=True)
  637. old_status = models.CharField(max_length=8, choices=STATUSES)
  638. new_status = models.CharField(max_length=8, choices=STATUSES)
  639. class Meta:
  640. indexes = [
  641. # For quickly looking up unprocessed flips.
  642. # Used in the sendalerts management command.
  643. models.Index(
  644. fields=["processed"],
  645. name="api_flip_not_processed",
  646. condition=models.Q(processed=None),
  647. )
  648. ]
  649. def to_dict(self):
  650. return {
  651. "timestamp": isostring(self.created),
  652. "up": 1 if self.new_status == "up" else 0,
  653. }
  654. def send_alerts(self):
  655. if self.new_status == "up" and self.old_status in ("new", "paused"):
  656. # Don't send alerts on new->up and paused->up transitions
  657. return []
  658. if self.new_status not in ("up", "down"):
  659. raise NotImplementedError("Unexpected status: %s" % self.status)
  660. errors = []
  661. for channel in self.owner.channel_set.all():
  662. error = channel.notify(self.owner)
  663. if error not in ("", "no-op"):
  664. errors.append((channel, error))
  665. return errors
  666. class TokenBucket(models.Model):
  667. value = models.CharField(max_length=80, unique=True)
  668. tokens = models.FloatField(default=1.0)
  669. updated = models.DateTimeField(default=timezone.now)
  670. @staticmethod
  671. def authorize(value, capacity, refill_time_secs):
  672. now = timezone.now()
  673. obj, created = TokenBucket.objects.get_or_create(value=value)
  674. if not created:
  675. # Top up the bucket:
  676. delta_secs = (now - obj.updated).total_seconds()
  677. obj.tokens = min(1.0, obj.tokens + delta_secs / refill_time_secs)
  678. obj.tokens -= 1.0 / capacity
  679. if obj.tokens < 0:
  680. # Not enough tokens
  681. return False
  682. # Race condition: two concurrent authorize calls can overwrite each
  683. # other's changes. It's OK to be a little inexact here for the sake
  684. # of simplicity.
  685. obj.updated = now
  686. obj.save()
  687. return True
  688. @staticmethod
  689. def authorize_login_email(email):
  690. # remove dots and alias:
  691. mailbox, domain = email.split("@")
  692. mailbox = mailbox.replace(".", "")
  693. mailbox = mailbox.split("+")[0]
  694. email = mailbox + "@" + domain
  695. salted_encoded = (email + settings.SECRET_KEY).encode()
  696. value = "em-%s" % hashlib.sha1(salted_encoded).hexdigest()
  697. # 20 login attempts for a single email per hour:
  698. return TokenBucket.authorize(value, 20, 3600)
  699. @staticmethod
  700. def authorize_invite(user):
  701. value = "invite-%d" % user.id
  702. # 20 invites per day
  703. return TokenBucket.authorize(value, 20, 3600 * 24)
  704. @staticmethod
  705. def authorize_login_password(email):
  706. salted_encoded = (email + settings.SECRET_KEY).encode()
  707. value = "pw-%s" % hashlib.sha1(salted_encoded).hexdigest()
  708. # 20 password attempts per day
  709. return TokenBucket.authorize(value, 20, 3600 * 24)
  710. @staticmethod
  711. def authorize_telegram(telegram_id):
  712. value = "tg-%s" % telegram_id
  713. # 10 messages for a single chat per minute:
  714. return TokenBucket.authorize(value, 10, 60)