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.

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