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.

298 lines
8.5 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.lib import emails
  8. def tmpl(template_name, **ctx):
  9. template_path = "integrations/%s" % template_name
  10. return render_to_string(template_path, ctx).strip()
  11. class Transport(object):
  12. def __init__(self, channel):
  13. self.channel = channel
  14. def notify(self, check):
  15. """ Send notification about current status of the check.
  16. This method returns None on success, and error message
  17. on error.
  18. """
  19. raise NotImplementedError()
  20. def is_noop(self, check):
  21. """ Return True if transport will ignore check's current status.
  22. This method is overriden in Webhook subclass where the user can
  23. configure webhook urls for "up" and "down" events, and both are
  24. optional.
  25. """
  26. return False
  27. def checks(self):
  28. return self.channel.user.check_set.order_by("created")
  29. class Email(Transport):
  30. def notify(self, check, bounce_url):
  31. if not self.channel.email_verified:
  32. return "Email not verified"
  33. headers = {"X-Bounce-Url": bounce_url}
  34. ctx = {
  35. "check": check,
  36. "checks": self.checks(),
  37. "now": timezone.now(),
  38. "unsub_link": self.channel.get_unsub_link()
  39. }
  40. emails.alert(self.channel.value, ctx, headers)
  41. class HttpTransport(Transport):
  42. @classmethod
  43. def _request(cls, method, url, **kwargs):
  44. try:
  45. options = dict(kwargs)
  46. if "headers" not in options:
  47. options["headers"] = {}
  48. options["timeout"] = 5
  49. options["headers"]["User-Agent"] = "healthchecks.io"
  50. r = requests.request(method, url, **options)
  51. if r.status_code not in (200, 201, 204):
  52. return "Received status code %d" % r.status_code
  53. except requests.exceptions.Timeout:
  54. # Well, we tried
  55. return "Connection timed out"
  56. except requests.exceptions.ConnectionError:
  57. return "Connection failed"
  58. @classmethod
  59. def get(cls, url):
  60. # Make 3 attempts--
  61. for x in range(0, 3):
  62. error = cls._request("get", url)
  63. if error is None:
  64. break
  65. return error
  66. @classmethod
  67. def post(cls, url, **kwargs):
  68. # Make 3 attempts--
  69. for x in range(0, 3):
  70. error = cls._request("post", url, **kwargs)
  71. if error is None:
  72. break
  73. return error
  74. class Webhook(HttpTransport):
  75. def prepare(self, template, check, urlencode=False):
  76. """ Replace variables with actual values.
  77. There should be no bad translations if users use $ symbol in
  78. check's name or tags, because $ gets urlencoded to %24
  79. """
  80. def safe(s):
  81. return quote(s) if urlencode else s
  82. result = template
  83. if "$CODE" in result:
  84. result = result.replace("$CODE", str(check.code))
  85. if "$STATUS" in result:
  86. result = result.replace("$STATUS", check.status)
  87. if "$NOW" in result:
  88. s = timezone.now().replace(microsecond=0).isoformat()
  89. result = result.replace("$NOW", safe(s))
  90. if "$NAME" in result:
  91. result = result.replace("$NAME", safe(check.name))
  92. if "$TAG" in result:
  93. for i, tag in enumerate(check.tags_list()):
  94. placeholder = "$TAG%d" % (i + 1)
  95. result = result.replace(placeholder, safe(tag))
  96. return result
  97. def is_noop(self, check):
  98. if check.status == "down" and not self.channel.value_down:
  99. return True
  100. if check.status == "up" and not self.channel.value_up:
  101. return True
  102. return False
  103. def notify(self, check):
  104. url = self.channel.value_down
  105. if check.status == "up":
  106. url = self.channel.value_up
  107. assert url
  108. url = self.prepare(url, check, urlencode=True)
  109. if self.channel.post_data:
  110. payload = self.prepare(self.channel.post_data, check)
  111. return self.post(url, data=payload)
  112. else:
  113. return self.get(url)
  114. class Slack(HttpTransport):
  115. def notify(self, check):
  116. text = tmpl("slack_message.json", check=check)
  117. payload = json.loads(text)
  118. return self.post(self.channel.slack_webhook_url, json=payload)
  119. class HipChat(HttpTransport):
  120. def notify(self, check):
  121. text = tmpl("hipchat_message.html", check=check)
  122. payload = {
  123. "message": text,
  124. "color": "green" if check.status == "up" else "red",
  125. }
  126. return self.post(self.channel.value, json=payload)
  127. class OpsGenie(HttpTransport):
  128. def notify(self, check):
  129. payload = {
  130. "apiKey": self.channel.value,
  131. "alias": str(check.code),
  132. "source": "healthchecks.io"
  133. }
  134. if check.status == "down":
  135. payload["tags"] = ",".join(check.tags_list())
  136. payload["message"] = tmpl("opsgenie_message.html", check=check)
  137. payload["note"] = tmpl("opsgenie_note.html", check=check)
  138. url = "https://api.opsgenie.com/v1/json/alert"
  139. if check.status == "up":
  140. url += "/close"
  141. return self.post(url, json=payload)
  142. class PagerDuty(HttpTransport):
  143. URL = "https://events.pagerduty.com/generic/2010-04-15/create_event.json"
  144. def notify(self, check):
  145. description = tmpl("pd_description.html", check=check)
  146. payload = {
  147. "service_key": self.channel.value,
  148. "incident_key": str(check.code),
  149. "event_type": "trigger" if check.status == "down" else "resolve",
  150. "description": description,
  151. "client": "healthchecks.io",
  152. "client_url": settings.SITE_ROOT
  153. }
  154. return self.post(self.URL, json=payload)
  155. class Pushbullet(HttpTransport):
  156. def notify(self, check):
  157. text = tmpl("pushbullet_message.html", check=check)
  158. url = "https://api.pushbullet.com/v2/pushes"
  159. headers = {
  160. "Access-Token": self.channel.value,
  161. "Conent-Type": "application/json"
  162. }
  163. payload = {
  164. "type": "note",
  165. "title": "healthchecks.io",
  166. "body": text
  167. }
  168. return self.post(url, json=payload, headers=headers)
  169. class Pushover(HttpTransport):
  170. URL = "https://api.pushover.net/1/messages.json"
  171. def notify(self, check):
  172. others = self.checks().filter(status="down").exclude(code=check.code)
  173. ctx = {
  174. "check": check,
  175. "down_checks": others,
  176. }
  177. text = tmpl("pushover_message.html", **ctx)
  178. title = tmpl("pushover_title.html", **ctx)
  179. user_key, prio = self.channel.value.split("|")
  180. payload = {
  181. "token": settings.PUSHOVER_API_TOKEN,
  182. "user": user_key,
  183. "message": text,
  184. "title": title,
  185. "html": 1,
  186. "priority": int(prio),
  187. }
  188. # Emergency notification
  189. if prio == "2":
  190. payload["retry"] = settings.PUSHOVER_EMERGENCY_RETRY_DELAY
  191. payload["expire"] = settings.PUSHOVER_EMERGENCY_EXPIRATION
  192. return self.post(self.URL, data=payload)
  193. class VictorOps(HttpTransport):
  194. def notify(self, check):
  195. description = tmpl("victorops_description.html", check=check)
  196. mtype = "CRITICAL" if check.status == "down" else "RECOVERY"
  197. payload = {
  198. "entity_id": str(check.code),
  199. "message_type": mtype,
  200. "entity_display_name": check.name_then_code(),
  201. "state_message": description,
  202. "monitoring_tool": "healthchecks.io",
  203. }
  204. return self.post(self.channel.value, json=payload)
  205. class Discord(HttpTransport):
  206. def notify(self, check):
  207. text = tmpl("slack_message.json", check=check)
  208. payload = json.loads(text)
  209. url = self.channel.discord_webhook_url + "/slack"
  210. return self.post(url, json=payload)
  211. class Telegram(HttpTransport):
  212. SM = "https://api.telegram.org/bot%s/sendMessage" % settings.TELEGRAM_TOKEN
  213. @classmethod
  214. def send(cls, chat_id, text):
  215. return cls.post(cls.SM, json={
  216. "chat_id": chat_id,
  217. "text": text,
  218. "parse_mode": "html"
  219. })
  220. def notify(self, check):
  221. text = tmpl("telegram_message.html", check=check)
  222. return self.send(self.channel.telegram_id, text)