desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Deserialize and apply the corresponding query string arg'
def _set_url_locale(self, value):
self.locale = value
'Deserialize and apply the corresponding query string arg'
def _set_url_retry_delay(self, value):
try: retry_delay = float(value) except ValueError as exc: raise ValueError(('Invalid retry_delay value %r: %r' % (value, exc))) self.retry_delay = retry_delay
'Deserialize and apply the corresponding query string arg'
def _set_url_socket_timeout(self, value):
try: socket_timeout = float(value) except ValueError as exc: raise ValueError(('Invalid socket_timeout value %r: %r' % (value, exc))) self.socket_timeout = socket_timeout
'Deserialize and apply the corresponding query string arg'
def _set_url_ssl_options(self, value):
self.ssl_options = ast.literal_eval(value)
'Connection initialization expects an object that has implemented the Parameters class and a callback function to notify when we have successfully connected to the AMQP Broker. Available Parameters classes are the ConnectionParameters class and URLParameters class. :param pika.connection.Parameters parameters: Connecti...
def __init__(self, parameters=None, on_open_callback=None, on_open_error_callback=None, on_close_callback=None):
self.connection_state = self.CONNECTION_CLOSED self._connection_attempt_timer = None self._blocked_conn_timer = None self.heartbeat = None self.params = (copy.deepcopy(parameters) if (parameters is not None) else ConnectionParameters()) self.callbacks = callback.CallbackManager() self.server...
'Call method "callback" when pika believes backpressure is being applied. :param method callback_method: The method to call'
def add_backpressure_callback(self, callback_method):
self.callbacks.add(0, self.ON_CONNECTION_BACKPRESSURE, callback_method, False)
'Add a callback notification when the connection has closed. The callback will be passed the connection, the reply_code (int) and the reply_text (str), if sent by the remote server. :param method callback_method: Callback to call on close'
def add_on_close_callback(self, callback_method):
self.callbacks.add(0, self.ON_CONNECTION_CLOSED, callback_method, False)
'Add a callback to be notified when RabbitMQ has sent a ``Connection.Blocked`` frame indicating that RabbitMQ is low on resources. Publishers can use this to voluntarily suspend publishing, instead of relying on back pressure throttling. The callback will be passed the ``Connection.Blocked`` method frame. See also `Con...
def add_on_connection_blocked_callback(self, callback_method):
self.callbacks.add(0, spec.Connection.Blocked, callback_method, False)
'Add a callback to be notified when RabbitMQ has sent a ``Connection.Unblocked`` frame letting publishers know it\'s ok to start publishing again. The callback will be passed the ``Connection.Unblocked`` method frame. :param method callback_method: Callback to call on `Connection.Unblocked`, having the signature `callb...
def add_on_connection_unblocked_callback(self, callback_method):
self.callbacks.add(0, spec.Connection.Unblocked, callback_method, False)
'Add a callback notification when the connection has opened. :param method callback_method: Callback to call when open'
def add_on_open_callback(self, callback_method):
self.callbacks.add(0, self.ON_CONNECTION_OPEN, callback_method, False)
'Add a callback notification when the connection can not be opened. The callback method should accept the connection object that could not connect, and an optional error message. :param method callback_method: Callback to call when can\'t connect :param bool remove_default: Remove default exception raising callback'
def add_on_open_error_callback(self, callback_method, remove_default=True):
if remove_default: self.callbacks.remove(0, self.ON_CONNECTION_ERROR, self._on_connection_error) self.callbacks.add(0, self.ON_CONNECTION_ERROR, callback_method, False)
'Adapters should override to call the callback after the specified number of seconds have elapsed, using a timer, or a thread, or similar. :param int deadline: The number of seconds to wait to call callback :param method callback_method: The callback method'
def add_timeout(self, deadline, callback_method):
raise NotImplementedError
'Create a new channel with the next available channel number or pass in a channel number to use. Must be non-zero if you would like to specify but it is recommended that you let Pika manage the channel numbers. :param method on_open_callback: The callback when the channel is opened :param int channel_number: The channe...
def channel(self, on_open_callback, channel_number=None):
if (not self.is_open): raise exceptions.ConnectionClosed(('Channel allocation requires an open connection: %s' % self)) if (not channel_number): channel_number = self._next_channel_number() self._channels[channel_number] = self._create_channel(channel_number, on_open_callba...
'Disconnect from RabbitMQ. If there are any open channels, it will attempt to close them prior to fully disconnecting. Channels which have active consumers will attempt to send a Basic.Cancel to RabbitMQ to cleanly stop the delivery of messages prior to closing the channel. :param int reply_code: The code number for th...
def close(self, reply_code=200, reply_text='Normal shutdown'):
if (self.is_closing or self.is_closed): LOGGER.warning('Suppressing close request on %s', self) return self._close_channels(reply_code, reply_text) self._set_connection_state(self.CONNECTION_CLOSING) LOGGER.info('Closing connection (%s): %s', reply_code, reply_text) ...
'Invoke if trying to reconnect to a RabbitMQ server. Constructing the Connection object should connect on its own.'
def connect(self):
assert (self._connection_attempt_timer is None), 'connect timer was already scheduled' assert self.is_closed, 'connect expected CLOSED state, but got: {}'.format(self._STATE_NAMES[self.connection_state]) self._set_connection_state(self.CONNECTION_INIT) self._connection_atte...
'Adapters should override: Remove a timeout :param str timeout_id: The timeout id to remove'
def remove_timeout(self, timeout_id):
raise NotImplementedError
'Alter the backpressure multiplier value. We set this to 10 by default. This value is used to raise warnings and trigger the backpressure callback. :param int value: The multiplier value to set'
def set_backpressure_multiplier(self, value=10):
self._backpressure_multiplier = value
'Returns a boolean reporting the current connection state.'
@property def is_closed(self):
return (self.connection_state == self.CONNECTION_CLOSED)
'Returns True if connection is in the process of closing due to client-initiated `close` request, but closing is not yet complete.'
@property def is_closing(self):
return (self.connection_state == self.CONNECTION_CLOSING)
'Returns a boolean reporting the current connection state.'
@property def is_open(self):
return (self.connection_state == self.CONNECTION_OPEN)
'Specifies if the server supports basic.nack on the active connection. :rtype: bool'
@property def basic_nack(self):
return self.server_capabilities.get('basic.nack', False)
'Specifies if the server supports consumer cancel notification on the active connection. :rtype: bool'
@property def consumer_cancel_notify(self):
return self.server_capabilities.get('consumer_cancel_notify', False)
'Specifies if the active connection supports exchange to exchange bindings. :rtype: bool'
@property def exchange_exchange_bindings(self):
return self.server_capabilities.get('exchange_exchange_bindings', False)
'Specifies if the active connection can use publisher confirmations. :rtype: bool'
@property def publisher_confirms(self):
return self.server_capabilities.get('publisher_confirms', False)
'Subclasses should override to set up the outbound socket connection. :raises: NotImplementedError'
def _adapter_connect(self):
raise NotImplementedError
'Subclasses should override this to cause the underlying transport (socket) to close. :raises: NotImplementedError'
def _adapter_disconnect(self):
raise NotImplementedError
'Add the appropriate callbacks for the specified channel number. :param int channel_number: The channel number for the callbacks'
def _add_channel_callbacks(self, channel_number):
self._channels[channel_number]._add_on_cleanup_callback(self._on_channel_cleanup)
'Add a callback for when a Connection.Start frame is received from the broker.'
def _add_connection_start_callback(self):
self.callbacks.add(0, spec.Connection.Start, self._on_connection_start)
'Add a callback for when a Connection.Tune frame is received.'
def _add_connection_tune_callback(self):
self.callbacks.add(0, spec.Connection.Tune, self._on_connection_tune)
'Append the bytes to the frame buffer. :param str value: The bytes to append to the frame buffer'
def _append_frame_buffer(self, value):
self._frame_buffer += value
'Return the suggested buffer size from the connection state/tune or the default if that is None. :rtype: int'
@property def _buffer_size(self):
return (self.params.frame_max or spec.FRAME_MAX_SIZE)
'Invoked when starting a connection to make sure it\'s a supported protocol. :param pika.frame.Method value: The frame to check :raises: ProtocolVersionMismatch'
def _check_for_protocol_mismatch(self, value):
if ((value.method.version_major, value.method.version_minor) != spec.PROTOCOL_VERSION[0:2]): raise exceptions.ProtocolVersionMismatch(frame.ProtocolHeader(), value)
'Return the client properties dictionary. :rtype: dict'
@property def _client_properties(self):
properties = {'product': PRODUCT, 'platform': ('Python %s' % platform.python_version()), 'capabilities': {'authentication_failure_close': True, 'basic.nack': True, 'connection.blocked': True, 'consumer_cancel_notify': True, 'publisher_confirms': True}, 'information': 'See http://pika.rtfd.org', 'version': __v...
'Initiate graceful closing of channels that are in OPEN or OPENING states, passing reply_code and reply_text. :param int reply_code: The code for why the channels are being closed :param str reply_text: The text reason for why the channels are closing'
def _close_channels(self, reply_code, reply_text):
assert self.is_open, str(self) for channel_number in dictkeys(self._channels): chan = self._channels[channel_number] if (not (chan.is_closing or chan.is_closed)): chan.close(reply_code, reply_text)
'Pass in two values, if a is 0, return b otherwise if b is 0, return a. If neither case matches return the smallest value. :param int val1: The first value :param int val2: The second value :rtype: int'
def _combine(self, val1, val2):
return (min(val1, val2) or (val1 or val2))
'Attempt to connect to RabbitMQ :rtype: bool'
def _connect(self):
warnings.warn('This method is deprecated, use Connection.connect', DeprecationWarning)
'Create a new channel using the specified channel number and calling back the method specified by on_open_callback :param int channel_number: The channel number to use :param method on_open_callback: The callback when the channel is opened'
def _create_channel(self, channel_number, on_open_callback):
LOGGER.debug('Creating channel %s', channel_number) return pika.channel.Channel(self, channel_number, on_open_callback)
'Create a heartbeat checker instance if there is a heartbeat interval set. :rtype: pika.heartbeat.Heartbeat'
def _create_heartbeat_checker(self):
if ((self.params.heartbeat is not None) and (self.params.heartbeat > 0)): LOGGER.debug('Creating a HeartbeatChecker: %r', self.params.heartbeat) return heartbeat.HeartbeatChecker(self, self.params.heartbeat)
'Stop the heartbeat checker if it exists'
def _remove_heartbeat(self):
if self.heartbeat: self.heartbeat.stop() self.heartbeat = None
'Deliver the frame to the channel specified in the frame. :param pika.frame.Method value: The frame to deliver'
def _deliver_frame_to_channel(self, value):
if (not (value.channel_number in self._channels)): LOGGER.critical('Received %s frame for unregistered channel %i on %s', value.NAME, value.channel_number, self) return self._channels[value.channel_number]._handle_content_frame(value)
'Attempt to calculate if TCP backpressure is being applied due to our outbound buffer being larger than the average frame size over a window of frames.'
def _detect_backpressure(self):
avg_frame_size = (self.bytes_sent / self.frames_sent) buffer_size = sum([len(f) for f in self.outbound_buffer]) if (buffer_size > (avg_frame_size * self._backpressure_multiplier)): LOGGER.warning(BACKPRESSURE_WARNING, buffer_size, int((buffer_size / avg_frame_size))) self.callbacks.process(0...
'If the connection is not closed, close it.'
def _ensure_closed(self):
if self.is_open: self.close()
'Adapters should override to flush the contents of outbound_buffer out along the socket. :raises: NotImplementedError'
def _flush_outbound(self):
raise NotImplementedError
'Calculate the maximum amount of bytes that can be in a body frame. :rtype: int'
def _get_body_frame_max_length(self):
return ((self.params.frame_max - spec.FRAME_HEADER_SIZE) - spec.FRAME_END_SIZE)
'Get credentials for authentication. :param pika.frame.MethodFrame method_frame: The Connection.Start frame :rtype: tuple(str, str)'
def _get_credentials(self, method_frame):
(auth_type, response) = self.params.credentials.response_for(method_frame.method) if (not auth_type): raise exceptions.AuthenticationError(self.params.credentials.TYPE) self.params.credentials.erase_credentials() return (auth_type, response)
'Return true if there are any callbacks pending for the specified frame. :param pika.frame.Method value: The frame to check :rtype: bool'
def _has_pending_callbacks(self, value):
return self.callbacks.pending(value.channel_number, value.method)
'Initialize or reset all of the internal state variables for a given connection. On disconnect or reconnect all of the state needs to be wiped.'
def _init_connection_state(self):
self._set_connection_state(self.CONNECTION_CLOSED) self.server_properties = None self.outbound_buffer = collections.deque([]) self._frame_buffer = bytes() self._channels = dict() self.remaining_connection_attempts = self.params.connection_attempts self.bytes_sent = 0 self.bytes_received ...
'Returns true if the frame is a method frame. :param pika.frame.Frame value: The frame to evaluate :rtype: bool'
def _is_method_frame(self, value):
return isinstance(value, frame.Method)
'Returns True if it\'s a protocol header frame. :rtype: bool'
def _is_protocol_header_frame(self, value):
return isinstance(value, frame.ProtocolHeader)
'Return the next available channel number or raise an exception. :rtype: int'
def _next_channel_number(self):
limit = (self.params.channel_max or pika.channel.MAX_CHANNELS) if (len(self._channels) >= limit): raise exceptions.NoFreeChannels() for num in xrange(1, (len(self._channels) + 1)): if (num not in self._channels): return num return (len(self._channels) + 1)
'Remove the channel from the dict of channels when Channel.CloseOk is sent. If connection is closing and no more channels remain, proceed to `_on_close_ready`. :param pika.channel.Channel channel: channel instance'
def _on_channel_cleanup(self, channel):
try: del self._channels[channel.channel_number] LOGGER.debug('Removed channel %s', channel.channel_number) except KeyError: LOGGER.error('Channel %r not in channels', channel.channel_number) if self.is_closing: if (not self._channels): self._on_c...
'Called when the Connection is in a state that it can close after a close has been requested. This happens, for example, when all of the channels are closed that were open when the close request was made.'
def _on_close_ready(self):
if self.is_closed: LOGGER.warning('_on_close_ready invoked when already closed') return self._send_connection_close(self.closing[0], self.closing[1])
'Invoked when the socket is connected and it\'s time to start speaking AMQP with the broker.'
def _on_connected(self):
self._set_connection_state(self.CONNECTION_PROTOCOL) self._send_frame(frame.ProtocolHeader())
'Called when the "connection blocked timeout" expires. When this happens, we tear down the connection'
def _on_blocked_connection_timeout(self):
self._blocked_conn_timer = None self._on_terminate(InternalCloseReasons.BLOCKED_CONNECTION_TIMEOUT, 'Blocked connection timeout expired')
'Handle Connection.Blocked notification from RabbitMQ broker :param pika.frame.Method method_frame: method frame having `method` member of type `pika.spec.Connection.Blocked`'
def _on_connection_blocked(self, method_frame):
LOGGER.warning('Received %s from broker', method_frame) if (self._blocked_conn_timer is not None): LOGGER.warning('_blocked_conn_timer %s already set when _on_connection_blocked is called', self._blocked_conn_timer) else: self._blocked_conn_timer = self.add_time...
'Handle Connection.Unblocked notification from RabbitMQ broker :param pika.frame.Method method_frame: method frame having `method` member of type `pika.spec.Connection.Blocked`'
def _on_connection_unblocked(self, method_frame):
LOGGER.info('Received %s from broker', method_frame) if (self._blocked_conn_timer is None): LOGGER.warning('_blocked_conn_timer was not active when _on_connection_unblocked called') else: self.remove_timeout(self._blocked_conn_timer) self._blocked_conn_time...
'Called when the connection is closed remotely via Connection.Close frame from broker. :param pika.frame.Method method_frame: The Connection.Close frame'
def _on_connection_close(self, method_frame):
LOGGER.debug('_on_connection_close: frame=%s', method_frame) self.closing = (method_frame.method.reply_code, method_frame.method.reply_text) self._on_terminate(self.closing[0], self.closing[1])
'Called when Connection.CloseOk is received from remote. :param pika.frame.Method method_frame: The Connection.CloseOk frame'
def _on_connection_close_ok(self, method_frame):
LOGGER.debug('_on_connection_close_ok: frame=%s', method_frame) self._on_terminate(self.closing[0], self.closing[1])
'Default behavior when the connecting connection can not connect. :raises: exceptions.AMQPConnectionError'
def _on_connection_error(self, _connection_unused, error_message=None):
raise exceptions.AMQPConnectionError((error_message or self.params.connection_attempts))
'This is called once we have tuned the connection with the server and called the Connection.Open on the server and it has replied with Connection.Ok.'
def _on_connection_open(self, method_frame):
self.known_hosts = method_frame.method.known_hosts self._set_connection_state(self.CONNECTION_OPEN) self.callbacks.process(0, self.ON_CONNECTION_OPEN, self, self)
'This is called as a callback once we have received a Connection.Start from the server. :param pika.frame.Method method_frame: The frame received :raises: UnexpectedFrameError'
def _on_connection_start(self, method_frame):
self._set_connection_state(self.CONNECTION_START) if self._is_protocol_header_frame(method_frame): raise exceptions.UnexpectedFrameError self._check_for_protocol_mismatch(method_frame) self._set_server_information(method_frame) self._add_connection_tune_callback() self._send_connection_s...
'Callback for self._connection_attempt_timer: initiate connection attempt in the context of the event loop'
def _on_connect_timer(self):
self._connection_attempt_timer = None error = self._adapter_connect() if (not error): return self._on_connected() self.remaining_connection_attempts -= 1 LOGGER.warning('Could not connect, %i attempts left', self.remaining_connection_attempts) if (self.remaining_connection...
'Determine heartbeat timeout per AMQP 0-9-1 rules Per https://www.rabbitmq.com/resources/specs/amqp0-9-1.pdf, > Both peers negotiate the limits to the lowest agreed value as follows: > - The server MUST tell the client what limits it proposes. > - The client responds and **MAY reduce those limits** for its connection W...
@staticmethod def _tune_heartbeat_timeout(client_value, server_value):
if (client_value is None): timeout = server_value elif ((client_value == 0) or (server_value == 0)): timeout = 0 else: timeout = max(client_value, server_value) return timeout
'Once the Broker sends back a Connection.Tune, we will set our tuning variables that have been returned to us and kick off the Heartbeat monitor if required, send our TuneOk and then the Connection. Open rpc call on channel 0. :param pika.frame.Method method_frame: The frame received'
def _on_connection_tune(self, method_frame):
self._set_connection_state(self.CONNECTION_TUNE) self.params.channel_max = self._combine(self.params.channel_max, method_frame.method.channel_max) self.params.frame_max = self._combine(self.params.frame_max, method_frame.method.frame_max) self.params.heartbeat = self._tune_heartbeat_timeout(client_value...
'This is called by our Adapter, passing in the data from the socket. As long as we have buffer try and map out frame data. :param str data_in: The data that is available to read'
def _on_data_available(self, data_in):
self._append_frame_buffer(data_in) while self._frame_buffer: (consumed_count, frame_value) = self._read_frame() if (not frame_value): return self._trim_frame_buffer(consumed_count) self._process_frame(frame_value)
'Terminate the connection and notify registered ON_CONNECTION_ERROR and/or ON_CONNECTION_CLOSED callbacks :param integer reason_code: either IETF RFC 821 reply code for AMQP-level closures or a value from `InternalCloseReasons` for internal causes, such as socket errors :param str reason_text: human-readable text messa...
def _on_terminate(self, reason_code, reason_text):
LOGGER.info('Disconnected from RabbitMQ at %s:%i (%s): %s', self.params.host, self.params.port, reason_code, reason_text) if (not isinstance(reason_code, numbers.Integral)): raise TypeError(('reason_code must be an integer, but got %r' % (reason_code,))) self._...
'Process the callbacks for the frame if the frame is a method frame and if it has any callbacks pending. :param pika.frame.Method frame_value: The frame to process :rtype: bool'
def _process_callbacks(self, frame_value):
if (self._is_method_frame(frame_value) and self._has_pending_callbacks(frame_value)): self.callbacks.process(frame_value.channel_number, frame_value.method, self, frame_value) return True return False
'Process an inbound frame from the socket. :param frame_value: The frame to process :type frame_value: pika.frame.Frame | pika.frame.Method'
def _process_frame(self, frame_value):
if (frame_value.frame_type < 0): return self.frames_received += 1 if self._process_callbacks(frame_value): return if isinstance(frame_value, frame.Heartbeat): if self.heartbeat: self.heartbeat.received() else: LOGGER.warning('Received heartbeat ...
'Try and read from the frame buffer and decode a frame. :rtype tuple: (int, pika.frame.Frame)'
def _read_frame(self):
return frame.decode_frame(self._frame_buffer)
'Remove the specified method_frame callback if it is set for the specified channel number. :param int channel_number: The channel number to remove the callback on :param pika.amqp_object.Method method_class: The method class for the callback'
def _remove_callback(self, channel_number, method_class):
self.callbacks.remove(str(channel_number), method_class)
'Remove the callbacks for the specified channel number and list of method frames. :param int channel_number: The channel number to remove the callback on :param sequence method_classes: The method classes (derived from `pika.amqp_object.Method`) for the callbacks'
def _remove_callbacks(self, channel_number, method_classes):
for method_frame in method_classes: self._remove_callback(channel_number, method_frame)
'Make an RPC call for the given callback, channel number and method. acceptable_replies lists out what responses we\'ll process from the server with the specified callback. :param int channel_number: The channel number for the RPC call :param pika.amqp_object.Method method: The method frame to call :param method callba...
def _rpc(self, channel_number, method, callback_method=None, acceptable_replies=None):
if (acceptable_replies and (not isinstance(acceptable_replies, list))): raise TypeError('acceptable_replies should be list or None') if callback_method: if (not utils.is_callable(callback_method)): raise TypeError('callback should be None, function or ...
'Send a Connection.Close method frame. :param int reply_code: The reason for the close :param str reply_text: The text reason for the close'
def _send_connection_close(self, reply_code, reply_text):
self._rpc(0, spec.Connection.Close(reply_code, reply_text, 0, 0), self._on_connection_close_ok, [spec.Connection.CloseOk])
'Send a Connection.Open frame'
def _send_connection_open(self):
self._rpc(0, spec.Connection.Open(self.params.virtual_host, insist=True), self._on_connection_open, [spec.Connection.OpenOk])
'Send a Connection.StartOk frame :param str authentication_type: The auth type value :param str response: The encoded value to send'
def _send_connection_start_ok(self, authentication_type, response):
self._send_method(0, spec.Connection.StartOk(self._client_properties, authentication_type, response, self.params.locale))
'Send a Connection.TuneOk frame'
def _send_connection_tune_ok(self):
self._send_method(0, spec.Connection.TuneOk(self.params.channel_max, self.params.frame_max, self.params.heartbeat))
'This appends the fully generated frame to send to the broker to the output buffer which will be then sent via the connection adapter. :param frame_value: The frame to write :type frame_value: pika.frame.Frame|pika.frame.ProtocolHeader :raises: exceptions.ConnectionClosed'
def _send_frame(self, frame_value):
if self.is_closed: LOGGER.error('Attempted to send frame when closed') raise exceptions.ConnectionClosed marshaled_frame = frame_value.marshal() self.bytes_sent += len(marshaled_frame) self.frames_sent += 1 self.outbound_buffer.append(marshaled_frame) self._flush_o...
'Constructs a RPC method frame and then sends it to the broker. :param int channel_number: The channel number for the frame :param pika.amqp_object.Method method: The method to send :param tuple content: If set, is a content frame, is tuple of properties and body.'
def _send_method(self, channel_number, method, content=None):
if content: self._send_message(channel_number, method, content) else: self._send_frame(frame.Method(channel_number, method))
'Send the message directly, bypassing the single _send_frame invocation by directly appending to the output buffer and flushing within a lock. :param int channel_number: The channel number for the frame :param pika.amqp_object.Method method: The method frame to send :param tuple content: If set, is a content frame, is ...
def _send_message(self, channel_number, method, content=None):
length = len(content[1]) write_buffer = [frame.Method(channel_number, method).marshal(), frame.Header(channel_number, length, content[0]).marshal()] if content[1]: chunks = int(math.ceil((float(length) / self._body_max_length))) for chunk in xrange(0, chunks): start = (chunk * se...
'Set the connection state. :param int connection_state: The connection state to set'
def _set_connection_state(self, connection_state):
self.connection_state = connection_state
'Set the server properties and capabilities :param spec.connection.Start method_frame: The Connection.Start frame'
def _set_server_information(self, method_frame):
self.server_properties = method_frame.method.server_properties self.server_capabilities = self.server_properties.get('capabilities', dict()) if hasattr(self.server_properties, 'capabilities'): del self.server_properties['capabilities']
'Trim the leading N bytes off the frame buffer and increment the counter that keeps track of how many bytes have been read/used from the socket. :param int byte_count: The number of bytes consumed'
def _trim_frame_buffer(self, byte_count):
self._frame_buffer = self._frame_buffer[byte_count:] self.bytes_received += byte_count
'Create a new instance of PlainCredentials :param str username: The username to authenticate with :param str password: The password to authenticate with :param bool erase_on_connect: erase credentials on connect.'
def __init__(self, username, password, erase_on_connect=False):
self.username = username self.password = password self.erase_on_connect = erase_on_connect
'Validate that this type of authentication is supported :param spec.Connection.Start start: Connection.Start method :rtype: tuple(str|None, str|None)'
def response_for(self, start):
if (as_bytes(PlainCredentials.TYPE) not in as_bytes(start.mechanisms).split()): return (None, None) return (PlainCredentials.TYPE, ((('\x00' + as_bytes(self.username)) + '\x00') + as_bytes(self.password)))
'Called by Connection when it no longer needs the credentials'
def erase_credentials(self):
if self.erase_on_connect: LOGGER.info('Erasing stored credential values') self.username = None self.password = None
'Create a new instance of ExternalCredentials'
def __init__(self):
self.erase_on_connect = False
'Validate that this type of authentication is supported :param spec.Connection.Start start: Connection.Start method :rtype: tuple(str or None, str or None)'
def response_for(self, start):
if (as_bytes(ExternalCredentials.TYPE) not in as_bytes(start.mechanisms).split()): return (None, None) return (ExternalCredentials.TYPE, '')
'Called by Connection when it no longer needs the credentials'
def erase_credentials(self):
LOGGER.debug('Not supported by this Credentials type')
'Create a new instance of the TornadoConnection class, connecting to RabbitMQ automatically :param pika.connection.Parameters parameters: Connection parameters :param on_open_callback: The method to call when the connection is open :type on_open_callback: method :param method on_open_error_callback: Called if the conne...
def __init__(self, parameters=None, on_open_callback=None, on_open_error_callback=None, on_close_callback=None, stop_ioloop_on_close=False, custom_ioloop=None):
self.sleep_counter = 0 self.ioloop = (custom_ioloop or ioloop.IOLoop.instance()) super(TornadoConnection, self).__init__(parameters, on_open_callback, on_open_error_callback, on_close_callback, self.ioloop, stop_ioloop_on_close)
'Connect to the remote socket, adding the socket to the IOLoop if connected. :rtype: bool'
def _adapter_connect(self):
error = super(TornadoConnection, self)._adapter_connect() if (not error): self.ioloop.add_handler(self.socket.fileno(), self._handle_events, self.event_state) return error
'Disconnect from the RabbitMQ broker'
def _adapter_disconnect(self):
if self.socket: self.ioloop.remove_handler(self.socket.fileno()) super(TornadoConnection, self)._adapter_disconnect()
'Add the callback_method to the IOLoop timer to fire after deadline seconds. Returns a handle to the timeout. Do not confuse with Tornado\'s timeout where you pass in the time you want to have your callback called. Only pass in the seconds until it\'s to be called. :param int deadline: The number of seconds to wait to ...
def add_timeout(self, deadline, callback_method):
return self.ioloop.add_timeout((time.time() + deadline), callback_method)
'Remove the timeout from the IOLoop by the ID returned from add_timeout. :rtype: str'
def remove_timeout(self, timeout_id):
return self.ioloop.remove_timeout(timeout_id)
'Create a new instance of the Connection object. :param pika.connection.Parameters parameters: Connection parameters :param method on_open_callback: Method to call on connection open :param method on_open_error_callback: Called if the connection can\'t be established: on_open_error_callback(connection, str|exception) :...
def __init__(self, parameters=None, on_open_callback=None, on_open_error_callback=None, on_close_callback=None, ioloop=None, stop_ioloop_on_close=True):
if (parameters and (not isinstance(parameters, connection.Parameters))): raise ValueError(('Expected instance of Parameters, not %r' % parameters)) if (parameters and parameters.ssl and (not ssl)): raise RuntimeError('SSL specified but it is not available') s...
'Add the callback_method to the IOLoop timer to fire after deadline seconds. Returns a handle to the timeout :param int deadline: The number of seconds to wait to call callback :param method callback_method: The callback method :rtype: str'
def add_timeout(self, deadline, callback_method):
return self.ioloop.add_timeout(deadline, callback_method)
'Disconnect from RabbitMQ. If there are any open channels, it will attempt to close them prior to fully disconnecting. Channels which have active consumers will attempt to send a Basic.Cancel to RabbitMQ to cleanly stop the delivery of messages prior to closing the channel. :param int reply_code: The code number for th...
def close(self, reply_code=200, reply_text='Normal shutdown'):
try: super(BaseConnection, self).close(reply_code, reply_text) finally: if self.is_closed: self._handle_ioloop_stop()
'Remove the timeout from the IOLoop by the ID returned from add_timeout. :rtype: str'
def remove_timeout(self, timeout_id):
self.ioloop.remove_timeout(timeout_id)
'Connect to the RabbitMQ broker, returning True if connected. :returns: error string or exception instance on error; None on success'
def _adapter_connect(self):
while True: try: addresses = self._getaddrinfo(self.params.host, self.params.port, 0, socket.SOCK_STREAM, socket.IPPROTO_TCP) break except _SOCKET_ERROR as error: if (error.errno == errno.EINTR): continue LOGGER.critical('Could not ...
'Invoked if the connection is being told to disconnect'
def _adapter_disconnect(self):
try: self._cleanup_socket() finally: self._handle_ioloop_stop()
'Close the socket cleanly'
def _cleanup_socket(self):
if self.socket: try: self.socket.shutdown(socket.SHUT_RDWR) except _SOCKET_ERROR: pass self.socket.close() self.socket = None