Skip to contentSkip to conversation

python: introduce Asynchronous QMP package

PATCH Superseded John Snow 3 participants 25 messages Jul 1, 2021 – Jul 8, 2021

v1 of 4 Superseded Latest is v4 →

lore
Share & tools
lore

John Snow

author
#0 lore raw

cover python: introduce Asynchronous QMP package

GitLab: https://gitlab.com/jsnow/qemu/-/commits/python-async-qmp-aqmp
CI: https://gitlab.com/jsnow/qemu/-/pipelines/330003554
Docs: https://people.redhat.com/~jsnow/sphinx/html/qemu.aqmp.html
Based-on: <[email protected]>

          [PULL 00/15] Python patches

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

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.

Ugly Bits
=========

- MultiException is ... wonky. I am still working out how to avoid needing it. See patch 04/20 for details here, or see
https://people.redhat.com/~jsnow/sphinx/html/qemu.aqmp.error.html

Patch 06/20 also goes into details of the ugliness; see AsyncProtocol._results or view the same information here:
https://people.redhat.com/~jsnow/sphinx/html/_modules/qemu/aqmp/protocol.html#AsyncProtocol._results

- There are quite a few lingering questions I have over the design of the EventListener subsystem; I wrote about those ugly bits in excruciating detail in patch 14/20.

You can view them formatted nicely here:
https://people.redhat.com/~jsnow/sphinx/html/qemu.aqmp.events.html#experimental-interfaces-design-issues

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

Patches 1-2 are tiny pylint configuration changes.
Patches 3-5 begin to check in Async QMP components, they are small. Patches 6-11 add a generic async message-based protocol class,
AsyncProto. They are split as small as I could reasonably split them.
Patches 12-14 check in more QMP-specific components.
Patches 15-18 add qmp_protocol.py, the new 'QMP' class. They're split as
far down as I could, I hope they're easy to review.
Patches 19-20 add a few finishing touches, they are small patches.

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.

- A QMP server class; to facilitate writing of unit tests.

- Unit tests. Real unit tests.

If you made it this far in the cover letter, congrats :)

John Snow (20):
python/pylint: Add exception for TypeVar names ('T') python/pylint: disable too-many-function-args python/aqmp: add asynchronous QMP (AQMP) subpackage python/aqmp: add error classes
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 to AsyncProtocol python/aqmp: add AsyncProtocol.accept() method 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/aqmp: add QMP protocol support
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/qemu/aqmp/__init__.py     |  61 +++
 python/qemu/aqmp/error.py        |  97 ++++
 python/qemu/aqmp/events.py       | 878 +++++++++++++++++++++++++++++++
 python/qemu/aqmp/message.py      | 207 ++++++++
 python/qemu/aqmp/models.py       | 133 +++++
 python/qemu/aqmp/protocol.py     | 851 ++++++++++++++++++++++++++++++
 python/qemu/aqmp/py.typed        |   0
 python/qemu/aqmp/qmp_protocol.py | 565 ++++++++++++++++++++
 python/qemu/aqmp/util.py         | 183 +++++++
 python/setup.cfg                 |   4 +-
 10 files changed, 2978 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_protocol.py
 create mode 100644 python/qemu/aqmp/util.py
Signature · 1 line
2.31.1
author
#1 lore raw

PATCH 1/20 python/pylint: Add exception for TypeVar names ('T')

'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 11f71d5312..cfbe17f0f6 100644
@@ -100,6 +100,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
#2 lore raw

PATCH 2/20 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 cfbe17f0f6..e1c48eb706 100644
@@ -87,7 +87,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
#3 lore raw

PATCH 3/20 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 0000000000..4c713b3ccf
@@ -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.
+
+:py:class:`~qmp_protocol.QMP` 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 0000000000..e69de29bb2
python/setup.cfg +1 -0
index e1c48eb706..bce8807702 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
#4 lore raw

PATCH 4/20 python/aqmp: add error classes

In reply to John Snow
---
 python/qemu/aqmp/__init__.py |  7 +++
 python/qemu/aqmp/error.py    | 97 ++++++++++++++++++++++++++++++++++++
 2 files changed, 104 insertions(+)
 create mode 100644 python/qemu/aqmp/error.py
python/qemu/aqmp/__init__.py +7 -0
index 4c713b3ccf..8e955d784d 100644
@@ -21,7 +21,14 @@
 # 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, MultiException
+
 
 # The order of these fields impact the Sphinx documentation order.
 __all__ = (
+    # Exceptions
+    'AQMPError',
+
+    # Niche topics
+    'MultiException',
 )
python/qemu/aqmp/error.py new file +97 -0

97 lines not on this page · raw message

Signature · 1 line
2.31.1
author
#5 lore raw

PATCH 5/20 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 | 77 ++++++++++++++++++++++++++++++++++++++++
 1 file changed, 77 insertions(+)
 create mode 100644 python/qemu/aqmp/util.py
