Debian Codegraph @

pika/adapters/select_connection.py

raw
1 """A connection adapter that tries to use the best polling method for the
2 platform pika is running on.
3
4 """
5 from __future__ import annotations
6
7 import abc
8 import collections
9 import errno
10 import heapq
11 import logging
12 import select
13 import time
14 import threading
15 from typing import Any, Callable, Optional, Sequence, Set, Tuple, Type, Dict, Union, TYPE_CHECKING
16
17 import pika.compat
18
19 from pika.adapters.utils import nbio_interface
20 from pika.adapters.base_connection import BaseConnection
21 from pika.adapters.utils.selector_ioloop_adapter import (
22 SelectorIOServicesAdapter, AbstractSelectorIOLoop)
23
24 if TYPE_CHECKING:
25 from typing_extensions import TypedDict
26 from pika import connection
27 from pika.adapters.utils import connection_workflow
28 import socket
29
30 SELECT_ERROR_T = Union[OSError, IOError, InterruptedError, select.error]
31
32 class POLLER_PARAMS(TypedDict):
33 get_wait_seconds: Callable[[], Optional[float]]
34 process_timeouts: Callable[[], None]
35
36
37 LOGGER = logging.getLogger(__name__)
38
39 # Non-blocking socket read/send returns one of these errnos when no data is
40 # available or the operation would block. On POSIX systems EAGAIN and
41 # EWOULDBLOCK have the same value; on Windows they differ (EWOULDBLOCK is
42 # WSAEWOULDBLOCK / 10035), so both must be checked for portable handling.
43 _TRY_IO_AGAIN_SOCK_ERROR_CODES = (errno.EAGAIN, errno.EWOULDBLOCK)
44
45 # One of select, epoll, kqueue or poll
46 SELECT_TYPE = None
47
48 # Reason for this unconventional dict initialization is the fact that on some
49 # platforms select.error is an aliases for OSError. We don't want the lambda
50 # for select.error to win over one for OSError.
51 _SELECT_ERROR_CHECKERS: Dict[Type[SELECT_ERROR_T], Callable[
52 [SELECT_ERROR_T], bool]] = {
53 InterruptedError: lambda _: True,
54 select.error: lambda e: e.args[0] == errno.EINTR,
55 IOError: lambda e: e.errno == errno.EINTR,
56 OSError: lambda e: e.errno == errno.EINTR,
57 }
58
59 # We can reduce the number of elements in the list by looking at super-sub
60 # class relationship because only the most generic ones needs to be caught.
61 # For now the optimization is left out.
62 # Following is better but still incomplete.
63 # _SELECT_ERRORS = tuple(filter(lambda e: not isinstance(e, OSError),
64 # _SELECT_ERROR_CHECKERS.keys())
65 # + [OSError])
66 _SELECT_ERRORS: Tuple[Type[SELECT_ERROR_T],
67 ...] = tuple(_SELECT_ERROR_CHECKERS.keys())
68
69
70 def _is_resumable(exc: SELECT_ERROR_T) -> bool:
71 """Check if caught exception represents EINTR error.
72 :param exc: exception; must be one of classes in _SELECT_ERRORS
73
74 """
75 checker = _SELECT_ERROR_CHECKERS.get(exc.__class__, None)
76 if checker is not None:
77 return checker(exc)
78 else:
79 return False
80
81
82 class SelectConnection(BaseConnection):
83 """An asynchronous connection adapter that attempts to use the fastest
84 event loop adapter for the given platform.
85
86 """
87
88 def __init__(
89 self, # pylint: disable=R0913
90 parameters: Optional[connection.Parameters] = None,
91 on_open_callback: Optional[Callable[[connection.Connection],
92 None]] = None,
93 on_open_error_callback: Optional[Callable[
94 [connection.Connection, BaseException], None]] = None,
95 on_close_callback: Optional[Callable[
96 [connection.Connection, BaseException], None]] = None,
97 custom_ioloop: Optional[Union[nbio_interface.AbstractIOServices,
98 IOLoop]] = None,
99 internal_connection_workflow: bool = True) -> None:
100 """Create a new instance of the Connection object.
101
102 :param pika.connection.Parameters parameters: Connection parameters
103 :param callable on_open_callback: Method to call on connection open
104 :param None | method on_open_error_callback: Called if the connection
105 can't be established or connection establishment is interrupted by
106 `Connection.close()`: on_open_error_callback(Connection, exception).
107 :param None | method on_close_callback: Called when a previously fully
108 open connection is closed:
109 `on_close_callback(Connection, exception)`, where `exception` is
110 either an instance of `exceptions.ConnectionClosed` if closed by
111 user or broker or exception of another type that describes the cause
112 of connection failure.
113 :param None | IOLoop | nbio_interface.AbstractIOServices custom_ioloop:
114 Provide a custom I/O Loop object.
115 :param bool internal_connection_workflow: True for autonomous connection
116 establishment which is default; False for externally-managed
117 connection workflow via the `create_connection()` factory.
118 :raises: RuntimeError
119
120 """
121 if isinstance(custom_ioloop, nbio_interface.AbstractIOServices):
122 nbio = custom_ioloop
123 else:
124 nbio = SelectorIOServicesAdapter(custom_ioloop or IOLoop())
125
126 super().__init__(
127 parameters,
128 on_open_callback,
129 on_open_error_callback,
130 on_close_callback,
131 nbio,
132 internal_connection_workflow=internal_connection_workflow)
133
134 @classmethod
135 def create_connection(
136 cls,
137 connection_configs: Sequence[connection.Parameters],
138 on_done: Callable[[
139 Union[connection.Connection,
140 connection_workflow.AMQPConnectorException]
141 ], None],
142 custom_ioloop: Optional[Any] = None,
143 workflow: Optional[
144 connection_workflow.AbstractAMQPConnectionWorkflow] = None
145 ) -> connection_workflow.AbstractAMQPConnectionWorkflow:
146 """Implement
147 :py:classmethod::`pika.adapters.BaseConnection.create_connection()`.
148
149 """
150 nbio = SelectorIOServicesAdapter(custom_ioloop or IOLoop())
151
152 def connection_factory(params):
153 """Connection factory."""
154 if params is None:
155 raise ValueError('Expected pika.connection.Parameters '
156 'instance, but got None in params arg.')
157 return cls(parameters=params,
158 custom_ioloop=nbio,
159 internal_connection_workflow=False)
160
161 return cls._start_connection_workflow(
162 connection_configs=connection_configs,
163 connection_factory=connection_factory,
164 nbio=nbio,
165 workflow=workflow,
166 on_done=on_done)
167
168 def _get_write_buffer_size(self) -> int:
169 """
170 :returns: Current size of output data buffered by the transport
171 :rtype: int
172 """
173 return self._transport.get_write_buffer_size() # type: ignore
174
175
176 class _Timeout:
177 """Represents a timeout"""
178
179 __slots__ = (
180 'deadline',
181 'callback',
182 )
183
184 def __init__(self, deadline: float, callback: Callable[[], None]):
185 """
186 :param float deadline: timer expiration as non-negative epoch number
187 :param callable callback: callback to call when timeout expires
188 :raises ValueError, TypeError:
189 """
190
191 if deadline < 0:
192 raise ValueError(
193 'deadline must be non-negative epoch number, but got %r' %
194 (deadline,))
195
196 if not callable(callback):
197 raise TypeError(
198 'callback must be a callable, but got {!r}'.format(callback))
199
200 self.deadline = deadline
201 self.callback: Optional[Callable[[], None]] = callback
202
203 def __eq__(self, other: object) -> bool:
204 """NOTE: not supporting sort stability"""
205 if isinstance(other, _Timeout):
206 return self.deadline == other.deadline
207 return NotImplemented
208
209 def __ne__(self, other: object) -> bool:
210 """NOTE: not supporting sort stability"""
211 result = self.__eq__(other)
212 if result is not NotImplemented:
213 return not result
214 return NotImplemented
215
216 def __lt__(self, other: object) -> bool:
217 """NOTE: not supporting sort stability"""
218 if isinstance(other, _Timeout):
219 return self.deadline < other.deadline
220 return NotImplemented
221
222 def __gt__(self, other: object) -> bool:
223 """NOTE: not supporting sort stability"""
224 if isinstance(other, _Timeout):
225 return self.deadline > other.deadline
226 return NotImplemented
227
228 def __le__(self, other: object) -> bool:
229 """NOTE: not supporting sort stability"""
230 if isinstance(other, _Timeout):
231 return self.deadline <= other.deadline
232 return NotImplemented
233
234 def __ge__(self, other: object) -> bool:
235 """NOTE: not supporting sort stability"""
236 if isinstance(other, _Timeout):
237 return self.deadline >= other.deadline
238 return NotImplemented
239
240
241 class _Timer:
242 """Manage timeouts for use in ioloop"""
243
244 # Cancellation count threshold for triggering garbage collection of
245 # cancelled timers
246 _GC_CANCELLATION_THRESHOLD = 1024
247
248 def __init__(self) -> None:
249 self._timeout_heap: Optional[list[_Timeout]] = []
250 # Number of canceled timeouts on heap; for scheduling garbage
251 # collection of canceled timeouts
252 self._num_cancellations = 0
253
254 def close(self) -> None:
255 """Release resources. Don't use the `_Timer` instance after closing
256 it
257 """
258 # Eliminate potential reference cycles to aid garbage-collection
259 if self._timeout_heap is not None:
260 for timeout in self._timeout_heap:
261 timeout.callback = None
262 self._timeout_heap = None
263
264 def call_later(self, delay: float, callback: Callable[[],
265 None]) -> _Timeout:
266 """Schedule a one-shot timeout given delay seconds.
267
268 NOTE: you may cancel the timer before dispatch of the callback. Timer
269 Manager cancels the timer upon dispatch of the callback.
270
271 :param float delay: Non-negative number of seconds from now until
272 expiration
273 :param callable callback: The callback method, having the signature
274 `callback()`
275
276 :rtype: _Timeout
277 :raises ValueError, TypeError
278
279 """
280 if self._timeout_heap is None:
281 raise ValueError("Timeout closed before call")
282
283 if delay < 0:
284 raise ValueError(
285 'call_later: delay must be non-negative, but got {!r}'.format(
286 delay))
287
288 now = pika.compat.time_now()
289
290 timeout = _Timeout(now + delay, callback)
291
292 heapq.heappush(self._timeout_heap, timeout)
293
294 LOGGER.debug(
295 'call_later: added timeout %r with deadline=%r and '
296 'callback=%r; now=%s; delay=%s', timeout, timeout.deadline,
297 timeout.callback, now, delay)
298
299 return timeout
300
301 def remove_timeout(self, timeout: _Timeout) -> None:
302 """Cancel the timeout
303
304 :param _Timeout timeout: The timer to cancel
305
306 """
307 # NOTE removing from the heap is difficult, so we just deactivate the
308 # timeout and garbage-collect it at a later time; see discussion
309 # in https://docs.python.org/library/heapq.html
310 if timeout.callback is None:
311 LOGGER.debug(
312 'remove_timeout: timeout was already removed or called %r',
313 timeout)
314 else:
315 LOGGER.debug(
316 'remove_timeout: removing timeout %r with deadline=%r '
317 'and callback=%r', timeout, timeout.deadline, timeout.callback)
318 timeout.callback = None
319 self._num_cancellations += 1
320
321 def get_remaining_interval(self) -> Optional[float]:
322 """Get the interval to the next timeout expiration
323
324 :returns: non-negative number of seconds until next timer expiration;
325 None if there are no timers
326 :rtype: float
327
328 """
329 if self._timeout_heap:
330 now = pika.compat.time_now()
331 interval = max(0, self._timeout_heap[0].deadline - now)
332 else:
333 interval = None
334
335 return interval
336
337 def process_timeouts(self) -> None:
338 """Process pending timeouts, invoking callbacks for those whose time has
339 come
340
341 """
342 if self._timeout_heap:
343 now = pika.compat.time_now()
344
345 # Remove ready timeouts from the heap now to prevent IO starvation
346 # from timeouts added during callback processing
347 ready_timeouts = []
348
349 while self._timeout_heap and self._timeout_heap[0].deadline <= now:
350 timeout = heapq.heappop(self._timeout_heap)
351 if timeout.callback is not None:
352 ready_timeouts.append(timeout)
353 else:
354 self._num_cancellations -= 1
355
356 # Invoke ready timeout callbacks
357 for timeout in ready_timeouts:
358 if timeout.callback is None:
359 # Must have been canceled from a prior callback
360 self._num_cancellations -= 1
361 continue
362
363 timeout.callback()
364 timeout.callback = None
365
366 # Garbage-collect canceled timeouts if they exceed threshold
367 if (self._num_cancellations >= self._GC_CANCELLATION_THRESHOLD and
368 self._num_cancellations > (len(self._timeout_heap) >> 1)):
369 self._num_cancellations = 0
370 self._timeout_heap = [
371 t for t in self._timeout_heap if t.callback is not None
372 ]
373 heapq.heapify(self._timeout_heap)
374
375
376 class PollEvents:
377 """Event flags for I/O"""
378
379 # Use epoll's constants to keep life easy
380 READ = getattr(select, 'POLLIN', 0x01) # available for read
381 WRITE = getattr(select, 'POLLOUT', 0x04) # available for write
382 ERROR = getattr(select, 'POLLERR', 0x08) # error on associated fd
383 HANGUP = getattr(select, 'POLLHUP', 0x10) # hangup on associated fd
384
385
386 class IOLoop(AbstractSelectorIOLoop):
387 """I/O loop implementation that picks a suitable poller (`select`,
388 `poll`, `epoll`, `kqueue`) to use based on platform.
389
390 Implements the
391 `pika.adapters.utils.selector_ioloop_adapter.AbstractSelectorIOLoop`
392 interface.
393
394 """
395 # READ/WRITE/ERROR per `AbstractSelectorIOLoop` requirements
396 READ = PollEvents.READ # pyright: ignore[reportIncompatibleMethodOverride, reportAssignmentType]
397 WRITE = PollEvents.WRITE # pyright: ignore[reportIncompatibleMethodOverride, reportAssignmentType]
398 ERROR = PollEvents.ERROR # pyright: ignore[reportIncompatibleMethodOverride, reportAssignmentType]
399
400 def __init__(self) -> None:
401 self._timer = _Timer()
402
403 # Callbacks requested via `add_callback`
404 self._callbacks: collections.deque[Callable[
405 [], None]] = collections.deque()
406
407 self._poller = self._get_poller(self._get_remaining_interval,
408 self.process_timeouts)
409
410 def close(self) -> None:
411 """Release IOLoop's resources.
412
413 `IOLoop.close` is intended to be called by the application or test code
414 only after `IOLoop.start()` returns. After calling `close()`, no other
415 interaction with the closed instance of `IOLoop` should be performed.
416
417 """
418 if self._callbacks is not None:
419 self._poller.close()
420 self._timer.close()
421 # Set _callbacks to empty list rather than None so that race from
422 # another thread calling add_callback_threadsafe() won't result in
423 # AttributeError
424 self._callbacks = [] # type: ignore
425
426 @staticmethod
427 def _get_poller(get_wait_seconds: Callable[[], Optional[float]],
428 process_timeouts: Callable[[], None]) -> _PollerBase:
429 """Determine the best poller to use for this environment and instantiate
430 it.
431
432 :param get_wait_seconds: Function for getting the maximum number of
433 seconds to wait for IO for use by the poller
434 :param process_timeouts: Function for processing timeouts for use by the
435 poller
436
437 :returns: The instantiated poller instance supporting `_PollerBase` API
438 :rtype: object
439 """
440
441 poller = None
442
443 kwargs: POLLER_PARAMS = {
444 "get_wait_seconds": get_wait_seconds,
445 "process_timeouts": process_timeouts
446 }
447
448 if hasattr(select, 'epoll'):
449 if not SELECT_TYPE or SELECT_TYPE == 'epoll':
450 LOGGER.debug('Using EPollPoller')
451 poller = EPollPoller(**kwargs)
452
453 if not poller and hasattr(select, 'kqueue'):
454 if not SELECT_TYPE or SELECT_TYPE == 'kqueue':
455 LOGGER.debug('Using KQueuePoller')
456 poller = KQueuePoller(**kwargs)
457
458 if (not poller and hasattr(select, 'poll') and
459 hasattr(select.poll(), 'modify')): # pylint: disable=E1101
460 if not SELECT_TYPE or SELECT_TYPE == 'poll':
461 LOGGER.debug('Using PollPoller')
462 poller = PollPoller(**kwargs)
463
464 if not poller:
465 LOGGER.debug('Using SelectPoller')
466 poller = SelectPoller(**kwargs)
467
468 return poller
469
470 def call_later(self, delay: float, callback: Callable[[],
471 None]) -> _Timeout:
472 """Add the callback to the IOLoop timer to be called after delay seconds
473 from the time of call on best-effort basis. Returns a handle to the
474 timeout.
475
476 :param float delay: The number of seconds to wait to call callback
477 :param callable callback: The callback method
478 :returns: handle to the created timeout that may be passed to
479 `remove_timeout()`
480 :rtype: object
481
482 """
483 return self._timer.call_later(delay, callback)
484
485 def remove_timeout(self, timeout_handle: _Timeout) -> None:
486 """Remove a timeout
487
488 :param timeout_handle: Handle of timeout to remove
489
490 """
491 self._timer.remove_timeout(timeout_handle)
492
493 def add_callback_threadsafe(self, callback: Callable[[], None]) -> None:
494 """Requests a call to the given function as soon as possible in the
495 context of this IOLoop's thread.
496
497 NOTE: This is the only thread-safe method in IOLoop. All other
498 manipulations of IOLoop must be performed from the IOLoop's thread.
499
500 For example, a thread may request a call to the `stop` method of an
501 ioloop that is running in a different thread via
502 `ioloop.add_callback_threadsafe(ioloop.stop)`
503
504 :param callable callback: The callback method
505
506 """
507 if not callable(callback):
508 raise TypeError(
509 'callback must be a callable, but got {!r}'.format(callback))
510
511 # NOTE: `deque.append` is atomic
512 self._callbacks.append(callback)
513
514 # Wake up the IOLoop which may be running in another thread
515 self._poller.wake_threadsafe()
516
517 LOGGER.debug('add_callback_threadsafe: added callback=%r', callback)
518
519 # To satisfy `AbstractSelectorIOLoop` requirement
520 add_callback = add_callback_threadsafe
521
522 def process_timeouts(self) -> None:
523 """[Extension] Process pending callbacks and timeouts, invoking those
524 whose time has come. Internal use only.
525
526 """
527 # Avoid I/O starvation by postponing new callbacks to the next iteration
528 for _ in range(len(self._callbacks)):
529 callback = self._callbacks.popleft()
530 LOGGER.debug('process_timeouts: invoking callback=%r', callback)
531 callback()
532
533 self._timer.process_timeouts()
534
535 def _get_remaining_interval(self) -> Optional[float]:
536 """Get the remaining interval to the next callback or timeout
537 expiration.
538
539 :returns: non-negative number of seconds until next callback or timer
540 expiration; None if there are no callbacks and timers
541 :rtype: float
542
543 """
544 if self._callbacks:
545 return 0
546
547 return self._timer.get_remaining_interval()
548
549 def add_handler(self, fd: int, handler: Callable[[int, int], None],
550 events: int) -> None:
551 """Start watching the given file descriptor for events
552
553 :param int fd: The file descriptor
554 :param callable handler: When requested event(s) occur,
555 `handler(fd, events)` will be called.
556 :param int events: The event mask using READ, WRITE, ERROR.
557
558 """
559 self._poller.add_handler(fd, handler, events)
560
561 def update_handler(self, fd: int, events: int) -> None:
562 """Changes the events we watch for
563
564 :param int fd: The file descriptor
565 :param int events: The event mask using READ, WRITE, ERROR
566
567 """
568 self._poller.update_handler(fd, events)
569
570 def remove_handler(self, fd: int) -> None:
571 """Stop watching the given file descriptor for events
572
573 :param int fd: The file descriptor
574
575 """
576 self._poller.remove_handler(fd)
577
578 def start(self) -> None:
579 """[API] Start the main poller loop. It will loop until requested to
580 exit. See `IOLoop.stop`.
581
582 """
583 self._poller.start()
584
585 def stop(self) -> None:
586 """[API] Request exit from the ioloop. The loop is NOT guaranteed to
587 stop before this method returns.
588
589 To invoke `stop()` safely from a thread other than this IOLoop's thread,
590 call it via `add_callback_threadsafe`; e.g.,
591
592 `ioloop.add_callback_threadsafe(ioloop.stop)`
593
594 """
595 self._poller.stop()
596
597 def activate_poller(self) -> None:
598 """[Extension] Activate the poller
599
600 """
601 self._poller.activate_poller()
602
603 def deactivate_poller(self) -> None:
604 """[Extension] Deactivate the poller
605
606 """
607 self._poller.deactivate_poller()
608
609 def poll(self) -> None:
610 """[Extension] Wait for events of interest on registered file
611 descriptors until an event of interest occurs or next timer deadline or
612 `_PollerBase._MAX_POLL_TIMEOUT`, whichever is sooner, and dispatch the
613 corresponding event handlers.
614
615 """
616 self._poller.poll()
617
618
619 class _PollerBase(pika.compat.AbstractBase): # type: ignore # pylint: disable=R0902
620 """Base class for select-based IOLoop implementations"""
621
622 # Drop out of the poll loop every _MAX_POLL_TIMEOUT secs as a worst case;
623 # this is only a backstop value; we will run timeouts when they are
624 # scheduled.
625 _MAX_POLL_TIMEOUT = 5
626
627 # if the poller uses MS override with 1000
628 POLL_TIMEOUT_MULT = 1
629
630 def __init__(self, get_wait_seconds: Callable[[], Optional[float]],
631 process_timeouts: Callable[[], None]) -> None:
632 """
633 :param get_wait_seconds: Function for getting the maximum number of
634 seconds to wait for IO for use by the poller
635 :param process_timeouts: Function for processing timeouts for use by the
636 poller
637
638 """
639 self._get_wait_seconds = get_wait_seconds
640 self._process_timeouts = process_timeouts
641
642 # We guard access to the waking file descriptors to avoid races from
643 # closing them while another thread is calling our `wake()` method.
644 self._waking_mutex = threading.Lock()
645
646 # fd-to-handler function mappings
647 self._fd_handlers: Dict[int, Callable[..., None]] = dict()
648
649 # event-to-fdset mappings
650 self._fd_events: Dict[int, Set[int]] = {
651 PollEvents.READ: set(),
652 PollEvents.WRITE: set(),
653 PollEvents.ERROR: set()
654 }
655
656 self._processing_fd_event_map: Dict[int, int] = {}
657
658 # Reentrancy tracker of the `start` method
659 self._running = False
660
661 self._stopping = False
662
663 # Create ioloop-interrupt socket pair and register read handler.
664 self._r_interrupt, self._w_interrupt = self._get_interrupt_pair()
665 self.add_handler(self._r_interrupt.fileno(), self._read_interrupt,
666 PollEvents.READ)
667
668 def close(self) -> None:
669 """Release poller's resources.
670
671 `close()` is intended to be called after the poller's `start()` method
672 returns. After calling `close()`, no other interaction with the closed
673 poller instance should be performed.
674
675 """
676 # Unregister and close ioloop-interrupt socket pair; mutual exclusion is
677 # necessary to avoid race condition with `wake_threadsafe` executing in
678 # another thread's context
679 assert not self._running, 'Cannot call close() before start() unwinds.'
680
681 with self._waking_mutex:
682 if self._w_interrupt is not None:
683 self.remove_handler(self._r_interrupt.fileno()) # pylint: disable=E1101 # type: ignore
684 self._r_interrupt.close(
685 ) # pyright: ignore[reportOptionalMemberAccess]
686 self._r_interrupt = None # type: ignore
687 self._w_interrupt.close()
688 self._w_interrupt = None # type: ignore
689
690 self.deactivate_poller()
691
692 self._fd_handlers = None # type: ignore
693 self._fd_events = None # type: ignore
694 self._processing_fd_event_map = None # type: ignore
695
696 def wake_threadsafe(self) -> None:
697 """Wake up the poller as soon as possible. As the name indicates, this
698 method is thread-safe.
699
700 """
701 with self._waking_mutex:
702 if self._w_interrupt is None:
703 return
704
705 try:
706 # Send byte to interrupt the poll loop, use send() instead of
707 # os.write for Windows compatibility
708 self._w_interrupt.send(b'X')
709 except pika.compat.SOCKET_ERROR as err:
710 if err.errno not in _TRY_IO_AGAIN_SOCK_ERROR_CODES:
711 raise
712 except Exception as err:
713 # There's nothing sensible to do here, we'll exit the interrupt
714 # loop after POLL_TIMEOUT secs in worst case anyway.
715 LOGGER.warning("Failed to send interrupt to poller: %s", err)
716 raise
717
718 def _get_max_wait(self) -> float:
719 """Get the interval to the next timeout event, or a default interval
720
721 :returns: maximum number of self.POLL_TIMEOUT_MULT-scaled time units
722 to wait for IO events
723 :rtype: float
724
725 """
726 delay = self._get_wait_seconds()
727 if delay is None:
728 delay = self._MAX_POLL_TIMEOUT
729 else:
730 delay = min(delay, self._MAX_POLL_TIMEOUT)
731
732 return delay * self.POLL_TIMEOUT_MULT
733
734 def add_handler(self, fileno: int, handler: Callable[..., None],
735 events: int) -> None:
736 """Add a new fileno to the set to be monitored
737
738 :param int fileno: The file descriptor
739 :param callable handler: What is called when an event happens
740 :param int events: The event mask using READ, WRITE, ERROR
741
742 """
743 self._fd_handlers[fileno] = handler
744 self._set_handler_events(fileno, events)
745
746 # Inform the derived class
747 self._register_fd(fileno, events)
748
749 def update_handler(self, fileno: int, events: int) -> None:
750 """Set the events to the current events
751
752 :param int fileno: The file descriptor
753 :param int events: The event mask using READ, WRITE, ERROR
754
755 """
756 # Record the change
757 events_cleared, events_set = self._set_handler_events(fileno, events)
758
759 # Inform the derived class
760 self._modify_fd_events(fileno,
761 events=events,
762 events_to_clear=events_cleared,
763 events_to_set=events_set)
764
765 def remove_handler(self, fileno: int) -> None:
766 """Remove a file descriptor from the set
767
768 :param int fileno: The file descriptor
769
770 """
771 try:
772 del self._processing_fd_event_map[fileno]
773 except KeyError:
774 pass
775
776 events_cleared, _ = self._set_handler_events(fileno, 0)
777 del self._fd_handlers[fileno]
778
779 # Inform the derived class
780 self._unregister_fd(fileno, events_to_clear=events_cleared)
781
782 def _set_handler_events(self, fileno: int, events: int) -> Tuple[int, int]:
783 """Set the handler's events to the given events; internal to
784 `_PollerBase`.
785
786 :param int fileno: The file descriptor
787 :param int events: The event mask (READ, WRITE, ERROR)
788
789 :returns: a 2-tuple (events_cleared, events_set)
790 :rtype: tuple
791 """
792 events_cleared = 0
793 events_set = 0
794
795 for evt in (PollEvents.READ, PollEvents.WRITE, PollEvents.ERROR):
796 if events & evt:
797 if fileno not in self._fd_events[evt]:
798 self._fd_events[evt].add(fileno)
799 events_set |= evt
800 else:
801 if fileno in self._fd_events[evt]:
802 self._fd_events[evt].discard(fileno)
803 events_cleared |= evt
804
805 return events_cleared, events_set
806
807 def activate_poller(self) -> None:
808 """Activate the poller
809
810 """
811 # Activate the underlying poller and register current events
812 self._init_poller()
813 fd_to_events: Dict[int, int] = collections.defaultdict(int)
814 for event, file_descriptors in self._fd_events.items():
815 for fileno in file_descriptors:
816 fd_to_events[fileno] |= event
817
818 for fileno, events in fd_to_events.items():
819 self._register_fd(fileno, events)
820
821 def deactivate_poller(self) -> None:
822 """Deactivate the poller
823
824 """
825 self._uninit_poller()
826
827 def start(self) -> None:
828 """Start the main poller loop. It will loop until requested to exit.
829 This method is not reentrant and will raise an error if called
830 recursively (pika/pika#1095)
831
832 :raises: RuntimeError
833
834 """
835 if self._running:
836 raise RuntimeError('IOLoop is not reentrant and is already running')
837
838 LOGGER.debug('Entering IOLoop')
839 self._running = True
840 self.activate_poller()
841
842 try:
843 # Run event loop
844 while not self._stopping:
845 self.poll()
846 self._process_timeouts()
847 finally:
848 try:
849 LOGGER.debug('Deactivating poller')
850 self.deactivate_poller()
851 finally:
852 self._stopping = False
853 self._running = False
854
855 def stop(self) -> None:
856 """Request exit from the ioloop. The loop is NOT guaranteed to stop
857 before this method returns.
858
859 """
860 LOGGER.debug('Stopping IOLoop')
861 self._stopping = True
862 self.wake_threadsafe()
863
864 @abc.abstractmethod
865 def poll(self) -> None:
866 """Wait for events on interested filedescriptors.
867 """
868 raise NotImplementedError
869
870 @abc.abstractmethod
871 def _init_poller(self) -> None:
872 """Notify the implementation to allocate the poller resource"""
873 raise NotImplementedError
874
875 @abc.abstractmethod
876 def _uninit_poller(self) -> None:
877 """Notify the implementation to release the poller resource"""
878 raise NotImplementedError
879
880 @abc.abstractmethod
881 def _register_fd(self, fileno: int, events: int) -> None:
882 """The base class invokes this method to notify the implementation to
883 register the file descriptor with the polling object. The request must
884 be ignored if the poller is not activated.
885
886 :param int fileno: The file descriptor
887 :param int events: The event mask (READ, WRITE, ERROR)
888 """
889 raise NotImplementedError
890
891 @abc.abstractmethod
892 def _modify_fd_events(self, fileno: int, events: int, events_to_clear: int,
893 events_to_set: int) -> None:
894 """The base class invokes this method to notify the implementation to
895 modify an already registered file descriptor. The request must be
896 ignored if the poller is not activated.
897
898 :param int fileno: The file descriptor
899 :param int events: absolute events (READ, WRITE, ERROR)
900 :param int events_to_clear: The events to clear (READ, WRITE, ERROR)
901 :param int events_to_set: The events to set (READ, WRITE, ERROR)
902 """
903 raise NotImplementedError
904
905 @abc.abstractmethod
906 def _unregister_fd(self, fileno: int, events_to_clear: int) -> None:
907 """The base class invokes this method to notify the implementation to
908 unregister the file descriptor being tracked by the polling object. The
909 request must be ignored if the poller is not activated.
910
911 :param int fileno: The file descriptor
912 :param int events_to_clear: The events to clear (READ, WRITE, ERROR)
913 """
914 raise NotImplementedError
915
916 def _dispatch_fd_events(self, fd_event_map: Dict[int, int]) -> None:
917 """ Helper to dispatch callbacks for file descriptors that received
918 events.
919
920 Before doing so we re-calculate the event mask based on what is
921 currently set in case it has been changed under our feet by a
922 previous callback. We also take a store a refernce to the
923 fd_event_map so that we can detect removal of an
924 fileno during processing of another callback and not generate
925 spurious callbacks on it.
926
927 :param dict fd_event_map: Map of fds to events received on them.
928 """
929 # Reset the prior map; if the call is nested, this will suppress the
930 # remaining dispatch in the earlier call.
931 self._processing_fd_event_map.clear()
932
933 self._processing_fd_event_map = fd_event_map
934
935 for fileno in list(fd_event_map.keys()):
936 if fileno not in fd_event_map:
937 # the fileno has been removed from the map under our feet.
938 continue
939
940 events = fd_event_map[fileno]
941 for evt in [PollEvents.READ, PollEvents.WRITE, PollEvents.ERROR]:
942 if fileno not in self._fd_events[evt]:
943 events &= ~evt
944
945 if events:
946 handler = self._fd_handlers[fileno]
947 handler(fileno, events)
948
949 @staticmethod
950 def _get_interrupt_pair() -> Tuple[socket.socket, socket.socket]:
951 """ Use a socketpair to be able to interrupt the ioloop if called
952 from another thread. Socketpair() is not supported on some OS (Win)
953 so use a pair of simple TCP sockets instead. The sockets will be
954 closed and garbage collected by python when the ioloop itself is.
955 """
956 return pika.compat.nonblocking_socketpair()
957
958 def _read_interrupt(self, _interrupt_fd: int, _events: int) -> None:
959 """ Read the interrupt byte(s). We ignore the event mask as we can ony
960 get here if there's data to be read on our fd.
961
962 :param int _interrupt_fd: (unused) The file descriptor to read from
963 :param int _events: (unused) The events generated for this fd
964 """
965 try:
966 # NOTE Use recv instead of os.read for windows compatibility
967 self._r_interrupt.recv(512) # pylint: disable=E1101 # type: ignore
968 except pika.compat.SOCKET_ERROR as err:
969 if err.errno not in _TRY_IO_AGAIN_SOCK_ERROR_CODES:
970 raise
971
972
973 class SelectPoller(_PollerBase):
974 """Default behavior is to use Select since it's the widest supported and has
975 all of the methods we need for child classes as well. One should only need
976 to override the update_handler and start methods for additional types.
977
978 """
979 # if the poller uses MS specify 1000
980 POLL_TIMEOUT_MULT = 1
981
982 def poll(self) -> None:
983 """Wait for events of interest on registered file descriptors until an
984 event of interest occurs or next timer deadline or _MAX_POLL_TIMEOUT,
985 whichever is sooner, and dispatch the corresponding event handlers.
986
987 """
988 while True:
989 try:
990 if (self._fd_events[PollEvents.READ] or
991 self._fd_events[PollEvents.WRITE] or
992 self._fd_events[PollEvents.ERROR]):
993 read, write, error = select.select(
994 self._fd_events[PollEvents.READ],
995 self._fd_events[PollEvents.WRITE],
996 self._fd_events[PollEvents.ERROR], self._get_max_wait())
997 else:
998 # NOTE When called without any FDs, select fails on
999 # Windows with error 10022, 'An invalid argument was
1000 # supplied'.
1001 time.sleep(self._get_max_wait())
1002 read, write, error = [], [], []
1003 break
1004 except _SELECT_ERRORS as error:
1005 if _is_resumable(error):
1006 continue
1007 else:
1008 raise
1009
1010 # Build an event bit mask for each fileno we've received an event for
1011 fd_event_map: Dict[int, int] = collections.defaultdict(int)
1012 for fd_set, evt in zip(
1013 (read, write, error),
1014 (PollEvents.READ, PollEvents.WRITE, PollEvents.ERROR)):
1015 for fileno in fd_set:
1016 fd_event_map[fileno] |= evt
1017
1018 self._dispatch_fd_events(fd_event_map)
1019
1020 def _init_poller(self) -> None:
1021 """Notify the implementation to allocate the poller resource"""
1022 # It's a no op in SelectPoller
1023
1024 def _uninit_poller(self) -> None:
1025 """Notify the implementation to release the poller resource"""
1026 # It's a no op in SelectPoller
1027
1028 def _register_fd(self, fileno: int, events: int) -> None:
1029 """The base class invokes this method to notify the implementation to
1030 register the file descriptor with the polling object. The request must
1031 be ignored if the poller is not activated.
1032
1033 :param int fileno: The file descriptor
1034 :param int events: The event mask using READ, WRITE, ERROR
1035 """
1036 # It's a no op in SelectPoller
1037
1038 def _modify_fd_events(self, fileno: int, events: int, events_to_clear: int,
1039 events_to_set: int) -> None:
1040 """The base class invokes this method to notify the implementation to
1041 modify an already registered file descriptor. The request must be
1042 ignored if the poller is not activated.
1043
1044 :param int fileno: The file descriptor
1045 :param int events: absolute events (READ, WRITE, ERROR)
1046 :param int events_to_clear: The events to clear (READ, WRITE, ERROR)
1047 :param int events_to_set: The events to set (READ, WRITE, ERROR)
1048 """
1049 # It's a no op in SelectPoller
1050
1051 def _unregister_fd(self, fileno: int, events_to_clear: int) -> None:
1052 """The base class invokes this method to notify the implementation to
1053 unregister the file descriptor being tracked by the polling object. The
1054 request must be ignored if the poller is not activated.
1055
1056 :param int fileno: The file descriptor
1057 :param int events_to_clear: The events to clear (READ, WRITE, ERROR)
1058 """
1059 # It's a no op in SelectPoller
1060
1061
1062 class KQueuePoller(_PollerBase):
1063 # pylint: disable=E1101
1064 """KQueuePoller works on BSD based systems and is faster than select"""
1065
1066 def __init__(self, get_wait_seconds: Callable[[], Optional[float]],
1067 process_timeouts: Callable[[], None]):
1068 """Create an instance of the KQueuePoller
1069 """
1070 self._kqueue = None
1071 super().__init__(get_wait_seconds, process_timeouts)
1072
1073 @staticmethod
1074 def _map_event(kevent: Any) -> int:
1075 """return the event type associated with a kevent object
1076
1077 :param kevent kevent: a kevent object as returned by kqueue.control()
1078
1079 """
1080 mask = 0
1081 if kevent.filter == select.KQ_FILTER_READ: # type: ignore
1082 mask = PollEvents.READ
1083 elif kevent.filter == select.KQ_FILTER_WRITE: # type: ignore
1084 mask = PollEvents.WRITE
1085 if kevent.flags & select.KQ_EV_EOF: # type: ignore
1086 # May be set when the peer reader disconnects. We don't check
1087 # KQ_EV_EOF for KQ_FILTER_READ because in that case it may be
1088 # set before the remaining data is consumed from sockbuf.
1089 mask |= PollEvents.ERROR
1090 elif kevent.flags & select.KQ_EV_ERROR: # type: ignore
1091 mask = PollEvents.ERROR
1092 else:
1093 LOGGER.critical('Unexpected kevent: %s', kevent)
1094
1095 return mask
1096
1097 def poll(self) -> None:
1098 """Wait for events of interest on registered file descriptors until an
1099 event of interest occurs or next timer deadline or _MAX_POLL_TIMEOUT,
1100 whichever is sooner, and dispatch the corresponding event handlers.
1101
1102 """
1103 while True:
1104 try:
1105 kevents = self._kqueue.control( # type: ignore[attr-defined]
1106 None, 1000, self._get_max_wait())
1107 break
1108 except _SELECT_ERRORS as error:
1109 if _is_resumable(error):
1110 continue
1111 else:
1112 raise
1113
1114 fd_event_map: Dict[int, int] = collections.defaultdict(int)
1115 for event in kevents:
1116 fd_event_map[event.ident] |= self._map_event(event)
1117
1118 self._dispatch_fd_events(fd_event_map)
1119
1120 def _init_poller(self) -> None:
1121 """Notify the implementation to allocate the poller resource"""
1122 assert self._kqueue is None
1123
1124 self._kqueue = select.kqueue() # type: ignore
1125
1126 def _uninit_poller(self) -> None:
1127 """Notify the implementation to release the poller resource"""
1128 if self._kqueue is not None:
1129 self._kqueue.close()
1130 self._kqueue = None
1131
1132 def _register_fd(self, fileno: int, events: int) -> None:
1133 """The base class invokes this method to notify the implementation to
1134 register the file descriptor with the polling object. The request must
1135 be ignored if the poller is not activated.
1136
1137 :param int fileno: The file descriptor
1138 :param int events: The event mask using READ, WRITE, ERROR
1139 """
1140 self._modify_fd_events(fileno,
1141 events=events,
1142 events_to_clear=0,
1143 events_to_set=events)
1144
1145 def _modify_fd_events(self, fileno: int, events: int, events_to_clear: int,
1146 events_to_set: int) -> None:
1147 """The base class invokes this method to notify the implementation to
1148 modify an already registered file descriptor. The request must be
1149 ignored if the poller is not activated.
1150
1151 :param int fileno: The file descriptor
1152 :param int events: absolute events (READ, WRITE, ERROR)
1153 :param int events_to_clear: The events to clear (READ, WRITE, ERROR)
1154 :param int events_to_set: The events to set (READ, WRITE, ERROR)
1155 """
1156 if self._kqueue is None:
1157 return
1158
1159 kevents = list()
1160
1161 if events_to_clear & PollEvents.READ:
1162 kevents.append(
1163 select.kevent( # pyright: ignore[reportAttributeAccessIssue]
1164 fileno,
1165 filter=select.
1166 KQ_FILTER_READ, # pyright: ignore[reportAttributeAccessIssue]
1167 flags=select.KQ_EV_DELETE)
1168 ) # pyright: ignore[reportAttributeAccessIssue]
1169 if events_to_set & PollEvents.READ: # pyright: ignore[reportAttributeAccessIssue]
1170 kevents.append(
1171 select.kevent( # pyright: ignore[reportAttributeAccessIssue]
1172 fileno,
1173 filter=select.
1174 KQ_FILTER_READ, # pyright: ignore[reportAttributeAccessIssue]
1175 flags=select.KQ_EV_ADD)
1176 ) # pyright: ignore[reportAttributeAccessIssue]
1177 if events_to_clear & PollEvents.WRITE:
1178 kevents.append(
1179 select.kevent( # pyright: ignore[reportAttributeAccessIssue]
1180 fileno,
1181 filter=select.
1182 KQ_FILTER_WRITE, # pyright: ignore[reportAttributeAccessIssue]
1183 flags=select.KQ_EV_DELETE)
1184 ) # pyright: ignore[reportAttributeAccessIssue]
1185 if events_to_set & PollEvents.WRITE:
1186 kevents.append(
1187 select.kevent( # pyright: ignore[reportAttributeAccessIssue]
1188 fileno,
1189 filter=select.
1190 KQ_FILTER_WRITE, # pyright: ignore[reportAttributeAccessIssue]
1191 flags=select.KQ_EV_ADD)
1192 ) # pyright: ignore[reportAttributeAccessIssue]
1193
1194 self._kqueue.control(kevents, 0)
1195
1196 def _unregister_fd(self, fileno: int, events_to_clear: int) -> None:
1197 """The base class invokes this method to notify the implementation to
1198 unregister the file descriptor being tracked by the polling object. The
1199 request must be ignored if the poller is not activated.
1200
1201 :param int fileno: The file descriptor
1202 :param int events_to_clear: The events to clear (READ, WRITE, ERROR)
1203 """
1204 self._modify_fd_events(fileno,
1205 events=0,
1206 events_to_clear=events_to_clear,
1207 events_to_set=0)
1208
1209
1210 class PollPoller(_PollerBase):
1211 """Poll works on Linux and can have better performance than EPoll in
1212 certain scenarios. Both are faster than select.
1213
1214 """
1215 POLL_TIMEOUT_MULT = 1000
1216
1217 def __init__(self, get_wait_seconds: Callable[[], Optional[float]],
1218 process_timeouts: Callable[[], None]):
1219 """Create an instance of the KQueuePoller
1220
1221 """
1222 self._poll: Any = None
1223 super().__init__(get_wait_seconds, process_timeouts)
1224
1225 @staticmethod
1226 def _create_poller() -> Any:
1227 """
1228 :rtype: `select.poll`
1229 """
1230 return getattr(select, 'poll')() # pylint: disable=E1101
1231
1232 def poll(self) -> None:
1233 """Wait for events of interest on registered file descriptors until an
1234 event of interest occurs or next timer deadline or _MAX_POLL_TIMEOUT,
1235 whichever is sooner, and dispatch the corresponding event handlers.
1236
1237 """
1238 while True:
1239 try:
1240 events = self._poll.poll(self._get_max_wait())
1241 break
1242 except _SELECT_ERRORS as error:
1243 if _is_resumable(error):
1244 continue
1245 else:
1246 raise
1247
1248 fd_event_map: Dict[int, int] = collections.defaultdict(int)
1249 for fileno, event in events:
1250 # NOTE: On OS X, when poll() sets POLLHUP, it's mutually-exclusive with
1251 # POLLOUT and it doesn't seem to set POLLERR along with POLLHUP when
1252 # socket connection fails, for example. So, we need to at least add
1253 # POLLERR when we see POLLHUP
1254 if (event & PollEvents.HANGUP) and pika.compat.ON_OSX:
1255 event |= PollEvents.ERROR
1256
1257 fd_event_map[fileno] |= event
1258
1259 self._dispatch_fd_events(fd_event_map)
1260
1261 def _init_poller(self) -> None:
1262 """Notify the implementation to allocate the poller resource"""
1263 assert self._poll is None
1264
1265 self._poll = self._create_poller()
1266
1267 def _uninit_poller(self) -> None:
1268 """Notify the implementation to release the poller resource"""
1269 if self._poll is not None:
1270 if hasattr(self._poll, "close"):
1271 self._poll.close(
1272 ) # pyright: ignore[reportAttributeAccessIssue]
1273
1274 self._poll = None
1275
1276 def _register_fd(self, fileno: int, events: int) -> None:
1277 """The base class invokes this method to notify the implementation to
1278 register the file descriptor with the polling object. The request must
1279 be ignored if the poller is not activated.
1280
1281 :param int fileno: The file descriptor
1282 :param int events: The event mask using READ, WRITE, ERROR
1283 """
1284 if self._poll is not None:
1285 self._poll.register(fileno, events)
1286
1287 def _modify_fd_events(self, fileno: int, events: int, events_to_clear: int,
1288 events_to_set: int) -> None:
1289 """The base class invokes this method to notify the implementation to
1290 modify an already registered file descriptor. The request must be
1291 ignored if the poller is not activated.
1292
1293 :param int fileno: The file descriptor
1294 :param int events: absolute events (READ, WRITE, ERROR)
1295 :param int events_to_clear: The events to clear (READ, WRITE, ERROR)
1296 :param int events_to_set: The events to set (READ, WRITE, ERROR)
1297 """
1298 if self._poll is not None:
1299 self._poll.modify(fileno, events)
1300
1301 def _unregister_fd(self, fileno: int, events_to_clear: int) -> None:
1302 """The base class invokes this method to notify the implementation to
1303 unregister the file descriptor being tracked by the polling object. The
1304 request must be ignored if the poller is not activated.
1305
1306 :param int fileno: The file descriptor
1307 :param int events_to_clear: The events to clear (READ, WRITE, ERROR)
1308 """
1309 if self._poll is not None:
1310 self._poll.unregister(fileno)
1311
1312
1313 class EPollPoller(PollPoller):
1314 """EPoll works on Linux and can have better performance than Poll in
1315 certain scenarios. Both are faster than select.
1316
1317 """
1318 POLL_TIMEOUT_MULT = 1
1319
1320 @staticmethod
1321 def _create_poller() -> Any:
1322 """
1323 :rtype: `select.poll`
1324 """
1325 return getattr(select, 'epoll')() # pylint: disable=E1101