Python pika 模块,PlainCredentials() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用pika.PlainCredentials()

项目:gemstone    作者:vladcalin    | 项目源码 | 文件源码
def __init__(self, host="127.0.0.1", port=5672, username="", password="", **connection_options):
        """
        Event transport via RabbitMQ server.

        :param host: ipv4 or hostname
        :param port: the port where the server listens
        :param username: username used for authentication
        :param password: password used for authentication
        :param connection_options: extra arguments that will be used in
                                   :py:class:`pika.BlockingConnection` initialization.
        """
        if not pika:
            raise RuntimeError("RabbitMqEventTransport requires 'pika' to run")

        super(RabbitMqEventTransport, self).__init__()
        self._handlers = {}

        self.connection = pika.BlockingConnection(
            pika.ConnectionParameters(
                host=host, port=port,
                credentials=pika.PlainCredentials(username=username, password=password),
                **connection_options
            )
        )
        self.channel = self.connection.channel()
项目:dati-ckan-docker    作者:italia    | 项目源码 | 文件源码
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)
项目:DIS_MeituanReptile    作者:myvary    | 项目源码 | 文件源码
def receive(self,callback, username, pwd, ip, port):
        '''
        # ????????????????????????
        :param callback: ????
        :param username: ??RabbitMQ???????
        :param pwd:      ??
        :param ip:      ip
        :param port:    ??
        :return:        
        '''
        user_pwd = pika.PlainCredentials(username, pwd)
        s_conn = pika.BlockingConnection(pika.ConnectionParameters(ip, port, '/', credentials=user_pwd))
        channel = s_conn.channel()
        channel.queue_declare(queue='city_task_queue', durable=True)
        channel.basic_qos(prefetch_count=1)
        print '???????????'
        channel.basic_consume(callback,
                              queue='city_task_queue',
                              )
        channel.start_consuming()
项目:landport    作者:land-pack    | 项目源码 | 文件源码
def connect(self):

        if self.connecting:
                print('PikaClient: Already connecting to RabbitMQ')
                return

        print('PikaClient: Connecting to RabbitMQ on localhost:5672, Object: %s' % (self,))

        self.connecting = True

        # credentials = pika.PlainCredentials('guest', 'guest')
        # param = pika.ConnectionParameters(host='localhost',
        #                                   port=5672,
        #                                   virtual_host="/"
        #                                   credentials=credentials
        #                                   )
        param = pika.ConnectionParameters("localhost")
        self.connection = TornadoConnection(param,
                                            on_open_callback=self.on_connected)

        #Currently this will close tornado ioloop.
        #self.connection.add_on_close_callback(self.on_closed)
项目:amqpeek    作者:steveYeah    | 项目源码 | 文件源码
def connect(self):
        """
        Create blocking connection in RMQ

        :return: pika.BlockingConnection
        """
        return BlockingConnection(
            parameters=ConnectionParameters(
                host=self.host,
                port=self.port,
                virtual_host=self.vhost,
                credentials=PlainCredentials(
                    username=self.user,
                    password=self.passwd,
                )
            )
        )
项目:cbapi-python    作者:carbonblack    | 项目源码 | 文件源码
def __init__(self, cb_server_address, rmq_username, rmq_password, routing_key):
        self.q = Queue.Queue()
        self.go = True

        # in case the cb url is passed in (which is often required for API stuff),
        # try to parse out the IP/DNS information.
        # This could be cleaner and better.
        cb_server_address = cb_server_address.lower()
        if cb_server_address.startswith("https://"):
            cb_server_address = cb_server_address[8:]
        elif cb_server_address.startswith("http://"):
            cb_server_address = cb_server_address[7:]
        cb_server_address = cb_server_address.split('/')[0]


        # Set the connection parameters to connect to rabbit-server1 on port 5672
        # on the / virtual host using the username "guest" and password "guest"
        credentials = pika.PlainCredentials(rmq_username, rmq_password)
        parameters = pika.ConnectionParameters(cb_server_address,
                                               5004,
                                               '/',
                                               credentials)

        self.connection = pika.BlockingConnection(parameters)
        self.channel = self.connection.channel()

        queue_name = self.__generate_queue_name()

        # make sure you use auto_delete so the queue isn't left filling
        # with events when this program exists.
        self.channel.queue_declare(queue=queue_name, auto_delete=True)
        self.channel.queue_bind(exchange='api.events', queue=queue_name, routing_key=routing_key)
        self.channel.basic_consume(self.__on_message, queue=queue_name)
        threading.Thread.__init__(self)
项目:sm-engine-ansible    作者:METASPACE2020    | 项目源码 | 文件源码
def queue_empty(self):
        try:
            creds = pika.PlainCredentials(self.ansible_config['rabbitmq_user'],
                                          self.ansible_config['rabbitmq_password'])
            conn = pika.BlockingConnection(pika.ConnectionParameters(host=self.ansible_config['rabbitmq_host'],
                                                                     credentials=creds))
            ch = conn.channel()
            m = ch.queue_declare(queue=self.qname, durable=True, arguments={'x-max-priority': 3})
            self.logger.debug('Messages in the queue: {}'.format(m.method.message_count))
            return m.method.message_count == 0
        except Exception as e:
            self.logger.warning(e, exc_info=True)
            return True
项目:globomap-driver-napi    作者:globocom    | 项目源码 | 文件源码
def __init__(self, host, port, user, password, vhost, queue_name):
        credentials = pika.PlainCredentials(user, password)
        parameters = pika.ConnectionParameters(
            host=host, port=port,
            virtual_host=vhost, credentials=credentials
        )
        self.queue_name = queue_name
        self.connection = pika.BlockingConnection(parameters)
        self.channel = self.connection.channel()
        self.channel.confirm_delivery()
项目:djangoStatusPanel    作者:okar1    | 项目源码 | 文件源码
def getMqConnection(mqConf,vErrors,maxMsgTotal):
    # try to connect via amqp
    amqpLink = pika.BlockingConnection(
        pika.ConnectionParameters(
            mqConf["server"],
            amqpPort,
            mqConf.get("vhost",'/'),
            pika.PlainCredentials(mqConf["user"], mqConf["pwd"])))
    return amqpLink
