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.

421 lines
13 KiB

  1. from django.conf import settings
  2. from django.template.loader import render_to_string
  3. from django.utils import timezone
  4. import json
  5. import requests
  6. from six.moves.urllib.parse import quote
  7. from hc.accounts.models import Profile
  8. from hc.lib import emails
  9. def tmpl(template_name, **ctx):
  10. template_path = "integrations/%s" % template_name
  11. # \xa0 is non-breaking space. It causes SMS messages to use UCS2 encoding
  12. # and cost twice the money.
  13. return render_to_string(template_path, ctx).strip().replace(u"\xa0", " ")
  14. class Transport(object):
  15. def __init__(self, channel):
  16. self.channel = channel
  17. def notify(self, check):
  18. """ Send notification about current status of the check.
  19. This method returns None on success, and error message
  20. on error.
  21. """
  22. raise NotImplementedError()
  23. def is_noop(self, check):
  24. """ Return True if transport will ignore check's current status.
  25. This method is overriden in Webhook subclass where the user can
  26. configure webhook urls for "up" and "down" events, and both are
  27. optional.
  28. """
  29. return False
  30. def checks(self):
  31. return self.channel.user.check_set.order_by("created")
  32. class Email(Transport):
  33. def notify(self, check, bounce_url):
  34. if not self.channel.email_verified:
  35. return "Email not verified"
  36. headers = {"X-Bounce-Url": bounce_url}
  37. try:
  38. # Look up the sorting preference for this email address
  39. p = Profile.objects.get(user__email=self.channel.value)
  40. sort = p.sort
  41. except Profile.DoesNotExist:
  42. # Default sort order is by check's creation time
  43. sort = "created"
  44. ctx = {
  45. "check": check,
  46. "checks": self.checks(),
  47. "sort": sort,
  48. "now": timezone.now(),
  49. "unsub_link": self.channel.get_unsub_link()
  50. }
  51. emails.alert(self.channel.value, ctx, headers)
  52. def is_noop(self, check):
  53. return not self.channel.email_verified
  54. class HttpTransport(Transport):
  55. @classmethod
  56. def _request(cls, method, url, **kwargs):
  57. try:
  58. options = dict(kwargs)
  59. options["timeout"] = 5
  60. if "headers" not in options:
  61. options["headers"] = {}
  62. if "User-Agent" not in options["headers"]:
  63. options["headers"]["User-Agent"] = "healthchecks.io"
  64. r = requests.request(method, url, **options)
  65. if r.status_code not in (200, 201, 202, 204):
  66. return "Received status code %d" % r.status_code
  67. except requests.exceptions.Timeout:
  68. # Well, we tried
  69. return "Connection timed out"
  70. except requests.exceptions.ConnectionError:
  71. return "Connection failed"
  72. @classmethod
  73. def get(cls, url, **kwargs):
  74. # Make 3 attempts--
  75. for x in range(0, 3):
  76. error = cls._request("get", url, **kwargs)
  77. if error is None:
  78. break
  79. return error
  80. @classmethod
  81. def post(cls, url, **kwargs):
  82. # Make 3 attempts--
  83. for x in range(0, 3):
  84. error = cls._request("post", url, **kwargs)
  85. if error is None:
  86. break
  87. return error
  88. @classmethod
  89. def put(cls, url, **kwargs):
  90. # Make 3 attempts--
  91. for x in range(0, 3):
  92. error = cls._request("put", url, **kwargs)
  93. if error is None:
  94. break
  95. return error
  96. class Webhook(HttpTransport):
  97. def prepare(self, template, check, urlencode=False):
  98. """ Replace variables with actual values.
  99. There should be no bad translations if users use $ symbol in
  100. check's name or tags, because $ gets urlencoded to %24
  101. """
  102. def safe(s):
  103. return quote(s) if urlencode else s
  104. result = template
  105. if "$CODE" in result:
  106. result = result.replace("$CODE", str(check.code))
  107. if "$STATUS" in result:
  108. result = result.replace("$STATUS", check.status)
  109. if "$NOW" in result:
  110. s = timezone.now().replace(microsecond=0).isoformat()
  111. result = result.replace("$NOW", safe(s))
  112. if "$NAME" in result:
  113. result = result.replace("$NAME", safe(check.name))
  114. if "$TAG" in result:
  115. for i, tag in enumerate(check.tags_list()):
  116. placeholder = "$TAG%d" % (i + 1)
  117. result = result.replace(placeholder, safe(tag))
  118. return result
  119. def is_noop(self, check):
  120. if check.status == "down" and not self.channel.url_down:
  121. return True
  122. if check.status == "up" and not self.channel.url_up:
  123. return True
  124. return False
  125. def notify(self, check):
  126. url = self.channel.url_down
  127. if check.status == "up":
  128. url = self.channel.url_up
  129. assert url
  130. url = self.prepare(url, check, urlencode=True)
  131. headers = {}
  132. for key, value in self.channel.headers.items():
  133. headers[key] = self.prepare(value, check)
  134. if self.channel.post_data:
  135. payload = self.prepare(self.channel.post_data, check)
  136. return self.post(url, data=payload.encode("utf-8"), headers=headers)
  137. else:
  138. return self.get(url, headers=headers)
  139. class Slack(HttpTransport):
  140. def notify(self, check):
  141. text = tmpl("slack_message.json", check=check)
  142. payload = json.loads(text)
  143. return self.post(self.channel.slack_webhook_url, json=payload)
  144. class HipChat(HttpTransport):
  145. def notify(self, check):
  146. text = tmpl("hipchat_message.json", check=check)
  147. payload = json.loads(text)
  148. self.channel.refresh_hipchat_access_token()
  149. return self.post(self.channel.hipchat_webhook_url, json=payload)
  150. class OpsGenie(HttpTransport):
  151. def notify(self, check):
  152. headers = {
  153. "Conent-Type": "application/json",
  154. "Authorization": "GenieKey %s" % self.channel.value
  155. }
  156. payload = {
  157. "alias": str(check.code),
  158. "source": settings.SITE_NAME
  159. }
  160. if check.status == "down":
  161. payload["tags"] = check.tags_list()
  162. payload["message"] = tmpl("opsgenie_message.html", check=check)
  163. payload["note"] = tmpl("opsgenie_note.html", check=check)
  164. payload["description"] = \
  165. tmpl("opsgenie_description.html", check=check)
  166. url = "https://api.opsgenie.com/v2/alerts"
  167. if check.status == "up":
  168. url += "/%s/close?identifierType=alias" % check.code
  169. return self.post(url, json=payload, headers=headers)
  170. class PagerDuty(HttpTransport):
  171. URL = "https://events.pagerduty.com/generic/2010-04-15/create_event.json"
  172. def notify(self, check):
  173. description = tmpl("pd_description.html", check=check)
  174. payload = {
  175. "vendor": settings.PD_VENDOR_KEY,
  176. "service_key": self.channel.pd_service_key,
  177. "incident_key": str(check.code),
  178. "event_type": "trigger" if check.status == "down" else "resolve",
  179. "description": description,
  180. "client": settings.SITE_NAME,
  181. "client_url": settings.SITE_ROOT
  182. }
  183. return self.post(self.URL, json=payload)
  184. class PagerTree(HttpTransport):
  185. def notify(self, check):
  186. url = self.channel.value
  187. headers = {
  188. "Conent-Type": "application/json"
  189. }
  190. payload = {
  191. "incident_key": str(check.code),
  192. "event_type": "trigger" if check.status == "down" else "resolve",
  193. "title": tmpl("pagertree_title.html", check=check),
  194. "description": tmpl("pagertree_description.html", check=check),
  195. "client": settings.SITE_NAME,
  196. "client_url": settings.SITE_ROOT,
  197. "tags": ",".join(check.tags_list())
  198. }
  199. return self.post(url, json=payload, headers=headers)
  200. class Pushbullet(HttpTransport):
  201. def notify(self, check):
  202. text = tmpl("pushbullet_message.html", check=check)
  203. url = "https://api.pushbullet.com/v2/pushes"
  204. headers = {
  205. "Access-Token": self.channel.value,
  206. "Conent-Type": "application/json"
  207. }
  208. payload = {
  209. "type": "note",
  210. "title": settings.SITE_NAME,
  211. "body": text
  212. }
  213. return self.post(url, json=payload, headers=headers)
  214. class Pushover(HttpTransport):
  215. URL = "https://api.pushover.net/1/messages.json"
  216. def notify(self, check):
  217. others = self.checks().filter(status="down").exclude(code=check.code)
  218. ctx = {
  219. "check": check,
  220. "down_checks": others,
  221. }
  222. text = tmpl("pushover_message.html", **ctx)
  223. title = tmpl("pushover_title.html", **ctx)
  224. user_key, prio = self.channel.value.split("|")
  225. payload = {
  226. "token": settings.PUSHOVER_API_TOKEN,
  227. "user": user_key,
  228. "message": text,
  229. "title": title,
  230. "html": 1,
  231. "priority": int(prio),
  232. }
  233. # Emergency notification
  234. if prio == "2":
  235. payload["retry"] = settings.PUSHOVER_EMERGENCY_RETRY_DELAY
  236. payload["expire"] = settings.PUSHOVER_EMERGENCY_EXPIRATION
  237. return self.post(self.URL, data=payload)
  238. class VictorOps(HttpTransport):
  239. def notify(self, check):
  240. description = tmpl("victorops_description.html", check=check)
  241. mtype = "CRITICAL" if check.status == "down" else "RECOVERY"
  242. payload = {
  243. "entity_id": str(check.code),
  244. "message_type": mtype,
  245. "entity_display_name": check.name_then_code(),
  246. "state_message": description,
  247. "monitoring_tool": settings.SITE_NAME,
  248. }
  249. return self.post(self.channel.value, json=payload)
  250. class Discord(HttpTransport):
  251. def notify(self, check):
  252. text = tmpl("slack_message.json", check=check)
  253. payload = json.loads(text)
  254. url = self.channel.discord_webhook_url + "/slack"
  255. return self.post(url, json=payload)
  256. class Telegram(HttpTransport):
  257. SM = "https://api.telegram.org/bot%s/sendMessage" % settings.TELEGRAM_TOKEN
  258. @classmethod
  259. def send(cls, chat_id, text):
  260. return cls.post(cls.SM, json={
  261. "chat_id": chat_id,
  262. "text": text,
  263. "parse_mode": "html"
  264. })
  265. def notify(self, check):
  266. text = tmpl("telegram_message.html", check=check)
  267. return self.send(self.channel.telegram_id, text)
  268. class Sms(HttpTransport):
  269. URL = 'https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json'
  270. def is_noop(self, check):
  271. return check.status != "down"
  272. def notify(self, check):
  273. profile = Profile.objects.for_user(self.channel.user)
  274. if not profile.authorize_sms():
  275. return "Monthly SMS limit exceeded"
  276. url = self.URL % settings.TWILIO_ACCOUNT
  277. auth = (settings.TWILIO_ACCOUNT, settings.TWILIO_AUTH)
  278. text = tmpl("sms_message.html", check=check,
  279. site_name=settings.SITE_NAME)
  280. data = {
  281. 'From': settings.TWILIO_FROM,
  282. 'To': self.channel.value,
  283. 'Body': text,
  284. }
  285. return self.post(url, data=data, auth=auth)
  286. class Zendesk(HttpTransport):
  287. TMPL = "https://%s.zendesk.com/api/v2/requests.json"
  288. def get_payload(self, check):
  289. return {
  290. "request": {
  291. "subject": tmpl("zendesk_title.html", check=check),
  292. "type": "incident",
  293. "comment": {
  294. "body": tmpl("zendesk_description.html", check=check)
  295. }
  296. }
  297. }
  298. def notify_down(self, check):
  299. headers = {"Authorization": "Bearer %s" % self.channel.zendesk_token}
  300. url = self.TMPL % self.channel.zendesk_subdomain
  301. return self.post(url, headers=headers, json=self.get_payload(check))
  302. def notify_up(self, check):
  303. # Get the list of requests made by us, in newest-to-oldest order
  304. url = self.TMPL % self.channel.zendesk_subdomain
  305. url += "?sort_by=created_at&sort_order=desc"
  306. headers = {"Authorization": "Bearer %s" % self.channel.zendesk_token}
  307. r = requests.get(url, headers=headers, timeout=10)
  308. if r.status_code != 200:
  309. return "Received status code %d" % r.status_code
  310. # Update the first request that has check.code in its description
  311. doc = r.json()
  312. if "requests" in doc:
  313. for obj in doc["requests"]:
  314. if str(check.code) in obj["description"]:
  315. payload = self.get_payload(check)
  316. return self.put(obj["url"], headers=headers, json=payload)
  317. return "Could not find a ticket to update"
  318. def notify(self, check):
  319. if check.status == "down":
  320. return self.notify_down(check)
  321. if check.status == "up":
  322. return self.notify_up(check)