2021-03-05 22:50:11 +00:00
|
|
|
import logging
|
2021-11-09 17:30:57 +00:00
|
|
|
import os
|
2021-03-05 22:50:11 +00:00
|
|
|
import subprocess
|
2021-11-09 17:30:57 +00:00
|
|
|
from contextlib import contextmanager
|
2021-03-08 15:42:49 +00:00
|
|
|
from time import sleep
|
|
|
|
|
2021-11-09 17:30:57 +00:00
|
|
|
import requests
|
|
|
|
import yaml
|
|
|
|
from retrying import retry
|
|
|
|
|
2021-03-08 15:42:49 +00:00
|
|
|
from constants import METRICS_PORT, MAX_RETRIES, BACKOFF_SECS
|
|
|
|
|
2021-03-05 22:50:11 +00:00
|
|
|
LOGGER = logging.getLogger(__name__)
|
|
|
|
|
2021-03-08 15:42:49 +00:00
|
|
|
|
2021-03-12 13:37:53 +00:00
|
|
|
def write_config(directory, config):
|
|
|
|
config_path = directory / "config.yml"
|
2021-03-05 22:50:11 +00:00
|
|
|
with open(config_path, 'w') as outfile:
|
|
|
|
yaml.dump(config, outfile)
|
|
|
|
return config_path
|
|
|
|
|
|
|
|
|
2021-11-09 17:30:57 +00:00
|
|
|
def start_cloudflared(directory, config, cfd_args=["run"], cfd_pre_args=["tunnel"], new_process=False,
|
|
|
|
allow_input=False, capture_output=True, root=False):
|
2021-03-12 13:37:53 +00:00
|
|
|
config_path = write_config(directory, config.full_config)
|
|
|
|
cmd = cloudflared_cmd(config, config_path, cfd_args, cfd_pre_args, root)
|
2021-03-08 15:42:49 +00:00
|
|
|
if new_process:
|
2021-03-11 13:49:09 +00:00
|
|
|
return run_cloudflared_background(cmd, allow_input, capture_output)
|
2021-03-08 15:42:49 +00:00
|
|
|
# By setting check=True, it will raise an exception if the process exits with non-zero exit code
|
|
|
|
return subprocess.run(cmd, check=True, capture_output=capture_output)
|
|
|
|
|
|
|
|
|
2021-03-12 13:37:53 +00:00
|
|
|
def cloudflared_cmd(config, config_path, cfd_args, cfd_pre_args, root):
|
|
|
|
cmd = []
|
|
|
|
if root:
|
|
|
|
cmd += ["sudo"]
|
|
|
|
cmd += [config.cloudflared_binary]
|
|
|
|
cmd += cfd_pre_args
|
2021-06-08 10:01:53 +00:00
|
|
|
cmd += ["--config", str(config_path)]
|
2021-03-12 13:37:53 +00:00
|
|
|
cmd += cfd_args
|
|
|
|
LOGGER.info(f"Run cmd {cmd} with config {config}")
|
|
|
|
return cmd
|
|
|
|
|
|
|
|
|
2021-03-08 15:42:49 +00:00
|
|
|
@contextmanager
|
2021-03-11 13:49:09 +00:00
|
|
|
def run_cloudflared_background(cmd, allow_input, capture_output):
|
2021-03-08 15:42:49 +00:00
|
|
|
output = subprocess.PIPE if capture_output else subprocess.DEVNULL
|
2021-03-11 13:49:09 +00:00
|
|
|
stdin = subprocess.PIPE if allow_input else None
|
2021-03-08 15:42:49 +00:00
|
|
|
try:
|
2021-03-11 13:49:09 +00:00
|
|
|
cfd = subprocess.Popen(cmd, stdin=stdin, stdout=output, stderr=output)
|
2021-03-08 15:42:49 +00:00
|
|
|
yield cfd
|
|
|
|
finally:
|
|
|
|
cfd.terminate()
|
2021-03-23 13:21:37 +00:00
|
|
|
if capture_output:
|
2021-06-08 10:01:53 +00:00
|
|
|
LOGGER.info(f"cloudflared log: {cfd.stderr.read()}")
|
2021-03-08 15:42:49 +00:00
|
|
|
|
|
|
|
|
2021-11-09 17:30:57 +00:00
|
|
|
def wait_tunnel_ready(tunnel_url=None, require_min_connections=1, cfd_logs=None):
|
|
|
|
try:
|
|
|
|
inner_wait_tunnel_ready(tunnel_url, require_min_connections)
|
|
|
|
except Exception as e:
|
|
|
|
if cfd_logs is not None:
|
|
|
|
_log_cloudflared_logs(cfd_logs)
|
|
|
|
raise e
|
|
|
|
|
|
|
|
|
2021-03-08 15:42:49 +00:00
|
|
|
@retry(stop_max_attempt_number=MAX_RETRIES, wait_fixed=BACKOFF_SECS * 1000)
|
2021-11-09 17:30:57 +00:00
|
|
|
def inner_wait_tunnel_ready(tunnel_url=None, require_min_connections=1):
|
2021-03-11 20:43:31 +00:00
|
|
|
metrics_url = f'http://localhost:{METRICS_PORT}/ready'
|
2021-03-11 13:49:09 +00:00
|
|
|
|
|
|
|
with requests.Session() as s:
|
2021-03-11 20:43:31 +00:00
|
|
|
resp = send_request(s, metrics_url, True)
|
2021-11-09 17:30:57 +00:00
|
|
|
|
|
|
|
assert resp.json()["readyConnections"] >= require_min_connections, \
|
|
|
|
f"Ready endpoint returned {resp.json()} but we expect at least {require_min_connections} connections"
|
|
|
|
|
2021-03-11 20:43:31 +00:00
|
|
|
if tunnel_url is not None:
|
|
|
|
send_request(s, tunnel_url, True)
|
2021-03-11 13:49:09 +00:00
|
|
|
|
|
|
|
|
2021-11-09 17:30:57 +00:00
|
|
|
def _log_cloudflared_logs(cfd_logs):
|
|
|
|
log_file = cfd_logs
|
|
|
|
if os.path.isdir(cfd_logs):
|
|
|
|
files = os.listdir(cfd_logs)
|
|
|
|
if len(files) == 0:
|
|
|
|
return
|
|
|
|
log_file = os.path.join(cfd_logs, files[0])
|
|
|
|
with open(log_file, "r") as f:
|
|
|
|
LOGGER.warning("Cloudflared Tunnel was not ready:")
|
|
|
|
for line in f.readlines():
|
|
|
|
LOGGER.warning(line)
|
|
|
|
|
|
|
|
|
2021-03-18 08:28:38 +00:00
|
|
|
@retry(stop_max_attempt_number=MAX_RETRIES * BACKOFF_SECS, wait_fixed=1000)
|
2021-03-11 20:43:31 +00:00
|
|
|
def check_tunnel_not_connected():
|
2021-03-11 13:49:09 +00:00
|
|
|
url = f'http://localhost:{METRICS_PORT}/ready'
|
|
|
|
|
2021-03-16 10:39:58 +00:00
|
|
|
try:
|
|
|
|
resp = requests.get(url, timeout=1)
|
|
|
|
assert resp.status_code == 503, f"Expect {url} returns 503, got {resp.status_code}"
|
|
|
|
# cloudflared might already terminate
|
|
|
|
except requests.exceptions.ConnectionError as e:
|
|
|
|
LOGGER.warning(f"Failed to connect to {url}, error: {e}")
|
2021-03-08 15:42:49 +00:00
|
|
|
|
|
|
|
|
2021-03-11 20:43:31 +00:00
|
|
|
# In some cases we don't need to check response status, such as when sending batch requests to generate logs
|
2021-03-08 15:42:49 +00:00
|
|
|
def send_requests(url, count, require_ok=True):
|
|
|
|
errors = 0
|
|
|
|
with requests.Session() as s:
|
|
|
|
for _ in range(count):
|
2021-03-11 13:49:09 +00:00
|
|
|
resp = send_request(s, url, require_ok)
|
|
|
|
if resp is None:
|
2021-03-08 15:42:49 +00:00
|
|
|
errors += 1
|
|
|
|
sleep(0.01)
|
|
|
|
if errors > 0:
|
|
|
|
LOGGER.warning(
|
|
|
|
f"{errors} out of {count} requests to {url} return non-200 status")
|
|
|
|
|
|
|
|
|
|
|
|
@retry(stop_max_attempt_number=MAX_RETRIES, wait_fixed=BACKOFF_SECS * 1000)
|
|
|
|
def send_request(session, url, require_ok):
|
|
|
|
resp = session.get(url, timeout=BACKOFF_SECS)
|
|
|
|
if require_ok:
|
|
|
|
assert resp.status_code == 200, f"{url} returned {resp}"
|
2021-03-11 13:49:09 +00:00
|
|
|
return resp if resp.status_code == 200 else None
|