项目:BrundleFuzz    作者:carlosgprado    | 项目源码 | 文件源码
def __init__(self, parent):
        """
        This module will communicate via RPC
        with RabbitMQ and ultimately with
        our fuzzing server
        """
        self.parent = parent
        self.ae = parent.ae
        self.cfg = parent.cfg
        host = self.cfg.get('server_info', 'host')

        credentials = pika.PlainCredentials(
            self.cfg.get('server_info', 'user'),
            self.cfg.get('server_info', 'pass'))

        try:
            self.connection = pika.BlockingConnection(pika.ConnectionParameters(
                host = host,
                credentials = credentials,
                retry_delay = 10,
                connection_attempts = 5))

            self.ae.m_ok("Connected to server (broker): %s" % host)

        except Exception as e:
            self.ae.m_fatal("Could not connect to server")
            self.ae.m_fatal(e)

        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)
项目:BrundleFuzz    作者:carlosgprado    | 项目源码 | 文件源码
def __init__(self, parent):
        """
        This module will communicate via RPC
        with RabbitMQ and ultimately with
        our fuzzing server
        """
        self.parent = parent
        self.ae = parent.ae
        self.cfg = parent.cfg
        host = self.cfg.get('server_info', 'host')

        credentials = pika.PlainCredentials(
            self.cfg.get('server_info', 'user'),
            self.cfg.get('server_info', 'pass'))

        try:
            self.connection = pika.BlockingConnection(pika.ConnectionParameters(
                host = host,
                credentials = credentials,
                retry_delay = 10,
                connection_attempts = 5))

            self.ae.m_ok("Connected to server (broker): %s" % host)

        except Exception as e:
            self.ae.m_fatal("Could not connect to server")
            self.ae.m_fatal(e)

        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)
项目:salt-terraform-demo    作者:dguitarbite    | 项目源码 | 文件源码
def __init__(self):

        print("Authenticating with rabbitmq server : %s" % HOSTURI)
        credentials = pika.PlainCredentials('simplerpc', 'simplerpc')
        connURI = pika.ConnectionParameters(host=HOSTURI,
                                            credentials=credentials)
        self.connection = pika.BlockingConnection(connURI)
        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)
        print("Authentication seems to be successful!")
项目:worker-manager    作者:nebula-orchestrator    | 项目源码 | 文件源码
def rabbit_connect(rabbit_user, rabbit_pass, rabbit_host, rabbit_port, rabbit_virtual_host, rabbit_heartbeat):
    credentials = pika.PlainCredentials(rabbit_user, rabbit_pass)
    connection = pika.BlockingConnection(pika.ConnectionParameters(rabbit_host, rabbit_port, rabbit_virtual_host,
                                                                   credentials, heartbeat_interval=rabbit_heartbeat))
    return connection


# close connection to rabbit function
项目:api-manager    作者:nebula-orchestrator    | 项目源码 | 文件源码
def rabbit_connect(rabbit_user, rabbit_pass, rabbit_host, rabbit_port, rabbit_virtual_host, rabbit_heartbeat):
    credentials = pika.PlainCredentials(rabbit_user, rabbit_pass)
    connection = pika.BlockingConnection(pika.ConnectionParameters(rabbit_host, rabbit_port, rabbit_virtual_host,
                                                                   credentials, heartbeat_interval=rabbit_heartbeat))
    return connection


# close connection to rabbit function
项目:openqa_review    作者:okurz    | 项目源码 | 文件源码
def __init__(self, args):
        """Construct object and save forwarded arguments."""
        verbose_to_log = {
            0: logging.CRITICAL,
            1: logging.ERROR,
            2: logging.WARN,
            3: logging.INFO,
            4: logging.DEBUG
        }
        logging_level = logging.DEBUG if args.verbose > 4 else verbose_to_log[args.verbose]
        log.setLevel(logging_level)
        log.debug("args: %s" % args)
        self.args = args
        config = ConfigParser()
        config_entries = config.read(self.args.config_path)
        self.whitelist = [i.strip() for i in args.whitelist.split(',')]
        if config_entries:
            self.whitelist += [i.strip() for i in config.get(self.args.product, 'whitelist').split(',')]
        else:
            log.info("No configuration file '{}' for whitelist, only using optionally specified command line whitelist".format(self.args.config_path))
            log.debug(CONFIG_USAGE)
        # does not look so nice, can be improved. Removing empty string entries.
        self.whitelist = [i for i in self.whitelist if i]
        log.info("Whitelist content for %s: %s" % (self.args.product, self.whitelist))
        self.release_info_path = os.path.join(self.args.dest, self.args.release_file)
        self.browser = Browser(args, args.openqa_host)
        if not config.has_section('notification'):
            return
        self.credentials = pika.PlainCredentials(config.get('notification', 'username', fallback='guest'),
                                                 config.get('notification', 'password', fallback='guest'))
        self.notify_host = config.get('notification', 'host', fallback='kazhua.suse.de')
        self.notify_connect()
项目:dazzar    作者:Philaeux    | 项目源码 | 文件源码
def _connect(self):
        """Initial connection to the queue manager."""
        self.connection = pika.BlockingConnection(pika.ConnectionParameters(host='dazzar_rabbitmq',
                                                                            credentials=pika.PlainCredentials(
                                                                                self.username,
                                                                                self.password)))
        self.channel = self.connection.channel()
        self.channel.basic_qos(prefetch_count=1)
        self.channel.queue_declare(queue='dazzar_jobs', durable=True)
项目:hydra    作者:lake-lerna    | 项目源码 | 文件源码
def run(argv):
    pub_ip = ""
    l.info("JOB RUN : " + pformat(argv))
    if len(argv) > 1:
        pub_ip = argv[1]
    if not pub_ip:
        raise Exception("Rmq-sub needs a pub server to subscribe to, pub_ip"
                        " can not be empty pub_ip[%s]" % (pub_ip))

    # Initalize HDaemonRepSrv
    sub_rep_port = os.environ.get('PORT0')
    hd = HDRmqsRepSrv(sub_rep_port)
    hd.reset_stats()
    hd.run()

    l.info("RabbitMQ SUB client connecting to RabbitMQ PUB server at [%s]" % (pub_ip))
    credentials = pika.PlainCredentials('hydra', 'hydra')
    connection = pika.BlockingConnection(pika.ConnectionParameters(host=pub_ip, credentials=credentials))
    channel = connection.channel()
    channel.exchange_declare(exchange='pub', type='fanout')
    result = channel.queue_declare(exclusive=True)
    queue_name = result.method.queue
    channel.queue_bind(exchange='pub', queue=queue_name)
    l.info("RabbitMQ SUB client succesfully connected to RabbitMQ PUB server at [%s]" % (pub_ip))

    hd.msg_cnt = 0
    channel.basic_consume(hd.callback, queue=queue_name, no_ack=True)
    channel.start_consuming()
