desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Create socket and connect to it, using SSL if enabled. :returns: error string on failure; None on success'
def _create_and_connect_to_socket(self, sock_addr_tuple):
self.socket = self._create_tcp_connection_socket(sock_addr_tuple[0], sock_addr_tuple[1], sock_addr_tuple[2]) self.socket.setsockopt(SOL_TCP, socket.TCP_NODELAY, 1) self.socket.settimeout(self.params.socket_timeout) if self.params.ssl: self.socket = self._wrap_socket(self.socket) ssl_text...
'Create TCP/IP stream socket for AMQP connection :param int sock_family: socket family :param int sock_type: socket type :param int sock_proto: socket protocol number NOTE We break this out to make it easier to patch in mock tests'
@staticmethod def _create_tcp_connection_socket(sock_family, sock_type, sock_proto):
return socket.socket(sock_family, sock_type, sock_proto)
'Perform SSL handshaking, copied from python stdlib test_ssl.py.'
def _do_ssl_handshake(self):
if (not self.DO_HANDSHAKE): return while True: try: self.socket.do_handshake() break except ssl.SSLError as err: if (err.args[0] == ssl.SSL_ERROR_WANT_READ): self.event_state = self.READ elif (err.args[0] == ssl.SSL_ERROR_WA...
'Wrap `socket.getaddrinfo` to make it easier to patch for unit tests'
@staticmethod def _getaddrinfo(host, port, family, socktype, proto):
return socket.getaddrinfo(host, port, family, socktype, proto)
'Get the error code from the error_value accounting for Python version differences. :rtype: int'
@staticmethod def _get_error_code(error_value):
if (not error_value): return None if hasattr(error_value, 'errno'): return error_value.errno else: return error_value[0]
'Have the state manager schedule the necessary I/O.'
def _flush_outbound(self):
self._manage_event_state()
'Invoked when the connection is closed to determine if the IOLoop should be stopped or not.'
def _handle_ioloop_stop(self):
if (self.stop_ioloop_on_close and self.ioloop): self.ioloop.stop() elif self.WARN_ABOUT_IOLOOP: LOGGER.warning('Connection is closed but not stopping IOLoop')
'Internal error handling method. Here we expect a socket.error coming in and will handle different socket errors differently. :param int|object error_value: The inbound error'
def _handle_error(self, error_value):
error_code = self._get_error_code(error_value) if (not error_code): LOGGER.critical('Tried to handle an error where no error existed') return if (error_code in self.ERRORS_TO_IGNORE): LOGGER.debug('Ignoring %s', error_code) return elif (error_co...
'Handle a socket timeout in read or write. We don\'t do anything in the non-blocking handlers because we only have the socket in a blocking state during connect.'
def _handle_timeout(self):
LOGGER.warning('Unexpected socket timeout')
'Handle IO/Event loop events, processing them. :param int fd: The file descriptor for the events :param int events: Events from the IO/Event loop :param int error: Was an error specified; TODO none of the current adapters appear to be able to pass the `error` arg - is it needed? :param bool write_only: Only handle writ...
def _handle_events(self, fd, events, error=None, write_only=False):
if (not self.socket): LOGGER.error('Received events on closed socket: %r', fd) return if (self.socket and (events & self.WRITE)): self._handle_write() self._manage_event_state() if (self.socket and (not write_only) and (events & self.READ)): self._handl...
'Read from the socket and call our on_data_available with the data.'
def _handle_read(self):
try: while True: try: if self.params.ssl: data = self.socket.read(self._buffer_size) else: data = self.socket.recv(self._buffer_size) break except _SOCKET_ERROR as error: if (error...
'Try and write as much as we can, if we get blocked requeue what\'s left'
def _handle_write(self):
total_bytes_sent = 0 try: while self.outbound_buffer: frame = self.outbound_buffer.popleft() while True: try: num_bytes_sent = self.socket.send(frame) break except _SOCKET_ERROR as error: ...
'Initialize or reset all of our internal state variables for a given connection. If we disconnect and reconnect, all of our state needs to be wiped.'
def _init_connection_state(self):
super(BaseConnection, self)._init_connection_state() self.base_events = (self.READ | self.ERROR) self.event_state = self.base_events self.socket = None
'Manage the bitmask for reading/writing/error which is used by the io/event handler to specify when there is an event such as a read or write.'
def _manage_event_state(self):
if self.outbound_buffer: if (not (self.event_state & self.WRITE)): self.event_state |= self.WRITE self.ioloop.update_handler(self.socket.fileno(), self.event_state) elif (self.event_state & self.WRITE): self.event_state = self.base_events self.ioloop.update_handle...
'Wrap the socket for connecting over SSL. :rtype: ssl.SSLSocket'
def _wrap_socket(self, sock):
ssl_options = (self.params.ssl_options or {}) return ssl.wrap_socket(sock, do_handshake_on_connect=self.DO_HANDSHAKE, **ssl_options)
'Basic adapter for asyncio event loop :type loop: asyncio.AbstractEventLoop :param loop: Asyncio Loop'
def __init__(self, loop):
self.loop = loop self.handlers = {} self.readers = set() self.writers = set()
'Add the callback_method to the EventLoop 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: asyncio.Handle'
def add_timeout(self, deadline, callback_method):
return self.loop.call_later(deadline, callback_method)
'Cancel asyncio.Handle :type handle: asyncio.Handle :rtype: bool'
@staticmethod def remove_timeout(handle):
return handle.cancel()
'Registers the given handler to receive the given events for ``fd``. The ``fd`` argument is an integer file descriptor. The ``event_state`` argument is a bitwise or of the constants ``base_connection.BaseConnection.READ``, ``base_connection.BaseConnection.WRITE``, and ``base_connection.BaseConnection.ERROR``.'
def add_handler(self, fd, cb, event_state):
if (fd in self.handlers): raise ValueError('fd {} added twice'.format(fd)) self.handlers[fd] = cb if (event_state & base_connection.BaseConnection.READ): self.loop.add_reader(fd, partial(cb, fd=fd, events=base_connection.BaseConnection.READ)) self.readers.add(fd) if (eve...
'Stop listening for events on ``fd``.'
def remove_handler(self, fd):
if (fd not in self.handlers): return if (fd in self.readers): self.loop.remove_reader(fd) self.readers.remove(fd) if (fd in self.writers): self.loop.remove_writer(fd) self.writers.remove(fd) del self.handlers[fd]
'Start Event Loop'
def start(self):
if self.loop.is_running(): return self.loop.run_forever()
'Stop Event Loop'
def stop(self):
if self.loop.is_closed(): return self.loop.stop()
'Create a new instance of the AsyncioConnection 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 on_open_error_callback: Method to call if the conn...
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.loop = (custom_ioloop or asyncio.get_event_loop()) self.ioloop = IOLoopAdapter(self.loop) super().__init__(parameters, on_open_callback, on_open_error_callback, on_close_callback, self.ioloop, stop_ioloop_on_close=stop_ioloop_on_close)
'Connect to the remote socket, adding the socket to the EventLoop if connected. :rtype: bool'
def _adapter_connect(self):
error = super()._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()._adapter_disconnect()
'Consume from a server queue. Returns a Deferred that fires with a tuple: (queue_object, consumer_tag). The queue object is an instance of ClosableDeferredQueue, where data received from the queue will be stored. Clients should use its get() method to fetch individual message.'
def basic_consume(self, *args, **kwargs):
if self.__closed: return defer.fail(self.__closed) queue = ClosableDeferredQueue() queue_name = kwargs['queue'] kwargs['consumer_callback'] = (lambda *args: queue.put(args)) self.__consumers.setdefault(queue_name, set()).add(queue) try: consumer_tag = self.__channel.basic_consume...
'Wraps the method the same way all the others are wrapped, but removes the reference to the queue object after it gets deleted on the server.'
def queue_delete(self, *args, **kwargs):
wrapped = self.__wrap_channel_method('queue_delete') queue_name = kwargs['queue'] d = wrapped(*args, **kwargs) return d.addCallback(self.__clear_consumer, queue_name)
'Make sure the channel is not closed and then publish. Return a Deferred that fires with the result of the channel\'s basic_publish.'
def basic_publish(self, *args, **kwargs):
if self.__closed: return defer.fail(self.__closed) return defer.succeed(self.__channel.basic_publish(*args, **kwargs))
'Wrap Pika\'s Channel method to make it return a Deferred that fires when the method completes and errbacks if the channel gets closed. If the original method\'s callback would receive more than one argument, the Deferred fires with a tuple of argument values.'
def __wrap_channel_method(self, name):
method = getattr(self.__channel, name) @functools.wraps(method) def wrapped(*args, **kwargs): if self.__closed: return defer.fail(self.__closed) d = defer.Deferred() self.__calls.add(d) d.addCallback(self.__clear_call, d) def single_argument(*args): ...
'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.reactor.callLater(deadline, callback_method)
'Remove a call :param twisted.internet.interfaces.IDelayedCall call: The call to cancel'
def remove_timeout(self, call):
call.cancel()
'Connect to the RabbitMQ broker'
def _adapter_connect(self):
error = super(TwistedConnection, self)._adapter_connect() if (not error): self.ioloop.update_handler(None, self.event_state) return error
'Called when the adapter should disconnect'
def _adapter_disconnect(self):
self.ioloop.remove_handler(None) self._cleanup_socket()
'Call superclass and then update the event state to flush the outgoing frame out. Commit 50d842526d9f12d32ad9f3c4910ef60b8c301f59 removed a self._flush_outbound call that was in _send_frame which previously made this step unnecessary.'
def _on_connected(self):
super(TwistedConnection, self)._on_connected() self._manage_event_state()
'Return a Deferred that fires with an instance of a wrapper around the Pika Channel class.'
def channel(self, channel_number=None):
d = defer.Deferred() base_connection.BaseConnection.channel(self, d.callback, channel_number) return d.addCallback(TwistedChannel)
'Override BaseConnection._flush_outbound to send all bufferred data the Twisted way, by writing to the transport. No need for buffering, Twisted handles that for us.'
def _flush_outbound(self):
while self.outbound_buffer: self.transport.write(self.outbound_buffer.popleft())
'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. Return a Deferred that fires with an instance of a wrapper around the Pika Channel class. :param int channel_...
def channel(self, channel_number=None):
d = defer.Deferred() base_connection.BaseConnection.channel(self, d.callback, channel_number) return d.addCallback(TwistedChannel)
'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, stop_ioloop_on_close=True, custom_ioloop=None):
ioloop = (custom_ioloop or IOLoop()) super(SelectConnection, self).__init__(parameters, on_open_callback, on_open_error_callback, on_close_callback, ioloop, stop_ioloop_on_close)
'Connect to the RabbitMQ broker, returning True on success, False on failure. :rtype: bool'
def _adapter_connect(self):
error = super(SelectConnection, 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(SelectConnection, self)._adapter_disconnect()
'Determine the best poller to use for this enviroment.'
@staticmethod def _get_poller():
poller = None if hasattr(select, 'epoll'): if ((not SELECT_TYPE) or (SELECT_TYPE == 'epoll')): LOGGER.debug('Using EPollPoller') poller = EPollPoller() if ((not poller) and hasattr(select, 'kqueue')): if ((not SELECT_TYPE) or (SELECT_TYPE == 'kqueue')): ...
'[API] 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 wa...
def add_timeout(self, deadline, callback_method):
return self._poller.add_timeout(deadline, callback_method)
'[API] Remove a timeout :param str timeout_id: The timeout id to remove'
def remove_timeout(self, timeout_id):
self._poller.remove_timeout(timeout_id)
'[API] Add a new fileno to the set to be monitored :param int fileno: The file descriptor :param method handler: What is called when an event happens :param int events: The event mask using READ, WRITE, ERROR'
def add_handler(self, fileno, handler, events):
self._poller.add_handler(fileno, handler, events)
'[API] Set the events to the current events :param int fileno: The file descriptor :param int events: The event mask using READ, WRITE, ERROR'
def update_handler(self, fileno, events):
self._poller.update_handler(fileno, events)
'[API] Remove a file descriptor from the set :param int fileno: The file descriptor'
def remove_handler(self, fileno):
self._poller.remove_handler(fileno)
'[API] Start the main poller loop. It will loop until requested to exit. See `IOLoop.stop`.'
def start(self):
self._poller.start()
'[API] Request exit from the ioloop. The loop is NOT guaranteed to stop before this method returns. This is the only method that may be called from another thread.'
def stop(self):
self._poller.stop()
'[Extension] Process pending timeouts, invoking callbacks for those whose time has come'
def process_timeouts(self):
self._poller.process_timeouts()
'[Extension] Activate the poller'
def activate_poller(self):
self._poller.activate_poller()
'[Extension] Deactivate the poller'
def deactivate_poller(self):
self._poller.deactivate_poller()
'[Extension] Wait for events of interest on registered file descriptors until an event of interest occurs or next timer deadline or `_PollerBase._MAX_POLL_TIMEOUT`, whichever is sooner, and dispatch the corresponding event handlers.'
def poll(self):
self._poller.poll()
'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):
timeout_at = (time.time() + deadline) value = {'deadline': timeout_at, 'callback': callback_method} timeout_id = hash(frozenset(value.items())) self._timeouts[timeout_id] = value if ((not self._next_timeout) or (timeout_at < self._next_timeout)): self._next_timeout = timeout_at LOGGER.de...
'Remove a timeout if it\'s still in the timeout stack :param str timeout_id: The timeout id to remove'
def remove_timeout(self, timeout_id):
try: timeout = self._timeouts.pop(timeout_id) except KeyError: LOGGER.warning('remove_timeout: %s not found', timeout_id) else: if (timeout['deadline'] == self._next_timeout): self._next_timeout = None LOGGER.debug('remove_timeout: removed %s', time...
'Get the interval to the next timeout event, or a default interval'
def _get_next_deadline(self):
if self._next_timeout: timeout = max((self._next_timeout - time.time()), 0) elif self._timeouts: deadlines = [t['deadline'] for t in self._timeouts.values()] self._next_timeout = min(deadlines) timeout = max(((self._next_timeout - time.time()), 0)) else: timeout = sel...
'Process pending timeouts, invoking callbacks for those whose time has come'
def process_timeouts(self):
now = time.time() to_run = sorted([(k, timer) for (k, timer) in self._timeouts.items() if (timer['deadline'] <= now)], key=(lambda item: item[1]['deadline'])) for (k, timer) in to_run: if (k not in self._timeouts): continue try: timer['callback']() finally: ...
'Add a new fileno to the set to be monitored :param int fileno: The file descriptor :param method handler: What is called when an event happens :param int events: The event mask using READ, WRITE, ERROR'
def add_handler(self, fileno, handler, events):
self._fd_handlers[fileno] = handler self._set_handler_events(fileno, events) self._register_fd(fileno, events)
'Set the events to the current events :param int fileno: The file descriptor :param int events: The event mask using READ, WRITE, ERROR'
def update_handler(self, fileno, events):
(events_cleared, events_set) = self._set_handler_events(fileno, events) self._modify_fd_events(fileno, events=events, events_to_clear=events_cleared, events_to_set=events_set)
'Remove a file descriptor from the set :param int fileno: The file descriptor'
def remove_handler(self, fileno):
try: del self._processing_fd_event_map[fileno] except KeyError: pass (events_cleared, _) = self._set_handler_events(fileno, 0) del self._fd_handlers[fileno] self._unregister_fd(fileno, events_to_clear=events_cleared)
'Set the handler\'s events to the given events; internal to `_PollerBase`. :param int fileno: The file descriptor :param int events: The event mask (READ, WRITE, ERROR) :returns: a 2-tuple (events_cleared, events_set)'
def _set_handler_events(self, fileno, events):
events_cleared = 0 events_set = 0 for evt in (READ, WRITE, ERROR): if (events & evt): if (fileno not in self._fd_events[evt]): self._fd_events[evt].add(fileno) events_set |= evt elif (fileno in self._fd_events[evt]): self._fd_events[evt...
'Activate the poller'
def activate_poller(self):
self._init_poller() fd_to_events = defaultdict(int) for (event, file_descriptors) in self._fd_events.items(): for fileno in file_descriptors: fd_to_events[fileno] |= event for (fileno, events) in fd_to_events.items(): self._register_fd(fileno, events)
'Deactivate the poller'
def deactivate_poller(self):
self._uninit_poller()
'Start the main poller loop. It will loop until requested to exit'
def start(self):
self._start_nesting_levels += 1 if (self._start_nesting_levels == 1): LOGGER.debug('Entering IOLoop') self._stopping = False self.activate_poller() with self._mutex: assert (self._r_interrupt is None) (self._r_interrupt, self._w_interrupt) = self._get_i...
'Request exit from the ioloop. The loop is NOT guaranteed to stop before this method returns. This is the only method that may be called from another thread.'
def stop(self):
LOGGER.debug('Stopping IOLoop') self._stopping = True with self._mutex: if (self._w_interrupt is None): return try: self._w_interrupt.send('X') except OSError as err: if (err.errno != errno.EWOULDBLOCK): raise except Exce...
'Wait for events on interested filedescriptors.'
@abc.abstractmethod def poll(self):
raise NotImplementedError
'Notify the implementation to allocate the poller resource'
@abc.abstractmethod def _init_poller(self):
raise NotImplementedError
'Notify the implementation to release the poller resource'
@abc.abstractmethod def _uninit_poller(self):
raise NotImplementedError
'The base class invokes this method to notify the implementation to register the file descriptor with the polling object. The request must be ignored if the poller is not activated. :param int fileno: The file descriptor :param int events: The event mask (READ, WRITE, ERROR)'
@abc.abstractmethod def _register_fd(self, fileno, events):
raise NotImplementedError
'The base class invoikes this method to notify the implementation to modify an already registered file descriptor. The request must be ignored if the poller is not activated. :param int fileno: The file descriptor :param int events: absolute events (READ, WRITE, ERROR) :param int events_to_clear: The events to clear (R...
@abc.abstractmethod def _modify_fd_events(self, fileno, events, events_to_clear, events_to_set):
raise NotImplementedError
'The base class invokes this method to notify the implementation to unregister the file descriptor being tracked by the polling object. The request must be ignored if the poller is not activated. :param int fileno: The file descriptor :param int events_to_clear: The events to clear (READ, WRITE, ERROR)'
@abc.abstractmethod def _unregister_fd(self, fileno, events_to_clear):
raise NotImplementedError
'Helper to dispatch callbacks for file descriptors that received events. Before doing so we re-calculate the event mask based on what is currently set in case it has been changed under our feet by a previous callback. We also take a store a refernce to the fd_event_map so that we can detect removal of an fileno during ...
def _dispatch_fd_events(self, fd_event_map):
self._processing_fd_event_map.clear() self._processing_fd_event_map = fd_event_map for fileno in dictkeys(fd_event_map): if (fileno not in fd_event_map): continue events = fd_event_map[fileno] for evt in [READ, WRITE, ERROR]: if (fileno not in self._fd_events[...
'Use a socketpair to be able to interrupt the ioloop if called from another thread. Socketpair() is not supported on some OS (Win) so use a pair of simple UDP sockets instead. The sockets will be closed and garbage collected by python when the ioloop itself is.'
@staticmethod def _get_interrupt_pair():
try: (read_sock, write_sock) = socket.socketpair() except AttributeError: LOGGER.debug('Using custom socketpair for interrupt') read_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) read_sock.bind(('localhost', 0)) write_sock = socket.socket(socket.AF_I...
'Read the interrupt byte(s). We ignore the event mask as we can ony get here if there\'s data to be read on our fd. :param int interrupt_fd: The file descriptor to read from :param int events: (unused) The events generated for this fd'
def _read_interrupt(self, interrupt_fd, events):
try: self._r_interrupt.recv(512) except OSError as err: if (err.errno != errno.EAGAIN): raise
'Create an instance of the SelectPoller'
def __init__(self):
super(SelectPoller, self).__init__()
'Wait for events of interest on registered file descriptors until an event of interest occurs or next timer deadline or _MAX_POLL_TIMEOUT, whichever is sooner, and dispatch the corresponding event handlers.'
def poll(self):
while True: try: if (self._fd_events[READ] or self._fd_events[WRITE] or self._fd_events[ERROR]): (read, write, error) = select.select(self._fd_events[READ], self._fd_events[WRITE], self._fd_events[ERROR], self._get_next_deadline()) else: time.sleep(sel...
'Notify the implementation to allocate the poller resource'
def _init_poller(self):
pass
'Notify the implementation to release the poller resource'
def _uninit_poller(self):
pass
'The base class invokes this method to notify the implementation to register the file descriptor with the polling object. The request must be ignored if the poller is not activated. :param int fileno: The file descriptor :param int events: The event mask using READ, WRITE, ERROR'
def _register_fd(self, fileno, events):
pass
'The base class invoikes this method to notify the implementation to modify an already registered file descriptor. The request must be ignored if the poller is not activated. :param int fileno: The file descriptor :param int events: absolute events (READ, WRITE, ERROR) :param int events_to_clear: The events to clear (R...
def _modify_fd_events(self, fileno, events, events_to_clear, events_to_set):
pass
'The base class invokes this method to notify the implementation to unregister the file descriptor being tracked by the polling object. The request must be ignored if the poller is not activated. :param int fileno: The file descriptor :param int events_to_clear: The events to clear (READ, WRITE, ERROR)'
def _unregister_fd(self, fileno, events_to_clear):
pass
'Create an instance of the KQueuePoller :param int fileno: The file descriptor to check events for :param method handler: What is called when an event happens :param int events: The events to look for'
def __init__(self):
super(KQueuePoller, self).__init__() self._kqueue = None
'return the event type associated with a kevent object :param kevent kevent: a kevent object as returned by kqueue.control()'
@staticmethod def _map_event(kevent):
if (kevent.filter == select.KQ_FILTER_READ): return READ elif (kevent.filter == select.KQ_FILTER_WRITE): return WRITE elif (kevent.flags & select.KQ_EV_ERROR): return ERROR
'Wait for events of interest on registered file descriptors until an event of interest occurs or next timer deadline or _MAX_POLL_TIMEOUT, whichever is sooner, and dispatch the corresponding event handlers.'
def poll(self):
while True: try: kevents = self._kqueue.control(None, 1000, self._get_next_deadline()) break except _SELECT_ERRORS as error: if _is_resumable(error): continue else: raise fd_event_map = defaultdict(int) for event...
'Notify the implementation to allocate the poller resource'
def _init_poller(self):
assert (self._kqueue is None) self._kqueue = select.kqueue()
'Notify the implementation to release the poller resource'
def _uninit_poller(self):
self._kqueue.close() self._kqueue = None
'The base class invokes this method to notify the implementation to register the file descriptor with the polling object. The request must be ignored if the poller is not activated. :param int fileno: The file descriptor :param int events: The event mask using READ, WRITE, ERROR'
def _register_fd(self, fileno, events):
self._modify_fd_events(fileno, events=events, events_to_clear=0, events_to_set=events)
'The base class invoikes this method to notify the implementation to modify an already registered file descriptor. The request must be ignored if the poller is not activated. :param int fileno: The file descriptor :param int events: absolute events (READ, WRITE, ERROR) :param int events_to_clear: The events to clear (R...
def _modify_fd_events(self, fileno, events, events_to_clear, events_to_set):
if (self._kqueue is None): return kevents = list() if (events_to_clear & READ): kevents.append(select.kevent(fileno, filter=select.KQ_FILTER_READ, flags=select.KQ_EV_DELETE)) if (events_to_set & READ): kevents.append(select.kevent(fileno, filter=select.KQ_FILTER_READ, flags=selec...
'The base class invokes this method to notify the implementation to unregister the file descriptor being tracked by the polling object. The request must be ignored if the poller is not activated. :param int fileno: The file descriptor :param int events_to_clear: The events to clear (READ, WRITE, ERROR)'
def _unregister_fd(self, fileno, events_to_clear):
self._modify_fd_events(fileno, events=0, events_to_clear=events_to_clear, events_to_set=0)
'Create an instance of the KQueuePoller :param int fileno: The file descriptor to check events for :param method handler: What is called when an event happens :param int events: The events to look for'
def __init__(self):
self._poll = None super(PollPoller, self).__init__()
':rtype: `select.poll`'
@staticmethod def _create_poller():
return select.poll()
'Wait for events of interest on registered file descriptors until an event of interest occurs or next timer deadline or _MAX_POLL_TIMEOUT, whichever is sooner, and dispatch the corresponding event handlers.'
def poll(self):
while True: try: events = self._poll.poll(self._get_next_deadline()) break except _SELECT_ERRORS as error: if _is_resumable(error): continue else: raise fd_event_map = defaultdict(int) for (fileno, event) in even...
'Notify the implementation to allocate the poller resource'
def _init_poller(self):
assert (self._poll is None) self._poll = self._create_poller()
'Notify the implementation to release the poller resource'
def _uninit_poller(self):
if hasattr(self._poll, 'close'): self._poll.close() self._poll = None
'The base class invokes this method to notify the implementation to register the file descriptor with the polling object. The request must be ignored if the poller is not activated. :param int fileno: The file descriptor :param int events: The event mask using READ, WRITE, ERROR'
def _register_fd(self, fileno, events):
if (self._poll is not None): self._poll.register(fileno, events)
'The base class invoikes this method to notify the implementation to modify an already registered file descriptor. The request must be ignored if the poller is not activated. :param int fileno: The file descriptor :param int events: absolute events (READ, WRITE, ERROR) :param int events_to_clear: The events to clear (R...
def _modify_fd_events(self, fileno, events, events_to_clear, events_to_set):
if (self._poll is not None): self._poll.modify(fileno, events)
'The base class invokes this method to notify the implementation to unregister the file descriptor being tracked by the polling object. The request must be ignored if the poller is not activated. :param int fileno: The file descriptor :param int events_to_clear: The events to clear (READ, WRITE, ERROR)'
def _unregister_fd(self, fileno, events_to_clear):
if (self._poll is not None): self._poll.unregister(fileno)
':rtype: `select.poll`'
@staticmethod def _create_poller():
return select.epoll()
'Create a new instance of the LibevConnection 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 connect...
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, on_signal_callback=None):
if custom_ioloop: self.ioloop = custom_ioloop else: with warnings.catch_warnings(): warnings.simplefilter('ignore', RuntimeWarning) self.ioloop = pyev.default_loop() self.ioloop.update() self.async = None self._on_signal_callback = on_signal_callback ...
'Connect to the remote socket, adding the socket to the IOLoop if connected :rtype: bool'
def _adapter_connect(self):
LOGGER.debug('init io and signal watchers if any') global global_sigint_watcher, global_sigterm_watcher error = super(LibevConnection, self)._adapter_connect() if (not error): if (self._on_signal_callback and (not global_sigterm_watcher)): global_sigterm_watcher = s...
'Initialize or reset all of our internal state variables for a given connection. If we disconnect and reconnect, all of our state needs to be wiped.'
def _init_connection_state(self):
active_timers = list(self._active_timers.keys()) for timer in active_timers: self.remove_timeout(timer) if global_sigint_watcher: global_sigint_watcher.stop() if global_sigterm_watcher: global_sigterm_watcher.stop() if self._io_watcher: self._io_watcher.stop() sup...