Debian Codegraph @

neutron_lib/callbacks/manager.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
15 from oslo_log import log as logging
16 from oslo_utils import reflection
17
18 from neutron_lib.callbacks import events
19 from neutron_lib.callbacks import exceptions
20 from neutron_lib.callbacks import priority_group
21 from neutron_lib.db import utils as db_utils
22
23 LOG = logging.getLogger(__name__)
24 PriorityCallbacks = collections.namedtuple(
25 'PriorityCallbacks', ['priority', 'pri_callbacks', 'cancellable'])
26 Callback = collections.namedtuple(
27 'Callback', ['id', 'method', 'cancellable'])
28
29
30 class CallbacksManager:
31 """A callback system that allows objects to cooperate in a loose manner."""
32
33 def __init__(self):
34 self.clear()
35
36 def subscribe(self, callback, resource, event,
37 priority=priority_group.PRIORITY_DEFAULT,
38 cancellable=False):
39 """Subscribe callback for a resource event.
40
41 The same callback may register for more than one event.
42
43 :param callback: the callback. It must raise or return a boolean.
44 :param resource: the resource. It must be a valid resource.
45 :param event: the event. It must be a valid event.
46 :param priority: the priority. Callbacks are sorted by priority
47 to be called. Smaller one is called earlier.
48 :param cancellable: if the callback is "cancellable", in case of
49 returning an exception, the callback manager will
50 raise a ``CallbackFailure`` exception.
51 """
52 LOG.debug("Subscribe: %(callback)s %(resource)s %(event)s "
53 "%(priority)d, %(cancellable)s",
54 {'callback': callback, 'resource': resource, 'event': event,
55 'priority': priority, 'cancellable': cancellable})
56
57 callback_id = _get_id(callback)
58 pri_callbacks_list = self._callbacks[resource].setdefault(event, [])
59 for pri_callbacks in pri_callbacks_list:
60 if pri_callbacks.priority == priority:
61 pri_callbacks = pri_callbacks.pri_callbacks
62 break
63 else:
64 pri_callbacks = {}
65 pri_callbacks_list.append(
66 PriorityCallbacks(priority, pri_callbacks, cancellable))
67 pri_callbacks_list.sort(key=lambda x: x.priority)
68 pri_callbacks[callback_id] = callback
69
70 # We keep a copy of callbacks to speed the unsubscribe operation.
71 if callback_id not in self._index:
72 self._index[callback_id] = collections.defaultdict(set)
73 self._index[callback_id][resource].add(event)
74
75 def _del_callback(self, pri_callbacks, callback_id):
76 for pri_callback in pri_callbacks:
77 if callback_id in pri_callback.pri_callbacks:
78 del pri_callback.pri_callbacks[callback_id]
79 if not pri_callback.pri_callbacks:
80 pri_callbacks.remove(pri_callback)
81 break
82
83 def unsubscribe(self, callback, resource, event):
84 """Unsubscribe callback from the registry.
85
86 :param callback: the callback.
87 :param resource: the resource.
88 :param event: the event.
89 """
90 LOG.debug("Unsubscribe: %(callback)s %(resource)s %(event)s",
91 {'callback': callback, 'resource': resource, 'event': event})
92
93 callback_id = self._find(callback)
94 if not callback_id:
95 LOG.debug("Callback %s not found", callback_id)
96 return
97 if resource and event:
98 self._del_callback(self._callbacks[resource][event], callback_id)
99 self._index[callback_id][resource].discard(event)
100 if not self._index[callback_id][resource]:
101 del self._index[callback_id][resource]
102 if not self._index[callback_id]:
103 del self._index[callback_id]
104 else:
105 value = f'{resource},{event}'
106 raise exceptions.Invalid(element='resource,event', value=value)
107
108 def unsubscribe_by_resource(self, callback, resource):
109 """Unsubscribe callback for any event associated to the resource.
110
111 :param callback: the callback.
112 :param resource: the resource.
113 """
114 callback_id = self._find(callback)
115 if callback_id:
116 if resource in self._index[callback_id]:
117 for event in self._index[callback_id][resource]:
118 self._del_callback(self._callbacks[resource][event],
119 callback_id)
120 del self._index[callback_id][resource]
121 if not self._index[callback_id]:
122 del self._index[callback_id]
123
124 def unsubscribe_all(self, callback):
125 """Unsubscribe callback for all events and all resources.
126
127
128 :param callback: the callback.
129 """
130 callback_id = self._find(callback)
131 if callback_id:
132 for resource, resource_events in self._index[callback_id].items():
133 for event in resource_events:
134 self._del_callback(self._callbacks[resource][event],
135 callback_id)
136 del self._index[callback_id]
137
138 @db_utils.reraise_as_retryrequest
139 def publish(self, resource, event, trigger, payload=None):
140 """Notify all subscribed callback(s) with a payload.
141
142 Dispatch the resource's event to the subscribed callbacks.
143
144 :param resource: The resource for the event.
145 :param event: The event.
146 :param trigger: The trigger. A reference to the sender of the event.
147 :param payload: The optional event object to send to subscribers. If
148 passed this must be an instance of BaseEvent.
149 :raises neutron_lib.callbacks.exceptions.Invalid: if
150 the payload object is not an instance of BaseEvent.
151 :raises CallbackFailure: if the underlying callback has errors.
152 """
153 if payload:
154 if not isinstance(payload, events.EventPayload):
155 raise exceptions.Invalid(element='event payload',
156 value=type(payload))
157 errors = self._notify_loop(resource, event, trigger, payload)
158 if errors:
159 if event.startswith(events.BEFORE):
160 abort_event = event.replace(
161 events.BEFORE, events.ABORT)
162 self._notify_loop(resource, abort_event, trigger, payload)
163
164 raise exceptions.CallbackFailure(errors=errors)
165
166 if (event.startswith(events.PRECOMMIT) or
167 any(error.is_cancellable for error in errors)):
168 raise exceptions.CallbackFailure(errors=errors)
169
170 def clear(self):
171 """Brings the manager to a clean slate."""
172 self._callbacks = collections.defaultdict(dict)
173 self._index = collections.defaultdict(dict)
174
175 def _notify_loop(self, resource, event, trigger, payload):
176 """The notification loop."""
177 errors = []
178 callbacks = []
179 for pri_callbacks in self._callbacks[resource].get(event, []):
180 for cb_id, cb_method in pri_callbacks.pri_callbacks.items():
181 cb = Callback(cb_id, cb_method, pri_callbacks.cancellable)
182 callbacks.append(cb)
183 resource_id = getattr(payload, "resource_id", None)
184 LOG.debug("Publish callbacks %s for %s (%s), %s",
185 [c.id for c in callbacks], resource, resource_id, event)
186 # TODO(armax): consider using a GreenPile
187 for callback in callbacks:
188 try:
189 callback.method(resource, event, trigger, payload=payload)
190 except Exception as e:
191 if not (events.is_cancellable_event(event) or
192 callback.cancellable):
193 LOG.exception("Error during notification for "
194 "%(callback)s %(resource)s, %(event)s",
195 {'callback': callback.id,
196 'resource': resource, 'event': event})
197 else:
198 LOG.debug("Callback %(callback)s raised %(error)s",
199 {'callback': callback.id, 'error': e})
200 errors.append(exceptions.NotificationError(
201 callback.id, e, cancellable=callback.cancellable))
202 return errors
203
204 def _find(self, callback):
205 """Return the callback_id if found, None otherwise."""
206 callback_id = _get_id(callback)
207 return callback_id if callback_id in self._index else None
208
209
210 def _get_id(callback):
211 """Return a unique identifier for the callback."""
212 # TODO(armax): consider using something other than names
213 # https://www.python.org/dev/peps/pep-3155/, but this
214 # might be okay for now.
215 parts = (reflection.get_callable_name(callback),
216 str(hash(callback)))
217 return '-'.join(parts)