Skip to content
Snippets Groups Projects
config.py 2.83 KiB
Newer Older
import json
import re

import jsonschema

CONFIG_SCHEMA = {
    "$schema": "http://json-schema.org/draft-07/schema#",

    "definitions": {
        "database_credentials": {
            "type": "object",
            "properties": {
                "hostname": {"type": "string"},
                "dbname": {"type": "string"},
                "username": {"type": "string"},
                "password": {"type": "string"}
            },
            "required": ["hostname", "dbname", "username", "password"],
            "additionalProperties": False

        }
    },

    "type": "object",
    "properties": {
        "ops-db": {"$ref": "#/definitions/database_credentials"},
        "oid_list.conf": {"type": "string"},
        "ssh": {
            "type": "object",
            "properties": {
                "username": {"type": "string"},
                "private-key": {"type": "string"},
                "known-hosts": {"type": "string"}
            },
            "required": ["private-key", "known-hosts"],
            "additionalProperties": False
        },
        "redis": {
            "type": "object",
            "properties": {
                "hostname": {"type": "string"},
                "port": {"type": "integer"}
            },
            "required": ["hostname", "port"],
            "additionalProperties": False
        "sentinel": {
            "type": "object",
            "properties": {
                "hostname": {"type": "string"},
                "port": {"type": "integer"},
                "name": {"type": "string"}
            },
            "required": ["hostname", "port"],
            "additionalProperties": False
        },
        "junosspace": {
            "api": {"type": "string"},
            "username": {"type": "string"},
            "password": {"type": "string"}
    "oneOf": [
        {
            "required": [
                "ops-db",
                "oid_list.conf",
                "ssh",
                "redis",
                "junosspace"]
        },
        {
            "required": [
                "ops-db",
                "oid_list.conf",
                "ssh",
                "sentinel",
                "junosspace"]
    "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(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)
    return config