2009-11-27 00:59:09 +00:00
|
|
|
#
|
python/qmp-shell: relicense as LGPLv2+
qmp-shell is presently licensed as GPLv2 (only). I intend to include
this tool as an add-on to an LGPLv2+ library package hosted on
PyPI.org. I've selected LGPLv2+ to maximize compatibility with other
licenses while retaining a copyleft license.
To keep licensing matters simple, I'd like to relicense this tool as
LGPLv2+ as well in order to keep the resultant license of the hosted
release files simple -- even if library users won't "link against" this
command line tool.
Therefore, I am asking permission from the current authors of this
tool to loosen the license. At present, those people are:
- John Snow (me!), 411/609
- Luiz Capitulino, Author, 97/609
- Daniel Berrangé, 81/609
- Eduardo Habkost, 10/609
- Marc-André Lureau, 6/609
- Fam Zheng, 3/609
- Cleber Rosa, 1/609
(All of which appear to have been written under redhat.com addresses.)
Eduardo's fixes are largely automated from 2to3 conversion tools and may
not necessarily constitute authorship, but his signature would put to
rest any questions.
Cleber's changes concern a single import statement change. Also won't
hurt to ask.
Signed-off-by: John Snow <jsnow@redhat.com>
Reviewed-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Acked-by: Fam Zheng <fam@euphon.net>
Acked-by: Luiz Capitulino <lcapitulino@redhat.com>
Acked-by: Eduardo Habkost <eduardo@habkost.net>
Acked-by: Daniel P. Berrangé <berrange@redhat.com>
Acked-by: Cleber Rosa <crosa@redhat.com>
Message-id: 20220325200438.2556381-4-jsnow@redhat.com
Signed-off-by: John Snow <jsnow@redhat.com>
2022-03-25 20:04:37 +00:00
|
|
|
# Copyright (C) 2009-2022 Red Hat Inc.
|
2009-11-27 00:59:09 +00:00
|
|
|
#
|
|
|
|
# Authors:
|
|
|
|
# Luiz Capitulino <lcapitulino@redhat.com>
|
python/qmp-shell: relicense as LGPLv2+
qmp-shell is presently licensed as GPLv2 (only). I intend to include
this tool as an add-on to an LGPLv2+ library package hosted on
PyPI.org. I've selected LGPLv2+ to maximize compatibility with other
licenses while retaining a copyleft license.
To keep licensing matters simple, I'd like to relicense this tool as
LGPLv2+ as well in order to keep the resultant license of the hosted
release files simple -- even if library users won't "link against" this
command line tool.
Therefore, I am asking permission from the current authors of this
tool to loosen the license. At present, those people are:
- John Snow (me!), 411/609
- Luiz Capitulino, Author, 97/609
- Daniel Berrangé, 81/609
- Eduardo Habkost, 10/609
- Marc-André Lureau, 6/609
- Fam Zheng, 3/609
- Cleber Rosa, 1/609
(All of which appear to have been written under redhat.com addresses.)
Eduardo's fixes are largely automated from 2to3 conversion tools and may
not necessarily constitute authorship, but his signature would put to
rest any questions.
Cleber's changes concern a single import statement change. Also won't
hurt to ask.
Signed-off-by: John Snow <jsnow@redhat.com>
Reviewed-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Acked-by: Fam Zheng <fam@euphon.net>
Acked-by: Luiz Capitulino <lcapitulino@redhat.com>
Acked-by: Eduardo Habkost <eduardo@habkost.net>
Acked-by: Daniel P. Berrangé <berrange@redhat.com>
Acked-by: Cleber Rosa <crosa@redhat.com>
Message-id: 20220325200438.2556381-4-jsnow@redhat.com
Signed-off-by: John Snow <jsnow@redhat.com>
2022-03-25 20:04:37 +00:00
|
|
|
# John Snow <jsnow@redhat.com>
|
2009-11-27 00:59:09 +00:00
|
|
|
#
|
python/qmp-shell: relicense as LGPLv2+
qmp-shell is presently licensed as GPLv2 (only). I intend to include
this tool as an add-on to an LGPLv2+ library package hosted on
PyPI.org. I've selected LGPLv2+ to maximize compatibility with other
licenses while retaining a copyleft license.
To keep licensing matters simple, I'd like to relicense this tool as
LGPLv2+ as well in order to keep the resultant license of the hosted
release files simple -- even if library users won't "link against" this
command line tool.
Therefore, I am asking permission from the current authors of this
tool to loosen the license. At present, those people are:
- John Snow (me!), 411/609
- Luiz Capitulino, Author, 97/609
- Daniel Berrangé, 81/609
- Eduardo Habkost, 10/609
- Marc-André Lureau, 6/609
- Fam Zheng, 3/609
- Cleber Rosa, 1/609
(All of which appear to have been written under redhat.com addresses.)
Eduardo's fixes are largely automated from 2to3 conversion tools and may
not necessarily constitute authorship, but his signature would put to
rest any questions.
Cleber's changes concern a single import statement change. Also won't
hurt to ask.
Signed-off-by: John Snow <jsnow@redhat.com>
Reviewed-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Acked-by: Fam Zheng <fam@euphon.net>
Acked-by: Luiz Capitulino <lcapitulino@redhat.com>
Acked-by: Eduardo Habkost <eduardo@habkost.net>
Acked-by: Daniel P. Berrangé <berrange@redhat.com>
Acked-by: Cleber Rosa <crosa@redhat.com>
Message-id: 20220325200438.2556381-4-jsnow@redhat.com
Signed-off-by: John Snow <jsnow@redhat.com>
2022-03-25 20:04:37 +00:00
|
|
|
# This work is licensed under the terms of the GNU LGPL, version 2 or
|
|
|
|
# later. See the COPYING file in the top-level directory.
|
2009-11-27 00:59:09 +00:00
|
|
|
#
|
2021-06-07 20:06:43 +00:00
|
|
|
|
|
|
|
"""
|
|
|
|
Low-level QEMU shell on top of QMP.
|
|
|
|
|
|
|
|
usage: qmp-shell [-h] [-H] [-N] [-v] [-p] qmp_server
|
|
|
|
|
|
|
|
positional arguments:
|
|
|
|
qmp_server < UNIX socket path | TCP address:port >
|
|
|
|
|
|
|
|
optional arguments:
|
|
|
|
-h, --help show this help message and exit
|
|
|
|
-H, --hmp Use HMP interface
|
|
|
|
-N, --skip-negotiation
|
|
|
|
Skip negotiate (for qemu-ga)
|
|
|
|
-v, --verbose Verbose (echo commands sent and received)
|
|
|
|
-p, --pretty Pretty-print JSON
|
|
|
|
|
|
|
|
|
|
|
|
Start QEMU with:
|
|
|
|
|
|
|
|
# qemu [...] -qmp unix:./qmp-sock,server
|
|
|
|
|
|
|
|
Run the shell:
|
|
|
|
|
|
|
|
$ qmp-shell ./qmp-sock
|
|
|
|
|
|
|
|
Commands have the following format:
|
|
|
|
|
|
|
|
< command-name > [ arg-name1=arg1 ] ... [ arg-nameN=argN ]
|
|
|
|
|
|
|
|
For example:
|
|
|
|
|
|
|
|
(QEMU) device_add driver=e1000 id=net1
|
|
|
|
{'return': {}}
|
|
|
|
(QEMU)
|
|
|
|
|
|
|
|
key=value pairs also support Python or JSON object literal subset notations,
|
|
|
|
without spaces. Dictionaries/objects {} are supported as are arrays [].
|
|
|
|
|
|
|
|
example-command arg-name1={'key':'value','obj'={'prop':"value"}}
|
|
|
|
|
|
|
|
Both JSON and Python formatting should work, including both styles of
|
|
|
|
string literal quotes. Both paradigms of literal values should work,
|
|
|
|
including null/true/false for JSON and None/True/False for Python.
|
|
|
|
|
|
|
|
|
|
|
|
Transactions have the following multi-line format:
|
|
|
|
|
|
|
|
transaction(
|
|
|
|
action-name1 [ arg-name1=arg1 ] ... [arg-nameN=argN ]
|
|
|
|
...
|
|
|
|
action-nameN [ arg-name1=arg1 ] ... [arg-nameN=argN ]
|
|
|
|
)
|
|
|
|
|
|
|
|
One line transactions are also supported:
|
|
|
|
|
|
|
|
transaction( action-name1 ... )
|
|
|
|
|
|
|
|
For example:
|
|
|
|
|
|
|
|
(QEMU) transaction(
|
|
|
|
TRANS> block-dirty-bitmap-add node=drive0 name=bitmap1
|
|
|
|
TRANS> block-dirty-bitmap-clear node=drive0 name=bitmap0
|
|
|
|
TRANS> )
|
|
|
|
{"return": {}}
|
|
|
|
(QEMU)
|
|
|
|
|
|
|
|
Use the -v and -p options to activate the verbose and pretty-print options,
|
|
|
|
which will echo back the properly formatted JSON-compliant QMP that is being
|
|
|
|
sent to QEMU, which is useful for debugging and documentation generation.
|
|
|
|
"""
|
|
|
|
|
2021-06-07 20:06:24 +00:00
|
|
|
import argparse
|
scripts: qmp-shell: Expand support for QMP expressions
This includes support for [] expressions, single-quotes in
QMP expressions (which is not strictly a part of JSON), and
the ability to use "True", "False" and "None" literals instead
of JSON's equivalent true, false, and null literals.
qmp-shell currently allows you to describe values as
JSON expressions:
key={"key":{"key2":"val"}}
But it does not currently support arrays, which are needed
for serializing and deserializing transactions:
key=[{"type":"drive-backup","data":{...}}]
qmp-shell also only currently accepts doubly quoted strings
as-per JSON spec, but QMP allows single quotes.
Lastly, python allows you to utilize "True" or "False" as
boolean literals, but JSON expects "true" or "false". Expand
qmp-shell to allow the user to type either, converting to the
correct type.
As a consequence of the above, the key=val parsing is also improved
to give better error messages if a key=val token is not provided.
CAVEAT: The parser is still extremely rudimentary and does not
expect to find spaces in {} nor [] expressions. This patch does
not improve this functionality.
Signed-off-by: John Snow <jsnow@redhat.com>
Reviewed-by: Eric Blake <eblake@redhat.com>
Tested-by: Kashyap Chamarthy <kchamart@redhat.com>
Signed-off-by: Luiz Capitulino <lcapitulino@redhat.com>
2015-04-29 19:14:02 +00:00
|
|
|
import ast
|
2021-06-07 20:06:08 +00:00
|
|
|
import json
|
2021-06-07 20:06:39 +00:00
|
|
|
import logging
|
2021-06-07 20:06:08 +00:00
|
|
|
import os
|
qmp-shell: fix nested json regression
Commit fcfab7541 ("qmp-shell: learn to send commands with quoted
arguments") introduces the usage of Python 'shlex' to handle quoted
arguments, but it accidentally broke generation of nested JSON
structs.
shlex drops quotes, which breaks parsing of the nested struct.
cmd='blockdev-create job-id="job0 foo" options={"driver":"qcow2","size":16384,"file":{"driver":"file","filename":"foo.qcow2"}}'
shlex.split(cmd)
['blockdev-create',
'job-id=job0 foo',
'options={driver:qcow2,size:16384,file:{driver:file,filename:foo.qcow2}}']
Replace with a regexp to split while respecting quoted strings and preserving quotes:
re.findall(r'''(?:[^\s"']|"(?:\\.|[^"])*"|'(?:\\.|[^'])*')+''', cmd)
['blockdev-create',
'job-id="job0 foo"',
'options={"driver":"qcow2","size":16384,"file":{"driver":"file","filename":"foo.qcow2"}}']
Fixes: fcfab7541 ("qmp-shell: learn to send commands with quoted arguments")
Reported-by: Kashyap Chamarthy <kchamart@redhat.com>
Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Message-Id: <20190205134926.8312-1-marcandre.lureau@redhat.com>
Tested-by: Kashyap Chamarthy <kchamart@redhat.com>
Signed-off-by: Eduardo Habkost <ehabkost@redhat.com>
2019-02-05 13:49:26 +00:00
|
|
|
import re
|
2021-06-07 20:06:08 +00:00
|
|
|
import readline
|
2022-01-28 16:11:56 +00:00
|
|
|
from subprocess import Popen
|
2021-06-07 20:06:08 +00:00
|
|
|
import sys
|
2021-06-07 20:06:34 +00:00
|
|
|
from typing import (
|
2022-01-28 16:11:57 +00:00
|
|
|
IO,
|
2023-10-06 15:41:12 +00:00
|
|
|
Dict,
|
2021-06-07 20:06:34 +00:00
|
|
|
Iterator,
|
|
|
|
List,
|
|
|
|
NoReturn,
|
|
|
|
Optional,
|
|
|
|
Sequence,
|
2023-10-06 15:41:12 +00:00
|
|
|
cast,
|
2021-06-07 20:06:34 +00:00
|
|
|
)
|
2021-06-07 20:06:08 +00:00
|
|
|
|
2023-10-06 15:41:12 +00:00
|
|
|
from qemu.qmp import (
|
|
|
|
ConnectError,
|
|
|
|
ExecuteError,
|
|
|
|
QMPError,
|
|
|
|
SocketAddrT,
|
|
|
|
)
|
2022-03-30 17:28:10 +00:00
|
|
|
from qemu.qmp.legacy import (
|
2022-01-10 23:28:53 +00:00
|
|
|
QEMUMonitorProtocol,
|
|
|
|
QMPBadPortError,
|
|
|
|
QMPMessage,
|
|
|
|
QMPObject,
|
|
|
|
)
|
2019-02-06 16:29:01 +00:00
|
|
|
|
2021-06-07 20:06:08 +00:00
|
|
|
|
2021-06-07 20:06:39 +00:00
|
|
|
LOG = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2021-06-07 20:06:31 +00:00
|
|
|
class QMPCompleter:
|
2021-06-07 20:06:46 +00:00
|
|
|
"""
|
|
|
|
QMPCompleter provides a readline library tab-complete behavior.
|
|
|
|
"""
|
2021-06-07 20:06:31 +00:00
|
|
|
# NB: Python 3.9+ will probably allow us to subclass list[str] directly,
|
|
|
|
# but pylint as of today does not know that List[str] is simply 'list'.
|
|
|
|
def __init__(self) -> None:
|
|
|
|
self._matches: List[str] = []
|
|
|
|
|
|
|
|
def append(self, value: str) -> None:
|
2021-06-07 20:06:46 +00:00
|
|
|
"""Append a new valid completion to the list of possibilities."""
|
2021-06-07 20:06:31 +00:00
|
|
|
return self._matches.append(value)
|
|
|
|
|
|
|
|
def complete(self, text: str, state: int) -> Optional[str]:
|
2021-06-07 20:06:46 +00:00
|
|
|
"""readline.set_completer() callback implementation."""
|
2021-06-07 20:06:31 +00:00
|
|
|
for cmd in self._matches:
|
2010-10-27 19:57:51 +00:00
|
|
|
if cmd.startswith(text):
|
2021-06-07 20:06:19 +00:00
|
|
|
if state == 0:
|
2010-10-27 19:57:51 +00:00
|
|
|
return cmd
|
2021-06-07 20:06:19 +00:00
|
|
|
state -= 1
|
|
|
|
return None
|
2009-11-27 00:59:09 +00:00
|
|
|
|
2021-06-07 20:06:09 +00:00
|
|
|
|
2022-01-10 23:28:53 +00:00
|
|
|
class QMPShellError(QMPError):
|
2021-06-07 20:06:46 +00:00
|
|
|
"""
|
|
|
|
QMP Shell Base error class.
|
|
|
|
"""
|
2010-10-27 19:57:51 +00:00
|
|
|
|
|
|
|
|
scripts: qmp-shell: Expand support for QMP expressions
This includes support for [] expressions, single-quotes in
QMP expressions (which is not strictly a part of JSON), and
the ability to use "True", "False" and "None" literals instead
of JSON's equivalent true, false, and null literals.
qmp-shell currently allows you to describe values as
JSON expressions:
key={"key":{"key2":"val"}}
But it does not currently support arrays, which are needed
for serializing and deserializing transactions:
key=[{"type":"drive-backup","data":{...}}]
qmp-shell also only currently accepts doubly quoted strings
as-per JSON spec, but QMP allows single quotes.
Lastly, python allows you to utilize "True" or "False" as
boolean literals, but JSON expects "true" or "false". Expand
qmp-shell to allow the user to type either, converting to the
correct type.
As a consequence of the above, the key=val parsing is also improved
to give better error messages if a key=val token is not provided.
CAVEAT: The parser is still extremely rudimentary and does not
expect to find spaces in {} nor [] expressions. This patch does
not improve this functionality.
Signed-off-by: John Snow <jsnow@redhat.com>
Reviewed-by: Eric Blake <eblake@redhat.com>
Tested-by: Kashyap Chamarthy <kchamart@redhat.com>
Signed-off-by: Luiz Capitulino <lcapitulino@redhat.com>
2015-04-29 19:14:02 +00:00
|
|
|
class FuzzyJSON(ast.NodeTransformer):
|
2021-06-07 20:06:17 +00:00
|
|
|
"""
|
|
|
|
This extension of ast.NodeTransformer filters literal "true/false/null"
|
2021-06-07 20:06:30 +00:00
|
|
|
values in a Python AST and replaces them by proper "True/False/None" values
|
|
|
|
that Python can properly evaluate.
|
2021-06-07 20:06:17 +00:00
|
|
|
"""
|
|
|
|
|
2021-06-07 20:06:14 +00:00
|
|
|
@classmethod
|
2021-06-07 20:06:30 +00:00
|
|
|
def visit_Name(cls, # pylint: disable=invalid-name
|
|
|
|
node: ast.Name) -> ast.AST:
|
2021-06-07 20:06:46 +00:00
|
|
|
"""
|
|
|
|
Transform Name nodes with certain values into Constant (keyword) nodes.
|
|
|
|
"""
|
scripts: qmp-shell: Expand support for QMP expressions
This includes support for [] expressions, single-quotes in
QMP expressions (which is not strictly a part of JSON), and
the ability to use "True", "False" and "None" literals instead
of JSON's equivalent true, false, and null literals.
qmp-shell currently allows you to describe values as
JSON expressions:
key={"key":{"key2":"val"}}
But it does not currently support arrays, which are needed
for serializing and deserializing transactions:
key=[{"type":"drive-backup","data":{...}}]
qmp-shell also only currently accepts doubly quoted strings
as-per JSON spec, but QMP allows single quotes.
Lastly, python allows you to utilize "True" or "False" as
boolean literals, but JSON expects "true" or "false". Expand
qmp-shell to allow the user to type either, converting to the
correct type.
As a consequence of the above, the key=val parsing is also improved
to give better error messages if a key=val token is not provided.
CAVEAT: The parser is still extremely rudimentary and does not
expect to find spaces in {} nor [] expressions. This patch does
not improve this functionality.
Signed-off-by: John Snow <jsnow@redhat.com>
Reviewed-by: Eric Blake <eblake@redhat.com>
Tested-by: Kashyap Chamarthy <kchamart@redhat.com>
Signed-off-by: Luiz Capitulino <lcapitulino@redhat.com>
2015-04-29 19:14:02 +00:00
|
|
|
if node.id == 'true':
|
2021-06-07 20:06:30 +00:00
|
|
|
return ast.Constant(value=True)
|
scripts: qmp-shell: Expand support for QMP expressions
This includes support for [] expressions, single-quotes in
QMP expressions (which is not strictly a part of JSON), and
the ability to use "True", "False" and "None" literals instead
of JSON's equivalent true, false, and null literals.
qmp-shell currently allows you to describe values as
JSON expressions:
key={"key":{"key2":"val"}}
But it does not currently support arrays, which are needed
for serializing and deserializing transactions:
key=[{"type":"drive-backup","data":{...}}]
qmp-shell also only currently accepts doubly quoted strings
as-per JSON spec, but QMP allows single quotes.
Lastly, python allows you to utilize "True" or "False" as
boolean literals, but JSON expects "true" or "false". Expand
qmp-shell to allow the user to type either, converting to the
correct type.
As a consequence of the above, the key=val parsing is also improved
to give better error messages if a key=val token is not provided.
CAVEAT: The parser is still extremely rudimentary and does not
expect to find spaces in {} nor [] expressions. This patch does
not improve this functionality.
Signed-off-by: John Snow <jsnow@redhat.com>
Reviewed-by: Eric Blake <eblake@redhat.com>
Tested-by: Kashyap Chamarthy <kchamart@redhat.com>
Signed-off-by: Luiz Capitulino <lcapitulino@redhat.com>
2015-04-29 19:14:02 +00:00
|
|
|
if node.id == 'false':
|
2021-06-07 20:06:30 +00:00
|
|
|
return ast.Constant(value=False)
|
scripts: qmp-shell: Expand support for QMP expressions
This includes support for [] expressions, single-quotes in
QMP expressions (which is not strictly a part of JSON), and
the ability to use "True", "False" and "None" literals instead
of JSON's equivalent true, false, and null literals.
qmp-shell currently allows you to describe values as
JSON expressions:
key={"key":{"key2":"val"}}
But it does not currently support arrays, which are needed
for serializing and deserializing transactions:
key=[{"type":"drive-backup","data":{...}}]
qmp-shell also only currently accepts doubly quoted strings
as-per JSON spec, but QMP allows single quotes.
Lastly, python allows you to utilize "True" or "False" as
boolean literals, but JSON expects "true" or "false". Expand
qmp-shell to allow the user to type either, converting to the
correct type.
As a consequence of the above, the key=val parsing is also improved
to give better error messages if a key=val token is not provided.
CAVEAT: The parser is still extremely rudimentary and does not
expect to find spaces in {} nor [] expressions. This patch does
not improve this functionality.
Signed-off-by: John Snow <jsnow@redhat.com>
Reviewed-by: Eric Blake <eblake@redhat.com>
Tested-by: Kashyap Chamarthy <kchamart@redhat.com>
Signed-off-by: Luiz Capitulino <lcapitulino@redhat.com>
2015-04-29 19:14:02 +00:00
|
|
|
if node.id == 'null':
|
2021-06-07 20:06:30 +00:00
|
|
|
return ast.Constant(value=None)
|
scripts: qmp-shell: Expand support for QMP expressions
This includes support for [] expressions, single-quotes in
QMP expressions (which is not strictly a part of JSON), and
the ability to use "True", "False" and "None" literals instead
of JSON's equivalent true, false, and null literals.
qmp-shell currently allows you to describe values as
JSON expressions:
key={"key":{"key2":"val"}}
But it does not currently support arrays, which are needed
for serializing and deserializing transactions:
key=[{"type":"drive-backup","data":{...}}]
qmp-shell also only currently accepts doubly quoted strings
as-per JSON spec, but QMP allows single quotes.
Lastly, python allows you to utilize "True" or "False" as
boolean literals, but JSON expects "true" or "false". Expand
qmp-shell to allow the user to type either, converting to the
correct type.
As a consequence of the above, the key=val parsing is also improved
to give better error messages if a key=val token is not provided.
CAVEAT: The parser is still extremely rudimentary and does not
expect to find spaces in {} nor [] expressions. This patch does
not improve this functionality.
Signed-off-by: John Snow <jsnow@redhat.com>
Reviewed-by: Eric Blake <eblake@redhat.com>
Tested-by: Kashyap Chamarthy <kchamart@redhat.com>
Signed-off-by: Luiz Capitulino <lcapitulino@redhat.com>
2015-04-29 19:14:02 +00:00
|
|
|
return node
|
|
|
|
|
2021-06-07 20:06:09 +00:00
|
|
|
|
2022-01-10 23:28:53 +00:00
|
|
|
class QMPShell(QEMUMonitorProtocol):
|
2021-06-07 20:06:46 +00:00
|
|
|
"""
|
|
|
|
QMPShell provides a basic readline-based QMP shell.
|
|
|
|
|
|
|
|
:param address: Address of the QMP server.
|
|
|
|
:param pretty: Pretty-print QMP messages.
|
|
|
|
:param verbose: Echo outgoing QMP messages to console.
|
|
|
|
"""
|
2022-01-10 23:28:53 +00:00
|
|
|
def __init__(self, address: SocketAddrT,
|
2022-01-28 16:11:56 +00:00
|
|
|
pretty: bool = False,
|
|
|
|
verbose: bool = False,
|
2022-01-28 16:11:57 +00:00
|
|
|
server: bool = False,
|
|
|
|
logfile: Optional[str] = None):
|
2022-01-28 16:11:56 +00:00
|
|
|
super().__init__(address, server=server)
|
2021-06-07 20:06:34 +00:00
|
|
|
self._greeting: Optional[QMPMessage] = None
|
2021-06-07 20:06:32 +00:00
|
|
|
self._completer = QMPCompleter()
|
2015-04-29 19:14:03 +00:00
|
|
|
self._transmode = False
|
2021-06-07 20:06:34 +00:00
|
|
|
self._actions: List[QMPMessage] = []
|
2017-04-27 22:36:28 +00:00
|
|
|
self._histfile = os.path.join(os.path.expanduser('~'),
|
|
|
|
'.qmp-shell_history')
|
2021-06-07 20:06:36 +00:00
|
|
|
self.pretty = pretty
|
2021-06-07 20:06:26 +00:00
|
|
|
self.verbose = verbose
|
2022-01-28 16:11:57 +00:00
|
|
|
self.logfile = None
|
|
|
|
|
|
|
|
if logfile is not None:
|
|
|
|
self.logfile = open(logfile, "w", encoding='utf-8')
|
2010-10-27 19:57:51 +00:00
|
|
|
|
2021-06-07 20:06:38 +00:00
|
|
|
def close(self) -> None:
|
|
|
|
# Hook into context manager of parent to save shell history.
|
|
|
|
self._save_history()
|
|
|
|
super().close()
|
|
|
|
|
2021-06-07 20:06:34 +00:00
|
|
|
def _fill_completion(self) -> None:
|
2023-10-06 15:41:12 +00:00
|
|
|
try:
|
2023-10-06 15:41:15 +00:00
|
|
|
cmds = cast(List[Dict[str, str]], self.cmd('query-commands'))
|
2023-10-06 15:41:12 +00:00
|
|
|
for cmd in cmds:
|
|
|
|
self._completer.append(cmd['name'])
|
|
|
|
except ExecuteError:
|
|
|
|
pass
|
2010-10-27 19:57:51 +00:00
|
|
|
|
2021-06-07 20:06:44 +00:00
|
|
|
def _completer_setup(self) -> None:
|
2010-10-27 19:57:51 +00:00
|
|
|
self._completer = QMPCompleter()
|
|
|
|
self._fill_completion()
|
2017-04-27 22:36:28 +00:00
|
|
|
readline.set_history_length(1024)
|
2010-10-27 19:57:51 +00:00
|
|
|
readline.set_completer(self._completer.complete)
|
|
|
|
readline.parse_and_bind("tab: complete")
|
2021-06-07 20:06:09 +00:00
|
|
|
# NB: default delimiters conflict with some command names
|
|
|
|
# (eg. query-), clearing everything as it doesn't seem to matter
|
2010-10-27 19:57:51 +00:00
|
|
|
readline.set_completer_delims('')
|
2017-04-27 22:36:28 +00:00
|
|
|
try:
|
|
|
|
readline.read_history_file(self._histfile)
|
2021-06-07 20:06:21 +00:00
|
|
|
except FileNotFoundError:
|
|
|
|
pass
|
|
|
|
except IOError as err:
|
2021-06-07 20:06:39 +00:00
|
|
|
msg = f"Failed to read history '{self._histfile}': {err!s}"
|
|
|
|
LOG.warning(msg)
|
2017-04-27 22:36:28 +00:00
|
|
|
|
2021-06-07 20:06:38 +00:00
|
|
|
def _save_history(self) -> None:
|
2017-04-27 22:36:28 +00:00
|
|
|
try:
|
|
|
|
readline.write_history_file(self._histfile)
|
2021-06-07 20:06:21 +00:00
|
|
|
except IOError as err:
|
2021-06-07 20:06:39 +00:00
|
|
|
msg = f"Failed to save history file '{self._histfile}': {err!s}"
|
|
|
|
LOG.warning(msg)
|
2010-10-27 19:57:51 +00:00
|
|
|
|
2021-06-07 20:06:14 +00:00
|
|
|
@classmethod
|
2021-06-07 20:06:44 +00:00
|
|
|
def _parse_value(cls, val: str) -> object:
|
scripts: qmp-shell: Expand support for QMP expressions
This includes support for [] expressions, single-quotes in
QMP expressions (which is not strictly a part of JSON), and
the ability to use "True", "False" and "None" literals instead
of JSON's equivalent true, false, and null literals.
qmp-shell currently allows you to describe values as
JSON expressions:
key={"key":{"key2":"val"}}
But it does not currently support arrays, which are needed
for serializing and deserializing transactions:
key=[{"type":"drive-backup","data":{...}}]
qmp-shell also only currently accepts doubly quoted strings
as-per JSON spec, but QMP allows single quotes.
Lastly, python allows you to utilize "True" or "False" as
boolean literals, but JSON expects "true" or "false". Expand
qmp-shell to allow the user to type either, converting to the
correct type.
As a consequence of the above, the key=val parsing is also improved
to give better error messages if a key=val token is not provided.
CAVEAT: The parser is still extremely rudimentary and does not
expect to find spaces in {} nor [] expressions. This patch does
not improve this functionality.
Signed-off-by: John Snow <jsnow@redhat.com>
Reviewed-by: Eric Blake <eblake@redhat.com>
Tested-by: Kashyap Chamarthy <kchamart@redhat.com>
Signed-off-by: Luiz Capitulino <lcapitulino@redhat.com>
2015-04-29 19:14:02 +00:00
|
|
|
try:
|
|
|
|
return int(val)
|
|
|
|
except ValueError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
if val.lower() == 'true':
|
|
|
|
return True
|
|
|
|
if val.lower() == 'false':
|
|
|
|
return False
|
|
|
|
if val.startswith(('{', '[')):
|
|
|
|
# Try first as pure JSON:
|
2010-10-27 19:57:51 +00:00
|
|
|
try:
|
scripts: qmp-shell: Expand support for QMP expressions
This includes support for [] expressions, single-quotes in
QMP expressions (which is not strictly a part of JSON), and
the ability to use "True", "False" and "None" literals instead
of JSON's equivalent true, false, and null literals.
qmp-shell currently allows you to describe values as
JSON expressions:
key={"key":{"key2":"val"}}
But it does not currently support arrays, which are needed
for serializing and deserializing transactions:
key=[{"type":"drive-backup","data":{...}}]
qmp-shell also only currently accepts doubly quoted strings
as-per JSON spec, but QMP allows single quotes.
Lastly, python allows you to utilize "True" or "False" as
boolean literals, but JSON expects "true" or "false". Expand
qmp-shell to allow the user to type either, converting to the
correct type.
As a consequence of the above, the key=val parsing is also improved
to give better error messages if a key=val token is not provided.
CAVEAT: The parser is still extremely rudimentary and does not
expect to find spaces in {} nor [] expressions. This patch does
not improve this functionality.
Signed-off-by: John Snow <jsnow@redhat.com>
Reviewed-by: Eric Blake <eblake@redhat.com>
Tested-by: Kashyap Chamarthy <kchamart@redhat.com>
Signed-off-by: Luiz Capitulino <lcapitulino@redhat.com>
2015-04-29 19:14:02 +00:00
|
|
|
return json.loads(val)
|
2010-10-27 19:57:51 +00:00
|
|
|
except ValueError:
|
scripts: qmp-shell: Expand support for QMP expressions
This includes support for [] expressions, single-quotes in
QMP expressions (which is not strictly a part of JSON), and
the ability to use "True", "False" and "None" literals instead
of JSON's equivalent true, false, and null literals.
qmp-shell currently allows you to describe values as
JSON expressions:
key={"key":{"key2":"val"}}
But it does not currently support arrays, which are needed
for serializing and deserializing transactions:
key=[{"type":"drive-backup","data":{...}}]
qmp-shell also only currently accepts doubly quoted strings
as-per JSON spec, but QMP allows single quotes.
Lastly, python allows you to utilize "True" or "False" as
boolean literals, but JSON expects "true" or "false". Expand
qmp-shell to allow the user to type either, converting to the
correct type.
As a consequence of the above, the key=val parsing is also improved
to give better error messages if a key=val token is not provided.
CAVEAT: The parser is still extremely rudimentary and does not
expect to find spaces in {} nor [] expressions. This patch does
not improve this functionality.
Signed-off-by: John Snow <jsnow@redhat.com>
Reviewed-by: Eric Blake <eblake@redhat.com>
Tested-by: Kashyap Chamarthy <kchamart@redhat.com>
Signed-off-by: Luiz Capitulino <lcapitulino@redhat.com>
2015-04-29 19:14:02 +00:00
|
|
|
pass
|
|
|
|
# Try once again as FuzzyJSON:
|
|
|
|
try:
|
2021-06-07 20:06:20 +00:00
|
|
|
tree = ast.parse(val, mode='eval')
|
2021-06-07 20:06:30 +00:00
|
|
|
transformed = FuzzyJSON().visit(tree)
|
|
|
|
return ast.literal_eval(transformed)
|
|
|
|
except (SyntaxError, ValueError):
|
scripts: qmp-shell: Expand support for QMP expressions
This includes support for [] expressions, single-quotes in
QMP expressions (which is not strictly a part of JSON), and
the ability to use "True", "False" and "None" literals instead
of JSON's equivalent true, false, and null literals.
qmp-shell currently allows you to describe values as
JSON expressions:
key={"key":{"key2":"val"}}
But it does not currently support arrays, which are needed
for serializing and deserializing transactions:
key=[{"type":"drive-backup","data":{...}}]
qmp-shell also only currently accepts doubly quoted strings
as-per JSON spec, but QMP allows single quotes.
Lastly, python allows you to utilize "True" or "False" as
boolean literals, but JSON expects "true" or "false". Expand
qmp-shell to allow the user to type either, converting to the
correct type.
As a consequence of the above, the key=val parsing is also improved
to give better error messages if a key=val token is not provided.
CAVEAT: The parser is still extremely rudimentary and does not
expect to find spaces in {} nor [] expressions. This patch does
not improve this functionality.
Signed-off-by: John Snow <jsnow@redhat.com>
Reviewed-by: Eric Blake <eblake@redhat.com>
Tested-by: Kashyap Chamarthy <kchamart@redhat.com>
Signed-off-by: Luiz Capitulino <lcapitulino@redhat.com>
2015-04-29 19:14:02 +00:00
|
|
|
pass
|
|
|
|
return val
|
|
|
|
|
2021-06-07 20:06:44 +00:00
|
|
|
def _cli_expr(self,
|
|
|
|
tokens: Sequence[str],
|
2022-01-10 23:28:53 +00:00
|
|
|
parent: QMPObject) -> None:
|
scripts: qmp-shell: Expand support for QMP expressions
This includes support for [] expressions, single-quotes in
QMP expressions (which is not strictly a part of JSON), and
the ability to use "True", "False" and "None" literals instead
of JSON's equivalent true, false, and null literals.
qmp-shell currently allows you to describe values as
JSON expressions:
key={"key":{"key2":"val"}}
But it does not currently support arrays, which are needed
for serializing and deserializing transactions:
key=[{"type":"drive-backup","data":{...}}]
qmp-shell also only currently accepts doubly quoted strings
as-per JSON spec, but QMP allows single quotes.
Lastly, python allows you to utilize "True" or "False" as
boolean literals, but JSON expects "true" or "false". Expand
qmp-shell to allow the user to type either, converting to the
correct type.
As a consequence of the above, the key=val parsing is also improved
to give better error messages if a key=val token is not provided.
CAVEAT: The parser is still extremely rudimentary and does not
expect to find spaces in {} nor [] expressions. This patch does
not improve this functionality.
Signed-off-by: John Snow <jsnow@redhat.com>
Reviewed-by: Eric Blake <eblake@redhat.com>
Tested-by: Kashyap Chamarthy <kchamart@redhat.com>
Signed-off-by: Luiz Capitulino <lcapitulino@redhat.com>
2015-04-29 19:14:02 +00:00
|
|
|
for arg in tokens:
|
2017-03-02 12:24:29 +00:00
|
|
|
(key, sep, val) = arg.partition('=')
|
|
|
|
if sep != '=':
|
2021-06-07 20:06:09 +00:00
|
|
|
raise QMPShellError(
|
|
|
|
f"Expected a key=value pair, got '{arg!s}'"
|
|
|
|
)
|
scripts: qmp-shell: Expand support for QMP expressions
This includes support for [] expressions, single-quotes in
QMP expressions (which is not strictly a part of JSON), and
the ability to use "True", "False" and "None" literals instead
of JSON's equivalent true, false, and null literals.
qmp-shell currently allows you to describe values as
JSON expressions:
key={"key":{"key2":"val"}}
But it does not currently support arrays, which are needed
for serializing and deserializing transactions:
key=[{"type":"drive-backup","data":{...}}]
qmp-shell also only currently accepts doubly quoted strings
as-per JSON spec, but QMP allows single quotes.
Lastly, python allows you to utilize "True" or "False" as
boolean literals, but JSON expects "true" or "false". Expand
qmp-shell to allow the user to type either, converting to the
correct type.
As a consequence of the above, the key=val parsing is also improved
to give better error messages if a key=val token is not provided.
CAVEAT: The parser is still extremely rudimentary and does not
expect to find spaces in {} nor [] expressions. This patch does
not improve this functionality.
Signed-off-by: John Snow <jsnow@redhat.com>
Reviewed-by: Eric Blake <eblake@redhat.com>
Tested-by: Kashyap Chamarthy <kchamart@redhat.com>
Signed-off-by: Luiz Capitulino <lcapitulino@redhat.com>
2015-04-29 19:14:02 +00:00
|
|
|
|
2021-06-07 20:06:44 +00:00
|
|
|
value = self._parse_value(val)
|
scripts: qmp-shell: Expand support for QMP expressions
This includes support for [] expressions, single-quotes in
QMP expressions (which is not strictly a part of JSON), and
the ability to use "True", "False" and "None" literals instead
of JSON's equivalent true, false, and null literals.
qmp-shell currently allows you to describe values as
JSON expressions:
key={"key":{"key2":"val"}}
But it does not currently support arrays, which are needed
for serializing and deserializing transactions:
key=[{"type":"drive-backup","data":{...}}]
qmp-shell also only currently accepts doubly quoted strings
as-per JSON spec, but QMP allows single quotes.
Lastly, python allows you to utilize "True" or "False" as
boolean literals, but JSON expects "true" or "false". Expand
qmp-shell to allow the user to type either, converting to the
correct type.
As a consequence of the above, the key=val parsing is also improved
to give better error messages if a key=val token is not provided.
CAVEAT: The parser is still extremely rudimentary and does not
expect to find spaces in {} nor [] expressions. This patch does
not improve this functionality.
Signed-off-by: John Snow <jsnow@redhat.com>
Reviewed-by: Eric Blake <eblake@redhat.com>
Tested-by: Kashyap Chamarthy <kchamart@redhat.com>
Signed-off-by: Luiz Capitulino <lcapitulino@redhat.com>
2015-04-29 19:14:02 +00:00
|
|
|
optpath = key.split('.')
|
2014-02-12 03:05:13 +00:00
|
|
|
curpath = []
|
2021-06-07 20:06:20 +00:00
|
|
|
for path in optpath[:-1]:
|
|
|
|
curpath.append(path)
|
|
|
|
obj = parent.get(path, {})
|
2021-06-07 20:06:23 +00:00
|
|
|
if not isinstance(obj, dict):
|
2021-06-07 20:06:09 +00:00
|
|
|
msg = 'Cannot use "{:s}" as both leaf and non-leaf key'
|
|
|
|
raise QMPShellError(msg.format('.'.join(curpath)))
|
2021-06-07 20:06:20 +00:00
|
|
|
parent[path] = obj
|
|
|
|
parent = obj
|
2014-02-12 03:05:13 +00:00
|
|
|
if optpath[-1] in parent:
|
2021-06-07 20:06:23 +00:00
|
|
|
if isinstance(parent[optpath[-1]], dict):
|
2021-06-07 20:06:09 +00:00
|
|
|
msg = 'Cannot use "{:s}" as both leaf and non-leaf key'
|
|
|
|
raise QMPShellError(msg.format('.'.join(curpath)))
|
2021-06-07 20:06:22 +00:00
|
|
|
raise QMPShellError(f'Cannot set "{key}" multiple times')
|
2014-02-12 03:05:13 +00:00
|
|
|
parent[optpath[-1]] = value
|
2015-04-29 19:14:01 +00:00
|
|
|
|
2021-06-07 20:06:44 +00:00
|
|
|
def _build_cmd(self, cmdline: str) -> Optional[QMPMessage]:
|
2015-04-29 19:14:01 +00:00
|
|
|
"""
|
|
|
|
Build a QMP input object from a user provided command-line in the
|
|
|
|
following format:
|
|
|
|
|
|
|
|
< command-name > [ arg-name1=arg1 ] ... [ arg-nameN=argN ]
|
|
|
|
"""
|
2021-06-07 20:06:09 +00:00
|
|
|
argument_regex = r'''(?:[^\s"']|"(?:\\.|[^"])*"|'(?:\\.|[^'])*')+'''
|
|
|
|
cmdargs = re.findall(argument_regex, cmdline)
|
2021-06-07 20:06:34 +00:00
|
|
|
qmpcmd: QMPMessage
|
2015-04-29 19:14:03 +00:00
|
|
|
|
2021-06-07 20:06:41 +00:00
|
|
|
# Transactional CLI entry:
|
|
|
|
if cmdargs and cmdargs[0] == 'transaction(':
|
2015-04-29 19:14:03 +00:00
|
|
|
self._transmode = True
|
2021-06-07 20:06:41 +00:00
|
|
|
self._actions = []
|
2015-04-29 19:14:03 +00:00
|
|
|
cmdargs.pop(0)
|
2021-06-07 20:06:41 +00:00
|
|
|
|
|
|
|
# Transactional CLI exit:
|
|
|
|
if cmdargs and cmdargs[0] == ')' and self._transmode:
|
2015-04-29 19:14:03 +00:00
|
|
|
self._transmode = False
|
|
|
|
if len(cmdargs) > 1:
|
2021-06-07 20:06:09 +00:00
|
|
|
msg = 'Unexpected input after close of Transaction sub-shell'
|
|
|
|
raise QMPShellError(msg)
|
|
|
|
qmpcmd = {
|
|
|
|
'execute': 'transaction',
|
|
|
|
'arguments': {'actions': self._actions}
|
|
|
|
}
|
2015-04-29 19:14:03 +00:00
|
|
|
return qmpcmd
|
|
|
|
|
2021-06-07 20:06:41 +00:00
|
|
|
# No args, or no args remaining
|
2015-04-29 19:14:03 +00:00
|
|
|
if not cmdargs:
|
|
|
|
return None
|
|
|
|
|
|
|
|
if self._transmode:
|
2021-06-07 20:06:41 +00:00
|
|
|
# Parse and cache this Transactional Action
|
2015-04-29 19:14:03 +00:00
|
|
|
finalize = False
|
2021-06-07 20:06:09 +00:00
|
|
|
action = {'type': cmdargs[0], 'data': {}}
|
2015-04-29 19:14:03 +00:00
|
|
|
if cmdargs[-1] == ')':
|
|
|
|
cmdargs.pop(-1)
|
|
|
|
finalize = True
|
2021-06-07 20:06:44 +00:00
|
|
|
self._cli_expr(cmdargs[1:], action['data'])
|
2015-04-29 19:14:03 +00:00
|
|
|
self._actions.append(action)
|
2021-06-07 20:06:44 +00:00
|
|
|
return self._build_cmd(')') if finalize else None
|
2015-04-29 19:14:03 +00:00
|
|
|
|
|
|
|
# Standard command: parse and return it to be executed.
|
2021-06-07 20:06:09 +00:00
|
|
|
qmpcmd = {'execute': cmdargs[0], 'arguments': {}}
|
2021-06-07 20:06:44 +00:00
|
|
|
self._cli_expr(cmdargs[1:], qmpcmd['arguments'])
|
2010-10-27 19:57:51 +00:00
|
|
|
return qmpcmd
|
|
|
|
|
2022-01-28 16:11:57 +00:00
|
|
|
def _print(self, qmp_message: object, fh: IO[str] = sys.stdout) -> None:
|
2021-06-07 20:06:36 +00:00
|
|
|
jsobj = json.dumps(qmp_message,
|
|
|
|
indent=4 if self.pretty else None,
|
|
|
|
sort_keys=self.pretty)
|
2022-01-28 16:11:57 +00:00
|
|
|
print(str(jsobj), file=fh)
|
2015-04-29 19:14:04 +00:00
|
|
|
|
2021-06-07 20:06:34 +00:00
|
|
|
def _execute_cmd(self, cmdline: str) -> bool:
|
2010-10-27 19:57:51 +00:00
|
|
|
try:
|
2021-06-07 20:06:44 +00:00
|
|
|
qmpcmd = self._build_cmd(cmdline)
|
2021-06-07 20:06:42 +00:00
|
|
|
except QMPShellError as err:
|
|
|
|
print(
|
|
|
|
f"Error while parsing command line: {err!s}\n"
|
|
|
|
"command format: <command-name> "
|
|
|
|
"[arg-name1=arg1] ... [arg-nameN=argN",
|
|
|
|
file=sys.stderr
|
|
|
|
)
|
2010-10-27 19:57:51 +00:00
|
|
|
return True
|
2015-04-29 19:14:03 +00:00
|
|
|
# For transaction mode, we may have just cached the action:
|
|
|
|
if qmpcmd is None:
|
|
|
|
return True
|
2021-06-07 20:06:26 +00:00
|
|
|
if self.verbose:
|
2015-04-29 19:14:04 +00:00
|
|
|
self._print(qmpcmd)
|
2010-10-27 19:57:51 +00:00
|
|
|
resp = self.cmd_obj(qmpcmd)
|
|
|
|
if resp is None:
|
2018-06-08 12:29:43 +00:00
|
|
|
print('Disconnected')
|
2010-10-27 19:57:51 +00:00
|
|
|
return False
|
2015-04-29 19:14:04 +00:00
|
|
|
self._print(resp)
|
2022-01-28 16:11:57 +00:00
|
|
|
if self.logfile is not None:
|
|
|
|
cmd = {**qmpcmd, **resp}
|
|
|
|
self._print(cmd, fh=self.logfile)
|
2010-10-27 19:57:51 +00:00
|
|
|
return True
|
|
|
|
|
2021-06-07 20:06:34 +00:00
|
|
|
def connect(self, negotiate: bool = True) -> None:
|
2021-06-07 20:06:15 +00:00
|
|
|
self._greeting = super().connect(negotiate)
|
2021-06-07 20:06:44 +00:00
|
|
|
self._completer_setup()
|
2009-11-27 00:59:09 +00:00
|
|
|
|
2021-06-07 20:06:34 +00:00
|
|
|
def show_banner(self,
|
|
|
|
msg: str = 'Welcome to the QMP low-level shell!') -> None:
|
2021-06-07 20:06:46 +00:00
|
|
|
"""
|
|
|
|
Print to stdio a greeting, and the QEMU version if available.
|
|
|
|
"""
|
2018-06-08 12:29:43 +00:00
|
|
|
print(msg)
|
2017-05-04 12:54:31 +00:00
|
|
|
if not self._greeting:
|
2018-06-08 12:29:43 +00:00
|
|
|
print('Connected')
|
2017-05-04 12:54:31 +00:00
|
|
|
return
|
2010-10-27 19:57:51 +00:00
|
|
|
version = self._greeting['QMP']['version']['qemu']
|
2021-06-07 20:06:09 +00:00
|
|
|
print("Connected to QEMU {major}.{minor}.{micro}\n".format(**version))
|
2009-11-27 00:59:09 +00:00
|
|
|
|
2021-06-07 20:06:27 +00:00
|
|
|
@property
|
2021-06-07 20:06:34 +00:00
|
|
|
def prompt(self) -> str:
|
2021-06-07 20:06:46 +00:00
|
|
|
"""
|
|
|
|
Return the current shell prompt, including a trailing space.
|
|
|
|
"""
|
2015-04-29 19:14:03 +00:00
|
|
|
if self._transmode:
|
2021-06-07 20:06:27 +00:00
|
|
|
return 'TRANS> '
|
|
|
|
return '(QEMU) '
|
2015-04-29 19:14:03 +00:00
|
|
|
|
2021-06-07 20:06:34 +00:00
|
|
|
def read_exec_command(self) -> bool:
|
2010-10-27 19:57:51 +00:00
|
|
|
"""
|
|
|
|
Read and execute a command.
|
2009-11-27 00:59:09 +00:00
|
|
|
|
2010-10-27 19:57:51 +00:00
|
|
|
@return True if execution was ok, return False if disconnected.
|
|
|
|
"""
|
2009-11-27 00:59:09 +00:00
|
|
|
try:
|
2021-06-07 20:06:28 +00:00
|
|
|
cmdline = input(self.prompt)
|
2009-11-27 00:59:09 +00:00
|
|
|
except EOFError:
|
2018-06-08 12:29:43 +00:00
|
|
|
print()
|
2010-10-27 19:57:51 +00:00
|
|
|
return False
|
2021-06-07 20:06:22 +00:00
|
|
|
|
2010-10-27 19:57:51 +00:00
|
|
|
if cmdline == '':
|
2021-06-07 20:06:20 +00:00
|
|
|
for event in self.get_events():
|
|
|
|
print(event)
|
2010-10-27 19:57:51 +00:00
|
|
|
return True
|
2021-06-07 20:06:22 +00:00
|
|
|
|
|
|
|
return self._execute_cmd(cmdline)
|
2010-10-27 19:57:51 +00:00
|
|
|
|
2021-06-07 20:06:34 +00:00
|
|
|
def repl(self) -> Iterator[None]:
|
2021-06-07 20:06:46 +00:00
|
|
|
"""
|
|
|
|
Return an iterator that implements the REPL.
|
|
|
|
"""
|
2021-06-07 20:06:29 +00:00
|
|
|
self.show_banner()
|
|
|
|
while self.read_exec_command():
|
|
|
|
yield
|
|
|
|
self.close()
|
|
|
|
|
2021-06-07 20:06:09 +00:00
|
|
|
|
2010-10-28 15:28:37 +00:00
|
|
|
class HMPShell(QMPShell):
|
2021-06-07 20:06:46 +00:00
|
|
|
"""
|
|
|
|
HMPShell provides a basic readline-based HMP shell, tunnelled via QMP.
|
|
|
|
|
|
|
|
:param address: Address of the QMP server.
|
|
|
|
:param pretty: Pretty-print QMP messages.
|
|
|
|
:param verbose: Echo outgoing QMP messages to console.
|
|
|
|
"""
|
2022-01-10 23:28:53 +00:00
|
|
|
def __init__(self, address: SocketAddrT,
|
2022-01-28 16:11:56 +00:00
|
|
|
pretty: bool = False,
|
|
|
|
verbose: bool = False,
|
2022-01-28 16:11:57 +00:00
|
|
|
server: bool = False,
|
|
|
|
logfile: Optional[str] = None):
|
|
|
|
super().__init__(address, pretty, verbose, server, logfile)
|
2021-06-07 20:06:44 +00:00
|
|
|
self._cpu_index = 0
|
2010-10-28 15:28:37 +00:00
|
|
|
|
2021-06-07 20:06:44 +00:00
|
|
|
def _cmd_completion(self) -> None:
|
|
|
|
for cmd in self._cmd_passthrough('help')['return'].split('\r\n'):
|
2010-10-28 15:28:37 +00:00
|
|
|
if cmd and cmd[0] != '[' and cmd[0] != '\t':
|
2021-06-07 20:06:09 +00:00
|
|
|
name = cmd.split()[0] # drop help text
|
2010-10-28 15:28:37 +00:00
|
|
|
if name == 'info':
|
|
|
|
continue
|
|
|
|
if name.find('|') != -1:
|
|
|
|
# Command in the form 'foobar|f' or 'f|foobar', take the
|
|
|
|
# full name
|
|
|
|
opt = name.split('|')
|
|
|
|
if len(opt[0]) == 1:
|
|
|
|
name = opt[1]
|
|
|
|
else:
|
|
|
|
name = opt[0]
|
|
|
|
self._completer.append(name)
|
2021-06-07 20:06:09 +00:00
|
|
|
self._completer.append('help ' + name) # help completion
|
2010-10-28 15:28:37 +00:00
|
|
|
|
2021-06-07 20:06:44 +00:00
|
|
|
def _info_completion(self) -> None:
|
|
|
|
for cmd in self._cmd_passthrough('info')['return'].split('\r\n'):
|
2010-10-28 15:28:37 +00:00
|
|
|
if cmd:
|
|
|
|
self._completer.append('info ' + cmd.split()[1])
|
|
|
|
|
2021-06-07 20:06:44 +00:00
|
|
|
def _other_completion(self) -> None:
|
2010-10-28 15:28:37 +00:00
|
|
|
# special cases
|
|
|
|
self._completer.append('help info')
|
|
|
|
|
2021-06-07 20:06:34 +00:00
|
|
|
def _fill_completion(self) -> None:
|
2021-06-07 20:06:44 +00:00
|
|
|
self._cmd_completion()
|
|
|
|
self._info_completion()
|
|
|
|
self._other_completion()
|
2010-10-28 15:28:37 +00:00
|
|
|
|
2021-06-07 20:06:44 +00:00
|
|
|
def _cmd_passthrough(self, cmdline: str,
|
|
|
|
cpu_index: int = 0) -> QMPMessage:
|
2021-06-07 20:06:09 +00:00
|
|
|
return self.cmd_obj({
|
|
|
|
'execute': 'human-monitor-command',
|
|
|
|
'arguments': {
|
|
|
|
'command-line': cmdline,
|
|
|
|
'cpu-index': cpu_index
|
|
|
|
}
|
|
|
|
})
|
2010-10-28 15:28:37 +00:00
|
|
|
|
2021-06-07 20:06:34 +00:00
|
|
|
def _execute_cmd(self, cmdline: str) -> bool:
|
2010-10-28 15:28:37 +00:00
|
|
|
if cmdline.split()[0] == "cpu":
|
|
|
|
# trap the cpu command, it requires special setting
|
|
|
|
try:
|
|
|
|
idx = int(cmdline.split()[1])
|
2021-06-07 20:06:44 +00:00
|
|
|
if 'return' not in self._cmd_passthrough('info version', idx):
|
2018-06-08 12:29:43 +00:00
|
|
|
print('bad CPU index')
|
2010-10-28 15:28:37 +00:00
|
|
|
return True
|
2021-06-07 20:06:44 +00:00
|
|
|
self._cpu_index = idx
|
2010-10-28 15:28:37 +00:00
|
|
|
except ValueError:
|
2018-06-08 12:29:43 +00:00
|
|
|
print('cpu command takes an integer argument')
|
2010-10-28 15:28:37 +00:00
|
|
|
return True
|
2021-06-07 20:06:44 +00:00
|
|
|
resp = self._cmd_passthrough(cmdline, self._cpu_index)
|
2010-10-28 15:28:37 +00:00
|
|
|
if resp is None:
|
2018-06-08 12:29:43 +00:00
|
|
|
print('Disconnected')
|
2010-10-28 15:28:37 +00:00
|
|
|
return False
|
|
|
|
assert 'return' in resp or 'error' in resp
|
|
|
|
if 'return' in resp:
|
|
|
|
# Success
|
|
|
|
if len(resp['return']) > 0:
|
2018-06-08 12:29:43 +00:00
|
|
|
print(resp['return'], end=' ')
|
2010-10-28 15:28:37 +00:00
|
|
|
else:
|
|
|
|
# Error
|
2018-06-08 12:29:43 +00:00
|
|
|
print('%s: %s' % (resp['error']['class'], resp['error']['desc']))
|
2010-10-28 15:28:37 +00:00
|
|
|
return True
|
|
|
|
|
2021-06-07 20:06:34 +00:00
|
|
|
def show_banner(self, msg: str = 'Welcome to the HMP shell!') -> None:
|
2021-06-07 20:06:10 +00:00
|
|
|
QMPShell.show_banner(self, msg)
|
2010-10-28 15:28:37 +00:00
|
|
|
|
2021-06-07 20:06:09 +00:00
|
|
|
|
2021-06-07 20:06:34 +00:00
|
|
|
def die(msg: str) -> NoReturn:
|
2021-06-07 20:06:46 +00:00
|
|
|
"""Write an error to stderr, then exit with a return code of 1."""
|
2010-10-27 19:57:51 +00:00
|
|
|
sys.stderr.write('ERROR: %s\n' % msg)
|
|
|
|
sys.exit(1)
|
|
|
|
|
2021-06-07 20:06:09 +00:00
|
|
|
|
2021-06-07 20:06:34 +00:00
|
|
|
def main() -> None:
|
2021-06-07 20:06:46 +00:00
|
|
|
"""
|
|
|
|
qmp-shell entry point: parse command line arguments and start the REPL.
|
|
|
|
"""
|
2021-06-07 20:06:24 +00:00
|
|
|
parser = argparse.ArgumentParser()
|
|
|
|
parser.add_argument('-H', '--hmp', action='store_true',
|
|
|
|
help='Use HMP interface')
|
|
|
|
parser.add_argument('-N', '--skip-negotiation', action='store_true',
|
|
|
|
help='Skip negotiate (for qemu-ga)')
|
|
|
|
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')
|
2022-01-28 16:11:57 +00:00
|
|
|
parser.add_argument('-l', '--logfile',
|
|
|
|
help='Save log of all QMP messages to PATH')
|
2021-06-07 20:06:24 +00:00
|
|
|
|
|
|
|
default_server = os.environ.get('QMP_SOCKET')
|
|
|
|
parser.add_argument('qmp_server', action='store',
|
|
|
|
default=default_server,
|
|
|
|
help='< UNIX socket path | TCP address:port >')
|
|
|
|
|
|
|
|
args = parser.parse_args()
|
|
|
|
if args.qmp_server is None:
|
|
|
|
parser.error("QMP socket or TCP address must be specified")
|
|
|
|
|
2021-06-07 20:06:25 +00:00
|
|
|
shell_class = HMPShell if args.hmp else QMPShell
|
2021-06-07 20:06:38 +00:00
|
|
|
|
2010-10-27 19:57:51 +00:00
|
|
|
try:
|
2021-06-07 20:06:35 +00:00
|
|
|
address = shell_class.parse_address(args.qmp_server)
|
2022-01-10 23:28:53 +00:00
|
|
|
except QMPBadPortError:
|
2021-06-07 20:06:24 +00:00
|
|
|
parser.error(f"Bad port number: {args.qmp_server}")
|
|
|
|
return # pycharm doesn't know error() is noreturn
|
2010-10-27 19:57:51 +00:00
|
|
|
|
2022-01-28 16:11:57 +00:00
|
|
|
with shell_class(address, args.pretty, args.verbose, args.logfile) as qemu:
|
2021-06-07 20:06:38 +00:00
|
|
|
try:
|
|
|
|
qemu.connect(negotiate=not args.skip_negotiation)
|
2022-01-10 23:28:53 +00:00
|
|
|
except ConnectError as err:
|
|
|
|
if isinstance(err.exc, OSError):
|
|
|
|
die(f"Couldn't connect to {args.qmp_server}: {err!s}")
|
|
|
|
die(str(err))
|
2021-06-07 20:06:38 +00:00
|
|
|
|
|
|
|
for _ in qemu.repl():
|
|
|
|
pass
|
2009-11-27 00:59:09 +00:00
|
|
|
|
2021-06-07 20:06:09 +00:00
|
|
|
|
2022-01-28 16:11:56 +00:00
|
|
|
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')
|
2022-01-28 16:11:57 +00:00
|
|
|
parser.add_argument('-l', '--logfile',
|
|
|
|
help='Save log of all QMP messages to PATH')
|
2022-01-28 16:11:56 +00:00
|
|
|
|
|
|
|
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:
|
2022-01-28 16:11:57 +00:00
|
|
|
with shell_class(address, args.pretty, args.verbose,
|
|
|
|
True, args.logfile) as qemu:
|
2022-01-28 16:11:56 +00:00
|
|
|
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)
|
|
|
|
|
|
|
|
|
2009-11-27 00:59:09 +00:00
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|