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.

197 lines
5.7 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 test(self):
  21. """ Send test message.
  22. This method returns None on success, and error message
  23. on error.
  24. """
  25. raise NotImplementedError()
  26. def checks(self):
  27. return self.channel.user.check_set.order_by("created")
  28. class Email(Transport):
  29. def notify(self, check):
  30. if not self.channel.email_verified:
  31. return "Email not verified"
  32. show_upgrade_note = False
  33. if settings.USE_PAYMENTS and check.status == "up":
  34. if not check.user.profile.team_access_allowed:
  35. show_upgrade_note = True
  36. ctx = {
  37. "check": check,
  38. "checks": self.checks(),
  39. "now": timezone.now(),
  40. "show_upgrade_note": show_upgrade_note
  41. }
  42. emails.alert(self.channel.value, ctx)
  43. class HttpTransport(Transport):
  44. def request(self, method, url, **kwargs):
  45. try:
  46. options = dict(kwargs)
  47. options["timeout"] = 5
  48. options["headers"] = {"User-Agent": "healthchecks.io"}
  49. r = requests.request(method, url, **options)
  50. if r.status_code not in (200, 201, 204):
  51. return "Received status code %d" % r.status_code
  52. except requests.exceptions.Timeout:
  53. # Well, we tried
  54. return "Connection timed out"
  55. except requests.exceptions.ConnectionError:
  56. return "Connection failed"
  57. def get(self, url):
  58. return self.request("get", url)
  59. def post(self, url, json):
  60. return self.request("post", url, json=json)
  61. def post_form(self, url, data):
  62. return self.request("post", url, data=data)
  63. class Webhook(HttpTransport):
  64. def notify(self, check):
  65. url = self.channel.value_down
  66. if check.status == "up":
  67. url = self.channel.value_up
  68. if not url:
  69. # If the URL is empty then we do nothing
  70. return "no-op"
  71. # Replace variables with actual values.
  72. # There should be no bad translations if users use $ symbol in
  73. # check's name or tags, because $ gets urlencoded to %24
  74. if "$CODE" in url:
  75. url = url.replace("$CODE", str(check.code))
  76. if "$STATUS" in url:
  77. url = url.replace("$STATUS", check.status)
  78. if "$NAME" in url:
  79. url = url.replace("$NAME", quote(check.name))
  80. if "$TAG" in url:
  81. for i, tag in enumerate(check.tags_list()):
  82. placeholder = "$TAG%d" % (i + 1)
  83. url = url.replace(placeholder, quote(tag))
  84. return self.get(url)
  85. def test(self):
  86. return self.get(self.channel.value)
  87. class Slack(HttpTransport):
  88. def notify(self, check):
  89. text = tmpl("slack_message.json", check=check)
  90. payload = json.loads(text)
  91. return self.post(self.channel.slack_webhook_url, payload)
  92. class HipChat(HttpTransport):
  93. def notify(self, check):
  94. text = tmpl("hipchat_message.html", check=check)
  95. payload = {
  96. "message": text,
  97. "color": "green" if check.status == "up" else "red",
  98. }
  99. return self.post(self.channel.value, payload)
  100. class PagerDuty(HttpTransport):
  101. URL = "https://events.pagerduty.com/generic/2010-04-15/create_event.json"
  102. def notify(self, check):
  103. description = tmpl("pd_description.html", check=check)
  104. payload = {
  105. "service_key": self.channel.value,
  106. "incident_key": str(check.code),
  107. "event_type": "trigger" if check.status == "down" else "resolve",
  108. "description": description,
  109. "client": "healthchecks.io",
  110. "client_url": settings.SITE_ROOT
  111. }
  112. return self.post(self.URL, payload)
  113. class Pushover(HttpTransport):
  114. URL = "https://api.pushover.net/1/messages.json"
  115. def notify(self, check):
  116. others = self.checks().filter(status="down").exclude(code=check.code)
  117. ctx = {
  118. "check": check,
  119. "down_checks": others,
  120. }
  121. text = tmpl("pushover_message.html", **ctx)
  122. title = tmpl("pushover_title.html", **ctx)
  123. user_key, prio = self.channel.value.split("|")
  124. payload = {
  125. "token": settings.PUSHOVER_API_TOKEN,
  126. "user": user_key,
  127. "message": text,
  128. "title": title,
  129. "html": 1,
  130. "priority": int(prio),
  131. }
  132. # Emergency notification
  133. if prio == "2":
  134. payload["retry"] = settings.PUSHOVER_EMERGENCY_RETRY_DELAY
  135. payload["expire"] = settings.PUSHOVER_EMERGENCY_EXPIRATION
  136. return self.post_form(self.URL, payload)
  137. class VictorOps(HttpTransport):
  138. def notify(self, check):
  139. description = tmpl("victorops_description.html", check=check)
  140. payload = {
  141. "entity_id": str(check.code),
  142. "message_type": "CRITICAL" if check.status == "down" else "RECOVERY",
  143. "entity_display_name": check.name_then_code(),
  144. "state_message": description,
  145. "monitoring_tool": "healthchecks.io",
  146. }
  147. return self.post(self.channel.value, payload)