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.

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