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.

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