Python pika.ConnectionParameters() Examples

The following are 30 code examples of pika.ConnectionParameters(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pika , or try the search function .
Example #1
Source File: amqp_async_consumer.py    From resilient-community-apps with MIT License 8 votes vote down vote up
def connect(self):
        """This method connects to RabbitMQ, returning the connection handle.
        When the connection is established, the on_connection_open method
        will be invoked by pika.

        :rtype: pika.SelectConnection

        """
        try:
            log.info('Connecting to %s', self._url)
            return pika.SelectConnection(
                        pika.ConnectionParameters(
                            host=self._host,
                            port=self._port,
                            virtual_host=self._virtual_host,
                            credentials=pika.PlainCredentials(self._username, self._amqp_password),
                            heartbeat_interval=600,
                            blocked_connection_timeout=300),
                        self.on_connection_open,
                        stop_ioloop_on_close=False,
                        )
        except AMQPConnectionError:
            raise ValueError("Error connecting to the AMQP instance, double check credentials and any proxy settings") 
Example #2
Source File: scmb.py    From oneview-redfish-toolkit with Apache License 2.0 6 votes vote down vote up
def scmb_connect(self):
        scmb_server = self.ov_ip

        # Setup our ssl options
        ssl_options = ({'ca_certs': _oneview_ca_path(self.ov_ip),
                        'certfile': _scmb_cert_path(self.ov_ip),
                        'keyfile': _scmb_key_path(self.ov_ip),
                        'cert_reqs': ssl.CERT_REQUIRED,
                        'server_side': False})

        scmb_connection = pika.BlockingConnection(
            pika.ConnectionParameters(
                scmb_server,
                SCMB_PORT,
                credentials=ExternalCredentials(),
                socket_timeout=SCMB_SOCKET_TIMEOUT,
                ssl=True,
                ssl_options=ssl_options))

        return scmb_connection 
Example #3
Source File: server.py    From gentun with Apache License 2.0 6 votes vote down vote up
def __init__(self, jobs, responses, host='localhost', port=5672,
                 user='guest', password='guest', rabbit_queue='rpc_queue'):
        # Set connection and channel
        self.credentials = pika.PlainCredentials(user, password)
        self.parameters = pika.ConnectionParameters(host, port, '/', self.credentials)
        self.connection = pika.BlockingConnection(self.parameters)
        self.channel = self.connection.channel()
        # Set queue for jobs and callback queue for responses
        result = self.channel.queue_declare(exclusive=True)
        self.callback_queue = result.method.queue
        self.channel.basic_consume(self.on_response, no_ack=True, queue=self.callback_queue)
        self.rabbit_queue = rabbit_queue
        self.channel.queue_declare(queue=self.rabbit_queue)
        self.response = None
        self.id = None
        # Local queues shared between threads
        self.jobs = jobs
        self.responses = responses
        # Report to the RabbitMQ server
        heartbeat_thread = threading.Thread(target=self.heartbeat)
        heartbeat_thread.daemon = True
        heartbeat_thread.start() 
Example #4
Source File: rpc_server.py    From ab-2018 with GNU General Public License v3.0 6 votes vote down vote up
def connect(self):
        """This method connects to RabbitMQ, returning the connection handle.
        When the connection is established, the on_connection_open method
        will be invoked by pika.

        :rtype: pika.SelectConnection

        """
        return pika.SelectConnection(
            pika.ConnectionParameters(
                host='localhost',
                virtual_host=self.VIRTUAL_HOST,
                credentials=self.CREDENTIALS
            ),
            self.on_connection_open,
            stop_ioloop_on_close=False
        ) 
Example #5
Source File: SendData.py    From AIOPS_PLATFORM with MIT License 6 votes vote down vote up
def sendData(self, server, queue, ci, data):
        self.logger.debug('Sending [{}] to [{}] Start'.format(ci, server))
        ## conn = pika.BlockingConnection(
                    ## pika.ConnectionParameters(server)
                ## )

        with pika.BlockingConnection(pika.ConnectionParameters(host = server,
                                        port = self.MQ_PORT)) as conn:
            for line in data:
                chan = conn.channel()
                chan.queue_declare(queue = queue, durable = True)
                chan.basic_publish(exchange = '', routing_key = queue, body = line,
                                    properties = pika.BasicProperties(delivery_mode = 2, ))
        self.logger.debug('Sending [{}] to [{}] Done'.format(ci, server))
        return(True)

    ## run func 
Example #6
Source File: main.py    From poseidon with Apache License 2.0 6 votes vote down vote up
def _connect_rabbit():
        # Rabbit settings
        exchange = 'topic-poseidon-internal'
        exchange_type = 'topic'

        # Starting rabbit connection
        connection = pika.BlockingConnection(
            pika.ConnectionParameters(host='RABBIT_SERVER')
        )

        channel = connection.channel()
        channel.exchange_declare(
            exchange=exchange, exchange_type=exchange_type
        )

        return channel, exchange, connection 
Example #7
Source File: worker.py    From poseidon with Apache License 2.0 6 votes vote down vote up
def main(queue_name, host):  # pragma: no cover
    """Creates the connection to RabbitMQ as a consumer and binds to the queue
    waiting for messages
    """
    counter = 0
    while True:
        counter += 1
        try:
            params = pika.ConnectionParameters(host=host, port=5672)
            connection = pika.BlockingConnection(params)
            channel = connection.channel()
            print('Connected to rabbit')
            channel.queue_declare(queue=queue_name, durable=True)
            channel.basic_qos(prefetch_count=1)
            channel.basic_consume(
                queue=queue_name, on_message_callback=callback)
            channel.start_consuming()
        except Exception as e:  # pragma: no cover
            print(str(e))
            print(
                'Waiting for connection to rabbit...attempt: {0}'.format(counter))
        time.sleep(1)

    return 
Example #8
Source File: amqp_client.py    From cloudify-plugins-common with Apache License 2.0 6 votes vote down vote up
def __init__(self,
                 amqp_user,
                 amqp_pass,
                 amqp_host,
                 amqp_vhost,
                 ssl_enabled,
                 ssl_cert_path):
        self.connection = None
        self.channel = None
        self._is_closed = False
        credentials = pika.credentials.PlainCredentials(
            username=amqp_user,
            password=amqp_pass)
        ssl_options = utils.internal.get_broker_ssl_options(ssl_enabled,
                                                            ssl_cert_path)
        self._connection_parameters = pika.ConnectionParameters(
            host=amqp_host,
            port=BROKER_PORT_SSL if ssl_enabled else BROKER_PORT_NO_SSL,
            virtual_host=amqp_vhost,
            socket_timeout=self.SOCKET_TIMEOUT,
            connection_attempts=self.CONNECTION_ATTEMPTS,
            credentials=credentials,
            ssl=bool(ssl_enabled),
            ssl_options=ssl_options)
        self._connect() 
Example #9
Source File: MessageInterface.py    From pilot with Apache License 2.0 6 votes vote down vote up
def create_connection_parameters(self):
        tolog("MQ ARGO: create connection parameters, server = " + self.host + " port = " + str(self.port))
        # need to set credentials to login to the message server
        #self.credentials = pika.PlainCredentials(self.username,self.password)
        self.credentials = pika.credentials.ExternalCredentials()
        ssl_options_dict = {
                            "certfile":  self.ssl_cert,
                            "keyfile":   self.ssl_key,
                            "ca_certs":  self.ssl_ca_certs,
                            "cert_reqs": ssl.CERT_REQUIRED,
                           }
    
                            
        #logger.debug(str(ssl_options_dict))
        # setup our connection parameters
        self.parameters = pika.ConnectionParameters(
                                                    host               = self.host,
                                                    port               = self.port,
                                                    virtual_host       = self.virtual_host,
                                                    credentials        = self.credentials,
                                                    socket_timeout     = self.socket_timeout,
                                                    ssl                = True,
                                                    ssl_options        = ssl_options_dict,
                                                   ) 
Example #10
Source File: rabbit.py    From faucet with Apache License 2.0 6 votes vote down vote up
def rabbit_conn(self):
        """Make connection to rabbit to send events"""
        # check if a rabbit host was specified
        if not self.host:
            print('Not connecting to any RabbitMQ, host is None.')  # pylint: disable=print-statement
            return False

        # create connection to rabbit
        params = pika.ConnectionParameters(host=self.host,
                                           port=self.port,
                                           heartbeat=600,
                                           blocked_connection_timeout=300)
        try:
            self.channel = pika.BlockingConnection(params).channel()
            self.channel.exchange_declare(exchange=self.exchange,
                                          exchange_type=self.exchange_type)
        except (pika.exceptions.AMQPError, socket.gaierror, OSError) as err:
            print("Unable to connect to RabbitMQ at %s:%s because: %s" %
                  (self.host, self.port, err))  # pylint: disable=print-statement
            return False
        print("Connected to RabbitMQ at %s:%s" % (self.host, self.port))  # pylint: disable=print-statement
        return True 
Example #11
Source File: example_consumer.py    From faucet with Apache License 2.0 6 votes vote down vote up
def main():
    """Creates the connection to RabbitMQ as a consumer and binds to the queue
    waiting for messages
    """
    params = pika.ConnectionParameters(host="0.0.0.0", port=5672)
    connection = pika.BlockingConnection(params)
    channel = connection.channel()

    channel.exchange_declare(exchange='topic_recs', exchange_type='topic')
    result = channel.queue_declare()
    queue_name = result.method.queue

    binding_key = "FAUCET.Event"
    channel.queue_bind(exchange='topic_recs',
                       queue=queue_name,
                       routing_key=binding_key)

    return channel, queue_name 
Example #12
Source File: MultiTopicConsumer.py    From ChaosTestingCode with MIT License 6 votes vote down vote up
def connect(self):
        try:
            self.connected_node = self.broker_manager.get_current_node(self.consumer_id)
            ip = self.broker_manager.get_node_ip(self.connected_node)
            console_out(f"Connecting to {self.connected_node}", self.get_actor())
            credentials = pika.PlainCredentials('jack', 'jack')
            parameters = pika.ConnectionParameters(ip,
                                                self.broker_manager.get_consumer_port(self.connected_node, self.consumer_id),
                                                '/',
                                                credentials)
            self.connection = pika.BlockingConnection(parameters)
            self.channel = self.connection.channel()

            if self.prefetch > 0:
                self.channel.basic_qos(prefetch_count=self.prefetch)

            return True
        except Exception as e:
            console_out_exception("Failed trying to connect.", e, self.get_actor())
            return False 
Example #13
Source File: test_amqp_racknode.py    From RackHD with Apache License 2.0 6 votes vote down vote up
def __init__(self, exchange_name, topic_routing_key, external_callback, timeout=10):
        threading.Thread.__init__(self)
        pika_logger = logging.getLogger('pika')
        if fit_common.VERBOSITY >= 8:
            pika_logger.setLevel(logging.DEBUG)
        elif fit_common.VERBOSITY >= 4:
            pika_logger.setLevel(logging.WARNING)
        else:
            pika_logger.setLevel(logging.ERROR)
        amqp_port = fit_common.fitports()['amqp_ssl']
        self.connection = pika.BlockingConnection(
            pika.ConnectionParameters(host=fit_common.fitargs()["ora"], port=amqp_port))
        self.channel = self.connection.channel()
        # self.channel.basic_qos(prefetch_count=1)
        result = self.channel.queue_declare(exclusive=True)
        queue_name = result.method.queue
        self.channel.queue_bind(
            exchange=exchange_name,
            queue=queue_name,
            routing_key=topic_routing_key)
        self.channel.basic_consume(external_callback, queue=queue_name)
        self.connection.add_timeout(timeout, self.dispose) 
Example #14
Source File: queue.py    From n6 with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_connection_params_dict(cls):
        """
        Get the AMQP connection parameters (as a dict)
        using n6lib.amqp_helpers.get_amqp_connection_params_dict()
        and the `SOCKET_TIMEOUT` class constant.

        Returns:
            A dict that can be used as **kwargs for pika.ConnectionParameters.
        """
        conn_params_dict = get_amqp_connection_params_dict(cls.rabbitmq_config_section)
        conn_params_dict.update(
                socket_timeout=cls.SOCKET_TIMEOUT,
        )
        return conn_params_dict


    #
    # Regular instance methods

    # Start/stop-related stuff: 
Example #15
Source File: amqp_facade.py    From resilient-community-apps with MIT License 6 votes vote down vote up
def __init__(self, host, virtual_host, username, amqp_password, port):
        self.DEFAULT_PORT = 5672

        self.connection = pika.BlockingConnection(
            pika.ConnectionParameters(
                host=host,
                port=int(port) if not isinstance(port, type(None)) else self.DEFAULT_PORT,  # Use provided port no or default if provided port is falsey
                virtual_host=virtual_host,
                credentials=pika.PlainCredentials(username, amqp_password)
            ))

        self.channel = self.connection.channel()

        result = self.channel.queue_declare(exclusive=True)
        self.callback_queue = result.method.queue

        self.channel.basic_consume(self.on_response, no_ack=True,
                                   queue=self.callback_queue) 
Example #16
Source File: queue.py    From daf-recipes with GNU General Public License v3.0 6 votes vote down vote up
def get_connection_amqp():
    try:
        port = int(config.get('ckan.harvest.mq.port', PORT))
    except ValueError:
        port = PORT
    userid = config.get('ckan.harvest.mq.user_id', USERID)
    password = config.get('ckan.harvest.mq.password', PASSWORD)
    hostname = config.get('ckan.harvest.mq.hostname', HOSTNAME)
    virtual_host = config.get('ckan.harvest.mq.virtual_host', VIRTUAL_HOST)

    credentials = pika.PlainCredentials(userid, password)
    parameters = pika.ConnectionParameters(host=hostname,
                                           port=port,
                                           virtual_host=virtual_host,
                                           credentials=credentials,
                                           frame_max=10000)
    log.debug("pika connection using %s" % parameters.__dict__)

    return pika.BlockingConnection(parameters) 
Example #17
Source File: mqtt.py    From cloudbrain with GNU Affero General Public License v3.0 6 votes vote down vote up
def _setup_mqtt_channel(username, password, host, vhost, exchange, routing_key,
                        queue_name):
    credentials = pika.PlainCredentials(username, password)
    connection = pika.BlockingConnection(
        pika.ConnectionParameters(host=host,
                                  credentials=credentials,
                                  virtual_host=vhost))
    channel = connection.channel()

    channel.exchange_declare(exchange=exchange, exchange_type='topic',
                             durable=True)

    result = channel.queue_declare(queue_name, exclusive=True)
    queue_name = result.method.queue

    channel.queue_bind(exchange=exchange,
                       queue=queue_name,
                       routing_key=routing_key)
    return channel 
Example #18
Source File: PubSubConsumer.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
def connect(self):
        """This method connects to RabbitMQ, returning the connection handle.
        When the connection is established, the on_connection_open method
        will be invoked by pika.

        :rtype: pika.SelectConnection

        """
        self.logger.info('Connecting to %s', self._prefix)
        account = 'opensuse'
        server = 'rabbit.opensuse.org'
        if self._prefix == 'suse':
            account = 'suse'
            server = 'rabbit.suse.de'
        credentials = pika.PlainCredentials(account, account)
        context = ssl.create_default_context()
        ssl_options = pika.SSLOptions(context, server)
        parameters = pika.ConnectionParameters(server, 5671, '/', credentials, ssl_options=ssl_options, socket_timeout=10)
        return pika.SelectConnection(parameters,
                                     on_open_callback=self.on_connection_open) 
Example #19
Source File: PubSubConsumer.py    From openSUSE-release-tools with GNU General Public License v2.0 6 votes vote down vote up
def connect(self):
        """This method connects to RabbitMQ, returning the connection handle.
        When the connection is established, the on_connection_open method
        will be invoked by pika.

        :rtype: pika.SelectConnection

        """
        self.logger.info('Connecting to %s', self._prefix)
        account = 'opensuse'
        server = 'rabbit.opensuse.org'
        if self._prefix == 'suse':
            account = 'suse'
            server = 'rabbit.suse.de'
        credentials = pika.PlainCredentials(account, account)
        context = ssl.create_default_context()
        ssl_options = pika.SSLOptions(context, server)
        parameters = pika.ConnectionParameters(server, 5671, '/', credentials, ssl_options=ssl_options, socket_timeout=10)
        return pika.SelectConnection(parameters,
                                     on_open_callback=self.on_connection_open) 
Example #20
Source File: handler_amqp.py    From python3-logstash with MIT License 6 votes vote down vote up
def __init__(self, host, port, username, password, virtual_host, exchange,
                routing_key, durable, exchange_type):

        # create connection parameters
        credentials = pika.PlainCredentials(username, password)
        parameters = pika.ConnectionParameters(host, port, virtual_host,
                                               credentials)

        # create connection & channel
        self.connection = pika.BlockingConnection(parameters)
        self.channel = self.connection.channel()

        # create an exchange, if needed
        self.channel.exchange_declare(exchange=exchange,
                                      exchange_type=exchange_type,
                                      durable=durable)

        # needed when publishing
        self.spec = pika.spec.BasicProperties(delivery_mode=2)
        self.routing_key = routing_key
        self.exchange = exchange 
Example #21
Source File: dispatcher.py    From listenbrainz-server with GNU General Public License v2.0 5 votes vote down vote up
def init_rabbitmq_connection(self):
        while True:
            try:
                credentials = pika.PlainCredentials(current_app.config['RABBITMQ_USERNAME'], current_app.config['RABBITMQ_PASSWORD'])
                connection_parameters = pika.ConnectionParameters(
                    host=current_app.config['RABBITMQ_HOST'],
                    port=current_app.config['RABBITMQ_PORT'],
                    virtual_host=current_app.config['RABBITMQ_VHOST'],
                    credentials=credentials,
                )
                self.connection = pika.SelectConnection(parameters=connection_parameters, on_open_callback=self.on_open)
                break
            except Exception as e:
                current_app.logger.error("Error while connecting to RabbitMQ: %s", str(e), exc_info=True)
                time.sleep(3) 
Example #22
Source File: RabbitMq.py    From sgx-kms with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        credentials = self.init_env_variables()
        self.credentials = pika.PlainCredentials(credentials['username'], 
                                                   credentials['password'])
        self.params = pika.ConnectionParameters(credentials['host'], 
                                                 int(credentials['port']), 
                                                  credentials['virtual_host'], 
                                                  self.credentials)
        self.connection = pika.BlockingConnection(self.params)
        self.channel = self.connection.channel()

    #Function to publish message using RabbitMq 
Example #23
Source File: server.py    From ab-2018 with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        super(SubscriptionList, self).__init__()
        self.redis_client = redis.Redis(host=REDIS_HOST, port=REDIS_PORT)
        connection = pika.BlockingConnection(
            pika.ConnectionParameters(
                host=RABBIT_HOST,
                virtual_host=VIRTUAL_HOST,
                credentials=pika.PlainCredentials(RABBIT_USER, RABBIT_PASSWORD)
            )
        )

        self.channel = connection.channel()

        self.channel.queue_declare(queue=QUEUE_NAME, durable=True) 
Example #24
Source File: main.py    From SecPi with GNU General Public License v3.0 5 votes vote down vote up
def connect(self, num_tries=3):
		credentials = pika.PlainCredentials(config.get('rabbitmq')['user'], config.get('rabbitmq')['password'])
		parameters = pika.ConnectionParameters(credentials=credentials,
			host=config.get('rabbitmq')['master_ip'],
			port=5671,
			ssl=True,
			socket_timeout=10,
			ssl_options = {
				"ca_certs":PROJECT_PATH+"/certs/"+config.get('rabbitmq')['cacert'],
				"certfile":PROJECT_PATH+"/certs/"+config.get('rabbitmq')['certfile'],
				"keyfile":PROJECT_PATH+"/certs/"+config.get('rabbitmq')['keyfile']
			}
		)

		connected = False
		while not connected and num_tries > 0:
			try:
				cherrypy.log("Trying to connect to rabbitmq service...")
				self.connection = pika.BlockingConnection(parameters=parameters)
				self.channel = self.connection.channel()
				connected = True
				cherrypy.log("Connection to rabbitmq service established")
			#except pika.exceptions.AMQPConnectionError as pe:
			except Exception as e:
				cherrypy.log("Error connecting to Queue! %s" % e, traceback=True)
				num_tries-=1
				time.sleep(30)

		if not connected:
			return False
		# define exchange
		self.channel.exchange_declare(exchange=utils.EXCHANGE, exchange_type='direct')

		# define queues
		self.channel.queue_declare(queue=utils.QUEUE_ON_OFF)
		self.channel.queue_bind(exchange=utils.EXCHANGE, queue=utils.QUEUE_ON_OFF)
		return True 
Example #25
Source File: consumers.py    From FFXIVBOT with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, username="guest", password="guest", queue="ffxivbot"):
        # print("initializing pika publisher")
        self.credentials = pika.PlainCredentials(username, password)
        self.queue = queue
        self.parameters = pika.ConnectionParameters(
            "127.0.0.1", 5672, "/", self.credentials, heartbeat=0
        )
        self.connection = pika.BlockingConnection(self.parameters)
        self.channel = self.connection.channel()
        self.priority_queue = {"x-max-priority": 20, "x-message-ttl": 60000}
        self.channel.queue_declare(queue=self.queue, arguments=self.priority_queue) 
