2019-09-17 17:00:45 +00:00
|
|
|
"""
|
|
|
|
Data Transport - 1.0
|
|
|
|
Steve L. Nyemba, The Phi Technology LLC
|
|
|
|
|
|
|
|
This file is a wrapper around rabbitmq server for reading and writing content to a queue (exchange)
|
|
|
|
|
|
|
|
"""
|
2019-09-17 04:08:43 +00:00
|
|
|
import pika
|
|
|
|
from datetime import datetime
|
|
|
|
import re
|
|
|
|
import json
|
|
|
|
import os
|
2019-11-05 03:51:20 +00:00
|
|
|
import sys
|
|
|
|
if sys.version_info[0] > 2 :
|
|
|
|
from transport.common import Reader, Writer
|
|
|
|
else:
|
|
|
|
from common import Reader, Writer
|
2019-09-17 04:08:43 +00:00
|
|
|
import json
|
2022-05-16 16:27:36 +00:00
|
|
|
from multiprocessing import RLock
|
2019-09-17 04:08:43 +00:00
|
|
|
class MessageQueue:
|
|
|
|
"""
|
|
|
|
This class hierarchy is designed to handle interactions with a queue server using pika framework (our tests are based on rabbitmq)
|
|
|
|
:host
|
2019-09-17 16:21:42 +00:00
|
|
|
:xid identifier of the exchange
|
2019-09-17 04:08:43 +00:00
|
|
|
:qid identifier of the queue
|
|
|
|
"""
|
|
|
|
def __init__(self,**params):
|
2020-02-05 21:06:35 +00:00
|
|
|
self.host= 'localhost' if 'host' not in params else params['host'] #-- location of the queue server
|
|
|
|
self.port= 5672 if 'port' not in params else params['port']
|
|
|
|
self.virtual_host = '/' if 'vhost' not in params else params['vhost']
|
|
|
|
self.exchange = params['exchange'] if 'exchange' in params else 'amq.direct' #-- exchange
|
2022-05-16 16:27:36 +00:00
|
|
|
self.queue = params['queue'] if 'queue' in params else 'demo'
|
2020-02-05 21:06:35 +00:00
|
|
|
self.connection = None
|
|
|
|
self.channel = None
|
|
|
|
|
2022-05-16 16:27:36 +00:00
|
|
|
self.name = self.__class__.__name__.lower() if 'name' not in params else params['name']
|
2020-02-06 00:14:30 +00:00
|
|
|
|
2022-05-16 16:27:36 +00:00
|
|
|
username = password = None
|
|
|
|
if 'username' in params :
|
|
|
|
username = params['username']
|
|
|
|
password = params['password']
|
|
|
|
if 'auth_file' in params :
|
|
|
|
_info = json.loads((open(params['auth_file'])).read())
|
|
|
|
username=_info['username']
|
|
|
|
password=_info['password']
|
|
|
|
self.virtual_host = _info['virtual_host'] if 'virtual_host' in _info else self.virtual_host
|
|
|
|
self.exchange = _info['exchange'] if 'exchange' in _info else self.exchange
|
|
|
|
self.queue = _info['queue'] if 'queue' in _info else self.queue
|
2020-02-06 00:14:30 +00:00
|
|
|
|
2020-02-05 21:06:35 +00:00
|
|
|
self.credentials= pika.PlainCredentials('guest','guest')
|
|
|
|
if 'username' in params :
|
|
|
|
self.credentials = pika.PlainCredentials(
|
|
|
|
params['username'],
|
|
|
|
('' if 'password' not in params else params['password'])
|
|
|
|
)
|
2019-09-17 04:08:43 +00:00
|
|
|
|
2020-02-05 21:06:35 +00:00
|
|
|
def init(self,label=None):
|
2022-05-16 16:27:36 +00:00
|
|
|
properties = pika.ConnectionParameters(host=self.host,port=self.port,virtual_host=self.virtual_host,
|
|
|
|
client_properties={'connection_name':self.name},
|
|
|
|
credentials=self.credentials)
|
2020-02-05 21:06:35 +00:00
|
|
|
self.connection = pika.BlockingConnection(properties)
|
|
|
|
self.channel = self.connection.channel()
|
|
|
|
self.info = self.channel.exchange_declare(exchange=self.exchange,exchange_type='direct',durable=True)
|
|
|
|
if label is None:
|
|
|
|
self.qhandler = self.channel.queue_declare(queue=self.queue,durable=True)
|
|
|
|
else:
|
|
|
|
self.qhandler = self.channel.queue_declare(queue=label,durable=True)
|
|
|
|
|
|
|
|
self.channel.queue_bind(exchange=self.exchange,queue=self.qhandler.method.queue)
|
|
|
|
|
2019-09-17 04:08:43 +00:00
|
|
|
def isready(self):
|
|
|
|
#self.init()
|
|
|
|
resp = self.connection is not None and self.connection.is_open
|
2020-02-10 21:48:23 +00:00
|
|
|
# self.close()
|
2019-09-17 04:08:43 +00:00
|
|
|
return resp
|
2020-02-06 00:14:30 +00:00
|
|
|
def finalize(self):
|
|
|
|
pass
|
2019-09-17 04:08:43 +00:00
|
|
|
def close(self):
|
2019-11-05 03:51:20 +00:00
|
|
|
if self.connection.is_closed == False :
|
|
|
|
self.channel.close()
|
|
|
|
self.connection.close()
|
2019-09-17 04:08:43 +00:00
|
|
|
|
|
|
|
class QueueWriter(MessageQueue,Writer):
|
|
|
|
"""
|
|
|
|
This class is designed to publish content to an AMQP (Rabbitmq)
|
|
|
|
The class will rely on pika to implement this functionality
|
|
|
|
|
|
|
|
We will publish information to a given queue for a given exchange
|
|
|
|
"""
|
|
|
|
def __init__(self,**params):
|
|
|
|
#self.host= params['host']
|
2020-02-05 21:06:35 +00:00
|
|
|
#self.exchange = params['uid']
|
|
|
|
#self.queue = params['queue']
|
2019-09-17 04:08:43 +00:00
|
|
|
MessageQueue.__init__(self,**params);
|
2020-02-05 21:06:35 +00:00
|
|
|
self.init()
|
2019-09-17 04:08:43 +00:00
|
|
|
|
|
|
|
|
2020-02-05 21:06:35 +00:00
|
|
|
|
2019-09-17 04:08:43 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
2020-02-06 00:14:30 +00:00
|
|
|
|
|
|
|
def write(self,data,_type='text/plain'):
|
|
|
|
"""
|
2019-09-17 04:08:43 +00:00
|
|
|
This function writes a stream of data to the a given queue
|
|
|
|
@param object object to be written (will be converted to JSON)
|
|
|
|
@TODO: make this less chatty
|
2020-02-06 00:14:30 +00:00
|
|
|
"""
|
2022-05-16 16:27:36 +00:00
|
|
|
|
2020-02-05 21:06:35 +00:00
|
|
|
stream = json.dumps(data) if isinstance(data,dict) else data
|
2019-09-17 04:08:43 +00:00
|
|
|
self.channel.basic_publish(
|
2020-02-05 21:06:35 +00:00
|
|
|
exchange=self.exchange,
|
|
|
|
routing_key=self.queue,
|
2019-09-17 04:08:43 +00:00
|
|
|
body=stream,
|
2020-02-05 21:06:35 +00:00
|
|
|
properties=pika.BasicProperties(content_type=_type,delivery_mode=2)
|
2019-09-17 04:08:43 +00:00
|
|
|
);
|
2020-02-05 21:06:35 +00:00
|
|
|
# self.close()
|
2019-09-17 04:08:43 +00:00
|
|
|
|
2020-02-05 21:06:35 +00:00
|
|
|
def flush(self):
|
|
|
|
self.init()
|
2019-09-17 04:08:43 +00:00
|
|
|
_mode = 1 #-- Non persistent
|
2020-02-05 21:06:35 +00:00
|
|
|
self.channel.queue_delete( queue=self.queue);
|
2019-09-17 04:08:43 +00:00
|
|
|
self.close()
|
|
|
|
|
|
|
|
class QueueReader(MessageQueue,Reader):
|
|
|
|
"""
|
|
|
|
This class will read from a queue provided an exchange, queue and host
|
|
|
|
@TODO: Account for security and virtualhosts
|
|
|
|
"""
|
|
|
|
|
|
|
|
def __init__(self,**params):
|
|
|
|
"""
|
|
|
|
@param host host
|
|
|
|
@param uid exchange identifier
|
|
|
|
@param qid queue identifier
|
|
|
|
"""
|
|
|
|
|
|
|
|
#self.host= params['host']
|
2020-02-05 21:06:35 +00:00
|
|
|
#self.exchange = params['uid']
|
|
|
|
#self.queue = params['qid']
|
2019-09-17 04:08:43 +00:00
|
|
|
MessageQueue.__init__(self,**params);
|
2020-03-04 08:23:21 +00:00
|
|
|
# self.init()
|
2022-05-16 16:27:36 +00:00
|
|
|
self.durable = False if 'durable' not in params else params['durable']
|
|
|
|
# if 'durable' in params :
|
|
|
|
# self.durable = True
|
|
|
|
# else:
|
|
|
|
# self.durable = False
|
2019-09-17 04:08:43 +00:00
|
|
|
self.size = -1
|
|
|
|
self.data = {}
|
2020-02-05 21:06:35 +00:00
|
|
|
# def init(self,qid):
|
2019-09-17 04:08:43 +00:00
|
|
|
|
2020-02-05 21:06:35 +00:00
|
|
|
# properties = pika.ConnectionParameters(host=self.host)
|
|
|
|
# self.connection = pika.BlockingConnection(properties)
|
|
|
|
# self.channel = self.connection.channel()
|
|
|
|
# self.channel.exchange_declare(exchange=self.exchange,type='direct',durable=True)
|
2019-09-17 04:08:43 +00:00
|
|
|
|
2020-02-05 21:06:35 +00:00
|
|
|
# self.info = self.channel.queue_declare(queue=qid,durable=True)
|
2019-09-17 04:08:43 +00:00
|
|
|
|
|
|
|
|
|
|
|
def callback(self,channel,method,header,stream):
|
|
|
|
"""
|
|
|
|
This is the callback function designed to process the data stream from the queue
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
r = []
|
2022-05-16 16:27:36 +00:00
|
|
|
# if re.match("^\{|\[",stream) is not None:
|
|
|
|
if stream.startswith(b'{') or stream.startswith(b'['):
|
2019-09-17 04:08:43 +00:00
|
|
|
r = json.loads(stream)
|
|
|
|
else:
|
|
|
|
|
|
|
|
r = stream
|
|
|
|
|
2020-03-02 17:33:35 +00:00
|
|
|
qid = self.qhandler.method.queue
|
2019-09-17 04:08:43 +00:00
|
|
|
if qid not in self.data :
|
|
|
|
self.data[qid] = []
|
|
|
|
|
|
|
|
self.data[qid].append(r)
|
|
|
|
#
|
|
|
|
# We stop reading when the all the messages of the queue are staked
|
|
|
|
#
|
|
|
|
if self.size == len(self.data[qid]) or len(self.data[qid]) == self.info.method.message_count:
|
|
|
|
self.close()
|
|
|
|
|
2020-05-18 02:57:18 +00:00
|
|
|
def read(self,**args):
|
2019-09-17 04:08:43 +00:00
|
|
|
"""
|
|
|
|
This function will read, the first message from a queue
|
|
|
|
@TODO:
|
|
|
|
Implement channel.basic_get in order to retrieve a single message at a time
|
|
|
|
Have the number of messages retrieved be specified by size (parameter)
|
|
|
|
"""
|
|
|
|
r = {}
|
2020-05-18 02:57:18 +00:00
|
|
|
self.size = -1 if 'size' in args else int(args['size'])
|
2019-09-17 04:08:43 +00:00
|
|
|
#
|
|
|
|
# We enabled the reader to be able to read from several queues (sequentially for now)
|
|
|
|
# The qid parameter will be an array of queues the reader will be reading from
|
|
|
|
#
|
2020-02-05 21:06:35 +00:00
|
|
|
if isinstance(self.queue,str) :
|
|
|
|
self.queue = [self.queue]
|
2020-03-04 08:23:21 +00:00
|
|
|
|
2020-02-05 21:06:35 +00:00
|
|
|
for qid in self.queue:
|
2019-09-17 04:08:43 +00:00
|
|
|
self.init(qid)
|
|
|
|
# r[qid] = []
|
|
|
|
|
2020-03-02 17:33:35 +00:00
|
|
|
if self.qhandler.method.message_count > 0:
|
2019-09-17 04:08:43 +00:00
|
|
|
|
2020-03-04 08:23:21 +00:00
|
|
|
self.channel.basic_consume(queue=qid,on_message_callback=self.callback,auto_ack=False);
|
2019-09-17 04:08:43 +00:00
|
|
|
self.channel.start_consuming()
|
|
|
|
else:
|
|
|
|
|
|
|
|
pass
|
|
|
|
#self.close()
|
|
|
|
# r[qid].append( self.data)
|
|
|
|
|
|
|
|
return self.data
|
2020-02-06 00:14:30 +00:00
|
|
|
class QueueListener(MessageQueue):
|
2022-05-16 16:27:36 +00:00
|
|
|
lock = RLock()
|
2020-02-05 21:06:35 +00:00
|
|
|
"""
|
|
|
|
This class is designed to have an active listener (worker) against a specified Exchange/Queue
|
|
|
|
It is initialized as would any other object and will require a callback function to address the objects returned.
|
|
|
|
"""
|
2020-02-06 00:14:30 +00:00
|
|
|
def __init__(self,**args):
|
|
|
|
MessageQueue.__init__(self,**args)
|
|
|
|
self.listen = self.read
|
2022-05-11 16:17:27 +00:00
|
|
|
self.apply = args['apply'] if 'apply' in args else print
|
2022-05-16 16:27:36 +00:00
|
|
|
self.lock = False if 'lock' not in args else args['lock']
|
2020-02-06 00:14:30 +00:00
|
|
|
|
|
|
|
def finalize(self,channel,ExceptionReason):
|
|
|
|
pass
|
2022-05-11 16:17:27 +00:00
|
|
|
|
2020-02-05 21:06:35 +00:00
|
|
|
def callback(self,channel,method,header,stream) :
|
2022-05-11 16:17:27 +00:00
|
|
|
_info= {}
|
|
|
|
# if re.match("^\{|\[",stream) is not None:
|
|
|
|
|
2022-05-16 16:27:36 +00:00
|
|
|
|
2022-05-11 16:17:27 +00:00
|
|
|
if stream.startswith(b"[") or stream.startswith(b"{"):
|
|
|
|
_info = json.loads(stream)
|
|
|
|
else:
|
|
|
|
|
|
|
|
_info = stream
|
2022-05-16 16:27:36 +00:00
|
|
|
#
|
|
|
|
# At this point we should invoke the apply function with a lock if need be
|
|
|
|
# @TODO: Establish a vocabulary
|
|
|
|
|
|
|
|
if stream == b'QUIT' :
|
|
|
|
# channel.exit()
|
|
|
|
self.close()
|
|
|
|
if self.lock == True :
|
|
|
|
QueueListener.lock.acquire()
|
|
|
|
try:
|
|
|
|
#
|
|
|
|
# In case the user has not specified a function to apply the data against, it will simply be printed
|
|
|
|
#
|
|
|
|
self.apply(_info)
|
|
|
|
except Exception as e:
|
|
|
|
pass
|
|
|
|
if self.lock == True :
|
|
|
|
QueueListener.lock.release()
|
2019-09-17 04:08:43 +00:00
|
|
|
def read(self):
|
|
|
|
|
2020-02-05 21:06:35 +00:00
|
|
|
self.init(self.queue)
|
2020-02-06 00:14:30 +00:00
|
|
|
|
2020-02-05 21:06:35 +00:00
|
|
|
self.channel.basic_consume(self.queue,self.callback,auto_ack=True);
|
2019-09-17 04:08:43 +00:00
|
|
|
self.channel.start_consuming()
|
2020-02-06 00:14:30 +00:00
|
|
|
|
|
|
|
|
2019-11-05 03:51:20 +00:00
|
|
|
|
2022-05-16 16:27:36 +00:00
|
|
|
class Factory :
|
|
|
|
@staticmethod
|
|
|
|
def instance(**_args):
|
|
|
|
"""
|
|
|
|
:param count number of workers
|
|
|
|
:param apply function workers
|
|
|
|
"""
|
|
|
|
_apply = _args['apply']
|
|
|
|
_count = _args['count']
|
|
|
|
for i in np.arange(_count) :
|
|
|
|
_name = _args['name'] if 'name' in _args else 'worker_'+str(i)
|
|
|
|
transport.factory.instance(provider="rabbit",context="listener",apply=_apply,auth_file=_args['auth_file'])
|