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 # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
20 from cmframework.apis import cmerror
23 class CMPluginLoader(object):
24 class LoadingFilter(object):
25 # pylint: disable=no-self-use, unused-argument
26 def is_supported(self, plugin):
29 def __init__(self, plugin_location, plugin_filter=None):
30 self.location = plugin_location
31 sys.path.append(self.location)
33 self.loaded_plugin = {}
35 self.plugin_filter = plugin_filter
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", ""))
45 def sort_plugin(self):
46 logging.debug('Sorting plugins')
47 self.pluginslist.sort()
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)
54 pluginmodule = imp.load_module(plugin, fp, pathname, description)
56 if self.plugin_filter:
57 class_name = getattr(pluginmodule, plugin)
58 instance = class_name()
59 add_plugin = self.plugin_filter.is_supported(instance)
61 logging.info('Adding plugin %s to list', plugin)
62 self.loaded_plugin[plugin] = pluginmodule
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)
73 def build_filter_dict(self):
75 for plugin, objectname in self.loaded_plugin.iteritems():
76 logging.debug('Getting the subsription info from %s %s', plugin, objectname)
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)
87 for plugin in faulty_plugins:
88 del self.loaded_plugin[plugin]
90 # pylint: disable=no-self-use
91 def validate_plugin(self):
98 self.build_filter_dict()
99 return self.loaded_plugin, self.filterlist
103 pl = CMPluginLoader("plug_in/tst")
109 if __name__ == '__main__':