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
7 # http://www.apache.org/licenses/LICENSE-2.0
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
18 from cmframework.apis import cmerror
19 from cmframework.utils.cmpluginloader import CMPluginLoader
20 from cmdatahandlers.api import configmanager
23 class UserConfig(object):
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)
30 def get_flat_config(self):
33 stream = file(self.user_config_file, 'r')
34 tmp = yaml.load(stream)
36 for key in tmp.keys():
37 userconfig['cloud.' + key] = tmp[key]
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)
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)
51 except Exception as exp:
52 raise cmerror.CMError("Failed to load user config %(userconfig)s: %(failure)s" %
53 {'userconfig': self.user_config_file,
57 class UserConfigPluginLoader(CMPluginLoader):
58 def __init__(self, plugin_location, plugin_filter=None):
59 super(UserConfigPluginLoader, self).__init__(plugin_location, plugin_filter)
61 def build_filter_dict(self):
64 def get_plugin_instances(self):
66 for plugin, module in self.loaded_plugin.iteritems():
67 class_name = getattr(module, plugin)
68 instance = class_name()
69 plugs[plugin] = instance
78 parser = argparse.ArgumentParser(description='Test userconfig handler', prog=sys.argv[0])
80 parser.add_argument('--config',
84 help='The user config yaml file',
88 parser.add_argument('--plugins',
92 help='The path to userconfig plugin(s)',
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))
103 except Exception as exp: # pylint: disable=broad-except
104 print("Got exp: %s" % exp)
105 traceback.print_exc()
110 if __name__ == '__main__':