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.

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