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.

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