summaryrefslogtreecommitdiff
path: root/clusterman/config.py
blob: c39c8c2ca17e5cebd94720ef39a88563afef4335 (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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
from pathlib import Path
import os, json, sys
from jsonschema import validate


class Config:
    CONF_DIR=os.path.join(os.environ['HOME'],".clusterman/")
    CONF_FILE=os.path.join(CONF_DIR,"clusterman.json")
    CACHE_FILE=os.path.join(CONF_DIR,"cache.json")
    NODE_FILE=os.path.join(CONF_DIR,"nodeslist.json")
    DEFAULT_CONFIG = {
        "cluster": {
            "ip4_from": "10.128.0.133",
            "ip4_to": "10.128.0.140",
            "ip4_ignore": ["10.0.0.5", "10.0.0.1"],
            "groups": {
                "all": "*"
            }
        },
        "plugins": { "ls": "ls -al" },
        "timeout": 0.5,
        "ssh_key_path": ""
    }
    SCHEMA_CONFIG = {
        "type": "object",
        "properties": {
            "timeout": {"type": "number"},
            "plugins": {"type": "object"},
            "ssh_key_path": {"type": "string"},
            "cluster": {"type": "object", "properties":{
                "ip4_from": {"type": "string"},
                "ip4_to": {"type": "string"},
                "ip4_ignore": {"type": "array", "items":{"type": "string"}},
                "groups": {"type": "object"}
            }}
        },
        "required":[
            "timeout",
            "plugins",
            "ssh_key_path",
            "cluster"
        ]
    }
    
    def __init__(self):
        Path(self.CONF_DIR).mkdir(parents=True, exist_ok=True)
        self.config=self.DEFAULT_CONFIG
        self.cache=dict()
        self.load()

    def load(self):
        if os.path.exists(self.CONF_FILE):
            with open(self.CONF_FILE) as f:
                self.config=json.load(f)
                try:
                    validate(instance=self.config, schema=self.SCHEMA_CONFIG)
                except:
                    print("Invalid configuration file")
                    sys.exit(1)
        else:
            self.save()
            
        if os.path.exists(self.CACHE_FILE):
            with open(self.CACHE_FILE) as f:
                self.cache=json.load(f)
        else:
            self.save()
                
    def save(self):
        with open(self.CONF_FILE, "w") as f:
            f.write(json.dumps(self.config,indent=4, sort_keys=True))

        with open(self.CACHE_FILE, "w") as f:
            f.write(json.dumps(self.cache,indent=4, sort_keys=True))

    def __getitem__(self, key):
        if key=="cache":
            return self.cache;
        return self.config[key]

    def __setitem__(self, key, value):
        self.config[key]=value
    

CONF=Config()