| 1 |
"""Implements `AMQPConnectionWorkflow` - the default workflow of performing |
| 2 |
multiple TCP/[SSL]/AMQP connection attempts with timeouts and retries until one |
| 3 |
succeeds or all attempts fail. |
| 4 |
|
| 5 |
Defines the interface `AbstractAMQPConnectionWorkflow` that facilitates |
| 6 |
implementing custom connection workflows. |
| 7 |
|
| 8 |
""" |
| 9 |
from __future__ import annotations |
| 10 |
|
| 11 |
import functools |
| 12 |
import logging |
| 13 |
import socket |
| 14 |
from typing import Any, Callable, Iterator, List, Optional, Sequence, TYPE_CHECKING, Tuple, Union |
| 15 |
|
| 16 |
import pika.compat |
| 17 |
import pika.connection |
| 18 |
import pika.exceptions |
| 19 |
import pika.tcp_socket_opts |
| 20 |
from pika import __version__ |
| 21 |
|
| 22 |
if TYPE_CHECKING: |
| 23 |
from pika.adapters.utils import nbio_interface |
| 24 |
|
| 25 |
ADDRESS_INFO = Tuple[socket.AddressFamily, socket.SocketKind, int, str, |
| 26 |
Union[Tuple[str, int], Tuple[str, int, int, int], |
| 27 |
Tuple[int, bytes]]] |
| 28 |
|
| 29 |
_LOG = logging.getLogger(__name__) |
| 30 |
|
| 31 |
|
| 32 |
class AMQPConnectorException(Exception): |
| 33 |
"""Base exception for this module""" |
| 34 |
|
| 35 |
|
| 36 |
class AMQPConnectorStackTimeout(AMQPConnectorException): |
| 37 |
"""Overall TCP/[SSL]/AMQP stack connection attempt timed out.""" |
| 38 |
|
| 39 |
|
| 40 |
class AMQPConnectorAborted(AMQPConnectorException): |
| 41 |
"""Asynchronous request was aborted""" |
| 42 |
|
| 43 |
|
| 44 |
class AMQPConnectorWrongState(AMQPConnectorException): |
| 45 |
"""AMQPConnector operation requested in wrong state, such as aborting after |
| 46 |
completion was reported. |
| 47 |
""" |
| 48 |
|
| 49 |
|
| 50 |
class AMQPConnectorPhaseErrorBase(AMQPConnectorException): |
| 51 |
"""Wrapper for exception that occurred during a particular bring-up phase. |
| 52 |
|
| 53 |
""" |
| 54 |
|
| 55 |
def __init__(self, exception: BaseException, *args: Any): |
| 56 |
""" |
| 57 |
|
| 58 |
:param BaseException exception: error that occurred while waiting for a |
| 59 |
subclass-specific protocol bring-up phase to complete. |
| 60 |
:param args: args for parent class |
| 61 |
""" |
| 62 |
super().__init__(*args) |
| 63 |
self.exception = exception |
| 64 |
|
| 65 |
def __repr__(self): |
| 66 |
return f'{self.__class__.__name__}: {self.exception!r}' |
| 67 |
|
| 68 |
|
| 69 |
class AMQPConnectorSocketConnectError(AMQPConnectorPhaseErrorBase): |
| 70 |
"""Error connecting TCP socket to remote peer""" |
| 71 |
|
| 72 |
|
| 73 |
class AMQPConnectorTransportSetupError(AMQPConnectorPhaseErrorBase): |
| 74 |
"""Error setting up transport after TCP connected but before AMQP handshake. |
| 75 |
|
| 76 |
""" |
| 77 |
|
| 78 |
|
| 79 |
class AMQPConnectorAMQPHandshakeError(AMQPConnectorPhaseErrorBase): |
| 80 |
"""Error during AMQP handshake""" |
| 81 |
|
| 82 |
|
| 83 |
class AMQPConnectionWorkflowAborted(AMQPConnectorException): |
| 84 |
"""AMQP Connection workflow was aborted.""" |
| 85 |
|
| 86 |
|
| 87 |
class AMQPConnectionWorkflowWrongState(AMQPConnectorException): |
| 88 |
"""AMQP Connection Workflow operation requested in wrong state, such as |
| 89 |
aborting after completion was reported. |
| 90 |
""" |
| 91 |
|
| 92 |
|
| 93 |
class AMQPConnectionWorkflowFailed(AMQPConnectorException): |
| 94 |
"""Indicates that AMQP connection workflow failed. |
| 95 |
|
| 96 |
""" |
| 97 |
|
| 98 |
def __init__(self, exceptions: Sequence[BaseException], *args: Any): |
| 99 |
""" |
| 100 |
:param sequence exceptions: Exceptions that occurred during the |
| 101 |
workflow. |
| 102 |
:param args: args to pass to base class |
| 103 |
|
| 104 |
""" |
| 105 |
super().__init__(*args) |
| 106 |
self.exceptions = tuple(exceptions) |
| 107 |
|
| 108 |
def __repr__(self) -> str: |
| 109 |
return ('{}: {} exceptions in all; last exception - {!r}; first ' |
| 110 |
'exception - {!r}').format( |
| 111 |
self.__class__.__name__, len(self.exceptions), |
| 112 |
self.exceptions[-1], |
| 113 |
self.exceptions[0] if len(self.exceptions) > 1 else None) |
| 114 |
|
| 115 |
|
| 116 |
class AMQPConnector: |
| 117 |
"""Performs a single TCP/[SSL]/AMQP connection workflow. |
| 118 |
|
| 119 |
""" |
| 120 |
|
| 121 |
_STATE_INIT = 0 # start() hasn't been called yet |
| 122 |
_STATE_TCP = 1 # TCP/IP connection establishment |
| 123 |
_STATE_TRANSPORT = 2 # [SSL] and transport linkup |
| 124 |
_STATE_AMQP = 3 # AMQP connection handshake |
| 125 |
_STATE_TIMEOUT = 4 # overall TCP/[SSL]/AMQP timeout |
| 126 |
_STATE_ABORTING = 5 # abort() called - aborting workflow |
| 127 |
_STATE_DONE = 6 # result reported to client |
| 128 |
|
| 129 |
def __init__(self, |
| 130 |
conn_factory: Callable[[pika.connection.Parameters], |
| 131 |
nbio_interface.AbstractStreamProtocol], |
| 132 |
nbio: nbio_interface.AbstractIOServices): |
| 133 |
""" |
| 134 |
|
| 135 |
:param callable conn_factory: A function that takes |
| 136 |
`pika.connection.Parameters` as its only arg and returns a brand new |
| 137 |
`pika.connection.Connection`-based adapter instance each time it is |
| 138 |
called. The factory must instantiate the connection with |
| 139 |
`internal_connection_workflow=False`. |
| 140 |
:param pika.adapters.utils.nbio_interface.AbstractIOServices nbio: |
| 141 |
|
| 142 |
""" |
| 143 |
self._conn_factory: Callable[ |
| 144 |
[pika.connection.Parameters], |
| 145 |
nbio_interface.AbstractStreamProtocol] = conn_factory |
| 146 |
self._nbio: nbio_interface.AbstractIOServices = nbio |
| 147 |
self._addr_record: Optional[Tuple] = None |
| 148 |
self._conn_params: pika.connection.Parameters = None # type: ignore |
| 149 |
self._on_done: Callable[ |
| 150 |
[Union[pika.connection.Connection, BaseException]], |
| 151 |
None] = None # type: ignore # will be provided via start() |
| 152 |
# TCP connection timeout |
| 153 |
# pylint: disable=C0301 |
| 154 |
self._tcp_timeout_ref: Optional[ |
| 155 |
nbio_interface.AbstractTimerReference] = None |
| 156 |
# Overall TCP/[SSL]/AMQP timeout |
| 157 |
self._stack_timeout_ref: Optional[ |
| 158 |
nbio_interface.AbstractTimerReference] = None |
| 159 |
# Current task |
| 160 |
self._task_ref: Optional[nbio_interface.AbstractIOReference] = None |
| 161 |
self._sock: socket.socket = None # type: ignore |
| 162 |
self._amqp_conn: Optional[pika.connection.Connection] = None |
| 163 |
|
| 164 |
self._state = self._STATE_INIT |
| 165 |
|
| 166 |
def start( |
| 167 |
self, addr_record: Tuple, conn_params: pika.connection.Parameters, |
| 168 |
on_done: Callable[[Union[pika.connection.Connection, BaseException]], |
| 169 |
None] |
| 170 |
) -> None: |
| 171 |
"""Asynchronously perform a single TCP/[SSL]/AMQP connection attempt. |
| 172 |
|
| 173 |
:param tuple addr_record: a single resolved address record compatible |
| 174 |
with `socket.getaddrinfo()` format. |
| 175 |
:param pika.connection.Parameters conn_params: |
| 176 |
:param callable on_done: Function to call upon completion of the |
| 177 |
workflow: `on_done(pika.connection.Connection | BaseException)`. If |
| 178 |
exception, it's going to be one of the following: |
| 179 |
`AMQPConnectorSocketConnectError` |
| 180 |
`AMQPConnectorTransportSetupError` |
| 181 |
`AMQPConnectorAMQPHandshakeError` |
| 182 |
`AMQPConnectorAborted` |
| 183 |
|
| 184 |
""" |
| 185 |
if self._state != self._STATE_INIT: |
| 186 |
raise AMQPConnectorWrongState( |
| 187 |
f'Already in progress or finished; state={self._state}') |
| 188 |
|
| 189 |
self._addr_record = addr_record |
| 190 |
self._conn_params = conn_params |
| 191 |
self._on_done = on_done |
| 192 |
|
| 193 |
# Create socket and initiate TCP/IP connection |
| 194 |
self._state = self._STATE_TCP |
| 195 |
self._sock = socket.socket(*self._addr_record[:3]) |
| 196 |
self._sock.setsockopt(pika.compat.SOL_TCP, socket.TCP_NODELAY, 1) |
| 197 |
pika.tcp_socket_opts.set_sock_opts(self._conn_params.tcp_options, |
| 198 |
self._sock) |
| 199 |
self._sock.setblocking(False) |
| 200 |
|
| 201 |
addr = self._addr_record[4] |
| 202 |
_LOG.info('Pika version %s connecting to %r', __version__, addr) |
| 203 |
self._task_ref = self._nbio.connect_socket( |
| 204 |
self._sock, addr, on_done=self._on_tcp_connection_done) |
| 205 |
|
| 206 |
# Start socket connection timeout timer |
| 207 |
self._tcp_timeout_ref = None |
| 208 |
if self._conn_params.socket_timeout is not None: |
| 209 |
self._tcp_timeout_ref = self._nbio.call_later( |
| 210 |
self._conn_params.socket_timeout, |
| 211 |
self._on_tcp_connection_timeout) |
| 212 |
|
| 213 |
# Start overall TCP/[SSL]/AMQP stack connection timeout timer |
| 214 |
self._stack_timeout_ref = None |
| 215 |
if self._conn_params.stack_timeout is not None: |
| 216 |
self._stack_timeout_ref = self._nbio.call_later( |
| 217 |
self._conn_params.stack_timeout, self._on_overall_timeout) |
| 218 |
|
| 219 |
def abort(self) -> None: |
| 220 |
"""Abort the workflow asynchronously. The completion callback will be |
| 221 |
called with an instance of AMQPConnectorAborted. |
| 222 |
|
| 223 |
NOTE: we can't cancel/close synchronously because aborting pika |
| 224 |
Connection and its transport requires an asynchronous operation. |
| 225 |
|
| 226 |
:raises AMQPConnectorWrongState: If called after completion has been |
| 227 |
reported or the workflow not started yet. |
| 228 |
""" |
| 229 |
if self._state == self._STATE_INIT: |
| 230 |
raise AMQPConnectorWrongState('Cannot abort before starting.') |
| 231 |
|
| 232 |
if self._state == self._STATE_DONE: |
| 233 |
raise AMQPConnectorWrongState( |
| 234 |
'Cannot abort after completion was reported') |
| 235 |
|
| 236 |
self._state = self._STATE_ABORTING |
| 237 |
self._deactivate() |
| 238 |
|
| 239 |
_LOG.info( |
| 240 |
'AMQPConnector: beginning client-initiated asynchronous ' |
| 241 |
'abort; %r/%s', self._conn_params.host, self._addr_record) |
| 242 |
|
| 243 |
if self._amqp_conn is None: |
| 244 |
_LOG.debug('AMQPConnector.abort(): no connection, so just ' |
| 245 |
'scheduling completion report via I/O loop.') |
| 246 |
self._nbio.add_callback_threadsafe( |
| 247 |
functools.partial(self._report_completion_and_cleanup, |
| 248 |
AMQPConnectorAborted())) |
| 249 |
else: |
| 250 |
if not self._amqp_conn.is_closing: |
| 251 |
# Initiate close of AMQP connection and wait for asynchronous |
| 252 |
# callback from the Connection instance before reporting |
| 253 |
# completion to client |
| 254 |
_LOG.debug('AMQPConnector.abort(): closing Connection.') |
| 255 |
self._amqp_conn.close( |
| 256 |
320, 'Client-initiated abort of AMQP Connection Workflow.') |
| 257 |
else: |
| 258 |
# It's already closing, must be due to our timeout processing, |
| 259 |
# so we'll just piggy back on the callback it registered |
| 260 |
_LOG.debug('AMQPConnector.abort(): closing of Connection was ' |
| 261 |
'already initiated.') |
| 262 |
assert self._state == self._STATE_TIMEOUT, \ |
| 263 |
('Connection is closing, but not in TIMEOUT state; state={}' |
| 264 |
.format(self._state)) |
| 265 |
|
| 266 |
def _close(self) -> None: |
| 267 |
"""Cancel asynchronous tasks and clean up to assist garbage collection. |
| 268 |
|
| 269 |
Transition to STATE_DONE. |
| 270 |
|
| 271 |
""" |
| 272 |
self._deactivate() |
| 273 |
|
| 274 |
if self._sock is not None: |
| 275 |
self._sock.close() |
| 276 |
self._sock = None # type: ignore |
| 277 |
|
| 278 |
self._conn_factory = None # type: ignore |
| 279 |
self._nbio = None # type: ignore |
| 280 |
self._addr_record = None |
| 281 |
self._on_done = None # type: ignore |
| 282 |
|
| 283 |
self._state = self._STATE_DONE |
| 284 |
|
| 285 |
def _deactivate(self) -> None: |
| 286 |
"""Cancel asynchronous tasks. |
| 287 |
|
| 288 |
""" |
| 289 |
# NOTE: self._amqp_conn requires special handling as it doesn't support |
| 290 |
# synchronous closing. We special-case it elsewhere in the code where |
| 291 |
# needed. |
| 292 |
assert self._amqp_conn is None, \ |
| 293 |
'_deactivate called with self._amqp_conn not None; state={}'.format( |
| 294 |
self._state) |
| 295 |
|
| 296 |
if self._tcp_timeout_ref is not None: |
| 297 |
self._tcp_timeout_ref.cancel() |
| 298 |
self._tcp_timeout_ref = None |
| 299 |
|
| 300 |
if self._stack_timeout_ref is not None: |
| 301 |
self._stack_timeout_ref.cancel() |
| 302 |
self._stack_timeout_ref = None |
| 303 |
|
| 304 |
if self._task_ref is not None: |
| 305 |
self._task_ref.cancel() |
| 306 |
self._task_ref = None |
| 307 |
|
| 308 |
def _report_completion_and_cleanup( |
| 309 |
self, result: Union[pika.connection.Connection, |
| 310 |
BaseException]) -> None: |
| 311 |
"""Clean up and invoke client's `on_done` callback. |
| 312 |
|
| 313 |
:param pika.connection.Connection | BaseException result: value to pass |
| 314 |
to user's `on_done` callback. |
| 315 |
""" |
| 316 |
if isinstance(result, BaseException): |
| 317 |
_LOG.error('AMQPConnector - reporting failure: %r', result) |
| 318 |
else: |
| 319 |
_LOG.info('AMQPConnector - reporting success: %r', result) |
| 320 |
|
| 321 |
on_done = self._on_done |
| 322 |
self._close() |
| 323 |
|
| 324 |
on_done(result) |
| 325 |
|
| 326 |
def _on_tcp_connection_timeout(self) -> None: |
| 327 |
"""Handle TCP connection timeout |
| 328 |
|
| 329 |
Reports AMQPConnectorSocketConnectError with socket.timeout inside. |
| 330 |
|
| 331 |
""" |
| 332 |
self._tcp_timeout_ref = None |
| 333 |
|
| 334 |
error = AMQPConnectorSocketConnectError( |
| 335 |
socket.timeout('TCP connection attempt timed out: {!r}/{}'.format( |
| 336 |
self._conn_params.host, self._addr_record))) |
| 337 |
self._report_completion_and_cleanup(error) |
| 338 |
|
| 339 |
def _on_overall_timeout(self) -> None: |
| 340 |
"""Handle overall TCP/[SSL]/AMQP connection attempt timeout by reporting |
| 341 |
`Timeout` error to the client. |
| 342 |
|
| 343 |
Reports AMQPConnectorSocketConnectError if timeout occurred during |
| 344 |
socket TCP connection attempt. |
| 345 |
Reports AMQPConnectorTransportSetupError if timeout occurred during |
| 346 |
tramsport [SSL] setup attempt. |
| 347 |
Reports AMQPConnectorAMQPHandshakeError if timeout occurred during |
| 348 |
AMQP handshake. |
| 349 |
|
| 350 |
""" |
| 351 |
self._stack_timeout_ref = None |
| 352 |
|
| 353 |
prev_state = self._state |
| 354 |
self._state = self._STATE_TIMEOUT |
| 355 |
|
| 356 |
if prev_state == self._STATE_AMQP: |
| 357 |
msg = ('Timeout while setting up AMQP to {!r}/{}; ssl={}'.format( |
| 358 |
self._conn_params.host, self._addr_record, |
| 359 |
bool(self._conn_params.ssl_options))) |
| 360 |
_LOG.error(msg) |
| 361 |
# Initiate close of AMQP connection and wait for asynchronous |
| 362 |
# callback from the Connection instance before reporting completion |
| 363 |
# to client |
| 364 |
assert not self._amqp_conn.is_open, f'Unexpected open state of {self._amqp_conn!r}' # type: ignore |
| 365 |
if not self._amqp_conn.is_closing: # type: ignore |
| 366 |
self._amqp_conn.close(320, msg) # type: ignore |
| 367 |
return |
| 368 |
|
| 369 |
if prev_state == self._STATE_TCP: |
| 370 |
error: Exception = AMQPConnectorSocketConnectError( |
| 371 |
AMQPConnectorStackTimeout( |
| 372 |
'Timeout while connecting socket to {!r}/{}'.format( |
| 373 |
self._conn_params.host, self._addr_record))) |
| 374 |
else: |
| 375 |
assert prev_state == self._STATE_TRANSPORT |
| 376 |
error = AMQPConnectorTransportSetupError( |
| 377 |
AMQPConnectorStackTimeout( |
| 378 |
'Timeout while setting up transport to {!r}/{}; ssl={}'. |
| 379 |
format(self._conn_params.host, self._addr_record, |
| 380 |
bool(self._conn_params.ssl_options)))) |
| 381 |
|
| 382 |
self._report_completion_and_cleanup(error) |
| 383 |
|
| 384 |
def _on_tcp_connection_done(self, exc: Optional[BaseException]) -> None: |
| 385 |
"""Handle completion of asynchronous socket connection attempt. |
| 386 |
|
| 387 |
Reports AMQPConnectorSocketConnectError if TCP socket connection |
| 388 |
failed. |
| 389 |
|
| 390 |
:param None|BaseException exc: None on success; exception object on |
| 391 |
failure |
| 392 |
|
| 393 |
""" |
| 394 |
self._task_ref = None |
| 395 |
if self._tcp_timeout_ref is not None: |
| 396 |
self._tcp_timeout_ref.cancel() |
| 397 |
self._tcp_timeout_ref = None |
| 398 |
|
| 399 |
if exc is not None: |
| 400 |
_LOG.error('TCP Connection attempt failed: %r; dest=%r', exc, |
| 401 |
self._addr_record) |
| 402 |
self._report_completion_and_cleanup( |
| 403 |
AMQPConnectorSocketConnectError(exc)) |
| 404 |
return |
| 405 |
|
| 406 |
# We succeeded in making a TCP/IP connection to the server |
| 407 |
_LOG.debug('TCP connection to broker established: %r.', self._sock) |
| 408 |
|
| 409 |
# Now set up the transport |
| 410 |
self._state = self._STATE_TRANSPORT |
| 411 |
|
| 412 |
ssl_context = server_hostname = None |
| 413 |
if self._conn_params.ssl_options is not None: |
| 414 |
ssl_context = self._conn_params.ssl_options.context |
| 415 |
server_hostname = self._conn_params.ssl_options.server_hostname |
| 416 |
if server_hostname is None: |
| 417 |
server_hostname = self._conn_params.host |
| 418 |
|
| 419 |
self._task_ref = self._nbio.create_streaming_connection( |
| 420 |
protocol_factory=functools.partial(self._conn_factory, |
| 421 |
self._conn_params), |
| 422 |
sock=self._sock, |
| 423 |
ssl_context=ssl_context, |
| 424 |
server_hostname=server_hostname, |
| 425 |
on_done=self._on_transport_establishment_done) |
| 426 |
|
| 427 |
self._sock = None # type: ignore # create_streaming_connection() takes ownership |
| 428 |
|
| 429 |
def _on_transport_establishment_done( |
| 430 |
self, result: Union[Tuple[nbio_interface.AbstractStreamTransport, |
| 431 |
nbio_interface.AbstractStreamProtocol], |
| 432 |
BaseException] |
| 433 |
) -> None: |
| 434 |
"""Handle asynchronous completion of |
| 435 |
`AbstractIOServices.create_streaming_connection()` |
| 436 |
|
| 437 |
Reports AMQPConnectorTransportSetupError if transport ([SSL]) setup |
| 438 |
failed. |
| 439 |
|
| 440 |
:param sequence|BaseException result: On success, a two-tuple |
| 441 |
(transport, protocol); on failure, exception instance. |
| 442 |
|
| 443 |
""" |
| 444 |
self._task_ref = None |
| 445 |
|
| 446 |
if isinstance(result, BaseException): |
| 447 |
_LOG.error( |
| 448 |
'Attempt to create the streaming transport failed: %r; ' |
| 449 |
'%r/%s; ssl=%s', result, self._conn_params.host, |
| 450 |
self._addr_record, bool(self._conn_params.ssl_options)) |
| 451 |
self._report_completion_and_cleanup( |
| 452 |
AMQPConnectorTransportSetupError(result)) |
| 453 |
return |
| 454 |
|
| 455 |
# We succeeded in setting up the streaming transport! |
| 456 |
# result is a two-tuple (transport, protocol) |
| 457 |
_LOG.info('Streaming transport linked up: %r.', result) |
| 458 |
_transport, self._amqp_conn = result # pyright: ignore[reportAttributeAccessIssue] |
| 459 |
|
| 460 |
# AMQP handshake is in progress - initiated during transport link-up |
| 461 |
self._state = self._STATE_AMQP |
| 462 |
# We explicitly remove default handler because it raises an exception. |
| 463 |
self._amqp_conn.add_on_open_error_callback( # pyright: ignore[reportOptionalMemberAccess] |
| 464 |
self._on_amqp_handshake_done, |
| 465 |
remove_default=True) |
| 466 |
self._amqp_conn.add_on_open_callback( |
| 467 |
self._on_amqp_handshake_done |
| 468 |
) # pyright: ignore[reportOptionalMemberAccess] |
| 469 |
|
| 470 |
def _on_amqp_handshake_done(self, |
| 471 |
connection: pika.connection.Connection, |
| 472 |
error: Optional[BaseException] = None) -> None: |
| 473 |
"""Handle completion of AMQP connection handshake attempt. |
| 474 |
|
| 475 |
NOTE: we handle two types of callbacks - success with just connection |
| 476 |
arg as well as the open-error callback with connection and error |
| 477 |
|
| 478 |
Reports AMQPConnectorAMQPHandshakeError if AMQP handshake failed. |
| 479 |
|
| 480 |
:param pika.connection.Connection connection: |
| 481 |
:param BaseException | None error: None on success, otherwise |
| 482 |
failure |
| 483 |
|
| 484 |
""" |
| 485 |
_LOG.debug( |
| 486 |
'AMQPConnector: AMQP handshake attempt completed; state=%s; ' |
| 487 |
'error=%r; %r/%s', self._state, error, self._conn_params.host, |
| 488 |
self._addr_record) |
| 489 |
|
| 490 |
# Don't need it any more; and _deactivate() checks that it's None |
| 491 |
self._amqp_conn = None |
| 492 |
|
| 493 |
if self._state == self._STATE_ABORTING: |
| 494 |
# Client-initiated abort takes precedence over timeout |
| 495 |
result: Union[BaseException, |
| 496 |
pika.connection.Connection] = AMQPConnectorAborted() |
| 497 |
elif self._state == self._STATE_TIMEOUT: |
| 498 |
result = AMQPConnectorAMQPHandshakeError( |
| 499 |
AMQPConnectorStackTimeout( |
| 500 |
'Timeout during AMQP handshake{!r}/{}; ssl={}'.format( |
| 501 |
self._conn_params.host, self._addr_record, |
| 502 |
bool(self._conn_params.ssl_options)))) |
| 503 |
elif self._state == self._STATE_AMQP: |
| 504 |
if error is None: |
| 505 |
_LOG.debug( |
| 506 |
'AMQPConnector: AMQP connection established for %r/%s: %r', |
| 507 |
self._conn_params.host, self._addr_record, connection) |
| 508 |
result = connection |
| 509 |
else: |
| 510 |
_LOG.debug( |
| 511 |
'AMQPConnector: AMQP connection handshake failed for ' |
| 512 |
'%r/%s: %r', self._conn_params.host, self._addr_record, |
| 513 |
error) |
| 514 |
result = AMQPConnectorAMQPHandshakeError(error) |
| 515 |
else: |
| 516 |
# We timed out or aborted and initiated closing of the connection, |
| 517 |
# but this callback snuck in |
| 518 |
_LOG.debug( |
| 519 |
'AMQPConnector: Ignoring AMQP handshake completion ' |
| 520 |
'notification due to wrong state=%s; error=%r; conn=%r', |
| 521 |
self._state, error, connection) |
| 522 |
return |
| 523 |
|
| 524 |
self._report_completion_and_cleanup(result) |
| 525 |
|
| 526 |
|
| 527 |
class AbstractAMQPConnectionWorkflow( |
| 528 |
pika.compat.AbstractBase # type: ignore[valid-type, misc] |
| 529 |
): |
| 530 |
"""Interface for implementing a custom TCP/[SSL]/AMQP connection workflow. |
| 531 |
|
| 532 |
""" |
| 533 |
|
| 534 |
def start( |
| 535 |
self, connection_configs: Sequence[pika.connection.Parameters], |
| 536 |
connector_factory: Callable[..., Any], native_loop, on_done: Callable[ |
| 537 |
[Union[pika.connection.Connection, AMQPConnectorException]], None] |
| 538 |
) -> None: |
| 539 |
"""Asynchronously perform the workflow until success or all retries |
| 540 |
are exhausted. Called by the adapter. |
| 541 |
|
| 542 |
:param sequence connection_configs: A sequence of one or more |
| 543 |
`pika.connection.Parameters`-based objects. Will attempt to connect |
| 544 |
using each config in the given order. |
| 545 |
:param callable connector_factory: call it without args to obtain a new |
| 546 |
instance of `AMQPConnector` for each connection attempt. |
| 547 |
See `AMQPConnector` for details. |
| 548 |
:param native_loop: Native I/O loop passed by app to the adapter or |
| 549 |
obtained by the adapter by default. |
| 550 |
:param callable on_done: Function to call upon completion of the |
| 551 |
workflow: |
| 552 |
`on_done(pika.connection.Connection | |
| 553 |
AMQPConnectionWorkflowFailed | |
| 554 |
AMQPConnectionWorkflowAborted)`. |
| 555 |
`Connection`-based adapter on success, |
| 556 |
`AMQPConnectionWorkflowFailed` on failure, |
| 557 |
`AMQPConnectionWorkflowAborted` if workflow was aborted. |
| 558 |
|
| 559 |
:raises AMQPConnectionWorkflowWrongState: If called in wrong state, such |
| 560 |
as after starting the workflow. |
| 561 |
""" |
| 562 |
raise NotImplementedError |
| 563 |
|
| 564 |
def abort(self) -> None: |
| 565 |
"""Abort the workflow asynchronously. The completion callback will be |
| 566 |
called with an instance of AMQPConnectionWorkflowAborted. |
| 567 |
|
| 568 |
NOTE: we can't cancel/close synchronously because aborting pika |
| 569 |
Connection and its transport requires an asynchronous operation. |
| 570 |
|
| 571 |
:raises AMQPConnectionWorkflowWrongState: If called in wrong state, such |
| 572 |
as before starting or after completion has been reported. |
| 573 |
""" |
| 574 |
raise NotImplementedError |
| 575 |
|
| 576 |
|
| 577 |
class AMQPConnectionWorkflow(AbstractAMQPConnectionWorkflow): |
| 578 |
"""Implements Pika's default workflow for performing multiple TCP/[SSL]/AMQP |
| 579 |
connection attempts with timeouts and retries until one succeeds or all |
| 580 |
attempts fail. |
| 581 |
|
| 582 |
The workflow: |
| 583 |
while not success and retries remain: |
| 584 |
1. For each given config (pika.connection.Parameters object): |
| 585 |
A. Perform DNS resolution of the config's host. |
| 586 |
B. Attempt to establish TCP/[SSL]/AMQP for each resolved address |
| 587 |
until one succeeds, in which case we're done. |
| 588 |
2. If all configs failed but retries remain, resume from beginning |
| 589 |
after the given retry pause. NOTE: failure of DNS resolution |
| 590 |
is equivalent to one cycle and will be retried after the pause |
| 591 |
if retries remain. |
| 592 |
|
| 593 |
""" |
| 594 |
|
| 595 |
_SOCK_TYPE = socket.SOCK_STREAM |
| 596 |
_IPPROTO = socket.IPPROTO_TCP |
| 597 |
|
| 598 |
_STATE_INIT = 0 |
| 599 |
_STATE_ACTIVE = 1 |
| 600 |
_STATE_ABORTING = 2 |
| 601 |
_STATE_DONE = 3 |
| 602 |
|
| 603 |
def __init__(self, _until_first_amqp_attempt: bool = False) -> None: |
| 604 |
""" |
| 605 |
:param int | float retry_pause: Non-negative number of seconds to wait |
| 606 |
before retrying the config sequence. Meaningful only if retries is |
| 607 |
greater than 0. Defaults to 2 seconds. |
| 608 |
:param bool _until_first_amqp_attempt: INTERNAL USE ONLY; ends workflow |
| 609 |
after first AMQP handshake attempt, regardless of outcome (success |
| 610 |
or failure). The automatic connection logic in |
| 611 |
`pika.connection.Connection` enables this because it's not |
| 612 |
designed/tested to reset all state properly to handle more than one |
| 613 |
AMQP handshake attempt. |
| 614 |
|
| 615 |
TODO: Do we need getaddrinfo timeout? |
| 616 |
TODO: Would it be useful to implement exponential back-off? |
| 617 |
|
| 618 |
""" |
| 619 |
self._attempts_remaining: int = None # type: ignore[assignment] # supplied by start() |
| 620 |
self._retry_pause: float = None # type: ignore[assignment] # supplied by start() |
| 621 |
self._until_first_amqp_attempt = _until_first_amqp_attempt |
| 622 |
|
| 623 |
# Provided by set_io_services() |
| 624 |
# pylint: disable=C0301 |
| 625 |
self._nbio: nbio_interface.AbstractIOServices = None # type: ignore |
| 626 |
|
| 627 |
# Current index within `_connection_configs`; initialized when |
| 628 |
# starting a new connection sequence. |
| 629 |
self._current_config_index: int = None # type: ignore |
| 630 |
|
| 631 |
self._connection_configs: Sequence[ |
| 632 |
pika.connection. |
| 633 |
Parameters] = None # type: ignore # supplied by start() |
| 634 |
self._connector_factory: Callable[ |
| 635 |
..., Any] = None # type: ignore # supplied by start() |
| 636 |
self._on_done: Callable[ |
| 637 |
[Union[pika.connection.Connection, AMQPConnectorException]], |
| 638 |
None] = None # type: ignore # supplied by start() |
| 639 |
|
| 640 |
self._connector: AMQPConnector = None # type: ignore |
| 641 |
|
| 642 |
self._task_ref: Optional[Union[ |
| 643 |
nbio_interface.AbstractTimerReference, nbio_interface. |
| 644 |
AbstractIOReference]] = None # current cancelable asynchronous task or timer |
| 645 |
self._addrinfo_iter: Iterator[ADDRESS_INFO] = None # type: ignore |
| 646 |
|
| 647 |
# Exceptions from all failed connection attempts in this workflow |
| 648 |
self._connection_errors: List[BaseException] = [] |
| 649 |
|
| 650 |
self._state = self._STATE_INIT |
| 651 |
|
| 652 |
def set_io_services(self, nbio: nbio_interface.AbstractIOServices) -> None: |
| 653 |
"""Called by the conneciton adapter only on pika's |
| 654 |
`AMQPConnectionWorkflow` instance to provide it the adapter-specific |
| 655 |
`AbstractIOServices` object before calling the `start()` method. |
| 656 |
|
| 657 |
NOTE: Custom workflow implementations should use the native I/O loop |
| 658 |
directly because `AbstractIOServices` is private to Pika |
| 659 |
implementation and its interface may change without notice. |
| 660 |
|
| 661 |
:param pika.adapters.utils.nbio_interface.AbstractIOServices nbio: |
| 662 |
|
| 663 |
""" |
| 664 |
self._nbio = nbio |
| 665 |
|
| 666 |
def start( |
| 667 |
self, |
| 668 |
connection_configs: Sequence[pika.connection.Parameters], |
| 669 |
connector_factory: Callable[..., Any], |
| 670 |
native_loop, # pylint: disable=W0613 |
| 671 |
on_done: Callable[ |
| 672 |
[Union[pika.connection.Connection, AMQPConnectorException]], None] |
| 673 |
) -> None: |
| 674 |
"""Override `AbstractAMQPConnectionWorkflow.start()`. |
| 675 |
|
| 676 |
NOTE: This implementation uses `connection_attempts` and `retry_delay` |
| 677 |
values from the last element of the given `connection_configs` sequence |
| 678 |
as the overall number of connection attempts of the entire |
| 679 |
`connection_configs` sequence and pause between each sequence. |
| 680 |
|
| 681 |
""" |
| 682 |
if self._state != self._STATE_INIT: |
| 683 |
raise AMQPConnectorWrongState( |
| 684 |
f'Already in progress or finished; state={self._state}') |
| 685 |
|
| 686 |
try: |
| 687 |
iter(connection_configs) |
| 688 |
except Exception as error: |
| 689 |
raise TypeError( |
| 690 |
'connection_configs does not support iteration: {!r}'.format( |
| 691 |
error)) |
| 692 |
if not connection_configs: |
| 693 |
raise ValueError( |
| 694 |
f'connection_configs is empty: {connection_configs!r}.') |
| 695 |
|
| 696 |
self._connection_configs = connection_configs |
| 697 |
self._connector_factory = connector_factory |
| 698 |
self._on_done = on_done |
| 699 |
|
| 700 |
self._attempts_remaining = connection_configs[-1].connection_attempts |
| 701 |
self._retry_pause = connection_configs[-1].retry_delay |
| 702 |
|
| 703 |
self._state = self._STATE_ACTIVE |
| 704 |
|
| 705 |
_LOG.debug('Starting AMQP Connection workflow asynchronously.') |
| 706 |
|
| 707 |
# Begin from our own I/O loop context to avoid calling back into client |
| 708 |
# from client's call here |
| 709 |
self._task_ref = self._nbio.call_later( |
| 710 |
0, functools.partial(self._start_new_cycle_async, first=True)) |
| 711 |
|
| 712 |
def abort(self) -> None: |
| 713 |
"""Override `AbstractAMQPConnectionWorkflow.abort()`. |
| 714 |
|
| 715 |
""" |
| 716 |
if self._state == self._STATE_INIT: |
| 717 |
raise AMQPConnectorWrongState('Cannot abort before starting.') |
| 718 |
elif self._state == self._STATE_DONE: |
| 719 |
raise AMQPConnectorWrongState( |
| 720 |
'Cannot abort after completion was reported') |
| 721 |
|
| 722 |
self._state = self._STATE_ABORTING |
| 723 |
self._deactivate() |
| 724 |
|
| 725 |
_LOG.info('AMQPConnectionWorkflow: beginning client-initiated ' |
| 726 |
'asynchronous abort.') |
| 727 |
|
| 728 |
if self._connector is None: |
| 729 |
_LOG.debug('AMQPConnectionWorkflow.abort(): no connector, so just ' |
| 730 |
'scheduling completion report via I/O loop.') |
| 731 |
self._nbio.add_callback_threadsafe( |
| 732 |
functools.partial(self._report_completion_and_cleanup, |
| 733 |
AMQPConnectionWorkflowAborted())) |
| 734 |
else: |
| 735 |
_LOG.debug('AMQPConnectionWorkflow.abort(): requesting ' |
| 736 |
'connector.abort().') |
| 737 |
self._connector.abort() |
| 738 |
|
| 739 |
def _close(self) -> None: |
| 740 |
"""Cancel asynchronous tasks and clean up to assist garbage collection. |
| 741 |
|
| 742 |
Transition to _STATE_DONE. |
| 743 |
|
| 744 |
""" |
| 745 |
self._deactivate() |
| 746 |
|
| 747 |
self._connection_configs = None # type: ignore |
| 748 |
self._nbio = None # type: ignore |
| 749 |
self._connector_factory = None # type: ignore |
| 750 |
self._on_done = None # type: ignore |
| 751 |
self._connector = None # type: ignore |
| 752 |
self._addrinfo_iter = None # type: ignore |
| 753 |
self._connection_errors = None # type: ignore |
| 754 |
|
| 755 |
self._state = self._STATE_DONE |
| 756 |
|
| 757 |
def _deactivate(self) -> None: |
| 758 |
"""Cancel asynchronous tasks. |
| 759 |
|
| 760 |
""" |
| 761 |
if self._task_ref is not None: |
| 762 |
self._task_ref.cancel() |
| 763 |
self._task_ref = None |
| 764 |
|
| 765 |
def _report_completion_and_cleanup( |
| 766 |
self, result: Union[pika.connection.Connection, |
| 767 |
AMQPConnectorException]) -> None: |
| 768 |
"""Clean up and invoke client's `on_done` callback. |
| 769 |
|
| 770 |
:param pika.connection.Connection | AMQPConnectionWorkflowFailed result: |
| 771 |
value to pass to user's `on_done` callback. |
| 772 |
""" |
| 773 |
if isinstance(result, BaseException): |
| 774 |
_LOG.error('AMQPConnectionWorkflow - reporting failure: %r', result) |
| 775 |
else: |
| 776 |
_LOG.info('AMQPConnectionWorkflow - reporting success: %r', result) |
| 777 |
|
| 778 |
on_done = self._on_done |
| 779 |
self._close() |
| 780 |
|
| 781 |
on_done(result) |
| 782 |
|
| 783 |
def _start_new_cycle_async(self, first: bool) -> None: |
| 784 |
"""Start a new workflow cycle (if any more attempts are left) beginning |
| 785 |
with the first Parameters object in self._connection_configs. If out of |
| 786 |
attempts, report `AMQPConnectionWorkflowFailed`. |
| 787 |
|
| 788 |
:param bool first: if True, don't delay; otherwise delay next attempt by |
| 789 |
`self._retry_pause` seconds. |
| 790 |
""" |
| 791 |
self._task_ref = None |
| 792 |
|
| 793 |
assert self._attempts_remaining >= 0, self._attempts_remaining |
| 794 |
|
| 795 |
if self._attempts_remaining <= 0: |
| 796 |
error = AMQPConnectionWorkflowFailed(self._connection_errors) |
| 797 |
_LOG.error('AMQP connection workflow failed: %r.', error) |
| 798 |
self._report_completion_and_cleanup(error) |
| 799 |
return |
| 800 |
|
| 801 |
self._attempts_remaining -= 1 |
| 802 |
_LOG.debug( |
| 803 |
'Beginning a new AMQP connection workflow cycle; attempts ' |
| 804 |
'remaining after this: %s', self._attempts_remaining) |
| 805 |
|
| 806 |
self._current_config_index = None # type: ignore |
| 807 |
|
| 808 |
self._task_ref = self._nbio.call_later( |
| 809 |
0 if first else self._retry_pause, self._try_next_config_async) |
| 810 |
|
| 811 |
def _try_next_config_async(self) -> None: |
| 812 |
"""Attempt to connect using the next Parameters config. If there are no |
| 813 |
more configs, start a new cycle. |
| 814 |
|
| 815 |
""" |
| 816 |
self._task_ref = None |
| 817 |
|
| 818 |
if self._current_config_index is None: |
| 819 |
self._current_config_index = 0 |
| 820 |
else: |
| 821 |
self._current_config_index += 1 |
| 822 |
|
| 823 |
if self._current_config_index >= len(self._connection_configs): |
| 824 |
_LOG.debug('_try_next_config_async: starting a new cycle.') |
| 825 |
self._start_new_cycle_async(first=False) |
| 826 |
return |
| 827 |
|
| 828 |
params = self._connection_configs[self._current_config_index] |
| 829 |
|
| 830 |
_LOG.debug('_try_next_config_async: %r:%s', params.host, params.port) |
| 831 |
|
| 832 |
# Begin with host address resolution |
| 833 |
assert self._task_ref is None |
| 834 |
self._task_ref = self._nbio.getaddrinfo( |
| 835 |
host=params.host, |
| 836 |
port=params.port, |
| 837 |
socktype=self._SOCK_TYPE, |
| 838 |
proto=self._IPPROTO, |
| 839 |
on_done=self._on_getaddrinfo_async_done) |
| 840 |
|
| 841 |
def _on_getaddrinfo_async_done( |
| 842 |
self, addrinfos_or_exc: Union[List[ADDRESS_INFO], |
| 843 |
BaseException]) -> None: |
| 844 |
"""Handles completion callback from asynchronous `getaddrinfo()`. |
| 845 |
|
| 846 |
:param list | BaseException addrinfos_or_exc: resolved address records |
| 847 |
returned by `getaddrinfo()` or an exception object from failure. |
| 848 |
""" |
| 849 |
self._task_ref = None |
| 850 |
|
| 851 |
if isinstance(addrinfos_or_exc, BaseException): |
| 852 |
_LOG.error('getaddrinfo failed: %r.', addrinfos_or_exc) |
| 853 |
self._connection_errors.append(addrinfos_or_exc) |
| 854 |
self._start_new_cycle_async(first=False) |
| 855 |
return |
| 856 |
|
| 857 |
_LOG.debug('getaddrinfo returned %s records', len(addrinfos_or_exc)) |
| 858 |
self._addrinfo_iter = iter(addrinfos_or_exc) |
| 859 |
|
| 860 |
self._try_next_resolved_address() |
| 861 |
|
| 862 |
def _try_next_resolved_address(self) -> None: |
| 863 |
"""Try connecting using next resolved address. If there aren't any left, |
| 864 |
continue with next Parameters config. |
| 865 |
|
| 866 |
""" |
| 867 |
try: |
| 868 |
addr_record = next(self._addrinfo_iter) |
| 869 |
except StopIteration: |
| 870 |
_LOG.debug( |
| 871 |
'_try_next_resolved_address: continuing with next config.') |
| 872 |
self._try_next_config_async() |
| 873 |
return |
| 874 |
|
| 875 |
_LOG.debug('Attempting to connect using address record %r', addr_record) |
| 876 |
|
| 877 |
self._connector = self._connector_factory() |
| 878 |
|
| 879 |
self._connector.start( |
| 880 |
addr_record=addr_record, |
| 881 |
conn_params=self._connection_configs[self._current_config_index], |
| 882 |
on_done=self._on_connector_done) |
| 883 |
|
| 884 |
def _on_connector_done( |
| 885 |
self, conn_or_exc: Union[pika.connection.Connection, |
| 886 |
BaseException]) -> None: |
| 887 |
"""Handle completion of connection attempt by `AMQPConnector`. |
| 888 |
|
| 889 |
:param pika.connection.Connection | BaseException conn_or_exc: See |
| 890 |
`AMQPConnector.start()` for exception details. |
| 891 |
|
| 892 |
""" |
| 893 |
self._connector = None # type: ignore |
| 894 |
_LOG.debug('Connection attempt completed with %r', conn_or_exc) |
| 895 |
|
| 896 |
if isinstance(conn_or_exc, BaseException): |
| 897 |
self._connection_errors.append(conn_or_exc) |
| 898 |
|
| 899 |
if isinstance(conn_or_exc, AMQPConnectorAborted): |
| 900 |
assert self._state == self._STATE_ABORTING, \ |
| 901 |
f'Expected _STATE_ABORTING, but got {self._state!r}' |
| 902 |
|
| 903 |
self._report_completion_and_cleanup( |
| 904 |
AMQPConnectionWorkflowAborted()) |
| 905 |
elif (self._until_first_amqp_attempt and |
| 906 |
isinstance(conn_or_exc, AMQPConnectorAMQPHandshakeError)): |
| 907 |
_LOG.debug('Ending AMQP connection workflow after first failed ' |
| 908 |
'AMQP handshake due to _until_first_amqp_attempt.') |
| 909 |
if isinstance(conn_or_exc.exception, |
| 910 |
pika.exceptions.ConnectionOpenAborted): |
| 911 |
error = AMQPConnectionWorkflowAborted |
| 912 |
else: |
| 913 |
error = AMQPConnectionWorkflowFailed( |
| 914 |
self._connection_errors) # type: ignore |
| 915 |
|
| 916 |
self._report_completion_and_cleanup(error) # type: ignore |
| 917 |
else: |
| 918 |
self._try_next_resolved_address() |
| 919 |
else: |
| 920 |
# Success! |
| 921 |
self._report_completion_and_cleanup(conn_or_exc) |