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.

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