项目:selenium-toy    作者:blackmatrix7    | 项目源码 | 文件源码
def connect(self):
        """
        ?rabbitmq ???????????????????????
        :return:
        """
        if self.connect_count <= 0 and self.connection is None or self.connection.is_closed:
            credentials = pika.PlainCredentials(self.user, self.pwd)
            parameters = pika.ConnectionParameters(self.host, self.port, '/', credentials)
            self.connection = pika.BlockingConnection(parameters)
            self.channel = self.connection.channel()
        self.connect_count += 1
项目:DIS_MeituanReptile    作者:myvary    | 项目源码 | 文件源码
def send(self, message_list, username, pwd, ip, port,queue_name):
        '''
        ????????????
        :param message_list ????
        :param username     ??RabbitMQ??????
        :param pwd          ??
        :param ip           ?????ip
        :param port         ??
        :param queue_name   ??????????
        :return 
        '''
        user_pwd = pika.PlainCredentials(username, pwd)
        s_conn = pika.BlockingConnection(pika.ConnectionParameters(ip, port, '/', credentials=user_pwd))  # ????
        channel = s_conn.channel()  # ??????????

        channel.queue_declare(queue=queue_name, durable=True)  # ???????task_queue????????????????????????????
        print '???????????:', len(message_list)
        for g in range(len(message_list)):
            message = message_list[g]
            message = message.encode('utf-8')#??????????????????
            channel.basic_publish(exchange='',
                                  routing_key=queue_name,  # ??????????worker
                                  body=message,  # ??????
                                  properties=pika.BasicProperties(delivery_mode=2, )  # ?????????????????????2??????????
                                  )
            print g, ':', message
            time.sleep(0.02)  # ????
        print g
项目:DIS_MeituanReptile    作者:myvary    | 项目源码 | 文件源码
def receive(self,username,pwd,ip,port):#????????????????????????
        user_pwd = pika.PlainCredentials(username, pwd)
        s_conn = pika.BlockingConnection(pika.ConnectionParameters(ip,port,'/', credentials=user_pwd))
        channel = s_conn.channel()
        channel.queue_declare(queue='city_task_queue', durable=True)
        channel.basic_qos(prefetch_count=1)
        print '???????????'
        channel.basic_consume(self.callback,
                              queue='city_task_queue',
                              )
        channel.start_consuming()
项目:nebula    作者:nebula-orchestrator    | 项目源码 | 文件源码
def rabbit_connect(rabbit_user, rabbit_pass, rabbit_host, rabbit_port, rabbit_virtual_host, rabbit_heartbeat):
    credentials = pika.PlainCredentials(rabbit_user, rabbit_pass)
    connection = pika.BlockingConnection(pika.ConnectionParameters(rabbit_host, rabbit_port, rabbit_virtual_host,
                                                                   credentials, heartbeat_interval=rabbit_heartbeat))
    return connection


# close connection to rabbit function
项目:nebula    作者:nebula-orchestrator    | 项目源码 | 文件源码
def rabbit_connect(rabbit_user, rabbit_pass, rabbit_host, rabbit_port, rabbit_virtual_host, rabbit_heartbeat):
    credentials = pika.PlainCredentials(rabbit_user, rabbit_pass)
    connection = pika.BlockingConnection(pika.ConnectionParameters(rabbit_host, rabbit_port, rabbit_virtual_host,
                                                                   credentials, heartbeat_interval=rabbit_heartbeat))
    return connection


# close connection to rabbit function
项目:pyactor    作者:pedrotgn    | 项目源码 | 文件源码
def __init__(self, addr):
        threading.Thread.__init__(self)
        ip, port = addr
        self.url = ip + '/' + str(port)
        creden = pika.PlainCredentials(RABBITU, RABBITP)
        params = pika.ConnectionParameters(host=ip, credentials=creden)
        self.connection = pika.BlockingConnection(params)

        self.channel = self.connection.channel()

        self.channel.queue_declare(queue=self.url)
        # self.channel.basic_qos(prefetch_count=1)
项目:pyactor    作者:pedrotgn    | 项目源码 | 文件源码
def __init__(self, url):
        aurl = urlparse(url)
        address = aurl.netloc.split(':')
        ip, port = address[0], int(address[1])
        self.url = ip + '/' + str(port)
        creden = pika.PlainCredentials(RABBITU, RABBITP)
        params = pika.ConnectionParameters(host=ip, credentials=creden)
        self.connection = pika.BlockingConnection(params)
        self.channel = self.connection.channel()
项目:websocket-tornado-rabbitmq-example    作者:zetaops    | 项目源码 | 文件源码
def connect(self):
        if self.connecting:
            return
        self.connecting = True

        cred = pika.PlainCredentials('guest', 'guest')
        param = pika.ConnectionParameters(
            host='localhost',
            port=5672,
            virtual_host='/',
            credentials=cred
        )

        self.connection = TornadoConnection(param,
                                            on_open_callback=self.on_connected)
项目:spamscope    作者:SpamScope    | 项目源码 | 文件源码
def connection(server, user, password):
        credentials = pika.PlainCredentials(user, password)
        try:
            connection = pika.BlockingConnection(
                pika.ConnectionParameters(
                    host=server,
                    credentials=credentials,
                )
            )
            return connection
        except:
            message = "Failed rabbit connection to server {}".format(server)
            log.exception(message)
            raise RabbitConnectionFailed(message)
项目:reproserver    作者:ViDA-NYU    | 项目源码 | 文件源码
def _connect(self):
        logging.info("Connecting to AMQP broker")
        self.connection = pika.BlockingConnection(pika.ConnectionParameters(
            host=os.environ['AMQP_HOST'],
            credentials=pika.PlainCredentials(os.environ['AMQP_USER'],
                                              os.environ['AMQP_PASSWORD'])))
        self.channel = self.connection.channel()

        self.channel.queue_declare(queue='build_queue', durable=True)
        self.channel.queue_declare(queue='run_queue', durable=True)

        self.channel.basic_qos(prefetch_count=1)
