def connect(self):
     if self.connected:
         return
     cred = PlainCredentials(USERNAME, PASSWORD)
     params = ConnectionParameters(host=HOST, port=PORT, virtual_host=VHOST, credentials=cred)
     self.connection = TornadoConnection(params, on_open_callback=self.on_connected)
     self.connection.add_on_close_callback(callback=self.on_closed)
class PikaClient(object):
	#all the following functions precede in order starting with connect
	def connect(self):
		try:
			logger = logging.getLogger('rmq_tornado')
			credentials = pika.PlainCredentials(RMQ_USER, RMQ_PWD)
			param = pika.ConnectionParameters(host=RMQ_HOST, port=RMQ_PORT, credentials=credentials)

			self.connection = TornadoConnection(param, on_open_callback=self.on_connected)
		except Exception as e:
			logger.error('Something went wrong... %s', e)

	def on_connected(self, connection):
		"""When we are completely connected to rabbitmq this is called"""

		logger.info('Succesfully connected to rabbitmq')

		#open a channel
		self.connection.channel(self.on_channel_open)

	def on_channel_open(self, new_channel):
		"""When the channel is open this is called"""
		logging.info('Opening channel to rabbitmq')

		global channel
		channel = new_channel
Пример #3
0
class PikaClient(object):
    # All the following functions precede in order starting with connect
    def connect(self):
        try:
            logger = logging.getLogger('rmq_tornado')
            credentials = pika.PlainCredentials(RMQ_USER, RMQ_PWD)
            param = pika.ConnectionParameters(host=RMQ_HOST, port=RMQ_PORT, credentials=credentials)

            self.connection = TornadoConnection(param, on_open_callback=self.on_connected)
        except Exception as e:
            logger.error('Something went wrong... %s', e)

    def on_connected(self, connection):
        """When we are completely connected to rabbitmq this is called"""

        logger.info('Succesfully connected to rabbitmq')

        # Open a channel
        self.connection.channel(self.on_channel_open)

    def on_channel_open(self, new_channel):
        """When the channel is open this is called"""
        logging.info('Opening channel to rabbitmq')

        global channel
        channel = new_channel
Пример #4
0
    def connect(self):
        if self.connecting:
            self.logger.info(
                'django-sockjs-server(SockjsServer): Already connecting to RabbitMQ'
            )
            return

        self.logger.info(
            'django-sockjs-server(SockjsServer): Connecting to RabbitMQ')
        self.connecting = True

        cred = pika.PlainCredentials(self.config.rabbitmq_user,
                                     self.config.rabbitmq_password)
        param = pika.ConnectionParameters(
            host=self.config.rabbitmq_host,
            port=self.config.rabbitmq_port,
            virtual_host=self.config.rabbitmq_vhost,
            credentials=cred)

        try:
            self.connection = TornadoConnection(
                param, on_open_callback=self.on_connected)
            self.connection.add_on_close_callback(self.on_closed)
        except AMQPConnectionError:
            self.logger.info(
                'django-sockjs-server(SockjsServer): error connect, wait 5 sec'
            )
            time.sleep(5)
            self.reconnect()

        self.last_reconnect = now()
Пример #5
0
class Sender(object):
    def __init__(self, settings, io_loop):
        self.io_loop = io_loop
        self.channel = None
        self.exchange = "poly"

        credentials = None
        if settings.get("username", None):
            credentials = pika.PlainCredentials(
                settings["username"],
                settings["password"]
            )
        self.connection_parameters = None
        if credentials or settings.get("host", None) or settings.get("vhost"):
            self.connection_parameters = pika.ConnectionParameters(
                credentials=credentials,
                host=settings.get("host", None),
                port=settings.get("port", None),
                virtual_host=settings.get("vhost", None)
            )
        else:
            raise Exception("NO self.connection_parameters")
        self.settings = settings

    def connect(self):
        logging.info("MQ connect...")
        try:
            self.connection = TornadoConnection(
                self.connection_parameters,
                self.on_connected
            )
            self.connection.add_on_close_callback(self.on_close)
        except socket.error, e:
            logging.warn("connection failed, trying again in 5 seconds")
            self.io_loop.add_timeout(time.time() + 5, self.connect)
Пример #6
0
 def connect(self):
     self.connection = TornadoConnection(
         self.parameters,
         on_open_callback=self.on_connected,
         stop_ioloop_on_close=False,
         on_open_error_callback=self.on_open_error)
     self.connection.add_on_close_callback(self.on_closed)
Пример #7
0
def test_tornado_connection_basic_consume_outside_transaction(producer):
    def on_message(channel, method_frame, header_frame, body):
        assert hasattr(method_frame, '_nr_start_time')
        assert body == BODY
        channel.basic_ack(method_frame.delivery_tag)
        channel.close()
        connection.close()
        connection.ioloop.stop()

    def on_open_channel(channel):
        basic_consume(channel, QUEUE, on_message)

    def on_open_connection(connection):
        connection.channel(on_open_callback=on_open_channel)

    connection = TornadoConnection(pika.ConnectionParameters(
        DB_SETTINGS['host']),
                                   on_open_callback=on_open_connection)

    try:
        connection.ioloop.start()
    except:
        connection.close()
        connection.ioloop.stop()
        raise
