lorrystream 0.0.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- lorrystream/__init__.py +1 -0
- lorrystream/cli.py +87 -0
- lorrystream/cmd.py +38 -0
- lorrystream/core.py +215 -0
- lorrystream/exceptions.py +14 -0
- lorrystream/model.py +132 -0
- lorrystream/streamz/__init__.py +0 -0
- lorrystream/streamz/amqp.py +513 -0
- lorrystream/streamz/model.py +148 -0
- lorrystream/streamz/sinks.py +114 -0
- lorrystream/streamz/sources.py +89 -0
- lorrystream/util/__init__.py +0 -0
- lorrystream/util/about.py +120 -0
- lorrystream/util/aio.py +59 -0
- lorrystream/util/cli.py +54 -0
- lorrystream/util/common.py +62 -0
- lorrystream/util/data.py +87 -0
- lorrystream-0.0.2.dist-info/LICENSE +165 -0
- lorrystream-0.0.2.dist-info/METADATA +382 -0
- lorrystream-0.0.2.dist-info/RECORD +23 -0
- lorrystream-0.0.2.dist-info/WHEEL +5 -0
- lorrystream-0.0.2.dist-info/entry_points.txt +9 -0
- lorrystream-0.0.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,513 @@
|
|
|
1
|
+
# Copyright (c) 2009-2021, Tony Garnock-Jones, Gavin M. Roy, Pivotal Software, Inc and others.
|
|
2
|
+
# All rights reserved. Distributed under the terms of a BSD-3-Clause license, see LICENSE.
|
|
3
|
+
#
|
|
4
|
+
# Derived from:
|
|
5
|
+
# https://github.com/pika/pika/blob/1.3.1/examples/asyncio_consumer_example.py
|
|
6
|
+
|
|
7
|
+
# pylint: disable=C0111,C0103,R0205
|
|
8
|
+
|
|
9
|
+
import functools
|
|
10
|
+
import logging
|
|
11
|
+
import time
|
|
12
|
+
import typing as t
|
|
13
|
+
|
|
14
|
+
import pika
|
|
15
|
+
from pika.adapters.asyncio_connection import AsyncioConnection
|
|
16
|
+
from pika.channel import Channel
|
|
17
|
+
from pika.exchange_type import ExchangeType
|
|
18
|
+
|
|
19
|
+
from lorrystream.model import StreamAddress
|
|
20
|
+
|
|
21
|
+
LOG_FORMAT = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) '
|
|
22
|
+
'-35s %(lineno) -5d: %(message)s')
|
|
23
|
+
LOGGER = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class AMQPAdapter:
|
|
27
|
+
"""This is an example consumer that will handle unexpected interactions
|
|
28
|
+
with RabbitMQ such as channel and connection closures.
|
|
29
|
+
|
|
30
|
+
If RabbitMQ closes the connection, this class will stop and indicate
|
|
31
|
+
that reconnection is necessary. You should look at the output, as
|
|
32
|
+
there are limited reasons why the connection may be closed, which
|
|
33
|
+
usually are tied to permission related issues or socket timeouts.
|
|
34
|
+
|
|
35
|
+
If the channel is closed, it will indicate a problem with one of the
|
|
36
|
+
commands that were issued and that should surface in the output as well.
|
|
37
|
+
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(self, address: StreamAddress, on_message: t.Callable = None):
|
|
41
|
+
"""
|
|
42
|
+
Create and maintain a connection to an AMQP broker.
|
|
43
|
+
"""
|
|
44
|
+
LOGGER.info('Creating consumer')
|
|
45
|
+
|
|
46
|
+
self.address = address
|
|
47
|
+
|
|
48
|
+
if "queue" not in self.address.options:
|
|
49
|
+
raise ValueError("Consuming from AMQP requires a queue name")
|
|
50
|
+
|
|
51
|
+
self.queue_name = self.address.options["queue"]
|
|
52
|
+
self.exchange_name = self.address.options.get("exchange", "")
|
|
53
|
+
self.exchange_type = self.address.options.get("exchange-type", "direct")
|
|
54
|
+
self.routing_key = self.address.options.get("routing-key")
|
|
55
|
+
|
|
56
|
+
self.should_reconnect = False
|
|
57
|
+
self.was_consuming = False
|
|
58
|
+
|
|
59
|
+
self._connection: AsyncioConnection
|
|
60
|
+
self._channel: Channel
|
|
61
|
+
self._closing = False
|
|
62
|
+
self._consumer_tag: str
|
|
63
|
+
self._consuming = False
|
|
64
|
+
# In production, experiment with higher prefetch values
|
|
65
|
+
# for higher consumer throughput
|
|
66
|
+
self._prefetch_count = 1_000
|
|
67
|
+
|
|
68
|
+
self.deliver_message = on_message
|
|
69
|
+
|
|
70
|
+
def needs_setup(self, key: str):
|
|
71
|
+
"""
|
|
72
|
+
Whether the URL query parameter ``setup={exchange,queue,bind}`` was specified.
|
|
73
|
+
"""
|
|
74
|
+
if "setup" in self.address.options:
|
|
75
|
+
setup = self.address.options["setup"]
|
|
76
|
+
return key in setup
|
|
77
|
+
return False
|
|
78
|
+
|
|
79
|
+
def connect(self):
|
|
80
|
+
"""This method connects to RabbitMQ, returning the connection handle.
|
|
81
|
+
When the connection is established, the on_connection_open method
|
|
82
|
+
will be invoked by pika.
|
|
83
|
+
|
|
84
|
+
:rtype: pika.adapters.asyncio_connection.AsyncioConnection
|
|
85
|
+
|
|
86
|
+
"""
|
|
87
|
+
LOGGER.info('Connecting to %s', self.address.uri)
|
|
88
|
+
return AsyncioConnection(
|
|
89
|
+
parameters=pika.URLParameters(str(self.address.uri)),
|
|
90
|
+
on_open_callback=self.on_connection_open,
|
|
91
|
+
on_open_error_callback=self.on_connection_open_error,
|
|
92
|
+
on_close_callback=self.on_connection_closed)
|
|
93
|
+
|
|
94
|
+
def close_connection(self):
|
|
95
|
+
self._consuming = False
|
|
96
|
+
if self._connection.is_closing or self._connection.is_closed:
|
|
97
|
+
LOGGER.info('Connection is closing or already closed')
|
|
98
|
+
else:
|
|
99
|
+
LOGGER.info('Closing connection')
|
|
100
|
+
self._connection.close()
|
|
101
|
+
|
|
102
|
+
def on_connection_open(self, _unused_connection):
|
|
103
|
+
"""This method is called by pika once the connection to RabbitMQ has
|
|
104
|
+
been established. It passes the handle to the connection object in
|
|
105
|
+
case we need it, but in this case, we'll just mark it unused.
|
|
106
|
+
|
|
107
|
+
:param pika.adapters.asyncio_connection.AsyncioConnection _unused_connection:
|
|
108
|
+
The connection
|
|
109
|
+
|
|
110
|
+
"""
|
|
111
|
+
LOGGER.info('Connection opened')
|
|
112
|
+
self.open_channel()
|
|
113
|
+
|
|
114
|
+
def on_connection_open_error(self, _unused_connection, err):
|
|
115
|
+
"""This method is called by pika if the connection to RabbitMQ
|
|
116
|
+
can't be established.
|
|
117
|
+
|
|
118
|
+
:param pika.adapters.asyncio_connection.AsyncioConnection _unused_connection:
|
|
119
|
+
The connection
|
|
120
|
+
:param Exception err: The error
|
|
121
|
+
|
|
122
|
+
"""
|
|
123
|
+
LOGGER.error('Connection open failed: %s', err)
|
|
124
|
+
self.reconnect()
|
|
125
|
+
|
|
126
|
+
def on_connection_closed(self, _unused_connection, reason):
|
|
127
|
+
"""This method is invoked by pika when the connection to RabbitMQ is
|
|
128
|
+
closed unexpectedly. Since it is unexpected, we will reconnect to
|
|
129
|
+
RabbitMQ if it disconnects.
|
|
130
|
+
|
|
131
|
+
:param pika.connection.Connection connection: The closed connection obj
|
|
132
|
+
:param Exception reason: exception representing reason for loss of
|
|
133
|
+
connection.
|
|
134
|
+
|
|
135
|
+
"""
|
|
136
|
+
del self._channel
|
|
137
|
+
if self._closing:
|
|
138
|
+
LOGGER.info('Connection closed, stopping i/o loop')
|
|
139
|
+
self._connection.ioloop.stop()
|
|
140
|
+
else:
|
|
141
|
+
LOGGER.warning('Connection closed, reconnect necessary: %s', reason)
|
|
142
|
+
self.reconnect()
|
|
143
|
+
|
|
144
|
+
def reconnect(self):
|
|
145
|
+
"""Will be invoked if the connection can't be opened or is
|
|
146
|
+
closed. Indicates that a reconnect is necessary then stops the
|
|
147
|
+
ioloop.
|
|
148
|
+
|
|
149
|
+
"""
|
|
150
|
+
LOGGER.info('Signalling reconnect')
|
|
151
|
+
self.should_reconnect = True
|
|
152
|
+
self.stop()
|
|
153
|
+
|
|
154
|
+
def open_channel(self):
|
|
155
|
+
"""Open a new channel with RabbitMQ by issuing the Channel.Open RPC
|
|
156
|
+
command. When RabbitMQ responds that the channel is open, the
|
|
157
|
+
on_channel_open callback will be invoked by pika.
|
|
158
|
+
|
|
159
|
+
"""
|
|
160
|
+
LOGGER.info('Creating a new channel')
|
|
161
|
+
self._connection.channel(on_open_callback=self.on_channel_open)
|
|
162
|
+
|
|
163
|
+
def on_channel_open(self, channel):
|
|
164
|
+
"""This method is invoked by pika when the channel has been opened.
|
|
165
|
+
The channel object is passed in so we can make use of it.
|
|
166
|
+
|
|
167
|
+
Since the channel is now open, we'll may declare the exchange to use.
|
|
168
|
+
|
|
169
|
+
:param pika.channel.Channel channel: The channel object
|
|
170
|
+
|
|
171
|
+
"""
|
|
172
|
+
LOGGER.info('Channel opened')
|
|
173
|
+
self._channel = channel
|
|
174
|
+
self.add_on_channel_close_callback()
|
|
175
|
+
self.setup_exchange()
|
|
176
|
+
|
|
177
|
+
def add_on_channel_close_callback(self):
|
|
178
|
+
"""This method tells pika to call the on_channel_closed method if
|
|
179
|
+
RabbitMQ unexpectedly closes the channel.
|
|
180
|
+
|
|
181
|
+
"""
|
|
182
|
+
LOGGER.info('Adding channel close callback')
|
|
183
|
+
self._channel.add_on_close_callback(self.on_channel_closed)
|
|
184
|
+
|
|
185
|
+
def on_channel_closed(self, channel, reason):
|
|
186
|
+
"""Invoked by pika when RabbitMQ unexpectedly closes the channel.
|
|
187
|
+
Channels are usually closed if you attempt to do something that
|
|
188
|
+
violates the protocol, such as re-declare an exchange or queue with
|
|
189
|
+
different parameters. In this case, we'll close the connection
|
|
190
|
+
to shutdown the object.
|
|
191
|
+
|
|
192
|
+
:param pika.channel.Channel: The closed channel
|
|
193
|
+
:param Exception reason: why the channel was closed
|
|
194
|
+
|
|
195
|
+
"""
|
|
196
|
+
LOGGER.warning('Channel %i was closed: %s', channel, reason)
|
|
197
|
+
self.close_connection()
|
|
198
|
+
|
|
199
|
+
def setup_exchange(self):
|
|
200
|
+
"""Set up the exchange on RabbitMQ by invoking the Exchange.Declare RPC
|
|
201
|
+
command. When it is complete, the on_exchange_declareok method will
|
|
202
|
+
be invoked by pika.
|
|
203
|
+
"""
|
|
204
|
+
# Note: using functools.partial is not required, it is demonstrating
|
|
205
|
+
# how arbitrary data can be passed to the callback when it is called
|
|
206
|
+
if self.needs_setup("exchange"):
|
|
207
|
+
LOGGER.info('Declaring exchange: %s', self.exchange_name)
|
|
208
|
+
cb = functools.partial(
|
|
209
|
+
self.on_exchange_declareok, userdata=self.exchange_name)
|
|
210
|
+
self._channel.exchange_declare(
|
|
211
|
+
exchange=self.exchange_name,
|
|
212
|
+
exchange_type=ExchangeType(self.exchange_type),
|
|
213
|
+
callback=cb)
|
|
214
|
+
else:
|
|
215
|
+
self.setup_queue()
|
|
216
|
+
|
|
217
|
+
def on_exchange_declareok(self, _unused_frame, userdata):
|
|
218
|
+
"""Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC
|
|
219
|
+
command.
|
|
220
|
+
|
|
221
|
+
:param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame
|
|
222
|
+
:param str|unicode userdata: Extra user data (exchange name)
|
|
223
|
+
|
|
224
|
+
"""
|
|
225
|
+
LOGGER.info('Exchange declared: %s', userdata)
|
|
226
|
+
self.setup_queue()
|
|
227
|
+
|
|
228
|
+
def setup_queue(self):
|
|
229
|
+
"""Setup the queue on RabbitMQ by invoking the Queue.Declare RPC
|
|
230
|
+
command. When it is complete, the on_queue_declareok method will
|
|
231
|
+
be invoked by pika.
|
|
232
|
+
|
|
233
|
+
"""
|
|
234
|
+
if self.needs_setup("queue"):
|
|
235
|
+
LOGGER.info('Declaring queue %s', self.queue_name)
|
|
236
|
+
cb = functools.partial(self.on_queue_declareok, userdata=self.queue_name)
|
|
237
|
+
self._channel.queue_declare(queue=self.queue_name, callback=cb)
|
|
238
|
+
else:
|
|
239
|
+
self.setup_bind()
|
|
240
|
+
|
|
241
|
+
def on_queue_declareok(self, _unused_frame, userdata):
|
|
242
|
+
"""Method invoked by pika when the Queue.Declare RPC call made in
|
|
243
|
+
setup_queue has completed. We may advance to binding that queue.
|
|
244
|
+
|
|
245
|
+
:param pika.frame.Method _unused_frame: The Queue.DeclareOk frame
|
|
246
|
+
:param str|unicode userdata: Extra user data (queue name)
|
|
247
|
+
|
|
248
|
+
"""
|
|
249
|
+
LOGGER.info('Queue declared: %s', self.queue_name)
|
|
250
|
+
self.setup_bind()
|
|
251
|
+
|
|
252
|
+
def setup_bind(self):
|
|
253
|
+
"""
|
|
254
|
+
Bind the queue and exchange together with the routing key, by issuing
|
|
255
|
+
the Queue.Bind RPC command. When this command is complete, the
|
|
256
|
+
on_bindok method will be invoked by pika.
|
|
257
|
+
:return:
|
|
258
|
+
"""
|
|
259
|
+
if self.needs_setup("bind"):
|
|
260
|
+
LOGGER.info(
|
|
261
|
+
"Binding queue '%s' to exchange '%s' with routing key '%s'",
|
|
262
|
+
self.queue_name, self.exchange_name, self.routing_key
|
|
263
|
+
)
|
|
264
|
+
if self.routing_key is None:
|
|
265
|
+
raise ValueError("When binding a queue, the routing key is required")
|
|
266
|
+
cb = functools.partial(self.on_bindok, userdata=self.queue_name)
|
|
267
|
+
self._channel.queue_bind(
|
|
268
|
+
self.queue_name,
|
|
269
|
+
self.exchange_name,
|
|
270
|
+
routing_key=self.routing_key,
|
|
271
|
+
callback=cb)
|
|
272
|
+
else:
|
|
273
|
+
self.subscribe()
|
|
274
|
+
|
|
275
|
+
def on_bindok(self, _unused_frame, userdata):
|
|
276
|
+
"""Invoked by pika when the Queue.Bind method has completed. At this
|
|
277
|
+
point, we will advance to actually consume messages.
|
|
278
|
+
|
|
279
|
+
:param pika.frame.Method _unused_frame: The Queue.BindOk response frame
|
|
280
|
+
:param str|unicode userdata: Extra user data (queue name)
|
|
281
|
+
|
|
282
|
+
"""
|
|
283
|
+
LOGGER.info('Queue bound: %s', userdata)
|
|
284
|
+
self.subscribe()
|
|
285
|
+
|
|
286
|
+
def subscribe(self):
|
|
287
|
+
"""
|
|
288
|
+
Actually start consuming messages, after setting the prefetch size for this channel.
|
|
289
|
+
"""
|
|
290
|
+
LOGGER.info('Subscribing')
|
|
291
|
+
self.set_qos()
|
|
292
|
+
|
|
293
|
+
def set_qos(self):
|
|
294
|
+
"""This method sets up the consumer prefetch to only be delivered
|
|
295
|
+
one message at a time. The consumer must acknowledge this message
|
|
296
|
+
before RabbitMQ will deliver another one. You should experiment
|
|
297
|
+
with different prefetch values to achieve desired performance.
|
|
298
|
+
|
|
299
|
+
"""
|
|
300
|
+
LOGGER.info('Setting QOS to: %d', self._prefetch_count)
|
|
301
|
+
self._channel.basic_qos(
|
|
302
|
+
prefetch_count=self._prefetch_count, callback=self.on_basic_qos_ok)
|
|
303
|
+
|
|
304
|
+
def on_basic_qos_ok(self, _unused_frame):
|
|
305
|
+
"""Invoked by pika when the Basic.QoS method has completed. At this
|
|
306
|
+
point, we will start consuming messages.
|
|
307
|
+
|
|
308
|
+
:param pika.frame.Method _unused_frame: The Basic.QosOk response frame
|
|
309
|
+
|
|
310
|
+
"""
|
|
311
|
+
LOGGER.info('QOS set to: %d', self._prefetch_count)
|
|
312
|
+
self.start_consuming()
|
|
313
|
+
|
|
314
|
+
def start_consuming(self):
|
|
315
|
+
"""Start consuming messages.
|
|
316
|
+
|
|
317
|
+
This method sets up the consumer by first calling
|
|
318
|
+
add_on_cancel_callback so that the object is notified if RabbitMQ
|
|
319
|
+
cancels the consumer. It then issues the Basic.Consume RPC command
|
|
320
|
+
which returns the consumer tag that is used to uniquely identify the
|
|
321
|
+
consumer with RabbitMQ. We keep the value to use it when we want to
|
|
322
|
+
cancel consuming. The on_message method is passed in as a callback pika
|
|
323
|
+
will invoke when a message is fully received.
|
|
324
|
+
|
|
325
|
+
"""
|
|
326
|
+
LOGGER.info('Issuing consumer related RPC commands')
|
|
327
|
+
self.add_on_cancel_callback()
|
|
328
|
+
LOGGER.info('Start consuming')
|
|
329
|
+
self._consumer_tag = self._channel.basic_consume(
|
|
330
|
+
self.queue_name, self.on_message)
|
|
331
|
+
self._consuming = True
|
|
332
|
+
|
|
333
|
+
def add_on_cancel_callback(self):
|
|
334
|
+
"""Add a callback that will be invoked if RabbitMQ cancels the consumer
|
|
335
|
+
for some reason. If RabbitMQ does cancel the consumer,
|
|
336
|
+
on_consumer_cancelled will be invoked by pika.
|
|
337
|
+
|
|
338
|
+
"""
|
|
339
|
+
LOGGER.info('Adding consumer cancellation callback')
|
|
340
|
+
self._channel.add_on_cancel_callback(self.on_consumer_cancelled)
|
|
341
|
+
|
|
342
|
+
def on_consumer_cancelled(self, method_frame):
|
|
343
|
+
"""Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer
|
|
344
|
+
receiving messages.
|
|
345
|
+
|
|
346
|
+
:param pika.frame.Method method_frame: The Basic.Cancel frame
|
|
347
|
+
|
|
348
|
+
"""
|
|
349
|
+
LOGGER.info('Consumer was cancelled remotely, shutting down: %r',
|
|
350
|
+
method_frame)
|
|
351
|
+
if self._channel:
|
|
352
|
+
self._channel.close()
|
|
353
|
+
|
|
354
|
+
def on_message(self, _unused_channel, basic_deliver, properties, body):
|
|
355
|
+
"""Invoked by pika when a message is delivered from RabbitMQ. The
|
|
356
|
+
channel is passed for your convenience. The basic_deliver object that
|
|
357
|
+
is passed in carries the exchange, routing key, delivery tag and
|
|
358
|
+
a redelivered flag for the message. The properties passed in is an
|
|
359
|
+
instance of BasicProperties with the message properties and the body
|
|
360
|
+
is the message that was sent.
|
|
361
|
+
|
|
362
|
+
:param pika.channel.Channel _unused_channel: The channel object
|
|
363
|
+
:param pika.Spec.Basic.Deliver: basic_deliver method
|
|
364
|
+
:param pika.Spec.BasicProperties: properties
|
|
365
|
+
:param bytes body: The message body
|
|
366
|
+
|
|
367
|
+
"""
|
|
368
|
+
self.was_consuming = True
|
|
369
|
+
LOGGER.info('Received message # %s from %s: %s',
|
|
370
|
+
basic_deliver.delivery_tag, properties.app_id, body)
|
|
371
|
+
if self.deliver_message:
|
|
372
|
+
self.deliver_message(_unused_channel, basic_deliver, properties, body)
|
|
373
|
+
self.acknowledge_message(basic_deliver.delivery_tag)
|
|
374
|
+
|
|
375
|
+
def acknowledge_message(self, delivery_tag):
|
|
376
|
+
"""Acknowledge the message delivery from RabbitMQ by sending a
|
|
377
|
+
Basic.Ack RPC method for the delivery tag.
|
|
378
|
+
|
|
379
|
+
:param int delivery_tag: The delivery tag from the Basic.Deliver frame
|
|
380
|
+
|
|
381
|
+
"""
|
|
382
|
+
LOGGER.info('Acknowledging message %s', delivery_tag)
|
|
383
|
+
self._channel.basic_ack(delivery_tag)
|
|
384
|
+
|
|
385
|
+
def stop_consuming(self):
|
|
386
|
+
"""Tell RabbitMQ that you would like to stop consuming by sending the
|
|
387
|
+
Basic.Cancel RPC command.
|
|
388
|
+
|
|
389
|
+
"""
|
|
390
|
+
if self._channel:
|
|
391
|
+
LOGGER.info('Sending a Basic.Cancel RPC command to RabbitMQ')
|
|
392
|
+
cb = functools.partial(
|
|
393
|
+
self.on_cancelok, userdata=self._consumer_tag)
|
|
394
|
+
self._channel.basic_cancel(self._consumer_tag, cb)
|
|
395
|
+
|
|
396
|
+
def on_cancelok(self, _unused_frame, userdata):
|
|
397
|
+
"""This method is invoked by pika when RabbitMQ acknowledges the
|
|
398
|
+
cancellation of a consumer. At this point we will close the channel.
|
|
399
|
+
This will invoke the on_channel_closed method once the channel has been
|
|
400
|
+
closed, which will in-turn close the connection.
|
|
401
|
+
|
|
402
|
+
:param pika.frame.Method _unused_frame: The Basic.CancelOk frame
|
|
403
|
+
:param str|unicode userdata: Extra user data (consumer tag)
|
|
404
|
+
|
|
405
|
+
"""
|
|
406
|
+
self._consuming = False
|
|
407
|
+
LOGGER.info(
|
|
408
|
+
'RabbitMQ acknowledged the cancellation of the consumer: %s',
|
|
409
|
+
userdata)
|
|
410
|
+
self.close_channel()
|
|
411
|
+
|
|
412
|
+
def close_channel(self):
|
|
413
|
+
"""Call to close the channel with RabbitMQ cleanly by issuing the
|
|
414
|
+
Channel.Close RPC command.
|
|
415
|
+
|
|
416
|
+
"""
|
|
417
|
+
LOGGER.info('Closing the channel')
|
|
418
|
+
self._channel.close()
|
|
419
|
+
|
|
420
|
+
def run(self):
|
|
421
|
+
"""Run the example consumer by connecting to RabbitMQ and then
|
|
422
|
+
starting the IOLoop to block and allow the AsyncioConnection to operate.
|
|
423
|
+
|
|
424
|
+
"""
|
|
425
|
+
LOGGER.info('Starting consumer')
|
|
426
|
+
self._connection = self.connect()
|
|
427
|
+
self._connection.ioloop.run_forever()
|
|
428
|
+
|
|
429
|
+
def stop(self):
|
|
430
|
+
"""Cleanly shutdown the connection to RabbitMQ by stopping the consumer
|
|
431
|
+
with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok
|
|
432
|
+
will be invoked by pika, which will then closing the channel and
|
|
433
|
+
connection. The IOLoop is started again because this method is invoked
|
|
434
|
+
when CTRL-C is pressed raising a KeyboardInterrupt exception. This
|
|
435
|
+
exception stops the IOLoop which needs to be running for pika to
|
|
436
|
+
communicate with RabbitMQ. All of the commands issued prior to starting
|
|
437
|
+
the IOLoop will be buffered but not processed.
|
|
438
|
+
|
|
439
|
+
"""
|
|
440
|
+
if not self._closing:
|
|
441
|
+
self._closing = True
|
|
442
|
+
LOGGER.info('Stopping consumer')
|
|
443
|
+
if self._consuming:
|
|
444
|
+
self.stop_consuming()
|
|
445
|
+
# TODO: Is this wrong on the original?
|
|
446
|
+
# self._connection.ioloop.run_forever() # noqa: ERA001
|
|
447
|
+
self._connection.ioloop.stop()
|
|
448
|
+
else:
|
|
449
|
+
self._connection.ioloop.stop()
|
|
450
|
+
LOGGER.info('Stopped consumer')
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
class ReconnectingAMQPAdapter:
|
|
454
|
+
"""This is an example consumer that will reconnect if the nested
|
|
455
|
+
AMQPAdapter indicates that a reconnect is necessary.
|
|
456
|
+
|
|
457
|
+
"""
|
|
458
|
+
|
|
459
|
+
def __init__(self, address: StreamAddress, on_message: t.Callable = None):
|
|
460
|
+
self.address = address
|
|
461
|
+
self._reconnect_delay = 0
|
|
462
|
+
self._on_message = on_message
|
|
463
|
+
self._consumer = self.consumer_factory()
|
|
464
|
+
|
|
465
|
+
def consumer_factory(self):
|
|
466
|
+
return AMQPAdapter(address=self.address, on_message=self._on_message)
|
|
467
|
+
|
|
468
|
+
def run(self):
|
|
469
|
+
while True:
|
|
470
|
+
try:
|
|
471
|
+
self._consumer.run()
|
|
472
|
+
except KeyboardInterrupt:
|
|
473
|
+
self._consumer.stop()
|
|
474
|
+
break
|
|
475
|
+
self._maybe_reconnect()
|
|
476
|
+
|
|
477
|
+
def stop(self):
|
|
478
|
+
self._consumer.stop()
|
|
479
|
+
|
|
480
|
+
def _maybe_reconnect(self):
|
|
481
|
+
if self._consumer.should_reconnect:
|
|
482
|
+
self._consumer.stop()
|
|
483
|
+
reconnect_delay = self._get_reconnect_delay()
|
|
484
|
+
LOGGER.info('Reconnecting after %d seconds', reconnect_delay)
|
|
485
|
+
time.sleep(reconnect_delay)
|
|
486
|
+
self._consumer = self.consumer_factory()
|
|
487
|
+
|
|
488
|
+
def _get_reconnect_delay(self):
|
|
489
|
+
if self._consumer.was_consuming:
|
|
490
|
+
self._reconnect_delay = 0
|
|
491
|
+
else:
|
|
492
|
+
self._reconnect_delay += 1
|
|
493
|
+
if self._reconnect_delay > 30:
|
|
494
|
+
self._reconnect_delay = 30
|
|
495
|
+
return self._reconnect_delay
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
def main():
|
|
499
|
+
"""
|
|
500
|
+
Demo how to use ``StreamAddress`` and ``ReconnectingAMQPAdapter`` to create a pipeline source element.
|
|
501
|
+
|
|
502
|
+
DATA='{"id": "device-42", "temperature": 42.42, "humidity": "84.84"}'
|
|
503
|
+
echo "${DATA}" | amqp-publish --url='amqp://guest:guest@localhost:5672/%2F' --routing-key=queue-43
|
|
504
|
+
"""
|
|
505
|
+
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)
|
|
506
|
+
amqp_url = "amqp://guest:guest@localhost:5672/%2F?queue=queue-43&setup=queue"
|
|
507
|
+
address = StreamAddress.from_url(amqp_url)
|
|
508
|
+
consumer = ReconnectingAMQPAdapter(address=address)
|
|
509
|
+
consumer.run()
|
|
510
|
+
|
|
511
|
+
|
|
512
|
+
if __name__ == '__main__':
|
|
513
|
+
main()
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import dataclasses
|
|
2
|
+
import typing as t
|
|
3
|
+
from collections import OrderedDict
|
|
4
|
+
|
|
5
|
+
import boltons.urlutils
|
|
6
|
+
import paho.mqtt.client
|
|
7
|
+
from paho.mqtt.client import MQTTMessage
|
|
8
|
+
from pika import BasicProperties
|
|
9
|
+
from pika.spec import Basic, Channel
|
|
10
|
+
from streamz import Stream
|
|
11
|
+
|
|
12
|
+
Universal = t.Optional[t.Any]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclasses.dataclass
|
|
16
|
+
class BusMessageConnection:
|
|
17
|
+
stream: Universal = None
|
|
18
|
+
|
|
19
|
+
# MQTT
|
|
20
|
+
client: Universal = None
|
|
21
|
+
|
|
22
|
+
# AMQP
|
|
23
|
+
channel: Universal = None
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclasses.dataclass
|
|
27
|
+
class BusMessageData:
|
|
28
|
+
# AMQP: basic_deliver, MQTT: `msg` modulo `payload`
|
|
29
|
+
meta: Universal = None
|
|
30
|
+
|
|
31
|
+
# AMQP: properties, MQTT: userdata
|
|
32
|
+
headers: Universal = None
|
|
33
|
+
|
|
34
|
+
# AMQP: body, MQTT: msg
|
|
35
|
+
payload: Universal = None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclasses.dataclass
|
|
39
|
+
class BusMessage:
|
|
40
|
+
"""
|
|
41
|
+
AMQP:
|
|
42
|
+
|
|
43
|
+
- channel
|
|
44
|
+
- basic_deliver
|
|
45
|
+
- properties: https://www.rabbitmq.com/publishers.html#message-properties
|
|
46
|
+
- body
|
|
47
|
+
|
|
48
|
+
MQTT
|
|
49
|
+
|
|
50
|
+
- client
|
|
51
|
+
- userdata
|
|
52
|
+
- msg
|
|
53
|
+
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
connection: BusMessageConnection
|
|
57
|
+
data: BusMessageData
|
|
58
|
+
|
|
59
|
+
@classmethod
|
|
60
|
+
def from_amqp_pika(
|
|
61
|
+
cls,
|
|
62
|
+
stream: Stream,
|
|
63
|
+
channel: Channel,
|
|
64
|
+
basic_deliver: Basic.Deliver,
|
|
65
|
+
properties: BasicProperties,
|
|
66
|
+
body: t.Union[str, bytes],
|
|
67
|
+
):
|
|
68
|
+
"""
|
|
69
|
+
Construct a `BusMessage` instance from Pika's `on_message` callback information.
|
|
70
|
+
|
|
71
|
+
:param stream: Streamz's `Stream` instance.
|
|
72
|
+
:param channel: Pika's channel instance.
|
|
73
|
+
:param basic_deliver: Pika's `Deliver` instance.
|
|
74
|
+
:param properties: Pika's `BasicProperties` instance.
|
|
75
|
+
:param body: Message payload.
|
|
76
|
+
:return:
|
|
77
|
+
"""
|
|
78
|
+
return BusMessage(
|
|
79
|
+
connection=BusMessageConnection(
|
|
80
|
+
stream=stream,
|
|
81
|
+
channel=channel,
|
|
82
|
+
),
|
|
83
|
+
data=BusMessageData(
|
|
84
|
+
meta=cls._pika_delivery_to_dict(basic_deliver),
|
|
85
|
+
headers=cls._pika_properties_to_dict(properties),
|
|
86
|
+
payload=body,
|
|
87
|
+
),
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
@classmethod
|
|
91
|
+
def from_mqtt_paho(
|
|
92
|
+
cls, stream: Stream, client: paho.mqtt.client.Client, userdata: t.Dict, msg: paho.mqtt.client.MQTTMessage
|
|
93
|
+
):
|
|
94
|
+
"""
|
|
95
|
+
Construct a `BusMessage` instance from Paho's `on_message` callback information.
|
|
96
|
+
|
|
97
|
+
:param stream: Streamz's `Stream` instance.
|
|
98
|
+
:param client: Paho's `Client` instance.
|
|
99
|
+
:param userdata: Userdata alongside message.
|
|
100
|
+
:param msg: Paho's `MQTTMessage` instance.
|
|
101
|
+
:return:
|
|
102
|
+
"""
|
|
103
|
+
return BusMessage(
|
|
104
|
+
connection=BusMessageConnection(
|
|
105
|
+
stream=stream,
|
|
106
|
+
client=client,
|
|
107
|
+
),
|
|
108
|
+
data=BusMessageData(
|
|
109
|
+
meta=cls._paho_decode_metadata(msg),
|
|
110
|
+
headers=userdata,
|
|
111
|
+
payload=msg.payload,
|
|
112
|
+
),
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
@staticmethod
|
|
116
|
+
def _pika_delivery_to_dict(basic_deliver) -> t.Dict:
|
|
117
|
+
deliver_slots = ["consumer_tag", "delivery_tag", "redelivered", "exchange", "routing_key"]
|
|
118
|
+
items = OrderedDict()
|
|
119
|
+
for attr in deliver_slots:
|
|
120
|
+
items[attr] = getattr(basic_deliver, attr)
|
|
121
|
+
return items
|
|
122
|
+
|
|
123
|
+
@staticmethod
|
|
124
|
+
def _pika_properties_to_dict(properties) -> t.Dict:
|
|
125
|
+
items = OrderedDict()
|
|
126
|
+
for key, value in properties.__dict__.items():
|
|
127
|
+
if getattr(properties.__class__, key, None) != value:
|
|
128
|
+
items[key] = value
|
|
129
|
+
return items
|
|
130
|
+
|
|
131
|
+
@staticmethod
|
|
132
|
+
def _paho_decode_metadata(msg: MQTTMessage) -> t.Dict:
|
|
133
|
+
header_slots = ["timestamp", "state", "dup", "mid", "topic", "qos", "retain", "info"]
|
|
134
|
+
items = OrderedDict()
|
|
135
|
+
for slot in header_slots:
|
|
136
|
+
items[slot] = getattr(msg, slot)
|
|
137
|
+
return items
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
class URL(boltons.urlutils.URL):
|
|
141
|
+
@property
|
|
142
|
+
def path_unquoted(self):
|
|
143
|
+
"""The URL's path, in text form, not quoted."""
|
|
144
|
+
return "/".join(self.path_parts)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
boltons.urlutils.register_scheme("mqtt", uses_netloc=True, default_port=1883)
|
|
148
|
+
boltons.urlutils.register_scheme("mqtts", uses_netloc=True, default_port=8883)
|