python/qemu/aqmp/util.py new file +77 -0
new file mode 100644
index 0000000000..c88a2201bc
@@ -0,0 +1,77 @@
+"""
+Miscellaneous Utilities
+
+This module primarily provides 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,
+)
+
+
+T = TypeVar('T')
+
+
+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.
+    """
+    # Python 3.7+:
+    if sys.version_info >= (3, 7):
+        # pylint: disable=no-member
+        if loop is not None:
+            return loop.create_task(coro)
+        return asyncio.create_task(coro)
+
+    # 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 hasattr(writer, 'is_closing'):
+        # Python 3.7+
+        return writer.is_closing()  # type: ignore
+
+    # 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 hasattr(writer, 'wait_closed'):
+        # Python 3.7+
+        await writer.wait_closed()  # type: ignore
+    else:
+        # Python 3.6
+        transport = writer.transport
+        assert isinstance(transport, asyncio.WriteTransport)
+
+        while not transport.is_closing():
+            await asyncio.sleep(0.0)
+        while transport.get_write_buffer_size() > 0:
+            await asyncio.sleep(0.0)
Signature · 1 line
2.31.1
author
#6 lore raw

PATCH 6/20 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

---

A note for reviewers: If you believe that it is unsafe to call certain methods at certain times, you're absolutely correct! These interfaces are protected in the following commit.

Some of the docstrings have dangling references, but they will resolve themselves within the next few commits. Forgive me for not wanting to rewrite them ... !

---
 python/qemu/aqmp/__init__.py |   4 +-
 python/qemu/aqmp/protocol.py | 523 +++++++++++++++++++++++++++++++++++
 python/qemu/aqmp/util.py     |  54 ++++
 3 files changed, 580 insertions(+), 1 deletion(-)
 create mode 100644 python/qemu/aqmp/protocol.py
python/qemu/aqmp/__init__.py +3 -1
index 8e955d784d..e003c898bd 100644
@@ -22,12 +22,14 @@
 # the COPYING file in the top-level directory.
 
 from .error import AQMPError, MultiException
