cli.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. import json
  2. import subprocess
  3. from time import sleep
  4. from constants import MANAGEMENT_HOST_NAME
  5. from setup import get_config_from_file
  6. from util import get_tunnel_connector_id
  7. SINGLE_CASE_TIMEOUT = 600
  8. class CloudflaredCli:
  9. def __init__(self, config, config_path, logger):
  10. self.basecmd = [config.cloudflared_binary, "tunnel"]
  11. if config_path is not None:
  12. self.basecmd += ["--config", str(config_path)]
  13. origincert = get_config_from_file()["origincert"]
  14. if origincert:
  15. self.basecmd += ["--origincert", origincert]
  16. self.logger = logger
  17. def _run_command(self, subcmd, subcmd_name, needs_to_pass=True):
  18. cmd = self.basecmd + subcmd
  19. # timeout limits the time a subprocess can run. This is useful to guard against running a tunnel when
  20. # command/args are in wrong order.
  21. result = run_subprocess(cmd, subcmd_name, self.logger, check=needs_to_pass, capture_output=True, timeout=15)
  22. return result
  23. def list_tunnels(self):
  24. cmd_args = ["list", "--output", "json"]
  25. listed = self._run_command(cmd_args, "list")
  26. return json.loads(listed.stdout)
  27. def get_management_token(self, config, config_path):
  28. basecmd = [config.cloudflared_binary]
  29. if config_path is not None:
  30. basecmd += ["--config", str(config_path)]
  31. origincert = get_config_from_file()["origincert"]
  32. if origincert:
  33. basecmd += ["--origincert", origincert]
  34. cmd_args = ["tail", "token", config.get_tunnel_id()]
  35. cmd = basecmd + cmd_args
  36. result = run_subprocess(cmd, "token", self.logger, check=True, capture_output=True, timeout=15)
  37. return json.loads(result.stdout.decode("utf-8").strip())["token"]
  38. def get_management_url(self, path, config, config_path):
  39. access_jwt = self.get_management_token(config, config_path)
  40. connector_id = get_tunnel_connector_id()
  41. return f"https://{MANAGEMENT_HOST_NAME}/{path}?connector_id={connector_id}&access_token={access_jwt}"
  42. def get_management_wsurl(self, path, config, config_path):
  43. access_jwt = self.get_management_token(config, config_path)
  44. connector_id = get_tunnel_connector_id()
  45. return f"wss://{MANAGEMENT_HOST_NAME}/{path}?connector_id={connector_id}&access_token={access_jwt}"
  46. def get_connector_id(self, config):
  47. op = self.get_tunnel_info(config.get_tunnel_id())
  48. connectors = []
  49. for conn in op["conns"]:
  50. connectors.append(conn["id"])
  51. return connectors
  52. def get_tunnel_info(self, tunnel_id):
  53. info = self._run_command(["info", "--output", "json", tunnel_id], "info")
  54. return json.loads(info.stdout)
  55. def __enter__(self):
  56. self.basecmd += ["run"]
  57. self.process = subprocess.Popen(self.basecmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  58. self.logger.info(f"Run cmd {self.basecmd}")
  59. return self.process
  60. def __exit__(self, exc_type, exc_value, exc_traceback):
  61. terminate_gracefully(self.process, self.logger, self.basecmd)
  62. self.logger.debug(f"{self.basecmd} logs: {self.process.stderr.read()}")
  63. def terminate_gracefully(process, logger, cmd):
  64. process.terminate()
  65. process_terminated = wait_for_terminate(process)
  66. if not process_terminated:
  67. process.kill()
  68. logger.warning(f"{cmd}: cloudflared did not terminate within wait period. Killing process. logs: \
  69. stdout: {process.stdout.read()}, stderr: {process.stderr.read()}")
  70. def wait_for_terminate(opened_subprocess, attempts=10, poll_interval=1):
  71. """
  72. wait_for_terminate polls the opened_subprocess every x seconds for a given number of attempts.
  73. It returns true if the subprocess was terminated and false if it didn't.
  74. """
  75. for _ in range(attempts):
  76. if _is_process_stopped(opened_subprocess):
  77. return True
  78. sleep(poll_interval)
  79. return False
  80. def _is_process_stopped(process):
  81. return process.poll() is not None
  82. def cert_path():
  83. return get_config_from_file()["origincert"]
  84. class SubprocessError(Exception):
  85. def __init__(self, program, exit_code, cause):
  86. self.program = program
  87. self.exit_code = exit_code
  88. self.cause = cause
  89. def run_subprocess(cmd, cmd_name, logger, timeout=SINGLE_CASE_TIMEOUT, **kargs):
  90. kargs["timeout"] = timeout
  91. try:
  92. result = subprocess.run(cmd, **kargs)
  93. logger.debug(f"{cmd} log: {result.stdout}", extra={"cmd": cmd_name})
  94. return result
  95. except subprocess.CalledProcessError as e:
  96. err = f"{cmd} return exit code {e.returncode}, stderr" + e.stderr.decode("utf-8")
  97. logger.error(err, extra={"cmd": cmd_name, "return_code": e.returncode})
  98. raise SubprocessError(cmd[0], e.returncode, e)
  99. except subprocess.TimeoutExpired as e:
  100. err = f"{cmd} timeout after {e.timeout} seconds, stdout: {e.stdout}, stderr: {e.stderr}"
  101. logger.error(err, extra={"cmd": cmd_name, "return_code": "timeout"})
  102. raise e