40414b88bc13e6672ca8cad65ceff441dbcad36b
[functest.git] / functest / utils / config.py
1 #!/usr/bin/env python
2
3 # pylint: disable=missing-docstring
4
5 import pkg_resources
6 import yaml
7
8 import six
9
10 from functest.utils import env
11
12
13 class Config():
14     def __init__(self):
15         try:
16             with open(pkg_resources.resource_filename(
17                     'functest', 'ci/config_functest.yaml'),
18                     encoding='utf-8') as yfile:
19                 self.functest_yaml = yaml.safe_load(yfile)
20         except Exception as error:
21             raise Exception(
22                 f'Parse config failed: {str(error)}') from error
23
24     @staticmethod
25     def _merge_dicts(dict1, dict2):
26         for k in set(dict1.keys()).union(dict2.keys()):
27             if k in dict1 and k in dict2:
28                 if isinstance(dict1[k], dict) and isinstance(dict2[k], dict):
29                     yield (k, dict(Config._merge_dicts(dict1[k], dict2[k])))
30                 else:
31                     yield (k, dict2[k])
32             elif k in dict1:
33                 yield (k, dict1[k])
34             else:
35                 yield (k, dict2[k])
36
37     def patch_file(self, patch_file_path):
38         with open(patch_file_path, encoding='utf-8') as yfile:
39             patch_file = yaml.safe_load(yfile)
40
41         for key in patch_file:
42             if key in env.get('DEPLOY_SCENARIO'):
43                 self.functest_yaml = dict(Config._merge_dicts(
44                     self.functest_yaml, patch_file[key]))
45
46     def _parse(self, attr_now, left_parametes):
47         for param_n, param_v in six.iteritems(left_parametes):
48             attr_further = self._get_attr_further(attr_now, param_n)
49             if attr_further:
50                 setattr(self, attr_further, param_v)
51             if isinstance(param_v, dict):
52                 self._parse(attr_further, param_v)
53
54     @staticmethod
55     def _get_attr_further(attr_now, next):  # pylint: disable=redefined-builtin
56         return attr_now if next == 'general' else (
57             f'{attr_now}_{next}' if attr_now else next)
58
59     def fill(self):
60         try:
61             self._parse(None, self.functest_yaml)
62         except Exception as error:
63             raise Exception(
64                 f'Parse config failed: {str(error)}') from error
65
66
67 CONF = Config()
68 CONF.patch_file(pkg_resources.resource_filename(
69     'functest', 'ci/config_patch.yaml'))
70 if env.get("POD_ARCH") in ['aarch64']:
71     CONF.patch_file(pkg_resources.resource_filename(
72         'functest', 'ci/config_aarch64_patch.yaml'))
73 CONF.fill()