+from .protocol import ConnectError
 
 
 # The order of these fields impact the Sphinx documentation order.
 __all__ = (
-    # Exceptions
+    # Exceptions, most generic to most explicit
     'AQMPError',
+    'ConnectError',
 
     # Niche topics
     'MultiException',
python/qemu/aqmp/protocol.py new file +523 -0

523 lines not on this page · raw message

python/qemu/aqmp/util.py +54 -0

69 lines not on this page · raw message

Signature · 1 line
2.31.1
author
#7 lore raw

PATCH 7/20 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 | 133 +++++++++++++++++++++++++++++++++--
 2 files changed, 133 insertions(+), 5 deletions(-)
python/qemu/aqmp/__init__.py +4 -1
index e003c898bd..5c44fabeea 100644
@@ -22,11 +22,14 @@
 # the COPYING file in the top-level directory.
 
 from .error import AQMPError, MultiException
-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 +129 -4

219 lines not on this page · raw message

Signature · 1 line
2.31.1
author
#8 lore raw

PATCH 8/20 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 | 64 ++++++++++++++++++++++++++++++++----
 python/qemu/aqmp/util.py     | 32 ++++++++++++++++++
 2 files changed, 90 insertions(+), 6 deletions(-)
python/qemu/aqmp/protocol.py +58 -6
index a99a191982..dd8564ee02 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,
@@ -34,6 +35,7 @@
     create_task,
     flush,
     is_closing,
+    pretty_traceback,
     upper_half,
     wait_closed,
     wait_task_done,
@@ -174,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
@@ -212,6 +228,15 @@ def __init__(self) -> None:
         #: An `asyncio.Event` that signals when `runstate` is changed.
         self.runstate_changed: asyncio.Event = asyncio.Event()
 
+    def __repr__(self) -> str:
+        argstr = ''
+        if self.name is not None:
+            argstr += f"name={self.name}"
+        return "{:s}({:s})".format(
+            type(self).__name__,
+            argstr,
+        )
+
     @property
     def runstate(self) -> Runstate:
         """The current `Runstate` of the connection."""
@@ -301,6 +326,8 @@ async def _new_session(self,
         assert self.runstate == Runstate.IDLE
         self._set_state(Runstate.CONNECTING)
 
+        if not self._outgoing.empty():
+            self.logger.warning("Outgoing message queue was not empty!")
         self._outgoing = asyncio.Queue()
 
         phase = "connection"
@@ -311,9 +338,15 @@ async def _new_session(self,
             await self._begin_new_session()
 
         except Exception as err:
-            # Reset from CONNECTING back to IDLE.
-            await self.disconnect()
             emsg = f"Failed to establish {phase}"
+            self.logger.error("%s:\n%s\n", emsg, pretty_traceback())
+            try:
+                # Reset from CONNECTING back to IDLE.
+                await self.disconnect()
+            except:
+                emsg = "Unexpected bottom half exceptions"
+                self.logger.error("%s:\n%s\n", emsg, pretty_traceback())
+                raise
             raise ConnectError(emsg, err) from err
 
         assert self.runstate == Runstate.RUNNING
@@ -330,12 +363,16 @@ async def _do_connect(self, address: Union[str, Tuple[str, int]],
 
         :raise OSError: For stream-related errors.
         """
+        self.logger.debug("Connecting ...")
+
         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 _begin_new_session(self) -> None:
         """
@@ -343,8 +380,8 @@ async def _begin_new_session(self) -> None:
         """
         assert self.runstate == Runstate.CONNECTING
 
-        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)
@@ -374,6 +411,7 @@ def _schedule_disconnect(self, force: bool = False) -> None:
             terminating execution. When `True`, terminate immediately.
         """
         if not self._dc_task:
+            self.logger.debug("scheduling disconnect.")
             self._dc_task = create_task(self._bh_disconnect(force))
 
     @upper_half
@@ -499,8 +537,13 @@ async def _bh_disconnect(self, force: bool = False) -> None:
         # 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 writer to close.")
             await wait_closed(self._writer)
+            self.logger.debug("Writer closed.")
+
+        self.logger.debug("Disconnected.")
 
     @bottom_half
     async def _bh_stop_writer(self, force: bool = False) -> None:
@@ -513,17 +556,19 @@ async def _bh_stop_writer(self, force: bool = False) -> None:
 
         # Cancel the writer task.
         if self._writer_task and not self._writer_task.done():
+            self.logger.debug("Cancelling writer task.")
             self._writer_task.cancel()
         await wait_task_done(self._writer_task)
 
     @bottom_half
     async def _bh_stop_reader(self) -> None:
         if self._reader_task and not self._reader_task.done():
+            self.logger.debug("Cancelling reader task.")
             self._reader_task.cancel()
         await wait_task_done(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.
 
@@ -531,16 +576,23 @@ 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:
+            self.logger.error(
+                "Task.%s: failure:\n%s\n", name, pretty_traceback()
+            )
             self._schedule_disconnect(force=True)
             raise
+        finally:
+            self.logger.debug("Task.%s: exiting.", name)
 
     @bottom_half
     async def _bh_send_message(self) -> None:
python/qemu/aqmp/util.py +32 -0
index 9ea91f2862..2311be5893 100644
@@ -3,10 +3,14 @@
 
 This module primarily provides compatibility wrappers for Python 3.6 to
 provide some features that otherwise become available in Python 3.7+.
+
+It additionally provides `pretty_traceback()`, used for formatting
+tracebacks for inclusion in the logging stream.
 """
 
 import asyncio
 import sys
+import traceback
 from typing import (
     Any,
     Coroutine,
@@ -105,6 +109,34 @@ async def wait_task_done(task: Optional['asyncio.Future[Any]']) -> None:
             break
 
 
+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])
+
+
 def upper_half(func: T) -> T:
     """
     Do-nothing decorator that annotates a method as an "upper-half" method.
Signature · 1 line
2.31.1
author
#9 lore raw

PATCH 9/20 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 | 85 ++++++++++++++++++++++++++++++++++--
 1 file changed, 82 insertions(+), 3 deletions(-)
python/qemu/aqmp/protocol.py +82 -3
index dd8564ee02..a32a8cbbf6 100644
@@ -242,6 +242,24 @@ def runstate(self) -> Runstate:
         """The current `Runstate` of the connection."""
         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]],
@@ -302,7 +320,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.
 
@@ -311,9 +330,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.
@@ -332,7 +352,10 @@ async def _new_session(self,
 
         phase = "connection"
         try:
-            await self._do_connect(address, ssl)
+            if accept:
+                await self._do_accept(address, ssl)
+            else:
+                await self._do_connect(address, ssl)
 
             phase = "session"
             await self._begin_new_session()
@@ -351,6 +374,62 @@ async def _new_session(self,
 
         assert self.runstate == Runstate.RUNNING
 
+    @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 ...")
+        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]],
                           ssl: Optional[SSLContext] = None) -> None:
Signature · 1 line
2.31.1
author
#10 lore raw

PATCH 10/20 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 a32a8cbbf6..72c9e95198 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
@@ -700,6 +705,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:
@@ -728,8 +770,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
@@ -759,7 +801,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
@@ -774,6 +816,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
#11 lore raw

PATCH 11/20 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 | 30 ++++++++++++++++++++++++++++++
 1 file changed, 30 insertions(+)
python/qemu/aqmp/protocol.py +30 -0
index 72c9e95198..6a2a7be056 100644
@@ -742,6 +742,36 @@ 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 4 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
#12 lore raw

PATCH 12/20 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  | 207 +++++++++++++++++++++++++++++++++++
 2 files changed, 210 insertions(+), 1 deletion(-)
 create mode 100644 python/qemu/aqmp/message.py
python/qemu/aqmp/__init__.py +3 -1
index 5c44fabeea..c1ec68a023 100644
@@ -22,12 +22,14 @@
 # the COPYING file in the top-level directory.
 
 from .error import AQMPError, MultiException
+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 +207 -0

207 lines not on this page · raw message

Signature · 1 line
2.31.1
#13 lore raw

Re: [PATCH 12/20] python/aqmp: add QMP Message format

Quoted 146 lines · 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  | 207 +++++++++++++++++++++++++++++++++++
 2 files changed, 210 insertions(+), 1 deletion(-)
 create mode 100644 python/qemu/aqmp/message.py
python/qemu/aqmp/__init__.py +3 -1
index 5c44fabeea..c1ec68a023 100644
@@ -22,12 +22,14 @@
 # the COPYING file in the top-level directory.
 
 from .error import AQMPError, MultiException
+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 +78 -0
new file mode 100644
index 0000000000..3a4b283032
@@ -0,0 +1,207 @@
+"""
+QMP Message Format
+
+This module provides the `Message` class, which represents a single QMP
+message sent to or from the server.
+"""
+
+import json
+from json import JSONDecodeError
+from typing import (
+    Dict,
+    Iterator,
+    Mapping,
+    MutableMapping,
+    Optional,
+    Union,
+)
+
+from .error import ProtocolError
+
+
+class Message(MutableMapping[str, object]):
+    """
+    Represents a single QMP protocol message.
+
+    QMP uses JSON objects as its basic communicative unit; so this
+    Python object is a :py:obj:`~collections.abc.MutableMapping`. It may
+    be instantiated from either another mapping (like a `dict`), or from
+    raw `bytes` that still need to be deserialized.
+
+    Once instantiated, it may be treated like any other MutableMapping::
+
+        >>> msg = Message(b'{"hello": "world"}')
+        >>> assert msg['hello'] == 'world'
+        >>> msg['id'] = 'foobar'
+        >>> print(msg)
+        {
+          "hello": "world",
+          "id": "foobar"
+        }
+
+    It can be converted to `bytes`::
+
+        >>> msg = Message({"hello": "world"})
+        >>> print(bytes(msg))
+        b'{"hello":"world","id":"foobar"}'
+
+    Or back into a garden-variety `dict`::
+
+       >>> dict(msg)
+       {'hello': 'world'}
+
+
+    :param value: Initial value, if any.
+    :param eager:
+        When `True`, attempt to serialize or deserialize the initial value
+        immediately, so that conversion exceptions are raised during
+        the call to ``__init__()``.
+    """
+    # pylint: disable=too-many-ancestors
+
+    def __init__(self,
+                 value: Union[bytes, Mapping[str, object]] = b'', *,
+                 eager: bool = True):
+        self._data: Optional[bytes] = None
+        self._obj: Optional[Dict[str, object]] = None
+
+        if isinstance(value, bytes):
+            self._data = value
+            if eager:
+                self._obj = self._deserialize(self._data)
+        else:
+            self._obj = dict(value)
+            if eager:
+                self._data = self._serialize(self._obj)
+
+    # Methods necessary to implement the MutableMapping interface, see:
+    #

https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping

python/qemu/aqmp/message.py new file +27 -0
+
+    # We get pop, popitem, clear, update, setdefault, __contains__,
+    # keys, items, values, get, __eq__ and __ne__ for free.
+
+    def __getitem__(self, key: str) -> object:
+        return self._object[key]
+
+    def __setitem__(self, key: str, value: object) -> None:
+        self._object[key] = value
+        self._data = None
+
+    def __delitem__(self, key: str) -> None:
+        del self._object[key]
+        self._data = None
+
+    def __iter__(self) -> Iterator[str]:
+        return iter(self._object)
+
+    def __len__(self) -> int:
+        return len(self._object)
+
+    # Dunder methods not related to MutableMapping:
+
+    def __repr__(self) -> str:
+        return f"Message({self._object!r})"
+
+    def __str__(self) -> str:

python/qemu/aqmp/message.py line 115

Quoted 10 lines
python/qemu/aqmp/message.py new file +10 -0
+        """Pretty-printed representation of this QMP message."""
+        return json.dumps(self._object, indent=2)
+
+    def __bytes__(self) -> bytes:
+        """bytes representing this QMP message."""
+        if self._data is None:
+            self._data = self._serialize(self._obj or {})
+        return self._data
+
+    #

Is this something intentional?

Quoted 96 lines
python/qemu/aqmp/message.py new file +92 -1
+
+    @property
+    def _object(self) -> Dict[str, object]:
+        """
+        A `dict` representing this QMP message.
+
+        Generated on-demand, if required. This property is private
+        because it returns an object that could be used to invalidate
+        the internal state of the `Message` object.
+        """
+        if self._obj is None:
+            self._obj = self._deserialize(self._data or b'')
+        return self._obj
+
+    @classmethod
+    def _serialize(cls, value: object) -> bytes:
+        """
+        Serialize a JSON object as `bytes`.
+
+        :raise ValueError: When the object cannot be serialized.
+        :raise TypeError: When the object cannot be serialized.
+
+        :return: `bytes` ready to be sent over the wire.
+        """
+        return json.dumps(value, separators=(',', ':')).encode('utf-8')
+
+    @classmethod
+    def _deserialize(cls, data: bytes) -> Dict[str, object]:
+        """
+        Deserialize JSON `bytes` into a native Python `dict`.
+
+        :raise DeserializationError:
+            If JSON deserialization fails for any reason.
+        :raise UnexpectedTypeError:
+            If the data does not represent a JSON object.
+
+        :return: A `dict` representing this QMP message.
+        """
+        try:
+            obj = json.loads(data)
+        except JSONDecodeError as err:
+            emsg = "Failed to deserialize QMP message."
+            raise DeserializationError(emsg, data) from err
+        if not isinstance(obj, dict):
+            raise UnexpectedTypeError(
+                "QMP message is not a JSON object.",
+                obj
+            )
+        return obj
+
+
+class DeserializationError(ProtocolError):
+    """
+    A QMP message was not understood as JSON.
+
+    When this Exception is raised, ``__cause__`` will be set to the
+    `json.JSONDecodeError` Exception, which can be interrogated for
+    further details.
+
+    :param error_message: Human-readable string describing the error.
+    :param raw: The raw `bytes` that prompted the failure.
+    """
+    def __init__(self, error_message: str, raw: bytes):
+        super().__init__(error_message)
+        #: The raw `bytes` that were not understood as JSON.
+        self.raw: bytes = raw
+
+    def __str__(self) -> str:
+        return "\n".join([
+            super().__str__(),
+            f"  raw bytes were: {str(self.raw)}",
+        ])
+
+
+class UnexpectedTypeError(ProtocolError):
+    """
+    A QMP message was JSON, but not a JSON object.
+
+    :param error_message: Human-readable string describing the error.
+    :param value: The deserialized JSON value that wasn't an object.
+    """
+    def __init__(self, error_message: str, value: object):
+        super().__init__(error_message)
+        #: The JSON value that was expected to be an object.
+        self.value: object = value
+
+    def __str__(self) -> str:
+        strval = json.dumps(self.value, indent=2)
+        return "\n".join([
+            super().__str__(),
+            f"  json value was: {strval}",
+        ])
--

2.31.1

author
#14 lore raw

Re: [PATCH 12/20] python/aqmp: add QMP Message format

Quoted 154 lines · Niteesh G. S.
Quoted 150 lines · 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  | 207 +++++++++++++++++++++++++++++++++++
 2 files changed, 210 insertions(+), 1 deletion(-)
 create mode 100644 python/qemu/aqmp/message.py
python/qemu/aqmp/__init__.py +3 -1
index 5c44fabeea..c1ec68a023 100644
@@ -22,12 +22,14 @@
 # the COPYING file in the top-level directory.
 
 from .error import AQMPError, MultiException
+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 +56 -0
new file mode 100644
index 0000000000..3a4b283032
@@ -0,0 +1,207 @@
+"""
+QMP Message Format
+
+This module provides the `Message` class, which represents a single QMP
+message sent to or from the server.
+"""
+
+import json
+from json import JSONDecodeError
+from typing import (
+    Dict,
+    Iterator,
+    Mapping,
+    MutableMapping,
+    Optional,
+    Union,
+)
+
+from .error import ProtocolError
+
+
+class Message(MutableMapping[str, object]):
+    """
+    Represents a single QMP protocol message.
+
+    QMP uses JSON objects as its basic communicative unit; so this
+    Python object is a :py:obj:`~collections.abc.MutableMapping`. It may
+    be instantiated from either another mapping (like a `dict`), or from
+    raw `bytes` that still need to be deserialized.
+
+    Once instantiated, it may be treated like any other MutableMapping::
+
+        >>> msg = Message(b'{"hello": "world"}')
+        >>> assert msg['hello'] == 'world'
+        >>> msg['id'] = 'foobar'
+        >>> print(msg)
+        {
+          "hello": "world",
+          "id": "foobar"
+        }
+
+    It can be converted to `bytes`::
+
+        >>> msg = Message({"hello": "world"})
+        >>> print(bytes(msg))
+        b'{"hello":"world","id":"foobar"}'
+
+    Or back into a garden-variety `dict`::
+
+       >>> dict(msg)
+       {'hello': 'world'}
+
+
+    :param value: Initial value, if any.
+    :param eager:
+        When `True`, attempt to serialize or deserialize the initial

value

python/qemu/aqmp/message.py new file +22 -0
+        immediately, so that conversion exceptions are raised during
+        the call to ``__init__()``.
+    """
+    # pylint: disable=too-many-ancestors
+
+    def __init__(self,
+                 value: Union[bytes, Mapping[str, object]] = b'', *,
+                 eager: bool = True):
+        self._data: Optional[bytes] = None
+        self._obj: Optional[Dict[str, object]] = None
+
+        if isinstance(value, bytes):
+            self._data = value
+            if eager:
+                self._obj = self._deserialize(self._data)
+        else:
+            self._obj = dict(value)
+            if eager:
+                self._data = self._serialize(self._obj)
+
+    # Methods necessary to implement the MutableMapping interface, see:
+    #

https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping

python/qemu/aqmp/message.py new file +31 -0
+
+    # We get pop, popitem, clear, update, setdefault, __contains__,
+    # keys, items, values, get, __eq__ and __ne__ for free.
+
+    def __getitem__(self, key: str) -> object:
+        return self._object[key]
+
+    def __setitem__(self, key: str, value: object) -> None:
+        self._object[key] = value
+        self._data = None
+
+    def __delitem__(self, key: str) -> None:
+        del self._object[key]
+        self._data = None
+
+    def __iter__(self) -> Iterator[str]:
+        return iter(self._object)
+
+    def __len__(self) -> int:
+        return len(self._object)
+
+    # Dunder methods not related to MutableMapping:
+
+    def __repr__(self) -> str:
+        return f"Message({self._object!r})"
+
+    def __str__(self) -> str:
+        """Pretty-printed representation of this QMP message."""
+        return json.dumps(self._object, indent=2)
+
+    def __bytes__(self) -> bytes:
Quoted 9 lines

python/qemu/aqmp/message.py line 115

Quoted 7 lines
python/qemu/aqmp/message.py new file +6 -0
+        """bytes representing this QMP message."""
+        if self._data is None:
+            self._data = self._serialize(self._obj or {})
+        return self._data
+
+    #

Is this something intentional?

Err, oops, kind of. I sometimes use little comment blocks to delineate sections of methods. Above, I have a "MutableMapping" section, and then a "Dunder method" section, and this marks the end of the dunder method section, but I neglected to give it its own title. I suppose I could name it "Conversion Methods" or similar.

Thanks,
--js

author
#15 lore raw

PATCH 13/20 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 0000000000..24c94123ac
@@ -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
#16 lore raw

PATCH 14/20 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 file.

It gets quite a bit too long otherwise.

---

Yes, the docstring is long. I recommend looking at the generated Sphinx output for that part instead. You can review the markup itself if you are a masochist.

---
 python/qemu/aqmp/__init__.py |   2 +
 python/qemu/aqmp/events.py   | 878 +++++++++++++++++++++++++++++++++++
 2 files changed, 880 insertions(+)
 create mode 100644 python/qemu/aqmp/events.py
python/qemu/aqmp/__init__.py +2 -0
index c1ec68a023..ae87436470 100644
@@ -22,6 +22,7 @@
 # the COPYING file in the top-level directory.
 
 from .error import AQMPError, MultiException
+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 +878 -0

878 lines not on this page · raw message

Signature · 1 line
2.31.1
author
#17 lore raw

PATCH 15/20 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 two commits.

---
 python/qemu/aqmp/__init__.py     |   2 +
 python/qemu/aqmp/qmp_protocol.py | 257 +++++++++++++++++++++++++++++++
 2 files changed, 259 insertions(+)
 create mode 100644 python/qemu/aqmp/qmp_protocol.py
python/qemu/aqmp/__init__.py +2 -0
index ae87436470..68d98cca75 100644
@@ -25,11 +25,13 @@
 from .events import EventListener
 from .message import Message
 from .protocol import ConnectError, Runstate
+from .qmp_protocol import QMP
 
 
 # The order of these fields impact the Sphinx documentation order.
 __all__ = (
     # Classes, most to least important
+    'QMP',
     'Message',
     'EventListener',
     'Runstate',
python/qemu/aqmp/qmp_protocol.py new file +257 -0

257 lines not on this page · raw message

Signature · 1 line
2.31.1
author
#18 lore raw

PATCH 16/20 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_protocol.py | 98 +++++++++++++++++++++++++++++++-
 1 file changed, 96 insertions(+), 2 deletions(-)
python/qemu/aqmp/qmp_protocol.py +96 -2
index 5872bfc017..04c8a8cb54 100644
@@ -7,15 +7,18 @@
 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,
 )
 
-from .error import ProtocolError
+from .error import AQMPError, ProtocolError
 from .events import Events
 from .message import Message
 from .models import Greeting
@@ -56,6 +59,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 QMP(AsyncProtocol[Message], Events):
     """
     Implements a QMP client connection.
@@ -98,6 +148,9 @@ async def run(self, address='/tmp/qemu.socket'):
     #: Logger object used for debugging messages.
     logger = logging.getLogger(__name__)
 
+    # 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)
@@ -112,6 +165,9 @@ 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[str, 'asyncio.Queue[QMP._PendingT]'] = {}
+
     @upper_half
     async def _begin_new_session(self) -> None:
         """
@@ -191,10 +247,27 @@ async def _negotiate(self) -> None:
             self.logger.error("%s:\n%s\n", emsg, pretty_traceback())
             raise
 
+    @bottom_half
+    async def _bh_disconnect(self, force: bool = False) -> None:
+        await super()._bh_disconnect(force)
+
+        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.")
+
     @bottom_half
     async def _on_message(self, msg: Message) -> None:
         """
         Add an incoming message to the appropriate queue/handler.
+
+        :raise ServerParseError: When Message has no 'event' nor 'id' member
         """
         # Incoming messages are not fully parsed/validated here;
         # do only light peeking to know how to route the messages.
@@ -204,7 +277,27 @@ 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!
+
+        if 'id' not in msg:
+            # 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 a message without an ID,"
+                                   " indicating parse failure.", msg)
+
+        assert 'id' in msg
+        exec_id = str(msg['id'])
+
+        if exec_id not in self._pending:
+            # qmp-spec.txt, section 2.4:
+            # 'Clients should drop all the responses
+            # that have an unknown "id" field.'
+            self.logger.warning("Unknown ID '%s', message dropped.", exec_id)
+            self.logger.debug("Unroutable message: %s", str(msg))
+            return
+
+        await self._pending[exec_id].put(msg)
 
     @upper_half
     @bottom_half
@@ -237,6 +330,7 @@ def _do_send(self, msg: Message) -> None:
     def _cleanup(self) -> None:
         super()._cleanup()
         self._greeting = None
+        assert not self._pending
 
     @classmethod
     def make_execute_msg(cls, cmd: str,
Signature · 1 line
2.31.1
author
#19 lore raw

PATCH 17/20 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_protocol.py | 203 +++++++++++++++++++++++++++++--
 2 files changed, 199 insertions(+), 8 deletions(-)
python/qemu/aqmp/__init__.py +3 -1
index 68d98cca75..5cd7df87c6 100644
@@ -25,7 +25,7 @@
 from .events import EventListener
 from .message import Message
 from .protocol import ConnectError, Runstate
-from .qmp_protocol import QMP
+from .qmp_protocol import QMP, ExecInterruptedError, ExecuteError
 
 
 # The order of these fields impact the Sphinx documentation order.
@@ -39,6 +39,8 @@
     # Exceptions, most generic to most explicit
     'AQMPError',
     'ConnectError',
+    'ExecuteError',
+    'ExecInterruptedError',
 
     # Niche topics
     'MultiException',
python/qemu/aqmp/qmp_protocol.py +196 -7

250 lines not on this page · raw message

Signature · 1 line
2.31.1
author
#20 lore raw

PATCH 18/20 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_protocol.py | 25 +++++++++++++++++++++++++
 1 file changed, 25 insertions(+)
python/qemu/aqmp/qmp_protocol.py +25 -0
index 3c16cdc213..36baef9fb3 100644
@@ -454,6 +454,31 @@ 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]
+    ) -> Message:
+        """
+        Issue a fairly raw `Message` to the QMP server and await a reply.
+
+        An AQMP execution ID will be assigned, so it isn't *truly* raw.
+
+        :param msg:
+            A Message to send to the server. It may be a `Message`, any
+            Mapping (including Dict), or raw bytes.
+
+        :return: Execution reply from the server.
+        :raise ExecInterruptedError:
+            When the reply could not be retrieved because the connection
+            was lost, or some other problem.
+        """
+        # 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)
+        return await self._execute(msg)
+
     @upper_half
     @require(Runstate.RUNNING)
     async def execute_msg(self, msg: Message) -> object:
Signature · 1 line
2.31.1
author
#21 lore raw

PATCH 19/20 python/aqmp: add asyncio_run compatibility wrapper

In reply to John Snow

Merely as a convenience for users stuck on Python 3.6. It isn't used by the library itself.

---
 python/qemu/aqmp/util.py | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)
python/qemu/aqmp/util.py +20 -0
index 2311be5893..356323ac70 100644
@@ -109,6 +109,26 @@ async def wait_task_done(task: Optional['asyncio.Future[Any]']) -> None:
             break
 
 
+def asyncio_run(coro: Coroutine[Any, Any, T]) -> T:
+    """
+    Python 3.6-compatible `asyncio.run` wrapper.
+
+    :param coro: A coroutine to execute now.
+    :return: The return value from the coroutine.
+    """
+    # Python 3.7+
+    if hasattr(asyncio, 'run'):
+        # pylint: disable=no-member
+        return asyncio.run(coro)  # type: ignore
+
+    # Python 3.6
+    loop = asyncio.get_event_loop()
+    ret = loop.run_until_complete(coro)
+    loop.close()
+
+    return ret
+
+
 def pretty_traceback(prefix: str = "  | ") -> str:
     """
     Formats the current traceback, indented to provide visual distinction.
Signature · 1 line
2.31.1
author
#22 lore raw

PATCH 20/20 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 5cd7df87c6..f85500e0a2 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, MultiException
 from .events import EventListener
 from .message import Message
@@ -28,6 +30,18 @@
 from .qmp_protocol import QMP, ExecInterruptedError, ExecuteError
 
 
+_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
Acked-by on the v1 series
#23 lore raw
In reply to John Snow
Quoted 182 lines · John Snow

GitLab: https://gitlab.com/jsnow/qemu/-/commits/python-async-qmp-aqmp
CI: https://gitlab.com/jsnow/qemu/-/pipelines/330003554
Docs: https://people.redhat.com/~jsnow/sphinx/html/qemu.aqmp.html
Based-on: <[email protected]>

          [PULL 00/15] Python patches

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

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.

Ugly Bits
=========

- MultiException is ... wonky. I am still working out how to avoid needing it. See patch 04/20 for details here, or see
https://people.redhat.com/~jsnow/sphinx/html/qemu.aqmp.error.html

Patch 06/20 also goes into details of the ugliness; see AsyncProtocol._results or view the same information here:
https://people.redhat.com/~jsnow/sphinx/html/_modules/qemu/aqmp/protocol.html#AsyncProtocol._results

- There are quite a few lingering questions I have over the design of the EventListener subsystem; I wrote about those ugly bits in excruciating detail in patch 14/20.

You can view them formatted nicely here:
https://people.redhat.com/~jsnow/sphinx/html/qemu.aqmp.events.html#experimental-interfaces-design-issues

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

Patches 1-2 are tiny pylint configuration changes.
Patches 3-5 begin to check in Async QMP components, they are small. Patches 6-11 add a generic async message-based protocol class,
AsyncProto. They are split as small as I could reasonably split them.
Patches 12-14 check in more QMP-specific components.
Patches 15-18 add qmp_protocol.py, the new 'QMP' class. They're split as
far down as I could, I hope they're easy to review.
Patches 19-20 add a few finishing touches, they are small patches.

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.

- A QMP server class; to facilitate writing of unit tests.

- Unit tests. Real unit tests.

If you made it this far in the cover letter, congrats :)

John Snow (20):
python/pylint: Add exception for TypeVar names ('T') python/pylint: disable too-many-function-args python/aqmp: add asynchronous QMP (AQMP) subpackage python/aqmp: add error classes
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 to AsyncProtocol python/aqmp: add AsyncProtocol.accept() method 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/aqmp: add QMP protocol support
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/qemu/aqmp/__init__.py     |  61 +++
 python/qemu/aqmp/error.py        |  97 ++++
 python/qemu/aqmp/events.py       | 878 +++++++++++++++++++++++++++++++
 python/qemu/aqmp/message.py      | 207 ++++++++
 python/qemu/aqmp/models.py       | 133 +++++
 python/qemu/aqmp/protocol.py     | 851 ++++++++++++++++++++++++++++++
 python/qemu/aqmp/py.typed        |   0
 python/qemu/aqmp/qmp_protocol.py | 565 ++++++++++++++++++++
 python/qemu/aqmp/util.py         | 183 +++++++
 python/setup.cfg                 |   4 +-
 10 files changed, 2978 insertions(+), 1 deletion(-)
 create mode 100644 python/qemu/aqmp/__init__.py
Quoted 8 lines
 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_protocol.py
 create mode 100644 python/qemu/aqmp/util.py
author
#24 lore raw
Quoted 196 lines · Stefan Hajnoczi
Quoted 98 lines · John Snow

GitLab: https://gitlab.com/jsnow/qemu/-/commits/python-async-qmp-aqmp
CI: https://gitlab.com/jsnow/qemu/-/pipelines/330003554
Docs: https://people.redhat.com/~jsnow/sphinx/html/qemu.aqmp.html
Based-on: <[email protected]>

          [PULL 00/15] Python patches

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

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.

Quoted 8 lines

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.

Ugly Bits
=========

- MultiException is ... wonky. I am still working out how to avoid

needing it.

Quoted 6 lines

See patch 04/20 for details here, or see
https://people.redhat.com/~jsnow/sphinx/html/qemu.aqmp.error.html

Patch 06/20 also goes into details of the ugliness; see AsyncProtocol._results or view the same information here:

https://people.redhat.com/~jsnow/sphinx/html/_modules/qemu/aqmp/protocol.html#AsyncProtocol._results

Quoted 3 lines

- There are quite a few lingering questions I have over the design of the EventListener subsystem; I wrote about those ugly bits in excruciating

detail

Quoted 4 lines

in patch 14/20.

You can view them formatted nicely here:

https://people.redhat.com/~jsnow/sphinx/html/qemu.aqmp.events.html#experimental-interfaces-design-issues

Quoted 63 lines

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

Patches 1-2 are tiny pylint configuration changes.
Patches 3-5 begin to check in Async QMP components, they are small. Patches 6-11 add a generic async message-based protocol class,
AsyncProto. They are split as small as I could reasonably split them.
Patches 12-14 check in more QMP-specific components.
Patches 15-18 add qmp_protocol.py, the new 'QMP' class. They're split as
far down as I could, I hope they're easy to review.
Patches 19-20 add a few finishing touches, they are small patches.

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.

- A QMP server class; to facilitate writing of unit tests.

- Unit tests. Real unit tests.

If you made it this far in the cover letter, congrats :)

John Snow (20):
python/pylint: Add exception for TypeVar names ('T') python/pylint: disable too-many-function-args python/aqmp: add asynchronous QMP (AQMP) subpackage python/aqmp: add error classes
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 to AsyncProtocol python/aqmp: add AsyncProtocol.accept() method 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/aqmp: add QMP protocol support
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/qemu/aqmp/__init__.py     |  61 +++
 python/qemu/aqmp/error.py        |  97 ++++
 python/qemu/aqmp/events.py       | 878 +++++++++++++++++++++++++++++++
 python/qemu/aqmp/message.py      | 207 ++++++++
 python/qemu/aqmp/models.py       | 133 +++++
 python/qemu/aqmp/protocol.py     | 851 ++++++++++++++++++++++++++++++
 python/qemu/aqmp/py.typed        |   0
 python/qemu/aqmp/qmp_protocol.py | 565 ++++++++++++++++++++
 python/qemu/aqmp/util.py         | 183 +++++++
 python/setup.cfg                 |   4 +-
 10 files changed, 2978 insertions(+), 1 deletion(-)
 create mode 100644 python/qemu/aqmp/__init__.py
Quoted 8 lines
 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_protocol.py
 create mode 100644 python/qemu/aqmp/util.py
Quoted 2 lines

Brave of you, thanks :)

I am working on a V2 presently, with a bunch of avocado unit tests, which has revealed a few small bugs and inconsistencies. This version also adds a mock QMPServer class alongside the client, for the purposes of testing. I think once those pieces are done I will be quite happy to check it into the tree as an "alpha" version, though I'd still be very happy to get more feedback on the EventListener piece from anyone willing to browse the "parts I don't like about this" section of the docs:

https://people.redhat.com/~jsnow/sphinx/html/qemu.aqmp.events.html#experimental-interfaces-design-issues