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.

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