Пример #8
0
 def connect(self):
     if self.connecting:
         return
     self.connecting = True
     self.connection = TornadoConnection(
         pika.ConnectionParameters(host=self.host),
         on_open_callback=self.on_connected)
     self.connection.add_on_close_callback(self.on_closed)
Пример #9
0
    def connect(self):
        if self.connecting:
            return

        self.connecting = True

        self.connection = TornadoConnection(on_open_callback=self.on_connected)
        self.connection.add_on_close_callback(self.on_closed)
Пример #10
0
	def start(self):
		credentials = pika.PlainCredentials('guest', 'guest')
		param = pika.ConnectionParameters(host="localhost",
						port=5672,
						virtual_host="/",
						credentials=credentials)

		self.connection = TornadoConnection(param, on_open_callback=self.on_connected)
		self.connection.set_backpressure_multiplier(100000)
Пример #11
0
    def connect(self):
        try:
            logger = logging.getLogger('rmq_tornado')
            credentials = pika.PlainCredentials(RMQ_USER, RMQ_PWD)
            param = pika.ConnectionParameters(host=RMQ_HOST, port=RMQ_PORT, credentials=credentials)

            self.connection = TornadoConnection(param, on_open_callback=self.on_connected)
        except Exception as e:
            logger.error('Something went wrong... %s', e)
Пример #12
0
 def connect(self):
     if self.connecting:
         logging.error("PikaClient already connected")
         return
     logging.info("connecting to RabbitMQ")
     self.connecting = True
     param = pika.ConnectionParameters(host='10.212.66.144', port=5672)
     self.connection = TornadoConnection(param,
                                         on_open_callback=self.on_connected)
     self.connection.add_on_close_callback(self.on_closed)
Пример #13
0
 def connect(self):
     try:
         self.connection = TornadoConnection(
             self.parameters,
             on_open_callback=self.on_connected,
             stop_ioloop_on_close=False,
             on_open_error_callback=self.on_open_error)
         self.connection.add_on_close_callback(self.on_closed)
     except:
         logging.info("connect faield")
Пример #14
0
    def connect(self):
        if self.connecting:
            pika.log.info('PikaClient: Already connecting to RabbitMQ')
            return
        pika.log.info('PikaClient: Connecting to RabbitMQ on localhost:5672')
        self.connecting = True

        param = pika.ConnectionParameters(host='115.146.93.175')
        self.connection = TornadoConnection(param,
                                            on_open_callback=self.on_connected)
        self.connection.add_on_close_callback(self.on_closed)
Пример #15
0
class PikaClient(object):
    def __init__(self, io_loop):
        self.io_loop = io_loop

        self.connected = False
        self.connecting = False
        self.connection = None
        self.channel = None

        self.event_listeners = set([])

    def connect(self):
        if self.connecting:
            return

        self.connecting = True

        self.connection = TornadoConnection(on_open_callback=self.on_connected)
        self.connection.add_on_close_callback(self.on_closed)

    def on_connected(self, connection):
        self.connected = True
        self.connection = connection
        self.connection.channel(self.on_channel_open)

    def on_channel_open(self, channel):
        self.channel = channel
        channel.queue_declare(queue="plase",
                              durable=True,
                              callback=self.on_queue_declared)

    def on_queue_declared(self, frame):
        self.channel.basic_consume(self.on_message, queue='plase')

    def on_closed(self, connection):
        self.io_loop.stop()

    def on_message(self, channel, method, header, body):
        self.notify_listeners(body)

    def notify_listeners(self, event_obj):
        event_json = json.dumps(event_obj)

        for listener in self.event_listeners:
            listener.write_message(event_json)

    def add_event_listener(self, listener):
        self.event_listeners.add(listener)

    def remove_event_listener(self, listener):
        try:
            self.event_listeners.remove(listener)
        except KeyError:
            pass
Пример #16
0
 def connect(self):
     if self.connecting:
         print('Already connecting to RabbitMQ.')
         return
     print("Connecting to RabbitMQ")
     self.connecting = True
     creds = pika.PlainCredentials('zyl', 'pwd_zyl')
     params = pika.ConnectionParameters(host='112.74.75.38', port=5672,
                                        virtual_host='/', credentials=creds)
     self.connection = TornadoConnection(params,
                                         on_open_callback=self.on_connect)
     self.connection.add_on_close_callback(self.on_closed)
Пример #17
0
 def connect(self):
     if self.connecting:
         log.info('Already connecting to RabbitMQ.')
         return
     #self.L.logger.info("Connecting to RabbitMQ")
     self.connecting = True
     creds = pika.PlainCredentials('guest', 'guest')
     params = pika.ConnectionParameters(host='localhost', port=5672,
                                        virtual_host='/', credentials=creds)
     self.connection = TornadoConnection(params,
                                         on_open_callback=self.on_connect)
     self.connection.add_on_close_callback(self.on_closed)
