config.py 2.31 KiB
import json
import logging
import re
import jsonschema
CONFIG_SCHEMA = {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"alarms-db": {
"type": "object",
"properties": {
"hostname": {"type": "string"},
"dbname": {"type": "string"},
"username": {"type": "string"},
"password": {"type": "string"}
},
"required": ["hostname", "dbname", "username", "password"],
"additionalProperties": False
},
"oid_list.conf": {"type": "string"},
"routers_community.conf": {"type": "string"},
"ssh": {
"type": "object",
"properties": {
"private-key": {"type": "string"},
"known-hosts": {"type": "string"}
},
"required": ["private-key", "known-hosts"],
"additionalProperties": False
}
},
"required": ["alarms-db", "oid_list.conf", "routers_community.conf"],
"additionalProperties": False
}
def _load_oids(config_file):
"""
:param config_file: file-like object
:return:
"""
result = {}
for line in config_file:
m = re.match(r'^([^=]+)=(.*)\s*$', line)
if m:
result[m.group(1)] = m.group(2)
return result
def _load_routers(config_file):
"""
:param config_file: file-like object
:return:
"""
for line in config_file:
m = re.match(
r'^([a-z\d]+\.[a-z\d]{3,4}\.[a-z\d]{2}'
r'\.(geant|eumedconnect)\d*\.net)\s*=([^,]+)\s*,(.*)\s*$',
line)
if not m:
logging.warning("malformed config file line: '%s'" % line.strip())
continue
yield {
"hostname": m.group(1),
"community": m.group(3),
"address": m.group(4)
}
def load(f):
"""
loads, validates and returns configuration parameters
:param f: file-like object that produces the config file
:return:
"""
config = json.loads(f.read())
jsonschema.validate(config, CONFIG_SCHEMA)
with open(config["oid_list.conf"]) as f:
config["oids"] = _load_oids(f)
with open(config["routers_community.conf"]) as f:
config["routers"] = list(_load_routers(f))
return config