root / snf-common / synnefo / lib / amqp / amqp_haigha.py @ 30333691
History | View | Annotate | Download (10 kB)
1 |
# Copyright 2012 GRNET S.A. All rights reserved.
|
---|---|
2 |
#
|
3 |
# Redistribution and use in source and binary forms, with or
|
4 |
# without modification, are permitted provided that the following
|
5 |
# conditions are met:
|
6 |
#
|
7 |
# 1. Redistributions of source code must retain the above
|
8 |
# copyright notice, this list of conditions and the following
|
9 |
# disclaimer.
|
10 |
#
|
11 |
# 2. Redistributions in binary form must reproduce the above
|
12 |
# copyright notice, this list of conditions and the following
|
13 |
# disclaimer in the documentation and/or other materials
|
14 |
# provided with the distribution.
|
15 |
#
|
16 |
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
|
17 |
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
18 |
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
19 |
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
|
20 |
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
|
23 |
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
|
24 |
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
25 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
26 |
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
27 |
# POSSIBILITY OF SUCH DAMAGE.
|
28 |
#
|
29 |
# The views and conclusions contained in the software and
|
30 |
# documentation are those of the authors and should not be
|
31 |
# interpreted as representing official policies, either expressed
|
32 |
# or implied, of GRNET S.A.
|
33 |
|
34 |
from haigha.connections import RabbitConnection |
35 |
from haigha.message import Message |
36 |
from haigha import exceptions |
37 |
from random import shuffle |
38 |
from time import sleep |
39 |
import logging |
40 |
import socket |
41 |
from synnefo import settings |
42 |
from ordereddict import OrderedDict |
43 |
import gevent |
44 |
from gevent import monkey |
45 |
from functools import wraps |
46 |
|
47 |
|
48 |
logging.basicConfig(level=logging.INFO, |
49 |
format="[%(levelname)s %(asctime)s] %(message)s")
|
50 |
logger = logging.getLogger('haigha')
|
51 |
|
52 |
sock_opts = { |
53 |
(socket.IPPROTO_TCP, socket.TCP_NODELAY): 1,
|
54 |
} |
55 |
|
56 |
|
57 |
def reconnect_decorator(func): |
58 |
"""
|
59 |
Decorator for persistent connection with one or more AMQP brokers.
|
60 |
|
61 |
"""
|
62 |
@wraps(func)
|
63 |
def wrapper(self, *args, **kwargs): |
64 |
try:
|
65 |
func(self, *args, **kwargs)
|
66 |
except (socket.error, exceptions.ConnectionError) as e: |
67 |
logger.error('Connection Closed while in %s: %s', func.__name__, e)
|
68 |
self.connect()
|
69 |
|
70 |
return wrapper
|
71 |
|
72 |
|
73 |
class AMQPHaighaClient(): |
74 |
def __init__(self, hosts=settings.AMQP_HOSTS, max_retries=30, |
75 |
confirms=True, confirm_buffer=200): |
76 |
self.hosts = hosts
|
77 |
shuffle(self.hosts)
|
78 |
|
79 |
self.max_retries = max_retries
|
80 |
self.confirms = confirms
|
81 |
self.confirm_buffer = confirm_buffer
|
82 |
|
83 |
self.connection = None |
84 |
self.channel = None |
85 |
self.consumers = {}
|
86 |
self.unacked = OrderedDict()
|
87 |
|
88 |
def connect(self, retries=0): |
89 |
if retries > self.max_retries: |
90 |
logger.error("Aborting after %s retries", retries - 1) |
91 |
raise AMQPConnectionError('Aborting after %d connection failures.' |
92 |
% (retries - 1))
|
93 |
return
|
94 |
|
95 |
# Pick up a host
|
96 |
host = self.hosts.pop()
|
97 |
self.hosts.insert(0, host) |
98 |
|
99 |
#Patch gevent
|
100 |
monkey.patch_all() |
101 |
|
102 |
try:
|
103 |
self.connection = \
|
104 |
RabbitConnection(logger=logger, debug=True,
|
105 |
user='rabbit', password='r@bb1t', |
106 |
vhost='/', host=host,
|
107 |
heartbeat=None,
|
108 |
sock_opts=sock_opts, |
109 |
transport='gevent')
|
110 |
except socket.error as e: |
111 |
logger.error('Cannot connect to host %s: %s', host, e)
|
112 |
if retries > 2 * len(self.hosts): |
113 |
sleep(1)
|
114 |
return self.connect(retries + 1) |
115 |
|
116 |
logger.info('Successfully connected to host: %s', host)
|
117 |
|
118 |
logger.info('Creating channel')
|
119 |
self.channel = self.connection.channel() |
120 |
|
121 |
if self.confirms: |
122 |
self._confirm_select()
|
123 |
|
124 |
if self.unacked: |
125 |
self._resend_unacked_messages()
|
126 |
|
127 |
if self.consumers: |
128 |
for queue, callback in self.consumers.items(): |
129 |
self.basic_consume(queue, callback)
|
130 |
|
131 |
def exchange_declare(self, exchange, type='direct'): |
132 |
"""Declare an exchange
|
133 |
@type exchange_name: string
|
134 |
@param exchange_name: name of the exchange
|
135 |
@type exchange_type: string
|
136 |
@param exhange_type: one of 'direct', 'topic', 'fanout'
|
137 |
|
138 |
"""
|
139 |
|
140 |
logger.info('Declaring %s exchange: %s', type, exchange) |
141 |
self.channel.exchange.declare(exchange, type, |
142 |
auto_delete=False, durable=True) |
143 |
|
144 |
def queue_declare(self, queue, exclusive=False, mirrored=True, |
145 |
mirrored_nodes='all'):
|
146 |
"""Declare a queue
|
147 |
|
148 |
@type queue: string
|
149 |
@param queue: name of the queue
|
150 |
@param mirrored: whether the queue will be mirrored to other brokers
|
151 |
@param mirrored_nodes: the policy for the mirrored queue.
|
152 |
Available policies:
|
153 |
- 'all': The queue is mirrored to all nodes and the
|
154 |
master node is the one to which the client is
|
155 |
connected
|
156 |
- a list of nodes. The queue will be mirrored only to
|
157 |
the specified nodes, and the master will be the
|
158 |
first node in the list. Node names must be provided
|
159 |
and not host IP. example: [node1@rabbit,node2@rabbit]
|
160 |
|
161 |
"""
|
162 |
|
163 |
logger.info('Declaring queue: %s', queue)
|
164 |
if mirrored:
|
165 |
if mirrored_nodes == 'all': |
166 |
arguments = {'x-ha-policy': 'all'} |
167 |
elif isinstance(mirrored_nodes, list): |
168 |
arguments = {'x-ha-policy': 'nodes', |
169 |
'x-ha-policy-params': mirrored_nodes}
|
170 |
else:
|
171 |
raise AttributeError |
172 |
else:
|
173 |
arguments = {} |
174 |
|
175 |
self.channel.queue.declare(queue, durable=True, exclusive=exclusive, |
176 |
auto_delete=False, arguments=arguments)
|
177 |
|
178 |
def queue_bind(self, queue, exchange, routing_key): |
179 |
logger.info('Binding queue %s to exchange %s with key %s', queue,
|
180 |
exchange, routing_key) |
181 |
self.channel.queue.bind(queue=queue, exchange=exchange,
|
182 |
routing_key=routing_key) |
183 |
|
184 |
def _confirm_select(self): |
185 |
logger.info('Setting channel to confirm mode')
|
186 |
self.channel.confirm.select()
|
187 |
self.channel.basic.set_ack_listener(self._ack_received) |
188 |
self.channel.basic.set_nack_listener(self._nack_received) |
189 |
|
190 |
@reconnect_decorator
|
191 |
def basic_publish(self, exchange, routing_key, body): |
192 |
msg = Message(body, delivery_mode=2)
|
193 |
mid = self.channel.basic.publish(msg, exchange, routing_key)
|
194 |
if self.confirms: |
195 |
self.unacked[mid] = (exchange, routing_key, body)
|
196 |
if len(self.unacked) > self.confirm_buffer: |
197 |
self.get_confirms()
|
198 |
|
199 |
logger.debug('Published message %s with id %s', body, mid)
|
200 |
|
201 |
@reconnect_decorator
|
202 |
def get_confirms(self): |
203 |
self.connection.read_frames()
|
204 |
|
205 |
@reconnect_decorator
|
206 |
def _resend_unacked_messages(self): |
207 |
msgs = self.unacked.values()
|
208 |
self.unacked.clear()
|
209 |
for exchange, routing_key, body in msgs: |
210 |
logger.debug('Resending message %s', body)
|
211 |
self.basic_publish(exchange, routing_key, body)
|
212 |
|
213 |
@reconnect_decorator
|
214 |
def _ack_received(self, mid): |
215 |
print mid
|
216 |
logger.debug('Received ACK for message with id %s', mid)
|
217 |
self.unacked.pop(mid)
|
218 |
|
219 |
@reconnect_decorator
|
220 |
def _nack_received(self, mid): |
221 |
logger.error('Received NACK for message with id %s. Retrying.', mid)
|
222 |
(exchange, routing_key, body) = self.unacked[mid]
|
223 |
self.basic_publish(exchange, routing_key, body)
|
224 |
|
225 |
def basic_consume(self, queue, callback): |
226 |
"""Consume from a queue.
|
227 |
|
228 |
@type queue: string or list of strings
|
229 |
@param queue: the name or list of names from the queues to consume
|
230 |
@type callback: function
|
231 |
@param callback: the callback function to run when a message arrives
|
232 |
|
233 |
"""
|
234 |
|
235 |
self.consumers[queue] = callback
|
236 |
self.channel.basic.consume(queue, consumer=callback, no_ack=False) |
237 |
|
238 |
@reconnect_decorator
|
239 |
def basic_wait(self): |
240 |
"""Wait for messages from the queues declared by basic_consume.
|
241 |
|
242 |
This function will block until a message arrives from the queues that
|
243 |
have been declared with basic_consume. If the optional arguments
|
244 |
'promise' is given, only messages for this promise will be delivered.
|
245 |
|
246 |
"""
|
247 |
|
248 |
self.connection.read_frames()
|
249 |
gevent.sleep(0)
|
250 |
|
251 |
@reconnect_decorator
|
252 |
def basic_get(self, queue): |
253 |
self.channel.basic.get(queue, no_ack=False) |
254 |
|
255 |
@reconnect_decorator
|
256 |
def basic_ack(self, message): |
257 |
delivery_tag = message.delivery_info['delivery_tag']
|
258 |
self.channel.basic.ack(delivery_tag)
|
259 |
|
260 |
@reconnect_decorator
|
261 |
def basic_nack(self, message): |
262 |
delivery_tag = message.delivery_info['delivery_tag']
|
263 |
self.channel.basic.ack(delivery_tag)
|
264 |
|
265 |
def close(self): |
266 |
try:
|
267 |
if self.confirms: |
268 |
while self.unacked: |
269 |
print self.unacked |
270 |
self.get_confirms()
|
271 |
self.channel.close()
|
272 |
close_info = self.channel.close_info
|
273 |
logger.info('Successfully closed channel. Info: %s', close_info)
|
274 |
self.connection.close()
|
275 |
except socket.error as e: |
276 |
logger.error('Connection closed while closing connection:%s', e)
|
277 |
|
278 |
def queue_delete(self, queue, if_unused=True, if_empty=True): |
279 |
self.channel.queue.delete(queue, if_unused, if_empty)
|
280 |
|
281 |
def exchange_delete(self, exchange, if_unused=True): |
282 |
self.channel.exchange.delete(exchange, if_unused)
|
283 |
|
284 |
def basic_class(self): |
285 |
pass
|
286 |
|
287 |
|
288 |
class AMQPConnectionError(): |
289 |
pass
|