Пример #18
0
class PikaClient(object):
    def __init__(self, io_loop):
        self.io_loop = io_loop

        self.connected = False
        self.connecting = False
        self.connection = None
        self.channel = None

        self.event_listeners = set([])

    def connect(self):
        if self.connecting:
            return

        self.connecting = True

        self.connection = TornadoConnection(on_open_callback=self.on_connected)
        self.connection.add_on_close_callback(self.on_closed)

    def on_connected(self, connection):
        self.connected = True
        self.connection = connection
        self.connection.channel(self.on_channel_open)

    def on_channel_open(self, channel):
        self.channel = channel
        channel.queue_declare(queue="plase", durable=True, callback=self.on_queue_declared)

    def on_queue_declared(self, frame):
        self.channel.basic_consume(self.on_message, queue="plase")

    def on_closed(self, connection):
        self.io_loop.stop()

    def on_message(self, channel, method, header, body):
        self.notify_listeners(body)

    def notify_listeners(self, event_obj):
        event_json = json.dumps(event_obj)

        for listener in self.event_listeners:
            listener.write_message(event_json)

    def add_event_listener(self, listener):
        self.event_listeners.add(listener)

    def remove_event_listener(self, listener):
        try:
            self.event_listeners.remove(listener)
        except KeyError:
            pass
Пример #19
0
    def _connect(self):
        conn = pika.ConnectionParameters(
            host=CREDS['host'], port=int(CREDS['port']),
            virtual_host='/',
            credentials=pika.PlainCredentials(
                CREDS['user'], CREDS['pasw']))

        self.tc = TornadoConnection(
            conn, on_open_callback=self.on_connected,
            on_open_error_callback=self.on_disconnect
        )

        self.tc.add_on_close_callback(self.on_disconnect)
