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.

741 lines
23 KiB

4 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. from django.utils.html import escape
  6. import json
  7. import requests
  8. from urllib.parse import quote, urlencode
  9. from hc.accounts.models import Profile
  10. from hc.lib import emails
  11. from hc.lib.string import replace
  12. try:
  13. import apprise
  14. except ImportError:
  15. # Enforce
  16. settings.APPRISE_ENABLED = False
  17. try:
  18. import dbus
  19. except ImportError:
  20. # Enforce
  21. dbus = None
  22. settings.SIGNAL_CLI_ENABLED = False
  23. def tmpl(template_name, **ctx):
  24. template_path = "integrations/%s" % template_name
  25. # \xa0 is non-breaking space. It causes SMS messages to use UCS2 encoding
  26. # and cost twice the money.
  27. return render_to_string(template_path, ctx).strip().replace("\xa0", " ")
  28. class Transport(object):
  29. def __init__(self, channel):
  30. self.channel = channel
  31. def notify(self, check):
  32. """ Send notification about current status of the check.
  33. This method returns None on success, and error message
  34. on error.
  35. """
  36. raise NotImplementedError()
  37. def is_noop(self, check):
  38. """ Return True if transport will ignore check's current status.
  39. This method is overridden in Webhook subclass where the user can
  40. configure webhook urls for "up" and "down" events, and both are
  41. optional.
  42. """
  43. return False
  44. def checks(self):
  45. return self.channel.project.check_set.order_by("created")
  46. class Email(Transport):
  47. def notify(self, check):
  48. if not self.channel.email_verified:
  49. return "Email not verified"
  50. unsub_link = self.channel.get_unsub_link()
  51. headers = {
  52. "X-Status-Url": check.status_url,
  53. "List-Unsubscribe": "<%s>" % unsub_link,
  54. "List-Unsubscribe-Post": "List-Unsubscribe=One-Click",
  55. }
  56. from hc.accounts.models import Profile
  57. # If this email address has an associated account, include
  58. # a summary of projects the account has access to
  59. try:
  60. profile = Profile.objects.get(user__email=self.channel.email_value)
  61. projects = list(profile.projects())
  62. except Profile.DoesNotExist:
  63. projects = None
  64. ctx = {
  65. "check": check,
  66. "ping": check.ping_set.order_by("created").last(),
  67. "projects": projects,
  68. "unsub_link": unsub_link,
  69. }
  70. emails.alert(self.channel.email_value, ctx, headers)
  71. def is_noop(self, check):
  72. if check.status == "down":
  73. return not self.channel.email_notify_down
  74. else:
  75. return not self.channel.email_notify_up
  76. class Shell(Transport):
  77. def prepare(self, template, check):
  78. """ Replace placeholders with actual values. """
  79. ctx = {
  80. "$CODE": str(check.code),
  81. "$STATUS": check.status,
  82. "$NOW": timezone.now().replace(microsecond=0).isoformat(),
  83. "$NAME": check.name,
  84. "$TAGS": check.tags,
  85. }
  86. for i, tag in enumerate(check.tags_list()):
  87. ctx["$TAG%d" % (i + 1)] = tag
  88. return replace(template, ctx)
  89. def is_noop(self, check):
  90. if check.status == "down" and not self.channel.cmd_down:
  91. return True
  92. if check.status == "up" and not self.channel.cmd_up:
  93. return True
  94. return False
  95. def notify(self, check):
  96. if not settings.SHELL_ENABLED:
  97. return "Shell commands are not enabled"
  98. if check.status == "up":
  99. cmd = self.channel.cmd_up
  100. elif check.status == "down":
  101. cmd = self.channel.cmd_down
  102. cmd = self.prepare(cmd, check)
  103. code = os.system(cmd)
  104. if code != 0:
  105. return "Command returned exit code %d" % code
  106. class HttpTransport(Transport):
  107. @classmethod
  108. def get_error(cls, response):
  109. # Override in subclasses: look for a specific error message in the
  110. # response and return it.
  111. return None
  112. @classmethod
  113. def _request(cls, method, url, **kwargs):
  114. try:
  115. options = dict(kwargs)
  116. options["timeout"] = 5
  117. if "headers" not in options:
  118. options["headers"] = {}
  119. if "User-Agent" not in options["headers"]:
  120. options["headers"]["User-Agent"] = "healthchecks.io"
  121. r = requests.request(method, url, **options)
  122. if r.status_code not in (200, 201, 202, 204):
  123. m = cls.get_error(r)
  124. if m:
  125. return f'Received status code {r.status_code} with a message: "{m}"'
  126. return f"Received status code {r.status_code}"
  127. except requests.exceptions.Timeout:
  128. # Well, we tried
  129. return "Connection timed out"
  130. except requests.exceptions.ConnectionError:
  131. return "Connection failed"
  132. @classmethod
  133. def get(cls, url, num_tries=3, **kwargs):
  134. for x in range(0, num_tries):
  135. error = cls._request("get", url, **kwargs)
  136. if error is None:
  137. break
  138. return error
  139. @classmethod
  140. def post(cls, url, num_tries=3, **kwargs):
  141. for x in range(0, num_tries):
  142. error = cls._request("post", url, **kwargs)
  143. if error is None:
  144. break
  145. return error
  146. @classmethod
  147. def put(cls, url, num_tries=3, **kwargs):
  148. for x in range(0, num_tries):
  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. if not settings.WEBHOOKS_ENABLED:
  176. return "Webhook notifications are not enabled."
  177. spec = self.channel.webhook_spec(check.status)
  178. if not spec["url"]:
  179. return "Empty webhook URL"
  180. url = self.prepare(spec["url"], check, urlencode=True)
  181. headers = {}
  182. for key, value in spec["headers"].items():
  183. headers[key] = self.prepare(value, check)
  184. body = spec["body"]
  185. if body:
  186. body = self.prepare(body, check).encode()
  187. num_tries = 3
  188. if getattr(check, "is_test"):
  189. # When sending a test notification, don't retry on failures.
  190. num_tries = 1
  191. if spec["method"] == "GET":
  192. return self.get(url, num_tries=num_tries, headers=headers)
  193. elif spec["method"] == "POST":
  194. return self.post(url, num_tries=num_tries, data=body, headers=headers)
  195. elif spec["method"] == "PUT":
  196. return self.put(url, num_tries=num_tries, data=body, headers=headers)
  197. class Slack(HttpTransport):
  198. def notify(self, check):
  199. if self.channel.kind == "slack" and not settings.SLACK_ENABLED:
  200. return "Slack notifications are not enabled."
  201. if self.channel.kind == "mattermost" and not settings.MATTERMOST_ENABLED:
  202. return "Mattermost notifications are not enabled."
  203. text = tmpl("slack_message.json", check=check)
  204. payload = json.loads(text)
  205. return self.post(self.channel.slack_webhook_url, json=payload)
  206. class HipChat(HttpTransport):
  207. def is_noop(self, check):
  208. return True
  209. class Opsgenie(HttpTransport):
  210. @classmethod
  211. def get_error(cls, response):
  212. try:
  213. return response.json().get("message")
  214. except ValueError:
  215. pass
  216. def notify(self, check):
  217. if not settings.OPSGENIE_ENABLED:
  218. return "Opsgenie notifications are not enabled."
  219. headers = {
  220. "Conent-Type": "application/json",
  221. "Authorization": "GenieKey %s" % self.channel.opsgenie_key,
  222. }
  223. payload = {"alias": str(check.code), "source": settings.SITE_NAME}
  224. if check.status == "down":
  225. payload["tags"] = check.tags_list()
  226. payload["message"] = tmpl("opsgenie_message.html", check=check)
  227. payload["note"] = tmpl("opsgenie_note.html", check=check)
  228. payload["description"] = tmpl("opsgenie_description.html", check=check)
  229. url = "https://api.opsgenie.com/v2/alerts"
  230. if self.channel.opsgenie_region == "eu":
  231. url = "https://api.eu.opsgenie.com/v2/alerts"
  232. if check.status == "up":
  233. url += "/%s/close?identifierType=alias" % check.code
  234. return self.post(url, json=payload, headers=headers)
  235. class PagerDuty(HttpTransport):
  236. URL = "https://events.pagerduty.com/generic/2010-04-15/create_event.json"
  237. def notify(self, check):
  238. if not settings.PD_ENABLED:
  239. return "PagerDuty notifications are not enabled."
  240. description = tmpl("pd_description.html", check=check)
  241. payload = {
  242. "service_key": self.channel.pd_service_key,
  243. "incident_key": str(check.code),
  244. "event_type": "trigger" if check.status == "down" else "resolve",
  245. "description": description,
  246. "client": settings.SITE_NAME,
  247. "client_url": check.details_url(),
  248. }
  249. return self.post(self.URL, json=payload)
  250. class PagerTree(HttpTransport):
  251. def notify(self, check):
  252. if not settings.PAGERTREE_ENABLED:
  253. return "PagerTree notifications are not enabled."
  254. url = self.channel.value
  255. headers = {"Conent-Type": "application/json"}
  256. payload = {
  257. "incident_key": str(check.code),
  258. "event_type": "trigger" if check.status == "down" else "resolve",
  259. "title": tmpl("pagertree_title.html", check=check),
  260. "description": tmpl("pagertree_description.html", check=check),
  261. "client": settings.SITE_NAME,
  262. "client_url": settings.SITE_ROOT,
  263. "tags": ",".join(check.tags_list()),
  264. }
  265. return self.post(url, json=payload, headers=headers)
  266. class PagerTeam(HttpTransport):
  267. def is_noop(self, check):
  268. return True
  269. class Pushbullet(HttpTransport):
  270. def notify(self, check):
  271. text = tmpl("pushbullet_message.html", check=check)
  272. url = "https://api.pushbullet.com/v2/pushes"
  273. headers = {
  274. "Access-Token": self.channel.value,
  275. "Conent-Type": "application/json",
  276. }
  277. payload = {"type": "note", "title": settings.SITE_NAME, "body": text}
  278. return self.post(url, json=payload, headers=headers)
  279. class Pushover(HttpTransport):
  280. URL = "https://api.pushover.net/1/messages.json"
  281. def notify(self, check):
  282. pieces = self.channel.value.split("|")
  283. user_key, prio = pieces[0], pieces[1]
  284. # The third element, if present, is the priority for "up" events
  285. if len(pieces) == 3 and check.status == "up":
  286. prio = pieces[2]
  287. from hc.api.models import TokenBucket
  288. if not TokenBucket.authorize_pushover(user_key):
  289. return "Rate limit exceeded"
  290. others = self.checks().filter(status="down").exclude(code=check.code)
  291. # list() executes the query, to avoid DB access while
  292. # rendering a template
  293. ctx = {"check": check, "down_checks": list(others)}
  294. text = tmpl("pushover_message.html", **ctx)
  295. title = tmpl("pushover_title.html", **ctx)
  296. payload = {
  297. "token": settings.PUSHOVER_API_TOKEN,
  298. "user": user_key,
  299. "message": text,
  300. "title": title,
  301. "html": 1,
  302. "priority": int(prio),
  303. }
  304. # Emergency notification
  305. if prio == "2":
  306. payload["retry"] = settings.PUSHOVER_EMERGENCY_RETRY_DELAY
  307. payload["expire"] = settings.PUSHOVER_EMERGENCY_EXPIRATION
  308. return self.post(self.URL, data=payload)
  309. class VictorOps(HttpTransport):
  310. def notify(self, check):
  311. if not settings.VICTOROPS_ENABLED:
  312. return "Splunk On-Call notifications are not enabled."
  313. description = tmpl("victorops_description.html", check=check)
  314. mtype = "CRITICAL" if check.status == "down" else "RECOVERY"
  315. payload = {
  316. "entity_id": str(check.code),
  317. "message_type": mtype,
  318. "entity_display_name": check.name_then_code(),
  319. "state_message": description,
  320. "monitoring_tool": settings.SITE_NAME,
  321. }
  322. return self.post(self.channel.value, json=payload)
  323. class Matrix(HttpTransport):
  324. def get_url(self):
  325. s = quote(self.channel.value)
  326. url = settings.MATRIX_HOMESERVER
  327. url += "/_matrix/client/r0/rooms/%s/send/m.room.message?" % s
  328. url += urlencode({"access_token": settings.MATRIX_ACCESS_TOKEN})
  329. return url
  330. def notify(self, check):
  331. plain = tmpl("matrix_description.html", check=check)
  332. formatted = tmpl("matrix_description_formatted.html", check=check)
  333. payload = {
  334. "msgtype": "m.text",
  335. "body": plain,
  336. "format": "org.matrix.custom.html",
  337. "formatted_body": formatted,
  338. }
  339. return self.post(self.get_url(), json=payload)
  340. class Discord(HttpTransport):
  341. def notify(self, check):
  342. text = tmpl("slack_message.json", check=check)
  343. payload = json.loads(text)
  344. url = self.channel.discord_webhook_url + "/slack"
  345. return self.post(url, json=payload)
  346. class Telegram(HttpTransport):
  347. SM = "https://api.telegram.org/bot%s/sendMessage" % settings.TELEGRAM_TOKEN
  348. @classmethod
  349. def get_error(cls, response):
  350. try:
  351. return response.json().get("description")
  352. except ValueError:
  353. pass
  354. @classmethod
  355. def send(cls, chat_id, text):
  356. # Telegram.send is a separate method because it is also used in
  357. # hc.front.views.telegram_bot to send invite links.
  358. return cls.post(
  359. cls.SM, json={"chat_id": chat_id, "text": text, "parse_mode": "html"}
  360. )
  361. def notify(self, check):
  362. from hc.api.models import TokenBucket
  363. if not TokenBucket.authorize_telegram(self.channel.telegram_id):
  364. return "Rate limit exceeded"
  365. text = tmpl("telegram_message.html", check=check)
  366. return self.send(self.channel.telegram_id, text)
  367. class Sms(HttpTransport):
  368. URL = "https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json"
  369. def is_noop(self, check):
  370. return check.status != "down"
  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("SMS")
  375. return "Monthly SMS limit exceeded"
  376. url = self.URL % settings.TWILIO_ACCOUNT
  377. auth = (settings.TWILIO_ACCOUNT, settings.TWILIO_AUTH)
  378. text = tmpl("sms_message.html", check=check, site_name=settings.SITE_NAME)
  379. data = {
  380. "From": settings.TWILIO_FROM,
  381. "To": self.channel.phone_number,
  382. "Body": text,
  383. "StatusCallback": check.status_url,
  384. }
  385. return self.post(url, data=data, auth=auth)
  386. class Call(HttpTransport):
  387. URL = "https://api.twilio.com/2010-04-01/Accounts/%s/Calls.json"
  388. def is_noop(self, check):
  389. return check.status != "down"
  390. def notify(self, check):
  391. profile = Profile.objects.for_user(self.channel.project.owner)
  392. if not profile.authorize_call():
  393. profile.send_call_limit_notice()
  394. return "Monthly phone call limit exceeded"
  395. url = self.URL % settings.TWILIO_ACCOUNT
  396. auth = (settings.TWILIO_ACCOUNT, settings.TWILIO_AUTH)
  397. twiml = tmpl("call_message.html", check=check, site_name=settings.SITE_NAME)
  398. data = {
  399. "From": settings.TWILIO_FROM,
  400. "To": self.channel.phone_number,
  401. "Twiml": twiml,
  402. "StatusCallback": check.status_url,
  403. }
  404. return self.post(url, data=data, auth=auth)
  405. class WhatsApp(HttpTransport):
  406. URL = "https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json"
  407. def is_noop(self, check):
  408. if check.status == "down":
  409. return not self.channel.whatsapp_notify_down
  410. else:
  411. return not self.channel.whatsapp_notify_up
  412. def notify(self, check):
  413. profile = Profile.objects.for_user(self.channel.project.owner)
  414. if not profile.authorize_sms():
  415. profile.send_sms_limit_notice("WhatsApp")
  416. return "Monthly message limit exceeded"
  417. url = self.URL % settings.TWILIO_ACCOUNT
  418. auth = (settings.TWILIO_ACCOUNT, settings.TWILIO_AUTH)
  419. text = tmpl("whatsapp_message.html", check=check, site_name=settings.SITE_NAME)
  420. data = {
  421. "From": "whatsapp:%s" % settings.TWILIO_FROM,
  422. "To": "whatsapp:%s" % self.channel.phone_number,
  423. "Body": text,
  424. "StatusCallback": check.status_url,
  425. }
  426. return self.post(url, data=data, auth=auth)
  427. class Trello(HttpTransport):
  428. URL = "https://api.trello.com/1/cards"
  429. def is_noop(self, check):
  430. return check.status != "down"
  431. def notify(self, check):
  432. params = {
  433. "idList": self.channel.trello_list_id,
  434. "name": tmpl("trello_name.html", check=check),
  435. "desc": tmpl("trello_desc.html", check=check),
  436. "key": settings.TRELLO_APP_KEY,
  437. "token": self.channel.trello_token,
  438. }
  439. return self.post(self.URL, params=params)
  440. class Apprise(HttpTransport):
  441. def notify(self, check):
  442. if not settings.APPRISE_ENABLED:
  443. # Not supported and/or enabled
  444. return "Apprise is disabled and/or not installed"
  445. a = apprise.Apprise()
  446. title = tmpl("apprise_title.html", check=check)
  447. body = tmpl("apprise_description.html", check=check)
  448. a.add(self.channel.value)
  449. notify_type = (
  450. apprise.NotifyType.SUCCESS
  451. if check.status == "up"
  452. else apprise.NotifyType.FAILURE
  453. )
  454. return (
  455. "Failed"
  456. if not a.notify(body=body, title=title, notify_type=notify_type)
  457. else None
  458. )
  459. class MsTeams(HttpTransport):
  460. def escape_md(self, s):
  461. # Escape special HTML characters
  462. s = escape(s)
  463. # Escape characters that have special meaning in Markdown
  464. for c in r"\`*_{}[]()#+-.!|":
  465. s = s.replace(c, "\\" + c)
  466. return s
  467. def notify(self, check):
  468. if not settings.MSTEAMS_ENABLED:
  469. return "MS Teams notifications are not enabled."
  470. text = tmpl("msteams_message.json", check=check)
  471. payload = json.loads(text)
  472. # MS Teams escapes HTML special characters in the summary field.
  473. # It does not interpret summary content as Markdown.
  474. name = check.name_then_code()
  475. payload["summary"] = f"“{name}” is {check.status.upper()}."
  476. # MS teams *strips* HTML special characters from the title field.
  477. # To avoid that, we use escape().
  478. # It does not interpret title as Markdown.
  479. safe_name = escape(name)
  480. payload["title"] = f"“{safe_name}” is {check.status.upper()}."
  481. # MS teams allows some HTML in the section text.
  482. # It also interprets the section text as Markdown.
  483. # We want to display the raw content, angle brackets and all,
  484. # so we run escape() and then additionally escape Markdown:
  485. payload["sections"][0]["text"] = self.escape_md(check.desc)
  486. return self.post(self.channel.value, json=payload)
  487. class Zulip(HttpTransport):
  488. @classmethod
  489. def get_error(cls, response):
  490. try:
  491. return response.json().get("msg")
  492. except ValueError:
  493. pass
  494. def notify(self, check):
  495. if not settings.ZULIP_ENABLED:
  496. return "Zulip notifications are not enabled."
  497. url = self.channel.zulip_site + "/api/v1/messages"
  498. auth = (self.channel.zulip_bot_email, self.channel.zulip_api_key)
  499. data = {
  500. "type": self.channel.zulip_type,
  501. "to": self.channel.zulip_to,
  502. "topic": tmpl("zulip_topic.html", check=check),
  503. "content": tmpl("zulip_content.html", check=check),
  504. }
  505. return self.post(url, data=data, auth=auth)
  506. class Spike(HttpTransport):
  507. def notify(self, check):
  508. if not settings.SPIKE_ENABLED:
  509. return "Spike notifications are not enabled."
  510. url = self.channel.value
  511. headers = {"Conent-Type": "application/json"}
  512. payload = {
  513. "check_id": str(check.code),
  514. "title": tmpl("spike_title.html", check=check),
  515. "message": tmpl("spike_description.html", check=check),
  516. "status": check.status,
  517. }
  518. return self.post(url, json=payload, headers=headers)
  519. class LineNotify(HttpTransport):
  520. URL = "https://notify-api.line.me/api/notify"
  521. def notify(self, check):
  522. headers = {
  523. "Content-Type": "application/x-www-form-urlencoded",
  524. "Authorization": "Bearer %s" % self.channel.linenotify_token,
  525. }
  526. payload = {"message": tmpl("linenotify_message.html", check=check)}
  527. return self.post(self.URL, headers=headers, params=payload)
  528. class Signal(Transport):
  529. def is_noop(self, check):
  530. if check.status == "down":
  531. return not self.channel.signal_notify_down
  532. else:
  533. return not self.channel.signal_notify_up
  534. def get_service(self):
  535. bus = dbus.SystemBus()
  536. signal_object = bus.get_object("org.asamk.Signal", "/org/asamk/Signal")
  537. return dbus.Interface(signal_object, "org.asamk.Signal")
  538. def notify(self, check):
  539. if not settings.SIGNAL_CLI_ENABLED:
  540. return "Signal notifications are not enabled"
  541. from hc.api.models import TokenBucket
  542. if not TokenBucket.authorize_signal(self.channel.phone_number):
  543. return "Rate limit exceeded"
  544. text = tmpl("signal_message.html", check=check, site_name=settings.SITE_NAME)
  545. try:
  546. dbus.SystemBus().call_blocking(
  547. "org.asamk.Signal",
  548. "/org/asamk/Signal",
  549. "org.asamk.Signal",
  550. "sendMessage",
  551. "sasas",
  552. (text, [], [self.channel.phone_number]),
  553. timeout=30,
  554. )
  555. except dbus.exceptions.DBusException as e:
  556. if "NotFoundException" in str(e):
  557. return "Recipient not found"
  558. return "signal-cli call failed"