7 class Notification(object):
9 This class can be used by the dashboard and the labs to exchange notifications about booking
10 events and pod status. It utilizes rabbitmq to communicate.
12 Notifications are associated to an event and to a topic.
14 [ 'booking_start', 'booking_stop', 'pod_status' ]
15 The topic is usually a POD name, ie:
19 def __init__(self, dashboard_url, verbose=False):
20 self.rabbitmq_broker = dashboard_url
21 self.verbose = verbose
24 self.connection = pika.BlockingConnection(pika.ConnectionParameters(
25 host=self.rabbitmq_broker))
26 self.channel = self.connection.channel()
28 self.channel.exchange_declare(exchange='notifications', type='topic')
30 self.result = self.channel.queue_declare(exclusive=True)
31 self.queue_name = self.result.method.queue
33 def register(self, function, event, regex):
35 Registers a function to be called for the specified event.
36 :param function: the function to register
37 :param event: the event type
38 :param regex: a regex to specify for wich topics the function will be called. Some
39 possible Expressions can be:
40 'Intel POD 2' : Intel POD 2
41 'Intel POD .*' : All Intel Pods
45 if event not in self._registry:
46 self._registry[event] = [(function, regex)]
48 self._registry[event].append((function, regex))
52 Start receiving notifications. This is a blocking operation, if a notification is received,
53 the registered functions will be called.
56 print('Start receiving Notifications. Keys: ', self._registry.keys())
57 self._receive_message(self._registry.keys())
59 def send(self, event, topic, content):
61 Send an event notification.
62 :param event: the event type
63 :param topic: the pod name
64 :param content: a JSON-serializable dictionary
71 self._send_message(message)
73 def _send_message(self, event):
74 routing_key = event['type']
75 message = json.dumps(event)
76 self.channel.basic_publish(exchange='notifications',
77 routing_key=routing_key,
79 properties=pika.BasicProperties(
80 content_type='application/json'
83 print(" [x] Sent %r:%r" % (routing_key, message))
85 def _receive_message(self, binding_keys):
86 for key in binding_keys:
87 self.channel.queue_bind(exchange='notifications',
88 queue=self.queue_name,
90 self.channel.basic_consume(self._message_callback,
91 queue=self.queue_name,
93 self.channel.start_consuming()
95 def _message_callback(self, ch, method, properties, body):
97 print(" [x] Got %r:%r" % (method.routing_key, body))
98 if method.routing_key not in self._registry:
100 for func, regex in self._registry[method.routing_key]:
101 message = json.loads(body.decode())
102 match = re.match(regex, message['topic'])