blob: 71e0009066fd9c7292606feec837d57a04714495 [file] [log] [blame]
Neels Hofmeyr3531a192017-03-28 14:30:28 +02001# osmo_gsm_tester: read and manage config files and global config
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +02002#
3# Copyright (C) 2016-2017 by sysmocom - s.f.m.c. GmbH
4#
5# Author: Neels Hofmeyr <neels@hofmeyr.de>
6#
7# This program is free software: you can redistribute it and/or modify
Harald Welte27205342017-06-03 09:51:45 +02008# it under the terms of the GNU General Public License as
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +02009# published by the Free Software Foundation, either version 3 of the
10# License, or (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Harald Welte27205342017-06-03 09:51:45 +020015# GNU General Public License for more details.
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +020016#
Harald Welte27205342017-06-03 09:51:45 +020017# You should have received a copy of the GNU General Public License
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +020018# along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20# discussion for choice of config file format:
21#
22# Python syntax is insane, because it allows the config file to run arbitrary
23# python commands.
24#
25# INI file format is nice and simple, but it doesn't allow having the same
26# section numerous times (e.g. to define several modems or BTS models) and does
27# not support nesting.
28#
29# JSON has too much braces and quotes to be easy to type
30#
Neels Hofmeyr3531a192017-03-28 14:30:28 +020031# YAML formatting is lean, but:
32# - too powerful. The normal load() allows arbitrary code execution. There is
33# safe_load().
34# - allows several alternative ways of formatting, better to have just one
35# authoritative style.
36# - tries to detect types. It would be better to receive every setting as
37# simple string rather than e.g. an IMSI as an integer.
38# - e.g. an IMSI starting with a zero is interpreted as octal value, resulting
39# in super confusing error messages if the user merely forgets to quote it.
40# - does not tell me which line a config item came from, so no detailed error
41# message is possible.
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +020042#
Neels Hofmeyr3531a192017-03-28 14:30:28 +020043# The Python ConfigParserShootout page has numerous contestants, but many of
44# those seem to be not widely used / standardized or even tested.
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +020045# https://wiki.python.org/moin/ConfigParserShootout
46#
47# The optimum would be a stripped down YAML format.
48# In the lack of that, we shall go with yaml.load_safe() + a round trip
49# (feeding back to itself), converting keys to lowercase and values to string.
Neels Hofmeyr3531a192017-03-28 14:30:28 +020050# There is no solution for octal interpretations nor config file source lines
51# unless, apparently, we implement our own config parser.
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +020052
53import yaml
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +020054import os
Pau Espin Pedrol802dfe52017-09-12 13:43:40 +020055import copy
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +020056
Pau Espin Pedrol6ed30122020-02-27 17:03:15 +010057from . import log, schema, util, template
Neels Hofmeyr3531a192017-03-28 14:30:28 +020058from .util import is_dict, is_list, Dir, get_tempdir
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +020059
Neels Hofmeyr3531a192017-03-28 14:30:28 +020060ENV_PREFIX = 'OSMO_GSM_TESTER_'
61ENV_CONF = os.getenv(ENV_PREFIX + 'CONF')
62
Neels Hofmeyrf15eaf92017-06-05 18:03:53 +020063override_conf = None
64
Neels Hofmeyr3531a192017-03-28 14:30:28 +020065DEFAULT_CONFIG_LOCATIONS = [
66 '.',
Your Name3c6673a2017-04-08 18:52:39 +020067 os.path.join(os.getenv('HOME'), '.config', 'osmo-gsm-tester'),
68 '/usr/local/etc/osmo-gsm-tester',
69 '/etc/osmo-gsm-tester'
Neels Hofmeyr3531a192017-03-28 14:30:28 +020070 ]
71
72PATHS_CONF = 'paths.conf'
Neels Hofmeyrd46ea132017-04-08 15:56:31 +020073DEFAULT_SUITES_CONF = 'default-suites.conf'
Neels Hofmeyr3531a192017-03-28 14:30:28 +020074PATH_STATE_DIR = 'state_dir'
75PATH_SUITES_DIR = 'suites_dir'
76PATH_SCENARIOS_DIR = 'scenarios_dir'
77PATHS_SCHEMA = {
78 PATH_STATE_DIR: schema.STR,
79 PATH_SUITES_DIR: schema.STR,
80 PATH_SCENARIOS_DIR: schema.STR,
81 }
82
83PATHS_TEMPDIR_STR = '$TEMPDIR'
84
85PATHS = None
86
Your Name3c6673a2017-04-08 18:52:39 +020087def _get_config_file(basename, fail_if_missing=True):
Neels Hofmeyrf15eaf92017-06-05 18:03:53 +020088 if override_conf:
89 locations = [ override_conf ]
90 elif ENV_CONF:
Neels Hofmeyr3531a192017-03-28 14:30:28 +020091 locations = [ ENV_CONF ]
92 else:
93 locations = DEFAULT_CONFIG_LOCATIONS
94
95 for l in locations:
Neels Hofmeyref9ed2d2017-05-04 16:39:29 +020096 real_l = os.path.realpath(l)
97 p = os.path.realpath(os.path.join(real_l, basename))
Neels Hofmeyr3531a192017-03-28 14:30:28 +020098 if os.path.isfile(p):
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +020099 log.dbg('Found config file', basename, 'as', p, 'in', l, 'which is', real_l, _category=log.C_CNF)
Neels Hofmeyref9ed2d2017-05-04 16:39:29 +0200100 return (p, real_l)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200101 if not fail_if_missing:
Your Name3c6673a2017-04-08 18:52:39 +0200102 return None, None
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200103 raise RuntimeError('configuration file not found: %r in %r' % (basename,
104 [os.path.abspath(p) for p in locations]))
105
Your Name3c6673a2017-04-08 18:52:39 +0200106def get_config_file(basename, fail_if_missing=True):
107 path, found_in = _get_config_file(basename, fail_if_missing)
108 return path
109
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200110def read_config_file(basename, validation_schema=None, if_missing_return=False):
111 fail_if_missing = True
112 if if_missing_return is not False:
113 fail_if_missing = False
114 path = get_config_file(basename, fail_if_missing=fail_if_missing)
Your Name3c6673a2017-04-08 18:52:39 +0200115 if path is None:
116 return if_missing_return
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200117 return read(path, validation_schema=validation_schema, if_missing_return=if_missing_return)
118
119def get_configured_path(label, allow_unset=False):
120 global PATHS
121
122 env_name = ENV_PREFIX + label.upper()
123 env_path = os.getenv(env_name)
124 if env_path:
Neels Hofmeyref9ed2d2017-05-04 16:39:29 +0200125 real_env_path = os.path.realpath(env_path)
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200126 log.dbg('Found path', label, 'as', env_path, 'in', '$' + env_name, 'which is', real_env_path, _category=log.C_CNF)
Neels Hofmeyref9ed2d2017-05-04 16:39:29 +0200127 return real_env_path
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200128
129 if PATHS is None:
Your Name3c6673a2017-04-08 18:52:39 +0200130 paths_file, found_in = _get_config_file(PATHS_CONF)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200131 PATHS = read(paths_file, PATHS_SCHEMA)
Neels Hofmeyref9ed2d2017-05-04 16:39:29 +0200132 # sorted for deterministic regression test results
133 for key, path in sorted(PATHS.items()):
Your Name3c6673a2017-04-08 18:52:39 +0200134 if not path.startswith(os.pathsep):
Neels Hofmeyref9ed2d2017-05-04 16:39:29 +0200135 PATHS[key] = os.path.realpath(os.path.join(found_in, path))
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200136 log.dbg(paths_file + ': relative path', path, 'is', PATHS[key], _category=log.C_CNF)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200137 p = PATHS.get(label)
138 if p is None and not allow_unset:
139 raise RuntimeError('missing configuration in %s: %r' % (PATHS_CONF, label))
140
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200141 log.dbg('Found path', label, 'as', p, _category=log.C_CNF)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200142 if p.startswith(PATHS_TEMPDIR_STR):
143 p = os.path.join(get_tempdir(), p[len(PATHS_TEMPDIR_STR):])
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200144 log.dbg('Path', label, 'contained', PATHS_TEMPDIR_STR, 'and becomes', p, _category=log.C_CNF)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200145 return p
146
147def get_state_dir():
148 return Dir(get_configured_path(PATH_STATE_DIR))
149
150def get_suites_dir():
151 return Dir(get_configured_path(PATH_SUITES_DIR))
152
153def get_scenarios_dir():
154 return Dir(get_configured_path(PATH_SCENARIOS_DIR))
155
156def read(path, validation_schema=None, if_missing_return=False):
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200157 log.ctx(path)
158 if not os.path.isfile(path) and if_missing_return is not False:
159 return if_missing_return
160 with open(path, 'r') as f:
161 config = yaml.safe_load(f)
162 config = _standardize(config)
163 if validation_schema:
164 schema.validate(config, validation_schema)
165 return config
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200166
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200167def write(path, config):
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200168 log.ctx(path)
169 with open(path, 'w') as f:
170 f.write(tostr(config))
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200171
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200172def tostr(config):
173 return _tostr(_standardize(config))
174
175def _tostr(config):
176 return yaml.dump(config, default_flow_style=False)
177
178def _standardize_item(item):
Pau Espin Pedrol7691f2d2020-02-18 12:12:01 +0100179 if item is None:
180 return None
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200181 if isinstance(item, (tuple, list)):
182 return [_standardize_item(i) for i in item]
183 if isinstance(item, dict):
184 return dict([(key.lower(), _standardize_item(val)) for key,val in item.items()])
185 return str(item)
186
187def _standardize(config):
188 config = yaml.safe_load(_tostr(_standardize_item(config)))
189 return config
190
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200191def get_defaults(for_kind):
Neels Hofmeyr05837ad2017-04-14 04:18:06 +0200192 defaults = read_config_file('defaults.conf', if_missing_return={})
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200193 return defaults.get(for_kind, {})
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200194
Your Name44af3412017-04-13 03:11:59 +0200195class Scenario(log.Origin, dict):
Pau Espin Pedrol6ed30122020-02-27 17:03:15 +0100196 def __init__(self, name, path, param_list=[]):
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200197 super().__init__(log.C_TST, name)
Your Name44af3412017-04-13 03:11:59 +0200198 self.path = path
Pau Espin Pedrol6ed30122020-02-27 17:03:15 +0100199 self.param_list = param_list
200
201 def read_from_file(self, validation_schema):
202 with open(self.path, 'r') as f:
203 config_str = f.read()
204 if len(self.param_list) != 0:
205 param_dict = {}
206 i = 1
207 for param in self.param_list:
208 param_dict['param' + str(i)] = param
209 i += 1
210 self.dbg(param_dict=param_dict)
211 config_str = template.render_strbuf_inline(config_str, param_dict)
212 config = yaml.safe_load(config_str)
213 config = _standardize(config)
214 if validation_schema:
215 schema.validate(config, validation_schema)
216 self.update(config)
Your Name44af3412017-04-13 03:11:59 +0200217
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200218def get_scenario(name, validation_schema=None):
219 scenarios_dir = get_scenarios_dir()
220 if not name.endswith('.conf'):
221 name = name + '.conf'
Pau Espin Pedrol6ed30122020-02-27 17:03:15 +0100222 is_parametrized_file = '@' in name
223 param_list = []
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200224 path = scenarios_dir.child(name)
Pau Espin Pedrol6ed30122020-02-27 17:03:15 +0100225 if not is_parametrized_file:
226 if not os.path.isfile(path):
227 raise RuntimeError('No such scenario file: %r' % path)
228 else: # parametrized scenario:
229 # Allow first matching complete matching names (eg: scenario@param1,param2.conf),
230 # this allows setting specific content in different files for specific values.
231 if not os.path.isfile(path):
232 # get "scenario@.conf" from "scenario@param1,param2.conf":
233 prefix_name = name[:name.index("@")+1] + '.conf'
234 path = scenarios_dir.child(prefix_name)
235 if not os.path.isfile(path):
236 raise RuntimeError('No such scenario file: %r (nor %s)' % (path, name))
237 # At this point, we have existing file path. Let's now scrap the parameter(s):
238 # get param1,param2 str from scenario@param1,param2.conf
239 param_list_str = name.split('@', 1)[1][:-len('.conf')]
240 param_list = param_list_str.split(',')
241 sc = Scenario(name, path, param_list)
242 sc.read_from_file(validation_schema)
Your Name44af3412017-04-13 03:11:59 +0200243 return sc
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200244
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200245def add(dest, src):
246 if is_dict(dest):
247 if not is_dict(src):
248 raise ValueError('cannot add to dict a value of type: %r' % type(src))
249
250 for key, val in src.items():
251 dest_val = dest.get(key)
252 if dest_val is None:
253 dest[key] = val
254 else:
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200255 log.ctx(key=key)
256 add(dest_val, val)
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200257 return
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200258 if is_list(dest):
259 if not is_list(src):
260 raise ValueError('cannot add to list a value of type: %r' % type(src))
261 dest.extend(src)
262 return
263 if dest == src:
264 return
265 raise ValueError('cannot add dicts, conflicting items (values %r and %r)'
266 % (dest, src))
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200267
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200268def combine(dest, src):
269 if is_dict(dest):
270 if not is_dict(src):
271 raise ValueError('cannot combine dict with a value of type: %r' % type(src))
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200272
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200273 for key, val in src.items():
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200274 log.ctx(key=key)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200275 dest_val = dest.get(key)
276 if dest_val is None:
277 dest[key] = val
278 else:
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200279 combine(dest_val, val)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200280 return
281 if is_list(dest):
282 if not is_list(src):
283 raise ValueError('cannot combine list with a value of type: %r' % type(src))
Pau Espin Pedrol43737da2017-08-28 14:04:07 +0200284 # Validate that all elements in both lists are of the same type:
285 t = util.list_validate_same_elem_type(src + dest)
286 if t is None:
287 return # both lists are empty, return
288 # For lists of complex objects, we expect them to be sorted lists:
289 if t in (dict, list, tuple):
290 for i in range(len(dest)):
291 log.ctx(idx=i)
292 src_it = src[i] if i < len(src) else util.empty_instance_type(t)
293 combine(dest[i], src_it)
294 for i in range(len(dest), len(src)):
295 log.ctx(idx=i)
296 dest.append(src[i])
297 else: # for lists of basic elements, we handle them as unsorted sets:
298 for elem in src:
299 if elem not in dest:
300 dest.append(elem)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200301 return
302 if dest == src:
303 return
304 raise ValueError('cannot combine dicts, conflicting items (values %r and %r)'
305 % (dest, src))
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200306
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200307def overlay(dest, src):
308 if is_dict(dest):
309 if not is_dict(src):
310 raise ValueError('cannot combine dict with a value of type: %r' % type(src))
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200311
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200312 for key, val in src.items():
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200313 log.ctx(key=key)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200314 dest_val = dest.get(key)
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200315 dest[key] = overlay(dest_val, val)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200316 return dest
317 if is_list(dest):
318 if not is_list(src):
319 raise ValueError('cannot combine list with a value of type: %r' % type(src))
Pau Espin Pedrol27532042017-09-15 15:31:52 +0200320 copy_len = min(len(src),len(dest))
321 for i in range(copy_len):
Pau Espin Pedrolebced952017-08-28 17:21:34 +0200322 log.ctx(idx=i)
Neels Hofmeyr1a7a3f02017-06-10 01:18:27 +0200323 dest[i] = overlay(dest[i], src[i])
Pau Espin Pedrol27532042017-09-15 15:31:52 +0200324 for i in range(copy_len, len(src)):
325 dest.append(src[i])
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200326 return dest
327 return src
Pau Espin Pedrol802dfe52017-09-12 13:43:40 +0200328
329def replicate_times(d):
Pau Espin Pedrol0b302792017-09-10 16:33:10 +0200330 '''
331 replicate items that have a "times" > 1
332
333 'd' is a dict matching WANT_SCHEMA, which is the same as
334 the RESOURCES_SCHEMA, except each entity that can be reserved has a 'times'
335 field added, to indicate how many of those should be reserved.
336 '''
Pau Espin Pedrol802dfe52017-09-12 13:43:40 +0200337 d = copy.deepcopy(d)
338 for key, item_list in d.items():
Pau Espin Pedrol26050342017-09-12 15:02:25 +0200339 idx = 0
340 while idx < len(item_list):
341 item = item_list[idx]
342 times = int(item.pop('times', 1))
343 for j in range(1, times):
344 item_list.insert(idx + j, copy.deepcopy(item))
345 idx += times
Pau Espin Pedrol802dfe52017-09-12 13:43:40 +0200346 return d
347
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200348# vim: expandtab tabstop=4 shiftwidth=4