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": "", "user": "root" } } SCHEMA_CONFIG = { "type": "object", "properties": { "timeout": {"type": "number"}, "plugins": {"type": "object"}, "ssh": {"type": "object", "properties":{ "key_path": {"type": "string"}, "user": {"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", "cluster", "ssh" ] } 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()