1 # Copyright 2015-2017 Intel Corporation.
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.
15 """Loader servant module used by Loader.
17 Module is inteded to be private to serve only Loader itself, nevertheless
18 some methods are exposed outside and can be used by any other clients:
19 - load_modules(self, path, interface)
20 - load_module(self, path, interface, class_name)
21 Those method are stateless static members.
29 from conf import settings
32 class LoaderServant(object):
33 """Class implements basic dynamic import operations.
39 def __init__(self, path, class_name, interface):
40 """LoaderServant constructor
42 Intializes all data needed for import operations.
45 path: path to directory which contains implementations derived from
47 class_name: Class name which will be returned in get_class
48 method, if such definition exists in directory
50 interface: interface type. Every object which doesn't
51 implement this particular interface will be
54 self._class_name = class_name
56 self._interface = interface
59 """Returns class type based on parameters passed in __init__.
61 :return: Type of the found class.
62 None if class hasn't been found
65 return self.load_module(path=self._path,
66 interface=self._interface,
67 class_name=self._class_name)
69 def get_classes(self):
70 """Returns all classes in path derived from interface
72 :return: Dictionary with following data:
73 - key: String representing class name,
76 return self.load_modules(path=self._path,
77 interface=self._interface)
79 def get_classes_printable(self):
80 """Returns all classes derived from _interface found in path
82 :return: String - list of classes in printable format.
85 out = self.load_modules(path=self._path,
86 interface=self._interface)
89 # sort modules to produce the same output everytime
90 for (name, mod) in sorted(out.items()):
91 desc = (mod.__doc__ or 'No description').strip().split('\n')[0]
92 results.append((name, desc))
94 header = 'Classes derived from: ' + self._interface.__name__
95 output = [header + '\n' + '=' * len(header) + '\n']
97 for (name, desc) in results:
98 output.append('* %-18s%s' % ('%s:' % name, desc))
104 return '\n'.join(output)
107 def load_module(path, interface, class_name):
108 """Imports everything from given path and returns class type
110 This is based on following conditions:
111 - Class is derived from interface,
112 - Class type name matches class_name.
114 :return: Type of the found class.
115 None if class hasn't been found
118 results = LoaderServant.load_modules(
119 path=path, interface=interface)
121 if class_name in results:
123 "Class found: %s.", class_name)
124 return results.get(class_name)
129 def load_modules(path, interface):
130 """Returns dictionary of class name/class type found in path
132 This is based on following conditions:
133 - classes found under path are derived from interface.
134 - class is not interface itself.
136 :return: Dictionary with following data:
137 - key: String representing class name,
142 for _, mod in LoaderServant._load_all_modules(path):
143 # find all classes derived from given interface, but suppress
144 # interface itself and any abstract class starting with iface name
145 gens = dict((k, v) for (k, v) in list(mod.__dict__.items())
146 if isinstance(v, type) and
147 issubclass(v, interface) and
148 not k.startswith(interface.__name__))
150 for (genname, gen) in list(gens.items()):
151 result[genname] = gen
155 def _load_all_modules(path):
156 """Load all modules from ``path`` directory.
158 This is based on the design used by OFTest:
159 https://github.com/floodlight/oftest/blob/master/oft
161 :param path: Path to a folder of modules.
163 :return: List of modules in a folder.
167 for root, _, filenames in os.walk(path):
168 # Iterate over each python file
169 for filename in fnmatch.filter(filenames, '[!.]*.py'):
170 modname = os.path.splitext(os.path.basename(filename))[0]
172 # skip module load if it is excluded by configuration
173 if modname in settings.getValue('EXCLUDE_MODULES'):
177 if modname in sys.modules:
178 mod = sys.modules[modname]
180 mod = imp.load_module(
181 modname, *imp.find_module(modname, [root]))
183 logging.error('Could not import file %s', filename)
186 mods.append((modname, mod))