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.

590 lines
18 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. new_status = "down" if action == "fail" else "up"
  185. if self.status != new_status:
  186. flip = Flip(owner=self)
  187. flip.created = self.last_ping
  188. flip.old_status = self.status
  189. flip.new_status = new_status
  190. flip.save()
  191. self.status = new_status
  192. self.alert_after = self.going_down_after()
  193. self.n_pings = models.F("n_pings") + 1
  194. self.has_confirmation_link = "confirm" in str(body).lower()
  195. self.save()
  196. self.refresh_from_db()
  197. ping = Ping(owner=self)
  198. ping.n = self.n_pings
  199. ping.start = action == "start"
  200. ping.fail = action == "fail"
  201. ping.remote_addr = remote_addr
  202. ping.scheme = scheme
  203. ping.method = method
  204. # If User-Agent is longer than 200 characters, truncate it:
  205. ping.ua = ua[:200]
  206. ping.body = body[:10000]
  207. ping.save()
  208. class Ping(models.Model):
  209. id = models.BigAutoField(primary_key=True)
  210. n = models.IntegerField(null=True)
  211. owner = models.ForeignKey(Check, models.CASCADE)
  212. created = models.DateTimeField(auto_now_add=True)
  213. start = models.NullBooleanField(default=False)
  214. fail = models.NullBooleanField(default=False)
  215. scheme = models.CharField(max_length=10, default="http")
  216. remote_addr = models.GenericIPAddressField(blank=True, null=True)
  217. method = models.CharField(max_length=10, blank=True)
  218. ua = models.CharField(max_length=200, blank=True)
  219. body = models.CharField(max_length=10000, blank=True, null=True)
  220. class Channel(models.Model):
  221. name = models.CharField(max_length=100, blank=True)
  222. code = models.UUIDField(default=uuid.uuid4, editable=False)
  223. user = models.ForeignKey(User, models.CASCADE)
  224. created = models.DateTimeField(auto_now_add=True)
  225. kind = models.CharField(max_length=20, choices=CHANNEL_KINDS)
  226. value = models.TextField(blank=True)
  227. email_verified = models.BooleanField(default=False)
  228. checks = models.ManyToManyField(Check)
  229. def __str__(self):
  230. if self.name:
  231. return self.name
  232. if self.kind == "email":
  233. return "Email to %s" % self.value
  234. elif self.kind == "sms":
  235. return "SMS to %s" % self.sms_number
  236. elif self.kind == "slack":
  237. return "Slack %s" % self.slack_channel
  238. elif self.kind == "telegram":
  239. return "Telegram %s" % self.telegram_name
  240. return self.get_kind_display()
  241. def to_dict(self):
  242. return {
  243. "id": str(self.code),
  244. "name": self.name,
  245. "kind": self.kind
  246. }
  247. def assign_all_checks(self):
  248. checks = Check.objects.filter(user=self.user)
  249. self.checks.add(*checks)
  250. def make_token(self):
  251. seed = "%s%s" % (self.code, settings.SECRET_KEY)
  252. seed = seed.encode()
  253. return hashlib.sha1(seed).hexdigest()
  254. def send_verify_link(self):
  255. args = [self.code, self.make_token()]
  256. verify_link = reverse("hc-verify-email", args=args)
  257. verify_link = settings.SITE_ROOT + verify_link
  258. emails.verify_email(self.value, {"verify_link": verify_link})
  259. def get_unsub_link(self):
  260. args = [self.code, self.make_token()]
  261. verify_link = reverse("hc-unsubscribe-alerts", args=args)
  262. return settings.SITE_ROOT + verify_link
  263. @property
  264. def transport(self):
  265. if self.kind == "email":
  266. return transports.Email(self)
  267. elif self.kind == "webhook":
  268. return transports.Webhook(self)
  269. elif self.kind == "slack":
  270. return transports.Slack(self)
  271. elif self.kind == "hipchat":
  272. return transports.HipChat(self)
  273. elif self.kind == "pd":
  274. return transports.PagerDuty(self)
  275. elif self.kind == "pagertree":
  276. return transports.PagerTree(self)
  277. elif self.kind == "victorops":
  278. return transports.VictorOps(self)
  279. elif self.kind == "pushbullet":
  280. return transports.Pushbullet(self)
  281. elif self.kind == "po":
  282. return transports.Pushover(self)
  283. elif self.kind == "opsgenie":
  284. return transports.OpsGenie(self)
  285. elif self.kind == "discord":
  286. return transports.Discord(self)
  287. elif self.kind == "telegram":
  288. return transports.Telegram(self)
  289. elif self.kind == "sms":
  290. return transports.Sms(self)
  291. elif self.kind == "trello":
  292. return transports.Trello(self)
  293. else:
  294. raise NotImplementedError("Unknown channel kind: %s" % self.kind)
  295. def notify(self, check):
  296. if self.transport.is_noop(check):
  297. return "no-op"
  298. n = Notification(owner=check, channel=self)
  299. n.check_status = check.status
  300. n.error = "Sending"
  301. n.save()
  302. if self.kind == "email":
  303. error = self.transport.notify(check, n.bounce_url()) or ""
  304. else:
  305. error = self.transport.notify(check) or ""
  306. n.error = error
  307. n.save()
  308. return error
  309. def icon_path(self):
  310. return 'img/integrations/%s.png' % self.kind
  311. @property
  312. def po_priority(self):
  313. assert self.kind == "po"
  314. parts = self.value.split("|")
  315. prio = int(parts[1])
  316. return PO_PRIORITIES[prio]
  317. @property
  318. def url_down(self):
  319. assert self.kind == "webhook"
  320. if not self.value.startswith("{"):
  321. parts = self.value.split("\n")
  322. return parts[0]
  323. doc = json.loads(self.value)
  324. return doc.get("url_down")
  325. @property
  326. def url_up(self):
  327. assert self.kind == "webhook"
  328. if not self.value.startswith("{"):
  329. parts = self.value.split("\n")
  330. return parts[1] if len(parts) > 1 else ""
  331. doc = json.loads(self.value)
  332. return doc.get("url_up")
  333. @property
  334. def post_data(self):
  335. assert self.kind == "webhook"
  336. if not self.value.startswith("{"):
  337. parts = self.value.split("\n")
  338. return parts[2] if len(parts) > 2 else ""
  339. doc = json.loads(self.value)
  340. return doc.get("post_data")
  341. @property
  342. def headers(self):
  343. assert self.kind == "webhook"
  344. if not self.value.startswith("{"):
  345. return {}
  346. doc = json.loads(self.value)
  347. return doc.get("headers", {})
  348. @property
  349. def slack_team(self):
  350. assert self.kind == "slack"
  351. if not self.value.startswith("{"):
  352. return None
  353. doc = json.loads(self.value)
  354. return doc["team_name"]
  355. @property
  356. def slack_channel(self):
  357. assert self.kind == "slack"
  358. if not self.value.startswith("{"):
  359. return None
  360. doc = json.loads(self.value)
  361. return doc["incoming_webhook"]["channel"]
  362. @property
  363. def slack_webhook_url(self):
  364. assert self.kind == "slack"
  365. if not self.value.startswith("{"):
  366. return self.value
  367. doc = json.loads(self.value)
  368. return doc["incoming_webhook"]["url"]
  369. @property
  370. def discord_webhook_url(self):
  371. assert self.kind == "discord"
  372. doc = json.loads(self.value)
  373. return doc["webhook"]["url"]
  374. @property
  375. def discord_webhook_id(self):
  376. assert self.kind == "discord"
  377. doc = json.loads(self.value)
  378. return doc["webhook"]["id"]
  379. @property
  380. def telegram_id(self):
  381. assert self.kind == "telegram"
  382. doc = json.loads(self.value)
  383. return doc.get("id")
  384. @property
  385. def telegram_type(self):
  386. assert self.kind == "telegram"
  387. doc = json.loads(self.value)
  388. return doc.get("type")
  389. @property
  390. def telegram_name(self):
  391. assert self.kind == "telegram"
  392. doc = json.loads(self.value)
  393. return doc.get("name")
  394. def refresh_hipchat_access_token(self):
  395. assert self.kind == "hipchat"
  396. if not self.value.startswith("{"):
  397. return # Don't have OAuth credentials
  398. doc = json.loads(self.value)
  399. if time.time() < doc.get("expires_at", 0):
  400. return # Current access token is still valid
  401. url = "https://api.hipchat.com/v2/oauth/token"
  402. auth = (doc["oauthId"], doc["oauthSecret"])
  403. r = requests.post(url, auth=auth, data={
  404. "grant_type": "client_credentials",
  405. "scope": "send_notification"
  406. })
  407. doc.update(r.json())
  408. doc["expires_at"] = int(time.time()) + doc["expires_in"] - 300
  409. self.value = json.dumps(doc)
  410. self.save()
  411. @property
  412. def hipchat_webhook_url(self):
  413. assert self.kind == "hipchat"
  414. if not self.value.startswith("{"):
  415. return self.value
  416. doc = json.loads(self.value)
  417. tmpl = "https://api.hipchat.com/v2/room/%s/notification?auth_token=%s"
  418. return tmpl % (doc["roomId"], doc.get("access_token"))
  419. @property
  420. def pd_service_key(self):
  421. assert self.kind == "pd"
  422. if not self.value.startswith("{"):
  423. return self.value
  424. doc = json.loads(self.value)
  425. return doc["service_key"]
  426. @property
  427. def pd_account(self):
  428. assert self.kind == "pd"
  429. if self.value.startswith("{"):
  430. doc = json.loads(self.value)
  431. return doc["account"]
  432. def latest_notification(self):
  433. return Notification.objects.filter(channel=self).latest()
  434. @property
  435. def sms_number(self):
  436. assert self.kind == "sms"
  437. if self.value.startswith("{"):
  438. doc = json.loads(self.value)
  439. return doc["value"]
  440. return self.value
  441. @property
  442. def sms_label(self):
  443. assert self.kind == "sms"
  444. if self.value.startswith("{"):
  445. doc = json.loads(self.value)
  446. return doc["label"]
  447. @property
  448. def trello_token(self):
  449. assert self.kind == "trello"
  450. if self.value.startswith("{"):
  451. doc = json.loads(self.value)
  452. return doc["token"]
  453. @property
  454. def trello_board_list(self):
  455. assert self.kind == "trello"
  456. if self.value.startswith("{"):
  457. doc = json.loads(self.value)
  458. return doc["board_name"], doc["list_name"]
  459. @property
  460. def trello_list_id(self):
  461. assert self.kind == "trello"
  462. if self.value.startswith("{"):
  463. doc = json.loads(self.value)
  464. return doc["list_id"]
  465. class Notification(models.Model):
  466. class Meta:
  467. get_latest_by = "created"
  468. code = models.UUIDField(default=uuid.uuid4, null=True, editable=False)
  469. owner = models.ForeignKey(Check, models.CASCADE)
  470. check_status = models.CharField(max_length=6)
  471. channel = models.ForeignKey(Channel, models.CASCADE)
  472. created = models.DateTimeField(auto_now_add=True)
  473. error = models.CharField(max_length=200, blank=True)
  474. def bounce_url(self):
  475. return settings.SITE_ROOT + reverse("hc-api-bounce", args=[self.code])
  476. class Flip(models.Model):
  477. owner = models.ForeignKey(Check, models.CASCADE)
  478. created = models.DateTimeField()
  479. processed = models.DateTimeField(null=True, blank=True, db_index=True)
  480. old_status = models.CharField(max_length=8, choices=STATUSES)
  481. new_status = models.CharField(max_length=8, choices=STATUSES)