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