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.

410 lines
12 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 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.project.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. unsub_link = self.channel.get_unsub_link()
  37. headers = {
  38. "X-Bounce-Url": bounce_url,
  39. "List-Unsubscribe": unsub_link
  40. }
  41. try:
  42. # Look up the sorting preference for this email address
  43. p = Profile.objects.get(user__email=self.channel.value)
  44. sort = p.sort
  45. except Profile.DoesNotExist:
  46. # Default sort order is by check's creation time
  47. sort = "created"
  48. # list() executes the query, to avoid DB access while
  49. # rendering a template
  50. ctx = {
  51. "check": check,
  52. "checks": list(self.checks()),
  53. "sort": sort,
  54. "now": timezone.now(),
  55. "unsub_link": unsub_link
  56. }
  57. emails.alert(self.channel.value, ctx, headers)
  58. def is_noop(self, check):
  59. return not self.channel.email_verified
  60. class HttpTransport(Transport):
  61. @classmethod
  62. def _request(cls, method, url, **kwargs):
  63. try:
  64. options = dict(kwargs)
  65. options["timeout"] = 5
  66. if "headers" not in options:
  67. options["headers"] = {}
  68. if "User-Agent" not in options["headers"]:
  69. options["headers"]["User-Agent"] = "healthchecks.io"
  70. r = requests.request(method, url, **options)
  71. if r.status_code not in (200, 201, 202, 204):
  72. return "Received status code %d" % r.status_code
  73. except requests.exceptions.Timeout:
  74. # Well, we tried
  75. return "Connection timed out"
  76. except requests.exceptions.ConnectionError:
  77. return "Connection failed"
  78. @classmethod
  79. def get(cls, url, **kwargs):
  80. # Make 3 attempts--
  81. for x in range(0, 3):
  82. error = cls._request("get", url, **kwargs)
  83. if error is None:
  84. break
  85. return error
  86. @classmethod
  87. def post(cls, url, **kwargs):
  88. # Make 3 attempts--
  89. for x in range(0, 3):
  90. error = cls._request("post", url, **kwargs)
  91. if error is None:
  92. break
  93. return error
  94. @classmethod
  95. def put(cls, url, **kwargs):
  96. # Make 3 attempts--
  97. for x in range(0, 3):
  98. error = cls._request("put", url, **kwargs)
  99. if error is None:
  100. break
  101. return error
  102. class Webhook(HttpTransport):
  103. def prepare(self, template, check, urlencode=False):
  104. """ Replace variables with actual values.
  105. There should be no bad translations if users use $ symbol in
  106. check's name or tags, because $ gets urlencoded to %24
  107. """
  108. def safe(s):
  109. return quote(s) if urlencode else s
  110. result = template
  111. if "$CODE" in result:
  112. result = result.replace("$CODE", str(check.code))
  113. if "$STATUS" in result:
  114. result = result.replace("$STATUS", check.status)
  115. if "$NOW" in result:
  116. s = timezone.now().replace(microsecond=0).isoformat()
  117. result = result.replace("$NOW", safe(s))
  118. if "$NAME" in result:
  119. result = result.replace("$NAME", safe(check.name))
  120. if "$TAG" in result:
  121. for i, tag in enumerate(check.tags_list()):
  122. placeholder = "$TAG%d" % (i + 1)
  123. result = result.replace(placeholder, safe(tag))
  124. return result
  125. def is_noop(self, check):
  126. if check.status == "down" and not self.channel.url_down:
  127. return True
  128. if check.status == "up" and not self.channel.url_up:
  129. return True
  130. return False
  131. def notify(self, check):
  132. url = self.channel.url_down
  133. if check.status == "up":
  134. url = self.channel.url_up
  135. assert url
  136. url = self.prepare(url, check, urlencode=True)
  137. headers = {}
  138. for key, value in self.channel.headers.items():
  139. headers[key] = self.prepare(value, check)
  140. if self.channel.post_data:
  141. payload = self.prepare(self.channel.post_data, check)
  142. return self.post(url, data=payload.encode(), headers=headers)
  143. else:
  144. return self.get(url, headers=headers)
  145. class Slack(HttpTransport):
  146. def notify(self, check):
  147. text = tmpl("slack_message.json", check=check)
  148. payload = json.loads(text)
  149. return self.post(self.channel.slack_webhook_url, json=payload)
  150. class HipChat(HttpTransport):
  151. def notify(self, check):
  152. text = tmpl("hipchat_message.json", check=check)
  153. payload = json.loads(text)
  154. self.channel.refresh_hipchat_access_token()
  155. return self.post(self.channel.hipchat_webhook_url, json=payload)
  156. class OpsGenie(HttpTransport):
  157. def notify(self, check):
  158. headers = {
  159. "Conent-Type": "application/json",
  160. "Authorization": "GenieKey %s" % self.channel.value
  161. }
  162. payload = {
  163. "alias": str(check.code),
  164. "source": settings.SITE_NAME
  165. }
  166. if check.status == "down":
  167. payload["tags"] = check.tags_list()
  168. payload["message"] = tmpl("opsgenie_message.html", check=check)
  169. payload["note"] = tmpl("opsgenie_note.html", check=check)
  170. payload["description"] = \
  171. tmpl("opsgenie_description.html", check=check)
  172. url = "https://api.opsgenie.com/v2/alerts"
  173. if check.status == "up":
  174. url += "/%s/close?identifierType=alias" % check.code
  175. return self.post(url, json=payload, headers=headers)
  176. class PagerDuty(HttpTransport):
  177. URL = "https://events.pagerduty.com/generic/2010-04-15/create_event.json"
  178. def notify(self, check):
  179. description = tmpl("pd_description.html", check=check)
  180. payload = {
  181. "vendor": settings.PD_VENDOR_KEY,
  182. "service_key": self.channel.pd_service_key,
  183. "incident_key": str(check.code),
  184. "event_type": "trigger" if check.status == "down" else "resolve",
  185. "description": description,
  186. "client": settings.SITE_NAME,
  187. "client_url": settings.SITE_ROOT
  188. }
  189. return self.post(self.URL, json=payload)
  190. class PagerTree(HttpTransport):
  191. def notify(self, check):
  192. url = self.channel.value
  193. headers = {
  194. "Conent-Type": "application/json"
  195. }
  196. payload = {
  197. "incident_key": str(check.code),
  198. "event_type": "trigger" if check.status == "down" else "resolve",
  199. "title": tmpl("pagertree_title.html", check=check),
  200. "description": tmpl("pagertree_description.html", check=check),
  201. "client": settings.SITE_NAME,
  202. "client_url": settings.SITE_ROOT,
  203. "tags": ",".join(check.tags_list())
  204. }
  205. return self.post(url, json=payload, headers=headers)
  206. class Pushbullet(HttpTransport):
  207. def notify(self, check):
  208. text = tmpl("pushbullet_message.html", check=check)
  209. url = "https://api.pushbullet.com/v2/pushes"
  210. headers = {
  211. "Access-Token": self.channel.value,
  212. "Conent-Type": "application/json"
  213. }
  214. payload = {
  215. "type": "note",
  216. "title": settings.SITE_NAME,
  217. "body": text
  218. }
  219. return self.post(url, json=payload, headers=headers)
  220. class Pushover(HttpTransport):
  221. URL = "https://api.pushover.net/1/messages.json"
  222. def notify(self, check):
  223. others = self.checks().filter(status="down").exclude(code=check.code)
  224. # list() executes the query, to avoid DB access while
  225. # rendering a template
  226. ctx = {
  227. "check": check,
  228. "down_checks": list(others),
  229. }
  230. text = tmpl("pushover_message.html", **ctx)
  231. title = tmpl("pushover_title.html", **ctx)
  232. pieces = self.channel.value.split("|")
  233. user_key, prio = pieces[0], pieces[1]
  234. # The third element, if present, is the priority for "up" events
  235. if len(pieces) == 3 and check.status == "up":
  236. prio = pieces[2]
  237. payload = {
  238. "token": settings.PUSHOVER_API_TOKEN,
  239. "user": user_key,
  240. "message": text,
  241. "title": title,
  242. "html": 1,
  243. "priority": int(prio),
  244. }
  245. # Emergency notification
  246. if prio == "2":
  247. payload["retry"] = settings.PUSHOVER_EMERGENCY_RETRY_DELAY
  248. payload["expire"] = settings.PUSHOVER_EMERGENCY_EXPIRATION
  249. return self.post(self.URL, data=payload)
  250. class VictorOps(HttpTransport):
  251. def notify(self, check):
  252. description = tmpl("victorops_description.html", check=check)
  253. mtype = "CRITICAL" if check.status == "down" else "RECOVERY"
  254. payload = {
  255. "entity_id": str(check.code),
  256. "message_type": mtype,
  257. "entity_display_name": check.name_then_code(),
  258. "state_message": description,
  259. "monitoring_tool": settings.SITE_NAME,
  260. }
  261. return self.post(self.channel.value, json=payload)
  262. class Discord(HttpTransport):
  263. def notify(self, check):
  264. text = tmpl("slack_message.json", check=check)
  265. payload = json.loads(text)
  266. url = self.channel.discord_webhook_url + "/slack"
  267. return self.post(url, json=payload)
  268. class Telegram(HttpTransport):
  269. SM = "https://api.telegram.org/bot%s/sendMessage" % settings.TELEGRAM_TOKEN
  270. @classmethod
  271. def send(cls, chat_id, text):
  272. return cls.post(cls.SM, json={
  273. "chat_id": chat_id,
  274. "text": text,
  275. "parse_mode": "html"
  276. })
  277. def notify(self, check):
  278. text = tmpl("telegram_message.html", check=check)
  279. return self.send(self.channel.telegram_id, text)
  280. class Sms(HttpTransport):
  281. URL = 'https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json'
  282. def is_noop(self, check):
  283. return check.status != "down"
  284. def notify(self, check):
  285. profile = Profile.objects.for_user(self.channel.user)
  286. if not profile.authorize_sms():
  287. return "Monthly SMS limit exceeded"
  288. url = self.URL % settings.TWILIO_ACCOUNT
  289. auth = (settings.TWILIO_ACCOUNT, settings.TWILIO_AUTH)
  290. text = tmpl("sms_message.html", check=check,
  291. site_name=settings.SITE_NAME)
  292. data = {
  293. 'From': settings.TWILIO_FROM,
  294. 'To': self.channel.sms_number,
  295. 'Body': text,
  296. }
  297. return self.post(url, data=data, auth=auth)
  298. class Trello(HttpTransport):
  299. URL = 'https://api.trello.com/1/cards'
  300. def is_noop(self, check):
  301. return check.status != "down"
  302. def notify(self, check):
  303. params = {
  304. "idList": self.channel.trello_list_id,
  305. "name": tmpl("trello_name.html", check=check),
  306. "desc": tmpl("trello_desc.html", check=check),
  307. "key": settings.TRELLO_APP_KEY,
  308. "token": self.channel.trello_token
  309. }
  310. return self.post(self.URL, params=params)