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.

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