项目:Distributed-Multi-User-Scrapy-System-with-a-Web-UI    作者:aaldaber    | 项目源码 | 文件源码
def from_settings(settings, spider_name):

    connection_type = settings.get('RABBITMQ_CONNECTION_TYPE',
                                   RABBITMQ_CONNECTION_TYPE)
    queue_name = "%s:requests" % spider_name
    connection_host = settings.get('RABBITMQ_HOST')
    connection_port = settings.get('RABBITMQ_PORT')
    connection_username = settings.get('RABBITMQ_USERNAME')
    connection_pass = settings.get('RABBITMQ_PASSWORD')

    connection_attempts = 5
    retry_delay = 3

    credentials = pika.PlainCredentials(connection_username, connection_pass)

    connection = {
        'blocking': pika.BlockingConnection,
        'libev': pika.LibevConnection,
        'select': pika.SelectConnection,
        'tornado': pika.TornadoConnection,
        'twisted': pika.TwistedConnection
    }[connection_type](pika.ConnectionParameters(host=connection_host,
                       port=connection_port, virtual_host='/',
                       credentials=credentials,
                       connection_attempts=connection_attempts,
                       retry_delay=retry_delay))

    channel = connection.channel()
    channel.queue_declare(queue=queue_name, durable=True)

    return channel
项目:rabbitChat    作者:anirbanroydas    | 项目源码 | 文件源码
def __init__(self):
        """Create a new instance of the consumer class, passing in the AMQP
        URL used to connect to RabbitMQ.
        """

        pi('__init__')

        self._connection = None
        self._connected = False
        self._connecting = False
        self._channel = None
        self._closing = False
        self._closed = False
        self._consumer_tag = None
        self._deliveries = []
        self._acked = 0
        self._nacked = 0
        self._message_number = 0
        self._credentials = pika.PlainCredentials('guest', 'guest')
        self._parameters = pika.ConnectionParameters(host='localhost',
                                                     port=PORT,
                                                     virtual_host='/',
                                                     credentials=self._credentials)
        self._queue = 'queue-' + str(uuid.uuid4())
        self.websocket = None
        self._status = 0
        self._person = None
        self._clientid = None
        self._participants = 0

        pp(self, '__INIT__')

        pr('__init__')
项目:rabbitChat    作者:anirbanroydas    | 项目源码 | 文件源码
def __init__(self, credentials=None, params=None, queue=None):
        """Create a new instance of the consumer class, passing in the AMQP
        URL used to connect to RabbitMQ.

        :param credentials: credentials to connect to rabbitmq broker server
        :type credentials: pika.credentials.PlainCredentials
        :param params: connection paramaters used to connect with rabbitmq broker server
        :type params: pika.connection.ConnectionParameters
        :param queue: queue to be created after a channel is established which will be bound to an exchange
        :type queue: string - random long base64 url safe encoded string

        """


        self._connection = None
        self._connected = False
        self._connecting = False
        self._channel = None
        self._closing = False
        self._closed = False
        self._consumer_tag = None
        self._deliveries = []
        self._acked = 0
        self._nacked = 0
        self._message_number = 0
        self._credentials = credentials if credentials else pika.PlainCredentials('guest', 'guest')
        self._parameters = params if params else pika.ConnectionParameters(host='localhost',
                                                                           port=PORT,
                                                                           virtual_host='/',
                                                                           credentials=self._credentials)
        self._queue = queue if queue else 'queue-' + str(uuid.uuid4())
        self.websocket = None
        self._status = 0
        self._person = None
        self._clientid = None
        self._participants = 0
项目:globomap-driver-acs    作者:globocom    | 项目源码 | 文件源码
def __init__(self, host, port, user, password, vhost, queue_name):
        credentials = pika.PlainCredentials(user, password)
        parameters = pika.ConnectionParameters(
            host=host, port=port,
            virtual_host=vhost, credentials=credentials
        )
        self.queue_name = queue_name
        self.connection = pika.BlockingConnection(parameters)
        self.channel = self.connection.channel()
        self.channel.confirm_delivery()
项目:rabbit2ev    作者:lovelle    | 项目源码 | 文件源码
def credentials(self):
        return pika.PlainCredentials(
            self.conf.rabbitmq_user, self.conf.rabbitmq_pass)
项目:amqppy    作者:marceljanerfont    | 项目源码 | 文件源码
def _create_connection(broker, heartbeat_sec=None):
    # builds AMQP connection for each broker URL
    params = parse_url(broker)
    return pika.BlockingConnection(pika.ConnectionParameters(
        host=params["host"],
        port=int(params["port"]),
        virtual_host=params["virtual_host"],
        credentials=pika.PlainCredentials(params["username"], params["password"]),
        socket_timeout=1.25,
        heartbeat_interval=heartbeat_sec))
项目:fibratus    作者:rabbitstack    | 项目源码 | 文件源码
def __init__(self, **kwargs):
        """Builds a new instance of the AMQP output adapter.

        Parameters
        ----------

        kwargs: dict
            AMQP configuration
        """
        Output.__init__(self)
        self._username = kwargs.pop('username', 'guest')
        self._password = kwargs.pop('password', 'guest')

        self._host = kwargs.pop('host', '127.0.0.1')
        self._port = kwargs.pop('port', 5672)
        self._vhost = kwargs.pop('vhost', '/')
        self._delivery_mode = kwargs.pop('delivery_mode', 1)

        credentials = pika.PlainCredentials(self._username, self._password)
        self._parameters = pika.ConnectionParameters(self._host,
                                                     self._port,
                                                     self._vhost,
                                                     credentials)

        self._exchange = kwargs.pop('exchange', None)
        self._routingkey = kwargs.pop('routingkey', None)

        self._connection = None
        self._channel = None

        self._basic_props = pika.BasicProperties(content_type='text/json',
                                                 delivery_mode=self._delivery_mode)
项目:charm-plumgrid-gateway    作者:openstack    | 项目源码 | 文件源码
def connect_amqp_by_unit(self, sentry_unit, ssl=False,
                             port=None, fatal=True,
                             username="testuser1", password="changeme"):
        """Establish and return a pika amqp connection to the rabbitmq service
        running on a rmq juju unit.

        :param sentry_unit: sentry unit pointer
        :param ssl: boolean, default to False
        :param port: amqp port, use defaults if None
        :param fatal: boolean, default to True (raises on connect error)
        :param username: amqp user name, default to testuser1
        :param password: amqp user password
        :returns: pika amqp connection pointer or None if failed and non-fatal
        """
        host = sentry_unit.info['public-address']
        unit_name = sentry_unit.info['unit_name']

        # Default port logic if port is not specified
        if ssl and not port:
            port = 5671
        elif not ssl and not port:
            port = 5672

        self.log.debug('Connecting to amqp on {}:{} ({}) as '
                       '{}...'.format(host, port, unit_name, username))

        try:
            credentials = pika.PlainCredentials(username, password)
            parameters = pika.ConnectionParameters(host=host, port=port,
                                                   credentials=credentials,
                                                   ssl=ssl,
                                                   connection_attempts=3,
                                                   retry_delay=5,
                                                   socket_timeout=1)
            connection = pika.BlockingConnection(parameters)
            assert connection.server_properties['product'] == 'RabbitMQ'
            self.log.debug('Connect OK')
            return connection
        except Exception as e:
            msg = ('amqp connection failed to {}:{} as '
                   '{} ({})'.format(host, port, username, str(e)))
            if fatal:
                amulet.raise_status(amulet.FAIL, msg)
            else:
                self.log.warn(msg)
                return None
