OSDN Git Service

python/aqmp: squelch pylint warning for too many lines
[qmiga/qemu.git] / python / qemu / aqmp / protocol.py
1 """
2 Generic Asynchronous Message-based Protocol Support
3
4 This module provides a generic framework for sending and receiving
5 messages over an asyncio stream. `AsyncProtocol` is an abstract class
6 that implements the core mechanisms of a simple send/receive protocol,
7 and is designed to be extended.
8
9 In this package, it is used as the implementation for the `QMPClient`
10 class.
11 """
12
13 # It's all the docstrings ... ! It's long for a good reason ^_^;
14 # pylint: disable=too-many-lines
15
16 import asyncio
17 from asyncio import StreamReader, StreamWriter
18 from enum import Enum
19 from functools import wraps
20 import logging
21 import socket
22 from ssl import SSLContext
23 from typing import (
24     Any,
25     Awaitable,
26     Callable,
27     Generic,
28     List,
29     Optional,
30     Tuple,
31     TypeVar,
32     Union,
33     cast,
34 )
35
36 from .error import QMPError
37 from .util import (
38     bottom_half,
39     create_task,
40     exception_summary,
41     flush,
42     is_closing,
43     pretty_traceback,
44     upper_half,
45     wait_closed,
46 )
47
48
49 T = TypeVar('T')
50 _U = TypeVar('_U')
51 _TaskFN = Callable[[], Awaitable[None]]  # aka ``async def func() -> None``
52
53 InternetAddrT = Tuple[str, int]
54 UnixAddrT = str
55 SocketAddrT = Union[UnixAddrT, InternetAddrT]
56
57
58 class Runstate(Enum):
59     """Protocol session runstate."""
60
61     #: Fully quiesced and disconnected.
62     IDLE = 0
63     #: In the process of connecting or establishing a session.
64     CONNECTING = 1
65     #: Fully connected and active session.
66     RUNNING = 2
67     #: In the process of disconnecting.
68     #: Runstate may be returned to `IDLE` by calling `disconnect()`.
69     DISCONNECTING = 3
70
71
72 class ConnectError(QMPError):
73     """
74     Raised when the initial connection process has failed.
75
76     This Exception always wraps a "root cause" exception that can be
77     interrogated for additional information.
78
79     :param error_message: Human-readable string describing the error.
80     :param exc: The root-cause exception.
81     """
82     def __init__(self, error_message: str, exc: Exception):
83         super().__init__(error_message)
84         #: Human-readable error string
85         self.error_message: str = error_message
86         #: Wrapped root cause exception
87         self.exc: Exception = exc
88
89     def __str__(self) -> str:
90         cause = str(self.exc)
91         if not cause:
92             # If there's no error string, use the exception name.
93             cause = exception_summary(self.exc)
94         return f"{self.error_message}: {cause}"
95
96
97 class StateError(QMPError):
98     """
99     An API command (connect, execute, etc) was issued at an inappropriate time.
100
101     This error is raised when a command like
102     :py:meth:`~AsyncProtocol.connect()` is issued at an inappropriate
103     time.
104
105     :param error_message: Human-readable string describing the state violation.
106     :param state: The actual `Runstate` seen at the time of the violation.
107     :param required: The `Runstate` required to process this command.
108     """
109     def __init__(self, error_message: str,
110                  state: Runstate, required: Runstate):
111         super().__init__(error_message)
112         self.error_message = error_message
113         self.state = state
114         self.required = required
115
116
117 F = TypeVar('F', bound=Callable[..., Any])  # pylint: disable=invalid-name
118
119
120 # Don't Panic.
121 def require(required_state: Runstate) -> Callable[[F], F]:
122     """
123     Decorator: protect a method so it can only be run in a certain `Runstate`.
124
125     :param required_state: The `Runstate` required to invoke this method.
126     :raise StateError: When the required `Runstate` is not met.
127     """
128     def _decorator(func: F) -> F:
129         # _decorator is the decorator that is built by calling the
130         # require() decorator factory; e.g.:
131         #
132         # @require(Runstate.IDLE) def foo(): ...
133         # will replace 'foo' with the result of '_decorator(foo)'.
134
135         @wraps(func)
136         def _wrapper(proto: 'AsyncProtocol[Any]',
137                      *args: Any, **kwargs: Any) -> Any:
138             # _wrapper is the function that gets executed prior to the
139             # decorated method.
140
141             name = type(proto).__name__
142
143             if proto.runstate != required_state:
144                 if proto.runstate == Runstate.CONNECTING:
145                     emsg = f"{name} is currently connecting."
146                 elif proto.runstate == Runstate.DISCONNECTING:
147                     emsg = (f"{name} is disconnecting."
148                             " Call disconnect() to return to IDLE state.")
149                 elif proto.runstate == Runstate.RUNNING:
150                     emsg = f"{name} is already connected and running."
151                 elif proto.runstate == Runstate.IDLE:
152                     emsg = f"{name} is disconnected and idle."
153                 else:
154                     assert False
155                 raise StateError(emsg, proto.runstate, required_state)
156             # No StateError, so call the wrapped method.
157             return func(proto, *args, **kwargs)
158
159         # Return the decorated method;
160         # Transforming Func to Decorated[Func].
161         return cast(F, _wrapper)
162
163     # Return the decorator instance from the decorator factory. Phew!
164     return _decorator
165
166
167 class AsyncProtocol(Generic[T]):
168     """
169     AsyncProtocol implements a generic async message-based protocol.
170
171     This protocol assumes the basic unit of information transfer between
172     client and server is a "message", the details of which are left up
173     to the implementation. It assumes the sending and receiving of these
174     messages is full-duplex and not necessarily correlated; i.e. it
175     supports asynchronous inbound messages.
176
177     It is designed to be extended by a specific protocol which provides
178     the implementations for how to read and send messages. These must be
179     defined in `_do_recv()` and `_do_send()`, respectively.
180
181     Other callbacks have a default implementation, but are intended to be
182     either extended or overridden:
183
184      - `_establish_session`:
185          The base implementation starts the reader/writer tasks.
186          A protocol implementation can override this call, inserting
187          actions to be taken prior to starting the reader/writer tasks
188          before the super() call; actions needing to occur afterwards
189          can be written after the super() call.
190      - `_on_message`:
191          Actions to be performed when a message is received.
192      - `_cb_outbound`:
193          Logging/Filtering hook for all outbound messages.
194      - `_cb_inbound`:
195          Logging/Filtering hook for all inbound messages.
196          This hook runs *before* `_on_message()`.
197
198     :param name:
199         Name used for logging messages, if any. By default, messages
200         will log to 'qemu.aqmp.protocol', but each individual connection
201         can be given its own logger by giving it a name; messages will
202         then log to 'qemu.aqmp.protocol.${name}'.
203     """
204     # pylint: disable=too-many-instance-attributes
205
206     #: Logger object for debugging messages from this connection.
207     logger = logging.getLogger(__name__)
208
209     # Maximum allowable size of read buffer
210     _limit = (64 * 1024)
211
212     # -------------------------
213     # Section: Public interface
214     # -------------------------
215
216     def __init__(self, name: Optional[str] = None) -> None:
217         #: The nickname for this connection, if any.
218         self.name: Optional[str] = name
219         if self.name is not None:
220             self.logger = self.logger.getChild(self.name)
221
222         # stream I/O
223         self._reader: Optional[StreamReader] = None
224         self._writer: Optional[StreamWriter] = None
225
226         # Outbound Message queue
227         self._outgoing: asyncio.Queue[T]
228
229         # Special, long-running tasks:
230         self._reader_task: Optional[asyncio.Future[None]] = None
231         self._writer_task: Optional[asyncio.Future[None]] = None
232
233         # Aggregate of the above two tasks, used for Exception management.
234         self._bh_tasks: Optional[asyncio.Future[Tuple[None, None]]] = None
235
236         #: Disconnect task. The disconnect implementation runs in a task
237         #: so that asynchronous disconnects (initiated by the
238         #: reader/writer) are allowed to wait for the reader/writers to
239         #: exit.
240         self._dc_task: Optional[asyncio.Future[None]] = None
241
242         self._runstate = Runstate.IDLE
243         self._runstate_changed: Optional[asyncio.Event] = None
244
245         # Workaround for bind()
246         self._sock: Optional[socket.socket] = None
247
248         # Server state for start_server() and _incoming()
249         self._server: Optional[asyncio.AbstractServer] = None
250         self._accepted: Optional[asyncio.Event] = None
251
252     def __repr__(self) -> str:
253         cls_name = type(self).__name__
254         tokens = []
255         if self.name is not None:
256             tokens.append(f"name={self.name!r}")
257         tokens.append(f"runstate={self.runstate.name}")
258         return f"<{cls_name} {' '.join(tokens)}>"
259
260     @property  # @upper_half
261     def runstate(self) -> Runstate:
262         """The current `Runstate` of the connection."""
263         return self._runstate
264
265     @upper_half
266     async def runstate_changed(self) -> Runstate:
267         """
268         Wait for the `runstate` to change, then return that runstate.
269         """
270         await self._runstate_event.wait()
271         return self.runstate
272
273     @upper_half
274     @require(Runstate.IDLE)
275     async def start_server_and_accept(
276             self, address: SocketAddrT,
277             ssl: Optional[SSLContext] = None
278     ) -> None:
279         """
280         Accept a connection and begin processing message queues.
281
282         If this call fails, `runstate` is guaranteed to be set back to `IDLE`.
283
284         :param address:
285             Address to listen on; UNIX socket path or TCP address/port.
286         :param ssl: SSL context to use, if any.
287
288         :raise StateError: When the `Runstate` is not `IDLE`.
289         :raise ConnectError:
290             When a connection or session cannot be established.
291
292             This exception will wrap a more concrete one. In most cases,
293             the wrapped exception will be `OSError` or `EOFError`. If a
294             protocol-level failure occurs while establishing a new
295             session, the wrapped error may also be an `QMPError`.
296         """
297         await self._session_guard(
298             self._do_accept(address, ssl),
299             'Failed to establish connection')
300         await self._session_guard(
301             self._establish_session(),
302             'Failed to establish session')
303         assert self.runstate == Runstate.RUNNING
304
305     @upper_half
306     @require(Runstate.IDLE)
307     async def connect(self, address: SocketAddrT,
308                       ssl: Optional[SSLContext] = None) -> None:
309         """
310         Connect to the server and begin processing message queues.
311
312         If this call fails, `runstate` is guaranteed to be set back to `IDLE`.
313
314         :param address:
315             Address to connect to; UNIX socket path or TCP address/port.
316         :param ssl: SSL context to use, if any.
317
318         :raise StateError: When the `Runstate` is not `IDLE`.
319         :raise ConnectError:
320             When a connection or session cannot be established.
321
322             This exception will wrap a more concrete one. In most cases,
323             the wrapped exception will be `OSError` or `EOFError`. If a
324             protocol-level failure occurs while establishing a new
325             session, the wrapped error may also be an `QMPError`.
326         """
327         await self._session_guard(
328             self._do_connect(address, ssl),
329             'Failed to establish connection')
330         await self._session_guard(
331             self._establish_session(),
332             'Failed to establish session')
333         assert self.runstate == Runstate.RUNNING
334
335     @upper_half
336     async def disconnect(self) -> None:
337         """
338         Disconnect and wait for all tasks to fully stop.
339
340         If there was an exception that caused the reader/writers to
341         terminate prematurely, it will be raised here.
342
343         :raise Exception: When the reader or writer terminate unexpectedly.
344         """
345         self.logger.debug("disconnect() called.")
346         self._schedule_disconnect()
347         await self._wait_disconnect()
348
349     # --------------------------
350     # Section: Session machinery
351     # --------------------------
352
353     async def _session_guard(self, coro: Awaitable[None], emsg: str) -> None:
354         """
355         Async guard function used to roll back to `IDLE` on any error.
356
357         On any Exception, the state machine will be reset back to
358         `IDLE`. Most Exceptions will be wrapped with `ConnectError`, but
359         `BaseException` events will be left alone (This includes
360         asyncio.CancelledError, even prior to Python 3.8).
361
362         :param error_message:
363             Human-readable string describing what connection phase failed.
364
365         :raise BaseException:
366             When `BaseException` occurs in the guarded block.
367         :raise ConnectError:
368             When any other error is encountered in the guarded block.
369         """
370         # Note: After Python 3.6 support is removed, this should be an
371         # @asynccontextmanager instead of accepting a callback.
372         try:
373             await coro
374         except BaseException as err:
375             self.logger.error("%s: %s", emsg, exception_summary(err))
376             self.logger.debug("%s:\n%s\n", emsg, pretty_traceback())
377             try:
378                 # Reset the runstate back to IDLE.
379                 await self.disconnect()
380             except:
381                 # We don't expect any Exceptions from the disconnect function
382                 # here, because we failed to connect in the first place.
383                 # The disconnect() function is intended to perform
384                 # only cannot-fail cleanup here, but you never know.
385                 emsg = (
386                     "Unexpected bottom half exception. "
387                     "This is a bug in the QMP library. "
388                     "Please report it to <qemu-devel@nongnu.org> and "
389                     "CC: John Snow <jsnow@redhat.com>."
390                 )
391                 self.logger.critical("%s:\n%s\n", emsg, pretty_traceback())
392                 raise
393
394             # CancelledError is an Exception with special semantic meaning;
395             # We do NOT want to wrap it up under ConnectError.
396             # NB: CancelledError is not a BaseException before Python 3.8
397             if isinstance(err, asyncio.CancelledError):
398                 raise
399
400             # Any other kind of error can be treated as some kind of connection
401             # failure broadly. Inspect the 'exc' field to explore the root
402             # cause in greater detail.
403             if isinstance(err, Exception):
404                 raise ConnectError(emsg, err) from err
405
406             # Raise BaseExceptions un-wrapped, they're more important.
407             raise
408
409     @property
410     def _runstate_event(self) -> asyncio.Event:
411         # asyncio.Event() objects should not be created prior to entrance into
412         # an event loop, so we can ensure we create it in the correct context.
413         # Create it on-demand *only* at the behest of an 'async def' method.
414         if not self._runstate_changed:
415             self._runstate_changed = asyncio.Event()
416         return self._runstate_changed
417
418     @upper_half
419     @bottom_half
420     def _set_state(self, state: Runstate) -> None:
421         """
422         Change the `Runstate` of the protocol connection.
423
424         Signals the `runstate_changed` event.
425         """
426         if state == self._runstate:
427             return
428
429         self.logger.debug("Transitioning from '%s' to '%s'.",
430                           str(self._runstate), str(state))
431         self._runstate = state
432         self._runstate_event.set()
433         self._runstate_event.clear()
434
435     @bottom_half  # However, it does not run from the R/W tasks.
436     async def _stop_server(self) -> None:
437         """
438         Stop listening for / accepting new incoming connections.
439         """
440         if self._server is None:
441             return
442
443         try:
444             self.logger.debug("Stopping server.")
445             self._server.close()
446             await self._server.wait_closed()
447             self.logger.debug("Server stopped.")
448         finally:
449             self._server = None
450
451     @bottom_half  # However, it does not run from the R/W tasks.
452     async def _incoming(self,
453                         reader: asyncio.StreamReader,
454                         writer: asyncio.StreamWriter) -> None:
455         """
456         Accept an incoming connection and signal the upper_half.
457
458         This method does the minimum necessary to accept a single
459         incoming connection. It signals back to the upper_half ASAP so
460         that any errors during session initialization can occur
461         naturally in the caller's stack.
462
463         :param reader: Incoming `asyncio.StreamReader`
464         :param writer: Incoming `asyncio.StreamWriter`
465         """
466         peer = writer.get_extra_info('peername', 'Unknown peer')
467         self.logger.debug("Incoming connection from %s", peer)
468
469         if self._reader or self._writer:
470             # Sadly, we can have more than one pending connection
471             # because of https://bugs.python.org/issue46715
472             # Close any extra connections we don't actually want.
473             self.logger.warning("Extraneous connection inadvertently accepted")
474             writer.close()
475             return
476
477         # A connection has been accepted; stop listening for new ones.
478         assert self._accepted is not None
479         await self._stop_server()
480         self._reader, self._writer = (reader, writer)
481         self._accepted.set()
482
483     def _bind_hack(self, address: Union[str, Tuple[str, int]]) -> None:
484         """
485         Used to create a socket in advance of accept().
486
487         This is a workaround to ensure that we can guarantee timing of
488         precisely when a socket exists to avoid a connection attempt
489         bouncing off of nothing.
490
491         Python 3.7+ adds a feature to separate the server creation and
492         listening phases instead, and should be used instead of this
493         hack.
494         """
495         if isinstance(address, tuple):
496             family = socket.AF_INET
497         else:
498             family = socket.AF_UNIX
499
500         sock = socket.socket(family, socket.SOCK_STREAM)
501         sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
502
503         try:
504             sock.bind(address)
505         except:
506             sock.close()
507             raise
508
509         self._sock = sock
510
511     @upper_half
512     async def _do_accept(self, address: SocketAddrT,
513                          ssl: Optional[SSLContext] = None) -> None:
514         """
515         Acting as the transport server, accept a single connection.
516
517         :param address:
518             Address to listen on; UNIX socket path or TCP address/port.
519         :param ssl: SSL context to use, if any.
520
521         :raise OSError: For stream-related errors.
522         """
523         assert self.runstate == Runstate.IDLE
524         self._set_state(Runstate.CONNECTING)
525
526         self.logger.debug("Awaiting connection on %s ...", address)
527         self._accepted = asyncio.Event()
528
529         if isinstance(address, tuple):
530             coro = asyncio.start_server(
531                 self._incoming,
532                 host=None if self._sock else address[0],
533                 port=None if self._sock else address[1],
534                 ssl=ssl,
535                 backlog=1,
536                 limit=self._limit,
537                 sock=self._sock,
538             )
539         else:
540             coro = asyncio.start_unix_server(
541                 self._incoming,
542                 path=None if self._sock else address,
543                 ssl=ssl,
544                 backlog=1,
545                 limit=self._limit,
546                 sock=self._sock,
547             )
548
549         # Allow runstate watchers to witness 'CONNECTING' state; some
550         # failures in the streaming layer are synchronous and will not
551         # otherwise yield.
552         await asyncio.sleep(0)
553
554         self._server = await coro    # Starts listening
555         await self._accepted.wait()  # Waits for the callback to finish
556         assert self._server is None
557         self._sock = None
558
559         self.logger.debug("Connection accepted.")
560
561     @upper_half
562     async def _do_connect(self, address: SocketAddrT,
563                           ssl: Optional[SSLContext] = None) -> None:
564         """
565         Acting as the transport client, initiate a connection to a server.
566
567         :param address:
568             Address to connect to; UNIX socket path or TCP address/port.
569         :param ssl: SSL context to use, if any.
570
571         :raise OSError: For stream-related errors.
572         """
573         assert self.runstate == Runstate.IDLE
574         self._set_state(Runstate.CONNECTING)
575
576         # Allow runstate watchers to witness 'CONNECTING' state; some
577         # failures in the streaming layer are synchronous and will not
578         # otherwise yield.
579         await asyncio.sleep(0)
580
581         self.logger.debug("Connecting to %s ...", address)
582
583         if isinstance(address, tuple):
584             connect = asyncio.open_connection(
585                 address[0],
586                 address[1],
587                 ssl=ssl,
588                 limit=self._limit,
589             )
590         else:
591             connect = asyncio.open_unix_connection(
592                 path=address,
593                 ssl=ssl,
594                 limit=self._limit,
595             )
596         self._reader, self._writer = await connect
597
598         self.logger.debug("Connected.")
599
600     @upper_half
601     async def _establish_session(self) -> None:
602         """
603         Establish a new session.
604
605         Starts the readers/writer tasks; subclasses may perform their
606         own negotiations here. The Runstate will be RUNNING upon
607         successful conclusion.
608         """
609         assert self.runstate == Runstate.CONNECTING
610
611         self._outgoing = asyncio.Queue()
612
613         reader_coro = self._bh_loop_forever(self._bh_recv_message, 'Reader')
614         writer_coro = self._bh_loop_forever(self._bh_send_message, 'Writer')
615
616         self._reader_task = create_task(reader_coro)
617         self._writer_task = create_task(writer_coro)
618
619         self._bh_tasks = asyncio.gather(
620             self._reader_task,
621             self._writer_task,
622         )
623
624         self._set_state(Runstate.RUNNING)
625         await asyncio.sleep(0)  # Allow runstate_event to process
626
627     @upper_half
628     @bottom_half
629     def _schedule_disconnect(self) -> None:
630         """
631         Initiate a disconnect; idempotent.
632
633         This method is used both in the upper-half as a direct
634         consequence of `disconnect()`, and in the bottom-half in the
635         case of unhandled exceptions in the reader/writer tasks.
636
637         It can be invoked no matter what the `runstate` is.
638         """
639         if not self._dc_task:
640             self._set_state(Runstate.DISCONNECTING)
641             self.logger.debug("Scheduling disconnect.")
642             self._dc_task = create_task(self._bh_disconnect())
643
644     @upper_half
645     async def _wait_disconnect(self) -> None:
646         """
647         Waits for a previously scheduled disconnect to finish.
648
649         This method will gather any bottom half exceptions and re-raise
650         the one that occurred first; presuming it to be the root cause
651         of any subsequent Exceptions. It is intended to be used in the
652         upper half of the call chain.
653
654         :raise Exception:
655             Arbitrary exception re-raised on behalf of the reader/writer.
656         """
657         assert self.runstate == Runstate.DISCONNECTING
658         assert self._dc_task
659
660         aws: List[Awaitable[object]] = [self._dc_task]
661         if self._bh_tasks:
662             aws.insert(0, self._bh_tasks)
663         all_defined_tasks = asyncio.gather(*aws)
664
665         # Ensure disconnect is done; Exception (if any) is not raised here:
666         await asyncio.wait((self._dc_task,))
667
668         try:
669             await all_defined_tasks  # Raise Exceptions from the bottom half.
670         finally:
671             self._cleanup()
672             self._set_state(Runstate.IDLE)
673
674     @upper_half
675     def _cleanup(self) -> None:
676         """
677         Fully reset this object to a clean state and return to `IDLE`.
678         """
679         def _paranoid_task_erase(task: Optional['asyncio.Future[_U]']
680                                  ) -> Optional['asyncio.Future[_U]']:
681             # Help to erase a task, ENSURING it is fully quiesced first.
682             assert (task is None) or task.done()
683             return None if (task and task.done()) else task
684
685         assert self.runstate == Runstate.DISCONNECTING
686         self._dc_task = _paranoid_task_erase(self._dc_task)
687         self._reader_task = _paranoid_task_erase(self._reader_task)
688         self._writer_task = _paranoid_task_erase(self._writer_task)
689         self._bh_tasks = _paranoid_task_erase(self._bh_tasks)
690
691         self._reader = None
692         self._writer = None
693
694         # NB: _runstate_changed cannot be cleared because we still need it to
695         # send the final runstate changed event ...!
696
697     # ----------------------------
698     # Section: Bottom Half methods
699     # ----------------------------
700
701     @bottom_half
702     async def _bh_disconnect(self) -> None:
703         """
704         Disconnect and cancel all outstanding tasks.
705
706         It is designed to be called from its task context,
707         :py:obj:`~AsyncProtocol._dc_task`. By running in its own task,
708         it is free to wait on any pending actions that may still need to
709         occur in either the reader or writer tasks.
710         """
711         assert self.runstate == Runstate.DISCONNECTING
712
713         def _done(task: Optional['asyncio.Future[Any]']) -> bool:
714             return task is not None and task.done()
715
716         # Are we already in an error pathway? If either of the tasks are
717         # already done, or if we have no tasks but a reader/writer; we
718         # must be.
719         #
720         # NB: We can't use _bh_tasks to check for premature task
721         # completion, because it may not yet have had a chance to run
722         # and gather itself.
723         tasks = tuple(filter(None, (self._writer_task, self._reader_task)))
724         error_pathway = _done(self._reader_task) or _done(self._writer_task)
725         if not tasks:
726             error_pathway |= bool(self._reader) or bool(self._writer)
727
728         try:
729             # Try to flush the writer, if possible.
730             # This *may* cause an error and force us over into the error path.
731             if not error_pathway:
732                 await self._bh_flush_writer()
733         except BaseException as err:
734             error_pathway = True
735             emsg = "Failed to flush the writer"
736             self.logger.error("%s: %s", emsg, exception_summary(err))
737             self.logger.debug("%s:\n%s\n", emsg, pretty_traceback())
738             raise
739         finally:
740             # Cancel any still-running tasks (Won't raise):
741             if self._writer_task is not None and not self._writer_task.done():
742                 self.logger.debug("Cancelling writer task.")
743                 self._writer_task.cancel()
744             if self._reader_task is not None and not self._reader_task.done():
745                 self.logger.debug("Cancelling reader task.")
746                 self._reader_task.cancel()
747
748             # Close out the tasks entirely (Won't raise):
749             if tasks:
750                 self.logger.debug("Waiting for tasks to complete ...")
751                 await asyncio.wait(tasks)
752
753             # Lastly, close the stream itself. (*May raise*!):
754             await self._bh_close_stream(error_pathway)
755             self.logger.debug("Disconnected.")
756
757     @bottom_half
758     async def _bh_flush_writer(self) -> None:
759         if not self._writer_task:
760             return
761
762         self.logger.debug("Draining the outbound queue ...")
763         await self._outgoing.join()
764         if self._writer is not None:
765             self.logger.debug("Flushing the StreamWriter ...")
766             await flush(self._writer)
767
768     @bottom_half
769     async def _bh_close_stream(self, error_pathway: bool = False) -> None:
770         # NB: Closing the writer also implcitly closes the reader.
771         if not self._writer:
772             return
773
774         if not is_closing(self._writer):
775             self.logger.debug("Closing StreamWriter.")
776             self._writer.close()
777
778         self.logger.debug("Waiting for StreamWriter to close ...")
779         try:
780             await wait_closed(self._writer)
781         except Exception:  # pylint: disable=broad-except
782             # It's hard to tell if the Stream is already closed or
783             # not. Even if one of the tasks has failed, it may have
784             # failed for a higher-layered protocol reason. The
785             # stream could still be open and perfectly fine.
786             # I don't know how to discern its health here.
787
788             if error_pathway:
789                 # We already know that *something* went wrong. Let's
790                 # just trust that the Exception we already have is the
791                 # better one to present to the user, even if we don't
792                 # genuinely *know* the relationship between the two.
793                 self.logger.debug(
794                     "Discarding Exception from wait_closed:\n%s\n",
795                     pretty_traceback(),
796                 )
797             else:
798                 # Oops, this is a brand-new error!
799                 raise
800         finally:
801             self.logger.debug("StreamWriter closed.")
802
803     @bottom_half
804     async def _bh_loop_forever(self, async_fn: _TaskFN, name: str) -> None:
805         """
806         Run one of the bottom-half methods in a loop forever.
807
808         If the bottom half ever raises any exception, schedule a
809         disconnect that will terminate the entire loop.
810
811         :param async_fn: The bottom-half method to run in a loop.
812         :param name: The name of this task, used for logging.
813         """
814         try:
815             while True:
816                 await async_fn()
817         except asyncio.CancelledError:
818             # We have been cancelled by _bh_disconnect, exit gracefully.
819             self.logger.debug("Task.%s: cancelled.", name)
820             return
821         except BaseException as err:
822             self.logger.log(
823                 logging.INFO if isinstance(err, EOFError) else logging.ERROR,
824                 "Task.%s: %s",
825                 name, exception_summary(err)
826             )
827             self.logger.debug("Task.%s: failure:\n%s\n",
828                               name, pretty_traceback())
829             self._schedule_disconnect()
830             raise
831         finally:
832             self.logger.debug("Task.%s: exiting.", name)
833
834     @bottom_half
835     async def _bh_send_message(self) -> None:
836         """
837         Wait for an outgoing message, then send it.
838
839         Designed to be run in `_bh_loop_forever()`.
840         """
841         msg = await self._outgoing.get()
842         try:
843             await self._send(msg)
844         finally:
845             self._outgoing.task_done()
846
847     @bottom_half
848     async def _bh_recv_message(self) -> None:
849         """
850         Wait for an incoming message and call `_on_message` to route it.
851
852         Designed to be run in `_bh_loop_forever()`.
853         """
854         msg = await self._recv()
855         await self._on_message(msg)
856
857     # --------------------
858     # Section: Message I/O
859     # --------------------
860
861     @upper_half
862     @bottom_half
863     def _cb_outbound(self, msg: T) -> T:
864         """
865         Callback: outbound message hook.
866
867         This is intended for subclasses to be able to add arbitrary
868         hooks to filter or manipulate outgoing messages. The base
869         implementation does nothing but log the message without any
870         manipulation of the message.
871
872         :param msg: raw outbound message
873         :return: final outbound message
874         """
875         self.logger.debug("--> %s", str(msg))
876         return msg
877
878     @upper_half
879     @bottom_half
880     def _cb_inbound(self, msg: T) -> T:
881         """
882         Callback: inbound message hook.
883
884         This is intended for subclasses to be able to add arbitrary
885         hooks to filter or manipulate incoming messages. The base
886         implementation does nothing but log the message without any
887         manipulation of the message.
888
889         This method does not "handle" incoming messages; it is a filter.
890         The actual "endpoint" for incoming messages is `_on_message()`.
891
892         :param msg: raw inbound message
893         :return: processed inbound message
894         """
895         self.logger.debug("<-- %s", str(msg))
896         return msg
897
898     @upper_half
899     @bottom_half
900     async def _readline(self) -> bytes:
901         """
902         Wait for a newline from the incoming reader.
903
904         This method is provided as a convenience for upper-layer
905         protocols, as many are line-based.
906
907         This method *may* return a sequence of bytes without a trailing
908         newline if EOF occurs, but *some* bytes were received. In this
909         case, the next call will raise `EOFError`. It is assumed that
910         the layer 5 protocol will decide if there is anything meaningful
911         to be done with a partial message.
912
913         :raise OSError: For stream-related errors.
914         :raise EOFError:
915             If the reader stream is at EOF and there are no bytes to return.
916         :return: bytes, including the newline.
917         """
918         assert self._reader is not None
919         msg_bytes = await self._reader.readline()
920
921         if not msg_bytes:
922             if self._reader.at_eof():
923                 raise EOFError
924
925         return msg_bytes
926
927     @upper_half
928     @bottom_half
929     async def _do_recv(self) -> T:
930         """
931         Abstract: Read from the stream and return a message.
932
933         Very low-level; intended to only be called by `_recv()`.
934         """
935         raise NotImplementedError
936
937     @upper_half
938     @bottom_half
939     async def _recv(self) -> T:
940         """
941         Read an arbitrary protocol message.
942
943         .. warning::
944             This method is intended primarily for `_bh_recv_message()`
945             to use in an asynchronous task loop. Using it outside of
946             this loop will "steal" messages from the normal routing
947             mechanism. It is safe to use prior to `_establish_session()`,
948             but should not be used otherwise.
949
950         This method uses `_do_recv()` to retrieve the raw message, and
951         then transforms it using `_cb_inbound()`.
952
953         :return: A single (filtered, processed) protocol message.
954         """
955         message = await self._do_recv()
956         return self._cb_inbound(message)
957
958     @upper_half
959     @bottom_half
960     def _do_send(self, msg: T) -> None:
961         """
962         Abstract: Write a message to the stream.
963
964         Very low-level; intended to only be called by `_send()`.
965         """
966         raise NotImplementedError
967
968     @upper_half
969     @bottom_half
970     async def _send(self, msg: T) -> None:
971         """
972         Send an arbitrary protocol message.
973
974         This method will transform any outgoing messages according to
975         `_cb_outbound()`.
976
977         .. warning::
978             Like `_recv()`, this method is intended to be called by
979             the writer task loop that processes outgoing
980             messages. Calling it directly may circumvent logic
981             implemented by the caller meant to correlate outgoing and
982             incoming messages.
983
984         :raise OSError: For problems with the underlying stream.
985         """
986         msg = self._cb_outbound(msg)
987         self._do_send(msg)
988
989     @bottom_half
990     async def _on_message(self, msg: T) -> None:
991         """
992         Called to handle the receipt of a new message.
993
994         .. caution::
995             This is executed from within the reader loop, so be advised
996             that waiting on either the reader or writer task will lead
997             to deadlock. Additionally, any unhandled exceptions will
998             directly cause the loop to halt, so logic may be best-kept
999             to a minimum if at all possible.
1000
1001         :param msg: The incoming message, already logged/filtered.
1002         """
1003         # Nothing to do in the abstract case.