Skip to contentSkip to conversation

python: introduce Asynchronous QMP package

PATCH Superseded John Snow 4 participants 36 messages Jul 17, 2021 – Aug 3, 2021 2 messages not in the archive

v2 of 4 Superseded Latest is v4 →

lore
Share & tools
lore

John Snow

author
#0 lore raw

v2 cover python: introduce Asynchronous QMP package

GitLab: https://gitlab.com/jsnow/qemu/-/commits/python-async-qmp-aqmp
CI: https://gitlab.com/jsnow/qemu/-/pipelines/338508045
Docs: https://people.redhat.com/~jsnow/sphinx/html/qemu.aqmp.html

Hi!

This patch series adds an Asynchronous QMP package to the Python library. It offers a few improvements over the previous library:

- out-of-band support
- true asynchronous event support
- avoids undocumented interfaces abusing non-blocking sockets
- unit tests!
- documentation!

This library serves as the basis for a new qmp-shell program that will offer improved reconnection support, true asynchronous display of events, VM and job status update notifiers, and so on.

My intent is to eventually publish this library directly to PyPI as a standalone package. I would like to phase out our usage of the old QMP library over time; eventually replacing it entirely with this one.

This series looks big by line count, but it's *mostly* docstrings. Seriously!

This package has *no* external dependencies whatsoever.

Notes & Design
==============

Here are some notes on the design of how the library works, to serve as a primer for review; however I also **highly recommend** browsing the generated Sphinx documentation for this series.

Here's that link again:
https://people.redhat.com/~jsnow/sphinx/html/qemu.aqmp.html

The core machinery is split between the AsyncProtocol and QMP classes. AsyncProtocol provides the generic machinery, while QMP provides the QMP-specific details.

The design uses two independent coroutines that act as the "bottom half", a writer task and a reader task. These tasks run for the duration of the connection and independently send and receive messages, respectively.

A third task, disconnect, is scheduled asynchronously whenever an unrecoverable error occurs and facilitates coalescing of the other two tasks.

This diagram for how execute() operates may be helpful for understanding how AsyncProtocol is laid out. The arrows indicate the direction of a QMP message; the long horizontal dash indicates the separation between the upper and lower half of the event loop. The queue mechanisms between both dashes serve as the intermediaries between the upper and lower half.

                       +---------+
                       | caller  |
                       +---------+
                           ^ |
                           | v
                       +---------+
     +---------------> |execute()| -----------+
     |                 +---------+            |
     |                                        |
[-----------------------------------------------------------]
     |                                        |
     |                                        v
+----+------+    +----------------+    +------+-------+
| ExecQueue |    | EventListeners |    |Outbound Queue|
+----+------+    +----+-----------+    +------+-------+
     ^                ^                       |
     |                |                       |
[-----------------------------------------------------------]
     |                |                       |
     |                |                       v
  +--+----------------+---+       +-----------+-----------+
  | Reader Task/Coroutine |       | Writer Task/Coroutine |
  +-----------+-----------+       +-----------+-----------+
              ^                               |
              |                               v
        +-----+------+                  +-----+------+
        |StreamReader|                  |StreamWriter|
        +------------+                  +------------+

The caller will invoke execute(), which in turn will deposit a message in the outbound send queue. This will wake up the writer task, which well send the message over the wire.

The execute() method will then yield to wait for a reply delivered to an execution queue created solely for that execute statement.

When a message arrives, the Reader task will unblock and route the message either to the EventListener subsystem, or place it in the appropriate pending execution queue.

Once a message is placed in the pending execution queue, execute() will unblock and the execution will conclude, returning the result of the RPC call to the caller.

Patch Layout
============

Patches 1-4 add tiny pre-requisites, utilities, etc.
Patches 5-12 add a generic async message-based protocol class,
AsyncProtocol. They are split fairly small and should be reasonably self-contained.
Patches 13-15 check in more QMP-centric components. Patches 16-21 add qmp_client.py, with a new 'QMPClient()' class.
They're split into reasonably tiny pieces here.
Patches 22-23 add a few finishing touches, they are small patches.
Patch 24 adds unit tests. They're maybe a little messy yet, but
they've been quite helpful to me so far. Coverage of protocol.py is at about 86%.

Future Work
===========

These items are in progress:

- A synchronous QMP wrapper that allows this library to be easily used from non-async code; this will also allow me to prove it works well by demoing its replacement throughout iotests. I have all of iotests passing locally, but I am still seeing some failures on gitlab CI I need to diagnose, possibly a race condition somewhere.

- A QMP server class; to facilitate writing of unit tests. It's done, but needs some polish and tests.

- More unit tests for qmp_client.py, qmp_server.py and other modules.

Changelog
=========

V2:

Renamed classes/methods:

- Renamed qmp_protocol.py to qmp_client.py
- Renamed 'QMP' class to 'QMPClient'
- Renamed _begin_new_session() to _establish_session()
- Split _establish_connection() out from _new_session().
- Removed _results() method

Bugfixes:

- Suppress duplicate Exceptions when attempting to drain the StreamWriter
- Delay initialization of asyncio.Queue and asyncio.Event variables to _new_session or later -- they must not be created outside of the loop, even if they are not async functions.
- Rework runstate_changed events to guarantee visibility of events to waiters
- Improve connect()/accept() cleanup to work with asyncio.CancelledError, asyncio.TimeoutError
- No-argument form of Message() now succeeds properly.
- flush utility will correctly yield when data is below the "high water mark", giving the stream a chance to actually flush.
- Increase read buffer size to accommodate query-qmp-schema (Thanks Niteesh)

Ugly bits from V1 removed:

- Remove tertiary filtering from EventListener (for now), accompanying documentation removed from events.py
- Use asyncio.wait() instead of custom wait_task_done()
- MultiException is removed in favor of just raising the first Exception that occurs in the bottom half; other Exceptions if any are logged instead.

Improvements:

- QMPClient now allows ID-less execution statements via the _raw() interface.
- Add tests that grant ~86% coverage of protocol.py to the avocado test suite.
- Removed 'force' parameter from _bh_disconnect; the disconnection routine determines for itself if we are in the error pathway or not instead now. This removes any chance of duplicate calls to _schedule_disconnect accidentally dropping the 'force' setting.

Debugging/Testing changes:

- Add debug: bool parameter to asyncio_run utility wrapper
- Improve error messages for '@require' decorator
- Add debugging message for state change events
- Avoid flushing the StreamWriter if we don't have one (This circumstance only arises in testing, but it's helpful.)
- Improved __repr__ method for AsyncProtocol, and removed __str__ method. enforcing eval(__repr__(x)) == x does not make sense for AsyncProtocol.
- Misc logging message changes
- Add a suite of fancy Task debugging utilities.
- Most tracebacks now log at the DEBUG level instead of CRITICAL/ERROR/WARNING; In those error cases, a one-line summary is logged instead.

Misc. aesthetic changes:

- Misc docstring fixes, whitespace, etc.
- Reordered the definition of some methods to try and keep similar methods near each other (Moved _cleanup near _bh_disconnect in QMPClient.)

~ Shucks Howdy, Gee Golly!

John Snow (24):
python/aqmp: add asynchronous QMP (AQMP) subpackage python/aqmp: add error classes
python/pylint: Add exception for TypeVar names ('T') python/aqmp: add asyncio compatibility wrappers python/aqmp: add generic async message-based protocol support python/aqmp: add runstate state machine to AsyncProtocol python/aqmp: Add logging utility helpers python/aqmp: add logging to AsyncProtocol python/aqmp: add AsyncProtocol.accept() method python/aqmp: add configurable read buffer limit python/aqmp: add _cb_inbound and _cb_inbound logging hooks python/aqmp: add AsyncProtocol._readline() method python/aqmp: add QMP Message format
python/aqmp: add well-known QMP object models python/aqmp: add QMP event support
python/pylint: disable too-many-function-args python/aqmp: add QMP protocol support python/pylint: disable no-member check
python/aqmp: Add message routing to QMP protocol python/aqmp: add execute() interfaces
python/aqmp: add _raw() execution interface python/aqmp: add asyncio_run compatibility wrapper python/aqmp: add scary message
python/aqmp: add AsyncProtocol unit tests

 python/qemu/aqmp/__init__.py   |  58 +++
 python/qemu/aqmp/error.py      |  50 ++
 python/qemu/aqmp/events.py     | 706 ++++++++++++++++++++++++++
 python/qemu/aqmp/message.py    | 209 ++++++++
 python/qemu/aqmp/models.py     | 133 +++++
 python/qemu/aqmp/protocol.py   | 882 +++++++++++++++++++++++++++++++++
 python/qemu/aqmp/py.typed      |   0
 python/qemu/aqmp/qmp_client.py | 621 +++++++++++++++++++++++
 python/qemu/aqmp/util.py       | 207 ++++++++
 python/setup.cfg               |   5 +-
 python/tests/null_proto.py     |  67 +++
 python/tests/protocol.py       | 458 +++++++++++++++++
 12 files changed, 3395 insertions(+), 1 deletion(-)
 create mode 100644 python/qemu/aqmp/__init__.py
 create mode 100644 python/qemu/aqmp/error.py
 create mode 100644 python/qemu/aqmp/events.py
 create mode 100644 python/qemu/aqmp/message.py
 create mode 100644 python/qemu/aqmp/models.py
 create mode 100644 python/qemu/aqmp/protocol.py
 create mode 100644 python/qemu/aqmp/py.typed
 create mode 100644 python/qemu/aqmp/qmp_client.py
 create mode 100644 python/qemu/aqmp/util.py
 create mode 100644 python/tests/null_proto.py
 create mode 100644 python/tests/protocol.py
Signature · 1 line
2.31.1
author
#2 lore raw

PATCH v2 2/24 python/aqmp: add error classes

---
 python/qemu/aqmp/__init__.py |  4 +++
 python/qemu/aqmp/error.py    | 50 ++++++++++++++++++++++++++++++++++++
 2 files changed, 54 insertions(+)
 create mode 100644 python/qemu/aqmp/error.py
python/qemu/aqmp/__init__.py +4 -0
index 391141c9484..c97be950bf4 100644
@@ -21,7 +21,11 @@
 # This work is licensed under the terms of the GNU GPL, version 2.  See
 # the COPYING file in the top-level directory.
 
+from .error import AQMPError
+
 
 # The order of these fields impact the Sphinx documentation order.
 __all__ = (
+    # Exceptions
+    'AQMPError',
 )
python/qemu/aqmp/error.py new file +50 -0

50 lines not on this page · raw message

Signature · 1 line
2.31.1
author
#10 lore raw

PATCH v2 6/24 python/aqmp: add runstate state machine to AsyncProtocol

In reply to John Snow

This serves a few purposes:

1. Protect interfaces when it's not safe to call them (via @require)

2. Add an interface by which an async client can determine if the state has changed, for the purposes of connection management.

---
 python/qemu/aqmp/__init__.py |   5 +-
 python/qemu/aqmp/protocol.py | 159 ++++++++++++++++++++++++++++++++++-
 2 files changed, 159 insertions(+), 5 deletions(-)
python/qemu/aqmp/__init__.py +4 -1
index 5c0de72672d..ed65913c83e 100644
@@ -22,11 +22,14 @@
 # the COPYING file in the top-level directory.
 
 from .error import AQMPError
