Initial commit
[ta/config-manager.git] / cmframework / src / cmframework / utils / cmpluginloader.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 # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
15 import os
16 import imp
17 import sys
18 import logging
19
20 from cmframework.apis import cmerror
21
22
23 class CMPluginLoader(object):
24     class LoadingFilter(object):
25         # pylint: disable=no-self-use, unused-argument
26         def is_supported(self, plugin):
27             return True
28
29     def __init__(self, plugin_location, plugin_filter=None):
30         self.location = plugin_location
31         sys.path.append(self.location)
32         self.pluginslist = []
33         self.loaded_plugin = {}
34         self.filterlist = {}
35         self.plugin_filter = plugin_filter
36
37     def find_plugin(self):
38         logging.debug('finding plugins in %s', self.location)
39         listofplugin = os.listdir(self.location)
40         for plugin in listofplugin:
41             if plugin.endswith('.py'):
42                 logging.debug('Adding plugin %s', plugin)
43                 self.pluginslist.append(plugin.replace(".py", ""))
44
45     def sort_plugin(self):
46         logging.debug('Sorting plugins')
47         self.pluginslist.sort()
48
49     def load_plugin(self):
50         for plugin in self.pluginslist:
51             logging.debug('Loading plugin %s', plugin)
52             fp, pathname, description = imp.find_module(plugin)
53             try:
54                 pluginmodule = imp.load_module(plugin, fp, pathname, description)
55                 add_plugin = True
56                 if self.plugin_filter:
57                     class_name = getattr(pluginmodule, plugin)
58                     instance = class_name()
59                     add_plugin = self.plugin_filter.is_supported(instance)
60                 if add_plugin:
61                     logging.info('Adding plugin %s to list', plugin)
62                     self.loaded_plugin[plugin] = pluginmodule
63                 else:
64                     logging.info(
65                         'Skipping plugin %s as it does not match configured filter', plugin)
66             except Exception as exp:  # pylint: disable=broad-except
67                 logging.error('Failed to load plugin %s, got exp %s', plugin, str(exp))
68                 raise cmerror.CMError('Loading %s plugin failed' % plugin)
69             finally:
70                 if fp:
71                     fp.close()
72
73     def build_filter_dict(self):
74         faulty_plugins = []
75         for plugin, objectname in self.loaded_plugin.iteritems():
76             logging.debug('Getting the subsription info from %s %s', plugin, objectname)
77             try:
78                 class_name = getattr(objectname, plugin)
79                 instance = class_name()
80                 filtername = instance.get_subscription_info()
81                 self.filterlist[plugin] = filtername
82             except Exception as exp:  # pylint: disable=broad-except
83                 logging.error('Getting subscription failed for %s %s, got exp %s',
84                               plugin, objectname, str(exp))
85                 faulty_plugins.append(plugin)
86
87         for plugin in faulty_plugins:
88             del self.loaded_plugin[plugin]
89
90     # pylint: disable=no-self-use
91     def validate_plugin(self):
92         pass
93
94     def load(self):
95         self.find_plugin()
96         self.sort_plugin()
97         self.load_plugin()
98         self.build_filter_dict()
99         return self.loaded_plugin, self.filterlist
100
101
102 def main():
103     pl = CMPluginLoader("plug_in/tst")
104     a, b = pl.load()
105     print a
106     print b
107
108
109 if __name__ == '__main__':
110     main()