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.

579 lines
17 KiB

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 overridden 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 check.status == "down":
  68. return not self.channel.email_notify_down
  69. else:
  70. return not self.channel.email_notify_up
  71. class Shell(Transport):
  72. def prepare(self, template, check):
  73. """ Replace placeholders with actual values. """
  74. ctx = {
  75. "$CODE": str(check.code),
  76. "$STATUS": check.status,
  77. "$NOW": timezone.now().replace(microsecond=0).isoformat(),
  78. "$NAME": check.name,
  79. "$TAGS": check.tags,
  80. }
  81. for i, tag in enumerate(check.tags_list()):
  82. ctx["$TAG%d" % (i + 1)] = tag
  83. return replace(template, ctx)
  84. def is_noop(self, check):
  85. if check.status == "down" and not self.channel.cmd_down:
  86. return True
  87. if check.status == "up" and not self.channel.cmd_up:
  88. return True
  89. return False
  90. def notify(self, check):
  91. if not settings.SHELL_ENABLED:
  92. return "Shell commands are not enabled"
  93. if check.status == "up":
  94. cmd = self.channel.cmd_up
  95. elif check.status == "down":
  96. cmd = self.channel.cmd_down
  97. cmd = self.prepare(cmd, check)
  98. code = os.system(cmd)
  99. if code != 0:
  100. return "Command returned exit code %d" % code
  101. class HttpTransport(Transport):
  102. @classmethod
  103. def get_error(cls, response):
  104. # Override in subclasses: look for a specific error message in the
  105. # response and return it.
  106. return None
  107. @classmethod
  108. def _request(cls, method, url, **kwargs):
  109. try:
  110. options = dict(kwargs)
  111. options["timeout"] = 5
  112. if "headers" not in options:
  113. options["headers"] = {}
  114. if "User-Agent" not in options["headers"]:
  115. options["headers"]["User-Agent"] = "healthchecks.io"
  116. r = requests.request(method, url, **options)
  117. if r.status_code not in (200, 201, 202, 204):
  118. m = cls.get_error(r)
  119. if m:
  120. return f'Received status code {r.status_code} with a message: "{m}"'
  121. return f"Received status code {r.status_code}"
  122. except requests.exceptions.Timeout:
  123. # Well, we tried
  124. return "Connection timed out"
  125. except requests.exceptions.ConnectionError:
  126. return "Connection failed"
  127. @classmethod
  128. def get(cls, url, **kwargs):
  129. # Make 3 attempts--
  130. for x in range(0, 3):
  131. error = cls._request("get", url, **kwargs)
  132. if error is None:
  133. break
  134. return error
  135. @classmethod
  136. def post(cls, url, **kwargs):
  137. # Make 3 attempts--
  138. for x in range(0, 3):
  139. error = cls._request("post", url, **kwargs)
  140. if error is None:
  141. break
  142. return error
  143. @classmethod
  144. def put(cls, url, **kwargs):
  145. # Make 3 attempts--
  146. for x in range(0, 3):
  147. error = cls._request("put", url, **kwargs)
  148. if error is None:
  149. break
  150. return error
  151. class Webhook(HttpTransport):
  152. def prepare(self, template, check, urlencode=False):
  153. """ Replace variables with actual values. """
  154. def safe(s):
  155. return quote(s) if urlencode else s
  156. ctx = {
  157. "$CODE": str(check.code),
  158. "$STATUS": check.status,
  159. "$NOW": safe(timezone.now().replace(microsecond=0).isoformat()),
  160. "$NAME": safe(check.name),
  161. "$TAGS": safe(check.tags),
  162. }
  163. for i, tag in enumerate(check.tags_list()):
  164. ctx["$TAG%d" % (i + 1)] = safe(tag)
  165. return replace(template, ctx)
  166. def is_noop(self, check):
  167. if check.status == "down" and not self.channel.url_down:
  168. return True
  169. if check.status == "up" and not self.channel.url_up:
  170. return True
  171. return False
  172. def notify(self, check):
  173. spec = self.channel.webhook_spec(check.status)
  174. if not spec["url"]:
  175. return "Empty webhook URL"
  176. url = self.prepare(spec["url"], check, urlencode=True)
  177. headers = {}
  178. for key, value in spec["headers"].items():
  179. headers[key] = self.prepare(value, check)
  180. body = spec["body"]
  181. if body:
  182. body = self.prepare(body, check)
  183. if spec["method"] == "GET":
  184. return self.get(url, headers=headers)
  185. elif spec["method"] == "POST":
  186. return self.post(url, data=body.encode(), headers=headers)
  187. elif spec["method"] == "PUT":
  188. return self.put(url, data=body.encode(), headers=headers)
  189. class Slack(HttpTransport):
  190. def notify(self, check):
  191. text = tmpl("slack_message.json", check=check)
  192. payload = json.loads(text)
  193. return self.post(self.channel.slack_webhook_url, json=payload)
  194. class HipChat(HttpTransport):
  195. def is_noop(self, check):
  196. return True
  197. class OpsGenie(HttpTransport):
  198. @classmethod
  199. def get_error(cls, response):
  200. try:
  201. return response.json().get("message")
  202. except ValueError:
  203. pass
  204. def notify(self, check):
  205. headers = {
  206. "Conent-Type": "application/json",
  207. "Authorization": "GenieKey %s" % self.channel.opsgenie_key,
  208. }
  209. payload = {"alias": str(check.code), "source": settings.SITE_NAME}
  210. if check.status == "down":
  211. payload["tags"] = check.tags_list()
  212. payload["message"] = tmpl("opsgenie_message.html", check=check)
  213. payload["note"] = tmpl("opsgenie_note.html", check=check)
  214. payload["description"] = tmpl("opsgenie_description.html", check=check)
  215. url = "https://api.opsgenie.com/v2/alerts"
  216. if self.channel.opsgenie_region == "eu":
  217. url = "https://api.eu.opsgenie.com/v2/alerts"
  218. if check.status == "up":
  219. url += "/%s/close?identifierType=alias" % check.code
  220. return self.post(url, json=payload, headers=headers)
  221. class PagerDuty(HttpTransport):
  222. URL = "https://events.pagerduty.com/generic/2010-04-15/create_event.json"
  223. def notify(self, check):
  224. description = tmpl("pd_description.html", check=check)
  225. payload = {
  226. "service_key": self.channel.pd_service_key,
  227. "incident_key": str(check.code),
  228. "event_type": "trigger" if check.status == "down" else "resolve",
  229. "description": description,
  230. "client": settings.SITE_NAME,
  231. "client_url": check.details_url(),
  232. }
  233. return self.post(self.URL, json=payload)
  234. class PagerTree(HttpTransport):
  235. def notify(self, check):
  236. url = self.channel.value
  237. headers = {"Conent-Type": "application/json"}
  238. payload = {
  239. "incident_key": str(check.code),
  240. "event_type": "trigger" if check.status == "down" else "resolve",
  241. "title": tmpl("pagertree_title.html", check=check),
  242. "description": tmpl("pagertree_description.html", check=check),
  243. "client": settings.SITE_NAME,
  244. "client_url": settings.SITE_ROOT,
  245. "tags": ",".join(check.tags_list()),
  246. }
  247. return self.post(url, json=payload, headers=headers)
  248. class PagerTeam(HttpTransport):
  249. def is_noop(self, check):
  250. return True
  251. class Pushbullet(HttpTransport):
  252. def notify(self, check):
  253. text = tmpl("pushbullet_message.html", check=check)
  254. url = "https://api.pushbullet.com/v2/pushes"
  255. headers = {
  256. "Access-Token": self.channel.value,
  257. "Conent-Type": "application/json",
  258. }
  259. payload = {"type": "note", "title": settings.SITE_NAME, "body": text}
  260. return self.post(url, json=payload, headers=headers)
  261. class Pushover(HttpTransport):
  262. URL = "https://api.pushover.net/1/messages.json"
  263. def notify(self, check):
  264. others = self.checks().filter(status="down").exclude(code=check.code)
  265. # list() executes the query, to avoid DB access while
  266. # rendering a template
  267. ctx = {"check": check, "down_checks": list(others)}
  268. text = tmpl("pushover_message.html", **ctx)
  269. title = tmpl("pushover_title.html", **ctx)
  270. pieces = self.channel.value.split("|")
  271. user_key, prio = pieces[0], pieces[1]
  272. # The third element, if present, is the priority for "up" events
  273. if len(pieces) == 3 and check.status == "up":
  274. prio = pieces[2]
  275. payload = {
  276. "token": settings.PUSHOVER_API_TOKEN,
  277. "user": user_key,
  278. "message": text,
  279. "title": title,
  280. "html": 1,
  281. "priority": int(prio),
  282. }
  283. # Emergency notification
  284. if prio == "2":
  285. payload["retry"] = settings.PUSHOVER_EMERGENCY_RETRY_DELAY
  286. payload["expire"] = settings.PUSHOVER_EMERGENCY_EXPIRATION
  287. return self.post(self.URL, data=payload)
  288. class VictorOps(HttpTransport):
  289. def notify(self, check):
  290. description = tmpl("victorops_description.html", check=check)
  291. mtype = "CRITICAL" if check.status == "down" else "RECOVERY"
  292. payload = {
  293. "entity_id": str(check.code),
  294. "message_type": mtype,
  295. "entity_display_name": check.name_then_code(),
  296. "state_message": description,
  297. "monitoring_tool": settings.SITE_NAME,
  298. }
  299. return self.post(self.channel.value, json=payload)
  300. class Matrix(HttpTransport):
  301. def get_url(self):
  302. s = quote(self.channel.value)
  303. url = settings.MATRIX_HOMESERVER
  304. url += "/_matrix/client/r0/rooms/%s/send/m.room.message?" % s
  305. url += urlencode({"access_token": settings.MATRIX_ACCESS_TOKEN})
  306. return url
  307. def notify(self, check):
  308. plain = tmpl("matrix_description.html", check=check)
  309. formatted = tmpl("matrix_description_formatted.html", check=check)
  310. payload = {
  311. "msgtype": "m.text",
  312. "body": plain,
  313. "format": "org.matrix.custom.html",
  314. "formatted_body": formatted,
  315. }
  316. return self.post(self.get_url(), json=payload)
  317. class Discord(HttpTransport):
  318. def notify(self, check):
  319. text = tmpl("slack_message.json", check=check)
  320. payload = json.loads(text)
  321. url = self.channel.discord_webhook_url + "/slack"
  322. return self.post(url, json=payload)
  323. class Telegram(HttpTransport):
  324. SM = "https://api.telegram.org/bot%s/sendMessage" % settings.TELEGRAM_TOKEN
  325. @classmethod
  326. def get_error(cls, response):
  327. try:
  328. return response.json().get("description")
  329. except ValueError:
  330. pass
  331. @classmethod
  332. def send(cls, chat_id, text):
  333. # Telegram.send is a separate method because it is also used in
  334. # hc.front.views.telegram_bot to send invite links.
  335. return cls.post(
  336. cls.SM, json={"chat_id": chat_id, "text": text, "parse_mode": "html"}
  337. )
  338. def notify(self, check):
  339. from hc.api.models import TokenBucket
  340. if not TokenBucket.authorize_telegram(self.channel.telegram_id):
  341. return "Rate limit exceeded"
  342. text = tmpl("telegram_message.html", check=check)
  343. return self.send(self.channel.telegram_id, text)
  344. class Sms(HttpTransport):
  345. URL = "https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json"
  346. def is_noop(self, check):
  347. return check.status != "down"
  348. def notify(self, check):
  349. profile = Profile.objects.for_user(self.channel.project.owner)
  350. if not profile.authorize_sms():
  351. profile.send_sms_limit_notice("SMS")
  352. return "Monthly SMS limit exceeded"
  353. url = self.URL % settings.TWILIO_ACCOUNT
  354. auth = (settings.TWILIO_ACCOUNT, settings.TWILIO_AUTH)
  355. text = tmpl("sms_message.html", check=check, site_name=settings.SITE_NAME)
  356. data = {
  357. "From": settings.TWILIO_FROM,
  358. "To": self.channel.sms_number,
  359. "Body": text,
  360. }
  361. return self.post(url, data=data, auth=auth)
  362. class WhatsApp(HttpTransport):
  363. URL = "https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json"
  364. def is_noop(self, check):
  365. if check.status == "down":
  366. return not self.channel.whatsapp_notify_down
  367. else:
  368. return not self.channel.whatsapp_notify_up
  369. def notify(self, check):
  370. profile = Profile.objects.for_user(self.channel.project.owner)
  371. if not profile.authorize_sms():
  372. profile.send_sms_limit_notice("WhatsApp")
  373. return "Monthly message limit exceeded"
  374. url = self.URL % settings.TWILIO_ACCOUNT
  375. auth = (settings.TWILIO_ACCOUNT, settings.TWILIO_AUTH)
  376. text = tmpl("whatsapp_message.html", check=check, site_name=settings.SITE_NAME)
  377. data = {
  378. "From": "whatsapp:%s" % settings.TWILIO_FROM,
  379. "To": "whatsapp:%s" % self.channel.sms_number,
  380. "Body": text,
  381. }
  382. return self.post(url, data=data, auth=auth)
  383. class Trello(HttpTransport):
  384. URL = "https://api.trello.com/1/cards"
  385. def is_noop(self, check):
  386. return check.status != "down"
  387. def notify(self, check):
  388. params = {
  389. "idList": self.channel.trello_list_id,
  390. "name": tmpl("trello_name.html", check=check),
  391. "desc": tmpl("trello_desc.html", check=check),
  392. "key": settings.TRELLO_APP_KEY,
  393. "token": self.channel.trello_token,
  394. }
  395. return self.post(self.URL, params=params)
  396. class Apprise(HttpTransport):
  397. def notify(self, check):
  398. if not settings.APPRISE_ENABLED:
  399. # Not supported and/or enabled
  400. return "Apprise is disabled and/or not installed"
  401. a = apprise.Apprise()
  402. title = tmpl("apprise_title.html", check=check)
  403. body = tmpl("apprise_description.html", check=check)
  404. a.add(self.channel.value)
  405. notify_type = (
  406. apprise.NotifyType.SUCCESS
  407. if check.status == "up"
  408. else apprise.NotifyType.FAILURE
  409. )
  410. return (
  411. "Failed"
  412. if not a.notify(body=body, title=title, notify_type=notify_type)
  413. else None
  414. )
  415. class MsTeams(HttpTransport):
  416. def notify(self, check):
  417. text = tmpl("msteams_message.json", check=check)
  418. payload = json.loads(text)
  419. return self.post(self.channel.value, json=payload)
  420. class Zulip(HttpTransport):
  421. @classmethod
  422. def get_error(cls, response):
  423. try:
  424. return response.json().get("msg")
  425. except ValueError:
  426. pass
  427. def notify(self, check):
  428. _, domain = self.channel.zulip_bot_email.split("@")
  429. url = "https://%s/api/v1/messages" % domain
  430. auth = (self.channel.zulip_bot_email, self.channel.zulip_api_key)
  431. data = {
  432. "type": self.channel.zulip_type,
  433. "to": self.channel.zulip_to,
  434. "topic": tmpl("zulip_topic.html", check=check),
  435. "content": tmpl("zulip_content.html", check=check),
  436. }
  437. return self.post(url, data=data, auth=auth)