Debian Codegraph @

neutron_lib/callbacks/registry.py

raw
1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # 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, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
11 # under the License.
12
13 import collections
14 import inspect
15
16 from neutron_lib._i18n import _
17 from neutron_lib.callbacks import manager
18 from neutron_lib.callbacks import priority_group
19
20
21 # TODO(armax): consider adding locking
22 _CALLBACK_MANAGER = None
23
24 # stores a dictionary keyed on function pointers with a list of
25 # (resource, event) tuples to subscribe to on class initialization
26 _REGISTERED_CLASS_METHODS = collections.defaultdict(list)
27
28
29 def _get_callback_manager():
30 global _CALLBACK_MANAGER
31 if _CALLBACK_MANAGER is None:
32 _CALLBACK_MANAGER = manager.CallbacksManager()
33 return _CALLBACK_MANAGER
34
35
36 def subscribe(callback, resource, event,
37 priority=priority_group.PRIORITY_DEFAULT,
38 cancellable=False):
39 _get_callback_manager().subscribe(callback, resource, event, priority,
40 cancellable)
41
42
43 def unsubscribe(callback, resource, event):
44 _get_callback_manager().unsubscribe(callback, resource, event)
45
46
47 def unsubscribe_by_resource(callback, resource):
48 _get_callback_manager().unsubscribe_by_resource(callback, resource)
49
50
51 def unsubscribe_all(callback):
52 _get_callback_manager().unsubscribe_all(callback)
53
54
55 def publish(resource, event, trigger, payload=None):
56 _get_callback_manager().publish(resource, event, trigger, payload=payload)
57
58
59 def clear():
60 _get_callback_manager().clear()
61
62
63 def receives(resource, events, priority=priority_group.PRIORITY_DEFAULT):
64 """Use to decorate methods on classes before initialization.
65
66 Any classes that use this must themselves be decorated with the
67 @has_registry_receivers decorator to setup the __new__ method to
68 actually register the instance methods after initialization.
69 """
70 if not isinstance(events, list | tuple | set):
71 msg = _("'events' must be a collection (list, tuple, set)")
72 raise AssertionError(msg)
73
74 def decorator(f):
75 for e in events:
76 _REGISTERED_CLASS_METHODS[f].append((resource, e, priority))
77 return f
78 return decorator
79
80
81 def has_registry_receivers(klass):
82 """Decorator to setup __new__ method in classes to subscribe bound methods.
83
84 Any method decorated with @receives above is an unbound method on a class.
85 This decorator sets up the class __new__ method to subscribe the bound
86 method in the callback registry after object instantiation.
87 """
88 orig_new = klass.__new__
89 new_inherited = '__new__' not in klass.__dict__
90
91 @staticmethod
92 def replacement_new(cls, *args, **kwargs):
93 if new_inherited:
94 # class didn't define __new__ so we need to call inherited __new__
95 super_new = super(klass, cls).__new__
96 if super_new is object.__new__:
97 # object.__new__ doesn't accept args nor kwargs
98 # pylint: disable=no-value-for-parameter
99 instance = super_new(cls)
100 else:
101 instance = super_new(cls, *args, **kwargs)
102 else:
103 instance = orig_new(cls, *args, **kwargs)
104 if getattr(instance, '_DECORATED_METHODS_SUBSCRIBED', False):
105 # Avoid running this logic twice for classes inheriting other
106 # classes with this same decorator. Only one needs to execute
107 # to subscribe all decorated methods.
108 return instance
109 for name, unbound_method in inspect.getmembers(cls):
110 if (not inspect.ismethod(unbound_method) and
111 not inspect.isfunction(unbound_method)):
112 continue
113 # handle py27/py34 difference
114 func = getattr(unbound_method, 'im_func', unbound_method)
115 if func not in _REGISTERED_CLASS_METHODS:
116 continue
117 for resource, event, priority in _REGISTERED_CLASS_METHODS[func]:
118 # subscribe the bound method
119 subscribe(getattr(instance, name), resource, event, priority)
120 setattr(instance, '_DECORATED_METHODS_SUBSCRIBED', True)
121 return instance
122 klass.__new__ = replacement_new
123 return klass