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.

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