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.

744 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. if check.status == "down":
  371. return not self.channel.sms_notify_down
  372. else:
  373. return not self.channel.sms_notify_up
  374. def notify(self, check):
  375. profile = Profile.objects.for_user(self.channel.project.owner)
  376. if not profile.authorize_sms():
  377. profile.send_sms_limit_notice("SMS")
  378. return "Monthly SMS limit exceeded"
  379. url = self.URL % settings.TWILIO_ACCOUNT
  380. auth = (settings.TWILIO_ACCOUNT, settings.TWILIO_AUTH)
  381. text = tmpl("sms_message.html", check=check, site_name=settings.SITE_NAME)
  382. data = {
  383. "From": settings.TWILIO_FROM,
  384. "To": self.channel.phone_number,
  385. "Body": text,
  386. "StatusCallback": check.status_url,
  387. }
  388. return self.post(url, data=data, auth=auth)
  389. class Call(HttpTransport):
  390. URL = "https://api.twilio.com/2010-04-01/Accounts/%s/Calls.json"
  391. def is_noop(self, check):
  392. return check.status != "down"
  393. def notify(self, check):
  394. profile = Profile.objects.for_user(self.channel.project.owner)
  395. if not profile.authorize_call():
  396. profile.send_call_limit_notice()
  397. return "Monthly phone call limit exceeded"
  398. url = self.URL % settings.TWILIO_ACCOUNT
  399. auth = (settings.TWILIO_ACCOUNT, settings.TWILIO_AUTH)
  400. twiml = tmpl("call_message.html", check=check, site_name=settings.SITE_NAME)
  401. data = {
  402. "From": settings.TWILIO_FROM,
  403. "To": self.channel.phone_number,
  404. "Twiml": twiml,
  405. "StatusCallback": check.status_url,
  406. }
  407. return self.post(url, data=data, auth=auth)
  408. class WhatsApp(HttpTransport):
  409. URL = "https://api.twilio.com/2010-04-01/Accounts/%s/Messages.json"
  410. def is_noop(self, check):
  411. if check.status == "down":
  412. return not self.channel.whatsapp_notify_down
  413. else:
  414. return not self.channel.whatsapp_notify_up
  415. def notify(self, check):
  416. profile = Profile.objects.for_user(self.channel.project.owner)
  417. if not profile.authorize_sms():
  418. profile.send_sms_limit_notice("WhatsApp")
  419. return "Monthly message limit exceeded"
  420. url = self.URL % settings.TWILIO_ACCOUNT
  421. auth = (settings.TWILIO_ACCOUNT, settings.TWILIO_AUTH)
  422. text = tmpl("whatsapp_message.html", check=check, site_name=settings.SITE_NAME)
  423. data = {
  424. "From": "whatsapp:%s" % settings.TWILIO_FROM,
  425. "To": "whatsapp:%s" % self.channel.phone_number,
  426. "Body": text,
  427. "StatusCallback": check.status_url,
  428. }
  429. return self.post(url, data=data, auth=auth)
  430. class Trello(HttpTransport):
  431. URL = "https://api.trello.com/1/cards"
  432. def is_noop(self, check):
  433. return check.status != "down"
  434. def notify(self, check):
  435. params = {
  436. "idList": self.channel.trello_list_id,
  437. "name": tmpl("trello_name.html", check=check),
  438. "desc": tmpl("trello_desc.html", check=check),
  439. "key": settings.TRELLO_APP_KEY,
  440. "token": self.channel.trello_token,
  441. }
  442. return self.post(self.URL, params=params)
  443. class Apprise(HttpTransport):
  444. def notify(self, check):
  445. if not settings.APPRISE_ENABLED:
  446. # Not supported and/or enabled
  447. return "Apprise is disabled and/or not installed"
  448. a = apprise.Apprise()
  449. title = tmpl("apprise_title.html", check=check)
  450. body = tmpl("apprise_description.html", check=check)
  451. a.add(self.channel.value)
  452. notify_type = (
  453. apprise.NotifyType.SUCCESS
  454. if check.status == "up"
  455. else apprise.NotifyType.FAILURE
  456. )
  457. return (
  458. "Failed"
  459. if not a.notify(body=body, title=title, notify_type=notify_type)
  460. else None
  461. )
  462. class MsTeams(HttpTransport):
  463. def escape_md(self, s):
  464. # Escape special HTML characters
  465. s = escape(s)
  466. # Escape characters that have special meaning in Markdown
  467. for c in r"\`*_{}[]()#+-.!|":
  468. s = s.replace(c, "\\" + c)
  469. return s
  470. def notify(self, check):
  471. if not settings.MSTEAMS_ENABLED:
  472. return "MS Teams notifications are not enabled."
  473. text = tmpl("msteams_message.json", check=check)
  474. payload = json.loads(text)
  475. # MS Teams escapes HTML special characters in the summary field.
  476. # It does not interpret summary content as Markdown.
  477. name = check.name_then_code()
  478. payload["summary"] = f"“{name}” is {check.status.upper()}."
  479. # MS teams *strips* HTML special characters from the title field.
  480. # To avoid that, we use escape().
  481. # It does not interpret title as Markdown.
  482. safe_name = escape(name)
  483. payload["title"] = f"“{safe_name}” is {check.status.upper()}."
  484. # MS teams allows some HTML in the section text.
  485. # It also interprets the section text as Markdown.
  486. # We want to display the raw content, angle brackets and all,
  487. # so we run escape() and then additionally escape Markdown:
  488. payload["sections"][0]["text"] = self.escape_md(check.desc)
  489. return self.post(self.channel.value, json=payload)
  490. class Zulip(HttpTransport):
  491. @classmethod
  492. def get_error(cls, response):
  493. try:
  494. return response.json().get("msg")
  495. except ValueError:
  496. pass
  497. def notify(self, check):
  498. if not settings.ZULIP_ENABLED:
  499. return "Zulip notifications are not enabled."
  500. url = self.channel.zulip_site + "/api/v1/messages"
  501. auth = (self.channel.zulip_bot_email, self.channel.zulip_api_key)
  502. data = {
  503. "type": self.channel.zulip_type,
  504. "to": self.channel.zulip_to,
  505. "topic": tmpl("zulip_topic.html", check=check),
  506. "content": tmpl("zulip_content.html", check=check),
  507. }
  508. return self.post(url, data=data, auth=auth)
  509. class Spike(HttpTransport):
  510. def notify(self, check):
  511. if not settings.SPIKE_ENABLED:
  512. return "Spike notifications are not enabled."
  513. url = self.channel.value
  514. headers = {"Conent-Type": "application/json"}
  515. payload = {
  516. "check_id": str(check.code),
  517. "title": tmpl("spike_title.html", check=check),
  518. "message": tmpl("spike_description.html", check=check),
  519. "status": check.status,
  520. }
  521. return self.post(url, json=payload, headers=headers)
  522. class LineNotify(HttpTransport):
  523. URL = "https://notify-api.line.me/api/notify"
  524. def notify(self, check):
  525. headers = {
  526. "Content-Type": "application/x-www-form-urlencoded",
  527. "Authorization": "Bearer %s" % self.channel.linenotify_token,
  528. }
  529. payload = {"message": tmpl("linenotify_message.html", check=check)}
  530. return self.post(self.URL, headers=headers, params=payload)
  531. class Signal(Transport):
  532. def is_noop(self, check):
  533. if check.status == "down":
  534. return not self.channel.signal_notify_down
  535. else:
  536. return not self.channel.signal_notify_up
  537. def get_service(self):
  538. bus = dbus.SystemBus()
  539. signal_object = bus.get_object("org.asamk.Signal", "/org/asamk/Signal")
  540. return dbus.Interface(signal_object, "org.asamk.Signal")
  541. def notify(self, check):
  542. if not settings.SIGNAL_CLI_ENABLED:
  543. return "Signal notifications are not enabled"
  544. from hc.api.models import TokenBucket
  545. if not TokenBucket.authorize_signal(self.channel.phone_number):
  546. return "Rate limit exceeded"
  547. text = tmpl("signal_message.html", check=check, site_name=settings.SITE_NAME)
  548. try:
  549. dbus.SystemBus().call_blocking(
  550. "org.asamk.Signal",
  551. "/org/asamk/Signal",
  552. "org.asamk.Signal",
  553. "sendMessage",
  554. "sasas",
  555. (text, [], [self.channel.phone_number]),
  556. timeout=30,
  557. )
  558. except dbus.exceptions.DBusException as e:
  559. if "NotFoundException" in str(e):
  560. return "Recipient not found"
  561. return "signal-cli call failed"