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.

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