项目:charm-swift-proxy    作者:openstack    | 项目源码 | 文件源码
def connect_amqp_by_unit(self, sentry_unit, ssl=False,
                             port=None, fatal=True,
                             username="testuser1", password="changeme"):
        """Establish and return a pika amqp connection to the rabbitmq service
        running on a rmq juju unit.

        :param sentry_unit: sentry unit pointer
        :param ssl: boolean, default to False
        :param port: amqp port, use defaults if None
        :param fatal: boolean, default to True (raises on connect error)
        :param username: amqp user name, default to testuser1
        :param password: amqp user password
        :returns: pika amqp connection pointer or None if failed and non-fatal
        """
        host = sentry_unit.info['public-address']
        unit_name = sentry_unit.info['unit_name']

        # Default port logic if port is not specified
        if ssl and not port:
            port = 5671
        elif not ssl and not port:
            port = 5672

        self.log.debug('Connecting to amqp on {}:{} ({}) as '
                       '{}...'.format(host, port, unit_name, username))

        try:
            credentials = pika.PlainCredentials(username, password)
            parameters = pika.ConnectionParameters(host=host, port=port,
                                                   credentials=credentials,
                                                   ssl=ssl,
                                                   connection_attempts=3,
                                                   retry_delay=5,
                                                   socket_timeout=1)
            connection = pika.BlockingConnection(parameters)
            assert connection.is_open is True
            assert connection.is_closing is False
            self.log.debug('Connect OK')
            return connection
        except Exception as e:
            msg = ('amqp connection failed to {}:{} as '
                   '{} ({})'.format(host, port, username, str(e)))
            if fatal:
                amulet.raise_status(amulet.FAIL, msg)
            else:
                self.log.warn(msg)
                return None
项目:charm-swift-proxy    作者:openstack    | 项目源码 | 文件源码
def connect_amqp_by_unit(self, sentry_unit, ssl=False,
                             port=None, fatal=True,
                             username="testuser1", password="changeme"):
        """Establish and return a pika amqp connection to the rabbitmq service
        running on a rmq juju unit.

        :param sentry_unit: sentry unit pointer
        :param ssl: boolean, default to False
        :param port: amqp port, use defaults if None
        :param fatal: boolean, default to True (raises on connect error)
        :param username: amqp user name, default to testuser1
        :param password: amqp user password
        :returns: pika amqp connection pointer or None if failed and non-fatal
        """
        host = sentry_unit.info['public-address']
        unit_name = sentry_unit.info['unit_name']

        # Default port logic if port is not specified
        if ssl and not port:
            port = 5671
        elif not ssl and not port:
            port = 5672

        self.log.debug('Connecting to amqp on {}:{} ({}) as '
                       '{}...'.format(host, port, unit_name, username))

        try:
            credentials = pika.PlainCredentials(username, password)
            parameters = pika.ConnectionParameters(host=host, port=port,
                                                   credentials=credentials,
                                                   ssl=ssl,
                                                   connection_attempts=3,
                                                   retry_delay=5,
                                                   socket_timeout=1)
            connection = pika.BlockingConnection(parameters)
            assert connection.is_open is True
            assert connection.is_closing is False
            self.log.debug('Connect OK')
            return connection
        except Exception as e:
            msg = ('amqp connection failed to {}:{} as '
                   '{} ({})'.format(host, port, username, str(e)))
            if fatal:
                amulet.raise_status(amulet.FAIL, msg)
            else:
                self.log.warn(msg)
                return None
项目:charm-heat    作者:openstack    | 项目源码 | 文件源码
def connect_amqp_by_unit(self, sentry_unit, ssl=False,
                             port=None, fatal=True,
                             username="testuser1", password="changeme"):
        """Establish and return a pika amqp connection to the rabbitmq service
        running on a rmq juju unit.

        :param sentry_unit: sentry unit pointer
        :param ssl: boolean, default to False
        :param port: amqp port, use defaults if None
        :param fatal: boolean, default to True (raises on connect error)
        :param username: amqp user name, default to testuser1
        :param password: amqp user password
        :returns: pika amqp connection pointer or None if failed and non-fatal
        """
        host = sentry_unit.info['public-address']
        unit_name = sentry_unit.info['unit_name']

        # Default port logic if port is not specified
        if ssl and not port:
            port = 5671
        elif not ssl and not port:
            port = 5672

        self.log.debug('Connecting to amqp on {}:{} ({}) as '
                       '{}...'.format(host, port, unit_name, username))

        try:
            credentials = pika.PlainCredentials(username, password)
            parameters = pika.ConnectionParameters(host=host, port=port,
                                                   credentials=credentials,
                                                   ssl=ssl,
                                                   connection_attempts=3,
                                                   retry_delay=5,
                                                   socket_timeout=1)
            connection = pika.BlockingConnection(parameters)
            assert connection.is_open is True
            assert connection.is_closing is False
            self.log.debug('Connect OK')
            return connection
        except Exception as e:
            msg = ('amqp connection failed to {}:{} as '
                   '{} ({})'.format(host, port, username, str(e)))
            if fatal:
                amulet.raise_status(amulet.FAIL, msg)
            else:
                self.log.warn(msg)
                return None
项目:charm-heat    作者:openstack    | 项目源码 | 文件源码
def connect_amqp_by_unit(self, sentry_unit, ssl=False,
                             port=None, fatal=True,
                             username="testuser1", password="changeme"):
        """Establish and return a pika amqp connection to the rabbitmq service
        running on a rmq juju unit.

        :param sentry_unit: sentry unit pointer
        :param ssl: boolean, default to False
        :param port: amqp port, use defaults if None
        :param fatal: boolean, default to True (raises on connect error)
        :param username: amqp user name, default to testuser1
        :param password: amqp user password
        :returns: pika amqp connection pointer or None if failed and non-fatal
        """
        host = sentry_unit.info['public-address']
        unit_name = sentry_unit.info['unit_name']

        # Default port logic if port is not specified
        if ssl and not port:
            port = 5671
        elif not ssl and not port:
            port = 5672

        self.log.debug('Connecting to amqp on {}:{} ({}) as '
                       '{}...'.format(host, port, unit_name, username))

        try:
            credentials = pika.PlainCredentials(username, password)
            parameters = pika.ConnectionParameters(host=host, port=port,
                                                   credentials=credentials,
                                                   ssl=ssl,
                                                   connection_attempts=3,
                                                   retry_delay=5,
                                                   socket_timeout=1)
            connection = pika.BlockingConnection(parameters)
            assert connection.is_open is True
            assert connection.is_closing is False
            self.log.debug('Connect OK')
            return connection
        except Exception as e:
            msg = ('amqp connection failed to {}:{} as '
                   '{} ({})'.format(host, port, username, str(e)))
            if fatal:
                amulet.raise_status(amulet.FAIL, msg)
            else:
                self.log.warn(msg)
                return None
