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
24 KiB

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