blob: 68bbd1345c3b2a3cbf264f5ec16ebc8ee60ec624 [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
8# it under the terms of the GNU Affero General Public License as
9# 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
15# GNU Affero General Public License for more details.
16#
17# You should have received a copy of the GNU Affero General Public License
18# 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
55
Neels Hofmeyr3531a192017-03-28 14:30:28 +020056from . import log, schema, util
57from .util import is_dict, is_list, Dir, get_tempdir
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +020058
Neels Hofmeyr3531a192017-03-28 14:30:28 +020059ENV_PREFIX = 'OSMO_GSM_TESTER_'
60ENV_CONF = os.getenv(ENV_PREFIX + 'CONF')
61
62DEFAULT_CONFIG_LOCATIONS = [
63 '.',
Your Name3c6673a2017-04-08 18:52:39 +020064 os.path.join(os.getenv('HOME'), '.config', 'osmo-gsm-tester'),
65 '/usr/local/etc/osmo-gsm-tester',
66 '/etc/osmo-gsm-tester'
Neels Hofmeyr3531a192017-03-28 14:30:28 +020067 ]
68
69PATHS_CONF = 'paths.conf'
Neels Hofmeyrd46ea132017-04-08 15:56:31 +020070DEFAULT_SUITES_CONF = 'default-suites.conf'
Neels Hofmeyr3531a192017-03-28 14:30:28 +020071PATH_STATE_DIR = 'state_dir'
72PATH_SUITES_DIR = 'suites_dir'
73PATH_SCENARIOS_DIR = 'scenarios_dir'
74PATHS_SCHEMA = {
75 PATH_STATE_DIR: schema.STR,
76 PATH_SUITES_DIR: schema.STR,
77 PATH_SCENARIOS_DIR: schema.STR,
78 }
79
80PATHS_TEMPDIR_STR = '$TEMPDIR'
81
82PATHS = None
83
Your Name3c6673a2017-04-08 18:52:39 +020084def _get_config_file(basename, fail_if_missing=True):
Neels Hofmeyr3531a192017-03-28 14:30:28 +020085 if ENV_CONF:
86 locations = [ ENV_CONF ]
87 else:
88 locations = DEFAULT_CONFIG_LOCATIONS
89
90 for l in locations:
91 p = os.path.join(l, basename)
92 if os.path.isfile(p):
Your Name3c6673a2017-04-08 18:52:39 +020093 return (p, l)
Neels Hofmeyr3531a192017-03-28 14:30:28 +020094 if not fail_if_missing:
Your Name3c6673a2017-04-08 18:52:39 +020095 return None, None
Neels Hofmeyr3531a192017-03-28 14:30:28 +020096 raise RuntimeError('configuration file not found: %r in %r' % (basename,
97 [os.path.abspath(p) for p in locations]))
98
Your Name3c6673a2017-04-08 18:52:39 +020099def get_config_file(basename, fail_if_missing=True):
100 path, found_in = _get_config_file(basename, fail_if_missing)
101 return path
102
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200103def read_config_file(basename, validation_schema=None, if_missing_return=False):
104 fail_if_missing = True
105 if if_missing_return is not False:
106 fail_if_missing = False
107 path = get_config_file(basename, fail_if_missing=fail_if_missing)
Your Name3c6673a2017-04-08 18:52:39 +0200108 if path is None:
109 return if_missing_return
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200110 return read(path, validation_schema=validation_schema, if_missing_return=if_missing_return)
111
112def get_configured_path(label, allow_unset=False):
113 global PATHS
114
115 env_name = ENV_PREFIX + label.upper()
116 env_path = os.getenv(env_name)
117 if env_path:
118 return env_path
119
120 if PATHS is None:
Your Name3c6673a2017-04-08 18:52:39 +0200121 paths_file, found_in = _get_config_file(PATHS_CONF)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200122 PATHS = read(paths_file, PATHS_SCHEMA)
Your Name3c6673a2017-04-08 18:52:39 +0200123 for key, path in PATHS.items():
124 if not path.startswith(os.pathsep):
125 PATHS[key] = os.path.join(found_in, path)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200126 p = PATHS.get(label)
127 if p is None and not allow_unset:
128 raise RuntimeError('missing configuration in %s: %r' % (PATHS_CONF, label))
129
130 if p.startswith(PATHS_TEMPDIR_STR):
131 p = os.path.join(get_tempdir(), p[len(PATHS_TEMPDIR_STR):])
132 return p
133
134def get_state_dir():
135 return Dir(get_configured_path(PATH_STATE_DIR))
136
137def get_suites_dir():
138 return Dir(get_configured_path(PATH_SUITES_DIR))
139
140def get_scenarios_dir():
141 return Dir(get_configured_path(PATH_SCENARIOS_DIR))
142
143def read(path, validation_schema=None, if_missing_return=False):
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200144 with log.Origin(path):
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200145 if not os.path.isfile(path) and if_missing_return is not False:
146 return if_missing_return
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200147 with open(path, 'r') as f:
148 config = yaml.safe_load(f)
149 config = _standardize(config)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200150 if validation_schema:
151 schema.validate(config, validation_schema)
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200152 return config
153
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200154def write(path, config):
155 with log.Origin(path):
156 with open(path, 'w') as f:
157 f.write(tostr(config))
158
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200159def tostr(config):
160 return _tostr(_standardize(config))
161
162def _tostr(config):
163 return yaml.dump(config, default_flow_style=False)
164
165def _standardize_item(item):
166 if isinstance(item, (tuple, list)):
167 return [_standardize_item(i) for i in item]
168 if isinstance(item, dict):
169 return dict([(key.lower(), _standardize_item(val)) for key,val in item.items()])
170 return str(item)
171
172def _standardize(config):
173 config = yaml.safe_load(_tostr(_standardize_item(config)))
174 return config
175
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200176def get_defaults(for_kind):
177 defaults = read_config_file('default.conf', if_missing_return={})
178 return defaults.get(for_kind, {})
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200179
Your Name44af3412017-04-13 03:11:59 +0200180class Scenario(log.Origin, dict):
181 def __init__(self, name, path):
182 self.set_name(name)
183 self.set_log_category(log.C_TST)
184 self.path = path
185
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200186def get_scenario(name, validation_schema=None):
187 scenarios_dir = get_scenarios_dir()
188 if not name.endswith('.conf'):
189 name = name + '.conf'
190 path = scenarios_dir.child(name)
191 if not os.path.isfile(path):
192 raise RuntimeError('No such scenario file: %r' % path)
Your Name44af3412017-04-13 03:11:59 +0200193 sc = Scenario(name, path)
194 sc.update(read(path, validation_schema=validation_schema))
195 return sc
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200196
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200197def add(dest, src):
198 if is_dict(dest):
199 if not is_dict(src):
200 raise ValueError('cannot add to dict a value of type: %r' % type(src))
201
202 for key, val in src.items():
203 dest_val = dest.get(key)
204 if dest_val is None:
205 dest[key] = val
206 else:
207 with log.Origin(key=key):
208 add(dest_val, val)
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200209 return
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200210 if is_list(dest):
211 if not is_list(src):
212 raise ValueError('cannot add to list a value of type: %r' % type(src))
213 dest.extend(src)
214 return
215 if dest == src:
216 return
217 raise ValueError('cannot add dicts, conflicting items (values %r and %r)'
218 % (dest, src))
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200219
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200220def combine(dest, src):
221 if is_dict(dest):
222 if not is_dict(src):
223 raise ValueError('cannot combine dict with a value of type: %r' % type(src))
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200224
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200225 for key, val in src.items():
226 dest_val = dest.get(key)
227 if dest_val is None:
228 dest[key] = val
229 else:
230 with log.Origin(key=key):
231 combine(dest_val, val)
232 return
233 if is_list(dest):
234 if not is_list(src):
235 raise ValueError('cannot combine list with a value of type: %r' % type(src))
236 for i in range(len(src)):
237 with log.Origin(idx=i):
238 combine(dest[i], src[i])
239 return
240 if dest == src:
241 return
242 raise ValueError('cannot combine dicts, conflicting items (values %r and %r)'
243 % (dest, src))
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200244
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200245def overlay(dest, src):
246 if is_dict(dest):
247 if not is_dict(src):
248 raise ValueError('cannot combine dict with a value of type: %r' % type(src))
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200249
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200250 for key, val in src.items():
251 dest_val = dest.get(key)
252 with log.Origin(key=key):
253 dest[key] = overlay(dest_val, val)
254 return dest
255 if is_list(dest):
256 if not is_list(src):
257 raise ValueError('cannot combine list with a value of type: %r' % type(src))
258 for i in range(len(src)):
259 with log.Origin(idx=i):
260 dest[i] = overlay(dest[i], src[i])
261 return dest
262 return src
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200263
264# vim: expandtab tabstop=4 shiftwidth=4