Debian Codegraph @

neutron_lib/utils/runtime.py

raw
1 # Licensed under the Apache License, Version 2.0 (the "License");
2 # you may not use this file except in compliance with the License.
3 # You may obtain a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS,
9 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
10 # implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 import pkgutil
15 import sys
16
17 from oslo_concurrency import lockutils
18 from oslo_log import log as logging
19 from oslo_utils import importutils
20 from stevedore import driver
21 from stevedore import enabled
22
23 from neutron_lib._i18n import _
24
25
26 LOG = logging.getLogger(__name__)
27 SYNCHRONIZED_PREFIX = 'neutron-'
28
29 # common synchronization decorator
30 synchronized = lockutils.synchronized_with_prefix(SYNCHRONIZED_PREFIX)
31
32
33 class NamespacedPlugins:
34 """Wraps a stevedore plugin namespace to load/access its plugins."""
35
36 def __init__(self, namespace):
37 self.namespace = namespace
38 self._extension_manager = None
39 self._extensions = {}
40 self.reload()
41
42 def reload(self):
43 """Force a reload of the plugins for this instances namespace.
44
45 :returns: None.
46 """
47 self._extensions = {}
48 self._extension_manager = enabled.EnabledExtensionManager(
49 self.namespace, lambda x: True,
50 invoke_on_load=False)
51
52 if not self._extension_manager.names():
53 LOG.debug("No plugins found in namespace: ", self.namespace)
54 return
55 self._extension_manager.map(self._add_extension)
56
57 def _add_extension(self, ext):
58 if ext.name in self._extensions:
59 msg = _("Plugin '%(p)s' already in namespace: %(ns)s") % {
60 'p': ext.name, 'ns': self.namespace}
61 raise KeyError(msg)
62
63 LOG.debug("Loaded plugin '%s' from namespace: %s",
64 ext.name, self.namespace)
65 self._extensions[ext.name] = ext
66
67 def _assert_plugin_loaded(self, plugin_name):
68 if plugin_name not in self._extensions:
69 msg = _("Plugin '%(p)s' not in namespace: %(ns)s") % {
70 'p': plugin_name, 'ns': self.namespace}
71 raise KeyError(msg)
72
73 def get_plugin_class(self, plugin_name):
74 """Gets a reference to a loaded plugin's class.
75
76 :param plugin_name: The name of the plugin to get the class for.
77 :returns: A reference to the loaded plugin's class.
78 :raises: KeyError if plugin_name is not loaded.
79 """
80 self._assert_plugin_loaded(plugin_name)
81 return self._extensions[plugin_name].plugin
82
83 def new_plugin_instance(self, plugin_name, *args, **kwargs):
84 """Create a new instance of a plugin.
85
86 :param plugin_name: The name of the plugin to instantiate.
87 :param args: Any args to pass onto the constructor.
88 :param kwargs: Any kwargs to pass onto the constructor.
89 :returns: A new instance of plugin_name.
90 :raises: KeyError if plugin_name is not loaded.
91 """
92 self._assert_plugin_loaded(plugin_name)
93 return self.get_plugin_class(plugin_name)(*args, **kwargs)
94
95 @property
96 def loaded_plugin_names(self):
97 return self._extensions.keys()
98
99
100 def load_class_by_alias_or_classname(namespace, name):
101 """Load a class using stevedore alias or the class name.
102
103 :param namespace: The namespace where the alias is defined.
104 :param name: The alias or class name of the class to be loaded.
105 :returns: Class if it can be loaded.
106 :raises ImportError: if class cannot be loaded.
107 """
108 if not name:
109 LOG.error("Alias or class name is not set")
110 raise ImportError(_("Class not found."))
111 try:
112 # Try to resolve class by alias
113 mgr = driver.DriverManager(
114 namespace, name, on_missing_entrypoints_callback=None)
115 class_to_load = mgr.driver
116 except RuntimeError:
117 e1_info = sys.exc_info()
118 # Fallback to class name
119 try:
120 class_to_load = importutils.import_class(name)
121 except (ImportError, ValueError) as e:
122 LOG.error("Error loading class by alias",
123 exc_info=e1_info)
124 LOG.error("Error loading class by class name",
125 exc_info=True)
126 raise ImportError(_("Class not found.")) from e
127 return class_to_load
128
129
130 def list_package_modules(package_name):
131 """Get a list of the modules for a given package.
132
133 :param package_name: The package name to get modules for.
134 :returns: A list of module objects for the said package name.
135 """
136 pkg_mod = importutils.import_module(package_name)
137 modules = [pkg_mod]
138
139 for mod in pkgutil.walk_packages(pkg_mod.__path__):
140 _, mod_name, _ = mod
141 fq_name = pkg_mod.__name__ + "." + mod_name
142 modules.append(importutils.import_module(fq_name))
143
144 return modules