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.

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