blob: 4e6af9e02ef0c47cbb9f794447727b04e1b68470 [file] [log] [blame]
Matteo Scandolod2044a42017-08-07 16:08:28 -07001
2# Copyright 2017-present Open Networking Foundation
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16
Matteo Scandolo56879722017-05-17 21:39:54 -070017import os
18import sys
19import yaml
20import requests
21import default
22from pykwalify.core import Core as PyKwalify
23
Matteo Scandolo6bc017c2017-05-25 18:37:42 -070024DEFAULT_CONFIG_FILE = "/opt/xos/xos_config.yaml"
Matteo Scandolo1879ce72017-05-30 15:45:26 -070025DEFAULT_CONFIG_SCHEMA = 'xos-config-schema.yaml'
Matteo Scandolo56879722017-05-17 21:39:54 -070026INITIALIZED = False
Matteo Scandoloe0fc6852017-06-07 16:01:54 -070027CONFIG_FILE = None
Matteo Scandolo56879722017-05-17 21:39:54 -070028CONFIG = {}
29
Zack Williams37845ca2017-07-18 15:39:20 -070030GLOBAL_CONFIG_FILE = DEFAULT_CONFIG_FILE
31GLOBAL_CONFIG_SCHEMA = DEFAULT_CONFIG_SCHEMA
32GLOBAL_CONFIG = {}
33
Matteo Scandolo56879722017-05-17 21:39:54 -070034class Config:
35 """
36 XOS Configuration APIs
37 """
38
39 @staticmethod
Matteo Scandolo1879ce72017-05-30 15:45:26 -070040 def init(config_file=DEFAULT_CONFIG_FILE, config_schema=DEFAULT_CONFIG_SCHEMA):
41
42 # make schema relative to this directory
43 # TODO give the possibility to specify an absolute path
44 config_schema = Config.get_abs_path(config_schema)
45
Matteo Scandolo56879722017-05-17 21:39:54 -070046 global INITIALIZED
47 global CONFIG
Matteo Scandoloe0fc6852017-06-07 16:01:54 -070048 global CONFIG_FILE
Zack Williams37845ca2017-07-18 15:39:20 -070049
50 global GLOBAL_CONFIG
51 global GLOBAL_CONFIG_FILE
52 global GLOBAL_CONFIG_SCHEMA
53
54 # Use same schema for both provided and global config by default
55 GLOBAL_CONFIG_SCHEMA = config_schema
56
Matteo Scandolo56879722017-05-17 21:39:54 -070057 # the config module can be initialized only one
58 if INITIALIZED:
59 raise Exception('[XOS-Config] Module already initialized')
60 INITIALIZED = True
61
Matteo Scandolo1879ce72017-05-30 15:45:26 -070062 # if XOS_CONFIG_FILE is defined override the config_file
63 # FIXME shouldn't this stay in whatever module call this one? and then just pass the file to the init method
64 if os.environ.get('XOS_CONFIG_FILE'):
65 config_file = os.environ['XOS_CONFIG_FILE']
66
67 # if XOS_CONFIG_SCHEMA is defined override the config_schema
68 # FIXME shouldn't this stay in whatever module call this one? and then just pass the file to the init method
69 if os.environ.get('XOS_CONFIG_SCHEMA'):
70 config_schema = Config.get_abs_path(os.environ['XOS_CONFIG_SCHEMA'])
Matteo Scandolo56879722017-05-17 21:39:54 -070071
Zack Williams37845ca2017-07-18 15:39:20 -070072 # allow GLOBAL_CONFIG_* to be overridden by env vars
73 if os.environ.get('XOS_GLOBAL_CONFIG_FILE'):
74 GLOBAL_CONFIG_FILE = os.environ['XOS_GLOBAL_CONFIG_FILE']
75 if os.environ.get('XOS_GLOBAL_CONFIG_SCHEMA'):
76 GLOBAL_CONFIG_SCHEMA = Config.get_abs_path(os.environ['XOS_GLOBAL_CONFIG_SCHEMA'])
77
Matteo Scandolo56879722017-05-17 21:39:54 -070078 # if a -C parameter is set in the cli override the config_file
79 # FIXME shouldn't this stay in whatever module call this one? and then just pass the file to the init method
80 if Config.get_cli_param(sys.argv):
Matteo Scandolo1879ce72017-05-30 15:45:26 -070081 config_schema = Config.get_cli_param(sys.argv)
Matteo Scandolo56879722017-05-17 21:39:54 -070082
Matteo Scandoloe0fc6852017-06-07 16:01:54 -070083
84 CONFIG_FILE = config_file
Matteo Scandolo1879ce72017-05-30 15:45:26 -070085 CONFIG = Config.read_config(config_file, config_schema)
Matteo Scandolo56879722017-05-17 21:39:54 -070086
Zack Williams37845ca2017-07-18 15:39:20 -070087 # Load global schema
88 GLOBAL_CONFIG = Config.read_config(GLOBAL_CONFIG_FILE, GLOBAL_CONFIG_SCHEMA, True)
89
Matteo Scandolo56879722017-05-17 21:39:54 -070090 @staticmethod
Matteo Scandoloe0fc6852017-06-07 16:01:54 -070091 def get_config_file():
92 return CONFIG_FILE
93
94 @staticmethod
Matteo Scandolo56879722017-05-17 21:39:54 -070095 def clear():
96 global INITIALIZED
97 INITIALIZED = False
98
99 @staticmethod
Matteo Scandolo1879ce72017-05-30 15:45:26 -0700100 def get_abs_path(path):
101 if os.path.isabs(path):
102 return path
103 return os.path.dirname(os.path.realpath(__file__)) + '/' + path
104
105 @staticmethod
106 def validate_config_format(config_file, config_schema):
107 schema = os.path.abspath(config_schema)
Matteo Scandolo56879722017-05-17 21:39:54 -0700108 c = PyKwalify(source_file=config_file, schema_files=[schema])
109 c.validate(raise_exception=True)
110
111 @staticmethod
112 def get_cli_param(args):
113 last = None
114 for arg in args:
115 if last == '-C':
116 return arg
117 last = arg
118
119 @staticmethod
Zack Williams37845ca2017-07-18 15:39:20 -0700120 def read_config(config_file, config_schema, ignore_if_not_found=False):
Matteo Scandolo56879722017-05-17 21:39:54 -0700121 """
122 Read the configuration file and return a dictionary
123 :param config_file: string
124 :return: dict
125 """
Zack Williams37845ca2017-07-18 15:39:20 -0700126
127 if(not os.path.exists(config_file) and ignore_if_not_found):
128 return {}
129
Matteo Scandolo56879722017-05-17 21:39:54 -0700130 if not os.path.exists(config_file):
131 raise Exception('[XOS-Config] Config file not found at: %s' % config_file)
132
Matteo Scandolo1879ce72017-05-30 15:45:26 -0700133 if not os.path.exists(config_schema):
134 raise Exception('[XOS-Config] Config schema not found at: %s' % config_schema)
135
Matteo Scandolo56879722017-05-17 21:39:54 -0700136 try:
Matteo Scandolo1879ce72017-05-30 15:45:26 -0700137 Config.validate_config_format(config_file, config_schema)
Matteo Scandolo56879722017-05-17 21:39:54 -0700138 except Exception, e:
Scott Baker1f6a32c2017-11-22 11:24:01 -0800139 try:
140 error_msg = e.msg
141 except AttributeError:
142 error_msg = str(e)
143 raise Exception('[XOS-Config] The config format is wrong: %s' % error_msg)
Matteo Scandolo56879722017-05-17 21:39:54 -0700144
145 with open(config_file, 'r') as stream:
146 return yaml.safe_load(stream)
147
148 @staticmethod
149 def get(query):
150 """
151 Read a parameter from the config
152 :param query: a dot separated selector for configuration options (eg: database.username)
153 :return: the requested parameter in any format the parameter is specified
154 """
155 global INITIALIZED
156 global CONFIG
Zack Williams37845ca2017-07-18 15:39:20 -0700157 global GLOBAL_CONFIG
Matteo Scandolo56879722017-05-17 21:39:54 -0700158
159 if not INITIALIZED:
160 raise Exception('[XOS-Config] Module has not been initialized')
161
162 val = Config.get_param(query, CONFIG)
163 if not val:
Zack Williams37845ca2017-07-18 15:39:20 -0700164 val = Config.get_param(query, GLOBAL_CONFIG)
165 if not val:
Matteo Scandolo56879722017-05-17 21:39:54 -0700166 val = Config.get_param(query, default.DEFAULT_VALUES)
167 if not val:
Matteo Scandolo1879ce72017-05-30 15:45:26 -0700168 # TODO if no val return none
169 # raise Exception('[XOS-Config] Config does not have a value (or a default) parameter %s' % query)
170 return None
Matteo Scandolo56879722017-05-17 21:39:54 -0700171 return val
172
173 @staticmethod
174 def get_param(query, config):
175 """
176 Search for a parameter in config's first level, other call get_nested_param
177 :param query: a dot separated selector for configuration options (eg: database.username)
178 :param config: the config source to read from (can be the config file or the defaults)
179 :return: the requested parameter in any format the parameter is specified
180 """
181 keys = query.split('.')
182 if len(keys) == 1:
183 key = keys[0]
184 if not config.has_key(key):
185 return None
186 return config[key]
187 else:
188 return Config.get_nested_param(keys, config)
189
190 @staticmethod
191 def get_nested_param(keys, config):
192 """
Zack Williams37845ca2017-07-18 15:39:20 -0700193
Matteo Scandolo56879722017-05-17 21:39:54 -0700194 :param keys: a list of descending selector
195 :param config: the config source to read from (can be the config file or the defaults)
196 :return: the requested parameter in any format the parameter is specified
197 """
198 param = config
199 for k in keys:
200 if not param.has_key(k):
201 return None
202 param = param[k]
203 return param
204
Matteo Scandolo56879722017-05-17 21:39:54 -0700205if __name__ == '__main__':
Zack Williams37845ca2017-07-18 15:39:20 -0700206 Config.init()