From 439125293cc9cfb684eb4db23db04199f5f435a2 Mon Sep 17 00:00:00 2001 From: Daniel P. Berrangé Date: Fri, 28 Jan 2022 16:11:56 +0000 Subject: python: introduce qmp-shell-wrap convenience tool With the current 'qmp-shell' tool developers must first spawn QEMU with a suitable -qmp arg and then spawn qmp-shell in a separate terminal pointing to the right socket. With 'qmp-shell-wrap' developers can ignore QMP sockets entirely and just pass the QEMU command and arguments they want. The program will listen on a UNIX socket and tell QEMU to connect QMP to that. For example, this: # qmp-shell-wrap -- qemu-system-x86_64 -display none Is roughly equivalent of running: # qemu-system-x86_64 -display none -qmp qmp-shell-1234 & # qmp-shell qmp-shell-1234 Except that 'qmp-shell-wrap' switches the socket peers around so that it is the UNIX socket server and QEMU is the socket client. This makes QEMU reliably go away when qmp-shell-wrap exits, closing the server socket. Signed-off-by: Daniel P. Berrangé Message-id: 20220128161157.36261-2-berrange@redhat.com [Edited for rebase. --js] Signed-off-by: John Snow --- python/qemu/aqmp/qmp_shell.py | 65 ++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 61 insertions(+), 4 deletions(-) (limited to 'python/qemu') diff --git a/python/qemu/aqmp/qmp_shell.py b/python/qemu/aqmp/qmp_shell.py index d11bf54b00..c60df787fc 100644 --- a/python/qemu/aqmp/qmp_shell.py +++ b/python/qemu/aqmp/qmp_shell.py @@ -86,6 +86,7 @@ import logging import os import re import readline +from subprocess import Popen import sys from typing import ( Iterator, @@ -167,8 +168,10 @@ class QMPShell(QEMUMonitorProtocol): :param verbose: Echo outgoing QMP messages to console. """ def __init__(self, address: SocketAddrT, - pretty: bool = False, verbose: bool = False): - super().__init__(address) + pretty: bool = False, + verbose: bool = False, + server: bool = False): + super().__init__(address, server=server) self._greeting: Optional[QMPMessage] = None self._completer = QMPCompleter() self._transmode = False @@ -409,8 +412,10 @@ class HMPShell(QMPShell): :param verbose: Echo outgoing QMP messages to console. """ def __init__(self, address: SocketAddrT, - pretty: bool = False, verbose: bool = False): - super().__init__(address, pretty, verbose) + pretty: bool = False, + verbose: bool = False, + server: bool = False): + super().__init__(address, pretty, verbose, server) self._cpu_index = 0 def _cmd_completion(self) -> None: @@ -533,5 +538,57 @@ def main() -> None: pass +def main_wrap() -> None: + """ + qmp-shell-wrap entry point: parse command line arguments and + start the REPL. + """ + parser = argparse.ArgumentParser() + parser.add_argument('-H', '--hmp', action='store_true', + help='Use HMP interface') + parser.add_argument('-v', '--verbose', action='store_true', + help='Verbose (echo commands sent and received)') + parser.add_argument('-p', '--pretty', action='store_true', + help='Pretty-print JSON') + + parser.add_argument('command', nargs=argparse.REMAINDER, + help='QEMU command line to invoke') + + args = parser.parse_args() + + cmd = args.command + if len(cmd) != 0 and cmd[0] == '--': + cmd = cmd[1:] + if len(cmd) == 0: + cmd = ["qemu-system-x86_64"] + + sockpath = "qmp-shell-wrap-%d" % os.getpid() + cmd += ["-qmp", "unix:%s" % sockpath] + + shell_class = HMPShell if args.hmp else QMPShell + + try: + address = shell_class.parse_address(sockpath) + except QMPBadPortError: + parser.error(f"Bad port number: {sockpath}") + return # pycharm doesn't know error() is noreturn + + try: + with shell_class(address, args.pretty, args.verbose, True) as qemu: + with Popen(cmd): + + try: + qemu.accept() + except ConnectError as err: + if isinstance(err.exc, OSError): + die(f"Couldn't connect to {args.qmp_server}: {err!s}") + die(str(err)) + + for _ in qemu.repl(): + pass + finally: + os.unlink(sockpath) + + if __name__ == '__main__': main() -- cgit v1.2.3-55-g7522 From 5c66d7d8de9a00460199669d26cd83fba135bee5 Mon Sep 17 00:00:00 2001 From: Daniel P. Berrangé Date: Fri, 28 Jan 2022 16:11:57 +0000 Subject: python: support recording QMP session to a file When running QMP commands with very large response payloads, it is often not easy to spot the info you want. If we can save the response to a file then tools like 'grep' or 'jq' can be used to extract information. For convenience of processing, we merge the QMP command and response dictionaries together: { "arguments": {}, "execute": "query-kvm", "return": { "enabled": false, "present": true } } Example usage $ ./scripts/qmp/qmp-shell-wrap -l q.log -p -- ./build/qemu-system-x86_64 -display none Welcome to the QMP low-level shell! Connected (QEMU) query-kvm { "return": { "enabled": false, "present": true } } (QEMU) query-mice { "return": [ { "absolute": false, "current": true, "index": 2, "name": "QEMU PS/2 Mouse" } ] } $ jq --slurp '. | to_entries[] | select(.value.execute == "query-kvm") | .value.return.enabled' < q.log false Reviewed-by: Philippe Mathieu-Daudé Signed-off-by: Daniel P. Berrangé Message-id: 20220128161157.36261-3-berrange@redhat.com Signed-off-by: John Snow --- python/qemu/aqmp/qmp_shell.py | 29 ++++++++++++++++++++++------- python/setup.cfg | 3 +++ 2 files changed, 25 insertions(+), 7 deletions(-) (limited to 'python/qemu') diff --git a/python/qemu/aqmp/qmp_shell.py b/python/qemu/aqmp/qmp_shell.py index c60df787fc..35691494d0 100644 --- a/python/qemu/aqmp/qmp_shell.py +++ b/python/qemu/aqmp/qmp_shell.py @@ -89,6 +89,7 @@ import readline from subprocess import Popen import sys from typing import ( + IO, Iterator, List, NoReturn, @@ -170,7 +171,8 @@ class QMPShell(QEMUMonitorProtocol): def __init__(self, address: SocketAddrT, pretty: bool = False, verbose: bool = False, - server: bool = False): + server: bool = False, + logfile: Optional[str] = None): super().__init__(address, server=server) self._greeting: Optional[QMPMessage] = None self._completer = QMPCompleter() @@ -180,6 +182,10 @@ class QMPShell(QEMUMonitorProtocol): '.qmp-shell_history') self.pretty = pretty self.verbose = verbose + self.logfile = None + + if logfile is not None: + self.logfile = open(logfile, "w", encoding='utf-8') def close(self) -> None: # Hook into context manager of parent to save shell history. @@ -320,11 +326,11 @@ class QMPShell(QEMUMonitorProtocol): self._cli_expr(cmdargs[1:], qmpcmd['arguments']) return qmpcmd - def _print(self, qmp_message: object) -> None: + def _print(self, qmp_message: object, fh: IO[str] = sys.stdout) -> None: jsobj = json.dumps(qmp_message, indent=4 if self.pretty else None, sort_keys=self.pretty) - print(str(jsobj)) + print(str(jsobj), file=fh) def _execute_cmd(self, cmdline: str) -> bool: try: @@ -347,6 +353,9 @@ class QMPShell(QEMUMonitorProtocol): print('Disconnected') return False self._print(resp) + if self.logfile is not None: + cmd = {**qmpcmd, **resp} + self._print(cmd, fh=self.logfile) return True def connect(self, negotiate: bool = True) -> None: @@ -414,8 +423,9 @@ class HMPShell(QMPShell): def __init__(self, address: SocketAddrT, pretty: bool = False, verbose: bool = False, - server: bool = False): - super().__init__(address, pretty, verbose, server) + server: bool = False, + logfile: Optional[str] = None): + super().__init__(address, pretty, verbose, server, logfile) self._cpu_index = 0 def _cmd_completion(self) -> None: @@ -508,6 +518,8 @@ def main() -> None: help='Verbose (echo commands sent and received)') parser.add_argument('-p', '--pretty', action='store_true', help='Pretty-print JSON') + parser.add_argument('-l', '--logfile', + help='Save log of all QMP messages to PATH') default_server = os.environ.get('QMP_SOCKET') parser.add_argument('qmp_server', action='store', @@ -526,7 +538,7 @@ def main() -> None: parser.error(f"Bad port number: {args.qmp_server}") return # pycharm doesn't know error() is noreturn - with shell_class(address, args.pretty, args.verbose) as qemu: + with shell_class(address, args.pretty, args.verbose, args.logfile) as qemu: try: qemu.connect(negotiate=not args.skip_negotiation) except ConnectError as err: @@ -550,6 +562,8 @@ def main_wrap() -> None: help='Verbose (echo commands sent and received)') parser.add_argument('-p', '--pretty', action='store_true', help='Pretty-print JSON') + parser.add_argument('-l', '--logfile', + help='Save log of all QMP messages to PATH') parser.add_argument('command', nargs=argparse.REMAINDER, help='QEMU command line to invoke') @@ -574,7 +588,8 @@ def main_wrap() -> None: return # pycharm doesn't know error() is noreturn try: - with shell_class(address, args.pretty, args.verbose, True) as qemu: + with shell_class(address, args.pretty, args.verbose, + True, args.logfile) as qemu: with Popen(cmd): try: diff --git a/python/setup.cfg b/python/setup.cfg index 0959603238..9821db9880 100644 --- a/python/setup.cfg +++ b/python/setup.cfg @@ -114,7 +114,10 @@ ignore_missing_imports = True # no Warning level messages displayed, use "--disable=all --enable=classes # --disable=W". disable=consider-using-f-string, + consider-using-with, + too-many-arguments, too-many-function-args, # mypy handles this with less false positives. + too-many-instance-attributes, no-member, # mypy also handles this better. [pylint.basic] -- cgit v1.2.3-55-g7522