summaryrefslogtreecommitdiff
path: root/clusterman/utils.py
blob: b68e0a6771c5e8e8618b4111b9feadd525a79169 (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
44
45
46
import subprocess, os, json, re
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 and len(key_path) > 0:
        output=subprocess.check_output(["ssh","-o", "StrictHostKeyChecking=no", "-o", "PasswordAuthentication=no", "-i", CONF["ssh"]["key_path"],"{}@{}".format(user,host), command])
        return output.decode("utf-8")
    elif use_key:
        print("Configuration variable \"key_path\" is not set")
        sys.exit(1)
    else:
        output=subprocess.check_output(["ssh","-o", "StrictHostKeyChecking=no", "{}@{}".format(user,host), 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.keys()
    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