Debian Codegraph @

neutron_lib/plugins/directory.py

raw
1 # All Rights Reserved.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License"); you may
4 # not use this file except in compliance with the License. You may obtain
5 # 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, WITHOUT
11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 # License for the specific language governing permissions and limitations
13 # under the License.
14
15 import weakref
16
17 from oslo_concurrency import lockutils
18
19 from neutron_lib.plugins import constants
20
21
22 _synchronized = lockutils.synchronized_with_prefix("neutron-")
23
24
25 class _PluginDirectory:
26 """A directory of activated plugins in a Neutron Deployment.
27
28 The directory is bootstrapped by a Neutron Manager running in
29 the context of a Neutron Server process.
30 """
31
32 def __init__(self):
33 self._plugins = {}
34
35 def add_plugin(self, alias, plugin):
36 """Add a plugin of type 'alias'."""
37 self._plugins[alias] = plugin
38
39 def get_plugin(self, alias):
40 """Get a plugin for a given alias or None if not present."""
41 p = self._plugins.get(alias)
42 return weakref.proxy(p) if p else None
43
44 @property
45 def plugins(self):
46 """The mapping alias -> weak reference to the plugin."""
47 return {x: weakref.proxy(y)
48 for x, y in self._plugins.items()}
49
50 @property
51 def unique_plugins(self):
52 """A sequence of the unique plugins activated in the environments."""
53 return tuple(weakref.proxy(x) for x in set(self._plugins.values()))
54
55 @property
56 def is_loaded(self):
57 """True if the directory is non empty."""
58 return len(self._plugins) > 0
59
60
61 # Create a singleton plugins directory for the Neutron server instance.
62 # Accessing these methods before a Neutron Manager has had the chance
63 # to load the environment may result in callers handling an empty directory.
64 _PLUGIN_DIRECTORY = None
65
66
67 @_synchronized("plugin-directory")
68 def _create_plugin_directory():
69 global _PLUGIN_DIRECTORY
70 if _PLUGIN_DIRECTORY is None:
71 _PLUGIN_DIRECTORY = _PluginDirectory()
72 return _PLUGIN_DIRECTORY
73
74
75 def _get_plugin_directory():
76 if _PLUGIN_DIRECTORY is None:
77 return _create_plugin_directory()
78 return _PLUGIN_DIRECTORY
79
80
81 def add_plugin(alias, plugin):
82 _get_plugin_directory().add_plugin(alias, plugin)
83
84
85 def get_plugin(alias=constants.CORE):
86 return _get_plugin_directory().get_plugin(alias)
87
88
89 def get_plugins():
90 return _get_plugin_directory().plugins
91
92
93 def get_unique_plugins():
94 return _get_plugin_directory().unique_plugins
95
96
97 def is_loaded():
98 return _get_plugin_directory().is_loaded