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.

463 lines
14 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("\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 "$TAGS" in result:
  123. result = result.replace("$TAGS", safe(check.tags))
  124. if "$TAG" in result:
  125. for i, tag in enumerate(check.tags_list()):
  126. placeholder = "$TAG%d" % (i + 1)
  127. result = result.replace(placeholder, safe(tag))
  128. return result
  129. def is_noop(self, check):
  130. if check.status == "down" and not self.channel.url_down:
  131. return True
  132. if check.status == "up" and not self.channel.url_up:
  133. return True
  134. return False
  135. def notify(self, check):
  136. spec = self.channel.webhook_spec(check.status)
  137. assert spec["url"]
  138. url = self.prepare(spec["url"], check, urlencode=True)
  139. headers = {}
  140. for key, value in spec["headers"].items():
  141. headers[key] = self.prepare(value, check)
  142. body = spec["body"]
  143. if body:
  144. body = self.prepare(body, check)
  145. if spec["method"] == "GET":
  146. return self.get(url, headers=headers)
  147. elif spec["method"] == "POST":
  148. return self.post(url, data=body.encode(), headers=headers)
  149. elif spec["method"] == "PUT":
  150. return self.put(url, data=body.encode(), headers=headers)
  151. class Slack(HttpTransport):
  152. def notify(self, check):
  153. text = tmpl("slack_message.json", check=check)
  154. payload = json.loads(text)
  155. return self.post(self.channel.slack_webhook_url, json=payload)
  156. class HipChat(HttpTransport):
  157. def is_noop(self, check):
  158. return True
  159. class OpsGenie(HttpTransport):
  160. def notify(self, check):
  161. headers = {
  162. "Conent-Type": "application/json",
  163. "Authorization": "GenieKey %s" % self.channel.value,
  164. }
  165. payload = {"alias": str(check.code), "source": settings.SITE_NAME}
  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"] = tmpl("opsgenie_description.html", check=check)
  171. url = "https://api.opsgenie.com/v2/alerts"
  172. if check.status == "up":
  173. url += "/%s/close?identifierType=alias" % check.code
  174. return self.post(url, json=payload, headers=headers)
  175. class PagerDuty(HttpTransport):
  176. URL = "https://events.pagerduty.com/generic/2010-04-15/create_event.json"
  177. def notify(self, check):
  178. description = tmpl("pd_description.html", check=check)
  179. payload = {
  180. "vendor": settings.PD_VENDOR_KEY,
  181. "service_key": self.channel.pd_service_key,
  182. "incident_key": str(check.code),
  183. "event_type": "trigger" if check.status == "down" else "resolve",
  184. "description": description,
  185. "client": settings.SITE_NAME,
  186. "client_url": settings.SITE_ROOT,
  187. }
  188. return self.post(self.URL, json=payload)
  189. class PagerTree(HttpTransport):
  190. def notify(self, check):
  191. url = self.channel.value
  192. headers = {"Conent-Type": "application/json"}
  193. payload = {
  194. "incident_key": str(check.code),
  195. "event_type": "trigger" if check.status == "down" else "resolve",
  196. "title": tmpl("pagertree_title.html", check=check),
  197. "description": tmpl("pagertree_description.html", check=check),
  198. "client": settings.SITE_NAME,
  199. "client_url": settings.SITE_ROOT,
  200. "tags": ",".join(check.tags_list()),
  201. }
  202. return self.post(url, json=payload, headers=headers)
  203. class PagerTeam(HttpTransport):
  204. def notify(self, check):
  205. url = self.channel.value
  206. headers = {"Conent-Type": "application/json"}
  207. payload = {
  208. "incident_key": str(check.code),
  209. "event_type": "trigger" if check.status == "down" else "resolve",
  210. "title": tmpl("pagerteam_title.html", check=check),
  211. "description": tmpl("pagerteam_description.html", check=check),
  212. "client": settings.SITE_NAME,
  213. "client_url": settings.SITE_ROOT,
  214. "tags": ",".join(check.tags_list()),
  215. }
  216. return self.post(url, json=payload, headers=headers)
  217. class Pushbullet(HttpTransport):
  218. def notify(self, check):
  219. text = tmpl("pushbullet_message.html", check=check)
  220. url = "https://api.pushbullet.com/v2/pushes"
  221. headers = {
  222. "Access-Token": self.channel.value,
  223. "Conent-Type": "application/json",
  224. }
  225. payload = {"type": "note", "title": settings.SITE_NAME, "body": text}
  226. return self.post(url, json=payload, headers=headers)
  227. class Pushover(HttpTransport):
  228. URL = "https://api.pushover.net/1/messages.json"
  229. def notify(self, check):
  230. others = self.checks().filter(status="down").exclude(code=check.code)
  231. # list() executes the query, to avoid DB access while
  232. # rendering a template
  233. ctx = {"check": check, "down_checks": list(others)}
  234. text = tmpl("pushover_message.html", **ctx)
  235. title = tmpl("pushover_title.html", **ctx)
  236. pieces = self.channel.value.split("|")
  237. user_key, prio = pieces[0], pieces[1]
  238. # The third element, if present, is the priority for "up" events
  239. if len(pieces) == 3 and check.status == "up":
  240. prio = pieces[2]
  241. payload = {
  242. "token": settings.PUSHOVER_API_TOKEN,
  243. "user": user_key,
  244. "message": text,
  245. "title": title,
  246. "html": 1,
  247. "priority": int(prio),
  248. }
  249. # Emergency notification
  250. if prio == "2":
  251. payload["retry"] = settings.PUSHOVER_EMERGENCY_RETRY_DELAY
  252. payload["expire"] = settings.PUSHOVER_EMERGENCY_EXPIRATION
  253. return self.post(self.URL, data=payload)
  254. class VictorOps(HttpTransport):
  255. def notify(self, check):
  256. description = tmpl("victorops_description.html", check=check)
  257. mtype = "CRITICAL" if check.status == "down" else "RECOVERY"
  258. payload = {
  259. "entity_id": str(check.code),
  260. "message_type": mtype,
  261. "entity_display_name": check.name_then_code(),
  262. "state_message": description,
  263. "monitoring_tool": settings.SITE_NAME,
  264. }
  265. return self.post(self.channel.value, json=payload)
  266. class Matrix(HttpTransport):
  267. def get_url(self):
  268. s = quote(self.channel.value)
  269. url = settings.MATRIX_HOMESERVER
  270. url += "/_matrix/client/r0/rooms/%s/send/m.room.message?" % s
  271. url += urlencode({"access_token": settings.MATRIX_ACCESS_TOKEN})
  272. return url
  273. def notify(self, check):
  274. plain = tmpl("matrix_description.html", check=check)
  275. formatted = tmpl("matrix_description_formatted.html", check=check)
  276. payload = {
  277. "msgtype": "m.text",
  278. "body": plain,
  279. "format": "org.matrix.custom.html",
  280. "formatted_body": formatted,
  281. }
  282. return self.post(self.get_url(), json=payload)
  283. class Discord(HttpTransport):
  284. def notify(self, check):
  285. text = tmpl("slack_message.json", check=check)
  286. payload = json.loads(text)
  287. url = self.channel.discord_webhook_url + "/slack"
  288. return self.post(url, json=payload)
  289. class Telegram(HttpTransport):
  290. SM = "https://api.telegram.org/bot%s/sendMessage" % settings.TELEGRAM_TOKEN
  291. @classmethod
  292. def send(cls, chat_id, text):
  293. return cls.post(
  294. cls.SM, json={"chat_id": chat_id, "text": text, "parse_mode": "html"}
  295. )
  296. def notify(self, check):
  297. text = tmpl("telegram_message.html", check=check)
  298. return self.send(self.channel.telegram_id, text)
  299. class Sms(HttpTransport):
  300. URL = "https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json"
  301. def is_noop(self, check):
  302. return check.status != "down"
  303. def notify(self, check):
  304. profile = Profile.objects.for_user(self.channel.project.owner)
  305. if not profile.authorize_sms():
  306. return "Monthly SMS limit exceeded"
  307. url = self.URL % settings.TWILIO_ACCOUNT
  308. auth = (settings.TWILIO_ACCOUNT, settings.TWILIO_AUTH)
  309. text = tmpl("sms_message.html", check=check, site_name=settings.SITE_NAME)
  310. data = {
  311. "From": settings.TWILIO_FROM,
  312. "To": self.channel.sms_number,
  313. "Body": text,
  314. }
  315. return self.post(url, data=data, auth=auth)
  316. class WhatsApp(HttpTransport):
  317. URL = "https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json"
  318. def is_noop(self, check):
  319. if check.status == "down":
  320. return not self.channel.whatsapp_notify_down
  321. else:
  322. return not self.channel.whatsapp_notify_up
  323. def notify(self, check):
  324. profile = Profile.objects.for_user(self.channel.project.owner)
  325. if not profile.authorize_sms():
  326. return "Monthly message limit exceeded"
  327. url = self.URL % settings.TWILIO_ACCOUNT
  328. auth = (settings.TWILIO_ACCOUNT, settings.TWILIO_AUTH)
  329. text = tmpl("whatsapp_message.html", check=check, site_name=settings.SITE_NAME)
  330. data = {
  331. "From": "whatsapp:%s" % settings.TWILIO_FROM,
  332. "To": "whatsapp:%s" % self.channel.sms_number,
  333. "Body": text,
  334. }
  335. return self.post(url, data=data, auth=auth)
  336. class Trello(HttpTransport):
  337. URL = "https://api.trello.com/1/cards"
  338. def is_noop(self, check):
  339. return check.status != "down"
  340. def notify(self, check):
  341. params = {
  342. "idList": self.channel.trello_list_id,
  343. "name": tmpl("trello_name.html", check=check),
  344. "desc": tmpl("trello_desc.html", check=check),
  345. "key": settings.TRELLO_APP_KEY,
  346. "token": self.channel.trello_token,
  347. }
  348. return self.post(self.URL, params=params)