Initial commit
[ta/config-manager.git] / cmframework / src / cmframework / utils / cmuserconfig.py
1 # Copyright 2019 Nokia
2
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain 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,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 from __future__ import print_function
15 import json
16 import yaml
17
18 from cmframework.apis import cmerror
19 from cmframework.utils.cmpluginloader import CMPluginLoader
20 from cmdatahandlers.api import configmanager
21
22
23 class UserConfig(object):
24
25     def __init__(self, user_config_file, plugin_path):
26         self.user_config_file = user_config_file
27         self.removed_values = ['version']
28         self.pluginloader = UserConfigPluginLoader(plugin_path)
29
30     def get_flat_config(self):
31         try:
32             result = {}
33             stream = file(self.user_config_file, 'r')
34             tmp = yaml.load(stream)
35             userconfig = {}
36             for key in tmp.keys():
37                 userconfig['cloud.' + key] = tmp[key]
38
39             confman = configmanager.ConfigManager(userconfig)
40             self.pluginloader.load()
41             plugins = self.pluginloader.get_plugin_instances()
42             for _, plugin in plugins.iteritems():
43                 plugin.handle(confman)
44
45             # change the multi-level deictionary to one level dictionary mapping
46             # the key to a josn string representation of the value.
47             for key, value in userconfig.iteritems():
48                 result[key] = json.dumps(value)
49
50             return result
51         except Exception as exp:
52             raise cmerror.CMError("Failed to load user config %(userconfig)s: %(failure)s" %
53                                   {'userconfig': self.user_config_file,
54                                    'failure': str(exp)})
55
56
57 class UserConfigPluginLoader(CMPluginLoader):
58     def __init__(self, plugin_location, plugin_filter=None):
59         super(UserConfigPluginLoader, self).__init__(plugin_location, plugin_filter)
60
61     def build_filter_dict(self):
62         pass
63
64     def get_plugin_instances(self):
65         plugs = {}
66         for plugin, module in self.loaded_plugin.iteritems():
67             class_name = getattr(module, plugin)
68             instance = class_name()
69             plugs[plugin] = instance
70         return plugs
71
72
73 def main():
74     import argparse
75     import sys
76     import traceback
77
78     parser = argparse.ArgumentParser(description='Test userconfig handler', prog=sys.argv[0])
79
80     parser.add_argument('--config',
81                         required=True,
82                         dest='config',
83                         metavar='CONFIG',
84                         help='The user config yaml file',
85                         type=str,
86                         action='store')
87
88     parser.add_argument('--plugins',
89                         required=True,
90                         dest='plugins',
91                         metavar='PLUGINS',
92                         help='The path to userconfig plugin(s)',
93                         type=str,
94                         action='store')
95
96     try:
97         args = parser.parse_args(sys.argv[1:])
98         config = UserConfig(args.config, args.plugins)
99         data = config.get_flat_config()
100         for key, value in data.iteritems():
101             print('%s=%s' % (key, value))
102
103     except Exception as exp:  # pylint: disable=broad-except
104         print("Got exp: %s" % exp)
105         traceback.print_exc()
106         sys.exit(1)
107     sys.exit(1)
108
109
110 if __name__ == '__main__':
111     main()