from fabric.api import local, run as _run, env, put from loguru import logger import json def run(cmd, capture=True, **kwargs): assert len(env.hosts) > 0 try: if env.hosts[0] == "localhost": return local(cmd, capture=capture, **kwargs) else: return _run(cmd, **kwargs) except Exception as e: logger.error(e) def show_config(config_file): with open(config_file, "r") as fr: config = json.loads(fr.read()) tiup_cmd = config["tiup_cmd"] cluster_name = config["tiup_cluster_name"] show_cmd = "%s cluster show-config %s --wait-timeout 5 --yes" % (tiup_cmd, cluster_name) resp = run(show_cmd) begin = resp.find("global:") end = resp.find("Done.") # remove xterm control char out = resp[begin:end].replace('\x1b[0m\x1b[0', '').strip() print(out) return out def edit_config(config_file, topology_file): with open(config_file, "r") as fr: config = json.loads(fr.read()) tiup_cmd = config["tiup_cmd"] cluster_name = config["tiup_cluster_name"] if env.hosts[0] != "localhost": put(topology_file, "/tmp/") edit_cmd = "%s cluster edit-config %s --topology-file %s " \ "--wait-timeout 5 --yes" % (tiup_cmd, cluster_name, topology_file) return run(edit_cmd) def reload(config_file, cluster_roles): with open(config_file, "r") as fr: config = json.loads(fr.read()) tiup_cmd = config["tiup_cmd"] cluster_name = config["tiup_cluster_name"] roles = cluster_roles.replace(':', ',') reload_cmd = "%s cluster reload %s -R %s --yes" % (tiup_cmd, cluster_name, roles) return run(reload_cmd)