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.

540 lines
16 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. import os
  2. from django.conf import settings
  3. from django.template.loader import render_to_string
  4. from django.utils import timezone
  5. import json
  6. import requests
  7. from urllib.parse import quote, urlencode
  8. from hc.accounts.models import Profile
  9. from hc.lib import emails
  10. from hc.lib.string import replace
  11. try:
  12. import apprise
  13. except ImportError:
  14. # Enforce
  15. settings.APPRISE_ENABLED = False
  16. def tmpl(template_name, **ctx):
  17. template_path = "integrations/%s" % template_name
  18. # \xa0 is non-breaking space. It causes SMS messages to use UCS2 encoding
  19. # and cost twice the money.
  20. return render_to_string(template_path, ctx).strip().replace("\xa0", " ")
  21. class Transport(object):
  22. def __init__(self, channel):
  23. self.channel = channel
  24. def notify(self, check):
  25. """ Send notification about current status of the check.
  26. This method returns None on success, and error message
  27. on error.
  28. """
  29. raise NotImplementedError()
  30. def is_noop(self, check):
  31. """ Return True if transport will ignore check's current status.
  32. This method is overriden in Webhook subclass where the user can
  33. configure webhook urls for "up" and "down" events, and both are
  34. optional.
  35. """
  36. return False
  37. def checks(self):
  38. return self.channel.project.check_set.order_by("created")
  39. class Email(Transport):
  40. def notify(self, check, bounce_url):
  41. if not self.channel.email_verified:
  42. return "Email not verified"
  43. unsub_link = self.channel.get_unsub_link()
  44. headers = {
  45. "X-Bounce-Url": bounce_url,
  46. "List-Unsubscribe": "<%s>" % unsub_link,
  47. "List-Unsubscribe-Post": "List-Unsubscribe=One-Click",
  48. }
  49. try:
  50. # Look up the sorting preference for this email address
  51. p = Profile.objects.get(user__email=self.channel.email_value)
  52. sort = p.sort
  53. except Profile.DoesNotExist:
  54. # Default sort order is by check's creation time
  55. sort = "created"
  56. # list() executes the query, to avoid DB access while
  57. # rendering a template
  58. ctx = {
  59. "check": check,
  60. "checks": list(self.checks()),
  61. "sort": sort,
  62. "now": timezone.now(),
  63. "unsub_link": unsub_link,
  64. }
  65. emails.alert(self.channel.email_value, ctx, headers)
  66. def is_noop(self, check):
  67. if not self.channel.email_verified:
  68. return True
  69. if check.status == "down":
  70. return not self.channel.email_notify_down
  71. else:
  72. return not self.channel.email_notify_up
  73. class Shell(Transport):
  74. def prepare(self, template, check):
  75. """ Replace placeholders with actual values. """
  76. ctx = {
  77. "$CODE": str(check.code),
  78. "$STATUS": check.status,
  79. "$NOW": timezone.now().replace(microsecond=0).isoformat(),
  80. "$NAME": check.name,
  81. "$TAGS": check.tags,
  82. }
  83. for i, tag in enumerate(check.tags_list()):
  84. ctx["$TAG%d" % (i + 1)] = tag
  85. return replace(template, ctx)
  86. def is_noop(self, check):
  87. if check.status == "down" and not self.channel.cmd_down:
  88. return True
  89. if check.status == "up" and not self.channel.cmd_up:
  90. return True
  91. return False
  92. def notify(self, check):
  93. if not settings.SHELL_ENABLED:
  94. return "Shell commands are not enabled"
  95. if check.status == "up":
  96. cmd = self.channel.cmd_up
  97. elif check.status == "down":
  98. cmd = self.channel.cmd_down
  99. cmd = self.prepare(cmd, check)
  100. code = os.system(cmd)
  101. if code != 0:
  102. return "Command returned exit code %d" % code
  103. class HttpTransport(Transport):
  104. @classmethod
  105. def _request(cls, method, url, **kwargs):
  106. try:
  107. options = dict(kwargs)
  108. options["timeout"] = 5
  109. if "headers" not in options:
  110. options["headers"] = {}
  111. if "User-Agent" not in options["headers"]:
  112. options["headers"]["User-Agent"] = "healthchecks.io"
  113. r = requests.request(method, url, **options)
  114. if r.status_code not in (200, 201, 202, 204):
  115. return "Received status code %d" % r.status_code
  116. except requests.exceptions.Timeout:
  117. # Well, we tried
  118. return "Connection timed out"
  119. except requests.exceptions.ConnectionError:
  120. return "Connection failed"
  121. @classmethod
  122. def get(cls, url, **kwargs):
  123. # Make 3 attempts--
  124. for x in range(0, 3):
  125. error = cls._request("get", url, **kwargs)
  126. if error is None:
  127. break
  128. return error
  129. @classmethod
  130. def post(cls, url, **kwargs):
  131. # Make 3 attempts--
  132. for x in range(0, 3):
  133. error = cls._request("post", url, **kwargs)
  134. if error is None:
  135. break
  136. return error
  137. @classmethod
  138. def put(cls, url, **kwargs):
  139. # Make 3 attempts--
  140. for x in range(0, 3):
  141. error = cls._request("put", url, **kwargs)
  142. if error is None:
  143. break
  144. return error
  145. class Webhook(HttpTransport):
  146. def prepare(self, template, check, urlencode=False):
  147. """ Replace variables with actual values. """
  148. def safe(s):
  149. return quote(s) if urlencode else s
  150. ctx = {
  151. "$CODE": str(check.code),
  152. "$STATUS": check.status,
  153. "$NOW": safe(timezone.now().replace(microsecond=0).isoformat()),
  154. "$NAME": safe(check.name),
  155. "$TAGS": safe(check.tags),
  156. }
  157. for i, tag in enumerate(check.tags_list()):
  158. ctx["$TAG%d" % (i + 1)] = safe(tag)
  159. return replace(template, ctx)
  160. def is_noop(self, check):
  161. if check.status == "down" and not self.channel.url_down:
  162. return True
  163. if check.status == "up" and not self.channel.url_up:
  164. return True
  165. return False
  166. def notify(self, check):
  167. spec = self.channel.webhook_spec(check.status)
  168. if not spec["url"]:
  169. return "Empty webhook URL"
  170. url = self.prepare(spec["url"], check, urlencode=True)
  171. headers = {}
  172. for key, value in spec["headers"].items():
  173. headers[key] = self.prepare(value, check)
  174. body = spec["body"]
  175. if body:
  176. body = self.prepare(body, check)
  177. if spec["method"] == "GET":
  178. return self.get(url, headers=headers)
  179. elif spec["method"] == "POST":
  180. return self.post(url, data=body.encode(), headers=headers)
  181. elif spec["method"] == "PUT":
  182. return self.put(url, data=body.encode(), headers=headers)
  183. class Slack(HttpTransport):
  184. def notify(self, check):
  185. text = tmpl("slack_message.json", check=check)
  186. payload = json.loads(text)
  187. return self.post(self.channel.slack_webhook_url, json=payload)
  188. class HipChat(HttpTransport):
  189. def is_noop(self, check):
  190. return True
  191. class OpsGenie(HttpTransport):
  192. def notify(self, check):
  193. headers = {
  194. "Conent-Type": "application/json",
  195. "Authorization": "GenieKey %s" % self.channel.opsgenie_key,
  196. }
  197. payload = {"alias": str(check.code), "source": settings.SITE_NAME}
  198. if check.status == "down":
  199. payload["tags"] = check.tags_list()
  200. payload["message"] = tmpl("opsgenie_message.html", check=check)
  201. payload["note"] = tmpl("opsgenie_note.html", check=check)
  202. payload["description"] = tmpl("opsgenie_description.html", check=check)
  203. url = "https://api.opsgenie.com/v2/alerts"
  204. if self.channel.opsgenie_region == "eu":
  205. url = "https://api.eu.opsgenie.com/v2/alerts"
  206. if check.status == "up":
  207. url += "/%s/close?identifierType=alias" % check.code
  208. return self.post(url, json=payload, headers=headers)
  209. class PagerDuty(HttpTransport):
  210. URL = "https://events.pagerduty.com/generic/2010-04-15/create_event.json"
  211. def notify(self, check):
  212. description = tmpl("pd_description.html", check=check)
  213. payload = {
  214. "service_key": self.channel.pd_service_key,
  215. "incident_key": str(check.code),
  216. "event_type": "trigger" if check.status == "down" else "resolve",
  217. "description": description,
  218. "client": settings.SITE_NAME,
  219. "client_url": check.details_url(),
  220. }
  221. return self.post(self.URL, json=payload)
  222. class PagerTree(HttpTransport):
  223. def notify(self, check):
  224. url = self.channel.value
  225. headers = {"Conent-Type": "application/json"}
  226. payload = {
  227. "incident_key": str(check.code),
  228. "event_type": "trigger" if check.status == "down" else "resolve",
  229. "title": tmpl("pagertree_title.html", check=check),
  230. "description": tmpl("pagertree_description.html", check=check),
  231. "client": settings.SITE_NAME,
  232. "client_url": settings.SITE_ROOT,
  233. "tags": ",".join(check.tags_list()),
  234. }
  235. return self.post(url, json=payload, headers=headers)
  236. class PagerTeam(HttpTransport):
  237. def notify(self, check):
  238. url = self.channel.value
  239. headers = {"Content-Type": "application/json"}
  240. payload = {
  241. "incident_key": str(check.code),
  242. "event_type": "trigger" if check.status == "down" else "resolve",
  243. "title": tmpl("pagerteam_title.html", check=check),
  244. "description": tmpl("pagerteam_description.html", check=check),
  245. "client": settings.SITE_NAME,
  246. "client_url": settings.SITE_ROOT,
  247. "tags": ",".join(check.tags_list()),
  248. }
  249. return self.post(url, json=payload, headers=headers)
  250. class Pushbullet(HttpTransport):
  251. def notify(self, check):
  252. text = tmpl("pushbullet_message.html", check=check)
  253. url = "https://api.pushbullet.com/v2/pushes"
  254. headers = {
  255. "Access-Token": self.channel.value,
  256. "Conent-Type": "application/json",
  257. }
  258. payload = {"type": "note", "title": settings.SITE_NAME, "body": text}
  259. return self.post(url, json=payload, headers=headers)
  260. class Pushover(HttpTransport):
  261. URL = "https://api.pushover.net/1/messages.json"
  262. def notify(self, check):
  263. others = self.checks().filter(status="down").exclude(code=check.code)
  264. # list() executes the query, to avoid DB access while
  265. # rendering a template
  266. ctx = {"check": check, "down_checks": list(others)}
  267. text = tmpl("pushover_message.html", **ctx)
  268. title = tmpl("pushover_title.html", **ctx)
  269. pieces = self.channel.value.split("|")
  270. user_key, prio = pieces[0], pieces[1]
  271. # The third element, if present, is the priority for "up" events
  272. if len(pieces) == 3 and check.status == "up":
  273. prio = pieces[2]
  274. payload = {
  275. "token": settings.PUSHOVER_API_TOKEN,
  276. "user": user_key,
  277. "message": text,
  278. "title": title,
  279. "html": 1,
  280. "priority": int(prio),
  281. }
  282. # Emergency notification
  283. if prio == "2":
  284. payload["retry"] = settings.PUSHOVER_EMERGENCY_RETRY_DELAY
  285. payload["expire"] = settings.PUSHOVER_EMERGENCY_EXPIRATION
  286. return self.post(self.URL, data=payload)
  287. class VictorOps(HttpTransport):
  288. def notify(self, check):
  289. description = tmpl("victorops_description.html", check=check)
  290. mtype = "CRITICAL" if check.status == "down" else "RECOVERY"
  291. payload = {
  292. "entity_id": str(check.code),
  293. "message_type": mtype,
  294. "entity_display_name": check.name_then_code(),
  295. "state_message": description,
  296. "monitoring_tool": settings.SITE_NAME,
  297. }
  298. return self.post(self.channel.value, json=payload)
  299. class Matrix(HttpTransport):
  300. def get_url(self):
  301. s = quote(self.channel.value)
  302. url = settings.MATRIX_HOMESERVER
  303. url += "/_matrix/client/r0/rooms/%s/send/m.room.message?" % s
  304. url += urlencode({"access_token": settings.MATRIX_ACCESS_TOKEN})
  305. return url
  306. def notify(self, check):
  307. plain = tmpl("matrix_description.html", check=check)
  308. formatted = tmpl("matrix_description_formatted.html", check=check)
  309. payload = {
  310. "msgtype": "m.text",
  311. "body": plain,
  312. "format": "org.matrix.custom.html",
  313. "formatted_body": formatted,
  314. }
  315. return self.post(self.get_url(), json=payload)
  316. class Discord(HttpTransport):
  317. def notify(self, check):
  318. text = tmpl("slack_message.json", check=check)
  319. payload = json.loads(text)
  320. url = self.channel.discord_webhook_url + "/slack"
  321. return self.post(url, json=payload)
  322. class Telegram(HttpTransport):
  323. SM = "https://api.telegram.org/bot%s/sendMessage" % settings.TELEGRAM_TOKEN
  324. @classmethod
  325. def send(cls, chat_id, text):
  326. return cls.post(
  327. cls.SM, json={"chat_id": chat_id, "text": text, "parse_mode": "html"}
  328. )
  329. def notify(self, check):
  330. text = tmpl("telegram_message.html", check=check)
  331. return self.send(self.channel.telegram_id, text)
  332. class Sms(HttpTransport):
  333. URL = "https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json"
  334. def is_noop(self, check):
  335. return check.status != "down"
  336. def notify(self, check):
  337. profile = Profile.objects.for_user(self.channel.project.owner)
  338. if not profile.authorize_sms():
  339. profile.send_sms_limit_notice("SMS")
  340. return "Monthly SMS limit exceeded"
  341. url = self.URL % settings.TWILIO_ACCOUNT
  342. auth = (settings.TWILIO_ACCOUNT, settings.TWILIO_AUTH)
  343. text = tmpl("sms_message.html", check=check, site_name=settings.SITE_NAME)
  344. data = {
  345. "From": settings.TWILIO_FROM,
  346. "To": self.channel.sms_number,
  347. "Body": text,
  348. }
  349. return self.post(url, data=data, auth=auth)
  350. class WhatsApp(HttpTransport):
  351. URL = "https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json"
  352. def is_noop(self, check):
  353. if check.status == "down":
  354. return not self.channel.whatsapp_notify_down
  355. else:
  356. return not self.channel.whatsapp_notify_up
  357. def notify(self, check):
  358. profile = Profile.objects.for_user(self.channel.project.owner)
  359. if not profile.authorize_sms():
  360. profile.send_sms_limit_notice("WhatsApp")
  361. return "Monthly message limit exceeded"
  362. url = self.URL % settings.TWILIO_ACCOUNT
  363. auth = (settings.TWILIO_ACCOUNT, settings.TWILIO_AUTH)
  364. text = tmpl("whatsapp_message.html", check=check, site_name=settings.SITE_NAME)
  365. data = {
  366. "From": "whatsapp:%s" % settings.TWILIO_FROM,
  367. "To": "whatsapp:%s" % self.channel.sms_number,
  368. "Body": text,
  369. }
  370. return self.post(url, data=data, auth=auth)
  371. class Trello(HttpTransport):
  372. URL = "https://api.trello.com/1/cards"
  373. def is_noop(self, check):
  374. return check.status != "down"
  375. def notify(self, check):
  376. params = {
  377. "idList": self.channel.trello_list_id,
  378. "name": tmpl("trello_name.html", check=check),
  379. "desc": tmpl("trello_desc.html", check=check),
  380. "key": settings.TRELLO_APP_KEY,
  381. "token": self.channel.trello_token,
  382. }
  383. return self.post(self.URL, params=params)
  384. class Apprise(HttpTransport):
  385. def notify(self, check):
  386. if not settings.APPRISE_ENABLED:
  387. # Not supported and/or enabled
  388. return "Apprise is disabled and/or not installed"
  389. a = apprise.Apprise()
  390. title = tmpl("apprise_title.html", check=check)
  391. body = tmpl("apprise_description.html", check=check)
  392. a.add(self.channel.value)
  393. notify_type = (
  394. apprise.NotifyType.SUCCESS
  395. if check.status == "up"
  396. else apprise.NotifyType.FAILURE
  397. )
  398. return (
  399. "Failed"
  400. if not a.notify(body=body, title=title, notify_type=notify_type)
  401. else None
  402. )
  403. class MsTeams(HttpTransport):
  404. def notify(self, check):
  405. text = tmpl("msteams_message.json", check=check)
  406. payload = json.loads(text)
  407. return self.post(self.channel.value, json=payload)