| 1 |
"""Use pika with the Gevent IOLoop.""" |
| 2 |
from __future__ import annotations |
| 3 |
|
| 4 |
import functools |
| 5 |
import logging |
| 6 |
import os |
| 7 |
import threading |
| 8 |
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union, TYPE_CHECKING |
| 9 |
|
| 10 |
import gevent._interfaces # type: ignore[import-untyped] |
| 11 |
|
| 12 |
import queue |
| 13 |
|
| 14 |
import gevent |
| 15 |
import gevent.hub # type: ignore[import-untyped] |
| 16 |
import gevent.socket # type: ignore[import-untyped] |
| 17 |
|
| 18 |
import pika.compat |
| 19 |
from pika.adapters.base_connection import BaseConnection |
| 20 |
from pika.adapters.utils.io_services_utils import check_callback_arg |
| 21 |
from pika.adapters.utils.nbio_interface import ( |
| 22 |
AbstractIOReference, |
| 23 |
AbstractIOServices, |
| 24 |
) |
| 25 |
from pika.adapters.utils.selector_ioloop_adapter import ( |
| 26 |
AbstractSelectorIOLoop, |
| 27 |
SelectorIOServicesAdapter, |
| 28 |
) |
| 29 |
|
| 30 |
if TYPE_CHECKING: |
| 31 |
from pika import connection |
| 32 |
from pika.adapters.utils import connection_workflow, nbio_interface |
| 33 |
|
| 34 |
LOGGER = logging.getLogger(__name__) |
| 35 |
|
| 36 |
|
| 37 |
class GeventConnection(BaseConnection): |
| 38 |
"""Implementation of pika's ``BaseConnection``. |
| 39 |
|
| 40 |
An async selector-based connection which integrates with Gevent. |
| 41 |
""" |
| 42 |
|
| 43 |
def __init__(self, |
| 44 |
parameters: Optional[connection.Parameters] = None, |
| 45 |
on_open_callback: Optional[Callable[[connection.Connection], |
| 46 |
None]] = None, |
| 47 |
on_open_error_callback: Optional[Callable[ |
| 48 |
[connection.Connection, BaseException], None]] = None, |
| 49 |
on_close_callback: Optional[Callable[ |
| 50 |
[connection.Connection, BaseException], None]] = None, |
| 51 |
custom_ioloop: Optional[Union[gevent._interfaces.ILoop, |
| 52 |
AbstractIOServices]] = None, |
| 53 |
internal_connection_workflow: bool = True) -> None: |
| 54 |
"""Create a new GeventConnection instance and connect to RabbitMQ on |
| 55 |
Gevent's event-loop. |
| 56 |
|
| 57 |
:param pika.connection.Parameters|None parameters: The connection |
| 58 |
parameters |
| 59 |
:param callable|None on_open_callback: The method to call when the |
| 60 |
connection is open |
| 61 |
:param callable|None on_open_error_callback: Called if the connection |
| 62 |
can't be established or connection establishment is interrupted by |
| 63 |
`Connection.close()`: |
| 64 |
on_open_error_callback(Connection, exception) |
| 65 |
:param callable|None on_close_callback: Called when a previously fully |
| 66 |
open connection is closed: |
| 67 |
`on_close_callback(Connection, exception)`, where `exception` is |
| 68 |
either an instance of `exceptions.ConnectionClosed` if closed by |
| 69 |
user or broker or exception of another type that describes the |
| 70 |
cause of connection failure |
| 71 |
:param gevent._interfaces.ILoop|nbio_interface.AbstractIOServices|None |
| 72 |
custom_ioloop: Use a custom Gevent ILoop. |
| 73 |
:param bool internal_connection_workflow: True for autonomous connection |
| 74 |
establishment which is default; False for externally-managed |
| 75 |
connection workflow via the `create_connection()` factory |
| 76 |
""" |
| 77 |
if pika.compat.ON_WINDOWS: |
| 78 |
raise RuntimeError('GeventConnection is not supported on Windows.') |
| 79 |
|
| 80 |
custom_ioloop = (custom_ioloop or |
| 81 |
_GeventSelectorIOLoop(gevent.get_hub())) |
| 82 |
|
| 83 |
if isinstance(custom_ioloop, AbstractIOServices): |
| 84 |
nbio = custom_ioloop |
| 85 |
else: |
| 86 |
nbio = _GeventSelectorIOServicesAdapter(custom_ioloop) |
| 87 |
|
| 88 |
super().__init__( |
| 89 |
parameters, |
| 90 |
on_open_callback, |
| 91 |
on_open_error_callback, |
| 92 |
on_close_callback, |
| 93 |
nbio, |
| 94 |
internal_connection_workflow=internal_connection_workflow) |
| 95 |
|
| 96 |
@classmethod |
| 97 |
def create_connection( |
| 98 |
cls, |
| 99 |
connection_configs: Sequence[connection.Parameters], |
| 100 |
on_done: Callable[[ |
| 101 |
Union[connection.Connection, |
| 102 |
connection_workflow.AMQPConnectorException] |
| 103 |
], None], |
| 104 |
custom_ioloop: Optional[gevent._interfaces.ILoop] = None, |
| 105 |
workflow: Optional[ |
| 106 |
connection_workflow.AbstractAMQPConnectionWorkflow] = None |
| 107 |
) -> connection_workflow.AbstractAMQPConnectionWorkflow: |
| 108 |
"""Implement |
| 109 |
:py:classmethod::`pika.adapters.BaseConnection.create_connection()`. |
| 110 |
""" |
| 111 |
custom_ioloop = (custom_ioloop or |
| 112 |
_GeventSelectorIOLoop(gevent.get_hub())) |
| 113 |
|
| 114 |
nbio = _GeventSelectorIOServicesAdapter(custom_ioloop) |
| 115 |
|
| 116 |
def connection_factory(params): |
| 117 |
"""Connection factory.""" |
| 118 |
if params is None: |
| 119 |
raise ValueError('Expected pika.connection.Parameters ' |
| 120 |
'instance, but got None in params arg.') |
| 121 |
return cls(parameters=params, |
| 122 |
custom_ioloop=nbio, |
| 123 |
internal_connection_workflow=False) |
| 124 |
|
| 125 |
return cls._start_connection_workflow( |
| 126 |
connection_configs=connection_configs, |
| 127 |
connection_factory=connection_factory, |
| 128 |
nbio=nbio, |
| 129 |
workflow=workflow, |
| 130 |
on_done=on_done) |
| 131 |
|
| 132 |
|
| 133 |
class _TSafeCallbackQueue: |
| 134 |
"""Dispatch callbacks from any thread to be executed in the main thread |
| 135 |
efficiently with IO events. |
| 136 |
""" |
| 137 |
|
| 138 |
def __init__(self) -> None: |
| 139 |
""" |
| 140 |
:param _GeventSelectorIOLoop loop: IO loop to add callbacks to. |
| 141 |
""" |
| 142 |
# Thread-safe, blocking queue. |
| 143 |
self._queue: queue.Queue[Callable[[], None]] = queue.Queue() |
| 144 |
# PIPE to trigger an event when the queue is ready. |
| 145 |
self._read_fd, self._write_fd = os.pipe() |
| 146 |
# Lock around writes to the PIPE in case some platform/implementation |
| 147 |
# requires this. |
| 148 |
self._write_lock = threading.RLock() |
| 149 |
|
| 150 |
@property |
| 151 |
def fd(self) -> int: |
| 152 |
"""The file-descriptor to register for READ events in the IO loop.""" |
| 153 |
return self._read_fd |
| 154 |
|
| 155 |
def add_callback_threadsafe(self, callback: Callable[[], None]) -> None: |
| 156 |
"""Add an item to the queue from any thread. The configured handler |
| 157 |
will be invoked with the item in the main thread. |
| 158 |
|
| 159 |
:param item: Object to add to the queue. |
| 160 |
""" |
| 161 |
self._queue.put(callback) |
| 162 |
with self._write_lock: |
| 163 |
# The value written is not important. |
| 164 |
os.write(self._write_fd, b'\xFF') |
| 165 |
|
| 166 |
def run_next_callback(self) -> None: |
| 167 |
"""Invoke the next callback from the queue. |
| 168 |
|
| 169 |
MUST run in the main thread. If no callback was added to the queue, |
| 170 |
this will block the IO loop. |
| 171 |
|
| 172 |
Performs a blocking READ on the pipe so must only be called when the |
| 173 |
pipe is ready for reading. |
| 174 |
""" |
| 175 |
try: |
| 176 |
callback = self._queue.get_nowait() |
| 177 |
except queue.Empty: |
| 178 |
# Should never happen. |
| 179 |
LOGGER.warning("Callback queue was empty.") |
| 180 |
else: |
| 181 |
# Read the byte from the pipe so the event doesn't re-fire. |
| 182 |
os.read(self._read_fd, 1) |
| 183 |
callback() |
| 184 |
|
| 185 |
|
| 186 |
class _GeventSelectorIOLoop(AbstractSelectorIOLoop): |
| 187 |
"""Implementation of `AbstractSelectorIOLoop` using the Gevent event loop. |
| 188 |
|
| 189 |
Required by implementations of `SelectorIOServicesAdapter`. |
| 190 |
""" |
| 191 |
# Gevent's READ and WRITE masks are defined as 1 and 2 respectively. No |
| 192 |
# ERROR mask is defined. |
| 193 |
# See https://www.gevent.org/api/gevent.hub.html#gevent._interfaces.ILoop.io |
| 194 |
READ = 1 # pyright: ignore[reportAssignmentType, reportIncompatibleMethodOverride] |
| 195 |
WRITE = 2 # pyright: ignore[reportAssignmentType, reportIncompatibleMethodOverride] |
| 196 |
ERROR = 0 # pyright: ignore[reportAssignmentType, reportIncompatibleMethodOverride] |
| 197 |
|
| 198 |
def __init__(self, gevent_hub: Optional[gevent.hub.Hub] = None) -> None: |
| 199 |
""" |
| 200 |
:param gevent._interfaces.ILoop gevent_loop: |
| 201 |
""" |
| 202 |
self._hub = gevent_hub or gevent.get_hub() |
| 203 |
self._io_watchers_by_fd: Dict[int, Any] = {} |
| 204 |
# Used to start/stop the loop. |
| 205 |
self._waiter = gevent.hub.Waiter() |
| 206 |
|
| 207 |
# For adding callbacks from other threads. See `add_callback(..)`. |
| 208 |
self._callback_queue = _TSafeCallbackQueue() |
| 209 |
|
| 210 |
def run_callback_in_main_thread(fd, events): |
| 211 |
"""Swallow the fd and events arguments.""" |
| 212 |
del fd |
| 213 |
del events |
| 214 |
self._callback_queue.run_next_callback() |
| 215 |
|
| 216 |
self.add_handler(self._callback_queue.fd, run_callback_in_main_thread, |
| 217 |
self.READ) |
| 218 |
|
| 219 |
def close(self) -> None: |
| 220 |
"""Release the loop's resources.""" |
| 221 |
self._hub.loop.destroy() # pyright: ignore[reportOptionalMemberAccess] |
| 222 |
self._hub = None |
| 223 |
|
| 224 |
def start(self) -> None: |
| 225 |
"""Run the I/O loop. It will loop until requested to exit. See `stop()`. |
| 226 |
""" |
| 227 |
LOGGER.debug("Passing control to Gevent's IOLoop") |
| 228 |
self._waiter.get() # Block until 'stop()' is called. |
| 229 |
|
| 230 |
LOGGER.debug("Control was passed back from Gevent's IOLoop") |
| 231 |
self._waiter.clear() |
| 232 |
|
| 233 |
def stop(self) -> None: |
| 234 |
"""Request exit from the ioloop. The loop is NOT guaranteed to |
| 235 |
stop before this method returns. |
| 236 |
|
| 237 |
To invoke `stop()` safely from a thread other than this IOLoop's thread, |
| 238 |
call it via `add_callback_threadsafe`; e.g., |
| 239 |
|
| 240 |
`ioloop.add_callback(ioloop.stop)` |
| 241 |
""" |
| 242 |
self._waiter.switch(None) |
| 243 |
|
| 244 |
def add_callback(self, callback: Callable[[], None]) -> None: |
| 245 |
"""Requests a call to the given function as soon as possible in the |
| 246 |
context of this IOLoop's thread. |
| 247 |
|
| 248 |
NOTE: This is the only thread-safe method in IOLoop. All other |
| 249 |
manipulations of IOLoop must be performed from the IOLoop's thread. |
| 250 |
|
| 251 |
For example, a thread may request a call to the `stop` method of an |
| 252 |
ioloop that is running in a different thread via |
| 253 |
`ioloop.add_callback_threadsafe(ioloop.stop)` |
| 254 |
|
| 255 |
:param callable callback: The callback method |
| 256 |
""" |
| 257 |
if gevent.get_hub() == self._hub: |
| 258 |
# We're in the main thread; just add the callback. |
| 259 |
LOGGER.debug("Adding callback from main thread") |
| 260 |
self._hub.loop.run_callback( |
| 261 |
callback) # pyright: ignore[reportOptionalMemberAccess] |
| 262 |
else: |
| 263 |
# This isn't the main thread and Gevent's hub/loop don't provide |
| 264 |
# any thread-safety so enqueue the callback for it to be registered |
| 265 |
# in the main thread. |
| 266 |
LOGGER.debug("Adding callback from another thread") |
| 267 |
callback = functools.partial( |
| 268 |
self._hub.loop.run_callback, callback |
| 269 |
) # pyright: ignore[reportAssignmentType, reportOptionalMemberAccess] |
| 270 |
self._callback_queue.add_callback_threadsafe(callback) |
| 271 |
|
| 272 |
def call_later(self, delay: float, callback: Callable[[], None]) -> Any: |
| 273 |
"""Add the callback to the IOLoop timer to be called after delay seconds |
| 274 |
from the time of call on best-effort basis. Returns a handle to the |
| 275 |
timeout. |
| 276 |
|
| 277 |
:param float delay: The number of seconds to wait to call callback |
| 278 |
:param callable callback: The callback method |
| 279 |
:returns: handle to the created timeout that may be passed to |
| 280 |
`remove_timeout()` |
| 281 |
:rtype: object |
| 282 |
""" |
| 283 |
timer = self._hub.loop.timer( |
| 284 |
delay) # pyright: ignore[reportOptionalMemberAccess] |
| 285 |
timer.start(callback) |
| 286 |
return timer |
| 287 |
|
| 288 |
def remove_timeout(self, timeout_handle: Any) -> None: |
| 289 |
"""Remove a timeout |
| 290 |
|
| 291 |
:param timeout_handle: Handle of timeout to remove |
| 292 |
""" |
| 293 |
timeout_handle.close() |
| 294 |
|
| 295 |
def add_handler(self, fd: int, handler: Callable[[int, int], None], |
| 296 |
events: int) -> None: |
| 297 |
"""Start watching the given file descriptor for events |
| 298 |
|
| 299 |
:param int fd: The file descriptor |
| 300 |
:param callable handler: When requested event(s) occur, |
| 301 |
`handler(fd, events)` will be called. |
| 302 |
:param int events: The event mask (READ|WRITE) |
| 303 |
""" |
| 304 |
io_watcher = self._hub.loop.io( |
| 305 |
fd, events) # pyright: ignore[reportOptionalMemberAccess] |
| 306 |
self._io_watchers_by_fd[fd] = io_watcher |
| 307 |
io_watcher.start(handler, fd, events) |
| 308 |
|
| 309 |
def update_handler(self, fd: int, events: int) -> None: |
| 310 |
"""Change the events being watched for. |
| 311 |
|
| 312 |
:param int fd: The file descriptor |
| 313 |
:param int events: The new event mask (READ|WRITE) |
| 314 |
""" |
| 315 |
io_watcher = self._io_watchers_by_fd[fd] |
| 316 |
# Save callback from the original watcher. The close the old watcher |
| 317 |
# and create a new one using the saved callback and the new events. |
| 318 |
callback = io_watcher.callback |
| 319 |
io_watcher.close() |
| 320 |
del self._io_watchers_by_fd[fd] |
| 321 |
self.add_handler(fd, callback, events) |
| 322 |
|
| 323 |
def remove_handler(self, fd: int) -> None: |
| 324 |
"""Stop watching the given file descriptor for events |
| 325 |
|
| 326 |
:param int fd: The file descriptor |
| 327 |
""" |
| 328 |
io_watcher = self._io_watchers_by_fd[fd] |
| 329 |
io_watcher.close() |
| 330 |
del self._io_watchers_by_fd[fd] |
| 331 |
|
| 332 |
|
| 333 |
class _GeventSelectorIOServicesAdapter(SelectorIOServicesAdapter): |
| 334 |
"""SelectorIOServicesAdapter implementation using Gevent's DNS resolver.""" |
| 335 |
|
| 336 |
def getaddrinfo(self, |
| 337 |
host: str, |
| 338 |
port: int, |
| 339 |
on_done: Callable[..., None], |
| 340 |
family: int = 0, |
| 341 |
socktype: int = 0, |
| 342 |
proto: int = 0, |
| 343 |
flags: int = 0) -> nbio_interface.AbstractIOReference: |
| 344 |
"""Implement :py:meth:`.nbio_interface.AbstractIOServices.getaddrinfo()`. |
| 345 |
""" |
| 346 |
resolver = _GeventAddressResolver(native_loop=self._loop, |
| 347 |
host=host, |
| 348 |
port=port, |
| 349 |
family=family, |
| 350 |
socktype=socktype, |
| 351 |
proto=proto, |
| 352 |
flags=flags, |
| 353 |
on_done=on_done) |
| 354 |
resolver.start() |
| 355 |
# Return needs an implementation of `AbstractIOReference`. |
| 356 |
return _GeventIOLoopIOHandle(resolver) |
| 357 |
|
| 358 |
|
| 359 |
class _GeventIOLoopIOHandle(AbstractIOReference): |
| 360 |
"""Implement `AbstractIOReference`. |
| 361 |
|
| 362 |
Only used to wrap the _GeventAddressResolver. |
| 363 |
""" |
| 364 |
|
| 365 |
def __init__(self, subject: Any) -> None: |
| 366 |
""" |
| 367 |
:param subject: subject of the reference containing a `cancel()` method |
| 368 |
""" |
| 369 |
self._cancel = subject.cancel |
| 370 |
|
| 371 |
def cancel(self) -> bool: |
| 372 |
"""Cancel pending operation |
| 373 |
|
| 374 |
:returns: False if was already done or cancelled; True otherwise |
| 375 |
:rtype: bool |
| 376 |
""" |
| 377 |
return self._cancel() |
| 378 |
|
| 379 |
|
| 380 |
class _GeventAddressResolver: |
| 381 |
"""Performs getaddrinfo asynchronously Gevent's configured resolver in a |
| 382 |
separate greenlet and invoking the provided callback with the result. |
| 383 |
|
| 384 |
See: https://www.gevent.org/dns.html |
| 385 |
""" |
| 386 |
__slots__ = ( |
| 387 |
'_loop', |
| 388 |
'_on_done', |
| 389 |
'_greenlet', |
| 390 |
# getaddrinfo(..) args: |
| 391 |
'_ga_host', |
| 392 |
'_ga_port', |
| 393 |
'_ga_family', |
| 394 |
'_ga_socktype', |
| 395 |
'_ga_proto', |
| 396 |
'_ga_flags') |
| 397 |
|
| 398 |
def __init__(self, native_loop: AbstractSelectorIOLoop, host: str, |
| 399 |
port: int, family: int, socktype: int, proto: int, flags: int, |
| 400 |
on_done: Callable[..., None]) -> None: |
| 401 |
"""Initialize the `_GeventAddressResolver`. |
| 402 |
|
| 403 |
:param AbstractSelectorIOLoop native_loop: |
| 404 |
:param host: `see socket.getaddrinfo()` |
| 405 |
:param port: `see socket.getaddrinfo()` |
| 406 |
:param family: `see socket.getaddrinfo()` |
| 407 |
:param socktype: `see socket.getaddrinfo()` |
| 408 |
:param proto: `see socket.getaddrinfo()` |
| 409 |
:param flags: `see socket.getaddrinfo()` |
| 410 |
:param on_done: on_done(records|BaseException) callback for reporting |
| 411 |
result from the given I/O loop. The single arg will be either an |
| 412 |
exception object (check for `BaseException`) in case of failure or |
| 413 |
the result returned by `socket.getaddrinfo()`. |
| 414 |
""" |
| 415 |
check_callback_arg(on_done, 'on_done') |
| 416 |
|
| 417 |
self._loop: Optional[AbstractSelectorIOLoop] = native_loop |
| 418 |
self._on_done: Optional[Callable[..., None]] = on_done |
| 419 |
# Reference to the greenlet performing `getaddrinfo`. |
| 420 |
self._greenlet = None |
| 421 |
# getaddrinfo(..) args. |
| 422 |
self._ga_host = host |
| 423 |
self._ga_port = port |
| 424 |
self._ga_family = family |
| 425 |
self._ga_socktype = socktype |
| 426 |
self._ga_proto = proto |
| 427 |
self._ga_flags = flags |
| 428 |
|
| 429 |
def start(self) -> None: |
| 430 |
"""Start an asynchronous getaddrinfo invocation.""" |
| 431 |
if self._greenlet is None: |
| 432 |
self._greenlet = gevent.spawn_raw(self._resolve) |
| 433 |
else: |
| 434 |
LOGGER.warning("_GeventAddressResolver already started") |
| 435 |
|
| 436 |
def cancel(self) -> bool: |
| 437 |
"""Cancel the pending resolver.""" |
| 438 |
changed = False |
| 439 |
|
| 440 |
if self._greenlet is not None: |
| 441 |
changed = True |
| 442 |
self._stop_greenlet() |
| 443 |
|
| 444 |
self._cleanup() |
| 445 |
return changed |
| 446 |
|
| 447 |
def _cleanup(self) -> None: |
| 448 |
"""Stop the resolver and release any resources.""" |
| 449 |
self._stop_greenlet() |
| 450 |
self._loop = None |
| 451 |
self._on_done = None |
| 452 |
|
| 453 |
def _stop_greenlet(self) -> None: |
| 454 |
"""Stop the greenlet performing getaddrinfo if running. |
| 455 |
|
| 456 |
Otherwise, this is a no-op. |
| 457 |
""" |
| 458 |
if self._greenlet is not None: |
| 459 |
gevent.kill(self._greenlet) |
| 460 |
self._greenlet = None |
| 461 |
|
| 462 |
def _resolve(self) -> None: |
| 463 |
"""Call `getaddrinfo()` and return result via user's callback |
| 464 |
function on the configured IO loop. |
| 465 |
""" |
| 466 |
try: |
| 467 |
result = gevent.socket.getaddrinfo(self._ga_host, self._ga_port, |
| 468 |
self._ga_family, |
| 469 |
self._ga_socktype, |
| 470 |
self._ga_proto, self._ga_flags) |
| 471 |
except Exception as exc: # pylint: disable=broad-except |
| 472 |
LOGGER.error('Address resolution failed: %r', exc) |
| 473 |
result = exc |
| 474 |
|
| 475 |
callback = functools.partial(self._dispatch_callback, result) |
| 476 |
self._loop.add_callback(callback) # type: ignore |
| 477 |
|
| 478 |
def _dispatch_callback( |
| 479 |
self, result: Union[List[Tuple[Any, Any, int, str, |
| 480 |
Union[Tuple[str, int], Tuple[str, int, |
| 481 |
int, int], |
| 482 |
Tuple[int, bytes]]]], Exception] |
| 483 |
) -> None: |
| 484 |
"""Invoke the configured completion callback and any subsequent cleanup. |
| 485 |
|
| 486 |
:param result: result from getaddrinfo, or the exception if raised. |
| 487 |
""" |
| 488 |
try: |
| 489 |
LOGGER.debug( |
| 490 |
'Invoking async getaddrinfo() completion callback; host=%r', |
| 491 |
self._ga_host) |
| 492 |
self._on_done(result) # type: ignore |
| 493 |
finally: |
| 494 |
self._cleanup() |