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.

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