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.

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