项目:charm-keystone    作者:openstack    | 项目源码 | 文件源码
def connect_amqp_by_unit(self, sentry_unit, ssl=False,
                             port=None, fatal=True,
                             username="testuser1", password="changeme"):
        """Establish and return a pika amqp connection to the rabbitmq service
        running on a rmq juju unit.

        :param sentry_unit: sentry unit pointer
        :param ssl: boolean, default to False
        :param port: amqp port, use defaults if None
        :param fatal: boolean, default to True (raises on connect error)
        :param username: amqp user name, default to testuser1
        :param password: amqp user password
        :returns: pika amqp connection pointer or None if failed and non-fatal
        """
        host = sentry_unit.info['public-address']
        unit_name = sentry_unit.info['unit_name']

        # Default port logic if port is not specified
        if ssl and not port:
            port = 5671
        elif not ssl and not port:
            port = 5672

        self.log.debug('Connecting to amqp on {}:{} ({}) as '
                       '{}...'.format(host, port, unit_name, username))

        try:
            credentials = pika.PlainCredentials(username, password)
            parameters = pika.ConnectionParameters(host=host, port=port,
                                                   credentials=credentials,
                                                   ssl=ssl,
                                                   connection_attempts=3,
                                                   retry_delay=5,
                                                   socket_timeout=1)
            connection = pika.BlockingConnection(parameters)
            assert connection.is_open is True
            assert connection.is_closing is False
            self.log.debug('Connect OK')
            return connection
        except Exception as e:
            msg = ('amqp connection failed to {}:{} as '
                   '{} ({})'.format(host, port, username, str(e)))
            if fatal:
                amulet.raise_status(amulet.FAIL, msg)
            else:
                self.log.warn(msg)
                return None
项目:charm-keystone    作者:openstack    | 项目源码 | 文件源码
def connect_amqp_by_unit(self, sentry_unit, ssl=False,
                             port=None, fatal=True,
                             username="testuser1", password="changeme"):
        """Establish and return a pika amqp connection to the rabbitmq service
        running on a rmq juju unit.

        :param sentry_unit: sentry unit pointer
        :param ssl: boolean, default to False
        :param port: amqp port, use defaults if None
        :param fatal: boolean, default to True (raises on connect error)
        :param username: amqp user name, default to testuser1
        :param password: amqp user password
        :returns: pika amqp connection pointer or None if failed and non-fatal
        """
        host = sentry_unit.info['public-address']
        unit_name = sentry_unit.info['unit_name']

        # Default port logic if port is not specified
        if ssl and not port:
            port = 5671
        elif not ssl and not port:
            port = 5672

        self.log.debug('Connecting to amqp on {}:{} ({}) as '
                       '{}...'.format(host, port, unit_name, username))

        try:
            credentials = pika.PlainCredentials(username, password)
            parameters = pika.ConnectionParameters(host=host, port=port,
                                                   credentials=credentials,
                                                   ssl=ssl,
                                                   connection_attempts=3,
                                                   retry_delay=5,
                                                   socket_timeout=1)
            connection = pika.BlockingConnection(parameters)
            assert connection.is_open is True
            assert connection.is_closing is False
            self.log.debug('Connect OK')
            return connection
        except Exception as e:
            msg = ('amqp connection failed to {}:{} as '
                   '{} ({})'.format(host, port, username, str(e)))
            if fatal:
                amulet.raise_status(amulet.FAIL, msg)
            else:
                self.log.warn(msg)
                return None
项目:charm-keystone    作者:openstack    | 项目源码 | 文件源码
def connect_amqp_by_unit(self, sentry_unit, ssl=False,
                             port=None, fatal=True,
                             username="testuser1", password="changeme"):
        """Establish and return a pika amqp connection to the rabbitmq service
        running on a rmq juju unit.

        :param sentry_unit: sentry unit pointer
        :param ssl: boolean, default to False
        :param port: amqp port, use defaults if None
        :param fatal: boolean, default to True (raises on connect error)
        :param username: amqp user name, default to testuser1
        :param password: amqp user password
        :returns: pika amqp connection pointer or None if failed and non-fatal
        """
        host = sentry_unit.info['public-address']
        unit_name = sentry_unit.info['unit_name']

        # Default port logic if port is not specified
        if ssl and not port:
            port = 5671
        elif not ssl and not port:
            port = 5672

        self.log.debug('Connecting to amqp on {}:{} ({}) as '
                       '{}...'.format(host, port, unit_name, username))

        try:
            credentials = pika.PlainCredentials(username, password)
            parameters = pika.ConnectionParameters(host=host, port=port,
                                                   credentials=credentials,
                                                   ssl=ssl,
                                                   connection_attempts=3,
                                                   retry_delay=5,
                                                   socket_timeout=1)
            connection = pika.BlockingConnection(parameters)
            assert connection.is_open is True
            assert connection.is_closing is False
            self.log.debug('Connect OK')
            return connection
        except Exception as e:
            msg = ('amqp connection failed to {}:{} as '
                   '{} ({})'.format(host, port, username, str(e)))
            if fatal:
                amulet.raise_status(amulet.FAIL, msg)
            else:
                self.log.warn(msg)
                return None