Пример #20
0
    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

        """
        LOGGER.info('Connecting to %s', self._url)
        self._connection = TornadoConnection(
            pika.URLParameters(self._url),
            on_open_callback=self.on_connection_open,
            on_open_error_callback=self.on_connection_open_error)
        return self._connection
Пример #21
0
class AMQPClient(object):

    channels = {}

    def __init__(self, uri, logger, on_connected_callback=None):
        self._uri = uri or 'amqp://*****:*****@localhost:5672/%2f'
        self._logger = logger or logging.getLogger(self.__class__.__name__)
        self._on_connected_callback = on_connected_callback
        self._amqp_connect()

    @property
    def uri(self):
        return self._uri

    @property
    def connection(self):
        return self._connection

    def __getattr__(self, name):
        if name in self.channels.keys():
            return self.channels[name]
        self.channels[name] = AMQPChannelClient(self, name)
        return self.channels[name]

    def __getitem__(self, name):
        return self.__getattr__(name)

    def _amqp_connect(self):
        self._connection = TornadoConnection(pika.URLParameters(self.uri),
            on_open_callback=self._on_amqp_opened, stop_ioloop_on_close=True)

    def _on_amqp_opened(self, connection):
        self._logger.debug('AMQP connection opened')
        self.connection.add_on_close_callback(self._on_connection_closed)
        if self._on_connected_callback:
            self._on_connected_callback()

    def _on_connection_closed(self, connection):
        #TODO: Log disconnection details...
        #self.log.warning('Server closed connection, reopening: (%s) %s',
                         #method_frame.method.reply_code,
                         #method_frame.method.reply_text)
        #self.log.debug(connection._is_method_frame())
        self._connection = self._amqp_connect()

    def close(self):
        for channel in self.channels.values():
            channel.cancel_consume()
        self._logger.debug('Closing AMQP connection')
        self._connection.close()
Пример #22
0
    def connect(self):
        if self.connecting:
            pika.log.info('PikaClient: Already connecting to RabbitMQ')
            return
        pika.log.info('PikaClient: Connecting to RabbitMQ on localhost:5672')
        self.connecting = True

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

    def __init__(self, io_loop):
        print(f'{self.__str__()}: __init__()')
        self.io_loop = io_loop
        self.connection = None
        self.connected = False
        self.channel = None

    # 打开链接
    def connect(self):
        if self.connected:
            return
        cred = PlainCredentials(USERNAME, PASSWORD)
        params = ConnectionParameters(host=HOST, port=PORT, virtual_host=VHOST, credentials=cred)
        self.connection = TornadoConnection(params, on_open_callback=self.on_connected)
        self.connection.add_on_close_callback(callback=self.on_closed)

    # 连接成功 callback
    def on_connected(self, connection):
        self.connected = True
        self.connection = connection
        print(f'{self.__str__()}: connected() succeed')
        self.connection.channel(on_open_callback=self.on_channel_open)

    # 关闭连接 callback
    def on_closed(self, connection):
        print(f'{self.__str__()}: on_closed()')
        connection.close()
        self.connection = None
        self.connected = False
        self.io_loop.stop()

    # 打开通道 callback
    def on_channel_open(self, channel):
        self.channel = channel
        self.channel.exchange_declare(exchange=EXCHANGE, exchange_type="direct", durable=True)
        # queue如果通过其他方式已经创建的话可能出错, 如果出错先删除再重新创建
        try:
            self.channel.queue_declare(queue=QUEUE, durable=True)
        except Exception as e:
            print(f'{self.__str__()} channel.queue_declare Error: ', e)
            channel.queue_delete(queue=QUEUE)
            channel.queue_declare(queue=QUEUE, durable=True)
        self.channel.queue_bind(queue=QUEUE, exchange=EXCHANGE, routing_key=ROUTING_KEY)
        # 如果是消费者, 绑定消息处理 callback
        if isinstance(self, Consumer):
            self.channel.basic_consume(queue=QUEUE, on_message_callback=self.handle_message, auto_ack=True)
Пример #24
0
 def create_connection(self):
     url_params = self._config.MQ_URI
     future = Future()
     TornadoConnection(URLParameters(url_params),
                       partial(self.on_connection_open, future),
                       partial(self.on_open_error, future))
     return future
Пример #25
0
 def connect(self):
     'Establish RabbitMQ connection.'
     
     self.connection = TornadoConnection(
             pika.ConnectionParameters(host=self._host, port=self._port), 
             on_open_callback=self.on_connected)
     logger.info('connecting to RabbitMQ...')
Пример #26
0
    def connect(self):
        if not sickrage.app.api.token or not sickrage.app.config.general.server_id:
            IOLoop.current().call_later(5, self.reconnect)
            return

        if sickrage.app.api.token_time_remaining < (int(sickrage.app.api.token['expires_in']) / 2):
            if not sickrage.app.api.refresh_token():
                IOLoop.current().call_later(5, self.reconnect)
                return

        try:
            credentials = pika.credentials.PlainCredentials(username='******', password=sickrage.app.api.token["access_token"])

            context = ssl.create_default_context()
            context.check_hostname = False
            context.verify_mode = ssl.CERT_NONE

            parameters = pika.ConnectionParameters(
                host=self._amqp_host,
                port=self._amqp_port,
                virtual_host=self._amqp_vhost,
                credentials=credentials,
                socket_timeout=300,
                ssl_options=pika.SSLOptions(context)
            )

            TornadoConnection(
                parameters,
                on_open_callback=self.on_connection_open,
                on_close_callback=self.on_connection_close,
                on_open_error_callback=self.on_connection_open_error
            )
        except (AMQPConnectorException, AMQPConnectionError, SSLCertVerificationError):
            sickrage.app.log.debug("AMQP connection error, attempting to reconnect")
            IOLoop.current().call_later(5, self.reconnect)
Пример #27
0
    def connect(self):
        if self.connecting:
            self.logger.info('django-sockjs-server(PikaClient): Already connecting to RabbitMQ')
            return

        self.logger.info('django-sockjs-server(PikaClient): Connecting to RabbitMQ')
        self.connecting = True

        cred = pika.PlainCredentials(self.config.rabbitmq_user, self.config.rabbitmq_password)
        param = pika.ConnectionParameters(
            host=self.config.rabbitmq_host,
            port=self.config.rabbitmq_port,
            virtual_host=self.config.rabbitmq_vhost,
            credentials=cred
        )

        try:
            self.connection = TornadoConnection(param,
                                                on_open_callback=self.on_connected)
            self.connection.add_on_close_callback(self.on_closed)
        except AMQPConnectionError:
            self.logger.info('django-sockjs-server(PikaClient): error connect, wait 5 sec')
            time.sleep(5)
            self.reconnect()

        self.last_reconnect = now()
    def connect(self):
        """This method connects to RabbitMQ using a TornadoConnection object,
        returning the connection handle.

        When the connection is established, the on_connection_open method
        will be invoked by pika.

        :rtype: pika.adapters.TornadoConnection

        """
        no_of_servers = len(self._rabbit_urls)

        while True:
            server_choice = (self._count % no_of_servers) - 1

            self._url = self._rabbit_urls[server_choice]

            try:
                logger.info('Connecting', attempt=self._count)
                return TornadoConnection(pika.URLParameters(self._url),
                                         on_open_callback=self.on_connection_open,
                                         on_open_error_callback=self.on_connection_open_error,
                                         on_close_callback=self.on_connection_closed)
            except pika.exceptions.AMQPConnectionError:
                logger.exception("Connection error")
                self._delay_before_reconnect()

                continue
Пример #29
0
    def connect(self, url=None, options=None, callback=None):
        if url is not None:
            self.url = url
        purl = urlparse(self.url)
        credentials = pika.PlainCredentials(purl.username, purl.password)
        virtual_host = purl.path[1:]
        host = purl.hostname
        port = purl.port

        options = options or {}
        options = dict([(k.lstrip('DEFAULT_').lower(), v)
                        for k, v in options.items()])
        options.update(host=host,
                       port=port,
                       virtual_host=virtual_host,
                       credentials=credentials)

        params = pika.ConnectionParameters(**options)
        try:
            TornadoConnection(params,
                              stop_ioloop_on_close=False,
                              on_open_callback=partial(self.on_connect,
                                                       callback),
                              custom_ioloop=self.io_loop)
        except AMQPConnectionError:
            logging.info('Retrying to connect in 2 seconds')
            self.io_loop.add_timeout(
                timedelta(seconds=2),
                partial(self.connect,
                        url=url,
                        options=options,
                        callback=callback))
Пример #30
0
    def connect(self) -> TornadoConnection:
        """This method connects to the broker, returning the connection handle."""
        logger.info(f"Connecting to {self._host}:{self._port}{self._vhost}")
        # set amqp credentials
        if self._username:
            credentials = pika.PlainCredentials(self._username, self._password)
            # set amqp connection parameters
            parameters = pika.ConnectionParameters(
                host=self._host,
                port=self._port,
                virtual_host=self._vhost,
                credentials=credentials,
            )
        else:
            parameters = pika.ConnectionParameters(
                host=self._host,
                port=self._port,
                virtual_host=self._vhost,
            )

        # connect
        connection = TornadoConnection(
            parameters=parameters,
            on_open_callback=self.on_connection_open,
            on_open_error_callback=self.on_connection_open_error,
            on_close_callback=self.on_connection_closed,
        )
        return connection
Пример #31
0
    def _try_connect(self):
        self.logger.debug("start creating connection")
        future = Future()
        self._io_loop.add_timeout(
            datetime.timedelta(seconds=self._timeout),
            functools.partial(self._on_timeout, future=future))

        def open_callback(unused_connection):
            self.logger.debug("created connection")
            self._current_status = self.OPEN_STATUS
            future.set_result(unused_connection)

        def open_error_callback(connection, exception):
            self.logger.error("open connection with error: %s", exception)
            self._current_status = self.CLOSE_STATUS
            future.set_exception(exception)

        def close_callback(connection, reason):
            self.logger.error("Connect closed, %s", reason)
            self._current_status = self.CLOSE_STATUS

        TornadoConnection(self._parameter,
                          on_open_callback=open_callback,
                          on_open_error_callback=open_error_callback,
                          on_close_callback=close_callback,
                          custom_ioloop=self._io_loop)
        return future
Пример #32
0
class PikaClient(object):
    """A modified class as described in pika's demo_tornado.py.
    It handles the connection for the Tornado instance. Messaging/RPC
    callbacks are handled by the Tornado RequestHandler above."""
    def __init__(self):
        self.connecting = False
        self.connection = None
        self.channel = None
        #self.L = log_class.Logger()
    def connect(self):
        if self.connecting:
            log.info('Already connecting to RabbitMQ.')
            return
        #self.L.logger.info("Connecting to RabbitMQ")
        self.connecting = True
        creds = pika.PlainCredentials('guest', 'guest')
        params = pika.ConnectionParameters(host='localhost',
                                           port=5672,
                                           virtual_host='/',
                                           credentials=creds)
        self.connection = TornadoConnection(params,
                                            on_open_callback=self.on_connect)
        self.connection.add_on_close_callback(self.on_closed)

    def on_connect(self, connection):
        self.connection = connection
        connection.channel(self.on_channel_open)

    def on_channel_open(self, channel):
        #self.L.logger.info('Channel Open')
        self.channel = channel
        # I'm having trouble using named exchanges.
        ## channel.exchange_declare(exchange='rpc_ex', type='direct',
        ##                          auto_delete=True, durable=False,
        ##                          callback=self.on_exchange_declare)

    def on_exchange_declare(self, frame):
        log.info("Exchange declared.")

    def on_basic_cancel(self, frame):
        log.info('Basic Cancel Ok.')
        # If we don't have any more consumer processes running close
        self.connection.close()

    def on_closed(self, connection):
        # We've closed our pika connection so stop the demo
        tornado.ioloop.IOLoop.instance().stop()
Пример #33
0
    def connect(self):
        if self.connecting:
            return

        self.connecting = True

        self.connection = TornadoConnection(on_open_callback=self.on_connected)
        self.connection.add_on_close_callback(self.on_closed)
Пример #34
0
  def connect(self):
    LOGGER.info('Connecting to RabbitMQ')
    # exc_type, exc_value, exc_traceback = sys.exc_info()
    # traceback.print_tb(exc_traceback, limit=None, file=sys.stdout)
    # self.connecting = True

    self._connection = TornadoConnection(rc.connParam,
      on_open_callback=self.on_connection_open)
Пример #35
0
class AMQPClient(object):
    "Connect to RabbitMQ and create a channel"

    def __init__(self, on_msg_callback=None, oid=None, io_loop=None,
                 on_channel_created=None):
        self.oid = oid or options.oid
        self.io_loop = io_loop or IOLoop.instance()
        self.on_msg_callback = on_msg_callback
        self.connection = None
        self.channel = None
        self._on_channel_created = on_channel_created
        self.checker = PeriodicCallback(self._check_connection, 1000)

    def connect(self):
        "Connect to RabbitMQ"
        log.debug("Connecting to RabbitMQ")
        if self.connection:
            return
        self.connection = TornadoConnection(
            get_conn_params(),
            self.on_connected,
            custom_ioloop=self.io_loop)

    def on_connected(self, connection):
        "Create a channel just after connected"
        log.debug("%s is established" % connection)
        self.connection.channel(self.on_channel_created)
        self.checker.start()

    def on_channel_created(self, channel):
        "Implement in subclasses"
        log.debug("%s is established" % channel)
        self.channel = channel
        if self._on_channel_created:
            self._on_channel_created(channel)

    def _check_connection(self):
        "Restablish connection to server if we lost it"
        if self.connection:
            try:
                self.connection.socket.fileno()
            except socket.error, exc:
                log.debug("lost connection to RabbitMQ, %s" % str(exc))
                self.checker.stop()
                self.connection = None
                self.connect()
Пример #36
0
    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)
        self.connection = TornadoConnection(param,
                                            on_open_callback=self.on_connected)
Пример #37
0
class PikaClient(object):
    """A modified class as described in pika's demo_tornado.py.
    It handles the connection for the Tornado instance. Messaging/RPC
    callbacks are handled by the Tornado RequestHandler above."""

    def __init__(self):
        self.connecting = False
        self.connection = None
        self.channel = None
        # self.L = log_class.Logger()

    def connect(self):
        if self.connecting:
            log.info("Already connecting to RabbitMQ.")
            return
        # self.L.logger.info("Connecting to RabbitMQ")
        self.connecting = True
        creds = pika.PlainCredentials("guest", "guest")
        params = pika.ConnectionParameters(host="localhost", port=5672, virtual_host="/", credentials=creds)
        self.connection = TornadoConnection(params, on_open_callback=self.on_connect)
        self.connection.add_on_close_callback(self.on_closed)

    def on_connect(self, connection):
        self.connection = connection
        connection.channel(self.on_channel_open)

    def on_channel_open(self, channel):
        # self.L.logger.info('Channel Open')
        self.channel = channel
        # I'm having trouble using named exchanges.
        ## channel.exchange_declare(exchange='rpc_ex', type='direct',
        ##                          auto_delete=True, durable=False,
        ##                          callback=self.on_exchange_declare)

    def on_exchange_declare(self, frame):
        log.info("Exchange declared.")

    def on_basic_cancel(self, frame):
        log.info("Basic Cancel Ok.")
        # If we don't have any more consumer processes running close
        self.connection.close()

    def on_closed(self, connection):
        # We've closed our pika connection so stop the demo
        tornado.ioloop.IOLoop.instance().stop()
Пример #38
0
 def connect(self):
     if self.connecting:
         return
     self.connecting = True
     self.connection = TornadoConnection(
         pika.ConnectionParameters(host=self.host),
         on_open_callback=self.on_connected
     )
     self.connection.add_on_close_callback(self.on_closed)
class PikaClient(object):
    def __init__(self):
        self.connected = False
        self.connection = None
        self.channel = None
        self.messages = list()

    def connect(self):
        self.connection = TornadoConnection(on_open_callback=self.on_connected)

    def on_connected(self, connection):
        self.connected = True
        self.connection = connection
        self.connection.channel(self.on_channel_open)

    def on_channel_open(self, channel):
        pika.log.info("channel open")
        self.channel = channel
Пример #40
0
 def connect(self):
     if self.connecting:
         return
     self.connecting = True
     creds = pika.PlainCredentials(
         self.config.get('user'),
         self.config.get('pw')
     )
     params = pika.ConnectionParameters(
         host=self.config.get('host'),
         port=5671 if self.config.get('amqps') else 5672,
         virtual_host=self.config.get('vhost'),
         credentials=creds
     )
     self.connection = TornadoConnection(params)
     self.connection.add_on_open_callback(self.on_connect)
     self.connection.add_on_close_callback(self.on_closed)
     return
Пример #41
0
	def connect(self):
		try:
			logger = logging.getLogger('rmq_tornado')
			credentials = pika.PlainCredentials(RMQ_USER, RMQ_PWD)
			param = pika.ConnectionParameters(host=RMQ_HOST, port=RMQ_PORT, credentials=credentials)

			self.connection = TornadoConnection(param, on_open_callback=self.on_connected)
		except Exception as e:
			logger.error('Something went wrong... %s', e)
Пример #42
0
 def connect(self):
     "Connect to RabbitMQ"
     log.debug("Connecting to RabbitMQ")
     if self.connection:
         return
     self.connection = TornadoConnection(
         get_conn_params(),
         self.on_connected,
         custom_ioloop=self.io_loop)
Пример #43
0
class PikaClient(object):
    """A modified class as described in pika's demo_tornado.py.
    It handles the connection for the Tornado instance. Messaging/RPC
    callbacks are handled by the Tornado RequestHandler above."""

    def __init__(self):
        self.connecting = False
        self.connection = None
        self.channel = None

    def connect(self):
        # print 22222222
        if self.connecting:
            logger.info('Already connecting to RabbitMQ.')
            return
        logger.info("Connecting to RabbitMQ")
        self.connecting = True
        creds = pika.PlainCredentials('zyl', 'pwd_zyl')
        params = pika.ConnectionParameters(host='112.74.75.38', port=5672,
                                     credentials=creds)
        self.connection = TornadoConnection(params,
                                            on_open_callback=self.on_connect)
        self.connection.add_on_close_callback(self.on_closed)
        # print 4444444444

    def on_connect(self, connection):
        self.connection = connection
        connection.channel(self.on_channel_open)

    def on_channel_open(self, channel):
        logger.info('Channel Open')
        self.channel = channel

    def on_exchange_declare(self, frame):
        logger.info("Exchange declared.")

    def on_basic_cancel(self, frame):
        logger.info('Basic Cancel Ok.')
        # If we don't have any more consumer processes running close
        self.connection.close()

    def on_closed(self, connection):
        # We've closed our pika connection so stop the demo
        print 'close'
Пример #44
0
class Pika(object):

    """ rabbitMQ manager.  """

    def __init__(self):
        """ rabbitMQ manager init. """
        self.connection = None
        self.connecting = False
        self.channel = None

    def connect(self):
        """ rabbitMQ manager connect. """
        if self.connecting:
            logging.info('Already connecting to RabbitMQ')
            return
        logging.info('Connectiong to RabbitMQ')
        self.connecting = True
        credentials = pika.PlainCredentials('guest', 'guest')
        params = pika.ConnectionParameters(
            host='localhost',
            port=5672,
            virtual_host='/smsgo',
            credentials=credentials)
        self.connection = TornadoConnection(
            params, on_open_callback=self.on_connect)
        self.connection.add_on_close_callback(on_closed)

    def on_connect(self, connection):
        """ rabbitMQ manager on connect callback. """
        self.connection = connection
        connection.channel(self.on_channel_open)

    def on_channel_open(self, channel):
        """ rabbitMQ manager on channel open callback. """
        logging.info('Channel Open')
        self.channel = channel

    #def on_exchange_declare(self, frame):
        #logging.info('Exchange Declare')

    def on_basic_cancel(self, frame):
        """ rabbitMQ manager on basic cancel callback. """
        logging.info('Basic Cancel Ok')
        self.connection.close()
Пример #45
0
 def connect(self):
     if self.connecting:
         log.info("Already connecting to RabbitMQ.")
         return
     # self.L.logger.info("Connecting to RabbitMQ")
     self.connecting = True
     creds = pika.PlainCredentials("guest", "guest")
     params = pika.ConnectionParameters(host="localhost", port=5672, virtual_host="/", credentials=creds)
     self.connection = TornadoConnection(params, on_open_callback=self.on_connect)
     self.connection.add_on_close_callback(self.on_closed)
Пример #46
0
    def connect(self):
        if self.connecting:
            pika.log.info('PikaClient: Already connecting to RabbitMQ')
            return

        pika.log.info('PikaClient: Connecting to RabbitMQ')
        self.connecting = True

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

        self.connection = TornadoConnection(param,
                                            on_open_callback=self.on_connected)
        self.connection.add_on_close_callback(self.on_closed)
Пример #47
0
    def connect(self):
        if self.connecting:
            pika.log.info("PikaClient: Already connecting to RabbitMQ")
            return
        pika.log.info("PikaClient: Connecting to RabbitMQ on localhost:5672")
        self.connecting = True

        credentials = pika.PlainCredentials("guest", "guest")
        param = pika.ConnectionParameters(host="localhost", port=5672, virtual_host="/", credentials=credentials)
        self.connection = TornadoConnection(param, on_open_callback=self.on_connected)
        self.connection.add_on_close_callback(self.on_closed)
Пример #48
0
    def connect(self):
        if self.connecting:
            pika.log.info('PikaClient: Already connecting to RabbitMQ')
            return
        pika.log.info('PikaClient: Connecting to RabbitMQ on localhost:5672')
        self.connecting = True

        param = pika.ConnectionParameters(host='115.146.93.175')
        self.connection = TornadoConnection(param,
                                            on_open_callback=self.on_connected)
        self.connection.add_on_close_callback(self.on_closed)
Пример #49
0
 def connect(self):
     logging.info("MQ connect...")
     try:
         self.connection = TornadoConnection(
             self.connection_parameters,
             self.on_connected
         )
         self.connection.add_on_close_callback(self.on_close)
     except socket.error, e:
         logging.warn("connection failed, trying again in 5 seconds")
         self.io_loop.add_timeout(time.time() + 5, self.connect)
Пример #50
0
    def connect(self):
        pika.log.info('PikaClient: Connecting to RabbitMQ on localhost:5672')

        credentials = pika.PlainCredentials('guest', 'guest')
        param = pika.ConnectionParameters(host='localhost',
                                          port=5672,
                                          virtual_host="/",
                                          credentials=credentials)
        self.connection = TornadoConnection(param,
                                            on_open_callback=self.on_connected)
        self.connection.add_on_close_callback(self.on_closed)
class PikaClient(object):

    def __init__(self, username='******', exchange_name='ws', password='******', host='localhost', port=5672, virtual_host='/'):
	self.exchange_name = exchange_name

        # Options
        self.username = username
        self.password = password
        self.host = host
        self.port = port
        self.virtual_host = virtual_host

        # Default values
        self.connected = False
        self.connecting = False
        self.connection = None
        self.channel = None

    def connect(self):
        if self.connecting:
            pika.log.info('PikaClient: Already connecting to RabbitMQ')
            return
        pika.log.info('PikaClient: Connecting to RabbitMQ on localhost:5672')
        self.connecting = True

        credentials = pika.PlainCredentials(self.username, self.password)
        param = pika.ConnectionParameters(host=self.host,
                                          port=self.port,
                                          virtual_host=self.virtual_host,
                                          credentials=credentials)
        self.connection = TornadoConnection(param,
                                            on_open_callback=self.on_connected)
        self.connection.add_on_close_callback(self.on_closed)

    def on_connected(self, connection):
        pika.log.info('PikaClient: Connected to RabbitMQ on localhost:5672')
        self.connected = True
        self.connection = connection
        self.connection.channel(self.on_channel_open)

    def on_channel_open(self, channel):
        pika.log.info('PikaClient: Channel Open, Declaring Exchange')
        self.channel = channel

        self.channel.exchange_declare(exchange=self.exchange_name,
                                      type="direct",
                                      callback=self.on_exchange_declared)

    def on_exchange_declared(self, frame):
        pika.log.info('PikaClient: Exchange Declared, Ready for declaring Queues')

    def on_basic_cancel(self, frame):
        pika.log.info('PikaClient: Basic Cancel Ok')
        # If we don't have any more consumer processes running close
        self.connection.close()

    def on_closed(self, connection):
        # We've closed our pika connection so stop the demo
        tornado.ioloop.IOLoop.instance().stop()
Пример #52
0
class RabbitClient(object):

    """Managing incoming messages from Rabbit Service"""

    def __init__(self, app=None):
        self.app = app
        self._connect()

    def _connect(self):
        conn = pika.ConnectionParameters(
            host=CREDS['host'], port=int(CREDS['port']),
            virtual_host='/',
            credentials=pika.PlainCredentials(
                CREDS['user'], CREDS['pasw']))

        self.tc = TornadoConnection(
            conn, on_open_callback=self.on_connected,
            on_open_error_callback=self.on_disconnect
        )

        self.tc.add_on_close_callback(self.on_disconnect)

    def on_disconnect(self, *args):
        logger.warning("Connection lost, reconnect in 5 seconds...")
        IOLoop.instance().add_timeout(
            time.time() + 5, self._connect)

    def on_connected(self, con):
        con.channel(self.on_channel_open)

    def on_channel_open(self, channel):
        channel.basic_consume(consumer_callback=self.on_message,
                              queue=CREDS['queue'],
                              no_ack=True)

    def on_message(self, channel, method, header, body):
        self.app.manager.send(body)
    def connect(self):
        if self.connecting:
            pika.log.info('PikaClient: Already connecting to RabbitMQ')
            return
        pika.log.info('PikaClient: Connecting to RabbitMQ on localhost:5672')
        self.connecting = True

        credentials = pika.PlainCredentials(self.username, self.password)
        param = pika.ConnectionParameters(host=self.host,
                                          port=self.port,
                                          virtual_host=self.virtual_host,
                                          credentials=credentials)
        self.connection = TornadoConnection(param,
                                            on_open_callback=self.on_connected)
        self.connection.add_on_close_callback(self.on_closed)
Пример #54
0
 def connect(self):
     """ rabbitMQ manager connect. """
     if self.connecting:
         logging.info('Already connecting to RabbitMQ')
         return
     logging.info('Connectiong to RabbitMQ')
     self.connecting = True
     credentials = pika.PlainCredentials('guest', 'guest')
     params = pika.ConnectionParameters(
         host='localhost',
         port=5672,
         virtual_host='/smsgo',
         credentials=credentials)
     self.connection = TornadoConnection(
         params, on_open_callback=self.on_connect)
     self.connection.add_on_close_callback(on_closed)
Пример #55
0
    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)
        self.connection = TornadoConnection(param,
                                            on_open_callback=self.on_connected)
Пример #56
0
    def connect(self):
        if self.connecting:
            pika.log.info("PikaClient: Already connecting to RabbitMQ")
            return

        pika.log.info("PikaClient: Connecting to RabbitMQ")
        self.connecting = True

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

        self.connection = TornadoConnection(param, on_open_callback=self.on_connected)
        self.connection.add_on_close_callback(self.on_closed)
Пример #57
0
 def connect(self):
     if self.connecting:
         self.logger.warning('Already connecting to RabbitMQ')
         return
     param = self._connect_pull[self._connect_index]
     self.logger.debug('Connecting to RabbitMQ on '
                       '{host}:{port}'.format(host=param.host,
                                              port=param.port))
     self.connecting = True
     # TODO: add on_connection_error
     try:
         self.connection = TornadoConnection(
             param,
             on_open_callback=self.on_connected
         )
         self.connection.add_on_close_callback(self.on_closed)
     except AMQPConnectionError:
         self.reconnect()
Пример #58
0
    def connect(self):
        if self.connecting:
            pika.log.info('PikaClient: Already connecting to RabbitMQ')
            return

        pika.log.info('PikaClient: Connecting to RabbitMQ')
        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)
        self.connection.add_on_close_callback(self.on_closed)