Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def flaky_declare_queue(*args, **kwargs):
nonlocal declare_called
if not declare_called:
declare_called = True
raise pika.exceptions.AMQPConnectionError
return original_declare(*args, **kwargs)
def on_open_error(connection, error):
self.assertIsInstance(error,
pika.exceptions.AMQPConnectionError)
self.stop()
self.broker = Broker(self.nodes)
self.broker._nodes = PropertyMock()
get_node_iterator = lambda: iter(self.nodes.items())
self.broker._nodes.__iter__ = MagicMock(side_effect=get_node_iterator)
def execute(self):
self.connection = self.broker.connect()
def should_recycle_nodes(self):
self.assertEqual(len(self.broker._nodes.__iter__.mock_calls), 2)
class WhenRecyclingNodesWithDelay(_BaseTestCase):
__contexts__ = (
('TornadoConnection', patch(mod + '.TornadoConnection',
side_effect=[AMQPConnectionError(1),
AMQPConnectionError(1),
TornadoConnection])),
('sleep', patch(mod + '.time.sleep')),
)
def configure(self):
self.ctx.TornadoConnection._adapter_connect = MagicMock()
self.broker = Broker({'rabbit1': {}, 'rabbit2': {}})
def execute(self):
self.connection = self.broker.connect(connection_attempts=5,
cycle_delay=sentinel.delay)
def should_sleep(self):
self.ctx.sleep.assert_called_once_with(sentinel.delay)
def _adapter_connect(self):
"""Connect to the RabbitMQ broker
:rtype: bool
:raises: pika.Exceptions.AMQPConnectionError
"""
# Remove the default behavior for connection errors
self.callbacks.remove(0, self.ON_CONNECTION_ERROR)
error = super(BlockingConnection, self)._adapter_connect()
if error:
raise exceptions.AMQPConnectionError(error)
self.socket.settimeout(self.SOCKET_CONNECT_TIMEOUT)
self._frames_written_without_read = 0
self._socket_timeouts = 0
self._timeouts = dict()
self._read_poller = ReadPoller(self.socket.fileno())
self._on_connected()
while not self.is_open:
self.process_data_events()
self.socket.settimeout(self.params.socket_timeout)
self._set_connection_state(self.CONNECTION_OPEN)
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import select
import socket
from oslo_serialization.serializer import json_serializer
from oslo_serialization.serializer import msgpack_serializer
from oslo_utils import timeutils
from pika import exceptions as pika_exceptions
import six
PIKA_CONNECTIVITY_ERRORS = (
pika_exceptions.AMQPConnectionError,
pika_exceptions.ConnectionClosed,
pika_exceptions.ChannelClosed,
socket.timeout,
select.error
)
EXCEPTIONS_MODULE = 'exceptions' if six.PY2 else 'builtins'
INFINITE_STOP_WATCH = timeutils.StopWatch(duration=None).start()
MESSAGE_SERIALIZERS = {
'application/json': json_serializer.JSONSerializer(),
'application/msgpack': msgpack_serializer.MessagePackSerializer()
}
def send_to_rabbitmq(message):
"""
Connects to rabbitmq and sends the json messsage to the queue
:param message:
:return:
"""
credentials = pika.PlainCredentials(settings.RABBITMQ_CONF['username'], settings.RABBITMQ_CONF['password'])
try:
connection = pika.BlockingConnection(pika.ConnectionParameters(
host=settings.RABBITMQ_CONF['host'],
port=settings.RABBITMQ_CONF['port'],
credentials=credentials,
virtual_host=settings.RABBITMQ_CONF['vhost'],
ssl=settings.RABBITMQ_CONF['ssl']))
except pika.exceptions.AMQPConnectionError:
logger.error('Error connecting to RabbitMQ server: %s' % settings.RABBITMQ_CONF['host'])
return
try:
channel = connection.channel()
except Exception as e:
logger.error('Error selecting channel, reason: %e')
return False
try:
channel.queue_declare(queue=settings.RABBITMQ_CONF['queue'], durable=True)
except Exception as e:
logger.error('Error declaring queue: %s, reason: %s' % (settings.RABBITMQ_CONF['queue'], e))
return False
try:
def run(self):
"""
RabbitMQ router loop to keep the connection running.
:return:
"""
self.start()
try:
self.connection.loop()
except KeyboardInterrupt:
pass
except (pika.exceptions.AMQPConnectionError,
pika.exceptions.AMQPChannelError) as exc:
_log.error("RabbitMQ Connection Error. {}".format(exc))
finally:
self.stop()
return self.args[1]
class ConnectionClosedByBroker(ConnectionClosed):
"""Connection.Close from broker."""
class ConnectionClosedByClient(ConnectionClosed):
"""Connection was closed at request of Pika client."""
class ConnectionBlockedTimeout(AMQPConnectionError):
"""RabbitMQ-specific: timed out waiting for connection.unblocked."""
class AMQPHeartbeatTimeout(AMQPConnectionError):
"""Connection was dropped as result of heartbeat timeout."""
class AMQPChannelError(AMQPError):
def __repr__(self):
return '{}: {!r}'.format(self.__class__.__name__, self.args)
class ChannelWrongStateError(AMQPChannelError):
"""Channel is in wrong state for the requested operation."""
class ChannelClosed(AMQPChannelError):
"""The channel closed by client or by broker
import logging
import random
import time
from pika import BlockingConnection, ConnectionParameters, PlainCredentials
from pika.adapters.tornado_connection import TornadoConnection
from pika.exceptions import AMQPConnectionError
from pikachewie.utils import Missing
__all__ = ['Broker']
log = logging.getLogger(__name__)
class BrokerConnectionError(AMQPConnectionError):
"""Raised when a new connection cannot be opened to a ``Broker``."""
pass
class Broker(object):
"""A RabbitMQ broker.
`nodes` is a two-level :class:`dict` containing the names and network
locations of the clustered nodes that comprise the RabbitMQ broker,
e.g.::
{
'bunny1': {'host': 'localhost'},
'bunny2': {'host': 'rabbit.example.com', 'port': 5678}
}
def _reap_last_connection_workflow_error(error):
"""Extract exception value from the last connection attempt
:param Exception error: error passed by the `AMQPConnectionWorkflow`
completion callback.
:returns: Exception value from the last connection attempt
:rtype: Exception
"""
if isinstance(error, connection_workflow.AMQPConnectionWorkflowFailed):
# Extract exception value from the last connection attempt
error = error.exceptions[-1]
if isinstance(error,
connection_workflow.AMQPConnectorSocketConnectError):
error = exceptions.AMQPConnectionError(error)
elif isinstance(error,
connection_workflow.AMQPConnectorPhaseErrorBase):
error = error.exception
return error