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.

750 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, latin1=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. result = replace(template, ctx)
  168. if latin1:
  169. # Replace non-latin-1 characters with XML character references.
  170. result = result.encode("latin-1", "xmlcharrefreplace").decode("latin-1")
  171. return result
  172. def is_noop(self, check):
  173. if check.status == "down" and not self.channel.url_down:
  174. return True
  175. if check.status == "up" and not self.channel.url_up:
  176. return True
  177. return False
  178. def notify(self, check):
  179. if not settings.WEBHOOKS_ENABLED:
  180. return "Webhook notifications are not enabled."
  181. spec = self.channel.webhook_spec(check.status)
  182. if not spec["url"]:
  183. return "Empty webhook URL"
  184. url = self.prepare(spec["url"], check, urlencode=True)
  185. headers = {}
  186. for key, value in spec["headers"].items():
  187. # Header values should contain ASCII and latin-1 only
  188. headers[key] = self.prepare(value, check, latin1=True)
  189. body = spec["body"]
  190. if body:
  191. body = self.prepare(body, check).encode()
  192. num_tries = 3
  193. if getattr(check, "is_test"):
  194. # When sending a test notification, don't retry on failures.
  195. num_tries = 1
  196. if spec["method"] == "GET":
  197. return self.get(url, num_tries=num_tries, headers=headers)
  198. elif spec["method"] == "POST":
  199. return self.post(url, num_tries=num_tries, data=body, headers=headers)
  200. elif spec["method"] == "PUT":
  201. return self.put(url, num_tries=num_tries, data=body, headers=headers)
  202. class Slack(HttpTransport):
  203. def notify(self, check):
  204. if self.channel.kind == "slack" and not settings.SLACK_ENABLED:
  205. return "Slack notifications are not enabled."
  206. if self.channel.kind == "mattermost" and not settings.MATTERMOST_ENABLED:
  207. return "Mattermost notifications are not enabled."
  208. text = tmpl("slack_message.json", check=check)
  209. payload = json.loads(text)
  210. return self.post(self.channel.slack_webhook_url, json=payload)
  211. class HipChat(HttpTransport):
  212. def is_noop(self, check):
  213. return True
  214. class Opsgenie(HttpTransport):
  215. @classmethod
  216. def get_error(cls, response):
  217. try:
  218. return response.json().get("message")
  219. except ValueError:
  220. pass
  221. def notify(self, check):
  222. if not settings.OPSGENIE_ENABLED:
  223. return "Opsgenie notifications are not enabled."
  224. headers = {
  225. "Conent-Type": "application/json",
  226. "Authorization": "GenieKey %s" % self.channel.opsgenie_key,
  227. }
  228. payload = {"alias": str(check.code), "source": settings.SITE_NAME}
  229. if check.status == "down":
  230. payload["tags"] = check.tags_list()
  231. payload["message"] = tmpl("opsgenie_message.html", check=check)
  232. payload["note"] = tmpl("opsgenie_note.html", check=check)
  233. payload["description"] = tmpl("opsgenie_description.html", check=check)
  234. url = "https://api.opsgenie.com/v2/alerts"
  235. if self.channel.opsgenie_region == "eu":
  236. url = "https://api.eu.opsgenie.com/v2/alerts"
  237. if check.status == "up":
  238. url += "/%s/close?identifierType=alias" % check.code
  239. return self.post(url, json=payload, headers=headers)
  240. class PagerDuty(HttpTransport):
  241. URL = "https://events.pagerduty.com/generic/2010-04-15/create_event.json"
  242. def notify(self, check):
  243. if not settings.PD_ENABLED:
  244. return "PagerDuty notifications are not enabled."
  245. description = tmpl("pd_description.html", check=check)
  246. payload = {
  247. "service_key": self.channel.pd_service_key,
  248. "incident_key": str(check.code),
  249. "event_type": "trigger" if check.status == "down" else "resolve",
  250. "description": description,
  251. "client": settings.SITE_NAME,
  252. "client_url": check.details_url(),
  253. }
  254. return self.post(self.URL, json=payload)
  255. class PagerTree(HttpTransport):
  256. def notify(self, check):
  257. if not settings.PAGERTREE_ENABLED:
  258. return "PagerTree notifications are not enabled."
  259. url = self.channel.value
  260. headers = {"Conent-Type": "application/json"}
  261. payload = {
  262. "incident_key": str(check.code),
  263. "event_type": "trigger" if check.status == "down" else "resolve",
  264. "title": tmpl("pagertree_title.html", check=check),
  265. "description": tmpl("pagertree_description.html", check=check),
  266. "client": settings.SITE_NAME,
  267. "client_url": settings.SITE_ROOT,
  268. "tags": ",".join(check.tags_list()),
  269. }
  270. return self.post(url, json=payload, headers=headers)
  271. class PagerTeam(HttpTransport):
  272. def is_noop(self, check):
  273. return True
  274. class Pushbullet(HttpTransport):
  275. def notify(self, check):
  276. text = tmpl("pushbullet_message.html", check=check)
  277. url = "https://api.pushbullet.com/v2/pushes"
  278. headers = {
  279. "Access-Token": self.channel.value,
  280. "Conent-Type": "application/json",
  281. }
  282. payload = {"type": "note", "title": settings.SITE_NAME, "body": text}
  283. return self.post(url, json=payload, headers=headers)
  284. class Pushover(HttpTransport):
  285. URL = "https://api.pushover.net/1/messages.json"
  286. def notify(self, check):
  287. pieces = self.channel.value.split("|")
  288. user_key, prio = pieces[0], pieces[1]
  289. # The third element, if present, is the priority for "up" events
  290. if len(pieces) == 3 and check.status == "up":
  291. prio = pieces[2]
  292. from hc.api.models import TokenBucket
  293. if not TokenBucket.authorize_pushover(user_key):
  294. return "Rate limit exceeded"
  295. others = self.checks().filter(status="down").exclude(code=check.code)
  296. # list() executes the query, to avoid DB access while
  297. # rendering a template
  298. ctx = {"check": check, "down_checks": list(others)}
  299. text = tmpl("pushover_message.html", **ctx)
  300. title = tmpl("pushover_title.html", **ctx)
  301. payload = {
  302. "token": settings.PUSHOVER_API_TOKEN,
  303. "user": user_key,
  304. "message": text,
  305. "title": title,
  306. "html": 1,
  307. "priority": int(prio),
  308. }
  309. # Emergency notification
  310. if prio == "2":
  311. payload["retry"] = settings.PUSHOVER_EMERGENCY_RETRY_DELAY
  312. payload["expire"] = settings.PUSHOVER_EMERGENCY_EXPIRATION
  313. return self.post(self.URL, data=payload)
  314. class VictorOps(HttpTransport):
  315. def notify(self, check):
  316. if not settings.VICTOROPS_ENABLED:
  317. return "Splunk On-Call notifications are not enabled."
  318. description = tmpl("victorops_description.html", check=check)
  319. mtype = "CRITICAL" if check.status == "down" else "RECOVERY"
  320. payload = {
  321. "entity_id": str(check.code),
  322. "message_type": mtype,
  323. "entity_display_name": check.name_then_code(),
  324. "state_message": description,
  325. "monitoring_tool": settings.SITE_NAME,
  326. }
  327. return self.post(self.channel.value, json=payload)
  328. class Matrix(HttpTransport):
  329. def get_url(self):
  330. s = quote(self.channel.value)
  331. url = settings.MATRIX_HOMESERVER
  332. url += "/_matrix/client/r0/rooms/%s/send/m.room.message?" % s
  333. url += urlencode({"access_token": settings.MATRIX_ACCESS_TOKEN})
  334. return url
  335. def notify(self, check):
  336. plain = tmpl("matrix_description.html", check=check)
  337. formatted = tmpl("matrix_description_formatted.html", check=check)
  338. payload = {
  339. "msgtype": "m.text",
  340. "body": plain,
  341. "format": "org.matrix.custom.html",
  342. "formatted_body": formatted,
  343. }
  344. return self.post(self.get_url(), json=payload)
  345. class Discord(HttpTransport):
  346. def notify(self, check):
  347. text = tmpl("slack_message.json", check=check)
  348. payload = json.loads(text)
  349. url = self.channel.discord_webhook_url + "/slack"
  350. return self.post(url, json=payload)
  351. class Telegram(HttpTransport):
  352. SM = "https://api.telegram.org/bot%s/sendMessage" % settings.TELEGRAM_TOKEN
  353. @classmethod
  354. def get_error(cls, response):
  355. try:
  356. return response.json().get("description")
  357. except ValueError:
  358. pass
  359. @classmethod
  360. def send(cls, chat_id, text):
  361. # Telegram.send is a separate method because it is also used in
  362. # hc.front.views.telegram_bot to send invite links.
  363. return cls.post(
  364. cls.SM, json={"chat_id": chat_id, "text": text, "parse_mode": "html"}
  365. )
  366. def notify(self, check):
  367. from hc.api.models import TokenBucket
  368. if not TokenBucket.authorize_telegram(self.channel.telegram_id):
  369. return "Rate limit exceeded"
  370. text = tmpl("telegram_message.html", check=check)
  371. return self.send(self.channel.telegram_id, text)
  372. class Sms(HttpTransport):
  373. URL = "https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json"
  374. def is_noop(self, check):
  375. if check.status == "down":
  376. return not self.channel.sms_notify_down
  377. else:
  378. return not self.channel.sms_notify_up
  379. def notify(self, check):
  380. profile = Profile.objects.for_user(self.channel.project.owner)
  381. if not profile.authorize_sms():
  382. profile.send_sms_limit_notice("SMS")
  383. return "Monthly SMS limit exceeded"
  384. url = self.URL % settings.TWILIO_ACCOUNT
  385. auth = (settings.TWILIO_ACCOUNT, settings.TWILIO_AUTH)
  386. text = tmpl("sms_message.html", check=check, site_name=settings.SITE_NAME)
  387. data = {
  388. "From": settings.TWILIO_FROM,
  389. "To": self.channel.phone_number,
  390. "Body": text,
  391. "StatusCallback": check.status_url,
  392. }
  393. return self.post(url, data=data, auth=auth)
  394. class Call(HttpTransport):
  395. URL = "https://api.twilio.com/2010-04-01/Accounts/%s/Calls.json"
  396. def is_noop(self, check):
  397. return check.status != "down"
  398. def notify(self, check):
  399. profile = Profile.objects.for_user(self.channel.project.owner)
  400. if not profile.authorize_call():
  401. profile.send_call_limit_notice()
  402. return "Monthly phone call limit exceeded"
  403. url = self.URL % settings.TWILIO_ACCOUNT
  404. auth = (settings.TWILIO_ACCOUNT, settings.TWILIO_AUTH)
  405. twiml = tmpl("call_message.html", check=check, site_name=settings.SITE_NAME)
  406. data = {
  407. "From": settings.TWILIO_FROM,
  408. "To": self.channel.phone_number,
  409. "Twiml": twiml,
  410. "StatusCallback": check.status_url,
  411. }
  412. return self.post(url, data=data, auth=auth)
  413. class WhatsApp(HttpTransport):
  414. URL = "https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json"
  415. def is_noop(self, check):
  416. if check.status == "down":
  417. return not self.channel.whatsapp_notify_down
  418. else:
  419. return not self.channel.whatsapp_notify_up
  420. def notify(self, check):
  421. profile = Profile.objects.for_user(self.channel.project.owner)
  422. if not profile.authorize_sms():
  423. profile.send_sms_limit_notice("WhatsApp")
  424. return "Monthly message limit exceeded"
  425. url = self.URL % settings.TWILIO_ACCOUNT
  426. auth = (settings.TWILIO_ACCOUNT, settings.TWILIO_AUTH)
  427. text = tmpl("whatsapp_message.html", check=check, site_name=settings.SITE_NAME)
  428. data = {
  429. "From": "whatsapp:%s" % settings.TWILIO_FROM,
  430. "To": "whatsapp:%s" % self.channel.phone_number,
  431. "Body": text,
  432. "StatusCallback": check.status_url,
  433. }
  434. return self.post(url, data=data, auth=auth)
  435. class Trello(HttpTransport):
  436. URL = "https://api.trello.com/1/cards"
  437. def is_noop(self, check):
  438. return check.status != "down"
  439. def notify(self, check):
  440. params = {
  441. "idList": self.channel.trello_list_id,
  442. "name": tmpl("trello_name.html", check=check),
  443. "desc": tmpl("trello_desc.html", check=check),
  444. "key": settings.TRELLO_APP_KEY,
  445. "token": self.channel.trello_token,
  446. }
  447. return self.post(self.URL, params=params)
  448. class Apprise(HttpTransport):
  449. def notify(self, check):
  450. if not settings.APPRISE_ENABLED:
  451. # Not supported and/or enabled
  452. return "Apprise is disabled and/or not installed"
  453. a = apprise.Apprise()
  454. title = tmpl("apprise_title.html", check=check)
  455. body = tmpl("apprise_description.html", check=check)
  456. a.add(self.channel.value)
  457. notify_type = (
  458. apprise.NotifyType.SUCCESS
  459. if check.status == "up"
  460. else apprise.NotifyType.FAILURE
  461. )
  462. return (
  463. "Failed"
  464. if not a.notify(body=body, title=title, notify_type=notify_type)
  465. else None
  466. )
  467. class MsTeams(HttpTransport):
  468. def escape_md(self, s):
  469. # Escape special HTML characters
  470. s = escape(s)
  471. # Escape characters that have special meaning in Markdown
  472. for c in r"\`*_{}[]()#+-.!|":
  473. s = s.replace(c, "\\" + c)
  474. return s
  475. def notify(self, check):
  476. if not settings.MSTEAMS_ENABLED:
  477. return "MS Teams notifications are not enabled."
  478. text = tmpl("msteams_message.json", check=check)
  479. payload = json.loads(text)
  480. # MS Teams escapes HTML special characters in the summary field.
  481. # It does not interpret summary content as Markdown.
  482. name = check.name_then_code()
  483. payload["summary"] = f"“{name}” is {check.status.upper()}."
  484. # MS teams *strips* HTML special characters from the title field.
  485. # To avoid that, we use escape().
  486. # It does not interpret title as Markdown.
  487. safe_name = escape(name)
  488. payload["title"] = f"“{safe_name}” is {check.status.upper()}."
  489. # MS teams allows some HTML in the section text.
  490. # It also interprets the section text as Markdown.
  491. # We want to display the raw content, angle brackets and all,
  492. # so we run escape() and then additionally escape Markdown:
  493. payload["sections"][0]["text"] = self.escape_md(check.desc)
  494. return self.post(self.channel.value, json=payload)
  495. class Zulip(HttpTransport):
  496. @classmethod
  497. def get_error(cls, response):
  498. try:
  499. return response.json().get("msg")
  500. except ValueError:
  501. pass
  502. def notify(self, check):
  503. if not settings.ZULIP_ENABLED:
  504. return "Zulip notifications are not enabled."
  505. url = self.channel.zulip_site + "/api/v1/messages"
  506. auth = (self.channel.zulip_bot_email, self.channel.zulip_api_key)
  507. data = {
  508. "type": self.channel.zulip_type,
  509. "to": self.channel.zulip_to,
  510. "topic": tmpl("zulip_topic.html", check=check),
  511. "content": tmpl("zulip_content.html", check=check),
  512. }
  513. return self.post(url, data=data, auth=auth)
  514. class Spike(HttpTransport):
  515. def notify(self, check):
  516. if not settings.SPIKE_ENABLED:
  517. return "Spike notifications are not enabled."
  518. url = self.channel.value
  519. headers = {"Conent-Type": "application/json"}
  520. payload = {
  521. "check_id": str(check.code),
  522. "title": tmpl("spike_title.html", check=check),
  523. "message": tmpl("spike_description.html", check=check),
  524. "status": check.status,
  525. }
  526. return self.post(url, json=payload, headers=headers)
  527. class LineNotify(HttpTransport):
  528. URL = "https://notify-api.line.me/api/notify"
  529. def notify(self, check):
  530. headers = {
  531. "Content-Type": "application/x-www-form-urlencoded",
  532. "Authorization": "Bearer %s" % self.channel.linenotify_token,
  533. }
  534. payload = {"message": tmpl("linenotify_message.html", check=check)}
  535. return self.post(self.URL, headers=headers, params=payload)
  536. class Signal(Transport):
  537. def is_noop(self, check):
  538. if check.status == "down":
  539. return not self.channel.signal_notify_down
  540. else:
  541. return not self.channel.signal_notify_up
  542. def get_service(self):
  543. bus = dbus.SystemBus()
  544. signal_object = bus.get_object("org.asamk.Signal", "/org/asamk/Signal")
  545. return dbus.Interface(signal_object, "org.asamk.Signal")
  546. def notify(self, check):
  547. if not settings.SIGNAL_CLI_ENABLED:
  548. return "Signal notifications are not enabled"
  549. from hc.api.models import TokenBucket
  550. if not TokenBucket.authorize_signal(self.channel.phone_number):
  551. return "Rate limit exceeded"
  552. text = tmpl("signal_message.html", check=check, site_name=settings.SITE_NAME)
  553. try:
  554. dbus.SystemBus().call_blocking(
  555. "org.asamk.Signal",
  556. "/org/asamk/Signal",
  557. "org.asamk.Signal",
  558. "sendMessage",
  559. "sasas",
  560. (text, [], [self.channel.phone_number]),
  561. timeout=30,
  562. )
  563. except dbus.exceptions.DBusException as e:
  564. if "NotFoundException" in str(e):
  565. return "Recipient not found"
  566. return "signal-cli call failed"