cloudflare/cloudflared
Publicmirrored fromhttps://github.com/cloudflare/cloudflaredAvailable
component-tests/cli.py
117lines · modecode
| 1 | import json |
| 2 | import subprocess |
| 3 | |
| 4 | from constants import MANAGEMENT_HOST_NAME |
| 5 | from setup import get_config_from_file |
| 6 | from util import get_tunnel_connector_id, CloudflaredProcess |
| 7 | |
| 8 | SINGLE_CASE_TIMEOUT = 600 |
| 9 | |
| 10 | class CloudflaredCli: |
| 11 | def __init__(self, config, config_path, logger): |
| 12 | self.basecmd = [config.cloudflared_binary, "tunnel"] |
| 13 | if config_path is not None: |
| 14 | self.basecmd += ["--config", str(config_path)] |
| 15 | origincert = get_config_from_file()["origincert"] |
| 16 | if origincert: |
| 17 | self.basecmd += ["--origincert", origincert] |
| 18 | self.logger = logger |
| 19 | |
| 20 | def _run_command(self, subcmd, subcmd_name, needs_to_pass=True): |
| 21 | cmd = self.basecmd + subcmd |
| 22 | # timeout limits the time a subprocess can run. This is useful to guard against running a tunnel when |
| 23 | # command/args are in wrong order. |
| 24 | result = run_subprocess(cmd, subcmd_name, self.logger, check=needs_to_pass, capture_output=True, timeout=15) |
| 25 | return result |
| 26 | |
| 27 | def list_tunnels(self): |
| 28 | cmd_args = ["list", "--output", "json"] |
| 29 | listed = self._run_command(cmd_args, "list") |
| 30 | return json.loads(listed.stdout) |
| 31 | |
| 32 | def get_management_token(self, config, config_path, resource): |
| 33 | basecmd = [config.cloudflared_binary] |
| 34 | if config_path is not None: |
| 35 | basecmd += ["--config", str(config_path)] |
| 36 | origincert = get_config_from_file()["origincert"] |
| 37 | if origincert: |
| 38 | basecmd += ["--origincert", origincert] |
| 39 | |
| 40 | cmd_args = ["management", "token", "--resource", resource, config.get_tunnel_id()] |
| 41 | cmd = basecmd + cmd_args |
| 42 | result = run_subprocess(cmd, "token", self.logger, check=True, capture_output=True, timeout=15) |
| 43 | return json.loads(result.stdout.decode("utf-8").strip())["token"] |
| 44 | |
| 45 | def get_tail_token(self, config, config_path): |
| 46 | """ |
| 47 | Get management token using the 'tail token' command. |
| 48 | Returns a token scoped for 'logs' resource. |
| 49 | """ |
| 50 | basecmd = [config.cloudflared_binary] |
| 51 | if config_path is not None: |
| 52 | basecmd += ["--config", str(config_path)] |
| 53 | origincert = get_config_from_file()["origincert"] |
| 54 | if origincert: |
| 55 | basecmd += ["--origincert", origincert] |
| 56 | |
| 57 | cmd_args = ["tail", "token", config.get_tunnel_id()] |
| 58 | cmd = basecmd + cmd_args |
| 59 | result = run_subprocess(cmd, "tail-token", self.logger, check=True, capture_output=True, timeout=15) |
| 60 | return json.loads(result.stdout.decode("utf-8").strip())["token"] |
| 61 | |
| 62 | def get_management_url(self, path, config, config_path, resource): |
| 63 | access_jwt = self.get_management_token(config, config_path, resource) |
| 64 | connector_id = get_tunnel_connector_id() |
| 65 | return f"https://{MANAGEMENT_HOST_NAME}/{path}?connector_id={connector_id}&access_token={access_jwt}" |
| 66 | |
| 67 | def get_management_wsurl(self, path, config, config_path, resource): |
| 68 | access_jwt = self.get_management_token(config, config_path, resource) |
| 69 | connector_id = get_tunnel_connector_id() |
| 70 | return f"wss://{MANAGEMENT_HOST_NAME}/{path}?connector_id={connector_id}&access_token={access_jwt}" |
| 71 | |
| 72 | def get_connector_id(self, config): |
| 73 | op = self.get_tunnel_info(config.get_tunnel_id()) |
| 74 | connectors = [] |
| 75 | for conn in op["conns"]: |
| 76 | connectors.append(conn["id"]) |
| 77 | return connectors |
| 78 | |
| 79 | def get_tunnel_info(self, tunnel_id): |
| 80 | info = self._run_command(["info", "--output", "json", tunnel_id], "info") |
| 81 | return json.loads(info.stdout) |
| 82 | |
| 83 | def __enter__(self): |
| 84 | self.basecmd += ["run"] |
| 85 | self.logger.info(f"Run cmd {self.basecmd}") |
| 86 | self.cfd = CloudflaredProcess(self.basecmd, allow_input=False, capture_output=True) |
| 87 | return self.cfd |
| 88 | |
| 89 | def __exit__(self, exc_type, exc_value, exc_traceback): |
| 90 | self.cfd.cleanup() |
| 91 | |
| 92 | |
| 93 | def cert_path(): |
| 94 | return get_config_from_file()["origincert"] |
| 95 | |
| 96 | |
| 97 | class SubprocessError(Exception): |
| 98 | def __init__(self, program, exit_code, cause): |
| 99 | self.program = program |
| 100 | self.exit_code = exit_code |
| 101 | self.cause = cause |
| 102 | |
| 103 | |
| 104 | def run_subprocess(cmd, cmd_name, logger, timeout=SINGLE_CASE_TIMEOUT, **kargs): |
| 105 | kargs["timeout"] = timeout |
| 106 | try: |
| 107 | result = subprocess.run(cmd, **kargs) |
| 108 | logger.debug(f"{cmd} log: {result.stdout}", extra={"cmd": cmd_name}) |
| 109 | return result |
| 110 | except subprocess.CalledProcessError as e: |
| 111 | err = f"{cmd} return exit code {e.returncode}, stderr" + e.stderr.decode("utf-8") |
| 112 | logger.error(err, extra={"cmd": cmd_name, "return_code": e.returncode}) |
| 113 | raise SubprocessError(cmd[0], e.returncode, e) |
| 114 | except subprocess.TimeoutExpired as e: |
| 115 | err = f"{cmd} timeout after {e.timeout} seconds, stdout: {e.stdout}, stderr: {e.stderr}" |
| 116 | logger.error(err, extra={"cmd": cmd_name, "return_code": "timeout"}) |
| 117 | raise e |