cloudflare/cloudflared
Publicmirrored from https://github.com/cloudflare/cloudflaredAvailable
component-tests/cli.py
95lines · modeblame
e921ab35Devin Carr4 years ago | 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_tunnel_info(self, tunnel_id): | |
| 32 | info = self._run_command(["info", "--output", "json", tunnel_id], "info") | |
| 33 | return json.loads(info.stdout) | |
| 34 | | |
| 35 | def __enter__(self): | |
| 36 | self.basecmd += ["run"] | |
| 37 | self.process = subprocess.Popen(self.basecmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) | |
| 38 | self.logger.info(f"Run cmd {self.basecmd}") | |
| 39 | return self.process | |
| 40 | | |
| 41 | def __exit__(self, exc_type, exc_value, exc_traceback): | |
| 42 | terminate_gracefully(self.process, self.logger, self.basecmd) | |
| 43 | self.logger.debug(f"{self.basecmd} logs: {self.process.stderr.read()}") | |
| 44 | | |
| 45 | | |
| 46 | def terminate_gracefully(process, logger, cmd): | |
| 47 | process.terminate() | |
| 48 | process_terminated = wait_for_terminate(process) | |
| 49 | if not process_terminated: | |
| 50 | process.kill() | |
| 51 | logger.warning(f"{cmd}: cloudflared did not terminate within wait period. Killing process. logs: \ | |
| 52 | stdout: {process.stdout.read()}, stderr: {process.stderr.read()}") | |
| 53 | | |
| 54 | | |
| 55 | def wait_for_terminate(opened_subprocess, attempts=10, poll_interval=1): | |
| 56 | """ | |
| 57 | wait_for_terminate polls the opened_subprocess every x seconds for a given number of attempts. | |
| 58 | It returns true if the subprocess was terminated and false if it didn't. | |
| 59 | """ | |
| 60 | for _ in range(attempts): | |
| 61 | if _is_process_stopped(opened_subprocess): | |
| 62 | return True | |
| 63 | sleep(poll_interval) | |
| 64 | return False | |
| 65 | | |
| 66 | | |
| 67 | def _is_process_stopped(process): | |
| 68 | return process.poll() is not None | |
| 69 | | |
| 70 | | |
| 71 | def cert_path(): | |
| 72 | return get_config_from_file()["origincert"] | |
| 73 | | |
| 74 | | |
| 75 | class SubprocessError(Exception): | |
| 76 | def __init__(self, program, exit_code, cause): | |
| 77 | self.program = program | |
| 78 | self.exit_code = exit_code | |
| 79 | self.cause = cause | |
| 80 | | |
| 81 | | |
| 82 | def run_subprocess(cmd, cmd_name, logger, timeout=SINGLE_CASE_TIMEOUT, **kargs): | |
| 83 | kargs["timeout"] = timeout | |
| 84 | try: | |
| 85 | result = subprocess.run(cmd, **kargs) | |
| 86 | logger.debug(f"{cmd} log: {result.stdout}", extra={"cmd": cmd_name}) | |
| 87 | return result | |
| 88 | except subprocess.CalledProcessError as e: | |
| 89 | err = f"{cmd} return exit code {e.returncode}, stderr" + e.stderr.decode("utf-8") | |
| 90 | logger.error(err, extra={"cmd": cmd_name, "return_code": e.returncode}) | |
| 91 | raise SubprocessError(cmd[0], e.returncode, e) | |
| 92 | except subprocess.TimeoutExpired as e: | |
| 93 | err = f"{cmd} timeout after {e.timeout} seconds, stdout: {e.stdout}, stderr: {e.stderr}" | |
| 94 | logger.error(err, extra={"cmd": cmd_name, "return_code": "timeout"}) | |
| 95 | raise e |