code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
for index in compatibility.RANGE(self._last_channel_id or 1,
self.max_allowed_channels + 1):
if index in self._channels:
continue
self._last_channel_id = index
return index
if self._last_channel_id:
self._last_channel_id = None
return self._get_next_available_channel_id()
raise AMQPConnectionError(
'reached the maximum number of channels %d' %
self.max_allowed_channels) | def _get_next_available_channel_id(self) | Returns the next available available channel id.
:raises AMQPConnectionError: Raises if there is no available channel.
:rtype: int | 3.340582 | 3.168995 | 1.054146 |
if not data_in:
return data_in, None, None
try:
byte_count, channel_id, frame_in = pamqp_frame.unmarshal(data_in)
return data_in[byte_count:], channel_id, frame_in
except pamqp_exception.UnmarshalingException:
pass
except specification.AMQPFrameError as why:
LOGGER.error('AMQPFrameError: %r', why, exc_info=True)
except ValueError as why:
LOGGER.error(why, exc_info=True)
self.exceptions.append(AMQPConnectionError(why))
return data_in, None, None | def _handle_amqp_frame(self, data_in) | Unmarshal a single AMQP frame and return the result.
:param data_in: socket data
:return: data_in, channel_id, frame | 3.476351 | 3.300422 | 1.053305 |
while data_in:
data_in, channel_id, frame_in = self._handle_amqp_frame(data_in)
if frame_in is None:
break
self.heartbeat.register_read()
if channel_id == 0:
self._channel0.on_frame(frame_in)
elif channel_id in self._channels:
self._channels[channel_id].on_frame(frame_in)
return data_in | def _read_buffer(self, data_in) | Process the socket buffer, and direct the data to the appropriate
channel.
:rtype: bytes | 3.519266 | 3.62519 | 0.970781 |
with self.lock:
if channel_id not in self._channels:
return
del self._channels[channel_id] | def _cleanup_channel(self, channel_id) | Remove the the channel from the list of available channels.
:param int channel_id: Channel id
:return: | 3.037339 | 3.74613 | 0.810794 |
if not compatibility.is_string(self.parameters['hostname']):
raise AMQPInvalidArgument('hostname should be a string')
elif not compatibility.is_integer(self.parameters['port']):
raise AMQPInvalidArgument('port should be an integer')
elif not compatibility.is_string(self.parameters['username']):
raise AMQPInvalidArgument('username should be a string')
elif not compatibility.is_string(self.parameters['password']):
raise AMQPInvalidArgument('password should be a string')
elif not compatibility.is_string(self.parameters['virtual_host']):
raise AMQPInvalidArgument('virtual_host should be a string')
elif not isinstance(self.parameters['timeout'], (int, float)):
raise AMQPInvalidArgument('timeout should be an integer or float')
elif not compatibility.is_integer(self.parameters['heartbeat']):
raise AMQPInvalidArgument('heartbeat should be an integer') | def _validate_parameters(self) | Validate Connection Parameters.
:return: | 1.771509 | 1.759279 | 1.006952 |
start_time = time.time()
while self.current_state != state:
self.check_for_errors()
if time.time() - start_time > rpc_timeout:
raise AMQPConnectionError('Connection timed out')
sleep(IDLE_WAIT) | def _wait_for_connection_state(self, state=Stateful.OPEN, rpc_timeout=30) | Wait for a Connection state.
:param int state: State that we expect
:raises AMQPConnectionError: Raises if we are unable to establish
a connection to RabbitMQ.
:return: | 3.68009 | 3.676563 | 1.000959 |
attempts = 0
while True:
attempts += 1
try:
self.connection = Connection('127.0.0.1', 'guest', 'guest')
break
except amqpstorm.AMQPError as why:
LOGGER.exception(why)
if self.max_retries and attempts > self.max_retries:
break
time.sleep(min(attempts * 2, 30))
except KeyboardInterrupt:
break | def create_connection(self) | Create a connection.
:return: | 3.562605 | 3.717555 | 0.958319 |
if not self.connection:
self.create_connection()
while True:
try:
channel = self.connection.channel()
channel.queue.declare('simple_queue')
channel.basic.consume(self, 'simple_queue', no_ack=False)
channel.start_consuming()
if not channel.consumer_tags:
channel.close()
except amqpstorm.AMQPError as why:
LOGGER.exception(why)
self.create_connection()
except KeyboardInterrupt:
self.connection.close()
break | def start(self) | Start the Consumers.
:return: | 3.027141 | 3.137826 | 0.964726 |
while self._consumers:
consumer = self._consumers.pop()
consumer.stop()
self._stopped.set()
self._connection.close() | def stop(self) | Stop all consumers.
:return: | 4.331292 | 4.471834 | 0.968572 |
attempts = 0
while True:
attempts += 1
if self._stopped.is_set():
break
try:
self._connection = Connection(self.hostname,
self.username,
self.password)
break
except amqpstorm.AMQPError as why:
LOGGER.warning(why)
if self.max_retries and attempts > self.max_retries:
raise Exception('max number of retries reached')
time.sleep(min(attempts * 2, 30))
except KeyboardInterrupt:
break | def _create_connection(self) | Create a connection.
:return: | 3.548774 | 3.714837 | 0.955297 |
while len(self._consumers) > number_of_consumers:
consumer = self._consumers.pop()
consumer.stop() | def _stop_consumers(self, number_of_consumers=0) | Stop a specific number of consumers.
:param number_of_consumers:
:return: | 2.482756 | 3.205493 | 0.774532 |
thread = threading.Thread(target=consumer.start,
args=(self._connection,))
thread.daemon = True
thread.start() | def _start_consumer(self, consumer) | Start a consumer as a new Thread.
:param Consumer consumer:
:return: | 3.857382 | 4.391092 | 0.878456 |
self._tx_active = True
return self._channel.rpc_request(specification.Tx.Select()) | def select(self) | Enable standard transaction mode.
This will enable transaction mode on the channel. Meaning that
messages will be kept in the remote server buffer until such a
time that either commit or rollback is called.
:return: | 36.064957 | 28.584526 | 1.261695 |
self._tx_active = False
return self._channel.rpc_request(specification.Tx.Commit()) | def commit(self) | Commit the current transaction.
Commit all messages published during the current transaction
session to the remote server.
A new transaction session starts as soon as the command has
been executed.
:return: | 34.621105 | 32.697113 | 1.058843 |
self._tx_active = False
return self._channel.rpc_request(specification.Tx.Rollback()) | def rollback(self) | Abandon the current transaction.
Rollback all messages published during the current transaction
session to the remote server.
Note that all messages published during this transaction session
will be lost, and will have to be published again.
A new transaction session starts as soon as the command has
been executed.
:return: | 28.860178 | 29.648901 | 0.973398 |
# Send the request and store the requests Unique ID.
corr_id = RPC_CLIENT.send_request(payload)
# Wait until we have received a response.
while RPC_CLIENT.queue[corr_id] is None:
sleep(0.1)
# Return the response to the user.
return RPC_CLIENT.queue[corr_id] | def rpc_call(payload) | Simple Flask implementation for making asynchronous Rpc calls. | 4.687339 | 4.479355 | 1.046432 |
thread = threading.Thread(target=self._process_data_events)
thread.setDaemon(True)
thread.start() | def _create_process_thread(self) | Create a thread responsible for consuming messages in response
to RPC requests. | 3.395124 | 3.37589 | 1.005697 |
properties = properties or {}
if 'correlation_id' not in properties:
properties['correlation_id'] = str(uuid.uuid4())
if 'message_id' not in properties:
properties['message_id'] = str(uuid.uuid4())
if 'timestamp' not in properties:
properties['timestamp'] = datetime.utcnow()
return Message(channel, auto_decode=False,
body=body, properties=properties) | def create(channel, body, properties=None) | Create a new Message.
:param Channel channel: AMQPStorm Channel
:param bytes|str|unicode body: Message payload
:param dict properties: Message properties
:rtype: Message | 2.197116 | 2.378237 | 0.923842 |
if not self._auto_decode:
return self._body
if 'body' in self._decode_cache:
return self._decode_cache['body']
body = try_utf8_decode(self._body)
self._decode_cache['body'] = body
return body | def body(self) | Return the Message Body.
If auto_decode is enabled, the body will automatically be
decoded using decode('utf-8') if possible.
:rtype: bytes|str|unicode | 3.709793 | 3.193077 | 1.161824 |
if not self._method:
raise AMQPMessageError(
'Message.ack only available on incoming messages'
)
self._channel.basic.ack(delivery_tag=self.delivery_tag) | def ack(self) | Acknowledge Message.
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return: | 6.520795 | 6.850601 | 0.951857 |
if not self._method:
raise AMQPMessageError(
'Message.nack only available on incoming messages'
)
self._channel.basic.nack(delivery_tag=self.delivery_tag,
requeue=requeue) | def nack(self, requeue=True) | Negative Acknowledgement.
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:param bool requeue: Re-queue the message | 4.709328 | 6.378246 | 0.738342 |
return self._channel.basic.publish(body=self._body,
routing_key=routing_key,
exchange=exchange,
properties=self._properties,
mandatory=mandatory,
immediate=immediate) | def publish(self, routing_key, exchange='', mandatory=False,
immediate=False) | Publish Message.
:param str routing_key: Message routing key
:param str exchange: The exchange to publish the message to
:param bool mandatory: Requires the message is published
:param bool immediate: Request immediate delivery
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: bool|None | 2.510313 | 2.850439 | 0.880676 |
if self._auto_decode and 'properties' in self._decode_cache:
self._decode_cache['properties'][name] = value
self._properties[name] = value | def _update_properties(self, name, value) | Update properties, and keep cache up-to-date if auto decode is
enabled.
:param str name: Key
:param obj value: Value
:return: | 5.029446 | 3.987871 | 1.261186 |
if not self._auto_decode or not content:
return content
if content_type in self._decode_cache:
return self._decode_cache[content_type]
if isinstance(content, dict):
content = self._try_decode_dict(content)
else:
content = try_utf8_decode(content)
self._decode_cache[content_type] = content
return content | def _try_decode_utf8_content(self, content, content_type) | Generic function to decode content.
:param object content:
:return: | 2.682353 | 2.777556 | 0.965724 |
result = dict()
for key, value in content.items():
key = try_utf8_decode(key)
if isinstance(value, dict):
result[key] = self._try_decode_dict(value)
elif isinstance(value, list):
result[key] = self._try_decode_list(value)
elif isinstance(value, tuple):
result[key] = self._try_decode_tuple(value)
else:
result[key] = try_utf8_decode(value)
return result | def _try_decode_dict(self, content) | Decode content of a dictionary.
:param dict content:
:return: | 1.65756 | 1.752719 | 0.945708 |
result = list()
for value in content:
result.append(try_utf8_decode(value))
return result | def _try_decode_list(content) | Decode content of a list.
:param list|tuple content:
:return: | 5.168183 | 6.071562 | 0.851211 |
exchange = quote(exchange, '')
properties = properties or {}
body = json.dumps(
{
'routing_key': routing_key,
'payload': body,
'payload_encoding': payload_encoding,
'properties': properties,
'vhost': virtual_host
}
)
virtual_host = quote(virtual_host, '')
return self.http_client.post(API_BASIC_PUBLISH %
(
virtual_host,
exchange),
payload=body) | def publish(self, body, routing_key, exchange='amq.default',
virtual_host='/', properties=None, payload_encoding='string') | Publish a Message.
:param bytes|str|unicode body: Message payload
:param str routing_key: Message routing key
:param str exchange: The exchange to publish the message to
:param str virtual_host: Virtual host name
:param dict properties: Message properties
:param str payload_encoding: Payload encoding.
:raises ApiError: Raises if the remote server encountered an error.
:raises ApiConnectionError: Raises if there was a connectivity issue.
:rtype: dict | 3.726178 | 3.972824 | 0.937917 |
ackmode = 'ack_requeue_false'
if requeue:
ackmode = 'ack_requeue_true'
get_messages = json.dumps(
{
'count': count,
'requeue': requeue,
'ackmode': ackmode,
'encoding': encoding,
'truncate': truncate,
'vhost': virtual_host
}
)
virtual_host = quote(virtual_host, '')
response = self.http_client.post(API_BASIC_GET_MESSAGE %
(
virtual_host,
queue
),
payload=get_messages)
if to_dict:
return response
messages = []
for message in response:
if 'payload' in message:
message['body'] = message.pop('payload')
messages.append(Message(channel=None, auto_decode=True, **message))
return messages | def get(self, queue, virtual_host='/', requeue=False, to_dict=False,
count=1, truncate=50000, encoding='auto') | Get Messages.
:param str queue: Queue name
:param str virtual_host: Virtual host name
:param bool requeue: Re-queue message
:param bool to_dict: Should incoming messages be converted to a
dictionary before delivery.
:param int count: How many messages should we try to fetch.
:param int truncate: The maximum length in bytes, beyond that the
server will truncate the message.
:param str encoding: Message encoding.
:raises ApiError: Raises if the remote server encountered an error.
:raises ApiConnectionError: Raises if there was a connectivity issue.
:rtype: list | 3.288614 | 3.666063 | 0.897042 |
virtual_host = quote(virtual_host, '')
return self.http_client.get(API_VIRTUAL_HOST % virtual_host) | def get(self, virtual_host) | Get Virtual Host details.
:param str virtual_host: Virtual host name
:raises ApiError: Raises if the remote server encountered an error.
:raises ApiConnectionError: Raises if there was a connectivity issue.
:rtype: dict | 5.144271 | 9.373917 | 0.548786 |
virtual_host = quote(virtual_host, '')
return self.http_client.put(API_VIRTUAL_HOST % virtual_host) | def create(self, virtual_host) | Create a Virtual Host.
:param str virtual_host: Virtual host name
:raises ApiError: Raises if the remote server encountered an error.
:raises ApiConnectionError: Raises if there was a connectivity issue.
:rtype: dict | 6.160017 | 9.432495 | 0.653063 |
virtual_host = quote(virtual_host, '')
return self.http_client.delete(API_VIRTUAL_HOST % virtual_host) | def delete(self, virtual_host) | Delete a Virtual Host.
:param str virtual_host: Virtual host name
:raises ApiError: Raises if the remote server encountered an error.
:raises ApiConnectionError: Raises if there was a connectivity issue.
:rtype: dict | 5.613844 | 9.848207 | 0.570037 |
virtual_host = quote(virtual_host, '')
return self.http_client.get(API_VIRTUAL_HOSTS_PERMISSION %
(
virtual_host
)) | def get_permissions(self, virtual_host) | Get all Virtual hosts permissions.
:raises ApiError: Raises if the remote server encountered an error.
:raises ApiConnectionError: Raises if there was a connectivity issue.
:rtype: dict | 7.794627 | 10.558445 | 0.738236 |
if not is_string(tag):
raise AMQPChannelError('consumer tag needs to be a string')
if tag not in self._consumer_tags:
self._consumer_tags.append(tag) | def add_consumer_tag(self, tag) | Add a Consumer tag.
:param str tag: Consumer tag.
:return: | 3.289261 | 4.269111 | 0.770479 |
if tag is not None:
if tag in self._consumer_tags:
self._consumer_tags.remove(tag)
else:
self._consumer_tags = [] | def remove_consumer_tag(self, tag=None) | Remove a Consumer tag.
If no tag is specified, all all tags will be removed.
:param str|None tag: Consumer tag.
:return: | 2.15399 | 2.933533 | 0.734265 |
return {
'body': self._body,
'method': self._method,
'properties': self._properties,
'channel': self._channel
} | def to_dict(self) | Message to Dictionary.
:rtype: dict | 4.743377 | 3.832613 | 1.237635 |
return self._body, self._channel, self._method, self._properties | def to_tuple(self) | Message to Tuple.
:rtype: tuple | 18.484598 | 13.082376 | 1.412939 |
close_payload = json.dumps({
'name': connection,
'reason': reason
})
connection = quote(connection, '')
return self.http_client.delete(API_CONNECTION % connection,
payload=close_payload,
headers={
'X-Reason': reason
}) | def close(self, connection, reason='Closed via management api') | Close Connection.
:param str connection: Connection name
:param str reason: Reason for closing connection.
:raises ApiError: Raises if the remote server encountered an error.
:raises ApiConnectionError: Raises if there was a connectivity issue.
:rtype: None | 5.501668 | 6.003273 | 0.916445 |
if frame_in.name not in self._request:
return False
uuid = self._request[frame_in.name]
if self._response[uuid]:
self._response[uuid].append(frame_in)
else:
self._response[uuid] = [frame_in]
return True | def on_frame(self, frame_in) | On RPC Frame.
:param specification.Frame frame_in: Amqp frame.
:return: | 3.116831 | 3.277611 | 0.950946 |
uuid = str(uuid4())
self._response[uuid] = []
for action in valid_responses:
self._request[action] = uuid
return uuid | def register_request(self, valid_responses) | Register a RPC request.
:param list valid_responses: List of possible Responses that
we should be waiting for.
:return: | 4.9451 | 5.975652 | 0.827542 |
for key in list(self._request):
if self._request[key] == uuid:
del self._request[key] | def remove_request(self, uuid) | Remove any RPC request(s) using this uuid.
:param str uuid: Rpc Identifier.
:return: | 3.456358 | 4.20416 | 0.822128 |
if uuid not in self._response:
return
self._wait_for_request(
uuid, connection_adapter or self._default_connection_adapter
)
frame = self._get_response_frame(uuid)
if not multiple:
self.remove(uuid)
result = None
if raw:
result = frame
elif frame is not None:
result = dict(frame)
return result | def get_request(self, uuid, raw=False, multiple=False,
connection_adapter=None) | Get a RPC request.
:param str uuid: Rpc Identifier
:param bool raw: If enabled return the frame as is, else return
result as a dictionary.
:param bool multiple: Are we expecting multiple frames.
:param obj connection_adapter: Provide custom connection adapter.
:return: | 3.958106 | 3.970683 | 0.996833 |
frame = None
frames = self._response.get(uuid, None)
if frames:
frame = frames.pop(0)
return frame | def _get_response_frame(self, uuid) | Get a response frame.
:param str uuid: Rpc Identifier
:return: | 3.90286 | 4.652677 | 0.838842 |
start_time = time.time()
while not self._response[uuid]:
connection_adapter.check_for_errors()
if time.time() - start_time > self._timeout:
self._raise_rpc_timeout_error(uuid)
time.sleep(IDLE_WAIT) | def _wait_for_request(self, uuid, connection_adapter=None) | Wait for RPC request to arrive.
:param str uuid: Rpc Identifier.
:param obj connection_adapter: Provide custom connection adapter.
:return: | 3.784701 | 3.882259 | 0.974871 |
requests = []
for key, value in self._request.items():
if value == uuid:
requests.append(key)
self.remove(uuid)
message = (
'rpc requests %s (%s) took too long' %
(
uuid,
', '.join(requests)
)
)
raise AMQPChannelError(message) | def _raise_rpc_timeout_error(self, uuid) | Gather information and raise an Rpc exception.
:param str uuid: Rpc Identifier.
:return: | 5.365731 | 6.286825 | 0.853488 |
if hasattr(ssl, 'PROTOCOL_TLSv1_2'):
return ssl.PROTOCOL_TLSv1_2
elif hasattr(ssl, 'PROTOCOL_TLSv1_1'):
return ssl.PROTOCOL_TLSv1_1
elif hasattr(ssl, 'PROTOCOL_TLSv1'):
return ssl.PROTOCOL_TLSv1
return None | def get_default_ssl_version() | Get the highest support TLS version, if none is available, return None.
:rtype: bool|None | 1.489171 | 1.64484 | 0.905359 |
if PYTHON3:
str_type = (bytes, str)
else:
str_type = (bytes, str, unicode)
return isinstance(obj, str_type) | def is_string(obj) | Is this a string.
:param object obj:
:rtype: bool | 3.460994 | 3.844372 | 0.900276 |
if PYTHON3:
return isinstance(obj, int)
return isinstance(obj, (int, long)) | def is_integer(obj) | Is this an integer.
:param object obj:
:return: | 3.346883 | 4.72387 | 0.708504 |
if not value or not is_string(value):
return value
elif PYTHON3 and not isinstance(value, bytes):
return value
elif not PYTHON3 and not isinstance(value, unicode):
return value
try:
return value.decode('utf-8')
except UnicodeDecodeError:
pass
return value | def try_utf8_decode(value) | Try to decode an object.
:param value:
:return: | 2.687526 | 2.838534 | 0.946801 |
index = uri.find(':')
if uri[:index] == 'amqps':
uri = uri.replace('amqps', 'https', 1)
elif uri[:index] == 'amqp':
uri = uri.replace('amqp', 'http', 1)
return uri | def patch_uri(uri) | If a custom uri schema is used with python 2.6 (e.g. amqps),
it will ignore some of the parsing logic.
As a work-around for this we change the amqp/amqps schema
internally to use http/https.
:param str uri: AMQP Connection string
:rtype: str | 2.470837 | 2.229817 | 1.108089 |
ssl_options = ssl_options or {}
kwargs = urlparse.parse_qs(parsed_uri.query)
vhost = urlparse.unquote(parsed_uri.path[1:]) or DEFAULT_VIRTUAL_HOST
options = {
'ssl': use_ssl,
'virtual_host': vhost,
'heartbeat': int(kwargs.pop('heartbeat',
[DEFAULT_HEARTBEAT_INTERVAL])[0]),
'timeout': int(kwargs.pop('timeout',
[DEFAULT_SOCKET_TIMEOUT])[0])
}
if use_ssl:
if not compatibility.SSL_SUPPORTED:
raise AMQPConnectionError(
'Python not compiled with support '
'for TLSv1 or higher'
)
ssl_options.update(self._parse_ssl_options(kwargs))
options['ssl_options'] = ssl_options
return options | def _parse_uri_options(self, parsed_uri, use_ssl=False, ssl_options=None) | Parse the uri options.
:param parsed_uri:
:param bool use_ssl:
:return: | 3.063626 | 3.273198 | 0.935973 |
ssl_options = {}
for key in ssl_kwargs:
if key not in compatibility.SSL_OPTIONS:
LOGGER.warning('invalid option: %s', key)
continue
if 'ssl_version' in key:
value = self._get_ssl_version(ssl_kwargs[key][0])
elif 'cert_reqs' in key:
value = self._get_ssl_validation(ssl_kwargs[key][0])
else:
value = ssl_kwargs[key][0]
ssl_options[key] = value
return ssl_options | def _parse_ssl_options(self, ssl_kwargs) | Parse TLS Options.
:param ssl_kwargs:
:rtype: dict | 2.463547 | 2.58745 | 0.952114 |
return self._get_ssl_attribute(value, compatibility.SSL_VERSIONS,
ssl.PROTOCOL_TLSv1,
'ssl_options: ssl_version \'%s\' not '
'found falling back to PROTOCOL_TLSv1.') | def _get_ssl_version(self, value) | Get the TLS Version.
:param str value:
:return: TLS Version | 10.711604 | 12.73958 | 0.840813 |
return self._get_ssl_attribute(value, compatibility.SSL_CERT_MAP,
ssl.CERT_NONE,
'ssl_options: cert_reqs \'%s\' not '
'found falling back to CERT_NONE.') | def _get_ssl_validation(self, value) | Get the TLS Validation option.
:param str value:
:return: TLS Certificate Options | 14.082837 | 17.143257 | 0.82148 |
for key in mapping:
if not key.endswith(value.lower()):
continue
return mapping[key]
LOGGER.warning(warning_message, value)
return default_value | def _get_ssl_attribute(value, mapping, default_value, warning_message) | Get the TLS attribute based on the compatibility mapping.
If no valid attribute can be found, fall-back on default and
display a warning.
:param str value:
:param dict mapping: Dictionary based mapping
:param default_value: Default fall-back value
:param str warning_message: Warning message
:return: | 4.01756 | 5.13138 | 0.782939 |
nodes = []
for node in self.nodes():
nodes.append(self.http_client.get(API_TOP % node['name']))
return nodes | def top(self) | Top Processes.
:raises ApiError: Raises if the remote server encountered an error.
:raises ApiConnectionError: Raises if there was a connectivity issue.
:rtype: list | 7.583011 | 7.234488 | 1.048175 |
if not compatibility.is_integer(prefetch_count):
raise AMQPInvalidArgument('prefetch_count should be an integer')
elif not compatibility.is_integer(prefetch_size):
raise AMQPInvalidArgument('prefetch_size should be an integer')
elif not isinstance(global_, bool):
raise AMQPInvalidArgument('global_ should be a boolean')
qos_frame = specification.Basic.Qos(prefetch_count=prefetch_count,
prefetch_size=prefetch_size,
global_=global_)
return self._channel.rpc_request(qos_frame) | def qos(self, prefetch_count=0, prefetch_size=0, global_=False) | Specify quality of service.
:param int prefetch_count: Prefetch window in messages
:param int/long prefetch_size: Prefetch window in octets
:param bool global_: Apply to entire connection
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: dict | 2.444467 | 2.381016 | 1.026648 |
if not compatibility.is_string(queue):
raise AMQPInvalidArgument('queue should be a string')
elif not isinstance(no_ack, bool):
raise AMQPInvalidArgument('no_ack should be a boolean')
elif self._channel.consumer_tags:
raise AMQPChannelError("Cannot call 'get' when channel is "
"set to consume")
get_frame = specification.Basic.Get(queue=queue,
no_ack=no_ack)
with self._channel.lock and self._channel.rpc.lock:
message = self._get_message(get_frame, auto_decode=auto_decode)
if message and to_dict:
return message.to_dict()
return message | def get(self, queue='', no_ack=False, to_dict=False, auto_decode=True) | Fetch a single message.
:param str queue: Queue name
:param bool no_ack: No acknowledgement needed
:param bool to_dict: Should incoming messages be converted to a
dictionary before delivery.
:param bool auto_decode: Auto-decode strings when possible.
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:returns: Returns a single message, as long as there is a message in
the queue. If no message is available, returns None.
:rtype: dict|Message|None | 3.543201 | 3.763862 | 0.941374 |
if not isinstance(requeue, bool):
raise AMQPInvalidArgument('requeue should be a boolean')
recover_frame = specification.Basic.Recover(requeue=requeue)
return self._channel.rpc_request(recover_frame) | def recover(self, requeue=False) | Redeliver unacknowledged messages.
:param bool requeue: Re-queue the messages
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: dict | 4.870334 | 4.813725 | 1.01176 |
if not compatibility.is_string(queue):
raise AMQPInvalidArgument('queue should be a string')
elif not compatibility.is_string(consumer_tag):
raise AMQPInvalidArgument('consumer_tag should be a string')
elif not isinstance(exclusive, bool):
raise AMQPInvalidArgument('exclusive should be a boolean')
elif not isinstance(no_ack, bool):
raise AMQPInvalidArgument('no_ack should be a boolean')
elif not isinstance(no_local, bool):
raise AMQPInvalidArgument('no_local should be a boolean')
elif arguments is not None and not isinstance(arguments, dict):
raise AMQPInvalidArgument('arguments should be a dict or None')
consume_rpc_result = self._consume_rpc_request(arguments, consumer_tag,
exclusive, no_ack,
no_local, queue)
tag = self._consume_add_and_get_tag(consume_rpc_result)
self._channel._consumer_callbacks[tag] = callback
return tag | def consume(self, callback=None, queue='', consumer_tag='',
exclusive=False, no_ack=False, no_local=False, arguments=None) | Start a queue consumer.
:param function callback: Message callback
:param str queue: Queue name
:param str consumer_tag: Consumer tag
:param bool no_local: Do not deliver own messages
:param bool no_ack: No acknowledgement needed
:param bool exclusive: Request exclusive access
:param dict arguments: Consume key/value arguments
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:returns: Consumer tag
:rtype: str | 2.067421 | 2.15416 | 0.959734 |
if not compatibility.is_string(consumer_tag):
raise AMQPInvalidArgument('consumer_tag should be a string')
cancel_frame = specification.Basic.Cancel(consumer_tag=consumer_tag)
result = self._channel.rpc_request(cancel_frame)
self._channel.remove_consumer_tag(consumer_tag)
return result | def cancel(self, consumer_tag='') | Cancel a queue consumer.
:param str consumer_tag: Consumer tag
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: dict | 3.833551 | 4.113206 | 0.932011 |
self._validate_publish_parameters(body, exchange, immediate, mandatory,
properties, routing_key)
properties = properties or {}
body = self._handle_utf8_payload(body, properties)
properties = specification.Basic.Properties(**properties)
method_frame = specification.Basic.Publish(exchange=exchange,
routing_key=routing_key,
mandatory=mandatory,
immediate=immediate)
header_frame = pamqp_header.ContentHeader(body_size=len(body),
properties=properties)
frames_out = [method_frame, header_frame]
for body_frame in self._create_content_body(body):
frames_out.append(body_frame)
if self._channel.confirming_deliveries:
with self._channel.rpc.lock:
return self._publish_confirm(frames_out)
self._channel.write_frames(frames_out) | def publish(self, body, routing_key, exchange='', properties=None,
mandatory=False, immediate=False) | Publish a Message.
:param bytes|str|unicode body: Message payload
:param str routing_key: Message routing key
:param str exchange: The exchange to publish the message to
:param dict properties: Message properties
:param bool mandatory: Requires the message is published
:param bool immediate: Request immediate delivery
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: bool|None | 3.354683 | 3.383135 | 0.99159 |
if not compatibility.is_integer(delivery_tag):
raise AMQPInvalidArgument('delivery_tag should be an integer')
elif not isinstance(multiple, bool):
raise AMQPInvalidArgument('multiple should be a boolean')
ack_frame = specification.Basic.Ack(delivery_tag=delivery_tag,
multiple=multiple)
self._channel.write_frame(ack_frame) | def ack(self, delivery_tag=0, multiple=False) | Acknowledge Message.
:param int/long delivery_tag: Server-assigned delivery tag
:param bool multiple: Acknowledge multiple messages
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return: | 3.094966 | 3.08755 | 1.002402 |
if not compatibility.is_integer(delivery_tag):
raise AMQPInvalidArgument('delivery_tag should be an integer')
elif not isinstance(multiple, bool):
raise AMQPInvalidArgument('multiple should be a boolean')
elif not isinstance(requeue, bool):
raise AMQPInvalidArgument('requeue should be a boolean')
nack_frame = specification.Basic.Nack(delivery_tag=delivery_tag,
multiple=multiple,
requeue=requeue)
self._channel.write_frame(nack_frame) | def nack(self, delivery_tag=0, multiple=False, requeue=True) | Negative Acknowledgement.
:param int/long delivery_tag: Server-assigned delivery tag
:param bool multiple: Negative acknowledge multiple messages
:param bool requeue: Re-queue the message
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return: | 2.223997 | 2.339772 | 0.950519 |
if not compatibility.is_integer(delivery_tag):
raise AMQPInvalidArgument('delivery_tag should be an integer')
elif not isinstance(requeue, bool):
raise AMQPInvalidArgument('requeue should be a boolean')
reject_frame = specification.Basic.Reject(delivery_tag=delivery_tag,
requeue=requeue)
self._channel.write_frame(reject_frame) | def reject(self, delivery_tag=0, requeue=True) | Reject Message.
:param int/long delivery_tag: Server-assigned delivery tag
:param bool requeue: Re-queue the message
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return: | 2.813304 | 2.946655 | 0.954745 |
consumer_tag = consume_rpc_result['consumer_tag']
self._channel.add_consumer_tag(consumer_tag)
return consumer_tag | def _consume_add_and_get_tag(self, consume_rpc_result) | Add the tag to the channel and return it.
:param dict consume_rpc_result:
:rtype: str | 3.152793 | 3.84532 | 0.819904 |
consume_frame = specification.Basic.Consume(queue=queue,
consumer_tag=consumer_tag,
exclusive=exclusive,
no_local=no_local,
no_ack=no_ack,
arguments=arguments)
return self._channel.rpc_request(consume_frame) | def _consume_rpc_request(self, arguments, consumer_tag, exclusive, no_ack,
no_local, queue) | Create a Consume Frame and execute a RPC request.
:param str queue: Queue name
:param str consumer_tag: Consumer tag
:param bool no_local: Do not deliver own messages
:param bool no_ack: No acknowledgement needed
:param bool exclusive: Request exclusive access
:param dict arguments: Consume key/value arguments
:rtype: dict | 2.771618 | 2.948072 | 0.940146 |
if not compatibility.is_string(body):
raise AMQPInvalidArgument('body should be a string')
elif not compatibility.is_string(routing_key):
raise AMQPInvalidArgument('routing_key should be a string')
elif not compatibility.is_string(exchange):
raise AMQPInvalidArgument('exchange should be a string')
elif properties is not None and not isinstance(properties, dict):
raise AMQPInvalidArgument('properties should be a dict or None')
elif not isinstance(mandatory, bool):
raise AMQPInvalidArgument('mandatory should be a boolean')
elif not isinstance(immediate, bool):
raise AMQPInvalidArgument('immediate should be a boolean') | def _validate_publish_parameters(body, exchange, immediate, mandatory,
properties, routing_key) | Validate Publish Parameters.
:param bytes|str|unicode body: Message payload
:param str routing_key: Message routing key
:param str exchange: The exchange to publish the message to
:param dict properties: Message properties
:param bool mandatory: Requires the message is published
:param bool immediate: Request immediate delivery
:raises AMQPInvalidArgument: Invalid Parameters
:return: | 1.756787 | 1.725581 | 1.018084 |
if 'content_encoding' not in properties:
properties['content_encoding'] = 'utf-8'
encoding = properties['content_encoding']
if compatibility.is_unicode(body):
body = body.encode(encoding)
elif compatibility.PYTHON3 and isinstance(body, str):
body = bytes(body, encoding=encoding)
return body | def _handle_utf8_payload(body, properties) | Update the Body and Properties to the appropriate encoding.
:param bytes|str|unicode body: Message payload
:param dict properties: Message properties
:return: | 2.837601 | 3.126925 | 0.907473 |
message_uuid = self._channel.rpc.register_request(
get_frame.valid_responses + ['ContentHeader', 'ContentBody']
)
try:
self._channel.write_frame(get_frame)
get_ok_frame = self._channel.rpc.get_request(message_uuid,
raw=True,
multiple=True)
if isinstance(get_ok_frame, specification.Basic.GetEmpty):
return None
content_header = self._channel.rpc.get_request(message_uuid,
raw=True,
multiple=True)
body = self._get_content_body(message_uuid,
content_header.body_size)
finally:
self._channel.rpc.remove(message_uuid)
return Message(channel=self._channel,
body=body,
method=dict(get_ok_frame),
properties=dict(content_header.properties),
auto_decode=auto_decode) | def _get_message(self, get_frame, auto_decode) | Get and return a message using a Basic.Get frame.
:param Basic.Get get_frame:
:param bool auto_decode: Auto-decode strings when possible.
:rtype: Message | 4.301732 | 4.15267 | 1.035895 |
confirm_uuid = self._channel.rpc.register_request(['Basic.Ack',
'Basic.Nack'])
self._channel.write_frames(frames_out)
result = self._channel.rpc.get_request(confirm_uuid, raw=True)
self._channel.check_for_errors()
if isinstance(result, specification.Basic.Ack):
return True
return False | def _publish_confirm(self, frames_out) | Confirm that message was published successfully.
:param list frames_out:
:rtype: bool | 6.403891 | 7.115816 | 0.899952 |
frames = int(math.ceil(len(body) / float(self._max_frame_size)))
for offset in compatibility.RANGE(0, frames):
start_frame = self._max_frame_size * offset
end_frame = start_frame + self._max_frame_size
body_len = len(body)
if end_frame > body_len:
end_frame = body_len
yield pamqp_body.ContentBody(body[start_frame:end_frame]) | def _create_content_body(self, body) | Split body based on the maximum frame size.
This function is based on code from Rabbitpy.
https://github.com/gmr/rabbitpy
:param bytes|str|unicode body: Message payload
:rtype: collections.Iterable | 3.215683 | 3.094819 | 1.039054 |
body = bytes()
while len(body) < body_size:
body_piece = self._channel.rpc.get_request(message_uuid, raw=True,
multiple=True)
if not body_piece.value:
break
body += body_piece.value
return body | def _get_content_body(self, message_uuid, body_size) | Get Content Body using RPC requests.
:param str uuid_body: Rpc Identifier.
:param int body_size: Content Size.
:rtype: str | 5.014866 | 5.59723 | 0.895955 |
if not compatibility.is_string(queue):
raise AMQPInvalidArgument('queue should be a string')
elif not isinstance(passive, bool):
raise AMQPInvalidArgument('passive should be a boolean')
elif not isinstance(durable, bool):
raise AMQPInvalidArgument('durable should be a boolean')
elif not isinstance(exclusive, bool):
raise AMQPInvalidArgument('exclusive should be a boolean')
elif not isinstance(auto_delete, bool):
raise AMQPInvalidArgument('auto_delete should be a boolean')
elif arguments is not None and not isinstance(arguments, dict):
raise AMQPInvalidArgument('arguments should be a dict or None')
declare_frame = pamqp_queue.Declare(queue=queue,
passive=passive,
durable=durable,
exclusive=exclusive,
auto_delete=auto_delete,
arguments=arguments)
return self._channel.rpc_request(declare_frame) | def declare(self, queue='', passive=False, durable=False,
exclusive=False, auto_delete=False, arguments=None) | Declare a Queue.
:param str queue: Queue name
:param bool passive: Do not create
:param bool durable: Durable queue
:param bool exclusive: Request exclusive access
:param bool auto_delete: Automatically delete when not in use
:param dict arguments: Queue key/value arguments
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: dict | 1.773073 | 1.852687 | 0.957028 |
if not compatibility.is_string(queue):
raise AMQPInvalidArgument('queue should be a string')
elif not isinstance(if_unused, bool):
raise AMQPInvalidArgument('if_unused should be a boolean')
elif not isinstance(if_empty, bool):
raise AMQPInvalidArgument('if_empty should be a boolean')
delete_frame = pamqp_queue.Delete(queue=queue, if_unused=if_unused,
if_empty=if_empty)
return self._channel.rpc_request(delete_frame) | def delete(self, queue='', if_unused=False, if_empty=False) | Delete a Queue.
:param str queue: Queue name
:param bool if_unused: Delete only if unused
:param bool if_empty: Delete only if empty
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: dict | 2.558283 | 2.605082 | 0.982035 |
if not compatibility.is_string(queue):
raise AMQPInvalidArgument('queue should be a string')
purge_frame = pamqp_queue.Purge(queue=queue)
return self._channel.rpc_request(purge_frame) | def purge(self, queue) | Purge a Queue.
:param str queue: Queue name
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: dict | 8.613212 | 8.110795 | 1.061944 |
if not compatibility.is_string(queue):
raise AMQPInvalidArgument('queue should be a string')
elif not compatibility.is_string(exchange):
raise AMQPInvalidArgument('exchange should be a string')
elif not compatibility.is_string(routing_key):
raise AMQPInvalidArgument('routing_key should be a string')
elif arguments is not None and not isinstance(arguments, dict):
raise AMQPInvalidArgument('arguments should be a dict or None')
bind_frame = pamqp_queue.Bind(queue=queue,
exchange=exchange,
routing_key=routing_key,
arguments=arguments)
return self._channel.rpc_request(bind_frame) | def bind(self, queue='', exchange='', routing_key='', arguments=None) | Bind a Queue.
:param str queue: Queue name
:param str exchange: Exchange name
:param str routing_key: The routing key to use
:param dict arguments: Bind key/value arguments
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: dict | 2.109001 | 2.219557 | 0.95019 |
if not compatibility.is_string(queue):
raise AMQPInvalidArgument('queue should be a string')
elif not compatibility.is_string(exchange):
raise AMQPInvalidArgument('exchange should be a string')
elif not compatibility.is_string(routing_key):
raise AMQPInvalidArgument('routing_key should be a string')
elif arguments is not None and not isinstance(arguments, dict):
raise AMQPInvalidArgument('arguments should be a dict or None')
unbind_frame = pamqp_queue.Unbind(queue=queue,
exchange=exchange,
routing_key=routing_key,
arguments=arguments)
return self._channel.rpc_request(unbind_frame) | def unbind(self, queue='', exchange='', routing_key='', arguments=None) | Unbind a Queue.
:param str queue: Queue name
:param str exchange: Exchange name
:param str routing_key: The routing key used
:param dict arguments: Unbind key/value arguments
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: dict | 2.087917 | 2.160721 | 0.966306 |
LOGGER.debug('Frame Received: %s', frame_in.name)
if frame_in.name == 'Heartbeat':
return
elif frame_in.name == 'Connection.Close':
self._close_connection(frame_in)
elif frame_in.name == 'Connection.CloseOk':
self._close_connection_ok()
elif frame_in.name == 'Connection.Blocked':
self._blocked_connection(frame_in)
elif frame_in.name == 'Connection.Unblocked':
self._unblocked_connection()
elif frame_in.name == 'Connection.OpenOk':
self._set_connection_state(Stateful.OPEN)
elif frame_in.name == 'Connection.Start':
self.server_properties = frame_in.server_properties
self._send_start_ok(frame_in)
elif frame_in.name == 'Connection.Tune':
self._send_tune_ok(frame_in)
self._send_open_connection()
else:
LOGGER.error('[Channel0] Unhandled Frame: %s', frame_in.name) | def on_frame(self, frame_in) | Handle frames sent to Channel0.
:param frame_in: Amqp frame.
:return: | 2.516028 | 2.208161 | 1.139423 |
self._set_connection_state(Stateful.CLOSED)
if frame_in.reply_code != 200:
reply_text = try_utf8_decode(frame_in.reply_text)
message = (
'Connection was closed by remote server: %s' % reply_text
)
exception = AMQPConnectionError(message,
reply_code=frame_in.reply_code)
self._connection.exceptions.append(exception) | def _close_connection(self, frame_in) | Connection Close.
:param specification.Connection.Close frame_in: Amqp frame.
:return: | 4.305486 | 4.313748 | 0.998085 |
self.is_blocked = True
LOGGER.warning(
'Connection is blocked by remote server: %s',
try_utf8_decode(frame_in.reason)
) | def _blocked_connection(self, frame_in) | Connection is Blocked.
:param frame_in:
:return: | 8.345557 | 8.867058 | 0.941187 |
mechanisms = try_utf8_decode(frame_in.mechanisms)
if 'EXTERNAL' in mechanisms:
mechanism = 'EXTERNAL'
credentials = '\0\0'
elif 'PLAIN' in mechanisms:
mechanism = 'PLAIN'
credentials = self._plain_credentials()
else:
exception = AMQPConnectionError(
'Unsupported Security Mechanism(s): %s' %
frame_in.mechanisms
)
self._connection.exceptions.append(exception)
return
start_ok_frame = specification.Connection.StartOk(
mechanism=mechanism,
client_properties=self._client_properties(),
response=credentials,
locale=LOCALE
)
self._write_frame(start_ok_frame) | def _send_start_ok(self, frame_in) | Send Start OK frame.
:param specification.Connection.Start frame_in: Amqp frame.
:return: | 3.622932 | 3.467706 | 1.044763 |
self.max_allowed_channels = self._negotiate(frame_in.channel_max,
MAX_CHANNELS)
self.max_frame_size = self._negotiate(frame_in.frame_max,
MAX_FRAME_SIZE)
LOGGER.debug(
'Negotiated max frame size %d, max channels %d',
self.max_frame_size, self.max_allowed_channels
)
tune_ok_frame = specification.Connection.TuneOk(
channel_max=self.max_allowed_channels,
frame_max=self.max_frame_size,
heartbeat=self._heartbeat)
self._write_frame(tune_ok_frame) | def _send_tune_ok(self, frame_in) | Send Tune OK frame.
:param specification.Connection.Tune frame_in: Tune frame.
:return: | 2.781188 | 2.615477 | 1.063358 |
open_frame = specification.Connection.Open(
virtual_host=self._parameters['virtual_host']
)
self._write_frame(open_frame) | def _send_open_connection(self) | Send Open Connection frame.
:return: | 7.431483 | 7.955098 | 0.934179 |
self._connection.write_frame(0, frame_out)
LOGGER.debug('Frame Sent: %s', frame_out.name) | def _write_frame(self, frame_out) | Write a pamqp frame from Channel0.
:param frame_out: Amqp frame.
:return: | 6.959308 | 7.656964 | 0.908886 |
return {
'product': 'AMQPStorm',
'platform': 'Python %s (%s)' % (platform.python_version(),
platform.python_implementation()),
'capabilities': {
'basic.nack': True,
'connection.blocked': True,
'publisher_confirms': True,
'consumer_cancel_notify': True,
'authentication_failure_close': True,
},
'information': 'See https://github.com/eandersson/amqpstorm',
'version': __version__
} | def _client_properties() | AMQPStorm Client Properties.
:rtype: dict | 3.394976 | 2.835733 | 1.197213 |
self.check_for_errors()
while not self.is_closed:
message = self._build_message(auto_decode=auto_decode)
if not message:
self.check_for_errors()
sleep(IDLE_WAIT)
if break_on_empty and not self._inbound:
break
continue
if to_tuple:
yield message.to_tuple()
continue
yield message | def build_inbound_messages(self, break_on_empty=False, to_tuple=False,
auto_decode=True) | Build messages in the inbound queue.
:param bool break_on_empty: Should we break the loop when there are
no more messages in our inbound queue.
This does not guarantee that the upstream
queue is empty, as it's possible that if
messages are consumed faster than
delivered, the inbound queue will then be
emptied and the consumption will be broken.
:param bool to_tuple: Should incoming messages be converted to a
tuple before delivery.
:param bool auto_decode: Auto-decode strings when possible.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:rtype: :py:class:`generator` | 3.469033 | 3.614361 | 0.959791 |
if not compatibility.is_integer(reply_code):
raise AMQPInvalidArgument('reply_code should be an integer')
elif not compatibility.is_string(reply_text):
raise AMQPInvalidArgument('reply_text should be a string')
try:
if self._connection.is_closed or self.is_closed:
self.stop_consuming()
LOGGER.debug('Channel #%d forcefully Closed', self.channel_id)
return
self.set_state(self.CLOSING)
LOGGER.debug('Channel #%d Closing', self.channel_id)
try:
self.stop_consuming()
except AMQPChannelError:
self.remove_consumer_tag()
self.rpc_request(specification.Channel.Close(
reply_code=reply_code,
reply_text=reply_text),
connection_adapter=self._connection
)
finally:
if self._inbound:
del self._inbound[:]
self.set_state(self.CLOSED)
if self._on_close_impl:
self._on_close_impl(self.channel_id)
LOGGER.debug('Channel #%d Closed', self.channel_id) | def close(self, reply_code=200, reply_text='') | Close Channel.
:param int reply_code: Close reply code (e.g. 200)
:param str reply_text: Close reply text
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return: | 3.229795 | 3.195372 | 1.010773 |
try:
self._connection.check_for_errors()
except AMQPConnectionError:
self.set_state(self.CLOSED)
raise
if self.exceptions:
exception = self.exceptions[0]
if self.is_open:
self.exceptions.pop(0)
raise exception
if self.is_closed:
raise AMQPChannelError('channel was closed') | def check_for_errors(self) | Check connection and channel for errors.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return: | 3.915552 | 3.592615 | 1.089889 |
self._confirming_deliveries = True
confirm_frame = specification.Confirm.Select()
return self.rpc_request(confirm_frame) | def confirm_deliveries(self) | Set the channel to confirm that each message has been
successfully delivered.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return: | 17.255327 | 14.773075 | 1.168025 |
if self.rpc.on_frame(frame_in):
return
if frame_in.name in CONTENT_FRAME:
self._inbound.append(frame_in)
elif frame_in.name == 'Basic.Cancel':
self._basic_cancel(frame_in)
elif frame_in.name == 'Basic.CancelOk':
self.remove_consumer_tag(frame_in.consumer_tag)
elif frame_in.name == 'Basic.ConsumeOk':
self.add_consumer_tag(frame_in['consumer_tag'])
elif frame_in.name == 'Basic.Return':
self._basic_return(frame_in)
elif frame_in.name == 'Channel.Close':
self._close_channel(frame_in)
elif frame_in.name == 'Channel.Flow':
self.write_frame(specification.Channel.FlowOk(frame_in.active))
else:
LOGGER.error(
'[Channel%d] Unhandled Frame: %s -- %s',
self.channel_id, frame_in.name, dict(frame_in)
) | def on_frame(self, frame_in) | Handle frame sent to this specific channel.
:param pamqp.Frame frame_in: Amqp frame.
:return: | 3.015962 | 2.700375 | 1.116868 |
self._inbound = []
self._exceptions = []
self.set_state(self.OPENING)
self.rpc_request(specification.Channel.Open())
self.set_state(self.OPEN) | def open(self) | Open Channel.
:return: | 9.717195 | 9.025538 | 1.076633 |
if not self._consumer_callbacks:
raise AMQPChannelError('no consumer callback defined')
for message in self.build_inbound_messages(break_on_empty=True,
auto_decode=auto_decode):
consumer_tag = message._method.get('consumer_tag')
if to_tuple:
# noinspection PyCallingNonCallable
self._consumer_callbacks[consumer_tag](*message.to_tuple())
continue
# noinspection PyCallingNonCallable
self._consumer_callbacks[consumer_tag](message) | def process_data_events(self, to_tuple=False, auto_decode=True) | Consume inbound messages.
:param bool to_tuple: Should incoming messages be converted to a
tuple before delivery.
:param bool auto_decode: Auto-decode strings when possible.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return: | 4.058539 | 3.73202 | 1.087491 |
with self.rpc.lock:
uuid = self.rpc.register_request(frame_out.valid_responses)
self._connection.write_frame(self.channel_id, frame_out)
return self.rpc.get_request(
uuid, connection_adapter=connection_adapter
) | def rpc_request(self, frame_out, connection_adapter=None) | Perform a RPC Request.
:param specification.Frame frame_out: Amqp frame.
:rtype: dict | 5.54143 | 5.608943 | 0.987963 |
while not self.is_closed:
self.process_data_events(
to_tuple=to_tuple,
auto_decode=auto_decode
)
if self.consumer_tags:
sleep(IDLE_WAIT)
continue
break | def start_consuming(self, to_tuple=False, auto_decode=True) | Start consuming messages.
:param bool to_tuple: Should incoming messages be converted to a
tuple before delivery.
:param bool auto_decode: Auto-decode strings when possible.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return: | 4.995795 | 5.438483 | 0.918601 |
if not self.consumer_tags:
return
if not self.is_closed:
for tag in self.consumer_tags:
self.basic.cancel(tag)
self.remove_consumer_tag() | def stop_consuming(self) | Stop consuming messages.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return: | 4.542165 | 4.714651 | 0.963415 |
self.check_for_errors()
self._connection.write_frame(self.channel_id, frame_out) | def write_frame(self, frame_out) | Write a pamqp frame from the current channel.
:param specification.Frame frame_out: A single pamqp frame.
:return: | 7.210715 | 7.51092 | 0.960031 |
self.check_for_errors()
self._connection.write_frames(self.channel_id, frames_out) | def write_frames(self, frames_out) | Write multiple pamqp frames from the current channel.
:param list frames_out: A list of pamqp frames.
:return: | 7.62429 | 7.023274 | 1.085575 |
LOGGER.warning(
'Received Basic.Cancel on consumer_tag: %s',
try_utf8_decode(frame_in.consumer_tag)
)
self.remove_consumer_tag(frame_in.consumer_tag) | def _basic_cancel(self, frame_in) | Handle a Basic Cancel frame.
:param specification.Basic.Cancel frame_in: Amqp frame.
:return: | 6.00425 | 5.753547 | 1.043574 |
reply_text = try_utf8_decode(frame_in.reply_text)
message = (
"Message not delivered: %s (%s) to queue '%s' from exchange '%s'" %
(
reply_text,
frame_in.reply_code,
frame_in.routing_key,
frame_in.exchange
)
)
exception = AMQPMessageError(message,
reply_code=frame_in.reply_code)
self.exceptions.append(exception) | def _basic_return(self, frame_in) | Handle a Basic Return Frame and treat it as an error.
:param specification.Basic.Return frame_in: Amqp frame.
:return: | 3.875766 | 3.941433 | 0.983339 |
with self.lock:
if len(self._inbound) < 2:
return None
headers = self._build_message_headers()
if not headers:
return None
basic_deliver, content_header = headers
body = self._build_message_body(content_header.body_size)
message = Message(channel=self,
body=body,
method=dict(basic_deliver),
properties=dict(content_header.properties),
auto_decode=auto_decode)
return message | def _build_message(self, auto_decode) | Fetch and build a complete Message from the inbound queue.
:param bool auto_decode: Auto-decode strings when possible.
:rtype: Message | 4.358205 | 4.296178 | 1.014438 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.