项目:charm-keystone    作者:openstack    | 项目源码 | 文件源码
def connect_amqp_by_unit(self, sentry_unit, ssl=False,
                             port=None, fatal=True,
                             username="testuser1", password="changeme"):
        """Establish and return a pika amqp connection to the rabbitmq service
        running on a rmq juju unit.

        :param sentry_unit: sentry unit pointer
        :param ssl: boolean, default to False
        :param port: amqp port, use defaults if None
        :param fatal: boolean, default to True (raises on connect error)
        :param username: amqp user name, default to testuser1
        :param password: amqp user password
        :returns: pika amqp connection pointer or None if failed and non-fatal
        """
        host = sentry_unit.info['public-address']
        unit_name = sentry_unit.info['unit_name']

        # Default port logic if port is not specified
        if ssl and not port:
            port = 5671
        elif not ssl and not port:
            port = 5672

        self.log.debug('Connecting to amqp on {}:{} ({}) as '
                       '{}...'.format(host, port, unit_name, username))

        try:
            credentials = pika.PlainCredentials(username, password)
            parameters = pika.ConnectionParameters(host=host, port=port,
                                                   credentials=credentials,
                                                   ssl=ssl,
                                                   connection_attempts=3,
                                                   retry_delay=5,
                                                   socket_timeout=1)
            connection = pika.BlockingConnection(parameters)
            assert connection.is_open is True
            assert connection.is_closing is False
            self.log.debug('Connect OK')
            return connection
        except Exception as e:
            msg = ('amqp connection failed to {}:{} as '
                   '{} ({})'.format(host, port, username, str(e)))
            if fatal:
                amulet.raise_status(amulet.FAIL, msg)
            else:
                self.log.warn(msg)
                return None
项目:charm-keystone    作者:openstack    | 项目源码 | 文件源码
def connect_amqp_by_unit(self, sentry_unit, ssl=False,
                             port=None, fatal=True,
                             username="testuser1", password="changeme"):
        """Establish and return a pika amqp connection to the rabbitmq service
        running on a rmq juju unit.

        :param sentry_unit: sentry unit pointer
        :param ssl: boolean, default to False
        :param port: amqp port, use defaults if None
        :param fatal: boolean, default to True (raises on connect error)
        :param username: amqp user name, default to testuser1
        :param password: amqp user password
        :returns: pika amqp connection pointer or None if failed and non-fatal
        """
        host = sentry_unit.info['public-address']
        unit_name = sentry_unit.info['unit_name']

        # Default port logic if port is not specified
        if ssl and not port:
            port = 5671
        elif not ssl and not port:
            port = 5672

        self.log.debug('Connecting to amqp on {}:{} ({}) as '
                       '{}...'.format(host, port, unit_name, username))

        try:
            credentials = pika.PlainCredentials(username, password)
            parameters = pika.ConnectionParameters(host=host, port=port,
                                                   credentials=credentials,
                                                   ssl=ssl,
                                                   connection_attempts=3,
                                                   retry_delay=5,
                                                   socket_timeout=1)
            connection = pika.BlockingConnection(parameters)
            assert connection.is_open is True
            assert connection.is_closing is False
            self.log.debug('Connect OK')
            return connection
        except Exception as e:
            msg = ('amqp connection failed to {}:{} as '
                   '{} ({})'.format(host, port, username, str(e)))
            if fatal:
                amulet.raise_status(amulet.FAIL, msg)
            else:
                self.log.warn(msg)
                return None
项目:charm-nova-cloud-controller    作者:openstack    | 项目源码 | 文件源码
def connect_amqp_by_unit(self, sentry_unit, ssl=False,
                             port=None, fatal=True,
                             username="testuser1", password="changeme"):
        """Establish and return a pika amqp connection to the rabbitmq service
        running on a rmq juju unit.

        :param sentry_unit: sentry unit pointer
        :param ssl: boolean, default to False
        :param port: amqp port, use defaults if None
        :param fatal: boolean, default to True (raises on connect error)
        :param username: amqp user name, default to testuser1
        :param password: amqp user password
        :returns: pika amqp connection pointer or None if failed and non-fatal
        """
        host = sentry_unit.info['public-address']
        unit_name = sentry_unit.info['unit_name']

        # Default port logic if port is not specified
        if ssl and not port:
            port = 5671
        elif not ssl and not port:
            port = 5672

        self.log.debug('Connecting to amqp on {}:{} ({}) as '
                       '{}...'.format(host, port, unit_name, username))

        try:
            credentials = pika.PlainCredentials(username, password)
            parameters = pika.ConnectionParameters(host=host, port=port,
                                                   credentials=credentials,
                                                   ssl=ssl,
                                                   connection_attempts=3,
                                                   retry_delay=5,
                                                   socket_timeout=1)
            connection = pika.BlockingConnection(parameters)
            assert connection.is_open is True
            assert connection.is_closing is False
            self.log.debug('Connect OK')
            return connection
        except Exception as e:
            msg = ('amqp connection failed to {}:{} as '
                   '{} ({})'.format(host, port, username, str(e)))
            if fatal:
                amulet.raise_status(amulet.FAIL, msg)
            else:
                self.log.warn(msg)
                return None
项目:zcp    作者:apolloliu    | 项目源码 | 文件源码
def connection():
    connect = None
    connection_state = False
    attemps = 0
    MAX_RETRIES = max_retries * len(hosts.split(','))
    while True:
        if connection_state:
            break
        try:
            for host in hosts.split(','):
                LOG.info("Connecting to Rabbitmq server %s..." % host)
                connect = pika.BlockingConnection(pika.ConnectionParameters(
                    host=host,
                    port=int(port),
                    virtual_host=vh,
                    credentials=pika.PlainCredentials(user,
                                                      passwd)))
        except Exception as e:
            if max_retries < 0:
                LOG.error('Unable to connect to the Rabbitmq cluster: '
                          '%(msg)s.Trying again in %(retry_interval)d '
                          'seconds,Continuing to retry to connect '
                          % {'msg': e,
                             'retry_interval': retry_interval})
                time.sleep(retry_interval)
            elif max_retries > 0 and attemps <= MAX_RETRIES:
                LOG.error('Unable to connect to the Rabbitmq cluster: '
                          '%(msg)s.Trying again in %(retry_interval)d '
                          'seconds,max_retries time: %(max_retries)d,'
                          'retry times left:%(left)d'
                          % {'msg': e,
                             'retry_interval': retry_interval,
                             'max_retries': MAX_RETRIES,
                             'left': (MAX_RETRIES - attemps)})
                attemps += 1
                time.sleep(retry_interval)
            else:
                LOG.error('Unable to connect to the Rabbitmq cluster: '
                          '%(msg)s.' % {'msg': e})
                raise
        else:
            connection_state = True
    return connect
