Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def _connect(self, connection_type):
if self.connection:
del self.connection
self.connected = False
parameters = pika.ConnectionParameters(HOST, PORT)
return connection_type(parameters, self._on_connected)
import json
import pika
import sys
import logging
logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser(description='Download results from RabbitMQ server.')
parser.add_argument('--server', dest='server', action='store',
default='localhost',
help='address of the RabbitMQ server (default: localhost)')
parser.add_argument('--noack', dest='noack', action='store_true', default=False,
help='Do not send acknowledgements to the RabbitMQ server (default: disabled)')
args = parser.parse_args()
connection = pika.BlockingConnection(pika.ConnectionParameters(
host=args.server))
channel = connection.channel()
channel.queue_declare(queue='autoexp_output_queue', durable=True)
writer = csv.DictWriter(sys.stdout, fieldnames=autoexp.ids + autoexp.measured)
writer.writeheader()
def all_done():
logging.info("Finished")
connection.close()
sys.exit(0)
def callback(ch, method, properties, body):
try:
logging.debug("Received %r" % (body,))
raise RuntimeError("the 'url' argument cannot be used in conjunction with pika parameters")
if isinstance(url, str) and ";" in url:
self.parameters = [pika.URLParameters(u) for u in url.split(";")]
elif isinstance(url, list):
self.parameters = [pika.URLParameters(u) for u in url]
else:
self.parameters = pika.URLParameters(url)
elif parameters is not None:
if kwargs:
raise RuntimeError("the 'parameters' argument cannot be used in conjunction with other pika parameters")
self.parameters = [pika.ConnectionParameters(**p) for p in parameters]
else:
self.parameters = pika.ConnectionParameters(**kwargs)
self.confirm_delivery = confirm_delivery
self.max_priority = max_priority
self.connections = set()
self.channels = set()
self.queues = set()
self.state = local()
def alertToMessageQueue(alertDict):
try:
connection = pika.BlockingConnection(pika.ConnectionParameters(host=options.mqserver))
channel = connection.channel()
# declare the exchanges
channel.exchange_declare(exchange=options.alertexchange, type='topic', durable=True)
# cherry pick items from the alertDict to send to the alerts messageQueue
mqAlert = dict(severity='INFO', category='')
if 'severity' in alertDict.keys():
mqAlert['severity'] = alertDict['severity']
if 'category' in alertDict.keys():
mqAlert['category'] = alertDict['category']
if 'utctimestamp' in alertDict.keys():
mqAlert['utctimestamp'] = alertDict['utctimestamp']
if 'eventtimestamp' in alertDict.keys():
mqAlert['eventtimestamp'] = alertDict['eventtimestamp']
mqAlert['summary'] = alertDict['summary']
channel.basic_publish(exchange=options.alertexchange, routing_key=options.alertqueue, body=json.dumps(mqAlert))
def __init__(self, queue, host='localhost'):
self.queue = queue
self.connection = pika.BlockingConnection(pika.ConnectionParameters(
host=host))
self.channel = self.connection.channel()
self.channel.queue_declare(queue=self.queue, durable=True)
def main():
import argparse
usage = "ank_measure_client"
parser = argparse.ArgumentParser(description = usage)
parser.add_argument('--hostname', default= "measure_client", help="Hostname for messaging")
parser.add_argument('--server', '-s', default= None, help="RabbitMQ server")
arguments = parser.parse_args()
server = arguments.hostname
try:
pika_host = arguments.server # test if manually specified
except IndexError:
import autonetkit.config as config
pika_host = config.settings['Rabbitmq']['server']
connection = pika.BlockingConnection(pika.ConnectionParameters(
host = pika_host))
channel = connection.channel()
channel.exchange_declare(exchange='measure',
type='direct')
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
channel.queue_bind(exchange='measure',
queue=queue_name,
routing_key = server)
print ' [*] Waiting for messages. To exit press CTRL+C'
def callback(ch, method, properties, body):
def configure(self, pipeline, connection, prefetch):
self.prefetch = prefetch
credentials = pika.credentials.PlainCredentials(
self.service, connection.password)
params = pika.ConnectionParameters(
connection.host, connection.port, pipeline, credentials)
while True:
try:
self.connection = pika.BlockingConnection(parameters=params)
self.channel = self.connection.channel()
break
except Exception as exc:
print(f'Failed pika connection...\n{exc.args}')
time.sleep(RECONNECT_DELAY)
and virtual_host is not None:
credentials = pika.PlainCredentials(user, password)
connection = pika.BlockingConnection(
pika.ConnectionParameters(host=host,
port=int(port),
virtual_host=virtual_host,
credentials=credentials))
if port is not None and user is None and password is None \
and virtual_host is None:
connection = pika.BlockingConnection(
pika.ConnectionParameters(host=host,
port=int(port)))
if port is None and user is None and password is None \
and virtual_host is None:
connection = pika.BlockingConnection(
pika.ConnectionParameters(host=host))
channel = connection.channel()
channel.queue_declare(queue='test')
channel.basic_publish(exchange='',
routing_key='test',
body='Test RabbitMQ to %s successfully'
% service_type)
print " [x] SENT: 'Message test to %s RabbitMQ successfully sent'""" \
% service_type
connection.close()
_receive_rabbitMQ(service_type, host, port, user, password,
virtual_host)
except Exception, e:
#logging.error('RabbitMQ to %s Test Failed...%s' % (service_type, e))
raise Exception('RabbitMQ to %s Test Failed...%s' % (service_type, e))
#!/usr/bin/env python
import pika
connection = pika.BlockingConnection(
pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
channel.basic_consume(
queue='hello', on_message_callback=callback, auto_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
def connectMq():
rabbitmq = json.loads(
open('/etc/sensu/conf.d/rabbitmq.json', 'r').read())['rabbitmq']
credentials = pika.PlainCredentials(rabbitmq['user'], rabbitmq['password'])
connection = pika.BlockingConnection(
pika.ConnectionParameters(rabbitmq['host'],
virtual_host=rabbitmq['vhost'], credentials=credentials))
return connection.channel()