[NFVBENCH-7] Return errors when unknown options are passed
[nfvbench.git] / nfvbench / config.py
1 # Copyright 2016 Cisco Systems, Inc.  All rights reserved.
2 #
3 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
4 #    not use this file except in compliance with the License. You may obtain
5 #    a copy of the License at
6 #
7 #         http://www.apache.org/licenses/LICENSE-2.0
8 #
9 #    Unless required by applicable law or agreed to in writing, software
10 #    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 #    License for the specific language governing permissions and limitations
13 #    under the License.
14 #
15
16 from attrdict import AttrDict
17 import yaml
18
19
20 def config_load(file_name, from_cfg=None):
21     """Load a yaml file into a config dict, merge with from_cfg if not None
22     The config file content taking precedence in case of duplicate
23     """
24     try:
25         with open(file_name) as fileobj:
26             cfg = AttrDict(yaml.safe_load(fileobj))
27     except IOError:
28         raise Exception("Configuration file at '{}' was not found. Please use correct path "
29                         "and verify it is visible to container if you run nfvbench in container."
30                         .format(file_name))
31
32     if from_cfg:
33         cfg = from_cfg + cfg
34
35     return cfg
36
37
38 def config_loads(cfg_text, from_cfg=None):
39     """Same as config_load but load from a string
40     """
41     try:
42         cfg = AttrDict(yaml.load(cfg_text))
43     except TypeError:
44         # empty string
45         cfg = AttrDict()
46     if from_cfg:
47         return from_cfg + cfg
48     return cfg
49
50
51 def get_err_config(subset, superset):
52     result = {}
53     for k, v in subset.items():
54         if k not in superset:
55             result.update({k: v})
56         elif v is not None and superset[k] is not None:
57             if not isinstance(v, type(superset[k])):
58                 result.update({k: v})
59                 continue
60         if isinstance(v, dict):
61             res = get_err_config(v, superset[k])
62             if res:
63                 result.update({k: res})
64     if not result:
65         return None
66     return result
67
68
69 def test_config():
70     cfg = config_load('a1.yaml')
71     cfg = config_load('a2.yaml', cfg)
72     cfg = config_loads('color: 500', cfg)
73     config_loads('')
74     config_loads('#')