项目:charm-nova-compute    作者:openstack    | 项目源码 | 文件源码
def connect_amqp_by_unit(self, sentry_unit, ssl=False,
                             port=None, fatal=True,
                             username="testuser1", password="changeme"):
        """Establish and return a pika amqp connection to the rabbitmq service
        running on a rmq juju unit.

        :param sentry_unit: sentry unit pointer
        :param ssl: boolean, default to False
        :param port: amqp port, use defaults if None
        :param fatal: boolean, default to True (raises on connect error)
        :param username: amqp user name, default to testuser1
        :param password: amqp user password
        :returns: pika amqp connection pointer or None if failed and non-fatal
        """
        host = sentry_unit.info['public-address']
        unit_name = sentry_unit.info['unit_name']

        # Default port logic if port is not specified
        if ssl and not port:
            port = 5671
        elif not ssl and not port:
            port = 5672

        self.log.debug('Connecting to amqp on {}:{} ({}) as '
                       '{}...'.format(host, port, unit_name, username))

        try:
            credentials = pika.PlainCredentials(username, password)
            parameters = pika.ConnectionParameters(host=host, port=port,
                                                   credentials=credentials,
                                                   ssl=ssl,
                                                   connection_attempts=3,
                                                   retry_delay=5,
                                                   socket_timeout=1)
            connection = pika.BlockingConnection(parameters)
            assert connection.is_open is True
            assert connection.is_closing is False
            self.log.debug('Connect OK')
            return connection
        except Exception as e:
            msg = ('amqp connection failed to {}:{} as '
                   '{} ({})'.format(host, port, username, str(e)))
            if fatal:
                amulet.raise_status(amulet.FAIL, msg)
            else:
                self.log.warn(msg)
                return None
项目:charm-nova-compute    作者:openstack    | 项目源码 | 文件源码
def connect_amqp_by_unit(self, sentry_unit, ssl=False,
                             port=None, fatal=True,
                             username="testuser1", password="changeme"):
        """Establish and return a pika amqp connection to the rabbitmq service
        running on a rmq juju unit.

        :param sentry_unit: sentry unit pointer
        :param ssl: boolean, default to False
        :param port: amqp port, use defaults if None
        :param fatal: boolean, default to True (raises on connect error)
        :param username: amqp user name, default to testuser1
        :param password: amqp user password
        :returns: pika amqp connection pointer or None if failed and non-fatal
        """
        host = sentry_unit.info['public-address']
        unit_name = sentry_unit.info['unit_name']

        # Default port logic if port is not specified
        if ssl and not port:
            port = 5671
        elif not ssl and not port:
            port = 5672

        self.log.debug('Connecting to amqp on {}:{} ({}) as '
                       '{}...'.format(host, port, unit_name, username))

        try:
            credentials = pika.PlainCredentials(username, password)
            parameters = pika.ConnectionParameters(host=host, port=port,
                                                   credentials=credentials,
                                                   ssl=ssl,
                                                   connection_attempts=3,
                                                   retry_delay=5,
                                                   socket_timeout=1)
            connection = pika.BlockingConnection(parameters)
            assert connection.is_open is True
            assert connection.is_closing is False
            self.log.debug('Connect OK')
            return connection
        except Exception as e:
            msg = ('amqp connection failed to {}:{} as '
                   '{} ({})'.format(host, port, username, str(e)))
            if fatal:
                amulet.raise_status(amulet.FAIL, msg)
            else:
                self.log.warn(msg)
                return None
项目:charm-ceph-osd    作者:openstack    | 项目源码 | 文件源码
def connect_amqp_by_unit(self, sentry_unit, ssl=False,
                             port=None, fatal=True,
                             username="testuser1", password="changeme"):
        """Establish and return a pika amqp connection to the rabbitmq service
        running on a rmq juju unit.

        :param sentry_unit: sentry unit pointer
        :param ssl: boolean, default to False
        :param port: amqp port, use defaults if None
        :param fatal: boolean, default to True (raises on connect error)
        :param username: amqp user name, default to testuser1
        :param password: amqp user password
        :returns: pika amqp connection pointer or None if failed and non-fatal
        """
        host = sentry_unit.info['public-address']
        unit_name = sentry_unit.info['unit_name']

        # Default port logic if port is not specified
        if ssl and not port:
            port = 5671
        elif not ssl and not port:
            port = 5672

        self.log.debug('Connecting to amqp on {}:{} ({}) as '
                       '{}...'.format(host, port, unit_name, username))

        try:
            credentials = pika.PlainCredentials(username, password)
            parameters = pika.ConnectionParameters(host=host, port=port,
                                                   credentials=credentials,
                                                   ssl=ssl,
                                                   connection_attempts=3,
                                                   retry_delay=5,
                                                   socket_timeout=1)
            connection = pika.BlockingConnection(parameters)
            assert connection.is_open is True
            assert connection.is_closing is False
            self.log.debug('Connect OK')
            return connection
        except Exception as e:
            msg = ('amqp connection failed to {}:{} as '
                   '{} ({})'.format(host, port, username, str(e)))
            if fatal:
                amulet.raise_status(amulet.FAIL, msg)
            else:
                self.log.warn(msg)
                return None
项目:charm-glance    作者:openstack    | 项目源码 | 文件源码
def connect_amqp_by_unit(self, sentry_unit, ssl=False,
                             port=None, fatal=True,
                             username="testuser1", password="changeme"):
        """Establish and return a pika amqp connection to the rabbitmq service
        running on a rmq juju unit.

        :param sentry_unit: sentry unit pointer
        :param ssl: boolean, default to False
        :param port: amqp port, use defaults if None
        :param fatal: boolean, default to True (raises on connect error)
        :param username: amqp user name, default to testuser1
        :param password: amqp user password
        :returns: pika amqp connection pointer or None if failed and non-fatal
        """
        host = sentry_unit.info['public-address']
        unit_name = sentry_unit.info['unit_name']

        # Default port logic if port is not specified
        if ssl and not port:
            port = 5671
        elif not ssl and not port:
            port = 5672

        self.log.debug('Connecting to amqp on {}:{} ({}) as '
                       '{}...'.format(host, port, unit_name, username))

        try:
            credentials = pika.PlainCredentials(username, password)
            parameters = pika.ConnectionParameters(host=host, port=port,
                                                   credentials=credentials,
                                                   ssl=ssl,
                                                   connection_attempts=3,
                                                   retry_delay=5,
                                                   socket_timeout=1)
            connection = pika.BlockingConnection(parameters)
            assert connection.is_open is True
            assert connection.is_closing is False
            self.log.debug('Connect OK')
            return connection
        except Exception as e:
            msg = ('amqp connection failed to {}:{} as '
                   '{} ({})'.format(host, port, username, str(e)))
            if fatal:
                amulet.raise_status(amulet.FAIL, msg)
            else:
                self.log.warn(msg)
                return None