-from .protocol import ConnectError
+from .protocol import ConnectError, Runstate
 
 
 # The order of these fields impact the Sphinx documentation order.
 __all__ = (
+    # Classes
+    'Runstate',
+
     # Exceptions, most generic to most explicit
     'AQMPError',
     'ConnectError',
python/qemu/aqmp/protocol.py +155 -4

269 lines not on this page · raw message

Signature · 1 line
2.31.1
author
#13 lore raw

PATCH v2 9/24 python/aqmp: add AsyncProtocol.accept() method

In reply to John Snow

It's a little messier than connect, because it wasn't designed to accept *precisely one* connection. Such is life.

---
 python/qemu/aqmp/protocol.py | 89 ++++++++++++++++++++++++++++++++++--
 1 file changed, 85 insertions(+), 4 deletions(-)
python/qemu/aqmp/protocol.py +85 -4
index f9295546cda..99b9614ba94 100644
@@ -245,6 +245,24 @@ async def runstate_changed(self) -> Runstate:
         await self._runstate_event.wait()
         return self.runstate
 
+    @upper_half
+    @require(Runstate.IDLE)
+    async def accept(self, address: Union[str, Tuple[str, int]],
+                     ssl: Optional[SSLContext] = None) -> None:
+        """
+        Accept a connection and begin processing message queues.
+
+        If this call fails, `runstate` is guaranteed to be set back to `IDLE`.
+
+        :param address:
+            Address to listen to; UNIX socket path or TCP address/port.
+        :param ssl: SSL context to use, if any.
+
+        :raise StateError: When the `Runstate` is not `IDLE`.
+        :raise ConnectError: If a connection could not be accepted.
+        """
+        await self._new_session(address, ssl, accept=True)
+
     @upper_half
     @require(Runstate.IDLE)
     async def connect(self, address: Union[str, Tuple[str, int]],
@@ -309,7 +327,8 @@ def _set_state(self, state: Runstate) -> None:
     @upper_half
     async def _new_session(self,
                            address: Union[str, Tuple[str, int]],
-                           ssl: Optional[SSLContext] = None) -> None:
+                           ssl: Optional[SSLContext] = None,
+                           accept: bool = False) -> None:
         """
         Establish a new connection and initialize the session.
 
@@ -318,9 +337,10 @@ async def _new_session(self,
         to be set back to `IDLE`.
 
         :param address:
-            Address to connect to;
+            Address to connect to/listen on;
             UNIX socket path or TCP address/port.
         :param ssl: SSL context to use, if any.
+        :param accept: Accept a connection instead of connecting when `True`.
 
         :raise ConnectError:
             When a connection or session cannot be established.
@@ -334,7 +354,7 @@ async def _new_session(self,
 
         try:
             phase = "connection"
-            await self._establish_connection(address, ssl)
+            await self._establish_connection(address, ssl, accept)
 
             phase = "session"
             await self._establish_session()
@@ -368,6 +388,7 @@ async def _establish_connection(
             self,
             address: Union[str, Tuple[str, int]],
             ssl: Optional[SSLContext] = None,
+            accept: bool = False
     ) -> None:
         """
         Establish a new connection.
@@ -376,6 +397,7 @@ async def _establish_connection(
             Address to connect to/listen on;
             UNIX socket path or TCP address/port.
         :param ssl: SSL context to use, if any.
+        :param accept: Accept a connection instead of connecting when `True`.
         """
         assert self.runstate == Runstate.IDLE
         self._set_state(Runstate.CONNECTING)
@@ -385,7 +407,66 @@ async def _establish_connection(
         # otherwise yield.
         await asyncio.sleep(0)
 
-        await self._do_connect(address, ssl)
+        if accept:
+            await self._do_accept(address, ssl)
+        else:
+            await self._do_connect(address, ssl)
+
+    @upper_half
+    async def _do_accept(self, address: Union[str, Tuple[str, int]],
+                         ssl: Optional[SSLContext] = None) -> None:
+        """
+        Acting as the transport server, accept a single connection.
+
+        :param address:
+            Address to listen on; UNIX socket path or TCP address/port.
+        :param ssl: SSL context to use, if any.
+
+        :raise OSError: For stream-related errors.
+        """
+        self.logger.debug("Awaiting connection on %s ...", address)
+        connected = asyncio.Event()
+        server: Optional[asyncio.AbstractServer] = None
+
+        async def _client_connected_cb(reader: asyncio.StreamReader,
+                                       writer: asyncio.StreamWriter) -> None:
+            """Used to accept a single incoming connection, see below."""
+            nonlocal server
+            nonlocal connected
+
+            # A connection has been accepted; stop listening for new ones.
+            assert server is not None
+            server.close()
+            await server.wait_closed()
+            server = None
+
+            # Register this client as being connected
+            self._reader, self._writer = (reader, writer)
+
+            # Signal back: We've accepted a client!
+            connected.set()
+
+        if isinstance(address, tuple):
+            coro = asyncio.start_server(
+                _client_connected_cb,
+                host=address[0],
+                port=address[1],
+                ssl=ssl,
+                backlog=1,
+            )
+        else:
+            coro = asyncio.start_unix_server(
+                _client_connected_cb,
+                path=address,
+                ssl=ssl,
+                backlog=1,
+            )
+
+        server = await coro     # Starts listening
+        await connected.wait()  # Waits for the callback to fire (and finish)
+        assert server is None
+
+        self.logger.debug("Connection accepted.")
 
     @upper_half
     async def _do_connect(self, address: Union[str, Tuple[str, int]],
Signature · 1 line
2.31.1
author
#1 lore raw

PATCH v2 1/24 python/aqmp: add asynchronous QMP (AQMP) subpackage

In reply to John Snow

For now, it's empty! Soon, it won't be.

---
 python/qemu/aqmp/__init__.py | 27 +++++++++++++++++++++++++++
 python/qemu/aqmp/py.typed    |  0
 python/setup.cfg             |  1 +
 3 files changed, 28 insertions(+)
 create mode 100644 python/qemu/aqmp/__init__.py
 create mode 100644 python/qemu/aqmp/py.typed
python/qemu/aqmp/__init__.py new file +27 -0
new file mode 100644
index 00000000000..391141c9484
@@ -0,0 +1,27 @@
+"""
+QEMU Monitor Protocol (QMP) development library & tooling.
+
+This package provides a fairly low-level class for communicating
+asynchronously with QMP protocol servers, as implemented by QEMU, the
+QEMU Guest Agent, and the QEMU Storage Daemon.
+
+`QMPClient` provides the main functionality of this package. All errors
+raised by this library dervive from `AQMPError`, see `aqmp.error` for
+additional detail. See `aqmp.events` for an in-depth tutorial on
+managing QMP events.
+"""
+
+# Copyright (C) 2020, 2021 John Snow for Red Hat, Inc.
+#
+# Authors:
+#  John Snow <[email protected]>
+#
+# Based on earlier work by Luiz Capitulino <[email protected]>.
+#
+# This work is licensed under the terms of the GNU GPL, version 2.  See
+# the COPYING file in the top-level directory.
+
+
+# The order of these fields impact the Sphinx documentation order.
+__all__ = (
+)
python/qemu/aqmp/py.typed new file +0 -0
new file mode 100644
index 00000000000..e69de29bb2d
python/setup.cfg +1 -0
index 14bab902883..ffb754fa9e5 100644
@@ -27,6 +27,7 @@ packages =
     qemu.qmp
     qemu.machine
     qemu.utils
+    qemu.aqmp
 
 [options.package_data]
 * = py.typed
Signature · 1 line
2.31.1
author
#7 lore raw

PATCH v2 3/24 python/pylint: Add exception for TypeVar names ('T')

In reply to John Snow

'T' is a common TypeVar name, allow its use.

See also https://github.com/PyCQA/pylint/issues/3401 -- In the future, we might be able to have a separate list of acceptable names for TypeVars exclusively.

---
 python/setup.cfg | 1 +
 1 file changed, 1 insertion(+)
python/setup.cfg +1 -0
index ffb754fa9e5..f87e32177ab 100644
@@ -101,6 +101,7 @@ good-names=i,
            fh,  # fh = open(...)
            fd,  # fd = os.open(...)
            c,   # for c in string: ...
+           T,   # for TypeVars. See pylint#3401
 
 [pylint.similarities]
 # Ignore imports when computing similarities.
Signature · 1 line
2.31.1
author
#11 lore raw

PATCH v2 7/24 python/aqmp: Add logging utility helpers

In reply to John Snow
---
 python/qemu/aqmp/util.py | 56 ++++++++++++++++++++++++++++++++++++++++
 1 file changed, 56 insertions(+)
python/qemu/aqmp/util.py +56 -0
index 88abfc9eb22..70ef94ad600 100644
@@ -4,10 +4,15 @@
 This module provides asyncio utilities and compatibility wrappers for
 Python 3.6 to provide some features that otherwise become available in
 Python 3.7+.
+
+Various logging and debugging utilities are also provided, such as
+`exception_summary()` and `pretty_traceback()`, used primarily for
+adding information into the logging stream.
 """
 
 import asyncio
 import sys
+import traceback
 from typing import (
     Any,
     Coroutine,
@@ -130,3 +135,54 @@ async def wait_closed(writer: asyncio.StreamWriter) -> None:
     while not transport.is_closing():
         await asyncio.sleep(0)
     await flush(writer)
+
+
+# ----------------------------
+# Section: Logging & Debugging
+# ----------------------------
+
+
+def exception_summary(exc: BaseException) -> str:
+    """
+    Return a summary string of an arbitrary exception.
+
+    It will be of the form "ExceptionType: Error Message", if the error
+    string is non-empty, and just "ExceptionType" otherwise.
+    """
+    name = type(exc).__qualname__
+    smod = type(exc).__module__
+    if smod not in ("__main__", "builtins"):
+        name = smod + '.' + name
+
+    error = str(exc)
+    if error:
+        return f"{name}: {error}"
+    return name
+
+
+def pretty_traceback(prefix: str = "  | ") -> str:
+    """
+    Formats the current traceback, indented to provide visual distinction.
+
+    This is useful for printing a traceback within a traceback for
+    debugging purposes when encapsulating errors to deliver them up the
+    stack; when those errors are printed, this helps provide a nice
+    visual grouping to quickly identify the parts of the error that
+    belong to the inner exception.
+
+    :param prefix: The prefix to append to each line of the traceback.
+    :return: A string, formatted something like the following::
+
+      | Traceback (most recent call last):
+      |   File "foobar.py", line 42, in arbitrary_example
+      |     foo.baz()
+      | ArbitraryError: [Errno 42] Something bad happened!
+    """
+    output = "".join(traceback.format_exception(*sys.exc_info()))
+
+    exc_lines = []
+    for line in output.split('\n'):
+        exc_lines.append(prefix + line)
+
+    # The last line is always empty, omit it
+    return "\n".join(exc_lines[:-1])
Signature · 1 line
2.31.1
author
#18 lore raw

PATCH v2 12/24 python/aqmp: add AsyncProtocol._readline() method

In reply to John Snow

This is added as a courtesy: many protocols are line-based, including QMP. Putting it in AsyncProtocol lets us keep the QMP class implementation just a pinch more abstract.

(And, if we decide to add a QTEST implementation later, it will need this, too. (Yes, I have a QTEST implementation.))

---
 python/qemu/aqmp/protocol.py | 29 +++++++++++++++++++++++++++++
 1 file changed, 29 insertions(+)
python/qemu/aqmp/protocol.py +29 -0
index 6f83d3e3922..28cd5d9f4fd 100644
@@ -774,6 +774,35 @@ def _cb_inbound(self, msg: T) -> T:
         self.logger.debug("<-- %s", str(msg))
         return msg
 
+    @upper_half
+    @bottom_half
+    async def _readline(self) -> bytes:
+        """
+        Wait for a newline from the incoming reader.
+
+        This method is provided as a convenience for upper-layer
+        protocols, as many are line-based.
+
+        This method *may* return a sequence of bytes without a trailing
+        newline if EOF occurs, but *some* bytes were received. In this
+        case, the next call will raise `EOFError`. It is assumed that
+        the layer 5 protocol will decide if there is anything meaningful
+        to be done with a partial message.
+
+        :raise OSError: For stream-related errors.
+        :raise EOFError:
+            If the reader stream is at EOF and there are no bytes to return.
+        :return: bytes, including the newline.
+        """
+        assert self._reader is not None
+        msg_bytes = await self._reader.readline()
+
+        if not msg_bytes:
+            if self._reader.at_eof():
+                raise EOFError
+
+        return msg_bytes
+
     @upper_half
     @bottom_half
     async def _do_recv(self) -> T:
Signature · 1 line
2.31.1
author
#8 lore raw

PATCH v2 4/24 python/aqmp: add asyncio compatibility wrappers

In reply to John Snow

Python 3.6 does not have all of the goodies that Python 3.7 does, and I need to support both. Add some compatibility wrappers needed for this purpose.

(Note: Python 3.6 is EOL December 2021.)

---
 python/qemu/aqmp/util.py | 106 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 106 insertions(+)
 create mode 100644 python/qemu/aqmp/util.py
python/qemu/aqmp/util.py new file +106 -0
new file mode 100644
index 00000000000..7e7c2584d2b
@@ -0,0 +1,106 @@
+"""
+Miscellaneous Utilities
+
+This module provides asyncio utilities and compatibility wrappers for
+Python 3.6 to provide some features that otherwise become available in
+Python 3.7+.
+"""
+
+import asyncio
+import sys
+from typing import (
+    Any,
+    Coroutine,
+    Optional,
+    TypeVar,
+    cast,
+)
+
+
+T = TypeVar('T')
+
+
+# --------------------------
+# Section: Utility Functions
+# --------------------------
+
+
+async def flush(writer: asyncio.StreamWriter) -> None:
+    """
+    Utility function to ensure a StreamWriter is *fully* drained.
+
+    `asyncio.StreamWriter.drain` only promises we will return to below
+    the "high-water mark". This function ensures we flush the entire
+    buffer -- by setting the high water mark to 0 and then calling
+    drain. The flow control limits are restored after the call is
+    completed.
+    """
+    transport = cast(asyncio.WriteTransport, writer.transport)
+
+    # https://github.com/python/typeshed/issues/5779
+    low, high = transport.get_write_buffer_limits()  # type: ignore
+    transport.set_write_buffer_limits(0, 0)
+    try:
+        await writer.drain()
+    finally:
+        transport.set_write_buffer_limits(high, low)
+
+
+# -------------------------------
+# Section: Compatibility Wrappers
+# -------------------------------
+
+
+def create_task(coro: Coroutine[Any, Any, T],
+                loop: Optional[asyncio.AbstractEventLoop] = None
+                ) -> 'asyncio.Future[T]':
+    """
+    Python 3.6-compatible `asyncio.create_task` wrapper.
+
+    :param coro: The coroutine to execute in a task.
+    :param loop: Optionally, the loop to create the task in.
+
+    :return: An `asyncio.Future` object.
+    """
+    if sys.version_info >= (3, 7):
+        if loop is not None:
+            return loop.create_task(coro)
+        return asyncio.create_task(coro)  # pylint: disable=no-member
+
+    # Python 3.6:
+    return asyncio.ensure_future(coro, loop=loop)
+
+
+def is_closing(writer: asyncio.StreamWriter) -> bool:
+    """
+    Python 3.6-compatible `asyncio.StreamWriter.is_closing` wrapper.
+
+    :param writer: The `asyncio.StreamWriter` object.
+    :return: `True` if the writer is closing, or closed.
+    """
+    if sys.version_info >= (3, 7):
+        return writer.is_closing()
+
+    # Python 3.6:
+    transport = writer.transport
+    assert isinstance(transport, asyncio.WriteTransport)
+    return transport.is_closing()
+
+
+async def wait_closed(writer: asyncio.StreamWriter) -> None:
+    """
+    Python 3.6-compatible `asyncio.StreamWriter.wait_closed` wrapper.
+
+    :param writer: The `asyncio.StreamWriter` to wait on.
+    """
+    if sys.version_info >= (3, 7):
+        await writer.wait_closed()
+        return
+
+    # Python 3.6
+    transport = writer.transport
+    assert isinstance(transport, asyncio.WriteTransport)
+
+    while not transport.is_closing():
+        await asyncio.sleep(0)
+    await flush(writer)
Signature · 1 line
2.31.1
author
#9 lore raw

PATCH v2 5/24 python/aqmp: add generic async message-based protocol support

In reply to John Snow

This is the bare minimum that you need to establish a full-duplex async message-based protocol with Python's asyncio.

The features to be added in forthcoming commits are:

- Runstate tracking
- Logging
- Support for incoming connections via accept()
- _cb_outbound, _cb_inbound message hooks
- _readline() method

Some of the docstrings have dangling references, but they will resolve themselves within the next few commits, and have been tested at the conclusion of this series.

A note on the broad-except in _bh_disconnect:

I'm not sure if there's a more elegant solution here, but the problem is that if an Exception occurred in the underlying StreamReader/StreamWriter and causes one of the tasks to fail and schedule a disconnect, the disconnect method itself will re-stumble across the exact same Exception when attempting to close/flush the stream.

Ignoring this Exception means we *might* miss a brand new Exception that we didn't see already, but as we are in the process of tearing down the connection anyway, I don't believe it matters. This stanza only really cares that the writer is flushed and closed -- If it raises an Exception, we know for sure it is not active and running.

---
 python/qemu/aqmp/__init__.py |   4 +-
 python/qemu/aqmp/protocol.py | 508 +++++++++++++++++++++++++++++++++++
 python/qemu/aqmp/util.py     |  26 ++
 3 files changed, 537 insertions(+), 1 deletion(-)
 create mode 100644 python/qemu/aqmp/protocol.py
python/qemu/aqmp/__init__.py +3 -1
index c97be950bf4..5c0de72672d 100644
@@ -22,10 +22,12 @@
 # the COPYING file in the top-level directory.
 
 from .error import AQMPError
+from .protocol import ConnectError
 
 
 # The order of these fields impact the Sphinx documentation order.
 __all__ = (
-    # Exceptions
+    # Exceptions, most generic to most explicit
     'AQMPError',
+    'ConnectError',
 )
python/qemu/aqmp/protocol.py new file +508 -0

508 lines not on this page · raw message

python/qemu/aqmp/util.py +26 -0
index 7e7c2584d2b..88abfc9eb22 100644
@@ -46,6 +46,32 @@ async def flush(writer: asyncio.StreamWriter) -> None:
         transport.set_write_buffer_limits(high, low)
 
 
+def upper_half(func: T) -> T:
+    """
+    Do-nothing decorator that annotates a method as an "upper-half" method.
+
+    These methods must not call bottom-half functions directly, but can
+    schedule them to run.
+    """
+    return func
+
+
+def bottom_half(func: T) -> T:
+    """
+    Do-nothing decorator that annotates a method as a "bottom-half" method.
+
+    These methods must take great care to handle their own exceptions whenever
+    possible. If they go unhandled, they will cause termination of the loop.
+
+    These methods do not, in general, have the ability to directly
+    report information to a caller’s context and will usually be
+    collected as a Task result instead.
+
+    They must not call upper-half functions directly.
+    """
+    return func
+
+
 # -------------------------------
 # Section: Compatibility Wrappers
 # -------------------------------
Signature · 1 line
2.31.1
author
#24 lore raw

PATCH v2 18/24 python/pylint: disable no-member check

In reply to John Snow

mypy handles this better -- but we only need the workaround because pylint under Python 3.6 does not understand that a MutableMapping really does have a .get() method attached.

We could remove this again once 3.7 is our minimum.

---
 python/setup.cfg | 1 +
 1 file changed, 1 insertion(+)
python/setup.cfg +1 -0
index 19d5e154630..2573cd7bfb3 100644
@@ -89,6 +89,7 @@ ignore_missing_imports = True
 # no Warning level messages displayed, use "--disable=all --enable=classes
 # --disable=W".
 disable=too-many-function-args,  # mypy handles this with less false positives.
+        no-member,  # mypy also handles this better.
 
 [pylint.basic]
 # Good variable names which should always be accepted, separated by a comma.
Signature · 1 line
2.31.1
author
#19 lore raw

PATCH v2 13/24 python/aqmp: add QMP Message format

In reply to John Snow

The Message class is here primarily to serve as a solid type to use for mypy static typing for unambiguous annotation and documentation.

We can also stuff JSON serialization and deserialization into this class itself so it can be re-used even outside this infrastructure.

---
 python/qemu/aqmp/__init__.py |   4 +-
 python/qemu/aqmp/message.py  | 209 +++++++++++++++++++++++++++++++++++
 2 files changed, 212 insertions(+), 1 deletion(-)
 create mode 100644 python/qemu/aqmp/message.py
python/qemu/aqmp/__init__.py +3 -1
index ed65913c83e..035987c756c 100644
@@ -22,12 +22,14 @@
 # the COPYING file in the top-level directory.
 
 from .error import AQMPError
+from .message import Message
 from .protocol import ConnectError, Runstate
 
 
 # The order of these fields impact the Sphinx documentation order.
 __all__ = (
-    # Classes
+    # Classes, most to least important
+    'Message',
     'Runstate',
 
     # Exceptions, most generic to most explicit
python/qemu/aqmp/message.py new file +209 -0

209 lines not on this page · raw message

Signature · 1 line
2.31.1
author
#12 lore raw

PATCH v2 8/24 python/aqmp: add logging to AsyncProtocol

In reply to John Snow

Give the connection and the reader/writer tasks nicknames, and add logging statements throughout.

---
 python/qemu/aqmp/protocol.py | 71 ++++++++++++++++++++++++++++++++----
 1 file changed, 64 insertions(+), 7 deletions(-)
python/qemu/aqmp/protocol.py +64 -7
index 247b60c31a6..f9295546cda 100644
@@ -14,6 +14,7 @@
 from asyncio import StreamReader, StreamWriter
 from enum import Enum
 from functools import wraps
+import logging
 from ssl import SSLContext
 from typing import (
     Any,
@@ -31,8 +32,10 @@
 from .util import (
     bottom_half,
     create_task,
+    exception_summary,
     flush,
     is_closing,
+    pretty_traceback,
     upper_half,
     wait_closed,
 )
@@ -173,14 +176,28 @@ class AsyncProtocol(Generic[T]):
          can be written after the super() call.
      - `_on_message`:
          Actions to be performed when a message is received.
+
+    :param name:
+        Name used for logging messages, if any. By default, messages
+        will log to 'qemu.aqmp.protocol', but each individual connection
+        can be given its own logger by giving it a name; messages will
+        then log to 'qemu.aqmp.protocol.${name}'.
     """
     # pylint: disable=too-many-instance-attributes
 
+    #: Logger object for debugging messages from this connection.
+    logger = logging.getLogger(__name__)
+
     # -------------------------
     # Section: Public interface
     # -------------------------
 
-    def __init__(self) -> None:
+    def __init__(self, name: Optional[str] = None) -> None:
+        #: The nickname for this connection, if any.
+        self.name: Optional[str] = name
+        if self.name is not None:
+            self.logger = self.logger.getChild(self.name)
+
         # stream I/O
         self._reader: Optional[StreamReader] = None
         self._writer: Optional[StreamWriter] = None
@@ -207,6 +224,14 @@ def __init__(self) -> None:
         self._runstate = Runstate.IDLE
         self._runstate_changed: Optional[asyncio.Event] = None
 
+    def __repr__(self) -> str:
+        cls_name = type(self).__name__
+        tokens = []
+        if self.name is not None:
+            tokens.append(f"name={self.name!r}")
+        tokens.append(f"runstate={self.runstate.name}")
+        return f"<{cls_name} {' '.join(tokens)}>"
+
     @property  # @upper_half
     def runstate(self) -> Runstate:
         """The current `Runstate` of the connection."""
@@ -275,6 +300,8 @@ def _set_state(self, state: Runstate) -> None:
         if state == self._runstate:
             return
 
+        self.logger.debug("Transitioning from '%s' to '%s'.",
+                          str(self._runstate), str(state))
         self._runstate = state
         self._runstate_event.set()
         self._runstate_event.clear()
@@ -314,8 +341,15 @@ async def _new_session(self,
 
         except BaseException as err:
             emsg = f"Failed to establish {phase}"
-            # Reset from CONNECTING back to IDLE.
-            await self.disconnect()
+            self.logger.error("%s: %s", emsg, exception_summary(err))
+            self.logger.debug("%s:\n%s\n", emsg, pretty_traceback())
+            try:
+                # Reset from CONNECTING back to IDLE.
+                await self.disconnect()
+            except:
+                emsg = "Unexpected bottom half exception"
+                self.logger.critical("%s:\n%s\n", emsg, pretty_traceback())
+                raise
 
             # NB: CancelledError is not a BaseException before Python 3.8
             if isinstance(err, asyncio.CancelledError):
@@ -365,12 +399,16 @@ async def _do_connect(self, address: Union[str, Tuple[str, int]],
 
         :raise OSError: For stream-related errors.
         """
+        self.logger.debug("Connecting to %s ...", address)
+
         if isinstance(address, tuple):
             connect = asyncio.open_connection(address[0], address[1], ssl=ssl)
         else:
             connect = asyncio.open_unix_connection(path=address, ssl=ssl)
         self._reader, self._writer = await connect
 
+        self.logger.debug("Connected.")
+
     @upper_half
     async def _establish_session(self) -> None:
         """
@@ -384,8 +422,8 @@ async def _establish_session(self) -> None:
 
         self._outgoing = asyncio.Queue()
 
-        reader_coro = self._bh_loop_forever(self._bh_recv_message)
-        writer_coro = self._bh_loop_forever(self._bh_send_message)
+        reader_coro = self._bh_loop_forever(self._bh_recv_message, 'Reader')
+        writer_coro = self._bh_loop_forever(self._bh_send_message, 'Writer')
 
         self._reader_task = create_task(reader_coro)
         self._writer_task = create_task(writer_coro)
@@ -412,6 +450,7 @@ def _schedule_disconnect(self) -> None:
         """
         if not self._dc_task:
             self._set_state(Runstate.DISCONNECTING)
+            self.logger.debug("Scheduling disconnect.")
             self._dc_task = create_task(self._bh_disconnect())
 
     @upper_half
@@ -497,8 +536,10 @@ def _exception(
         # This implicitly closes the reader, too.
         if self._writer:
             if not is_closing(self._writer):
+                self.logger.debug("Closing StreamWriter.")
                 self._writer.close()
 
+            self.logger.debug("Waiting for StreamWriter to close ...")
             try:
                 await wait_closed(self._writer)
             except Exception as err:  # pylint: disable=broad-except
@@ -509,6 +550,10 @@ def _exception(
                         self._reader_task, self._writer_task))):
                     raise
 
+            self.logger.debug("StreamWriter closed.")
+
+        self.logger.debug("Disconnected.")
+
     @bottom_half
     async def _bh_stop_writer(self, force: bool = False) -> None:
         if not self._writer_task or self._writer_task.done():
@@ -516,10 +561,13 @@ async def _bh_stop_writer(self, force: bool = False) -> None:
 
         # If we're not in a hurry, drain the outbound queue.
         if not force:
+            self.logger.debug("Draining the outbound queue ...")
             await self._outgoing.join()
             if self._writer is not None:
+                self.logger.debug("Flushing the StreamWriter ...")
                 await flush(self._writer)
 
+        self.logger.debug("Cancelling writer task ...")
         self._writer_task.cancel()
         # Waits for the writer to finish but does NOT raise its exception.
         await asyncio.wait((self._writer_task,))
@@ -529,12 +577,13 @@ async def _bh_stop_reader(self) -> None:
         if not self._reader_task or self._reader_task.done():
             return
 
+        self.logger.debug("Cancelling reader task ...")
         self._reader_task.cancel()
         # Waits for the reader to finish but does NOT raise its exception.
         await asyncio.wait((self._reader_task,))
 
     @bottom_half
-    async def _bh_loop_forever(self, async_fn: _TaskFN) -> None:
+    async def _bh_loop_forever(self, async_fn: _TaskFN, name: str) -> None:
         """
         Run one of the bottom-half methods in a loop forever.
 
@@ -542,16 +591,24 @@ async def _bh_loop_forever(self, async_fn: _TaskFN) -> None:
         disconnect that will terminate the entire loop.
 
         :param async_fn: The bottom-half method to run in a loop.
+        :param name: The name of this task, used for logging.
         """
         try:
             while True:
                 await async_fn()
         except asyncio.CancelledError:
             # We have been cancelled by _bh_disconnect, exit gracefully.
+            self.logger.debug("Task.%s: cancelled.", name)
             return
-        except BaseException:
+        except BaseException as err:
+            self.logger.error("Task.%s: %s",
+                              name, exception_summary(err))
+            self.logger.debug("Task.%s: failure:\n%s\n",
+                              name, pretty_traceback())
             self._schedule_disconnect()
             raise
+        finally:
+            self.logger.debug("Task.%s: exiting.", name)
 
     @bottom_half
     async def _bh_send_message(self) -> None:
Signature · 1 line
2.31.1
author
#21 lore raw

PATCH v2 15/24 python/aqmp: add QMP event support

In reply to John Snow

This class was designed as a "mix-in" primarily so that the feature could be given its own treatment in its own python module.

It gets quite a bit too long otherwise.

---
 python/qemu/aqmp/__init__.py |   2 +
 python/qemu/aqmp/events.py   | 706 +++++++++++++++++++++++++++++++++++
 2 files changed, 708 insertions(+)
 create mode 100644 python/qemu/aqmp/events.py
python/qemu/aqmp/__init__.py +2 -0
index 035987c756c..084eb5ab3e8 100644
@@ -22,6 +22,7 @@
 # the COPYING file in the top-level directory.
 
 from .error import AQMPError
+from .events import EventListener
 from .message import Message
 from .protocol import ConnectError, Runstate
 
@@ -30,6 +31,7 @@
 __all__ = (
     # Classes, most to least important
     'Message',
+    'EventListener',
     'Runstate',
 
     # Exceptions, most generic to most explicit
python/qemu/aqmp/events.py new file +706 -0

706 lines not on this page · raw message

Signature · 1 line
2.31.1
author
#22 lore raw

PATCH v2 16/24 python/pylint: disable too-many-function-args

In reply to John Snow

too-many-function-args seems prone to failure when considering things like Method Resolution Order, which mypy gets correct. When dealing with multiple inheritance, pylint doesn't seem to understand which method will actually get called, while mypy does.

Remove the less powerful, redundant check.

---
 python/setup.cfg | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
python/setup.cfg +1 -1
index f87e32177ab..19d5e154630 100644
@@ -88,7 +88,7 @@ ignore_missing_imports = True
 # --enable=similarities". If you want to run only the classes checker, but have
 # no Warning level messages displayed, use "--disable=all --enable=classes
 # --disable=W".
-disable=
+disable=too-many-function-args,  # mypy handles this with less false positives.
 
 [pylint.basic]
 # Good variable names which should always be accepted, separated by a comma.
Signature · 1 line
2.31.1
author
#14 lore raw

PATCH v2 10/24 python/aqmp: add configurable read buffer limit

In reply to John Snow

QMP can transmit some pretty big messages, and the default limit of 64KB isn't sufficient. Make sure that we can configure it.

---
 python/qemu/aqmp/protocol.py | 18 ++++++++++++++++--
 1 file changed, 16 insertions(+), 2 deletions(-)
python/qemu/aqmp/protocol.py +16 -2
index 99b9614ba94..86002a52654 100644
@@ -188,6 +188,9 @@ class AsyncProtocol(Generic[T]):
     #: Logger object for debugging messages from this connection.
     logger = logging.getLogger(__name__)
 
+    # Maximum allowable size of read buffer
+    _limit = (64 * 1024)
+
     # -------------------------
     # Section: Public interface
     # -------------------------
@@ -453,6 +456,7 @@ async def _client_connected_cb(reader: asyncio.StreamReader,
                 port=address[1],
                 ssl=ssl,
                 backlog=1,
+                limit=self._limit,
             )
         else:
             coro = asyncio.start_unix_server(
@@ -460,6 +464,7 @@ async def _client_connected_cb(reader: asyncio.StreamReader,
                 path=address,
                 ssl=ssl,
                 backlog=1,
+                limit=self._limit,
             )
 
         server = await coro     # Starts listening
@@ -483,9 +488,18 @@ async def _do_connect(self, address: Union[str, Tuple[str, int]],
         self.logger.debug("Connecting to %s ...", address)
 
         if isinstance(address, tuple):
-            connect = asyncio.open_connection(address[0], address[1], ssl=ssl)
+            connect = asyncio.open_connection(
+                address[0],
+                address[1],
+                ssl=ssl,
+                limit=self._limit,
+            )
         else:
-            connect = asyncio.open_unix_connection(path=address, ssl=ssl)
+            connect = asyncio.open_unix_connection(
+                path=address,
+                ssl=ssl,
+                limit=self._limit,
+            )
         self._reader, self._writer = await connect
 
         self.logger.debug("Connected.")
Signature · 1 line
2.31.1
author
#20 lore raw

PATCH v2 14/24 python/aqmp: add well-known QMP object models

In reply to John Snow

The QMP spec doesn't define very many objects that are iron-clad in their format, but there are a few. This module makes it trivial to validate them without relying on an external third-party library.

---
 python/qemu/aqmp/models.py | 133 +++++++++++++++++++++++++++++++++++++
 1 file changed, 133 insertions(+)
 create mode 100644 python/qemu/aqmp/models.py
python/qemu/aqmp/models.py new file +133 -0
new file mode 100644
index 00000000000..24c94123ac0
@@ -0,0 +1,133 @@
+"""
+QMP Data Models
+
+This module provides simplistic data classes that represent the few
+structures that the QMP spec mandates; they are used to verify incoming
+data to make sure it conforms to spec.
+"""
+# pylint: disable=too-few-public-methods
+
+from collections import abc
+from typing import (
+    Any,
+    Mapping,
+    Optional,
+    Sequence,
+)
+
+
+class Model:
+    """
+    Abstract data model, representing some QMP object of some kind.
+
+    :param raw: The raw object to be validated.
+    :raise KeyError: If any required fields are absent.
+    :raise TypeError: If any required fields have the wrong type.
+    """
+    def __init__(self, raw: Mapping[str, Any]):
+        self._raw = raw
+
+    def _check_key(self, key: str) -> None:
+        if key not in self._raw:
+            raise KeyError(f"'{self._name}' object requires '{key}' member")
+
+    def _check_value(self, key: str, type_: type, typestr: str) -> None:
+        assert key in self._raw
+        if not isinstance(self._raw[key], type_):
+            raise TypeError(
+                f"'{self._name}' member '{key}' must be a {typestr}"
+            )
+
+    def _check_member(self, key: str, type_: type, typestr: str) -> None:
+        self._check_key(key)
+        self._check_value(key, type_, typestr)
+
+    @property
+    def _name(self) -> str:
+        return type(self).__name__
+
+    def __repr__(self) -> str:
+        return f"{self._name}({self._raw!r})"
+
+
+class Greeting(Model):
+    """
+    Defined in qmp-spec.txt, section 2.2, "Server Greeting".
+
+    :param raw: The raw Greeting object.
+    :raise KeyError: If any required fields are absent.
+    :raise TypeError: If any required fields have the wrong type.
+    """
+    def __init__(self, raw: Mapping[str, Any]):
+        super().__init__(raw)
+        #: 'QMP' member
+        self.QMP: QMPGreeting  # pylint: disable=invalid-name
+
+        self._check_member('QMP', abc.Mapping, "JSON object")
+        self.QMP = QMPGreeting(self._raw['QMP'])
+
+
+class QMPGreeting(Model):
+    """
+    Defined in qmp-spec.txt, section 2.2, "Server Greeting".
+
+    :param raw: The raw QMPGreeting object.
+    :raise KeyError: If any required fields are absent.
+    :raise TypeError: If any required fields have the wrong type.
+    """
+    def __init__(self, raw: Mapping[str, Any]):
+        super().__init__(raw)
+        #: 'version' member
+        self.version: Mapping[str, object]
+        #: 'capabilities' member
+        self.capabilities: Sequence[object]
+
+        self._check_member('version', abc.Mapping, "JSON object")
+        self.version = self._raw['version']
+
+        self._check_member('capabilities', abc.Sequence, "JSON array")
+        self.capabilities = self._raw['capabilities']
+
+
+class ErrorResponse(Model):
+    """
+    Defined in qmp-spec.txt, section 2.4.2, "error".
+
+    :param raw: The raw ErrorResponse object.
+    :raise KeyError: If any required fields are absent.
+    :raise TypeError: If any required fields have the wrong type.
+    """
+    def __init__(self, raw: Mapping[str, Any]):
+        super().__init__(raw)
+        #: 'error' member
+        self.error: ErrorInfo
+        #: 'id' member
+        self.id: Optional[object] = None  # pylint: disable=invalid-name
+
+        self._check_member('error', abc.Mapping, "JSON object")
+        self.error = ErrorInfo(self._raw['error'])
+
+        if 'id' in raw:
+            self.id = raw['id']
+
+
+class ErrorInfo(Model):
+    """
+    Defined in qmp-spec.txt, section 2.4.2, "error".
+
+    :param raw: The raw ErrorInfo object.
+    :raise KeyError: If any required fields are absent.
+    :raise TypeError: If any required fields have the wrong type.
+    """
+    def __init__(self, raw: Mapping[str, Any]):
+        super().__init__(raw)
+        #: 'class' member, with an underscore to avoid conflicts in Python.
+        self.class_: str
+        #: 'desc' member
+        self.desc: str
+
+        self._check_member('class', str, "string")
+        self.class_ = self._raw['class']
+
+        self._check_member('desc', str, "string")
+        self.desc = self._raw['desc']
Signature · 1 line
2.31.1
author
#30 lore raw

PATCH v2 24/24 python/aqmp: add AsyncProtocol unit tests

In reply to John Snow

This tests most of protocol.py -- From a hacked up Coverage.py run, it's at about 86%. There's a few error cases that aren't very well tested yet, they're hard to induce artificially so far. I'm working on it.

---
 python/tests/null_proto.py |  67 ++++++
 python/tests/protocol.py   | 458 +++++++++++++++++++++++++++++++++++++
 2 files changed, 525 insertions(+)
 create mode 100644 python/tests/null_proto.py
 create mode 100644 python/tests/protocol.py
python/tests/null_proto.py new file +67 -0
new file mode 100644
index 00000000000..c697efc0001
@@ -0,0 +1,67 @@
+import asyncio
+
+from qemu.aqmp.protocol import AsyncProtocol
+
+
+class NullProtocol(AsyncProtocol[None]):
+    """
+    NullProtocol is a test mockup of an AsyncProtocol implementation.
+
+    It adds a fake_session instance variable that enables a code path
+    that bypasses the actual connection logic, but still allows the
+    reader/writers to start.
+
+    Because the message type is defined as None, an asyncio.Event named
+    'trigger_input' is created that prohibits the reader from
+    incessantly being able to yield None; this input can be poked to
+    simulate an incoming message.
+
+    For testing symmetry with do_recv, an interface is added to "send" a
+    Null message.
+
+    For testing purposes, a "simulate_disconnection" method is also
+    added which allows us to trigger a bottom half disconnect without
+    injecting any real errors into the reader/writer loops; in essence
+    it performs exactly half of what disconnect() normally does.
+    """
+    def __init__(self, name=None):
+        self.fake_session = False
+        self.trigger_input: asyncio.Event
+        super().__init__(name)
+
+    async def _establish_session(self):
+        self.trigger_input = asyncio.Event()
+        await super()._establish_session()
+
+    async def _do_accept(self, address, ssl=None):
+        if not self.fake_session:
+            await super()._do_accept(address, ssl)
+
+    async def _do_connect(self, address, ssl=None):
+        if not self.fake_session:
+            await super()._do_connect(address, ssl)
+
+    async def _do_recv(self) -> None:
+        await self.trigger_input.wait()
+        self.trigger_input.clear()
+
+    def _do_send(self, msg: None) -> None:
+        pass
+
+    async def send_msg(self) -> None:
+        await self._outgoing.put(None)
+
+    async def simulate_disconnect(self) -> None:
+        # Simulates a bottom half disconnect, e.g. schedules a
+        # disconnection but does not wait for it to complete. This is
+        # used to put the loop into the DISCONNECTING state without
+        # fully quiescing it back to IDLE; this is normally something
+        # you cannot coax AsyncProtocol to do on purpose, but it will be
+        # similar to what happens with an unhandled Exception in the
+        # reader/writer.
+        #
+        # Under normal circumstances, the library design requires you to
+        # await on disconnect(), which awaits the disconnect task and
+        # returns bottom half errors as a pre-condition to allowing the
+        # loop to return back to IDLE.
+        self._schedule_disconnect()
python/tests/protocol.py new file +458 -0

458 lines not on this page · raw message

Signature · 1 line
2.31.1
author
#15 lore raw

PATCH v2 11/24 python/aqmp: add _cb_inbound and _cb_inbound logging hooks

In reply to John Snow

Add hooks designed to log/filter incoming/outgoing messages. The primary intent for these is to be able to support iotests which may want to log messages with specific filters for reproducible output.

Another use is for plugging into Urwid frameworks; all messages in/out can be automatically added to a rendering list for the purposes of a qmp-shell like tool.

---
 python/qemu/aqmp/protocol.py | 50 +++++++++++++++++++++++++++++++++---
 1 file changed, 46 insertions(+), 4 deletions(-)
python/qemu/aqmp/protocol.py +46 -4
index 86002a52654..6f83d3e3922 100644
@@ -176,6 +176,11 @@ class AsyncProtocol(Generic[T]):
          can be written after the super() call.
      - `_on_message`:
          Actions to be performed when a message is received.
+     - `_cb_outbound`:
+         Logging/Filtering hook for all outbound messages.
+     - `_cb_inbound`:
+         Logging/Filtering hook for all inbound messages.
+         This hook runs *before* `_on_message()`.
 
     :param name:
         Name used for logging messages, if any. By default, messages
@@ -732,6 +737,43 @@ async def _bh_recv_message(self) -> None:
     # Section: Message I/O
     # --------------------
 
+    @upper_half
+    @bottom_half
+    def _cb_outbound(self, msg: T) -> T:
+        """
+        Callback: outbound message hook.
+
+        This is intended for subclasses to be able to add arbitrary
+        hooks to filter or manipulate outgoing messages. The base
+        implementation does nothing but log the message without any
+        manipulation of the message.
+
+        :param msg: raw outbound message
+        :return: final outbound message
+        """
+        self.logger.debug("--> %s", str(msg))
+        return msg
+
+    @upper_half
+    @bottom_half
+    def _cb_inbound(self, msg: T) -> T:
+        """
+        Callback: inbound message hook.
+
+        This is intended for subclasses to be able to add arbitrary
+        hooks to filter or manipulate incoming messages. The base
+        implementation does nothing but log the message without any
+        manipulation of the message.
+
+        This method does not "handle" incoming messages; it is a filter.
+        The actual "endpoint" for incoming messages is `_on_message()`.
+
+        :param msg: raw inbound message
+        :return: processed inbound message
+        """
+        self.logger.debug("<-- %s", str(msg))
+        return msg
+
     @upper_half
     @bottom_half
     async def _do_recv(self) -> T:
@@ -760,8 +802,8 @@ async def _recv(self) -> T:
 
         :return: A single (filtered, processed) protocol message.
         """
-        # A forthcoming commit makes this method less trivial.
-        return await self._do_recv()
+        message = await self._do_recv()
+        return self._cb_inbound(message)
 
     @upper_half
     @bottom_half
@@ -791,7 +833,7 @@ async def _send(self, msg: T) -> None:
 
         :raise OSError: For problems with the underlying stream.
         """
-        # A forthcoming commit makes this method less trivial.
+        msg = self._cb_outbound(msg)
         self._do_send(msg)
 
     @bottom_half
@@ -806,6 +848,6 @@ async def _on_message(self, msg: T) -> None:
             directly cause the loop to halt, so logic may be best-kept
             to a minimum if at all possible.
 
-        :param msg: The incoming message
+        :param msg: The incoming message, already logged/filtered.
         """
         # Nothing to do in the abstract case.
Signature · 1 line
2.31.1
author
#25 lore raw

PATCH v2 19/24 python/aqmp: Add message routing to QMP protocol

In reply to John Snow

Add the ability to handle and route messages in qmp_protocol.py. The interface for actually sending anything still isn't added until next commit.

---
 python/qemu/aqmp/qmp_client.py | 122 ++++++++++++++++++++++++++++++++-
 1 file changed, 120 insertions(+), 2 deletions(-)
python/qemu/aqmp/qmp_client.py +120 -2
index 000ff59c7a7..fa0cc7c5ae5 100644
@@ -7,15 +7,19 @@
 accept an incoming connection from that server.
 """
 
+# The import workarounds here are fixed in the next commit.
+import asyncio  # pylint: disable=unused-import # noqa
 import logging
 from typing import (
     Dict,
     List,
     Mapping,
     Optional,
+    Union,
+    cast,
 )
 
-from .error import ProtocolError
+from .error import AQMPError, ProtocolError
 from .events import Events
 from .message import Message
 from .models import Greeting
@@ -61,6 +65,53 @@ class NegotiationError(_WrappedProtocolError):
     """
 
 
+class ExecInterruptedError(AQMPError):
+    """
+    Exception raised when an RPC is interrupted.
+
+    This error is raised when an execute() statement could not be
+    completed.  This can occur because the connection itself was
+    terminated before a reply was received.
+
+    The true cause of the interruption will be available via `disconnect()`.
+    """
+
+
+class _MsgProtocolError(ProtocolError):
+    """
+    Abstract error class for protocol errors that have a `Message` object.
+
+    This Exception class is used for protocol errors where the `Message`
+    was mechanically understood, but was found to be inappropriate or
+    malformed.
+
+    :param error_message: Human-readable string describing the error.
+    :param msg: The QMP `Message` that caused the error.
+    """
+    def __init__(self, error_message: str, msg: Message):
+        super().__init__(error_message)
+        #: The received `Message` that caused the error.
+        self.msg: Message = msg
+
+    def __str__(self) -> str:
+        return "\n".join([
+            super().__str__(),
+            f"  Message was: {str(self.msg)}\n",
+        ])
+
+
+class ServerParseError(_MsgProtocolError):
+    """
+    The Server sent a `Message` indicating parsing failure.
+
+    i.e. A reply has arrived from the server, but it is missing the "ID"
+    field, indicating a parsing error.
+
+    :param error_message: Human-readable string describing the error.
+    :param msg: The QMP `Message` that caused the error.
+    """
+
+
 class QMPClient(AsyncProtocol[Message], Events):
     """
     Implements a QMP client connection.
@@ -106,6 +157,9 @@ async def run(self, address='/tmp/qemu.socket'):
     # Read buffer limit; large enough to accept query-qmp-schema
     _limit = (256 * 1024)
 
+    # Type alias for pending execute() result items
+    _PendingT = Union[Message, ExecInterruptedError]
+
     def __init__(self, name: Optional[str] = None) -> None:
         super().__init__(name)
         Events.__init__(self)
@@ -120,6 +174,12 @@ def __init__(self, name: Optional[str] = None) -> None:
         # Cached Greeting, if one was awaited.
         self._greeting: Optional[Greeting] = None
 
+        # Incoming RPC reply messages.
+        self._pending: Dict[
+            Union[str, None],
+            'asyncio.Queue[QMPClient._PendingT]'
+        ] = {}
+
     @upper_half
     async def _establish_session(self) -> None:
         """
@@ -132,6 +192,9 @@ async def _establish_session(self) -> None:
         :raise EOFError: When the server unexpectedly hangs up.
         :raise OSError: For underlying stream errors.
         """
+        self._greeting = None
+        self._pending = {}
+
         if self.await_greeting or self.negotiate:
             self._greeting = await self._get_greeting()
 
@@ -203,10 +266,33 @@ async def _negotiate(self) -> None:
             self.logger.debug("%s:\n%s\n", emsg, pretty_traceback())
             raise
 
+    @bottom_half
+    async def _bh_disconnect(self) -> None:
+        try:
+            await super()._bh_disconnect()
+        finally:
+            if self._pending:
+                self.logger.debug("Cancelling pending executions")
+            keys = self._pending.keys()
+            for key in keys:
+                self.logger.debug("Cancelling execution '%s'", key)
+                self._pending[key].put_nowait(
+                    ExecInterruptedError("Disconnected")
+                )
+
+            self.logger.debug("QMP Disconnected.")
+
+    @upper_half
+    def _cleanup(self) -> None:
+        super()._cleanup()
+        assert not self._pending
+
     @bottom_half
     async def _on_message(self, msg: Message) -> None:
         """
         Add an incoming message to the appropriate queue/handler.
+
+        :raise ServerParseError: When Message indicates server parse failure.
         """
         # Incoming messages are not fully parsed/validated here;
         # do only light peeking to know how to route the messages.
@@ -216,7 +302,39 @@ async def _on_message(self, msg: Message) -> None:
             return
 
         # Below, we assume everything left is an execute/exec-oob response.
-        # ... Which we'll implement in the next commit!
+
+        exec_id = cast(Optional[str], msg.get('id'))
+
+        if exec_id in self._pending:
+            await self._pending[exec_id].put(msg)
+            return
+
+        # We have a message we can't route back to a caller.
+
+        is_error = 'error' in msg
+        has_id = 'id' in msg
+
+        if is_error and not has_id:
+            # This is very likely a server parsing error.
+            # It doesn't inherently belong to any pending execution.
+            # Instead of performing clever recovery, just terminate.
+            # See "NOTE" in qmp-spec.txt, section 2.4.2
+            raise ServerParseError(
+                ("Server sent an error response without an ID, "
+                 "but there are no ID-less executions pending. "
+                 "Assuming this is a server parser failure."),
+                msg
+            )
+
+        # qmp-spec.txt, section 2.4:
+        # 'Clients should drop all the responses
+        # that have an unknown "id" field.'
+        self.logger.log(
+            logging.ERROR if is_error else logging.WARNING,
+            "Unknown ID '%s', message dropped.",
+            exec_id,
+        )
+        self.logger.debug("Unroutable message: %s", str(msg))
 
     @upper_half
     @bottom_half
Signature · 1 line
2.31.1
author
#23 lore raw

PATCH v2 17/24 python/aqmp: add QMP protocol support

In reply to John Snow

The star of our show!

Add most of the QMP protocol, sans support for actually executing commands. No problem, that happens in the next several commits.

---
 python/qemu/aqmp/__init__.py   |   2 +
 python/qemu/aqmp/qmp_client.py | 264 +++++++++++++++++++++++++++++++++
 2 files changed, 266 insertions(+)
 create mode 100644 python/qemu/aqmp/qmp_client.py
python/qemu/aqmp/__init__.py +2 -0
index 084eb5ab3e8..7bd66a48bed 100644
@@ -25,11 +25,13 @@
 from .events import EventListener
 from .message import Message
 from .protocol import ConnectError, Runstate
+from .qmp_client import QMPClient
 
 
 # The order of these fields impact the Sphinx documentation order.
 __all__ = (
     # Classes, most to least important
+    'QMPClient',
     'Message',
     'EventListener',
     'Runstate',
python/qemu/aqmp/qmp_client.py new file +264 -0

264 lines not on this page · raw message

Signature · 1 line
2.31.1
author
#26 lore raw

PATCH v2 20/24 python/aqmp: add execute() interfaces

In reply to John Snow

Add execute() and execute_msg().

_execute() is split into _issue() and _reply() halves so that hypothetical subclasses of QMP that want to support different execution paradigms can do so.

I anticipate a synchronous interface may have need of separating the send/reply phases. However, I do not wish to expose that interface here and want to actively discourage it, so they remain private interfaces.

---
 python/qemu/aqmp/__init__.py   |   4 +-
 python/qemu/aqmp/qmp_client.py | 202 +++++++++++++++++++++++++++++++--
 2 files changed, 198 insertions(+), 8 deletions(-)
python/qemu/aqmp/__init__.py +3 -1
index 7bd66a48bed..ef2903fa7fc 100644
@@ -25,7 +25,7 @@
 from .events import EventListener
 from .message import Message
 from .protocol import ConnectError, Runstate
-from .qmp_client import QMPClient
+from .qmp_client import ExecInterruptedError, ExecuteError, QMPClient
 
 
 # The order of these fields impact the Sphinx documentation order.
@@ -39,4 +39,6 @@
     # Exceptions, most generic to most explicit
     'AQMPError',
     'ConnectError',
+    'ExecuteError',
+    'ExecInterruptedError',
 )
python/qemu/aqmp/qmp_client.py +195 -7

249 lines not on this page · raw message

Signature · 1 line
2.31.1
author
#27 lore raw

PATCH v2 21/24 python/aqmp: add _raw() execution interface

In reply to John Snow

This is added in anticipation of wanting it for a synchronous wrapper for the iotest interface. Normally, execute() and execute_msg() both raise QMP errors in the form of Python exceptions.

Many iotests expect the entire reply as-is. To reduce churn there, add a private execution interface that will ease transition churn. However, I do not wish to encourage its use, so it will remain a private interface.

---
 python/qemu/aqmp/qmp_client.py | 51 ++++++++++++++++++++++++++++++++++
 1 file changed, 51 insertions(+)
python/qemu/aqmp/qmp_client.py +51 -0
index 879348feaaa..82e9dab124c 100644
@@ -484,6 +484,57 @@ async def _execute(self, msg: Message, assign_id: bool = True) -> Message:
         exec_id = await self._issue(msg)
         return await self._reply(exec_id)
 
+    @upper_half
+    @require(Runstate.RUNNING)
+    async def _raw(
+            self,
+            msg: Union[Message, Mapping[str, object], bytes],
+            assign_id: bool = True,
+    ) -> Message:
+        """
+        Issue a raw `Message` to the QMP server and await a reply.
+
+        :param msg:
+            A Message to send to the server. It may be a `Message`, any
+            Mapping (including Dict), or raw bytes.
+        :param assign_id:
+            Assign an arbitrary execution ID to this message. If
+            `False`, the existing id must either be absent (and no other
+            such pending execution may omit an ID) or a string. If it is
+            a string, it must not start with '__aqmp#' and no other such
+            pending execution may currently be using that ID.
+
+        :return: Execution reply from the server.
+
+        :raise ExecInterruptedError:
+            When the reply could not be retrieved because the connection
+            was lost, or some other problem.
+        :raise TypeError:
+            When assign_id is `False`, an ID is given, and it is not a string.
+        :raise ValueError:
+            When assign_id is `False`, but the ID is not usable;
+            Either because it starts with '__aqmp#' or it is already in-use.
+        """
+        # 1. convert generic Mapping or bytes to a QMP Message
+        # 2. copy Message objects so that we assign an ID only to the copy.
+        msg = Message(msg)
+
+        exec_id = msg.get('id')
+        if not assign_id and 'id' in msg:
+            if not isinstance(exec_id, str):
+                raise TypeError(f"ID ('{exec_id}') must be a string.")
+            if exec_id.startswith('__aqmp#'):
+                raise ValueError(
+                    f"ID ('{exec_id}') must not start with '__aqmp#'."
+                )
+
+        if not assign_id and exec_id in self._pending:
+            raise ValueError(
+                f"ID '{exec_id}' is in-use and cannot be used."
+            )
+
+        return await self._execute(msg, assign_id=assign_id)
+
     @upper_half
     @require(Runstate.RUNNING)
     async def execute_msg(self, msg: Message) -> object:
Signature · 1 line
2.31.1
author
#29 lore raw

PATCH v2 23/24 python/aqmp: add scary message

In reply to John Snow

Add a warning whenever AQMP is used to steer people gently away from using it for the time-being.

---
 python/qemu/aqmp/__init__.py | 14 ++++++++++++++
 1 file changed, 14 insertions(+)
python/qemu/aqmp/__init__.py +14 -0
index ef2903fa7fc..321ea5c5c4b 100644
@@ -21,6 +21,8 @@
 # This work is licensed under the terms of the GNU GPL, version 2.  See
 # the COPYING file in the top-level directory.
 
+import warnings
+
 from .error import AQMPError
 from .events import EventListener
 from .message import Message
@@ -28,6 +30,18 @@
 from .qmp_client import ExecInterruptedError, ExecuteError, QMPClient
 
 
+_WMSG = """
+
+The Asynchronous QMP library is currently in development and its API
+should be considered highly fluid and subject to change. It should
+not be used by any other scripts checked into the QEMU tree.
+
+Proceed with caution!
+"""
+
+warnings.warn(_WMSG, FutureWarning)
+
+
 # The order of these fields impact the Sphinx documentation order.
 __all__ = (
     # Classes, most to least important
Signature · 1 line
2.31.1
author
#28 lore raw

PATCH v2 22/24 python/aqmp: add asyncio_run compatibility wrapper

In reply to John Snow

As a convenience. It isn't used by the library itself, but it is used by the test suite. It will also come in handy for users of the library still on Python 3.6.

---
 python/qemu/aqmp/util.py | 19 +++++++++++++++++++
 1 file changed, 19 insertions(+)
python/qemu/aqmp/util.py +19 -0
index 70ef94ad600..de0df44cbd7 100644
@@ -137,6 +137,25 @@ async def wait_closed(writer: asyncio.StreamWriter) -> None:
     await flush(writer)
 
 
+def asyncio_run(coro: Coroutine[Any, Any, T], *, debug: bool = False) -> T:
+    """
+    Python 3.6-compatible `asyncio.run` wrapper.
+
+    :param coro: A coroutine to execute now.
+    :return: The return value from the coroutine.
+    """
+    if sys.version_info >= (3, 7):
+        return asyncio.run(coro, debug=debug)
+
+    # Python 3.6
+    loop = asyncio.get_event_loop()
+    loop.set_debug(debug)
+    ret = loop.run_until_complete(coro)
+    loop.close()
+
+    return ret
+
+
 # ----------------------------
 # Section: Logging & Debugging
 # ----------------------------
Signature · 1 line
2.31.1
#16 lore raw

Re: [PATCH v2 11/24] python/aqmp: add _cb_inbound and _cb_inbound logging hooks

In reply to John Snow

I think there's a typo in your commit message subject.

Thanks,
Niteesh.

Quoted 105 lines · John Snow

Add hooks designed to log/filter incoming/outgoing messages. The primary intent for these is to be able to support iotests which may want to log messages with specific filters for reproducible output.

Another use is for plugging into Urwid frameworks; all messages in/out can be automatically added to a rendering list for the purposes of a qmp-shell like tool.

---
 python/qemu/aqmp/protocol.py | 50 +++++++++++++++++++++++++++++++++---
 1 file changed, 46 insertions(+), 4 deletions(-)
python/qemu/aqmp/protocol.py +46 -5
index 86002a52654..6f83d3e3922 100644
@@ -176,6 +176,11 @@ class AsyncProtocol(Generic[T]):
          can be written after the super() call.
      - `_on_message`:
          Actions to be performed when a message is received.
+     - `_cb_outbound`:
+         Logging/Filtering hook for all outbound messages.
+     - `_cb_inbound`:
+         Logging/Filtering hook for all inbound messages.
+         This hook runs *before* `_on_message()`.
 
     :param name:
         Name used for logging messages, if any. By default, messages
@@ -732,6 +737,43 @@ async def _bh_recv_message(self) -> None:
     # Section: Message I/O
     # --------------------
 
+    @upper_half
+    @bottom_half
+    def _cb_outbound(self, msg: T) -> T:
+        """
+        Callback: outbound message hook.
+
+        This is intended for subclasses to be able to add arbitrary
+        hooks to filter or manipulate outgoing messages. The base
+        implementation does nothing but log the message without any
+        manipulation of the message.
+
+        :param msg: raw outbound message
+        :return: final outbound message
+        """
+        self.logger.debug("--> %s", str(msg))
+        return msg
+
+    @upper_half
+    @bottom_half
+    def _cb_inbound(self, msg: T) -> T:
+        """
+        Callback: inbound message hook.
+
+        This is intended for subclasses to be able to add arbitrary
+        hooks to filter or manipulate incoming messages. The base
+        implementation does nothing but log the message without any
+        manipulation of the message.
+
+        This method does not "handle" incoming messages; it is a filter.
+        The actual "endpoint" for incoming messages is `_on_message()`.
+
+        :param msg: raw inbound message
+        :return: processed inbound message
+        """
+        self.logger.debug("<-- %s", str(msg))
+        return msg
+
     @upper_half
     @bottom_half
     async def _do_recv(self) -> T:
@@ -760,8 +802,8 @@ async def _recv(self) -> T:
 
         :return: A single (filtered, processed) protocol message.
         """
-        # A forthcoming commit makes this method less trivial.
-        return await self._do_recv()
+        message = await self._do_recv()
+        return self._cb_inbound(message)
 
     @upper_half
     @bottom_half
@@ -791,7 +833,7 @@ async def _send(self, msg: T) -> None:
 
         :raise OSError: For problems with the underlying stream.
         """
-        # A forthcoming commit makes this method less trivial.
+        msg = self._cb_outbound(msg)
         self._do_send(msg)
 
     @bottom_half
@@ -806,6 +848,6 @@ async def _on_message(self, msg: T) -> None:
             directly cause the loop to halt, so logic may be best-kept
             to a minimum if at all possible.
 
-        :param msg: The incoming message
+        :param msg: The incoming message, already logged/filtered.
         """
         # Nothing to do in the abstract case.
--

2.31.1

author
#17 lore raw

Re: [PATCH v2 11/24] python/aqmp: add _cb_inbound and _cb_inbound logging hooks

Quoted 6 lines · Niteesh G. S.

I think there's a typo in your commit message subject.

Thanks,
Niteesh.

Whoops, there sure is. Fixed locally, thanks!

--js

Reviewed-by on v2 24/24
#31 lore raw

Re: [PATCH v2 24/24] python/aqmp: add AsyncProtocol unit tests

In reply to John Snow
Quoted 75 lines · John Snow

This tests most of protocol.py -- From a hacked up Coverage.py run, it's at about 86%. There's a few error cases that aren't very well tested yet, they're hard to induce artificially so far. I'm working on it.

---
 python/tests/null_proto.py |  67 ++++++
 python/tests/protocol.py   | 458 +++++++++++++++++++++++++++++++++++++
 2 files changed, 525 insertions(+)
 create mode 100644 python/tests/null_proto.py
 create mode 100644 python/tests/protocol.py
python/tests/null_proto.py new file +57 -0
new file mode 100644
index 00000000000..c697efc0001
@@ -0,0 +1,67 @@
+import asyncio
+
+from qemu.aqmp.protocol import AsyncProtocol
+
+
+class NullProtocol(AsyncProtocol[None]):
+    """
+    NullProtocol is a test mockup of an AsyncProtocol implementation.
+
+    It adds a fake_session instance variable that enables a code path
+    that bypasses the actual connection logic, but still allows the
+    reader/writers to start.
+
+    Because the message type is defined as None, an asyncio.Event named
+    'trigger_input' is created that prohibits the reader from
+    incessantly being able to yield None; this input can be poked to
+    simulate an incoming message.
+
+    For testing symmetry with do_recv, an interface is added to "send" a
+    Null message.
+
+    For testing purposes, a "simulate_disconnection" method is also
+    added which allows us to trigger a bottom half disconnect without
+    injecting any real errors into the reader/writer loops; in essence
+    it performs exactly half of what disconnect() normally does.
+    """
+    def __init__(self, name=None):
+        self.fake_session = False
+        self.trigger_input: asyncio.Event
+        super().__init__(name)
+
+    async def _establish_session(self):
+        self.trigger_input = asyncio.Event()
+        await super()._establish_session()
+
+    async def _do_accept(self, address, ssl=None):
+        if not self.fake_session:
+            await super()._do_accept(address, ssl)
+
+    async def _do_connect(self, address, ssl=None):
+        if not self.fake_session:
+            await super()._do_connect(address, ssl)
+
+    async def _do_recv(self) -> None:
+        await self.trigger_input.wait()
+        self.trigger_input.clear()
+
+    def _do_send(self, msg: None) -> None:
+        pass
+
+    async def send_msg(self) -> None:
+        await self._outgoing.put(None)
+
+    async def simulate_disconnect(self) -> None:
+        # Simulates a bottom half disconnect, e.g. schedules a
+        # disconnection but does not wait for it to complete. This is
+        # used to put the loop into the DISCONNECTING state without

python/tests/null_proto.py line 67

Quoted 10 lines
python/tests/null_proto.py new file +10 -0
+        # fully quiescing it back to IDLE; this is normally something
+        # you cannot coax AsyncProtocol to do on purpose, but it will be
+        # similar to what happens with an unhandled Exception in the
+        # reader/writer.
+        #
+        # Under normal circumstances, the library design requires you to
+        # await on disconnect(), which awaits the disconnect task and
+        # returns bottom half errors as a pre-condition to allowing the
+        # loop to return back to IDLE.
+        self._schedule_disconnect()

Nitpick: Any reason for not using a docstring? I wouldn't mind if it was a docstring instead. ;)

Quoted 7 lines
python/tests/protocol.py new file +1 -0
new file mode 100644
index 00000000000..2374d01365e
@@ -0,0 +1,458 @@
+import asyncio

python/tests/protocol.py line 11

Quoted 10 lines
python/tests/protocol.py new file +10 -0
+from contextlib import contextmanager
+import os
+import socket
+from tempfile import TemporaryDirectory
+
+import avocado
+
+from qemu.aqmp import ConnectError, Runstate
+from qemu.aqmp.protocol import StateError
+from qemu.aqmp.util import asyncio_run, create_task

Nitpick: Maybe an isort?

python/tests/protocol.py line 14

Quoted 2 lines
python/tests/protocol.py new file +2 -0
+# An Avocado bug prevents us from defining this testing class in-line here:
+from null_proto import NullProtocol

Is this what you are looking for?

https://github.com/avocado-framework/avocado/pull/4764

If not, can you point to the right issue, please?

Quoted 431 lines
python/tests/protocol.py new file +429 -0
+@contextmanager
+def jammed_socket():
+    # This method opens up a random TCP port on localhost, then jams it.
+    socks = []
+
+    try:
+        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+        sock.bind(('127.0.0.1', 0))
+        sock.listen(1)
+        address = sock.getsockname()
+
+        socks.append(sock)
+
+        # I don't *fully* understand why, but it takes *two* un-accepted
+        # connections to start jamming the socket.
+        for _ in range(2):
+            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+            sock.connect(address)
+            socks.append(sock)
+
+        yield address
+
+    finally:
+        for sock in socks:
+            sock.close()
+
+
+class Smoke(avocado.Test):
+
+    def setUp(self):
+        self.proto = NullProtocol()
+
+    def test__repr__(self):
+        self.assertEqual(
+            repr(self.proto),
+            "<NullProtocol runstate=IDLE>"
+        )
+
+    def testRunstate(self):
+        self.assertEqual(
+            self.proto.runstate,
+            Runstate.IDLE
+        )
+
+    def testDefaultName(self):
+        self.assertEqual(
+            self.proto.name,
+            None
+        )
+
+    def testLogger(self):
+        self.assertEqual(
+            self.proto.logger.name,
+            'qemu.aqmp.protocol'
+        )
+
+    def testName(self):
+        self.proto = NullProtocol('Steve')
+
+        self.assertEqual(
+            self.proto.name,
+            'Steve'
+        )
+
+        self.assertEqual(
+            self.proto.logger.name,
+            'qemu.aqmp.protocol.Steve'
+        )
+
+        self.assertEqual(
+            repr(self.proto),
+            "<NullProtocol name='Steve' runstate=IDLE>"
+        )
+
+
+class TestBase(avocado.Test):
+
+    def setUp(self):
+        self.proto = NullProtocol(type(self).__name__)
+        self.assertEqual(self.proto.runstate, Runstate.IDLE)
+        self.runstate_watcher = None
+
+    def tearDown(self):
+        self.assertEqual(self.proto.runstate, Runstate.IDLE)
+
+    async def _asyncSetUp(self):
+        pass
+
+    async def _asyncTearDown(self):
+        if self.runstate_watcher:
+            await self.runstate_watcher
+
+    def _asyncRunner(self, test_coroutine):
+        async def coroutine():
+            await self._asyncSetUp()
+            await test_coroutine
+            await self._asyncTearDown()
+
+        asyncio_run(coroutine(), debug=True)
+
+    # Definitions
+
+    # The states we expect a "bad" connect/accept attempt to transition through
+    BAD_CONNECTION_STATES = (
+        Runstate.CONNECTING,
+        Runstate.DISCONNECTING,
+        Runstate.IDLE,
+    )
+
+    # The states we expect a "good" session to transition through
+    GOOD_CONNECTION_STATES = (
+        Runstate.CONNECTING,
+        Runstate.RUNNING,
+        Runstate.DISCONNECTING,
+        Runstate.IDLE,
+    )
+
+    # Helpers
+
+    async def _watch_runstates(self, *states):
+        # This launches a task alongside most tests below to confirm that the
+        # sequence of runstate changes is exactly as anticipated.
+
+        async def _watcher():
+            for state in states:
+                new_state = await self.proto.runstate_changed()
+                self.assertEqual(
+                    new_state,
+                    state,
+                    msg=f"Expected state '{state.name}'",
+                )
+
+        self.runstate_watcher = create_task(_watcher())
+        # Kick the loop and force the task to block on the event.
+        await asyncio.sleep(0)
+
+
+class State(TestBase):
+
+    async def testSuperfluousDisconnect_(self):
+        await self._watch_runstates(
+            Runstate.DISCONNECTING,
+            Runstate.IDLE,
+        )
+        await self.proto.disconnect()
+
+    def testSuperfluousDisconnect(self):
+        self._asyncRunner(self.testSuperfluousDisconnect_())
+
+
+class Connect(TestBase):
+
+    async def _bad_connection(self, family: str):
+        assert family in ('INET', 'UNIX')
+
+        if family == 'INET':
+            await self.proto.connect(('127.0.0.1', 0))
+        elif family == 'UNIX':
+            await self.proto.connect('/dev/null')
+
+    async def _hanging_connection(self):
+        with jammed_socket() as addr:
+            await self.proto.connect(addr)
+
+    async def _bad_connection_test(self, family: str):
+        await self._watch_runstates(*self.BAD_CONNECTION_STATES)
+
+        with self.assertRaises(ConnectError) as context:
+            await self._bad_connection(family)
+
+        self.assertIsInstance(context.exception.exc, OSError)
+        self.assertEqual(
+            context.exception.error_message,
+            "Failed to establish connection"
+        )
+
+    def testBadINET(self):
+        self._asyncRunner(self._bad_connection_test('INET'))
+        # self.assertIsInstance(err.exc, ConnectionRefusedError)
+
+    def testBadUNIX(self):
+        self._asyncRunner(self._bad_connection_test('UNIX'))
+        # self.assertIsInstance(err.exc, ConnectionRefusedError)
+
+    async def testCancellation_(self):
+        # Note that accept() cannot be cancelled outright, as it isn't a task.
+        # However, we can wrap it in a task and cancel *that*.
+        await self._watch_runstates(*self.BAD_CONNECTION_STATES)
+        task = run_as_task(self._hanging_connection(), allow_cancellation=True)
+
+        state = await self.proto.runstate_changed()
+        self.assertEqual(state, Runstate.CONNECTING)
+
+        # This is insider baseball, but the connection attempt has
+        # yielded *just* before the actual connection attempt, so kick
+        # the loop to make sure it's truly wedged.
+        await asyncio.sleep(0)
+
+        task.cancel()
+        await task
+
+    def testCancellation(self):
+        self._asyncRunner(self.testCancellation_())
+
+    async def testTimeout_(self):
+        await self._watch_runstates(*self.BAD_CONNECTION_STATES)
+        task = run_as_task(self._hanging_connection())
+
+        # More insider baseball: to improve the speed of this test while
+        # guaranteeing that the connection even gets a chance to start,
+        # verify that the connection hangs *first*, then await the
+        # result of the task with a nearly-zero timeout.
+
+        state = await self.proto.runstate_changed()
+        self.assertEqual(state, Runstate.CONNECTING)
+        await asyncio.sleep(0)
+
+        with self.assertRaises(asyncio.TimeoutError):
+            await asyncio.wait_for(task, timeout=0)
+
+    def testTimeout(self):
+        self._asyncRunner(self.testTimeout_())
+
+    async def testRequire_(self):
+        await self._watch_runstates(*self.BAD_CONNECTION_STATES)
+        task = run_as_task(self._hanging_connection(), allow_cancellation=True)
+
+        state = await self.proto.runstate_changed()
+        self.assertEqual(state, Runstate.CONNECTING)
+
+        with self.assertRaises(StateError) as context:
+            await self._bad_connection('UNIX')
+
+        self.assertEqual(
+            context.exception.error_message,
+            "NullProtocol is currently connecting."
+        )
+        self.assertEqual(context.exception.state, Runstate.CONNECTING)
+        self.assertEqual(context.exception.required, Runstate.IDLE)
+
+        task.cancel()
+        await task
+
+    def testRequire(self):
+        self._asyncRunner(self.testRequire_())
+
+    async def testImplicitRunstateInit_(self):
+        # This tests what happens if we do not wait on the
+        # runstate until AFTER we connect, i.e., connect()/accept()
+        # themselves initialize the runstate event. All of the above
+        # tests force the initialization by waiting on the runstate
+        # *first*.
+        task = run_as_task(self._hanging_connection(), allow_cancellation=True)
+
+        # Kick the loop to coerce the state change
+        await asyncio.sleep(0)
+        assert self.proto.runstate == Runstate.CONNECTING
+
+        # We already missed the transition to CONNECTING
+        await self._watch_runstates(Runstate.DISCONNECTING, Runstate.IDLE)
+
+        task.cancel()
+        await task
+
+    def testImplicitRunstateInit(self):
+        self._asyncRunner(self.testImplicitRunstateInit_())
+
+
+class Accept(Connect):
+
+    async def _bad_connection(self, family: str):
+        assert family in ('INET', 'UNIX')
+
+        if family == 'INET':
+            await self.proto.accept(('example.com', 1))
+        elif family == 'UNIX':
+            await self.proto.accept('/dev/null')
+
+    async def _hanging_connection(self):
+        with TemporaryDirectory(suffix='.aqmp') as tmpdir:
+            sock = os.path.join(tmpdir, type(self.proto).__name__ + ".sock")
+            await self.proto.accept(sock)
+
+
+class FakeSession(TestBase):
+
+    def setUp(self):
+        super().setUp()
+        self.proto.fake_session = True
+
+    async def _asyncSetUp(self):
+        await super()._asyncSetUp()
+        await self._watch_runstates(*self.GOOD_CONNECTION_STATES)
+
+    async def _asyncTearDown(self):
+        await self.proto.disconnect()
+        await super()._asyncTearDown()
+
+    ####
+
+    async def testFakeConnect_(self):
+        await self.proto.connect('/not/a/real/path')
+        self.assertEqual(self.proto.runstate, Runstate.RUNNING)
+
+    def testFakeConnect(self):
+        """Test the full state lifecycle (via connect) with a no-op session."""
+        self._asyncRunner(self.testFakeConnect_())
+
+    async def testFakeAccept_(self):
+        await self.proto.accept('/not/a/real/path')
+        self.assertEqual(self.proto.runstate, Runstate.RUNNING)
+
+    def testFakeAccept(self):
+        """Test the full state lifecycle (via accept) with a no-op session."""
+        self._asyncRunner(self.testFakeAccept_())
+
+    async def testFakeRecv_(self):
+        await self.proto.accept('/not/a/real/path')
+
+        logname = self.proto.logger.name
+        with self.assertLogs(logname, level='DEBUG') as context:
+            self.proto.trigger_input.set()
+            self.proto.trigger_input.clear()
+            await asyncio.sleep(0)  # Kick reader.
+
+        self.assertEqual(
+            context.output,
+            [f"DEBUG:{logname}:<-- None"],
+        )
+
+    def testFakeRecv(self):
+        """Test receiving a fake/null message."""
+        self._asyncRunner(self.testFakeRecv_())
+
+    async def testFakeSend_(self):
+        await self.proto.accept('/not/a/real/path')
+
+        logname = self.proto.logger.name
+        with self.assertLogs(logname, level='DEBUG') as context:
+            # Cheat: Send a Null message to nobody.
+            await self.proto.send_msg()
+            # Kick writer; awaiting on a queue.put isn't sufficient to yield.
+            await asyncio.sleep(0)
+
+        self.assertEqual(
+            context.output,
+            [f"DEBUG:{logname}:--> None"],
+        )
+
+    def testFakeSend(self):
+        """Test sending a fake/null message."""
+        self._asyncRunner(self.testFakeSend_())
+
+    async def _prod_session_api(
+            self,
+            current_state: Runstate,
+            error_message: str,
+            accept: bool = True
+    ):
+        with self.assertRaises(StateError) as context:
+            if accept:
+                await self.proto.accept('/not/a/real/path')
+            else:
+                await self.proto.connect('/not/a/real/path')
+
+        self.assertEqual(context.exception.error_message, error_message)
+        self.assertEqual(context.exception.state, current_state)
+        self.assertEqual(context.exception.required, Runstate.IDLE)
+
+    async def testAcceptRequireRunning_(self):
+        await self.proto.accept('/not/a/real/path')
+
+        await self._prod_session_api(
+            Runstate.RUNNING,
+            "NullProtocol is already connected and running.",
+            accept=True,
+        )
+
+    def testAcceptRequireRunning(self):
+        """Test that accept() cannot be called when Runstate=RUNNING"""
+        self._asyncRunner(self.testAcceptRequireRunning_())
+
+    async def testConnectRequireRunning_(self):
+        await self.proto.accept('/not/a/real/path')
+
+        await self._prod_session_api(
+            Runstate.RUNNING,
+            "NullProtocol is already connected and running.",
+            accept=False,
+        )
+
+    def testConnectRequireRunning(self):
+        """Test that connect() cannot be called when Runstate=RUNNING"""
+        self._asyncRunner(self.testConnectRequireRunning_())
+
+    async def testAcceptRequireDisconnecting_(self):
+        await self.proto.accept('/not/a/real/path')
+
+        # Cheat: force a disconnect.
+        await self.proto.simulate_disconnect()
+
+        await self._prod_session_api(
+            Runstate.DISCONNECTING,
+            ("NullProtocol is disconnecting."
+             " Call disconnect() to return to IDLE state."),
+            accept=True,
+        )
+
+    def testAcceptRequireDisconnecting(self):
+        """Test that accept() cannot be called when Runstate=DISCONNECTING"""
+        self._asyncRunner(self.testAcceptRequireDisconnecting_())
+
+    async def testConnectRequireDisconnecting_(self):
+        await self.proto.accept('/not/a/real/path')
+
+        # Cheat: force a disconnect.
+        await self.proto.simulate_disconnect()
+
+        await self._prod_session_api(
+            Runstate.DISCONNECTING,
+            ("NullProtocol is disconnecting."
+             " Call disconnect() to return to IDLE state."),
+            accept=False,
+        )
+
+    def testConnectRequireDisconnecting(self):
+        """Test that connect() cannot be called when Runstate=DISCONNECTING"""
+        self._asyncRunner(self.testConnectRequireDisconnecting_())
Signature · 1 line
2.31.1

Besides that, I just would like to bring to the table that Avocado has now a basic support for coroutines as tests that might help here. IIUC, some of the boilerplate code (and duplicated methods) could be removed with this:

https://github.com/avocado-framework/avocado/pull/4788

In any case, I understand if the latest version is not an option here, so:

Thanks,
--
Beraldo

#33 lore raw
In reply to John Snow

Hello all,

I recently rebased(incrementally) my TUI on this V2 patch and faced an issue.
https://gitlab.com/niteesh.gs/qemu/-/commits/aqmp-tui-prototype-v3
I decided to rebase incrementally so that I can address some of the comments posted
in my patch series. While testing out, the initial draft of TUI which worked fine in the V1
version of AQMP failed in this version.

Disconnecting from a fully connected state doesn't exit cleanly.
---------------------------------------------------------------------------------
To reproduce the issue:
1) Initiate a QMP server
2) Connect the TUI to the server using aqmp-tui localhost:1234 --log-file log.txt
3) Once the TUI is connected and running, press 'Esc' to exit the app. This should result
in the following exception.
--------------------------------------------------------------------------------------------------------------------------------------------
Transitioning from 'Runstate.IDLE' to 'Runstate.CONNECTING'. Connecting to ('localhost', 1234) ...
Connected.
Awaiting greeting ...
Response: {

  "QMP": {
    .......... Skipping

}
}
Negotiating capabilities ...
Request: {
"execute": "qmp_capabilities",

    .......... Skipping

}
}
Response: {
"return": {}
}
Transitioning from 'Runstate.CONNECTING' to 'Runstate.RUNNING'.
Transitioning from 'Runstate.RUNNING' to 'Runstate.DISCONNECTING'.
Scheduling disconnect.
Draining the outbound queue ...
Flushing the StreamWriter ...
Cancelling writer task ...
Task.Writer: cancelled.
Task.Writer: exiting.
Cancelling reader task ...
Task.Reader: cancelled.
Task.Reader: exiting.
Closing StreamWriter.
Waiting for StreamWriter to close ...
QMP Disconnected.
Transitioning from 'Runstate.DISCONNECTING' to 'Runstate.IDLE'.
_kill_app: Connection lost
Connection lost
| Traceback (most recent call last):
| File "/home/niteesh/development/qemu/python/qemu/aqmp/aqmp_tui.py",
line 246, in run
| main_loop.run()
| File
"/home/niteesh/development/qemu/python/.venv/lib/python3.6/site-packages/urwid/main_loop.py", line 287, in run
| self._run()
| File
"/home/niteesh/development/qemu/python/.venv/lib/python3.6/site-packages/urwid/main_loop.py", line 385, in _run
| self.event_loop.run()
| File
"/home/niteesh/development/qemu/python/.venv/lib/python3.6/site-packages/urwid/main_loop.py", line 1494, in run
| reraise(*exc_info)
| File
"/home/niteesh/development/qemu/python/.venv/lib/python3.6/site-packages/urwid/compat.py", line 58, in reraise
| raise value
| File "/home/niteesh/development/qemu/python/qemu/aqmp/aqmp_tui.py",
line 206, in _kill_app
| raise err
| File "/home/niteesh/development/qemu/python/qemu/aqmp/aqmp_tui.py",
line 201, in _kill_app
| await self.disconnect()
| File "/home/niteesh/development/qemu/python/qemu/aqmp/protocol.py",
line 303, in disconnect
| await self._wait_disconnect()
| File "/home/niteesh/development/qemu/python/qemu/aqmp/protocol.py",
line 573, in _wait_disconnect
| await self._dc_task
| File "/home/niteesh/development/qemu/python/qemu/aqmp/qmp_client.py",
line 316, in _bh_disconnect
| await super()._bh_disconnect()
| File "/home/niteesh/development/qemu/python/qemu/aqmp/protocol.py",
line 644, in _bh_disconnect
| await wait_closed(self._writer)
| File "/home/niteesh/development/qemu/python/qemu/aqmp/util.py", line
137, in wait_closed
| await flush(writer)
| File "/home/niteesh/development/qemu/python/qemu/aqmp/util.py", line
49, in flush

  |     await writer.drain()
  |   File "/usr/lib/python3.6/asyncio/streams.py", line 339, in drain
  |     yield from self._protocol._drain_helper()
  |   File "/usr/lib/python3.6/asyncio/streams.py", line 210, in

_drain_helper
| raise ConnectionResetError('Connection lost')
| ConnectionResetError: Connection lost
--------------------------------------------------------------------------------------------------------------------------------------------

Quoted 264 lines · John Snow

GitLab: https://gitlab.com/jsnow/qemu/-/commits/python-async-qmp-aqmp
CI: https://gitlab.com/jsnow/qemu/-/pipelines/338508045
Docs: https://people.redhat.com/~jsnow/sphinx/html/qemu.aqmp.html

Hi!

This patch series adds an Asynchronous QMP package to the Python library. It offers a few improvements over the previous library:

- out-of-band support
- true asynchronous event support
- avoids undocumented interfaces abusing non-blocking sockets
- unit tests!
- documentation!

This library serves as the basis for a new qmp-shell program that will offer improved reconnection support, true asynchronous display of events, VM and job status update notifiers, and so on.

My intent is to eventually publish this library directly to PyPI as a standalone package. I would like to phase out our usage of the old QMP library over time; eventually replacing it entirely with this one.

This series looks big by line count, but it's *mostly* docstrings. Seriously!

This package has *no* external dependencies whatsoever.

Notes & Design
==============

Here are some notes on the design of how the library works, to serve as a primer for review; however I also **highly recommend** browsing the generated Sphinx documentation for this series.

Here's that link again:
https://people.redhat.com/~jsnow/sphinx/html/qemu.aqmp.html

The core machinery is split between the AsyncProtocol and QMP classes. AsyncProtocol provides the generic machinery, while QMP provides the QMP-specific details.

The design uses two independent coroutines that act as the "bottom half", a writer task and a reader task. These tasks run for the duration of the connection and independently send and receive messages, respectively.

A third task, disconnect, is scheduled asynchronously whenever an unrecoverable error occurs and facilitates coalescing of the other two tasks.

This diagram for how execute() operates may be helpful for understanding how AsyncProtocol is laid out. The arrows indicate the direction of a QMP message; the long horizontal dash indicates the separation between the upper and lower half of the event loop. The queue mechanisms between both dashes serve as the intermediaries between the upper and lower half.

                       +---------+
                       | caller  |
                       +---------+
                           ^ |
                           | v
                       +---------+
     +---------------> |execute()| -----------+
     |                 +---------+            |
     |                                        |
[-----------------------------------------------------------]
     |                                        |
     |                                        v
+----+------+    +----------------+    +------+-------+
| ExecQueue |    | EventListeners |    |Outbound Queue|
+----+------+    +----+-----------+    +------+-------+
     ^                ^                       |
     |                |                       |
[-----------------------------------------------------------]
     |                |                       |
     |                |                       v
  +--+----------------+---+       +-----------+-----------+
  | Reader Task/Coroutine |       | Writer Task/Coroutine |
  +-----------+-----------+       +-----------+-----------+
              ^                               |
              |                               v
        +-----+------+                  +-----+------+
        |StreamReader|                  |StreamWriter|
        +------------+                  +------------+

The caller will invoke execute(), which in turn will deposit a message in the outbound send queue. This will wake up the writer task, which well send the message over the wire.

The execute() method will then yield to wait for a reply delivered to an execution queue created solely for that execute statement.

When a message arrives, the Reader task will unblock and route the message either to the EventListener subsystem, or place it in the appropriate pending execution queue.

Once a message is placed in the pending execution queue, execute() will unblock and the execution will conclude, returning the result of the RPC call to the caller.

Patch Layout
============

Patches 1-4 add tiny pre-requisites, utilities, etc.
Patches 5-12 add a generic async message-based protocol class,
AsyncProtocol. They are split fairly small and should be reasonably self-contained.
Patches 13-15 check in more QMP-centric components. Patches 16-21 add qmp_client.py, with a new 'QMPClient()' class.
They're split into reasonably tiny pieces here.
Patches 22-23 add a few finishing touches, they are small patches.
Patch 24 adds unit tests. They're maybe a little messy yet, but
they've been quite helpful to me so far. Coverage of protocol.py is at about 86%.

Future Work
===========

These items are in progress:

- A synchronous QMP wrapper that allows this library to be easily used from non-async code; this will also allow me to prove it works well by demoing its replacement throughout iotests. I have all of iotests passing locally, but I am still seeing some failures on gitlab CI I need to diagnose, possibly a race condition somewhere.

- A QMP server class; to facilitate writing of unit tests. It's done, but needs some polish and tests.

- More unit tests for qmp_client.py, qmp_server.py and other modules.

Changelog
=========

V2:

Renamed classes/methods:

- Renamed qmp_protocol.py to qmp_client.py
- Renamed 'QMP' class to 'QMPClient'
- Renamed _begin_new_session() to _establish_session()
- Split _establish_connection() out from _new_session().
- Removed _results() method

Bugfixes:

- Suppress duplicate Exceptions when attempting to drain the StreamWriter
- Delay initialization of asyncio.Queue and asyncio.Event variables to _new_session or later -- they must not be created outside of the loop, even if they are not async functions.
- Rework runstate_changed events to guarantee visibility of events to waiters
- Improve connect()/accept() cleanup to work with asyncio.CancelledError, asyncio.TimeoutError
- No-argument form of Message() now succeeds properly.
- flush utility will correctly yield when data is below the "high water mark", giving the stream a chance to actually flush.
- Increase read buffer size to accommodate query-qmp-schema (Thanks Niteesh)

Ugly bits from V1 removed:

- Remove tertiary filtering from EventListener (for now), accompanying documentation removed from events.py
- Use asyncio.wait() instead of custom wait_task_done()
- MultiException is removed in favor of just raising the first Exception that occurs in the bottom half; other Exceptions if any are logged instead.

Improvements:

- QMPClient now allows ID-less execution statements via the _raw() interface.
- Add tests that grant ~86% coverage of protocol.py to the avocado test suite.
- Removed 'force' parameter from _bh_disconnect; the disconnection routine determines for itself if we are in the error pathway or not instead now. This removes any chance of duplicate calls to _schedule_disconnect accidentally dropping the 'force' setting.

Debugging/Testing changes:

- Add debug: bool parameter to asyncio_run utility wrapper
- Improve error messages for '@require' decorator
- Add debugging message for state change events
- Avoid flushing the StreamWriter if we don't have one (This circumstance only arises in testing, but it's helpful.)
- Improved __repr__ method for AsyncProtocol, and removed __str__ method. enforcing eval(__repr__(x)) == x does not make sense for AsyncProtocol.
- Misc logging message changes
- Add a suite of fancy Task debugging utilities.
- Most tracebacks now log at the DEBUG level instead of CRITICAL/ERROR/WARNING; In those error cases, a one-line summary is logged instead.

Misc. aesthetic changes:

- Misc docstring fixes, whitespace, etc.
- Reordered the definition of some methods to try and keep similar methods near each other (Moved _cleanup near _bh_disconnect in QMPClient.)

~ Shucks Howdy, Gee Golly!

John Snow (24):
python/aqmp: add asynchronous QMP (AQMP) subpackage python/aqmp: add error classes
python/pylint: Add exception for TypeVar names ('T') python/aqmp: add asyncio compatibility wrappers python/aqmp: add generic async message-based protocol support python/aqmp: add runstate state machine to AsyncProtocol python/aqmp: Add logging utility helpers python/aqmp: add logging to AsyncProtocol python/aqmp: add AsyncProtocol.accept() method python/aqmp: add configurable read buffer limit python/aqmp: add _cb_inbound and _cb_inbound logging hooks python/aqmp: add AsyncProtocol._readline() method python/aqmp: add QMP Message format
python/aqmp: add well-known QMP object models python/aqmp: add QMP event support
python/pylint: disable too-many-function-args python/aqmp: add QMP protocol support python/pylint: disable no-member check
python/aqmp: Add message routing to QMP protocol python/aqmp: add execute() interfaces
python/aqmp: add _raw() execution interface python/aqmp: add asyncio_run compatibility wrapper python/aqmp: add scary message
python/aqmp: add AsyncProtocol unit tests

 python/qemu/aqmp/__init__.py   |  58 +++
 python/qemu/aqmp/error.py      |  50 ++
 python/qemu/aqmp/events.py     | 706 ++++++++++++++++++++++++++
 python/qemu/aqmp/message.py    | 209 ++++++++
 python/qemu/aqmp/models.py     | 133 +++++
 python/qemu/aqmp/protocol.py   | 882 +++++++++++++++++++++++++++++++++
 python/qemu/aqmp/py.typed      |   0
 python/qemu/aqmp/qmp_client.py | 621 +++++++++++++++++++++++
 python/qemu/aqmp/util.py       | 207 ++++++++
 python/setup.cfg               |   5 +-
 python/tests/null_proto.py     |  67 +++
 python/tests/protocol.py       | 458 +++++++++++++++++
 12 files changed, 3395 insertions(+), 1 deletion(-)
 create mode 100644 python/qemu/aqmp/__init__.py
 create mode 100644 python/qemu/aqmp/error.py
 create mode 100644 python/qemu/aqmp/events.py
 create mode 100644 python/qemu/aqmp/message.py
 create mode 100644 python/qemu/aqmp/models.py
 create mode 100644 python/qemu/aqmp/protocol.py
 create mode 100644 python/qemu/aqmp/py.typed
 create mode 100644 python/qemu/aqmp/qmp_client.py
 create mode 100644 python/qemu/aqmp/util.py
 create mode 100644 python/tests/null_proto.py
 create mode 100644 python/tests/protocol.py

--
2.31.1

author
#36 lore raw
In reply to a message not in the archive

Looping qemu-devel back in: I removed them by accident by not hitting reply-all :(

Quoted 148 lines · Niteesh G. S.
Quoted 16 lines · John Snow
Quoted 11 lines · Niteesh G. S.

Hello all,

I recently rebased(incrementally) my TUI on this V2 patch and faced an issue.
https://gitlab.com/niteesh.gs/qemu/-/commits/aqmp-tui-prototype-v3
I decided to rebase incrementally so that I can address some of the comments posted
in my patch series. While testing out, the initial draft of TUI which worked fine in the V1
version of AQMP failed in this version.

Quoted 9 lines
Quoted 6 lines

Disconnecting from a fully connected state doesn't exit cleanly.

---------------------------------------------------------------------------------
To reproduce the issue:
1) Initiate a QMP server

Please provide the command line.

qemu-system-x86_64 -qmp tcp:localhost:1234,server,wait=on

Quoted 9 lines
Quoted 5 lines

2) Connect the TUI to the server using aqmp-tui localhost:1234 --log-file log.txt

The entry point isn't defined yet in your series, so I will assume "python3 -m qemu.aqmp.aqmp_tui localhost:1234" should work here.

Yup, sorry about that. I realized this later when recreated the venv.

Quoted 106 lines
Quoted 96 lines

3) Once the TUI is connected and running, press 'Esc' to exit the app. This should result
in the following exception.

--------------------------------------------------------------------------------------------------------------------------------------------
Transitioning from 'Runstate.IDLE' to 'Runstate.CONNECTING'. Connecting to ('localhost', 1234) ...
Connected.
Awaiting greeting ...
Response: {

  "QMP": {
    .......... Skipping

}
}
Negotiating capabilities ...
Request: {
"execute": "qmp_capabilities",

    .......... Skipping

}
}
Response: {
"return": {}
}
Transitioning from 'Runstate.CONNECTING' to 'Runstate.RUNNING'.
Transitioning from 'Runstate.RUNNING' to 'Runstate.DISCONNECTING'.
Scheduling disconnect.
Draining the outbound queue ...
Flushing the StreamWriter ...
Cancelling writer task ...
Task.Writer: cancelled.
Task.Writer: exiting.
Cancelling reader task ...
Task.Reader: cancelled.
Task.Reader: exiting.
Closing StreamWriter.
Waiting for StreamWriter to close ...
QMP Disconnected.
Transitioning from 'Runstate.DISCONNECTING' to 'Runstate.IDLE'.
_kill_app: Connection lost
Connection lost
| Traceback (most recent call last):
| File
"/home/niteesh/development/qemu/python/qemu/aqmp/aqmp_tui.py", line 246, in run
| main_loop.run()
| File
"/home/niteesh/development/qemu/python/.venv/lib/python3.6/site-packages/urwid/main_loop.py", line 287, in run
| self._run()
| File
"/home/niteesh/development/qemu/python/.venv/lib/python3.6/site-packages/urwid/main_loop.py", line 385, in _run
| self.event_loop.run()
| File
"/home/niteesh/development/qemu/python/.venv/lib/python3.6/site-packages/urwid/main_loop.py", line 1494, in run
| reraise(*exc_info)
| File
"/home/niteesh/development/qemu/python/.venv/lib/python3.6/site-packages/urwid/compat.py", line 58, in reraise
| raise value
| File
"/home/niteesh/development/qemu/python/qemu/aqmp/aqmp_tui.py", line 206, in _kill_app
| raise err
| File
"/home/niteesh/development/qemu/python/qemu/aqmp/aqmp_tui.py", line 201, in _kill_app
| await self.disconnect()
| File
"/home/niteesh/development/qemu/python/qemu/aqmp/protocol.py", line 303, in disconnect
| await self._wait_disconnect()
| File
"/home/niteesh/development/qemu/python/qemu/aqmp/protocol.py", line 573, in _wait_disconnect
| await self._dc_task
| File
"/home/niteesh/development/qemu/python/qemu/aqmp/qmp_client.py", line 316,
in _bh_disconnect
| await super()._bh_disconnect()
| File
"/home/niteesh/development/qemu/python/qemu/aqmp/protocol.py", line 644, in _bh_disconnect
| await wait_closed(self._writer)
| File "/home/niteesh/development/qemu/python/qemu/aqmp/util.py",
line 137, in wait_closed
| await flush(writer)
| File "/home/niteesh/development/qemu/python/qemu/aqmp/util.py",
line 49, in flush

  |     await writer.drain()
  |   File "/usr/lib/python3.6/asyncio/streams.py", line 339, in drain
  |     yield from self._protocol._drain_helper()
  |   File "/usr/lib/python3.6/asyncio/streams.py", line 210, in
Quoted 7 lines

_drain_helper
| raise ConnectionResetError('Connection lost')
| ConnectionResetError: Connection lost

--------------------------------------------------------------------------------------------------------------------------------------------

I can't reproduce in Python 3.9, but I *can* reproduce in python 3.6 using the pipenv environment; i.e.

Quoted 26 lines
Quoted 6 lines
Quoted 3 lines

make check-pipenv
pipenv shell
python3 -m qemu.aqmp.aqmp_tui 127.0.0.1:1234

What python version are you using to see this failure? Is it 3.6 ?

Yes, I was using python 3.6. I just tried it on 3.8 and I don't face this issue.

Quoted 17 lines

It seems like the wait_closed() wrapper I wrote isn't quite compatible with Python 3.6, it looks like it's not really safe to try and flush a closing socket. I was doing so in an attempt to tell when the socket had finished closing out its buffer (expecting it to normally be a no-op) but in this case even a no-op drain in 3.6 seems to raise an error if we attempt it after we've asked for the socket to close.

wait_closed() was added in Python 3.7 and we just don't have access to it here ... I'm not sure if there's something else we can do here to serve as a workaround for not having this function.

--js

I can't find a *nice* workaround, but I found one that should probably work in most universes. We can remove this ugly code when we support 3.7 as a minimum. However, please try this patch as a fixup:

python/qemu/aqmp/util.py +0 -0
index de0df44cbd7..eaa5fc7d5f9 100644
@@ -134,7 +134,17 @@ async def wait_closed(writer: asyncio.StreamWriter) ->

None:

while not transport.is_closing():
await asyncio.sleep(0)
- await flush(writer)
+
+ # This is an ugly workaround, but it's the best I can come up with.
+ sock = transport.get_extra_info('socket')
+
+ if sock is None:

+        # Our transport doesn't have a socket? ...
+        # Nothing we can reasonably do.
+        return

+
+ while sock.fileno() != -1:
+ await asyncio.sleep(0)

#37 lore raw
Quoted 196 lines · John Snow

Looping qemu-devel back in: I removed them by accident by not hitting reply-all :(

Quoted 148 lines · Niteesh G. S.
Quoted 16 lines · John Snow
Quoted 11 lines · Niteesh G. S.

Hello all,

I recently rebased(incrementally) my TUI on this V2 patch and faced an issue.
https://gitlab.com/niteesh.gs/qemu/-/commits/aqmp-tui-prototype-v3
I decided to rebase incrementally so that I can address some of the comments posted
in my patch series. While testing out, the initial draft of TUI which worked fine in the V1
version of AQMP failed in this version.

Quoted 9 lines
Quoted 6 lines

Disconnecting from a fully connected state doesn't exit cleanly.

---------------------------------------------------------------------------------
To reproduce the issue:
1) Initiate a QMP server

Please provide the command line.

qemu-system-x86_64 -qmp tcp:localhost:1234,server,wait=on

Quoted 9 lines
Quoted 5 lines

2) Connect the TUI to the server using aqmp-tui localhost:1234 --log-file log.txt

The entry point isn't defined yet in your series, so I will assume "python3 -m qemu.aqmp.aqmp_tui localhost:1234" should work here.

Yup, sorry about that. I realized this later when recreated the venv.

Quoted 106 lines
Quoted 96 lines

3) Once the TUI is connected and running, press 'Esc' to exit the app. This should result
in the following exception.

--------------------------------------------------------------------------------------------------------------------------------------------
Transitioning from 'Runstate.IDLE' to 'Runstate.CONNECTING'. Connecting to ('localhost', 1234) ...
Connected.
Awaiting greeting ...
Response: {

  "QMP": {
    .......... Skipping

}
}
Negotiating capabilities ...
Request: {
"execute": "qmp_capabilities",

    .......... Skipping

}
}
Response: {
"return": {}
}
Transitioning from 'Runstate.CONNECTING' to 'Runstate.RUNNING'.
Transitioning from 'Runstate.RUNNING' to 'Runstate.DISCONNECTING'.
Scheduling disconnect.
Draining the outbound queue ...
Flushing the StreamWriter ...
Cancelling writer task ...
Task.Writer: cancelled.
Task.Writer: exiting.
Cancelling reader task ...
Task.Reader: cancelled.
Task.Reader: exiting.
Closing StreamWriter.
Waiting for StreamWriter to close ...
QMP Disconnected.
Transitioning from 'Runstate.DISCONNECTING' to 'Runstate.IDLE'.
_kill_app: Connection lost
Connection lost
| Traceback (most recent call last):
| File
"/home/niteesh/development/qemu/python/qemu/aqmp/aqmp_tui.py", line 246, in run
| main_loop.run()
| File
"/home/niteesh/development/qemu/python/.venv/lib/python3.6/site-packages/urwid/main_loop.py", line 287, in run
| self._run()
| File
"/home/niteesh/development/qemu/python/.venv/lib/python3.6/site-packages/urwid/main_loop.py", line 385, in _run
| self.event_loop.run()
| File
"/home/niteesh/development/qemu/python/.venv/lib/python3.6/site-packages/urwid/main_loop.py", line 1494, in run
| reraise(*exc_info)
| File
"/home/niteesh/development/qemu/python/.venv/lib/python3.6/site-packages/urwid/compat.py", line 58, in reraise
| raise value
| File
"/home/niteesh/development/qemu/python/qemu/aqmp/aqmp_tui.py", line 206, in _kill_app
| raise err
| File
"/home/niteesh/development/qemu/python/qemu/aqmp/aqmp_tui.py", line 201, in _kill_app
| await self.disconnect()
| File
"/home/niteesh/development/qemu/python/qemu/aqmp/protocol.py", line 303, in disconnect
| await self._wait_disconnect()
| File
"/home/niteesh/development/qemu/python/qemu/aqmp/protocol.py", line 573, in _wait_disconnect
| await self._dc_task
| File
"/home/niteesh/development/qemu/python/qemu/aqmp/qmp_client.py", line 316,
in _bh_disconnect
| await super()._bh_disconnect()
| File
"/home/niteesh/development/qemu/python/qemu/aqmp/protocol.py", line 644, in _bh_disconnect
| await wait_closed(self._writer)
| File "/home/niteesh/development/qemu/python/qemu/aqmp/util.py",
line 137, in wait_closed
| await flush(writer)
| File "/home/niteesh/development/qemu/python/qemu/aqmp/util.py",
line 49, in flush

  |     await writer.drain()
  |   File "/usr/lib/python3.6/asyncio/streams.py", line 339, in drain
  |     yield from self._protocol._drain_helper()
  |   File "/usr/lib/python3.6/asyncio/streams.py", line 210, in
Quoted 7 lines

_drain_helper
| raise ConnectionResetError('Connection lost')
| ConnectionResetError: Connection lost

--------------------------------------------------------------------------------------------------------------------------------------------

I can't reproduce in Python 3.9, but I *can* reproduce in python 3.6 using the pipenv environment; i.e.

Quoted 26 lines
Quoted 6 lines
Quoted 3 lines

make check-pipenv
pipenv shell
python3 -m qemu.aqmp.aqmp_tui 127.0.0.1:1234

What python version are you using to see this failure? Is it 3.6 ?

Yes, I was using python 3.6. I just tried it on 3.8 and I don't face this issue.

Quoted 17 lines

It seems like the wait_closed() wrapper I wrote isn't quite compatible with Python 3.6, it looks like it's not really safe to try and flush a closing socket. I was doing so in an attempt to tell when the socket had finished closing out its buffer (expecting it to normally be a no-op) but in this case even a no-op drain in 3.6 seems to raise an error if we attempt it after we've asked for the socket to close.

wait_closed() was added in Python 3.7 and we just don't have access to it here ... I'm not sure if there's something else we can do here to serve as a workaround for not having this function.

--js

I can't find a *nice* workaround, but I found one that should probably work in most universes. We can remove this ugly code when we support 3.7 as a minimum. However, please try this patch as a fixup:

python/qemu/aqmp/util.py +2 -2
index de0df44cbd7..eaa5fc7d5f9 100644
@@ -134,7 +134,17 @@ async def wait_closed(writer: asyncio.StreamWriter)
-> None:
 
     while not transport.is_closing():
         await asyncio.sleep(0)
-    await flush(writer)
+
+    # This is an ugly workaround, but it's the best I can come up with.

python/qemu/aqmp/util.py async def wait_closed(writer: asyncio.StreamWriter) · line 148

Quoted 10 lines
python/qemu/aqmp/util.py +9 -0
+    sock = transport.get_extra_info('socket')
+
+    if sock is None:
+        # Our transport doesn't have a socket? ...
+        # Nothing we can reasonably do.
+        return
+
+    while sock.fileno() != -1:
+        await asyncio.sleep(0)
 

Thanks for the patch. I am now able to disconnect/quit without any exceptions.

Thanks,
Niteesh.

Quoted 3 lines
author
#32 lore raw

Re: [PATCH v2 24/24] python/aqmp: add AsyncProtocol unit tests

In reply to Beraldo Leal
Quoted 81 lines · Beraldo Leal
Quoted 80 lines · John Snow

This tests most of protocol.py -- From a hacked up Coverage.py run, it's at about 86%. There's a few error cases that aren't very well tested yet, they're hard to induce artificially so far. I'm working on it.

---
 python/tests/null_proto.py |  67 ++++++
 python/tests/protocol.py   | 458 +++++++++++++++++++++++++++++++++++++
 2 files changed, 525 insertions(+)
 create mode 100644 python/tests/null_proto.py
 create mode 100644 python/tests/protocol.py
python/tests/null_proto.py new file +62 -0
new file mode 100644
index 00000000000..c697efc0001
@@ -0,0 +1,67 @@
+import asyncio
+
+from qemu.aqmp.protocol import AsyncProtocol
+
+
+class NullProtocol(AsyncProtocol[None]):
+    """
+    NullProtocol is a test mockup of an AsyncProtocol implementation.
+
+    It adds a fake_session instance variable that enables a code path
+    that bypasses the actual connection logic, but still allows the
+    reader/writers to start.
+
+    Because the message type is defined as None, an asyncio.Event named
+    'trigger_input' is created that prohibits the reader from
+    incessantly being able to yield None; this input can be poked to
+    simulate an incoming message.
+
+    For testing symmetry with do_recv, an interface is added to "send" a
+    Null message.
+
+    For testing purposes, a "simulate_disconnection" method is also
+    added which allows us to trigger a bottom half disconnect without
+    injecting any real errors into the reader/writer loops; in essence
+    it performs exactly half of what disconnect() normally does.
+    """
+    def __init__(self, name=None):
+        self.fake_session = False
+        self.trigger_input: asyncio.Event
+        super().__init__(name)
+
+    async def _establish_session(self):
+        self.trigger_input = asyncio.Event()
+        await super()._establish_session()
+
+    async def _do_accept(self, address, ssl=None):
+        if not self.fake_session:
+            await super()._do_accept(address, ssl)
+
+    async def _do_connect(self, address, ssl=None):
+        if not self.fake_session:
+            await super()._do_connect(address, ssl)
+
+    async def _do_recv(self) -> None:
+        await self.trigger_input.wait()
+        self.trigger_input.clear()
+
+    def _do_send(self, msg: None) -> None:
+        pass
+
+    async def send_msg(self) -> None:
+        await self._outgoing.put(None)
+
+    async def simulate_disconnect(self) -> None:
+        # Simulates a bottom half disconnect, e.g. schedules a
+        # disconnection but does not wait for it to complete. This is
+        # used to put the loop into the DISCONNECTING state without
+        # fully quiescing it back to IDLE; this is normally something
+        # you cannot coax AsyncProtocol to do on purpose, but it will be
+        # similar to what happens with an unhandled Exception in the
+        # reader/writer.
+        #
Quoted 10 lines

python/tests/null_proto.py line 67

Quoted 5 lines
python/tests/null_proto.py new file +5 -0
+        # Under normal circumstances, the library design requires you to
+        # await on disconnect(), which awaits the disconnect task and
+        # returns bottom half errors as a pre-condition to allowing the
+        # loop to return back to IDLE.
+        self._schedule_disconnect()

Nitpick: Any reason for not using a docstring? I wouldn't mind if it was a docstring instead. ;)

Nope. I've changed it.

Quoted 11 lines
Quoted 11 lines
python/tests/protocol.py new file +5 -0
new file mode 100644
index 00000000000..2374d01365e
@@ -0,0 +1,458 @@
+import asyncio
+from contextlib import contextmanager
+import os
+import socket
+from tempfile import TemporaryDirectory
Quoted 10 lines

python/tests/protocol.py line 11

Quoted 6 lines
python/tests/protocol.py new file +6 -0
+
+import avocado
+
+from qemu.aqmp import ConnectError, Runstate
+from qemu.aqmp.protocol import StateError
+from qemu.aqmp.util import asyncio_run, create_task

Nitpick: Maybe an isort?

It actually is isorted, just using some different settings than you're used to seeing in Avocado.

Quoted 11 lines

python/tests/protocol.py line 12

Quoted 1 line
python/tests/protocol.py new file +1 -0
+# An Avocado bug prevents us from defining this testing class in-line

here:

python/tests/protocol.py line 14

Quoted 1 line
python/tests/protocol.py new file +1 -0
+from null_proto import NullProtocol

Is this what you are looking for?

https://github.com/avocado-framework/avocado/pull/4764

If not, can you point to the right issue, please?

That's the one. I don't have time to update to v90 right now, so I'm going to leave it as a todo item, please forgive me! I'll update the comment, though.

Quoted 450 lines
Quoted 94 lines
python/tests/protocol.py new file +94 -0
+@contextmanager
+def jammed_socket():
+    # This method opens up a random TCP port on localhost, then jams it.
+    socks = []
+
+    try:
+        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+        sock.bind(('127.0.0.1', 0))
+        sock.listen(1)
+        address = sock.getsockname()
+
+        socks.append(sock)
+
+        # I don't *fully* understand why, but it takes *two* un-accepted
+        # connections to start jamming the socket.
+        for _ in range(2):
+            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+            sock.connect(address)
+            socks.append(sock)
+
+        yield address
+
+    finally:
+        for sock in socks:
+            sock.close()
+
+
+class Smoke(avocado.Test):
+
+    def setUp(self):
+        self.proto = NullProtocol()
+
+    def test__repr__(self):
+        self.assertEqual(
+            repr(self.proto),
+            "<NullProtocol runstate=IDLE>"
+        )
+
+    def testRunstate(self):
+        self.assertEqual(
+            self.proto.runstate,
+            Runstate.IDLE
+        )
+
+    def testDefaultName(self):
+        self.assertEqual(
+            self.proto.name,
+            None
+        )
+
+    def testLogger(self):
+        self.assertEqual(
+            self.proto.logger.name,
+            'qemu.aqmp.protocol'
+        )
+
+    def testName(self):
+        self.proto = NullProtocol('Steve')
+
+        self.assertEqual(
+            self.proto.name,
+            'Steve'
+        )
+
+        self.assertEqual(
+            self.proto.logger.name,
+            'qemu.aqmp.protocol.Steve'
+        )
+
+        self.assertEqual(
+            repr(self.proto),
+            "<NullProtocol name='Steve' runstate=IDLE>"
+        )
+
+
+class TestBase(avocado.Test):
+
+    def setUp(self):
+        self.proto = NullProtocol(type(self).__name__)
+        self.assertEqual(self.proto.runstate, Runstate.IDLE)
+        self.runstate_watcher = None
+
+    def tearDown(self):
+        self.assertEqual(self.proto.runstate, Runstate.IDLE)
+
+    async def _asyncSetUp(self):
+        pass
+
+    async def _asyncTearDown(self):
+        if self.runstate_watcher:
+            await self.runstate_watcher
+
+    def _asyncRunner(self, test_coroutine):

python/tests/protocol.py

Quoted 10 lines
python/tests/protocol.py new file +10 -0
+        async def coroutine():
+            await self._asyncSetUp()
+            await test_coroutine
+            await self._asyncTearDown()
+
+        asyncio_run(coroutine(), debug=True)
+
+    # Definitions
+
+    # The states we expect a "bad" connect/accept attempt to transition

through

Quoted 8 lines
python/tests/protocol.py new file +8 -0
+    BAD_CONNECTION_STATES = (
+        Runstate.CONNECTING,
+        Runstate.DISCONNECTING,
+        Runstate.IDLE,
+    )
+
+    # The states we expect a "good" session to transition through
+    GOOD_CONNECTION_STATES = (

python/tests/protocol.py

Quoted 10 lines
python/tests/protocol.py new file +10 -0
+        Runstate.CONNECTING,
+        Runstate.RUNNING,
+        Runstate.DISCONNECTING,
+        Runstate.IDLE,
+    )
+
+    # Helpers
+
+    async def _watch_runstates(self, *states):
+        # This launches a task alongside most tests below to confirm

that the

Quoted 55 lines
python/tests/protocol.py new file +55 -0
+        # sequence of runstate changes is exactly as anticipated.
+
+        async def _watcher():
+            for state in states:
+                new_state = await self.proto.runstate_changed()
+                self.assertEqual(
+                    new_state,
+                    state,
+                    msg=f"Expected state '{state.name}'",
+                )
+
+        self.runstate_watcher = create_task(_watcher())
+        # Kick the loop and force the task to block on the event.
+        await asyncio.sleep(0)
+
+
+class State(TestBase):
+
+    async def testSuperfluousDisconnect_(self):
+        await self._watch_runstates(
+            Runstate.DISCONNECTING,
+            Runstate.IDLE,
+        )
+        await self.proto.disconnect()
+
+    def testSuperfluousDisconnect(self):
+        self._asyncRunner(self.testSuperfluousDisconnect_())
+
+
+class Connect(TestBase):
+
+    async def _bad_connection(self, family: str):
+        assert family in ('INET', 'UNIX')
+
+        if family == 'INET':
+            await self.proto.connect(('127.0.0.1', 0))
+        elif family == 'UNIX':
+            await self.proto.connect('/dev/null')
+
+    async def _hanging_connection(self):
+        with jammed_socket() as addr:
+            await self.proto.connect(addr)
+
+    async def _bad_connection_test(self, family: str):
+        await self._watch_runstates(*self.BAD_CONNECTION_STATES)
+
+        with self.assertRaises(ConnectError) as context:
+            await self._bad_connection(family)
+
+        self.assertIsInstance(context.exception.exc, OSError)
+        self.assertEqual(
+            context.exception.error_message,
+            "Failed to establish connection"
+        )
+

python/tests/protocol.py

Quoted 10 lines
python/tests/protocol.py new file +10 -0
+    def testBadINET(self):
+        self._asyncRunner(self._bad_connection_test('INET'))
+        # self.assertIsInstance(err.exc, ConnectionRefusedError)
+
+    def testBadUNIX(self):
+        self._asyncRunner(self._bad_connection_test('UNIX'))
+        # self.assertIsInstance(err.exc, ConnectionRefusedError)
+
+    async def testCancellation_(self):
+        # Note that accept() cannot be cancelled outright, as it isn't

a task.

python/tests/protocol.py

Quoted 3 lines
python/tests/protocol.py new file +3 -0
+        # However, we can wrap it in a task and cancel *that*.
+        await self._watch_runstates(*self.BAD_CONNECTION_STATES)
+        task = run_as_task(self._hanging_connection(),

allow_cancellation=True)

Quoted 27 lines
python/tests/protocol.py new file +27 -0
+
+        state = await self.proto.runstate_changed()
+        self.assertEqual(state, Runstate.CONNECTING)
+
+        # This is insider baseball, but the connection attempt has
+        # yielded *just* before the actual connection attempt, so kick
+        # the loop to make sure it's truly wedged.
+        await asyncio.sleep(0)
+
+        task.cancel()
+        await task
+
+    def testCancellation(self):
+        self._asyncRunner(self.testCancellation_())
+
+    async def testTimeout_(self):
+        await self._watch_runstates(*self.BAD_CONNECTION_STATES)
+        task = run_as_task(self._hanging_connection())
+
+        # More insider baseball: to improve the speed of this test while
+        # guaranteeing that the connection even gets a chance to start,
+        # verify that the connection hangs *first*, then await the
+        # result of the task with a nearly-zero timeout.
+
+        state = await self.proto.runstate_changed()
+        self.assertEqual(state, Runstate.CONNECTING)
+        await asyncio.sleep(0)

python/tests/protocol.py

Quoted 10 lines
python/tests/protocol.py new file +10 -0
+
+        with self.assertRaises(asyncio.TimeoutError):
+            await asyncio.wait_for(task, timeout=0)
+
+    def testTimeout(self):
+        self._asyncRunner(self.testTimeout_())
+
+    async def testRequire_(self):
+        await self._watch_runstates(*self.BAD_CONNECTION_STATES)
+        task = run_as_task(self._hanging_connection(),

allow_cancellation=True)

Quoted 17 lines
python/tests/protocol.py new file +17 -0
+
+        state = await self.proto.runstate_changed()
+        self.assertEqual(state, Runstate.CONNECTING)
+
+        with self.assertRaises(StateError) as context:
+            await self._bad_connection('UNIX')
+
+        self.assertEqual(
+            context.exception.error_message,
+            "NullProtocol is currently connecting."
+        )
+        self.assertEqual(context.exception.state, Runstate.CONNECTING)
+        self.assertEqual(context.exception.required, Runstate.IDLE)
+
+        task.cancel()
+        await task
+

python/tests/protocol.py

Quoted 10 lines
python/tests/protocol.py new file +10 -0
+    def testRequire(self):
+        self._asyncRunner(self.testRequire_())
+
+    async def testImplicitRunstateInit_(self):
+        # This tests what happens if we do not wait on the
+        # runstate until AFTER we connect, i.e., connect()/accept()
+        # themselves initialize the runstate event. All of the above
+        # tests force the initialization by waiting on the runstate
+        # *first*.
+        task = run_as_task(self._hanging_connection(),

allow_cancellation=True)

python/tests/protocol.py

Quoted 7 lines
python/tests/protocol.py new file +7 -0
+
+        # Kick the loop to coerce the state change
+        await asyncio.sleep(0)
+        assert self.proto.runstate == Runstate.CONNECTING
+
+        # We already missed the transition to CONNECTING
+        await self._watch_runstates(Runstate.DISCONNECTING,

Runstate.IDLE)

Quoted 11 lines
python/tests/protocol.py new file +11 -0
+
+        task.cancel()
+        await task
+
+    def testImplicitRunstateInit(self):
+        self._asyncRunner(self.testImplicitRunstateInit_())
+
+
+class Accept(Connect):
+
+    async def _bad_connection(self, family: str):

python/tests/protocol.py

Quoted 10 lines
python/tests/protocol.py new file +10 -0
+        assert family in ('INET', 'UNIX')
+
+        if family == 'INET':
+            await self.proto.accept(('example.com', 1))
+        elif family == 'UNIX':
+            await self.proto.accept('/dev/null')
+
+    async def _hanging_connection(self):
+        with TemporaryDirectory(suffix='.aqmp') as tmpdir:
+            sock = os.path.join(tmpdir, type(self.proto).__name__ +

".sock")

Quoted 15 lines
python/tests/protocol.py new file +15 -0
+            await self.proto.accept(sock)
+
+
+class FakeSession(TestBase):
+
+    def setUp(self):
+        super().setUp()
+        self.proto.fake_session = True
+
+    async def _asyncSetUp(self):
+        await super()._asyncSetUp()
+        await self._watch_runstates(*self.GOOD_CONNECTION_STATES)
+
+    async def _asyncTearDown(self):
+        await self.proto.disconnect()

python/tests/protocol.py

Quoted 10 lines
python/tests/protocol.py new file +10 -0
+        await super()._asyncTearDown()
+
+    ####
+
+    async def testFakeConnect_(self):
+        await self.proto.connect('/not/a/real/path')
+        self.assertEqual(self.proto.runstate, Runstate.RUNNING)
+
+    def testFakeConnect(self):
+        """Test the full state lifecycle (via connect) with a no-op

session."""

python/tests/protocol.py

Quoted 8 lines
python/tests/protocol.py new file +8 -0
+        self._asyncRunner(self.testFakeConnect_())
+
+    async def testFakeAccept_(self):
+        await self.proto.accept('/not/a/real/path')
+        self.assertEqual(self.proto.runstate, Runstate.RUNNING)
+
+    def testFakeAccept(self):
+        """Test the full state lifecycle (via accept) with a no-op

session."""

Quoted 18 lines
python/tests/protocol.py new file +18 -0
+        self._asyncRunner(self.testFakeAccept_())
+
+    async def testFakeRecv_(self):
+        await self.proto.accept('/not/a/real/path')
+
+        logname = self.proto.logger.name
+        with self.assertLogs(logname, level='DEBUG') as context:
+            self.proto.trigger_input.set()
+            self.proto.trigger_input.clear()
+            await asyncio.sleep(0)  # Kick reader.
+
+        self.assertEqual(
+            context.output,
+            [f"DEBUG:{logname}:<-- None"],
+        )
+
+    def testFakeRecv(self):
+        """Test receiving a fake/null message."""

python/tests/protocol.py

Quoted 10 lines
python/tests/protocol.py new file +10 -0
+        self._asyncRunner(self.testFakeRecv_())
+
+    async def testFakeSend_(self):
+        await self.proto.accept('/not/a/real/path')
+
+        logname = self.proto.logger.name
+        with self.assertLogs(logname, level='DEBUG') as context:
+            # Cheat: Send a Null message to nobody.
+            await self.proto.send_msg()
+            # Kick writer; awaiting on a queue.put isn't sufficient to

yield.

Quoted 58 lines
python/tests/protocol.py new file +58 -0
+            await asyncio.sleep(0)
+
+        self.assertEqual(
+            context.output,
+            [f"DEBUG:{logname}:--> None"],
+        )
+
+    def testFakeSend(self):
+        """Test sending a fake/null message."""
+        self._asyncRunner(self.testFakeSend_())
+
+    async def _prod_session_api(
+            self,
+            current_state: Runstate,
+            error_message: str,
+            accept: bool = True
+    ):
+        with self.assertRaises(StateError) as context:
+            if accept:
+                await self.proto.accept('/not/a/real/path')
+            else:
+                await self.proto.connect('/not/a/real/path')
+
+        self.assertEqual(context.exception.error_message, error_message)
+        self.assertEqual(context.exception.state, current_state)
+        self.assertEqual(context.exception.required, Runstate.IDLE)
+
+    async def testAcceptRequireRunning_(self):
+        await self.proto.accept('/not/a/real/path')
+
+        await self._prod_session_api(
+            Runstate.RUNNING,
+            "NullProtocol is already connected and running.",
+            accept=True,
+        )
+
+    def testAcceptRequireRunning(self):
+        """Test that accept() cannot be called when Runstate=RUNNING"""
+        self._asyncRunner(self.testAcceptRequireRunning_())
+
+    async def testConnectRequireRunning_(self):
+        await self.proto.accept('/not/a/real/path')
+
+        await self._prod_session_api(
+            Runstate.RUNNING,
+            "NullProtocol is already connected and running.",
+            accept=False,
+        )
+
+    def testConnectRequireRunning(self):
+        """Test that connect() cannot be called when Runstate=RUNNING"""
+        self._asyncRunner(self.testConnectRequireRunning_())
+
+    async def testAcceptRequireDisconnecting_(self):
+        await self.proto.accept('/not/a/real/path')
+
+        # Cheat: force a disconnect.
+        await self.proto.simulate_disconnect()

python/tests/protocol.py

Quoted 10 lines
python/tests/protocol.py new file +10 -0
+
+        await self._prod_session_api(
+            Runstate.DISCONNECTING,
+            ("NullProtocol is disconnecting."
+             " Call disconnect() to return to IDLE state."),
+            accept=True,
+        )
+
+    def testAcceptRequireDisconnecting(self):
+        """Test that accept() cannot be called when

Runstate=DISCONNECTING"""

Quoted 7 lines
python/tests/protocol.py new file +7 -0
+        self._asyncRunner(self.testAcceptRequireDisconnecting_())
+
+    async def testConnectRequireDisconnecting_(self):
+        await self.proto.accept('/not/a/real/path')
+
+        # Cheat: force a disconnect.
+        await self.proto.simulate_disconnect()

python/tests/protocol.py

Quoted 10 lines
python/tests/protocol.py new file +10 -0
+
+        await self._prod_session_api(
+            Runstate.DISCONNECTING,
+            ("NullProtocol is disconnecting."
+             " Call disconnect() to return to IDLE state."),
+            accept=False,
+        )
+
+    def testConnectRequireDisconnecting(self):
+        """Test that connect() cannot be called when

Runstate=DISCONNECTING"""

Quoted 3 lines
python/tests/protocol.py new file +1 -1
+        self._asyncRunner(self.testConnectRequireDisconnecting_())
--

2.31.1

Besides that, I just would like to bring to the table that Avocado has now a basic support for coroutines as tests that might help here. IIUC, some of the boilerplate code (and duplicated methods) could be removed with this:

Quoted 6 lines

https://github.com/avocado-framework/avocado/pull/4788

In any case, I understand if the latest version is not an option here, so:

It's an option, it's time that is the harsh master.

Quoted 3 lines

Thanks! I updated a few bits and pieces and added the other items to a list of things to do "later".

Quoted 5 lines

Thanks,
--
Beraldo

--js

#3 lore raw

Re: [PATCH v2 02/24] python/aqmp: add error classes

In reply to John Snow
Quoted 9 lines · John Snow
---
 python/qemu/aqmp/__init__.py |  4 +++
 python/qemu/aqmp/error.py    | 50 ++++++++++++++++++++++++++++++++++++
 2 files changed, 54 insertions(+)
 create mode 100644 python/qemu/aqmp/error.py

+++ b/python/qemu/aqmp/error.py

python/qemu/aqmp/error.py line 43

Quoted 8 lines
python/qemu/aqmp/error.py new file +7 -0
@@ -0,0 +1,50 @@
 
+
+class ProtocolError(AQMPError):
+    """
+    Abstract error class for protocol failures.
+
+    Semantically, these errors are generally the fault of either the
+    protocol server or as a result of a bug in this this library.

duplicate 'this'

Signature · 3 lines
Eric Blake, Principal Software Engineer
Red Hat, Inc.           +1-919-301-3266
Virtualization:  qemu.org | libvirt.org
author
#4 lore raw

Re: [PATCH v2 02/24] python/aqmp: add error classes

Got it. I was *just* about to send a refreshed version of this patchset because I found a new bug while on my way to making a sync compatibility shim for iotests -- Do you have more feedback cooking, or should I hit the send button?

--js

Quoted 27 lines · Eric Blake
Quoted 9 lines · John Snow
---
 python/qemu/aqmp/__init__.py |  4 +++
 python/qemu/aqmp/error.py    | 50 ++++++++++++++++++++++++++++++++++++
 2 files changed, 54 insertions(+)
 create mode 100644 python/qemu/aqmp/error.py

+++ b/python/qemu/aqmp/error.py

python/qemu/aqmp/error.py line 43

Quoted 8 lines
python/qemu/aqmp/error.py new file +7 -0
@@ -0,0 +1,50 @@
 
+
+class ProtocolError(AQMPError):
+    """
+    Abstract error class for protocol failures.
+
+    Semantically, these errors are generally the fault of either the
+    protocol server or as a result of a bug in this this library.

duplicate 'this'

--
Eric Blake, Principal Software Engineer
Red Hat, Inc. +1-919-301-3266
Virtualization: qemu.org | libvirt.org

Reviewed-by
#5 lore raw

Re: [PATCH v2 02/24] python/aqmp: add error classes

Quoted 4 lines · John Snow

Got it. I was *just* about to send a refreshed version of this patchset because I found a new bug while on my way to making a sync compatibility shim for iotests -- Do you have more feedback cooking, or should I hit the send button?

I spotted another typo while browsing the web page (disconnect() "If there were was an exception"), but I'm fine if you re-send, and I'll resume looking at the series on the updated v3. For 1-6, you can add:

although my python is weak enough that you may want another set of eyes as well.

Signature · 3 lines
Eric Blake, Principal Software Engineer
Red Hat, Inc.           +1-919-301-3266
Virtualization:  qemu.org | libvirt.org
author
#6 lore raw

Re: [PATCH v2 02/24] python/aqmp: add error classes

Quoted 10 lines · Eric Blake
Quoted 3 lines · John Snow

Got it. I was *just* about to send a refreshed version of this patchset because I found a new bug while on my way to making a sync compatibility shim for iotests -- Do you have more feedback cooking, or should I hit

the

Quoted 1 line

send button?

I spotted another typo while browsing the web page (disconnect() "If there were was an exception"), but I'm fine if you re-send, and I'll

Thanks for spotting that. Your proofreading ability is admired and appreciated :)

Quoted 8 lines

resume looking at the series on the updated v3. For 1-6, you can add:

although my python is weak enough that you may want another set of eyes as well.

Thanks! Review on overall design, documentation, layout, organization and presentation is plenty helpful even if you aren't necessarily eagle-eyed on minutiae of Python. (Maybe especially if?)
I've written quite a few tests and have used this library to run our entire iotests suite, plus Niteesh has been banging the bits pretty hard while working on aqmp-shell, so I am not too fearful of mechanical errors.