1
# Copyright 2012 OpenStack LLC.
4
# Licensed under the Apache License, Version 2.0 (the "License"); you may
5
# not use this file except in compliance with the License. You may obtain
6
# a copy of the License at
8
# http://www.apache.org/licenses/LICENSE-2.0
10
# Unless required by applicable law or agreed to in writing, software
11
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13
# License for the specific language governing permissions and limitations
16
from nova.openstack.common import log as logging
17
from nova.openstack.common.plugin import plugin
20
LOG = logging.getLogger(__name__)
23
class _CallbackNotifier(object):
24
"""Manages plugin-defined notification callbacks.
26
For each Plugin, a CallbackNotifier will be added to the
27
notification driver list. Calls to notify() with appropriate
28
messages will be hooked and prompt callbacks.
30
A callback should look like this:
31
def callback(context, message, user_data)
35
self._callback_dict = {}
37
def _add_callback(self, event_type, callback, user_data):
38
callback_list = self._callback_dict.get(event_type, [])
39
callback_list.append({'function': callback,
40
'user_data': user_data})
41
self._callback_dict[event_type] = callback_list
43
def _remove_callback(self, callback):
44
for callback_list in self._callback_dict.values():
45
for entry in callback_list:
46
if entry['function'] == callback:
47
callback_list.remove(entry)
49
def notify(self, context, message):
50
if message.get('event_type') not in self._callback_dict:
53
for entry in self._callback_dict[message.get('event_type')]:
54
entry['function'](context, message, entry.get('user_data'))
57
return self._callback_dict
60
class CallbackPlugin(plugin.Plugin):
61
""" Plugin with a simple callback interface.
63
This class is provided as a convenience for producing a simple
64
plugin that only watches a couple of events. For example, here's
65
a subclass which prints a line the first time an instance is created.
67
class HookInstanceCreation(CallbackPlugin):
69
def __init__(self, _service_name):
70
super(HookInstanceCreation, self).__init__()
71
self._add_callback(self.magic, 'compute.instance.create.start')
74
print "An instance was created!"
75
self._remove_callback(self, self.magic)
78
def __init__(self, service_name):
79
super(CallbackPlugin, self).__init__(service_name)
80
self._callback_notifier = _CallbackNotifier()
81
self._add_notifier(self._callback_notifier)
83
def _add_callback(self, callback, event_type, user_data=None):
84
"""Add callback for a given event notification.
86
Subclasses can call this as an alternative to implementing
87
a fullblown notify notifier.
89
self._callback_notifier._add_callback(event_type, callback, user_data)
91
def _remove_callback(self, callback):
92
"""Remove all notification callbacks to specified function."""
93
self._callback_notifier._remove_callback(callback)