Example #26
Source File: broadcast_message_producer.py    From whatsapp_automation with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        rhost = configp.get('rabbitmq', 'ip')
        username = configp.get('rabbitmq', 'username')
        password = configp.get('rabbitmq', 'password')
        credentials = pika.PlainCredentials(username, password)
        parameters = pika.ConnectionParameters(rhost,5672,'/',credentials)

        self.connection = pika.BlockingConnection(parameters)

        self.channel = self.connection.channel()

        result = self.channel.queue_declare(exclusive=True)

        self.callback_queue = result.method.queue 
Example #27
Source File: single_message_producer.py    From whatsapp_automation with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        rhost = configp.get('rabbitmq', 'ip')
        username = configp.get('rabbitmq', 'username')
        password = configp.get('rabbitmq', 'password')
        credentials = pika.PlainCredentials(username, password)
        parameters = pika.ConnectionParameters(rhost,5672,'/',credentials)

        self.connection = pika.BlockingConnection(parameters)

        self.channel = self.connection.channel()

        result = self.channel.queue_declare(exclusive=True)

        self.callback_queue = result.method.queue 
Example #28
Source File: add_new_contact_producer.py    From whatsapp_automation with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        rhost = configp.get('rabbitmq', 'ip')
        username = configp.get('rabbitmq', 'username')
        password = configp.get('rabbitmq', 'password')
        credentials = pika.PlainCredentials(username, password)
        parameters = pika.ConnectionParameters(rhost,5672,'/',credentials)

        self.connection = pika.BlockingConnection(parameters)

        self.channel = self.connection.channel()

        result = self.channel.queue_declare(exclusive=True)

        self.callback_queue = result.method.queue 
Example #29
Source File: new_message_listener_producer.py    From whatsapp_automation with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        rhost = configp.get('rabbitmq', 'ip')
        username = configp.get('rabbitmq', 'username')
        password = configp.get('rabbitmq', 'password')
        credentials = pika.PlainCredentials(username, password)
        parameters = pika.ConnectionParameters(rhost,5672,'/',credentials)

        self.connection = pika.BlockingConnection(parameters)

        self.channel = self.connection.channel()

        result = self.channel.queue_declare(exclusive=True)

        self.callback_queue = result.method.queue 
Example #30
Source File: mqhelper.py    From k8sMG with GNU General Public License v3.0 5 votes vote down vote up
def create_channel(self):
        credentials = pika.PlainCredentials(self.user, self.pwd)
        self.__connection = pika.BlockingConnection(
            pika.ConnectionParameters(self.addr, self.port, self.vhost, credentials=credentials))
        channel = self.__connection.channel()
        return channel