blob: 0c820c375d268d560d20e5380ec78bc7d6e78cb5 [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 '.',
64 os.path.join(os.getenv('HOME'), '.config', 'osmo_gsm_tester'),
65 '/usr/local/etc/osmo_gsm_tester',
66 '/etc/osmo_gsm_tester'
67 ]
68
69PATHS_CONF = 'paths.conf'
70PATH_STATE_DIR = 'state_dir'
71PATH_SUITES_DIR = 'suites_dir'
72PATH_SCENARIOS_DIR = 'scenarios_dir'
73PATHS_SCHEMA = {
74 PATH_STATE_DIR: schema.STR,
75 PATH_SUITES_DIR: schema.STR,
76 PATH_SCENARIOS_DIR: schema.STR,
77 }
78
79PATHS_TEMPDIR_STR = '$TEMPDIR'
80
81PATHS = None
82
83def get_config_file(basename, fail_if_missing=True):
84 if ENV_CONF:
85 locations = [ ENV_CONF ]
86 else:
87 locations = DEFAULT_CONFIG_LOCATIONS
88
89 for l in locations:
90 p = os.path.join(l, basename)
91 if os.path.isfile(p):
92 return p
93 if not fail_if_missing:
94 return None
95 raise RuntimeError('configuration file not found: %r in %r' % (basename,
96 [os.path.abspath(p) for p in locations]))
97
98def read_config_file(basename, validation_schema=None, if_missing_return=False):
99 fail_if_missing = True
100 if if_missing_return is not False:
101 fail_if_missing = False
102 path = get_config_file(basename, fail_if_missing=fail_if_missing)
103 return read(path, validation_schema=validation_schema, if_missing_return=if_missing_return)
104
105def get_configured_path(label, allow_unset=False):
106 global PATHS
107
108 env_name = ENV_PREFIX + label.upper()
109 env_path = os.getenv(env_name)
110 if env_path:
111 return env_path
112
113 if PATHS is None:
114 paths_file = get_config_file(PATHS_CONF)
115 PATHS = read(paths_file, PATHS_SCHEMA)
116 p = PATHS.get(label)
117 if p is None and not allow_unset:
118 raise RuntimeError('missing configuration in %s: %r' % (PATHS_CONF, label))
119
120 if p.startswith(PATHS_TEMPDIR_STR):
121 p = os.path.join(get_tempdir(), p[len(PATHS_TEMPDIR_STR):])
122 return p
123
124def get_state_dir():
125 return Dir(get_configured_path(PATH_STATE_DIR))
126
127def get_suites_dir():
128 return Dir(get_configured_path(PATH_SUITES_DIR))
129
130def get_scenarios_dir():
131 return Dir(get_configured_path(PATH_SCENARIOS_DIR))
132
133def read(path, validation_schema=None, if_missing_return=False):
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200134 with log.Origin(path):
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200135 if not os.path.isfile(path) and if_missing_return is not False:
136 return if_missing_return
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200137 with open(path, 'r') as f:
138 config = yaml.safe_load(f)
139 config = _standardize(config)
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200140 if validation_schema:
141 schema.validate(config, validation_schema)
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200142 return config
143
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200144def write(path, config):
145 with log.Origin(path):
146 with open(path, 'w') as f:
147 f.write(tostr(config))
148
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200149def tostr(config):
150 return _tostr(_standardize(config))
151
152def _tostr(config):
153 return yaml.dump(config, default_flow_style=False)
154
155def _standardize_item(item):
156 if isinstance(item, (tuple, list)):
157 return [_standardize_item(i) for i in item]
158 if isinstance(item, dict):
159 return dict([(key.lower(), _standardize_item(val)) for key,val in item.items()])
160 return str(item)
161
162def _standardize(config):
163 config = yaml.safe_load(_tostr(_standardize_item(config)))
164 return config
165
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200166def get_defaults(for_kind):
167 defaults = read_config_file('default.conf', if_missing_return={})
168 return defaults.get(for_kind, {})
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200169
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200170def get_scenario(name, validation_schema=None):
171 scenarios_dir = get_scenarios_dir()
172 if not name.endswith('.conf'):
173 name = name + '.conf'
174 path = scenarios_dir.child(name)
175 if not os.path.isfile(path):
176 raise RuntimeError('No such scenario file: %r' % path)
177 return read(path, validation_schema=validation_schema)
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200178
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200179def add(dest, src):
180 if is_dict(dest):
181 if not is_dict(src):
182 raise ValueError('cannot add to dict a value of type: %r' % type(src))
183
184 for key, val in src.items():
185 dest_val = dest.get(key)
186 if dest_val is None:
187 dest[key] = val
188 else:
189 with log.Origin(key=key):
190 add(dest_val, val)
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200191 return
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200192 if is_list(dest):
193 if not is_list(src):
194 raise ValueError('cannot add to list a value of type: %r' % type(src))
195 dest.extend(src)
196 return
197 if dest == src:
198 return
199 raise ValueError('cannot add dicts, conflicting items (values %r and %r)'
200 % (dest, src))
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200201
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200202def combine(dest, src):
203 if is_dict(dest):
204 if not is_dict(src):
205 raise ValueError('cannot combine dict with a value of type: %r' % type(src))
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200206
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200207 for key, val in src.items():
208 dest_val = dest.get(key)
209 if dest_val is None:
210 dest[key] = val
211 else:
212 with log.Origin(key=key):
213 combine(dest_val, val)
214 return
215 if is_list(dest):
216 if not is_list(src):
217 raise ValueError('cannot combine list with a value of type: %r' % type(src))
218 for i in range(len(src)):
219 with log.Origin(idx=i):
220 combine(dest[i], src[i])
221 return
222 if dest == src:
223 return
224 raise ValueError('cannot combine dicts, conflicting items (values %r and %r)'
225 % (dest, src))
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200226
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200227def overlay(dest, src):
228 if is_dict(dest):
229 if not is_dict(src):
230 raise ValueError('cannot combine dict with a value of type: %r' % type(src))
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200231
Neels Hofmeyr3531a192017-03-28 14:30:28 +0200232 for key, val in src.items():
233 dest_val = dest.get(key)
234 with log.Origin(key=key):
235 dest[key] = overlay(dest_val, val)
236 return dest
237 if is_list(dest):
238 if not is_list(src):
239 raise ValueError('cannot combine list with a value of type: %r' % type(src))
240 for i in range(len(src)):
241 with log.Origin(idx=i):
242 dest[i] = overlay(dest[i], src[i])
243 return dest
244 return src
Neels Hofmeyrdae3d3c2017-03-28 12:16:58 +0200245
246# vim: expandtab tabstop=4 shiftwidth=4