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.

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