From patchwork Sat Jul 17 00:32:29 2021 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Patchwork-Submitter: John Snow X-Patchwork-Id: 1506324 Return-Path: X-Original-To: incoming@patchwork.ozlabs.org Delivered-To: patchwork-incoming@bilbo.ozlabs.org Authentication-Results: ozlabs.org; spf=pass (sender SPF authorized) smtp.mailfrom=nongnu.org (client-ip=209.51.188.17; helo=lists.gnu.org; envelope-from=qemu-devel-bounces+incoming=patchwork.ozlabs.org@nongnu.org; receiver=) Authentication-Results: ozlabs.org; dkim=fail reason="signature verification failed" (1024-bit key; unprotected) header.d=redhat.com header.i=@redhat.com header.a=rsa-sha256 header.s=mimecast20190719 header.b=POqZDqX7; dkim-atps=neutral Received: from lists.gnu.org (lists.gnu.org [209.51.188.17]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (No client certificate requested) by ozlabs.org (Postfix) with ESMTPS id 4GRTcj3Wvbz9sWS for ; Sat, 17 Jul 2021 10:33:55 +1000 (AEST) Received: from localhost ([::1]:60146 helo=lists1p.gnu.org) by lists.gnu.org with esmtp (Exim 4.90_1) (envelope-from ) id 1m4YHA-0004N3-9h for incoming@patchwork.ozlabs.org; Fri, 16 Jul 2021 20:33:52 -0400 Received: from eggs.gnu.org ([2001:470:142:3::10]:37398) by lists.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1m4YGU-0004Mi-GV for qemu-devel@nongnu.org; Fri, 16 Jul 2021 20:33:10 -0400 Received: from us-smtp-delivery-124.mimecast.com ([170.10.133.124]:20734) by eggs.gnu.org with esmtps (TLS1.2:ECDHE_RSA_AES_256_GCM_SHA384:256) (Exim 4.90_1) (envelope-from ) id 1m4YGQ-00066l-5Y for qemu-devel@nongnu.org; Fri, 16 Jul 2021 20:33:09 -0400 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1626481983; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:cc:mime-version:mime-version:content-type:content-type: content-transfer-encoding:content-transfer-encoding; bh=5oP4cMzqjZI35yTQnGyd2UtibPqNO/orU+PFgeuSTOo=; b=POqZDqX7rceV5APNcQ3uyP6b6Vx9dI64km/vhMyDt2lAPynYpWwEfMKAinNCSvYRt4UEwM 4hisn9Xyd/1/096AjKgy3eEirdfo/kyN5ThXh+x/hRiuYiEqb5n/lYZhAQvBqGQ9MkMNZu Iz9atmadJkLbzjyaRAghPHFm7xB/ztA= Received: from mimecast-mx01.redhat.com (mimecast-mx01.redhat.com [209.132.183.4]) (Using TLS) by relay.mimecast.com with ESMTP id us-mta-504-nC80fMj5NCuim4TsTBr4eA-1; Fri, 16 Jul 2021 20:33:01 -0400 X-MC-Unique: nC80fMj5NCuim4TsTBr4eA-1 Received: from smtp.corp.redhat.com (int-mx06.intmail.prod.int.phx2.redhat.com [10.5.11.16]) (using TLSv1.2 with cipher AECDH-AES256-SHA (256/256 bits)) (No client certificate requested) by mimecast-mx01.redhat.com (Postfix) with ESMTPS id E999E362FA; Sat, 17 Jul 2021 00:33:00 +0000 (UTC) Received: from scv.redhat.com (ovpn-119-183.rdu2.redhat.com [10.10.119.183]) by smtp.corp.redhat.com (Postfix) with ESMTP id 103445C1A1; Sat, 17 Jul 2021 00:32:54 +0000 (UTC) From: John Snow To: qemu-devel@nongnu.org Subject: [PATCH v2 00/24] python: introduce Asynchronous QMP package Date: Fri, 16 Jul 2021 20:32:29 -0400 Message-Id: <20210717003253.457418-1-jsnow@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 2.79 on 10.5.11.16 Authentication-Results: relay.mimecast.com; auth=pass smtp.auth=CUSA124A263 smtp.mailfrom=jsnow@redhat.com X-Mimecast-Spam-Score: 0 X-Mimecast-Originator: redhat.com Received-SPF: pass client-ip=170.10.133.124; envelope-from=jsnow@redhat.com; helo=us-smtp-delivery-124.mimecast.com X-Spam_score_int: -34 X-Spam_score: -3.5 X-Spam_bar: --- X-Spam_report: (-3.5 / 5.0 requ) BAYES_00=-1.9, DKIMWL_WL_HIGH=-0.7, DKIM_SIGNED=0.1, DKIM_VALID=-0.1, DKIM_VALID_AU=-0.1, DKIM_VALID_EF=-0.1, RCVD_IN_DNSWL_LOW=-0.7, RCVD_IN_MSPIKE_H4=0.001, RCVD_IN_MSPIKE_WL=0.001, SPF_HELO_NONE=0.001, SPF_PASS=-0.001 autolearn=ham autolearn_force=no X-Spam_action: no action X-BeenThere: qemu-devel@nongnu.org X-Mailman-Version: 2.1.23 Precedence: list List-Id: List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Cc: Eduardo Habkost , Eric Blake , Stefan Hajnoczi , Markus Armbruster , Wainer dos Santos Moschetta , "Niteesh G . S ." , Willian Rampazzo , Cleber Rosa , John Snow Errors-To: qemu-devel-bounces+incoming=patchwork.ozlabs.org@nongnu.org Sender: "Qemu-devel" 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