cloudflare/cloudflared

Public

mirrored from https://github.com/cloudflare/cloudflaredAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
2026.3.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

component-tests/cli.py

144lines · modeblame

e921ab35Devin Carr4 years ago1import json
2import subprocess
3from time import sleep
4
ee5e447dDevin Carr3 years ago5from constants import MANAGEMENT_HOST_NAME
e921ab35Devin Carr4 years ago6from setup import get_config_from_file
ee5e447dDevin Carr3 years ago7from util import get_tunnel_connector_id
e921ab35Devin Carr4 years ago8
9SINGLE_CASE_TIMEOUT = 600
10
11class CloudflaredCli:
12def __init__(self, config, config_path, logger):
13self.basecmd = [config.cloudflared_binary, "tunnel"]
14if config_path is not None:
15self.basecmd += ["--config", str(config_path)]
16origincert = get_config_from_file()["origincert"]
17if origincert:
18self.basecmd += ["--origincert", origincert]
19self.logger = logger
20
21def _run_command(self, subcmd, subcmd_name, needs_to_pass=True):
22cmd = self.basecmd + subcmd
23# timeout limits the time a subprocess can run. This is useful to guard against running a tunnel when
24# command/args are in wrong order.
25result = run_subprocess(cmd, subcmd_name, self.logger, check=needs_to_pass, capture_output=True, timeout=15)
26return result
27
28def list_tunnels(self):
29cmd_args = ["list", "--output", "json"]
30listed = self._run_command(cmd_args, "list")
31return json.loads(listed.stdout)
32
372a4b70Gonçalo Garcia3 months ago33def get_management_token(self, config, config_path, resource):
5e212a6bSudarsan Reddy3 years ago34basecmd = [config.cloudflared_binary]
35if config_path is not None:
36basecmd += ["--config", str(config_path)]
37origincert = get_config_from_file()["origincert"]
38if origincert:
39basecmd += ["--origincert", origincert]
40
372a4b70Gonçalo Garcia3 months ago41cmd_args = ["management", "token", "--resource", resource, config.get_tunnel_id()]
5e212a6bSudarsan Reddy3 years ago42cmd = basecmd + cmd_args
43result = run_subprocess(cmd, "token", self.logger, check=True, capture_output=True, timeout=15)
44return json.loads(result.stdout.decode("utf-8").strip())["token"]
ee5e447dDevin Carr3 years ago45
372a4b70Gonçalo Garcia3 months ago46def get_tail_token(self, config, config_path):
47"""
48Get management token using the 'tail token' command.
49Returns a token scoped for 'logs' resource.
50"""
51basecmd = [config.cloudflared_binary]
52if config_path is not None:
53basecmd += ["--config", str(config_path)]
54origincert = get_config_from_file()["origincert"]
55if origincert:
56basecmd += ["--origincert", origincert]
57
58cmd_args = ["tail", "token", config.get_tunnel_id()]
59cmd = basecmd + cmd_args
60result = run_subprocess(cmd, "tail-token", self.logger, check=True, capture_output=True, timeout=15)
61return json.loads(result.stdout.decode("utf-8").strip())["token"]
62
63def get_management_url(self, path, config, config_path, resource):
64access_jwt = self.get_management_token(config, config_path, resource)
ee5e447dDevin Carr3 years ago65connector_id = get_tunnel_connector_id()
66return f"https://{MANAGEMENT_HOST_NAME}/{path}?connector_id={connector_id}&access_token={access_jwt}"
67
372a4b70Gonçalo Garcia3 months ago68def get_management_wsurl(self, path, config, config_path, resource):
69access_jwt = self.get_management_token(config, config_path, resource)
ee5e447dDevin Carr3 years ago70connector_id = get_tunnel_connector_id()
71return f"wss://{MANAGEMENT_HOST_NAME}/{path}?connector_id={connector_id}&access_token={access_jwt}"
5e212a6bSudarsan Reddy3 years ago72
73def get_connector_id(self, config):
74op = self.get_tunnel_info(config.get_tunnel_id())
75connectors = []
76for conn in op["conns"]:
77connectors.append(conn["id"])
78return connectors
79
e921ab35Devin Carr4 years ago80def get_tunnel_info(self, tunnel_id):
81info = self._run_command(["info", "--output", "json", tunnel_id], "info")
82return json.loads(info.stdout)
83
84def __enter__(self):
85self.basecmd += ["run"]
86self.process = subprocess.Popen(self.basecmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
87self.logger.info(f"Run cmd {self.basecmd}")
88return self.process
89
90def __exit__(self, exc_type, exc_value, exc_traceback):
91terminate_gracefully(self.process, self.logger, self.basecmd)
92self.logger.debug(f"{self.basecmd} logs: {self.process.stderr.read()}")
93
94
95def terminate_gracefully(process, logger, cmd):
96process.terminate()
97process_terminated = wait_for_terminate(process)
98if not process_terminated:
99process.kill()
100logger.warning(f"{cmd}: cloudflared did not terminate within wait period. Killing process. logs: \
101stdout: {process.stdout.read()}, stderr: {process.stderr.read()}")
102
103
104def wait_for_terminate(opened_subprocess, attempts=10, poll_interval=1):
105"""
106wait_for_terminate polls the opened_subprocess every x seconds for a given number of attempts.
107It returns true if the subprocess was terminated and false if it didn't.
108"""
109for _ in range(attempts):
110if _is_process_stopped(opened_subprocess):
111return True
112sleep(poll_interval)
113return False
114
115
116def _is_process_stopped(process):
117return process.poll() is not None
118
119
120def cert_path():
121return get_config_from_file()["origincert"]
122
123
124class SubprocessError(Exception):
125def __init__(self, program, exit_code, cause):
126self.program = program
127self.exit_code = exit_code
128self.cause = cause
129
130
131def run_subprocess(cmd, cmd_name, logger, timeout=SINGLE_CASE_TIMEOUT, **kargs):
132kargs["timeout"] = timeout
133try:
134result = subprocess.run(cmd, **kargs)
135logger.debug(f"{cmd} log: {result.stdout}", extra={"cmd": cmd_name})
136return result
137except subprocess.CalledProcessError as e:
138err = f"{cmd} return exit code {e.returncode}, stderr" + e.stderr.decode("utf-8")
139logger.error(err, extra={"cmd": cmd_name, "return_code": e.returncode})
140raise SubprocessError(cmd[0], e.returncode, e)
141except subprocess.TimeoutExpired as e:
142err = f"{cmd} timeout after {e.timeout} seconds, stdout: {e.stdout}, stderr: {e.stderr}"
143logger.error(err, extra={"cmd": cmd_name, "return_code": "timeout"})
144raise e