Debian Codegraph @

pika/adapters/base_connection.py

raw
1 """Base class extended by connection adapters. This extends the
2 connection.Connection class to encapsulate connection behavior but still
3 isolate socket and low level communication.
4
5 """
6 from __future__ import annotations
7
8 import abc
9 import functools
10 import logging
11 from typing import Any, Callable, Optional, Sequence, Union
12
13 import pika.compat
14 import pika.exceptions
15 import pika.tcp_socket_opts
16
17 from pika.adapters.utils import connection_workflow, nbio_interface
18 from pika import connection
19
20 LOGGER = logging.getLogger(__name__)
21
22
23 class BaseConnection(connection.Connection):
24 """BaseConnection class that should be extended by connection adapters.
25
26 This class abstracts I/O loop and transport services from pika core.
27
28 """
29
30 def __init__(self,
31 parameters: Optional[connection.Parameters],
32 on_open_callback: Optional[Callable[[connection.Connection],
33 None]],
34 on_open_error_callback: Optional[Callable[
35 [connection.Connection, BaseException], None]],
36 on_close_callback: Optional[Callable[
37 [connection.Connection, BaseException], None]],
38 nbio: nbio_interface.AbstractIOServices,
39 internal_connection_workflow: bool = True) -> None:
40 """Create a new instance of the Connection object.
41
42 :param None|pika.connection.Parameters parameters: Connection parameters
43 :param None|method on_open_callback: Method to call on connection open
44 :param None | method on_open_error_callback: Called if the connection
45 can't be established or connection establishment is interrupted by
46 `Connection.close()`: on_open_error_callback(Connection, exception).
47 :param None | method on_close_callback: Called when a previously fully
48 open connection is closed:
49 `on_close_callback(Connection, exception)`, where `exception` is
50 either an instance of `exceptions.ConnectionClosed` if closed by
51 user or broker or exception of another type that describes the cause
52 of connection failure.
53 :param pika.adapters.utils.nbio_interface.AbstractIOServices nbio:
54 asynchronous services
55 :param bool internal_connection_workflow: True for autonomous connection
56 establishment which is default; False for externally-managed
57 connection workflow via the `create_connection()` factory.
58 :raises: RuntimeError
59 :raises: ValueError
60
61 """
62 if parameters and not isinstance(parameters, connection.Parameters):
63 raise ValueError(
64 'Expected instance of Parameters, not {!r}'.format(parameters))
65
66 self._nbio: nbio_interface.AbstractIOServices = nbio
67
68 self._connection_workflow: Optional[
69 connection_workflow.AbstractAMQPConnectionWorkflow] = None
70 self._transport: Optional[nbio_interface.AbstractStreamTransport] = None
71
72 self._got_eof: bool = False # transport indicated EOF (connection reset)
73
74 super().__init__(
75 parameters,
76 on_open_callback,
77 on_open_error_callback,
78 on_close_callback,
79 internal_connection_workflow=internal_connection_workflow)
80
81 def _init_connection_state(self) -> None:
82 """Initialize or reset all of our internal state variables for a given
83 connection. If we disconnect and reconnect, all of our state needs to
84 be wiped.
85
86 """
87 super()._init_connection_state()
88
89 self._connection_workflow = None
90 self._transport = None
91 self._got_eof = False
92
93 def __repr__(self) -> str:
94
95 # def get_socket_repr(sock):
96 # """Return socket info suitable for use in repr"""
97 # if sock is None:
98 # return None
99 #
100 # sockname = None
101 # peername = None
102 # try:
103 # sockname = sock.getsockname()
104 # except pika.compat.SOCKET_ERROR:
105 # # closed?
106 # pass
107 # else:
108 # try:
109 # peername = sock.getpeername()
110 # except pika.compat.SOCKET_ERROR:
111 # # not connected?
112 # pass
113 #
114 # return '%s->%s' % (sockname, peername)
115 # TODO need helpful __repr__ in transports
116 return ('<{} {} transport={} params={}>'.format(
117 self.__class__.__name__, self._STATE_NAMES[self.connection_state],
118 self._transport, self.params))
119
120 @classmethod
121 @abc.abstractmethod
122 def create_connection(
123 cls,
124 connection_configs: Sequence[connection.Parameters],
125 on_done: Callable[[
126 Union[connection.Connection,
127 connection_workflow.AMQPConnectorException]
128 ], None],
129 custom_ioloop: Optional[Any] = None,
130 workflow: Optional[
131 connection_workflow.AbstractAMQPConnectionWorkflow] = None
132 ) -> connection_workflow.AbstractAMQPConnectionWorkflow:
133 """Asynchronously create a connection to an AMQP broker using the given
134 configurations. Will attempt to connect using each config in the given
135 order, including all compatible resolved IP addresses of the hostname
136 supplied in each config, until one is established or all attempts fail.
137
138 See also `_start_connection_workflow()`.
139
140 :param sequence connection_configs: A sequence of one or more
141 `pika.connection.Parameters`-based objects.
142 :param callable on_done: as defined in
143 `connection_workflow.AbstractAMQPConnectionWorkflow.start()`.
144 :param object | None custom_ioloop: Provide a custom I/O loop that is
145 native to the specific adapter implementation; if None, the adapter
146 will use a default loop instance, which is typically a singleton.
147 :param connection_workflow.AbstractAMQPConnectionWorkflow | None workflow:
148 Pass an instance of an implementation of the
149 `connection_workflow.AbstractAMQPConnectionWorkflow` interface;
150 defaults to a `connection_workflow.AMQPConnectionWorkflow` instance
151 with default values for optional args.
152 :returns: Connection workflow instance in use. The user should limit
153 their interaction with this object only to it's `abort()` method.
154 :rtype: connection_workflow.AbstractAMQPConnectionWorkflow
155
156 """
157 raise NotImplementedError
158
159 @classmethod
160 def _start_connection_workflow(
161 cls, connection_configs: Sequence[connection.Parameters],
162 connection_factory: Callable[[connection.Parameters], BaseConnection],
163 nbio: nbio_interface.AbstractIOServices,
164 workflow: Optional[connection_workflow.AbstractAMQPConnectionWorkflow],
165 on_done: Callable[[
166 Union[connection.Connection,
167 connection_workflow.AMQPConnectorException]
168 ], None]
169 ) -> connection_workflow.AbstractAMQPConnectionWorkflow:
170 """Helper function for custom implementations of `create_connection()`.
171
172 :param sequence connection_configs: A sequence of one or more
173 `pika.connection.Parameters`-based objects.
174 :param callable connection_factory: A function that takes
175 `pika.connection.Parameters` as its only arg and returns a brand new
176 `pika.connection.Connection`-based adapter instance each time it is
177 called. The factory must instantiate the connection with
178 `internal_connection_workflow=False`.
179 :param pika.adapters.utils.nbio_interface.AbstractIOServices nbio:
180 :param connection_workflow.AbstractAMQPConnectionWorkflow | None workflow:
181 Pass an instance of an implementation of the
182 `connection_workflow.AbstractAMQPConnectionWorkflow` interface;
183 defaults to a `connection_workflow.AMQPConnectionWorkflow` instance
184 with default values for optional args.
185 :param callable on_done: as defined in
186 :py:meth:`connection_workflow.AbstractAMQPConnectionWorkflow.start()`.
187 :returns: Connection workflow instance in use. The user should limit
188 their interaction with this object only to it's `abort()` method.
189 :rtype: connection_workflow.AbstractAMQPConnectionWorkflow
190
191 """
192 if workflow is None:
193 workflow = connection_workflow.AMQPConnectionWorkflow()
194 LOGGER.debug('Created default connection workflow %r', workflow)
195
196 if isinstance(workflow, connection_workflow.AMQPConnectionWorkflow):
197 workflow.set_io_services(nbio)
198
199 def create_connector() -> connection_workflow.AMQPConnector:
200 """`AMQPConnector` factory."""
201 return connection_workflow.AMQPConnector(
202 lambda params: _StreamingProtocolShim(connection_factory(params)
203 ), nbio)
204
205 workflow.start(connection_configs=connection_configs,
206 connector_factory=create_connector,
207 native_loop=nbio.get_native_ioloop(),
208 on_done=functools.partial(
209 cls._unshim_connection_workflow_callback,
210 on_done)) # type: ignore[arg-type]
211
212 return workflow
213
214 @property
215 def ioloop(self) -> Any:
216 """
217 :returns: the native I/O loop instance underlying async services selected
218 by user or the default selected by the specialized connection
219 adapter (e.g., Twisted reactor, `asyncio.SelectorEventLoop`,
220 `select_connection.IOLoop`, etc.)
221 :rtype: object
222 """
223 return self._nbio.get_native_ioloop()
224
225 def _adapter_call_later(self, delay: Union[int, float],
226 callback: Callable[[], None]) -> object:
227 """Implement
228 :py:meth:`pika.connection.Connection._adapter_call_later()`.
229
230 """
231 return self._nbio.call_later(delay, callback)
232
233 def _adapter_remove_timeout(self, timeout_id: object) -> None:
234 """Implement
235 :py:meth:`pika.connection.Connection._adapter_remove_timeout()`.
236
237 """
238 timeout_id.cancel() # type: ignore
239
240 def _adapter_add_callback_threadsafe(self, callback: Callable[...,
241 Any]) -> None:
242 """Implement
243 :py:meth:`pika.connection.Connection._adapter_add_callback_threadsafe()`.
244
245 """
246 if not callable(callback):
247 raise TypeError(
248 'callback must be a callable, but got {!r}'.format(callback))
249
250 self._nbio.add_callback_threadsafe(callback)
251
252 def _adapter_connect_stream(self) -> None:
253 """Initiate full-stack connection establishment asynchronously for
254 internally-initiated connection bring-up.
255
256 Upon failed completion, we will invoke
257 `Connection._on_stream_terminated()`. NOTE: On success,
258 the stack will be up already, so there is no corresponding callback.
259
260 """
261 self._connection_workflow = connection_workflow.AMQPConnectionWorkflow(
262 _until_first_amqp_attempt=True)
263
264 self._connection_workflow.set_io_services(self._nbio)
265
266 def create_connector() -> connection_workflow.AMQPConnector:
267 """`AMQPConnector` factory"""
268 return connection_workflow.AMQPConnector(
269 lambda _params: _StreamingProtocolShim(self), self._nbio)
270
271 self._connection_workflow.start(
272 [self.params],
273 connector_factory=create_connector,
274 native_loop=self._nbio.get_native_ioloop(),
275 on_done=functools.partial(
276 self._unshim_connection_workflow_callback,
277 self._on_connection_workflow_done)) # type: ignore
278
279 @staticmethod
280 def _unshim_connection_workflow_callback(
281 user_on_done: Callable[[Union[BaseConnection, BaseException]],
282 None],
283 shim_or_exc: Union[_StreamingProtocolShim, Exception]) -> None:
284 """
285
286 :param callable user_on_done: user's `on_done` callback as defined in
287 :py:meth:`connection_workflow.AbstractAMQPConnectionWorkflow.start()`.
288 :param _StreamingProtocolShim | Exception shim_or_exc:
289 """
290 result = shim_or_exc
291 if isinstance(result, _StreamingProtocolShim):
292 result = result.conn
293
294 user_on_done(result)
295
296 def _abort_connection_workflow(self) -> None:
297 """Asynchronously abort connection workflow. Upon
298 completion, `Connection._on_stream_terminated()` will be called with None
299 as the error argument.
300
301 Assumption: may be called only while connection is opening.
302
303 """
304 assert not self._opened, (
305 '_abort_connection_workflow() may be called only when '
306 'connection is opening.')
307
308 if self._transport is None:
309 # NOTE: this is possible only when user calls Connection.close() to
310 # interrupt internally-initiated connection establishment.
311 # self._connection_workflow.abort() would not call
312 # Connection.close() before pairing of connection with transport.
313 assert self._internal_connection_workflow, (
314 'Unexpected _abort_connection_workflow() call with '
315 'no transport in external connection workflow mode.')
316
317 # This will result in call to _on_connection_workflow_done() upon
318 # completion
319 self._connection_workflow.abort() # type: ignore
320 else:
321 # NOTE: we can't use self._connection_workflow.abort() in this case,
322 # because it would result in infinite recursion as we're called
323 # from Connection.close() and _connection_workflow.abort() calls
324 # Connection.close() to abort a connection that's already been
325 # paired with a transport. During internally-initiated connection
326 # establishment, AMQPConnectionWorkflow will discover that user
327 # aborted the connection when it receives
328 # pika.exceptions.ConnectionOpenAborted.
329
330 # This completes asynchronously, culminating in call to our method
331 # `connection_lost()`
332 self._transport.abort()
333
334 def _on_connection_workflow_done(
335 self, conn_or_exc: Union[BaseConnection, Exception]) -> None:
336 """`AMQPConnectionWorkflow` completion callback.
337
338 :param BaseConnection | Exception conn_or_exc: Our own connection
339 instance on success; exception on failure. See
340 `AbstractAMQPConnectionWorkflow.start()` for details.
341
342 """
343 LOGGER.debug('Full-stack connection workflow completed: %r',
344 conn_or_exc)
345
346 self._connection_workflow = None
347
348 # Notify protocol of failure
349 if isinstance(conn_or_exc, Exception):
350 self._transport = None
351 if isinstance(conn_or_exc,
352 connection_workflow.AMQPConnectionWorkflowAborted):
353 LOGGER.info('Full-stack connection workflow aborted: %r',
354 conn_or_exc)
355 # So that _handle_connection_workflow_failure() will know it's
356 # not a failure
357 conn_or_exc = None # type: ignore
358 else:
359 LOGGER.error('Full-stack connection workflow failed: %r',
360 conn_or_exc)
361 if (isinstance(conn_or_exc,
362 connection_workflow.AMQPConnectionWorkflowFailed)
363 and isinstance(
364 conn_or_exc.exceptions[-1],
365 connection_workflow.AMQPConnectorSocketConnectError)
366 ):
367 conn_or_exc = pika.exceptions.AMQPConnectionError(
368 conn_or_exc)
369
370 self._handle_connection_workflow_failure(
371 conn_or_exc) # pyright: ignore[reportArgumentType]
372 else:
373 # NOTE: On success, the stack will be up already, so there is no
374 # corresponding callback.
375 assert conn_or_exc is self, \
376 'Expected self conn={!r} from workflow, but got {!r}.'.format(
377 self, conn_or_exc)
378
379 def _handle_connection_workflow_failure(
380 self, error: Union[Exception, None]) -> None:
381 """Handle failure of self-initiated stack bring-up and call
382 `Connection._on_stream_terminated()` if connection is not in closed state
383 yet. Called by adapter layer when the full-stack connection workflow
384 fails.
385
386 :param Exception | None error: exception instance describing the reason
387 for failure or None if the connection workflow was aborted.
388 """
389 if error is None:
390 LOGGER.info('Self-initiated stack bring-up aborted.')
391 else:
392 LOGGER.error('Self-initiated stack bring-up failed: %r', error)
393
394 if not self.is_closed:
395 self._on_stream_terminated(error)
396 else:
397 # This may happen when AMQP layer bring up was started but did not
398 # complete
399 LOGGER.debug('_handle_connection_workflow_failure(): '
400 'suppressing - connection already closed.')
401
402 def _adapter_disconnect_stream(self) -> None:
403 """Asynchronously bring down the streaming transport layer and invoke
404 `Connection._on_stream_terminated()` asynchronously when complete.
405
406 """
407 if not self._opened:
408 self._abort_connection_workflow()
409 else:
410 # This completes asynchronously, culminating in call to our method
411 # `connection_lost()`
412 self._transport.abort() # type: ignore
413
414 def _adapter_emit_data(self, data: bytes) -> None:
415 """Take ownership of data and send it to AMQP server as soon as
416 possible.
417
418 :param bytes data:
419
420 """
421 self._transport.write(data) # type: ignore
422
423 def _proto_connection_made(
424 self, transport: nbio_interface.AbstractStreamTransport) -> None:
425 """Introduces transport to protocol after transport is connected.
426
427 :py:class:`.utils.nbio_interface.AbstractStreamProtocol` implementation.
428
429 :param nbio_interface.AbstractStreamTransport transport:
430 :raises Exception: Exception-based exception on error
431
432 """
433 self._transport = transport
434
435 # Let connection know that stream is available
436 self._on_stream_connected()
437
438 def _proto_connection_lost(self, error: Union[BaseException, None]) -> None:
439 """Called upon loss or closing of TCP connection.
440
441 :py:class:`.utils.nbio_interface.AbstractStreamProtocol` implementation.
442
443 NOTE: `connection_made()` and `connection_lost()` are each called just
444 once and in that order. All other callbacks are called between them.
445
446 :param BaseException | None error: An exception (check for
447 `BaseException`) indicates connection failure. None indicates that
448 connection was closed on this side, such as when it's aborted or
449 when `AbstractStreamProtocol.eof_received()` returns a falsy result.
450 :raises Exception: Exception-based exception on error
451
452 """
453 self._transport = None
454
455 if error is None:
456 # Either result of `eof_received()` or abort
457 if self._got_eof:
458 error = pika.exceptions.StreamLostError(
459 'Transport indicated EOF')
460 else:
461 error = pika.exceptions.StreamLostError(
462 f'Stream connection lost: {error!r}')
463
464 LOGGER.log(logging.DEBUG if error is None else logging.ERROR,
465 'connection_lost: %r', error)
466
467 self._on_stream_terminated(error)
468
469 def _proto_eof_received(self) -> bool: # pylint: disable=R0201
470 """Called after the remote peer shuts its write end of the connection.
471 :py:class:`.utils.nbio_interface.AbstractStreamProtocol` implementation.
472
473 :returns: A falsy value (including None) will cause the transport to
474 close itself, resulting in an eventual `connection_lost()` call
475 from the transport. If a truthy value is returned, it will be the
476 protocol's responsibility to close/abort the transport.
477 :rtype: falsy|truthy
478 :raises Exception: Exception-based exception on error
479
480 """
481 LOGGER.error('Transport indicated EOF.')
482
483 self._got_eof = True
484
485 # This is how a reset connection will typically present itself
486 # when we have nothing to send to the server over plaintext stream.
487 #
488 # Have transport tear down the connection and invoke our
489 # `connection_lost` method
490 return False
491
492 def _proto_data_received(self, data: bytes) -> None:
493 """Called to deliver incoming data from the server to the protocol.
494
495 :py:class:`.utils.nbio_interface.AbstractStreamProtocol` implementation.
496
497 :param data: Non-empty data bytes.
498 :raises Exception: Exception-based exception on error
499
500 """
501 self._on_data_available(data)
502
503
504 class _StreamingProtocolShim(nbio_interface.AbstractStreamProtocol):
505 """Shim for callbacks from transport so that we BaseConnection can
506 delegate to private methods, thus avoiding contamination of API with
507 methods that look public, but aren't.
508
509 """
510
511 # Override AbstractStreamProtocol abstract methods to enable instantiation
512 connection_made = None # type: ignore
513 connection_lost = None # type: ignore
514 eof_received = None # type: ignore
515 data_received = None # type: ignore
516
517 def __init__(self, conn: BaseConnection) -> None:
518 """
519 :param BaseConnection conn:
520 """
521 self.conn = conn
522 # pylint: disable=W0212
523 self.connection_made = conn._proto_connection_made
524 self.connection_lost = conn._proto_connection_lost
525 self.eof_received = conn._proto_eof_received
526 self.data_received = conn._proto_data_received
527
528 def __getattr__(self, attr: str) -> Any:
529 """Proxy inexistent attribute requests to our connection instance
530 so that AMQPConnectionWorkflow/AMQPConnector may treat the shim as an
531 actual connection.
532
533 """
534 return getattr(self.conn, attr)
535
536 def __repr__(self) -> str:
537 return f'{self.__class__.__name__}: {self.conn!r}'