import os, json, time, re, sys, subprocess from clusterman.config import CONF def get_node_list(): nodes_path=CONF.NODE_FILE if os.path.exists(nodes_path): with open(nodes_path) as f: nodes=json.load(f) return nodes return list() def get_node_in_group(group): nodes=get_node_list() # Search ingroup=list() if len(nodes) > 0 and group in CONF["cluster"]["groups"]: patterns=[re.compile(pattern) for pattern in CONF["cluster"]["groups"][group]] for node in nodes: for pattern in patterns: if pattern.match(node): ingroup.append(node) break; return ingroup def ls(group=None): nodes_path=CONF.NODE_FILE nodes=get_node_list() if len(nodes)<=0: print("Please perform a scan before") exit(0) # Print nodes if group is not None: for node in get_node_in_group(group): print(node) else: for node in nodes: print(node) def scan(timeout): from_split=[int(n) for n in CONF["cluster"]["ip4_from"].split(".")] to_split=[int(n) for n in CONF["cluster"]["ip4_to"].split(".")] ignore_list=[ip.strip(" ") for ip in CONF["cluster"]["ip4_ignore"]] nodes=list() print("----- Starting node scan (timeout={}s) -----".format(timeout)) for W in range(from_split[0],to_split[0]+1): for X in range(from_split[1],to_split[1]+1): for Y in range(from_split[2],to_split[2]+1): for Z in range(from_split[3],to_split[3]+1): ip="{}.{}.{}.{}".format(W,X,Y,Z) if ip in ignore_list: print("Skipping {}".format(ip)) continue print("Contacting {}...".format(ip),end='') try: subprocess.run(["ping", "-c", "1", "-W", str(timeout), ip],capture_output=True,check=True) nodes.append(ip) print("=> Found!!") except: print() with open(CONF.NODE_FILE, "w") as f: f.write(json.dumps(nodes,indent=4)) CONF["cache"]["last_scan"]=int(time.time()) CONF.save() def check(timeout): nodes_path=CONF.NODE_FILE nodes=None if os.path.exists(nodes_path): with open(nodes_path) as f: nodes=json.load(f) else: print("Please perform a scan before") exit(0) if not nodes == None: fail=False for ip in nodes: print("Contacting {}...".format(ip),end='') response = os.system("ping -c 1 -W " + str(timeout)+ " " + ip + " &>/dev/null") if response == 0: print("") else: fail=True print("=> Not responding!!") if not fail: print("Success: All nodes are reachable") else: print("Error: Some of your nodes are not reachable") def exec(command): user="root" if len(CONF["ssh"]["user"]) <= 0 else CONF["ssh"]["user"] key_path=CONF["ssh"]["key_path"] for ip in get_node_list(): print("----- Node {} -----".format(ip)) if len(key_path)>0: output=subprocess.check_output(["ssh","-o", "StrictHostKeyChecking=no", "-i", CONF["ssh"]["key_path"],"{}@{}".format(user,ip), " ".join(command)]) print(output.decode("utf-8")) else: output=subprocess.check_output(["ssh","-o", "StrictHostKeyChecking=no", "{}@{}".format(user,ip), " ".join(command)]) print(output.decode("utf-8"))