func_code_string
stringlengths
52
1.94M
func_documentation_string
stringlengths
1
47.2k
def _get_socket_addresses(self): family = socket.AF_UNSPEC if not socket.has_ipv6: family = socket.AF_INET try: addresses = socket.getaddrinfo(self._parameters['hostname'], self._parameters['port'], family, ...
Get Socket address information. :rtype: list
def _find_address_and_connect(self, addresses): error_message = None for address in addresses: sock = self._create_socket(socket_family=address[0]) try: sock.connect(address[4]) except (IOError, OSError) as why: error_message =...
Find and connect to the appropriate address. :param addresses: :raises AMQPConnectionError: Raises if the connection encountered an error. :rtype: socket.socket
def _create_socket(self, socket_family): sock = socket.socket(socket_family, socket.SOCK_STREAM, 0) sock.settimeout(self._parameters['timeout'] or None) if self.use_ssl: if not compatibility.SSL_SUPPORTED: raise AMQPConnectionError( 'Pytho...
Create Socket. :param int socket_family: :rtype: socket.socket
def _ssl_wrap_socket(self, sock): context = self._parameters['ssl_options'].get('context') if context is not None: hostname = self._parameters['ssl_options'].get('server_hostname') return context.wrap_socket( sock, do_handshake_on_connect=True, ...
Wrap SSLSocket around the Socket. :param socket.socket sock: :rtype: SSLSocket
def _create_inbound_thread(self): inbound_thread = threading.Thread(target=self._process_incoming_data, name=__name__) inbound_thread.daemon = True inbound_thread.start() return inbound_thread
Internal Thread that handles all incoming traffic. :rtype: threading.Thread
def _process_incoming_data(self): while self._running.is_set(): if self.poller.is_ready: self.data_in += self._receive() self.data_in = self._on_read_impl(self.data_in)
Retrieve and process any incoming data. :return:
def _receive(self): data_in = EMPTY_BUFFER try: data_in = self._read_from_socket() except socket.timeout: pass except (IOError, OSError) as why: if why.args[0] not in (EWOULDBLOCK, EAGAIN): self._exceptions.append(AMQPConnectio...
Receive any incoming socket data. If an error is thrown, handle it and return an empty string. :return: data_in :rtype: bytes
def _read_from_socket(self): if not self.use_ssl: if not self.socket: raise socket.error('connection/socket error') return self.socket.recv(MAX_FRAME_SIZE) with self._rd_lock: if not self.socket: raise socket.error('connection/...
Read data from the socket. :rtype: bytes
def start(self, exceptions): if not self._interval: return False self._running.set() with self._lock: self._threshold = 0 self._reads_since_check = 0 self._writes_since_check = 0 self._exceptions = exceptions LOGGER.debug('...
Start the Heartbeat Checker. :param list exceptions: :return:
def stop(self): self._running.clear() with self._lock: if self._timer: self._timer.cancel() self._timer = None
Stop the Heartbeat Checker. :return:
def _check_for_life_signs(self): if not self._running.is_set(): return False if self._writes_since_check == 0: self.send_heartbeat_impl() self._lock.acquire() try: if self._reads_since_check == 0: self._threshold += 1 ...
Check Connection for life signs. First check if any data has been sent, if not send a heartbeat to the remote server. If we have not received any data what so ever within two intervals, we need to raise an exception so that we can close the connection. ...
def _raise_or_append_exception(self): message = ( 'Connection dead, no heartbeat or data received in >= ' '%ds' % ( self._interval * 2 ) ) why = AMQPConnectionError(message) if self._exceptions is None: raise why ...
The connection is presumably dead and we need to raise or append an exception. If we have a list for exceptions, append the exception and let the connection handle it, if not raise the exception here. :return:
def _start_new_timer(self): if not self._running.is_set(): return False self._timer = self.timer_impl( interval=self._interval, function=self._check_for_life_signs ) self._timer.daemon = True self._timer.start() return True
Create a timer that will be used to periodically check the connection for heartbeats. :return:
def declare(self, exchange='', exchange_type='direct', passive=False, durable=False, auto_delete=False, arguments=None): if not compatibility.is_string(exchange): raise AMQPInvalidArgument('exchange should be a string') elif not compatibility.is_string(exchange_type)...
Declare an Exchange. :param str exchange: Exchange name :param str exchange_type: Exchange type :param bool passive: Do not create :param bool durable: Durable exchange :param bool auto_delete: Automatically delete when not in use :param dict arguments: Exchange key/valu...
def delete(self, exchange='', if_unused=False): if not compatibility.is_string(exchange): raise AMQPInvalidArgument('exchange should be a string') delete_frame = pamqp_exchange.Delete(exchange=exchange, if_unused=if_unused) return...
Delete an Exchange. :param str exchange: Exchange name :param bool if_unused: Delete only if unused :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError: Raises if the connection ...
def bind(self, destination='', source='', routing_key='', arguments=None): if not compatibility.is_string(destination): raise AMQPInvalidArgument('destination should be a string') elif not compatibility.is_string(source): raise AMQPInvalidArgument('source sh...
Bind an Exchange. :param str destination: Exchange name :param str source: Exchange to bind to :param str routing_key: The routing key to use :param dict arguments: Bind key/value arguments :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises...
def unbind(self, destination='', source='', routing_key='', arguments=None): if not compatibility.is_string(destination): raise AMQPInvalidArgument('destination should be a string') elif not compatibility.is_string(source): raise AMQPInvalidArgument('sourc...
Unbind an Exchange. :param str destination: Exchange name :param str source: Exchange to unbind from :param str routing_key: The routing key used :param dict arguments: Unbind key/value arguments :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: ...
def get(self, queue, virtual_host='/'): virtual_host = quote(virtual_host, '') return self.http_client.get( API_QUEUE % ( virtual_host, queue ) )
Get Queue details. :param queue: Queue name :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
def list(self, virtual_host='/', show_all=False): if show_all: return self.http_client.get(API_QUEUES) virtual_host = quote(virtual_host, '') return self.http_client.get( API_QUEUES_VIRTUAL_HOST % virtual_host )
List Queues. :param str virtual_host: Virtual host name :param bool show_all: List all Queues :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list
def declare(self, queue='', virtual_host='/', passive=False, durable=False, auto_delete=False, arguments=None): if passive: return self.get(queue, virtual_host=virtual_host) queue_payload = json.dumps( { 'durable': durable, ...
Declare a Queue. :param str queue: Queue name :param str virtual_host: Virtual host name :param bool passive: Do not create :param bool durable: Durable queue :param bool auto_delete: Automatically delete when not in use :param dict|None arguments: Queue key/value argume...
def delete(self, queue, virtual_host='/'): virtual_host = quote(virtual_host, '') return self.http_client.delete(API_QUEUE % ( virtual_host, queue ...
Delete a Queue. :param str queue: Queue name :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
def purge(self, queue, virtual_host='/'): virtual_host = quote(virtual_host, '') return self.http_client.delete(API_QUEUE_PURGE % ( virtual_host, queue ...
Purge a Queue. :param str queue: Queue name :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: None
def bindings(self, queue, virtual_host='/'): virtual_host = quote(virtual_host, '') return self.http_client.get(API_QUEUE_BINDINGS % ( virtual_host, queue ...
Get Queue bindings. :param str queue: Queue name :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: list
def bind(self, queue='', exchange='', routing_key='', virtual_host='/', arguments=None): bind_payload = json.dumps({ 'destination': queue, 'destination_type': 'q', 'routing_key': routing_key, 'source': exchange, 'arguments': argum...
Bind a Queue. :param str queue: Queue name :param str exchange: Exchange name :param str routing_key: The routing key to use :param str virtual_host: Virtual host name :param dict|None arguments: Bind key/value arguments :raises ApiError: Raises if the remote server enc...
def unbind(self, queue='', exchange='', routing_key='', virtual_host='/', properties_key=None): unbind_payload = json.dumps({ 'destination': queue, 'destination_type': 'q', 'properties_key': properties_key or routing_key, 'source': exchange...
Unbind a Queue. :param str queue: Queue name :param str exchange: Exchange name :param str routing_key: The routing key to use :param str virtual_host: Virtual host name :param str properties_key: :raises ApiError: Raises if the remote server encountered an error. ...
def get(self, exchange, virtual_host='/'): virtual_host = quote(virtual_host, '') return self.http_client.get( API_EXCHANGE % ( virtual_host, exchange) )
Get Exchange details. :param str exchange: Exchange name :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
def list(self, virtual_host='/', show_all=False): if show_all: return self.http_client.get(API_EXCHANGES) virtual_host = quote(virtual_host, '') return self.http_client.get( API_EXCHANGES_VIRTUAL_HOST % virtual_host )
List Exchanges. :param str virtual_host: Virtual host name :param bool show_all: List all Exchanges :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list
def declare(self, exchange='', exchange_type='direct', virtual_host='/', passive=False, durable=False, auto_delete=False, internal=False, arguments=None): if passive: return self.get(exchange, virtual_host=virtual_host) exchange_payload = json.dumps( ...
Declare an Exchange. :param str exchange: Exchange name :param str exchange_type: Exchange type :param str virtual_host: Virtual host name :param bool passive: Do not create :param bool durable: Durable exchange :param bool auto_delete: Automatically delete when not in u...
def delete(self, exchange, virtual_host='/'): virtual_host = quote(virtual_host, '') return self.http_client.delete(API_EXCHANGE % ( virtual_host, exchange ...
Delete an Exchange. :param str exchange: Exchange name :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
def bindings(self, exchange, virtual_host='/'): virtual_host = quote(virtual_host, '') return self.http_client.get(API_EXCHANGE_BINDINGS % ( virtual_host, exchange ...
Get Exchange bindings. :param str exchange: Exchange name :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: list
def bind(self, destination='', source='', routing_key='', virtual_host='/', arguments=None): bind_payload = json.dumps({ 'destination': destination, 'destination_type': 'e', 'routing_key': routing_key, 'source': source, 'arguments...
Bind an Exchange. :param str source: Source Exchange name :param str destination: Destination Exchange name :param str routing_key: The routing key to use :param str virtual_host: Virtual host name :param dict|None arguments: Bind key/value arguments :raises ApiError: R...
def unbind(self, destination='', source='', routing_key='', virtual_host='/', properties_key=None): unbind_payload = json.dumps({ 'destination': destination, 'destination_type': 'e', 'properties_key': properties_key or routing_key, 'source'...
Unbind an Exchange. :param str source: Source Exchange name :param str destination: Destination Exchange name :param str routing_key: The routing key to use :param str virtual_host: Virtual host name :param str properties_key: :raises ApiError: Raises if the remote serv...
def channel(self, rpc_timeout=60, lazy=False): LOGGER.debug('Opening a new Channel') if not compatibility.is_integer(rpc_timeout): raise AMQPInvalidArgument('rpc_timeout should be an integer') elif self.is_closed: raise AMQPConnectionError('socket/connection clos...
Open Channel. :param int rpc_timeout: Timeout before we give up waiting for an RPC response from the server. :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError: Raises if the channel encountered an error. :raises AMQPConnectionError...
def check_for_errors(self): if not self.exceptions: if not self.is_closed: return why = AMQPConnectionError('connection was closed') self.exceptions.append(why) self.set_state(self.CLOSED) self.close() raise self.exceptions[0]
Check Connection for errors. :raises AMQPConnectionError: Raises if the connection encountered an error. :return:
def close(self): LOGGER.debug('Connection Closing') if not self.is_closed: self.set_state(self.CLOSING) self.heartbeat.stop() try: if not self.is_closed and self.socket: self._channel0.send_close_connection() self._wait_for...
Close connection. :raises AMQPConnectionError: Raises if the connection encountered an error. :return:
def open(self): LOGGER.debug('Connection Opening') self.set_state(self.OPENING) self._exceptions = [] self._channels = {} self._last_channel_id = None self._io.open() self._send_handshake() self._wait_for_connection_state(state=Stateful.OPEN) ...
Open Connection. :raises AMQPConnectionError: Raises if the connection encountered an error.
def write_frame(self, channel_id, frame_out): frame_data = pamqp_frame.marshal(frame_out, channel_id) self.heartbeat.register_write() self._io.write_to_socket(frame_data)
Marshal and write an outgoing pamqp frame to the Socket. :param int channel_id: Channel ID. :param specification.Frame frame_out: Amqp frame. :return:
def write_frames(self, channel_id, frames_out): data_out = EMPTY_BUFFER for single_frame in frames_out: data_out += pamqp_frame.marshal(single_frame, channel_id) self.heartbeat.register_write() self._io.write_to_socket(data_out)
Marshal and write multiple outgoing pamqp frames to the Socket. :param int channel_id: Channel ID/ :param list frames_out: Amqp frames. :return:
def _close_remaining_channels(self): for channel_id in list(self._channels): self._channels[channel_id].set_state(Channel.CLOSED) self._channels[channel_id].close() self._cleanup_channel(channel_id)
Forcefully close all open channels. :return:
def _get_next_available_channel_id(self): 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 i...
Returns the next available available channel id. :raises AMQPConnectionError: Raises if there is no available channel. :rtype: int
def _handle_amqp_frame(self, data_in): 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: ...
Unmarshal a single AMQP frame and return the result. :param data_in: socket data :return: data_in, channel_id, frame
def _read_buffer(self, data_in): 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...
Process the socket buffer, and direct the data to the appropriate channel. :rtype: bytes
def _cleanup_channel(self, channel_id): with self.lock: if channel_id not in self._channels: return del self._channels[channel_id]
Remove the the channel from the list of available channels. :param int channel_id: Channel id :return:
def _validate_parameters(self): 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') ...
Validate Connection Parameters. :return:
def _wait_for_connection_state(self, state=Stateful.OPEN, rpc_timeout=30): 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') ...
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:
def create_connection(self): 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) ...
Create a connection. :return:
def start(self): 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) ...
Start the Consumers. :return:
def stop(self): while self._consumers: consumer = self._consumers.pop() consumer.stop() self._stopped.set() self._connection.close()
Stop all consumers. :return:
def _create_connection(self): attempts = 0 while True: attempts += 1 if self._stopped.is_set(): break try: self._connection = Connection(self.hostname, self.username, ...
Create a connection. :return:
def _stop_consumers(self, number_of_consumers=0): while len(self._consumers) > number_of_consumers: consumer = self._consumers.pop() consumer.stop()
Stop a specific number of consumers. :param number_of_consumers: :return:
def _start_consumer(self, consumer): thread = threading.Thread(target=consumer.start, args=(self._connection,)) thread.daemon = True thread.start()
Start a consumer as a new Thread. :param Consumer consumer: :return:
def select(self): self._tx_active = True return self._channel.rpc_request(specification.Tx.Select())
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:
def commit(self): self._tx_active = False return self._channel.rpc_request(specification.Tx.Commit())
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:
def rollback(self): self._tx_active = False return self._channel.rpc_request(specification.Tx.Rollback())
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 transacti...
def rpc_call(payload): # 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]
Simple Flask implementation for making asynchronous Rpc calls.
def _create_process_thread(self): thread = threading.Thread(target=self._process_data_events) thread.setDaemon(True) thread.start()
Create a thread responsible for consuming messages in response to RPC requests.
def create(channel, body, properties=None): 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...
Create a new Message. :param Channel channel: AMQPStorm Channel :param bytes|str|unicode body: Message payload :param dict properties: Message properties :rtype: Message
def body(self): 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
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
def ack(self): if not self._method: raise AMQPMessageError( 'Message.ack only available on incoming messages' ) self._channel.basic.ack(delivery_tag=self.delivery_tag)
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:
def nack(self, requeue=True): if not self._method: raise AMQPMessageError( 'Message.nack only available on incoming messages' ) self._channel.basic.nack(delivery_tag=self.delivery_tag, requeue=requeue)
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...
def publish(self, routing_key, exchange='', mandatory=False, immediate=False): return self._channel.basic.publish(body=self._body, routing_key=routing_key, exchange=exchange, ...
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 ...
def _update_properties(self, name, value): if self._auto_decode and 'properties' in self._decode_cache: self._decode_cache['properties'][name] = value self._properties[name] = value
Update properties, and keep cache up-to-date if auto decode is enabled. :param str name: Key :param obj value: Value :return:
def _try_decode_utf8_content(self, content, content_type): 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_...
Generic function to decode content. :param object content: :return:
def _try_decode_dict(self, content): 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]...
Decode content of a dictionary. :param dict content: :return:
def _try_decode_list(content): result = list() for value in content: result.append(try_utf8_decode(value)) return result
Decode content of a list. :param list|tuple content: :return:
def publish(self, body, routing_key, exchange='amq.default', virtual_host='/', properties=None, payload_encoding='string'): exchange = quote(exchange, '') properties = properties or {} body = json.dumps( { 'routing_key': routing_key, ...
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 payl...
def get(self, queue, virtual_host='/', requeue=False, to_dict=False, count=1, truncate=50000, encoding='auto'): ackmode = 'ack_requeue_false' if requeue: ackmode = 'ack_requeue_true' get_messages = json.dumps( { 'count': count, ...
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 message...
def get(self, virtual_host): virtual_host = quote(virtual_host, '') return self.http_client.get(API_VIRTUAL_HOST % 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
def create(self, virtual_host): virtual_host = quote(virtual_host, '') return self.http_client.put(API_VIRTUAL_HOST % 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
def delete(self, virtual_host): virtual_host = quote(virtual_host, '') return self.http_client.delete(API_VIRTUAL_HOST % 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
def get_permissions(self, virtual_host): virtual_host = quote(virtual_host, '') return self.http_client.get(API_VIRTUAL_HOSTS_PERMISSION % ( 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
def add_consumer_tag(self, tag): 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)
Add a Consumer tag. :param str tag: Consumer tag. :return:
def remove_consumer_tag(self, tag=None): if tag is not None: if tag in self._consumer_tags: self._consumer_tags.remove(tag) else: self._consumer_tags = []
Remove a Consumer tag. If no tag is specified, all all tags will be removed. :param str|None tag: Consumer tag. :return:
def to_dict(self): return { 'body': self._body, 'method': self._method, 'properties': self._properties, 'channel': self._channel }
Message to Dictionary. :rtype: dict
def to_tuple(self): return self._body, self._channel, self._method, self._properties
Message to Tuple. :rtype: tuple
def close(self, connection, reason='Closed via management api'): close_payload = json.dumps({ 'name': connection, 'reason': reason }) connection = quote(connection, '') return self.http_client.delete(API_CONNECTION % connection, ...
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
def on_frame(self, frame_in): 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
On RPC Frame. :param specification.Frame frame_in: Amqp frame. :return:
def register_request(self, valid_responses): uuid = str(uuid4()) self._response[uuid] = [] for action in valid_responses: self._request[action] = uuid return uuid
Register a RPC request. :param list valid_responses: List of possible Responses that we should be waiting for. :return:
def remove_request(self, uuid): for key in list(self._request): if self._request[key] == uuid: del self._request[key]
Remove any RPC request(s) using this uuid. :param str uuid: Rpc Identifier. :return:
def get_request(self, uuid, raw=False, multiple=False, connection_adapter=None): if uuid not in self._response: return self._wait_for_request( uuid, connection_adapter or self._default_connection_adapter ) frame = self._get_response_fr...
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. ...
def _get_response_frame(self, uuid): frame = None frames = self._response.get(uuid, None) if frames: frame = frames.pop(0) return frame
Get a response frame. :param str uuid: Rpc Identifier :return:
def _wait_for_request(self, uuid, connection_adapter=None): 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.sl...
Wait for RPC request to arrive. :param str uuid: Rpc Identifier. :param obj connection_adapter: Provide custom connection adapter. :return:
def _raise_rpc_timeout_error(self, uuid): 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...
Gather information and raise an Rpc exception. :param str uuid: Rpc Identifier. :return:
def get_default_ssl_version(): 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
Get the highest support TLS version, if none is available, return None. :rtype: bool|None
def is_string(obj): if PYTHON3: str_type = (bytes, str) else: str_type = (bytes, str, unicode) return isinstance(obj, str_type)
Is this a string. :param object obj: :rtype: bool
def is_integer(obj): if PYTHON3: return isinstance(obj, int) return isinstance(obj, (int, long))
Is this an integer. :param object obj: :return:
def try_utf8_decode(value): 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 UnicodeDecodeErro...
Try to decode an object. :param value: :return:
def patch_uri(uri): 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
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
def _parse_uri_options(self, parsed_uri, use_ssl=False, ssl_options=None): 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, 'virt...
Parse the uri options. :param parsed_uri: :param bool use_ssl: :return:
def _parse_ssl_options(self, ssl_kwargs): 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_ve...
Parse TLS Options. :param ssl_kwargs: :rtype: dict
def _get_ssl_version(self, value): return self._get_ssl_attribute(value, compatibility.SSL_VERSIONS, ssl.PROTOCOL_TLSv1, 'ssl_options: ssl_version \'%s\' not ' 'found falling back to PRO...
Get the TLS Version. :param str value: :return: TLS Version
def _get_ssl_validation(self, value): return self._get_ssl_attribute(value, compatibility.SSL_CERT_MAP, ssl.CERT_NONE, 'ssl_options: cert_reqs \'%s\' not ' 'found falling back to CERT_NO...
Get the TLS Validation option. :param str value: :return: TLS Certificate Options
def _get_ssl_attribute(value, mapping, default_value, warning_message): for key in mapping: if not key.endswith(value.lower()): continue return mapping[key] LOGGER.warning(warning_message, value) return default_value
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 war...
def top(self): nodes = [] for node in self.nodes(): nodes.append(self.http_client.get(API_TOP % node['name'])) return nodes
Top Processes. :raises ApiError: Raises if the remote server encountered an error. :raises ApiConnectionError: Raises if there was a connectivity issue. :rtype: list
def qos(self, prefetch_count=0, prefetch_size=0, global_=False): 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 s...
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 ch...
def get(self, queue='', no_ack=False, to_dict=False, auto_decode=True): 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 se...
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...
def recover(self, requeue=False): 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)
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 ...
def consume(self, callback=None, queue='', consumer_tag='', exclusive=False, no_ack=False, no_local=False, arguments=None): if not compatibility.is_string(queue): raise AMQPInvalidArgument('queue should be a string') elif not compatibility.is_string(consumer_tag): ...
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 ...
def cancel(self, consumer_tag=''): 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._c...
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...
def publish(self, body, routing_key, exchange='', properties=None, mandatory=False, immediate=False): self._validate_publish_parameters(body, exchange, immediate, mandatory, properties, routing_key) properties = properties or {} ...
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 :...