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.

433 lines
13 KiB

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