summaryrefslogtreecommitdiff
path: root/clusterman/utils.py
blob: 5fa66b28b2173c2098e01e570cb26fcf63f536ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import subprocess, os, json
from clusterman.config import CONF

def ssh_exec(host,command,use_key=True):
    user="root" if len(CONF["ssh"]["user"]) <= 0 else CONF["ssh"]["user"]
    key_path=CONF["ssh"]["key_path"]
    if use_key:
        output=subprocess.check_output(["ssh","-o", "StrictHostKeyChecking=no", "-o", "PasswordAuthentication=no", "-i", CONF["ssh"]["key_path"],"{}@{}".format(user,ip), command])
        return output.decode("utf-8")
    else:
        output=subprocess.check_output(["ssh","-o", "StrictHostKeyChecking=no", "{}@{}".format(user,ip), command])
        return output.decode("utf-8")

def ping_test(host, timeout=None):
    t=CONF["timeout"]
    if timeout is not None:
        t=timeout
    try:
        subprocess.run(["ping", "-c", "1", "-W", str(t), host],capture_output=True,check=True)
        return 0
    except:
        return 1

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