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