Merge "heat: convert open to context manager"
[yardstick.git] / yardstick / network_services / nfvi / collectd.py
1 # Copyright (c) 2016-2017 Intel Corporation
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain 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,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 """ AMQP Consumer senario definition """
15
16 from __future__ import absolute_import
17 from __future__ import print_function
18 import logging
19 import pika
20 from pika.exceptions import AMQPConnectionError
21
22
23 class AmqpConsumer(object):
24     """ This Class handles amqp consumer and collects collectd data """
25     EXCHANGE = 'amq.fanout'
26     EXCHANGE_TYPE = 'fanout'
27     QUEUE = ''
28     ROUTING_KEY = 'collectd'
29
30     def __init__(self, amqp_url, queue):
31         self._connection = None
32         self._channel = None
33         self._closing = False
34         self._consumer_tag = None
35         self._url = amqp_url
36         self._queue = queue
37
38     def connect(self):
39         """ connect to amqp url """
40         try:
41             return pika.SelectConnection(pika.URLParameters(self._url),
42                                          self.on_connection_open,
43                                          stop_ioloop_on_close=False)
44         except AMQPConnectionError:
45             raise RuntimeError
46
47     def on_connection_open(self, unused_connection):
48         """ call back from pika & open channel """
49         logging.info("list of unused connections %s", unused_connection)
50         self._connection.add_on_close_callback(self.on_connection_closed)
51         self._connection.channel(on_open_callback=self.on_channel_open)
52
53     def on_connection_closed(self, connection, reply_code, reply_text):
54         """ close the amqp connections. if force close, try re-connect """
55         logging.info("amqp connection (%s)", connection)
56         self._channel = None
57         if self._closing:
58             self._connection.ioloop.stop()
59         else:
60             logging.debug(('Connection closed, reopening in 5 sec: (%s) %s',
61                            reply_code, reply_text))
62             self._connection.add_timeout(5, self.reconnect)
63
64     def reconnect(self):
65         """ re-connect amqp consumer"""
66         self._connection.ioloop.stop()
67
68         if not self._closing:
69             self._connection = self.connect()
70             self._connection.ioloop.start()
71
72     def on_channel_open(self, channel):
73         """ add close callback & setup exchange """
74         self._channel = channel
75         self.add_on_channel_close_callback()
76         self._channel.exchange_declare(self.on_exchange_declareok,
77                                        self.EXCHANGE,
78                                        self.EXCHANGE_TYPE,
79                                        durable=True, auto_delete=False)
80
81     def add_on_channel_close_callback(self):
82         """ register for close callback """
83         self._channel.add_on_close_callback(self.on_channel_closed)
84
85     def on_channel_closed(self, channel, reply_code, reply_text):
86         """ close amqp channel connection """
87         logging.info("amqp channel closed channel(%s), "
88                      "reply_code(%s) reply_text(%s)",
89                      channel, reply_code, reply_text)
90         self._connection.close()
91
92     def on_exchange_declareok(self, unused_frame):
93         """ if exchange declare is ok, setup queue """
94         logging.info("amqp exchange unused frame (%s)", unused_frame)
95         self.setup_queue(self.QUEUE)
96
97     def setup_queue(self, queue_name):
98         """ setup queue & declare same with channel """
99         logging.info("amqp queue name (%s)", queue_name)
100         self._channel.queue_declare(self.on_queue_declareok, queue_name)
101
102     def on_queue_declareok(self, method_frame):
103         """ bind queue to channel """
104         logging.info("amqp queue method frame (%s)", method_frame)
105         self._channel.queue_bind(self._on_bindok, self.QUEUE,
106                                  self.EXCHANGE, self.ROUTING_KEY)
107
108     def _on_bindok(self, unused_frame):
109         """ call back on bind start consuming data from amqp queue """
110         logging.info("amqp unused frame %s", unused_frame)
111         self.add_on_cancel_callback()
112         self._consumer_tag = self._channel.basic_consume(self.on_message,
113                                                          self.QUEUE)
114
115     def add_on_cancel_callback(self):
116         """ add cancel func to amqp callback """
117         self._channel.add_on_cancel_callback(self.on_consumer_cancelled)
118
119     def on_consumer_cancelled(self, method_frame):
120         """ on cancel close the channel """
121         logging.info("amqp method frame %s", method_frame)
122         if self._channel:
123             self._channel.close()
124
125     def on_message(self, unused_channel, basic_deliver, properties, body):
126         """ parse received data from amqp server (collectd) """
127         logging.info("amqp unused channel %s, properties %s",
128                      unused_channel, properties)
129         metrics = body.rsplit()
130         self._queue.put({metrics[1]: metrics[3]})
131         self.ack_message(basic_deliver.delivery_tag)
132
133     def ack_message(self, delivery_tag):
134         """ acknowledge amqp msg """
135         self._channel.basic_ack(delivery_tag)
136
137     def on_cancelok(self, unused_frame):
138         """ initiate amqp close channel on callback """
139         logging.info("amqp unused frame %s", unused_frame)
140         self._channel.close()
141
142     def run(self):
143         """ Initiate amqp connection. """
144         self._connection = self.connect()
145         self._connection.ioloop.start()
146
147     def stop(self):
148         """ stop amqp consuming data """
149         self._closing = True
150         if self._channel:
151             self._channel.basic_cancel(self.on_cancelok, self._consumer_tag)
152
153         if self._connection:
154             self._connection.ioloop.start()
155
156     def close_connection(self):
157         """ close amqp connection """
158         self._connection.close()