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.

596 lines
19 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
10 years ago
6 years ago
7 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.contrib.auth.models import User
  10. from django.db import models
  11. from django.urls import reverse
  12. from django.utils import timezone
  13. from hc.accounts.models import Project
  14. from hc.api import transports
  15. from hc.lib import emails
  16. import requests
  17. import pytz
  18. STATUSES = (
  19. ("up", "Up"),
  20. ("down", "Down"),
  21. ("new", "New"),
  22. ("paused", "Paused")
  23. )
  24. DEFAULT_TIMEOUT = td(days=1)
  25. DEFAULT_GRACE = td(hours=1)
  26. NEVER = datetime(3000, 1, 1, tzinfo=pytz.UTC)
  27. CHECK_KINDS = (("simple", "Simple"),
  28. ("cron", "Cron"))
  29. CHANNEL_KINDS = (("email", "Email"),
  30. ("webhook", "Webhook"),
  31. ("hipchat", "HipChat"),
  32. ("slack", "Slack"),
  33. ("pd", "PagerDuty"),
  34. ("pagertree", "PagerTree"),
  35. ("po", "Pushover"),
  36. ("pushbullet", "Pushbullet"),
  37. ("opsgenie", "OpsGenie"),
  38. ("victorops", "VictorOps"),
  39. ("discord", "Discord"),
  40. ("telegram", "Telegram"),
  41. ("sms", "SMS"),
  42. ("zendesk", "Zendesk"),
  43. ("trello", "Trello"))
  44. PO_PRIORITIES = {
  45. -2: "lowest",
  46. -1: "low",
  47. 0: "normal",
  48. 1: "high",
  49. 2: "emergency"
  50. }
  51. def isostring(dt):
  52. """Convert the datetime to ISO 8601 format with no microseconds. """
  53. if dt:
  54. return dt.replace(microsecond=0).isoformat()
  55. class Check(models.Model):
  56. name = models.CharField(max_length=100, blank=True)
  57. tags = models.CharField(max_length=500, blank=True)
  58. code = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
  59. desc = models.TextField(blank=True)
  60. user = models.ForeignKey(User, models.CASCADE)
  61. project = models.ForeignKey(Project, models.CASCADE)
  62. created = models.DateTimeField(auto_now_add=True)
  63. kind = models.CharField(max_length=10, default="simple",
  64. choices=CHECK_KINDS)
  65. timeout = models.DurationField(default=DEFAULT_TIMEOUT)
  66. grace = models.DurationField(default=DEFAULT_GRACE)
  67. schedule = models.CharField(max_length=100, default="* * * * *")
  68. tz = models.CharField(max_length=36, default="UTC")
  69. subject = models.CharField(max_length=100, blank=True)
  70. n_pings = models.IntegerField(default=0)
  71. last_ping = models.DateTimeField(null=True, blank=True)
  72. last_start = models.DateTimeField(null=True, blank=True)
  73. last_ping_was_fail = models.NullBooleanField(default=False)
  74. has_confirmation_link = models.BooleanField(default=False)
  75. alert_after = models.DateTimeField(null=True, blank=True, editable=False)
  76. status = models.CharField(max_length=6, choices=STATUSES, default="new")
  77. def __str__(self):
  78. return "%s (%d)" % (self.name or self.code, self.id)
  79. def name_then_code(self):
  80. if self.name:
  81. return self.name
  82. return str(self.code)
  83. def url(self):
  84. return settings.PING_ENDPOINT + str(self.code)
  85. def details_url(self):
  86. return settings.SITE_ROOT + reverse("hc-details", args=[self.code])
  87. def email(self):
  88. return "%s@%s" % (self.code, settings.PING_EMAIL_DOMAIN)
  89. def get_grace_start(self):
  90. """ Return the datetime when the grace period starts.
  91. If the check is currently new, paused or down, return None.
  92. """
  93. # NEVER is a constant sentinel value (year 3000).
  94. # Using None instead would make the logic clunky.
  95. result = NEVER
  96. if self.kind == "simple" and self.status == "up":
  97. result = self.last_ping + self.timeout
  98. elif self.kind == "cron" and self.status == "up":
  99. # The complex case, next ping is expected based on cron schedule.
  100. # Don't convert to naive datetimes (and so avoid ambiguities around
  101. # DST transitions). Croniter will handle the timezone-aware datetimes.
  102. zone = pytz.timezone(self.tz)
  103. last_local = timezone.localtime(self.last_ping, zone)
  104. it = croniter(self.schedule, last_local)
  105. result = it.next(datetime)
  106. if self.last_start and self.status != "down":
  107. result = min(result, self.last_start)
  108. if result != NEVER:
  109. return result
  110. def going_down_after(self):
  111. """ Return the datetime when the check goes down.
  112. If the check is new or paused, and not currently running, return None.
  113. If the check is already down, also return None.
  114. """
  115. grace_start = self.get_grace_start()
  116. if grace_start is not None:
  117. return grace_start + self.grace
  118. def get_status(self, now=None, with_started=True):
  119. """ Return current status for display. """
  120. if now is None:
  121. now = timezone.now()
  122. if self.last_start:
  123. if now >= self.last_start + self.grace:
  124. return "down"
  125. elif with_started:
  126. return "started"
  127. if self.status in ("new", "paused", "down"):
  128. return self.status
  129. grace_start = self.get_grace_start()
  130. grace_end = grace_start + self.grace
  131. if now >= grace_end:
  132. return "down"
  133. if now >= grace_start:
  134. return "grace"
  135. return "up"
  136. def assign_all_channels(self):
  137. if self.user:
  138. channels = Channel.objects.filter(user=self.user)
  139. self.channel_set.add(*channels)
  140. def tags_list(self):
  141. return [t.strip() for t in self.tags.split(" ") if t.strip()]
  142. def matches_tag_set(self, tag_set):
  143. return tag_set.issubset(self.tags_list())
  144. def to_dict(self):
  145. update_rel_url = reverse("hc-api-update", args=[self.code])
  146. pause_rel_url = reverse("hc-api-pause", args=[self.code])
  147. channel_codes = [str(ch.code) for ch in self.channel_set.all()]
  148. result = {
  149. "name": self.name,
  150. "ping_url": self.url(),
  151. "update_url": settings.SITE_ROOT + update_rel_url,
  152. "pause_url": settings.SITE_ROOT + pause_rel_url,
  153. "tags": self.tags,
  154. "grace": int(self.grace.total_seconds()),
  155. "n_pings": self.n_pings,
  156. "status": self.get_status(),
  157. "channels": ",".join(sorted(channel_codes)),
  158. "last_ping": isostring(self.last_ping),
  159. "next_ping": isostring(self.get_grace_start())
  160. }
  161. if self.kind == "simple":
  162. result["timeout"] = int(self.timeout.total_seconds())
  163. elif self.kind == "cron":
  164. result["schedule"] = self.schedule
  165. result["tz"] = self.tz
  166. return result
  167. def ping(self, remote_addr, scheme, method, ua, body, action):
  168. if action == "start":
  169. self.last_start = timezone.now()
  170. # Don't update "last_ping" field.
  171. elif action == "ign":
  172. pass
  173. else:
  174. self.last_start = None
  175. self.last_ping = timezone.now()
  176. new_status = "down" if action == "fail" else "up"
  177. if self.status != new_status:
  178. flip = Flip(owner=self)
  179. flip.created = self.last_ping
  180. flip.old_status = self.status
  181. flip.new_status = new_status
  182. flip.save()
  183. self.status = new_status
  184. self.alert_after = self.going_down_after()
  185. self.n_pings = models.F("n_pings") + 1
  186. self.has_confirmation_link = "confirm" in str(body).lower()
  187. self.save()
  188. self.refresh_from_db()
  189. ping = Ping(owner=self)
  190. ping.n = self.n_pings
  191. if action in ("start", "fail", "ign"):
  192. ping.kind = action
  193. ping.remote_addr = remote_addr
  194. ping.scheme = scheme
  195. ping.method = method
  196. # If User-Agent is longer than 200 characters, truncate it:
  197. ping.ua = ua[:200]
  198. ping.body = body[:10000]
  199. ping.save()
  200. class Ping(models.Model):
  201. id = models.BigAutoField(primary_key=True)
  202. n = models.IntegerField(null=True)
  203. owner = models.ForeignKey(Check, models.CASCADE)
  204. created = models.DateTimeField(auto_now_add=True)
  205. kind = models.CharField(max_length=6, blank=True, null=True)
  206. scheme = models.CharField(max_length=10, default="http")
  207. remote_addr = models.GenericIPAddressField(blank=True, null=True)
  208. method = models.CharField(max_length=10, blank=True)
  209. ua = models.CharField(max_length=200, blank=True)
  210. body = models.CharField(max_length=10000, blank=True, null=True)
  211. class Channel(models.Model):
  212. name = models.CharField(max_length=100, blank=True)
  213. code = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)
  214. user = models.ForeignKey(User, models.CASCADE)
  215. project = models.ForeignKey(Project, models.CASCADE)
  216. created = models.DateTimeField(auto_now_add=True)
  217. kind = models.CharField(max_length=20, choices=CHANNEL_KINDS)
  218. value = models.TextField(blank=True)
  219. email_verified = models.BooleanField(default=False)
  220. checks = models.ManyToManyField(Check)
  221. def __str__(self):
  222. if self.name:
  223. return self.name
  224. if self.kind == "email":
  225. return "Email to %s" % self.value
  226. elif self.kind == "sms":
  227. return "SMS to %s" % self.sms_number
  228. elif self.kind == "slack":
  229. return "Slack %s" % self.slack_channel
  230. elif self.kind == "telegram":
  231. return "Telegram %s" % self.telegram_name
  232. return self.get_kind_display()
  233. def to_dict(self):
  234. return {
  235. "id": str(self.code),
  236. "name": self.name,
  237. "kind": self.kind
  238. }
  239. def assign_all_checks(self):
  240. checks = Check.objects.filter(user=self.user)
  241. self.checks.add(*checks)
  242. def make_token(self):
  243. seed = "%s%s" % (self.code, settings.SECRET_KEY)
  244. seed = seed.encode()
  245. return hashlib.sha1(seed).hexdigest()
  246. def send_verify_link(self):
  247. args = [self.code, self.make_token()]
  248. verify_link = reverse("hc-verify-email", args=args)
  249. verify_link = settings.SITE_ROOT + verify_link
  250. emails.verify_email(self.value, {"verify_link": verify_link})
  251. def get_unsub_link(self):
  252. args = [self.code, self.make_token()]
  253. verify_link = reverse("hc-unsubscribe-alerts", args=args)
  254. return settings.SITE_ROOT + verify_link
  255. @property
  256. def transport(self):
  257. if self.kind == "email":
  258. return transports.Email(self)
  259. elif self.kind == "webhook":
  260. return transports.Webhook(self)
  261. elif self.kind == "slack":
  262. return transports.Slack(self)
  263. elif self.kind == "hipchat":
  264. return transports.HipChat(self)
  265. elif self.kind == "pd":
  266. return transports.PagerDuty(self)
  267. elif self.kind == "pagertree":
  268. return transports.PagerTree(self)
  269. elif self.kind == "victorops":
  270. return transports.VictorOps(self)
  271. elif self.kind == "pushbullet":
  272. return transports.Pushbullet(self)
  273. elif self.kind == "po":
  274. return transports.Pushover(self)
  275. elif self.kind == "opsgenie":
  276. return transports.OpsGenie(self)
  277. elif self.kind == "discord":
  278. return transports.Discord(self)
  279. elif self.kind == "telegram":
  280. return transports.Telegram(self)
  281. elif self.kind == "sms":
  282. return transports.Sms(self)
  283. elif self.kind == "trello":
  284. return transports.Trello(self)
  285. else:
  286. raise NotImplementedError("Unknown channel kind: %s" % self.kind)
  287. def notify(self, check):
  288. if self.transport.is_noop(check):
  289. return "no-op"
  290. n = Notification(owner=check, channel=self)
  291. n.check_status = check.status
  292. n.error = "Sending"
  293. n.save()
  294. if self.kind == "email":
  295. error = self.transport.notify(check, n.bounce_url()) or ""
  296. else:
  297. error = self.transport.notify(check) or ""
  298. n.error = error
  299. n.save()
  300. return error
  301. def icon_path(self):
  302. return 'img/integrations/%s.png' % self.kind
  303. @property
  304. def po_priority(self):
  305. assert self.kind == "po"
  306. parts = self.value.split("|")
  307. prio = int(parts[1])
  308. return PO_PRIORITIES[prio]
  309. @property
  310. def url_down(self):
  311. assert self.kind == "webhook"
  312. if not self.value.startswith("{"):
  313. parts = self.value.split("\n")
  314. return parts[0]
  315. doc = json.loads(self.value)
  316. return doc.get("url_down")
  317. @property
  318. def url_up(self):
  319. assert self.kind == "webhook"
  320. if not self.value.startswith("{"):
  321. parts = self.value.split("\n")
  322. return parts[1] if len(parts) > 1 else ""
  323. doc = json.loads(self.value)
  324. return doc.get("url_up")
  325. @property
  326. def post_data(self):
  327. assert self.kind == "webhook"
  328. if not self.value.startswith("{"):
  329. parts = self.value.split("\n")
  330. return parts[2] if len(parts) > 2 else ""
  331. doc = json.loads(self.value)
  332. return doc.get("post_data")
  333. @property
  334. def headers(self):
  335. assert self.kind == "webhook"
  336. if not self.value.startswith("{"):
  337. return {}
  338. doc = json.loads(self.value)
  339. return doc.get("headers", {})
  340. @property
  341. def slack_team(self):
  342. assert self.kind == "slack"
  343. if not self.value.startswith("{"):
  344. return None
  345. doc = json.loads(self.value)
  346. return doc["team_name"]
  347. @property
  348. def slack_channel(self):
  349. assert self.kind == "slack"
  350. if not self.value.startswith("{"):
  351. return None
  352. doc = json.loads(self.value)
  353. return doc["incoming_webhook"]["channel"]
  354. @property
  355. def slack_webhook_url(self):
  356. assert self.kind == "slack"
  357. if not self.value.startswith("{"):
  358. return self.value
  359. doc = json.loads(self.value)
  360. return doc["incoming_webhook"]["url"]
  361. @property
  362. def discord_webhook_url(self):
  363. assert self.kind == "discord"
  364. doc = json.loads(self.value)
  365. return doc["webhook"]["url"]
  366. @property
  367. def discord_webhook_id(self):
  368. assert self.kind == "discord"
  369. doc = json.loads(self.value)
  370. return doc["webhook"]["id"]
  371. @property
  372. def telegram_id(self):
  373. assert self.kind == "telegram"
  374. doc = json.loads(self.value)
  375. return doc.get("id")
  376. @property
  377. def telegram_type(self):
  378. assert self.kind == "telegram"
  379. doc = json.loads(self.value)
  380. return doc.get("type")
  381. @property
  382. def telegram_name(self):
  383. assert self.kind == "telegram"
  384. doc = json.loads(self.value)
  385. return doc.get("name")
  386. def refresh_hipchat_access_token(self):
  387. assert self.kind == "hipchat"
  388. if not self.value.startswith("{"):
  389. return # Don't have OAuth credentials
  390. doc = json.loads(self.value)
  391. if time.time() < doc.get("expires_at", 0):
  392. return # Current access token is still valid
  393. url = "https://api.hipchat.com/v2/oauth/token"
  394. auth = (doc["oauthId"], doc["oauthSecret"])
  395. r = requests.post(url, auth=auth, data={
  396. "grant_type": "client_credentials",
  397. "scope": "send_notification"
  398. })
  399. doc.update(r.json())
  400. doc["expires_at"] = int(time.time()) + doc["expires_in"] - 300
  401. self.value = json.dumps(doc)
  402. self.save()
  403. @property
  404. def hipchat_webhook_url(self):
  405. assert self.kind == "hipchat"
  406. if not self.value.startswith("{"):
  407. return self.value
  408. doc = json.loads(self.value)
  409. tmpl = "https://api.hipchat.com/v2/room/%s/notification?auth_token=%s"
  410. return tmpl % (doc["roomId"], doc.get("access_token"))
  411. @property
  412. def pd_service_key(self):
  413. assert self.kind == "pd"
  414. if not self.value.startswith("{"):
  415. return self.value
  416. doc = json.loads(self.value)
  417. return doc["service_key"]
  418. @property
  419. def pd_account(self):
  420. assert self.kind == "pd"
  421. if self.value.startswith("{"):
  422. doc = json.loads(self.value)
  423. return doc["account"]
  424. def latest_notification(self):
  425. return Notification.objects.filter(channel=self).latest()
  426. @property
  427. def sms_number(self):
  428. assert self.kind == "sms"
  429. if self.value.startswith("{"):
  430. doc = json.loads(self.value)
  431. return doc["value"]
  432. return self.value
  433. @property
  434. def sms_label(self):
  435. assert self.kind == "sms"
  436. if self.value.startswith("{"):
  437. doc = json.loads(self.value)
  438. return doc["label"]
  439. @property
  440. def trello_token(self):
  441. assert self.kind == "trello"
  442. if self.value.startswith("{"):
  443. doc = json.loads(self.value)
  444. return doc["token"]
  445. @property
  446. def trello_board_list(self):
  447. assert self.kind == "trello"
  448. if self.value.startswith("{"):
  449. doc = json.loads(self.value)
  450. return doc["board_name"], doc["list_name"]
  451. @property
  452. def trello_list_id(self):
  453. assert self.kind == "trello"
  454. if self.value.startswith("{"):
  455. doc = json.loads(self.value)
  456. return doc["list_id"]
  457. class Notification(models.Model):
  458. class Meta:
  459. get_latest_by = "created"
  460. code = models.UUIDField(default=uuid.uuid4, null=True, editable=False)
  461. owner = models.ForeignKey(Check, models.CASCADE)
  462. check_status = models.CharField(max_length=6)
  463. channel = models.ForeignKey(Channel, models.CASCADE)
  464. created = models.DateTimeField(auto_now_add=True)
  465. error = models.CharField(max_length=200, blank=True)
  466. def bounce_url(self):
  467. return settings.SITE_ROOT + reverse("hc-api-bounce", args=[self.code])
  468. class Flip(models.Model):
  469. owner = models.ForeignKey(Check, models.CASCADE)
  470. created = models.DateTimeField()
  471. processed = models.DateTimeField(null=True, blank=True, db_index=True)
  472. old_status = models.CharField(max_length=8, choices=STATUSES)
  473. new_status = models.CharField(max_length=8, choices=STATUSES)
  474. def send_alerts(self):
  475. if self.new_status == "up" and self.old_status in ("new", "paused"):
  476. # Don't send alerts on new->up and paused->up transitions
  477. return []
  478. if self.new_status not in ("up", "down"):
  479. raise NotImplementedError("Unexpected status: %s" % self.status)
  480. errors = []
  481. for channel in self.owner.channel_set.all():
  482. error = channel.notify(self.owner)
  483. if error not in ("", "no-op"):
  484. errors.append((channel, error))
  485. return errors