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.

359 lines
11 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, 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. class Webhook(HttpTransport):
  89. def prepare(self, template, check, urlencode=False):
  90. """ Replace variables with actual values.
  91. There should be no bad translations if users use $ symbol in
  92. check's name or tags, because $ gets urlencoded to %24
  93. """
  94. def safe(s):
  95. return quote(s) if urlencode else s
  96. result = template
  97. if "$CODE" in result:
  98. result = result.replace("$CODE", str(check.code))
  99. if "$STATUS" in result:
  100. result = result.replace("$STATUS", check.status)
  101. if "$NOW" in result:
  102. s = timezone.now().replace(microsecond=0).isoformat()
  103. result = result.replace("$NOW", safe(s))
  104. if "$NAME" in result:
  105. result = result.replace("$NAME", safe(check.name))
  106. if "$TAG" in result:
  107. for i, tag in enumerate(check.tags_list()):
  108. placeholder = "$TAG%d" % (i + 1)
  109. result = result.replace(placeholder, safe(tag))
  110. return result
  111. def is_noop(self, check):
  112. if check.status == "down" and not self.channel.url_down:
  113. return True
  114. if check.status == "up" and not self.channel.url_up:
  115. return True
  116. return False
  117. def notify(self, check):
  118. url = self.channel.url_down
  119. if check.status == "up":
  120. url = self.channel.url_up
  121. assert url
  122. url = self.prepare(url, check, urlencode=True)
  123. headers = {}
  124. for key, value in self.channel.headers.items():
  125. headers[key] = self.prepare(value, check)
  126. if self.channel.post_data:
  127. payload = self.prepare(self.channel.post_data, check)
  128. return self.post(url, data=payload.encode("utf-8"), headers=headers)
  129. else:
  130. return self.get(url, headers=headers)
  131. class Slack(HttpTransport):
  132. def notify(self, check):
  133. text = tmpl("slack_message.json", check=check)
  134. payload = json.loads(text)
  135. return self.post(self.channel.slack_webhook_url, json=payload)
  136. class HipChat(HttpTransport):
  137. def notify(self, check):
  138. text = tmpl("hipchat_message.json", check=check)
  139. payload = json.loads(text)
  140. self.channel.refresh_hipchat_access_token()
  141. return self.post(self.channel.hipchat_webhook_url, json=payload)
  142. class OpsGenie(HttpTransport):
  143. def notify(self, check):
  144. payload = {
  145. "apiKey": self.channel.value,
  146. "alias": str(check.code),
  147. "source": "healthchecks.io"
  148. }
  149. if check.status == "down":
  150. payload["tags"] = ",".join(check.tags_list())
  151. payload["message"] = tmpl("opsgenie_message.html", check=check)
  152. payload["note"] = tmpl("opsgenie_note.html", check=check)
  153. url = "https://api.opsgenie.com/v1/json/alert"
  154. if check.status == "up":
  155. url += "/close"
  156. return self.post(url, json=payload)
  157. class PagerDuty(HttpTransport):
  158. URL = "https://events.pagerduty.com/generic/2010-04-15/create_event.json"
  159. def notify(self, check):
  160. description = tmpl("pd_description.html", check=check)
  161. payload = {
  162. "vendor": settings.PD_VENDOR_KEY,
  163. "service_key": self.channel.pd_service_key,
  164. "incident_key": str(check.code),
  165. "event_type": "trigger" if check.status == "down" else "resolve",
  166. "description": description,
  167. "client": settings.SITE_NAME,
  168. "client_url": settings.SITE_ROOT
  169. }
  170. return self.post(self.URL, json=payload)
  171. class PagerTree(HttpTransport):
  172. def notify(self, check):
  173. url = self.channel.value
  174. headers = {
  175. "Conent-Type": "application/json"
  176. }
  177. payload = {
  178. "incident_key": str(check.code),
  179. "event_type": "trigger" if check.status == "down" else "resolve",
  180. "title": tmpl("pagertree_title.html", check=check),
  181. "description": tmpl("pagertree_description.html", check=check),
  182. "client": settings.SITE_NAME,
  183. "client_url": settings.SITE_ROOT,
  184. "tags": ",".join(check.tags_list())
  185. }
  186. return self.post(url, json=payload, headers=headers)
  187. class Pushbullet(HttpTransport):
  188. def notify(self, check):
  189. text = tmpl("pushbullet_message.html", check=check)
  190. url = "https://api.pushbullet.com/v2/pushes"
  191. headers = {
  192. "Access-Token": self.channel.value,
  193. "Conent-Type": "application/json"
  194. }
  195. payload = {
  196. "type": "note",
  197. "title": "healthchecks.io",
  198. "body": text
  199. }
  200. return self.post(url, json=payload, headers=headers)
  201. class Pushover(HttpTransport):
  202. URL = "https://api.pushover.net/1/messages.json"
  203. def notify(self, check):
  204. others = self.checks().filter(status="down").exclude(code=check.code)
  205. ctx = {
  206. "check": check,
  207. "down_checks": others,
  208. }
  209. text = tmpl("pushover_message.html", **ctx)
  210. title = tmpl("pushover_title.html", **ctx)
  211. user_key, prio = self.channel.value.split("|")
  212. payload = {
  213. "token": settings.PUSHOVER_API_TOKEN,
  214. "user": user_key,
  215. "message": text,
  216. "title": title,
  217. "html": 1,
  218. "priority": int(prio),
  219. }
  220. # Emergency notification
  221. if prio == "2":
  222. payload["retry"] = settings.PUSHOVER_EMERGENCY_RETRY_DELAY
  223. payload["expire"] = settings.PUSHOVER_EMERGENCY_EXPIRATION
  224. return self.post(self.URL, data=payload)
  225. class VictorOps(HttpTransport):
  226. def notify(self, check):
  227. description = tmpl("victorops_description.html", check=check)
  228. mtype = "CRITICAL" if check.status == "down" else "RECOVERY"
  229. payload = {
  230. "entity_id": str(check.code),
  231. "message_type": mtype,
  232. "entity_display_name": check.name_then_code(),
  233. "state_message": description,
  234. "monitoring_tool": "healthchecks.io",
  235. }
  236. return self.post(self.channel.value, json=payload)
  237. class Discord(HttpTransport):
  238. def notify(self, check):
  239. text = tmpl("slack_message.json", check=check)
  240. payload = json.loads(text)
  241. url = self.channel.discord_webhook_url + "/slack"
  242. return self.post(url, json=payload)
  243. class Telegram(HttpTransport):
  244. SM = "https://api.telegram.org/bot%s/sendMessage" % settings.TELEGRAM_TOKEN
  245. @classmethod
  246. def send(cls, chat_id, text):
  247. return cls.post(cls.SM, json={
  248. "chat_id": chat_id,
  249. "text": text,
  250. "parse_mode": "html"
  251. })
  252. def notify(self, check):
  253. text = tmpl("telegram_message.html", check=check)
  254. return self.send(self.channel.telegram_id, text)
  255. class Sms(HttpTransport):
  256. URL = 'https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json'
  257. def is_noop(self, check):
  258. return check.status != "down"
  259. def notify(self, check):
  260. profile = Profile.objects.for_user(self.channel.user)
  261. if not profile.authorize_sms():
  262. return "Monthly SMS limit exceeded"
  263. url = self.URL % settings.TWILIO_ACCOUNT
  264. auth = (settings.TWILIO_ACCOUNT, settings.TWILIO_AUTH)
  265. text = tmpl("sms_message.html", check=check,
  266. site_name=settings.SITE_NAME)
  267. data = {
  268. 'From': settings.TWILIO_FROM,
  269. 'To': self.channel.value,
  270. 'Body': text,
  271. }
  272. return self.post(url, data=data, auth=auth)