Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def safe_connect_nonblocking_socket(sock, addr_pair):
"""Initiate socket connection, suppressing EINPROGRESS/EWOULDBLOCK
:param socket.socket sock
:param addr_pair: two tuple of address string and port integer
"""
try:
sock.connect(addr_pair)
except pika.compat.SOCKET_ERROR as error:
# EINPROGRESS for posix and EWOULDBLOCK for windows
if error.errno not in (errno.EINPROGRESS, errno.EWOULDBLOCK,):
raise
def get_dead_socket_address(self):
"""
:return: socket address pair (ip-addr, port) that will refuse connection
"""
s1, s2 = pika.compat._nonblocking_socketpair()
s2.close()
self.addCleanup(s1.close)
return s1.getsockname() # pylint: disable=E1101
def safe_connect_nonblocking_socket(sock, addr_pair):
"""Initiate socket connection, suppressing EINPROGRESS/EWOULDBLOCK
:param socket.socket sock
:param addr_pair: two tuple of address string and port integer
"""
try:
sock.connect(addr_pair)
except pika.compat.SOCKET_ERROR as error:
# EINPROGRESS for posix and EWOULDBLOCK for windows
if error.errno not in (errno.EINPROGRESS, errno.EWOULDBLOCK,):
raise
def start(self):
nbio = self.create_nbio()
original_data = tuple(
os.urandom(1000) for _ in pika.compat.xrange(1000))
original_data_length = sum(len(s) for s in original_data)
my_protocol_bucket = []
logger = self.logger
class TestStreamConnectorTxRxStreamProtocol(
nbio_interface.AbstractStreamProtocol):
def __init__(self):
self.transport = None # type: nbio_interface.AbstractStreamTransport
self.connection_lost_error_bucket = []
self.eof_rx = False
self.all_rx_data = b''
my_protocol_bucket.append(self)
TestStreamConnectorTxRxStreamProtocol,
sock,
on_streaming_creation_done)
nbio.connect_socket(sock,
echo.server_address,
on_socket_connect_done)
nbio.run()
self.assertEqual(socket_connect_done_result_bucket, [None])
my_proto = my_protocol_bucket[0] # type: TestStreamConnectorTxRxStreamProtocol
error = my_proto.connection_lost_error_bucket[0]
self.assertIsInstance(error, pika.compat.SOCKET_ERROR)
# NOTE: we occasionally see EPROTOTYPE on OSX
self.assertIn(error.errno,
[errno.EPIPE, errno.ECONNRESET, errno.EPROTOTYPE])
on_done=on_done)
nbio.run()
self.assertEqual(len(result_bucket), 1)
result = result_bucket[0]
self.logger.debug('TestGetaddrinfoWWWGoogleDotComPort80: result=%r',
result)
self.assertIsInstance(result, list)
self.assertEqual(len(result[0]), 5)
for family, socktype, proto, canonname, sockaddr in result:
self.assertIn(family, [socket.AF_INET, socket.AF_INET6])
self.assertEqual(socktype, socket.SOCK_STREAM)
if pika.compat.ON_WINDOWS:
self.assertEqual(proto, socket.IPPROTO_IP)
else:
self.assertEqual(proto, socket.IPPROTO_TCP)
self.assertEqual(canonname, '') # AI_CANONNAME not requested
ipaddr, port = sockaddr[:2]
self.assertIsInstance(ipaddr, str)
self.assertGreater(len(ipaddr), 0)
socket.inet_pton(family, ipaddr)
self.assertEqual(port, 80)
self.assertEqual(ref.cancel(), False)
"""
super(URLParameters, self).__init__()
self._all_url_query_values = None
# Handle the Protocol scheme
#
# Fix up scheme amqp(s) to http(s) so urlparse won't barf on python
# prior to 2.7. On Python 2.6.9,
# `urlparse('amqp://127.0.0.1/%2f?socket_timeout=1')` produces an
# incorrect path='/%2f?socket_timeout=1'
if url[0:4].lower() == 'amqp':
url = 'http' + url[4:]
parts = pika.compat.urlparse(url)
if parts.scheme == 'https':
# Create default context which will get overridden by the
# ssl_options URL arg, if any
self.ssl_options = pika.SSLOptions(
context=ssl.create_default_context())
elif parts.scheme == 'http':
self.ssl_options = None
elif parts.scheme:
raise ValueError('Unexpected URL scheme %r; supported scheme '
'values: amqp, amqps' % (parts.scheme,))
if parts.hostname is not None:
self.host = parts.hostname
# Take care of port after SSL status is known
def wake_threadsafe(self):
"""Wake up the poller as soon as possible. As the name indicates, this
method is thread-safe.
"""
with self._waking_mutex:
if self._w_interrupt is None:
return
try:
# Send byte to interrupt the poll loop, use send() instead of
# os.write for Windows compatibility
self._w_interrupt.send(b'X')
except pika.compat.SOCKET_ERROR as err:
if err.errno != errno.EWOULDBLOCK:
raise
except Exception as err:
# There's nothing sensible to do here, we'll exit the interrupt
# loop after POLL_TIMEOUT secs in worst case anyway.
LOGGER.warning("Failed to send interrupt to poller: %s", err)
raise
:param int reply_code: The code number for the close
:param str reply_text: The text reason for the close
:raises pika.exceptions.ConnectionWrongStateError: if called on a closed
connection (NEW in v1.0.0)
"""
if not self.is_open:
msg = '{}.close({}, {!r}) called on closed connection.'.format(
self.__class__.__name__, reply_code, reply_text)
LOGGER.error(msg)
raise exceptions.ConnectionWrongStateError(msg)
LOGGER.info('Closing connection (%s): %s', reply_code, reply_text)
# Close channels that remain opened
for impl_channel in compat.dictvalues(self._impl._channels):
channel = impl_channel._get_cookie()
if channel.is_open:
try:
channel.close(reply_code, reply_text)
except exceptions.ChannelClosed as exc:
# Log and suppress broker-closed channel
LOGGER.warning(
'Got ChannelClosed while closing channel '
'from connection.close: %r', exc)
# Close the connection
self._impl.close(reply_code, reply_text)
self._flush_output(self._closed_result.is_ready)
async def send_start_ok(self):
start_ok_response = b'\0' + pika.compat.as_bytes(self.username) + b'\0' + pika.compat.as_bytes(self.pwd)
start_ok_obj = pika.spec.Connection.StartOk(client_properties=self.client_info, response=start_ok_response)
frame_value = pika.frame.Method(0, start_ok_obj)
await self.sock.sendall(frame_value.marshal())
return