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.

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