2009-11-27 01:59:09 +01:00
|
|
|
#
|
2010-10-27 21:57:51 +02:00
|
|
|
# Copyright (C) 2009, 2010 Red Hat Inc.
|
2009-11-27 01:59:09 +01:00
|
|
|
#
|
|
|
|
# Authors:
|
|
|
|
# Luiz Capitulino <lcapitulino@redhat.com>
|
|
|
|
#
|
|
|
|
# This work is licensed under the terms of the GNU GPL, version 2. See
|
|
|
|
# the COPYING file in the top-level directory.
|
|
|
|
#
|
2021-06-07 22:06:43 +02: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 22:06:24 +02: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 21:14:02 +02:00
|
|
|
import ast
|
2021-06-07 22:06:08 +02:00
|
|
|
import json
|
2021-06-07 22:06:39 +02:00
|
|
|
import logging
|
2021-06-07 22:06:08 +02: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 14:49:26 +01:00
|
|
|
import re
|
2021-06-07 22:06:08 +02:00
|
|
|
import readline
|
|
|
|
import sys
|
2021-06-07 22:06:34 +02:00
|
|
|
from typing import (
|
|
|
|
Iterator,
|
|
|
|
List,
|
|
|
|
NoReturn,
|
|
|
|
Optional,
|
|
|
|
Sequence,
|
|
|
|
)
|
2021-06-07 22:06:08 +02:00
|
|
|
|
2022-01-11 00:28:53 +01:00
|
|
|
from qemu.aqmp import ConnectError, QMPError, SocketAddrT
|
|
|
|
from qemu.aqmp.legacy import (
|
|
|
|
QEMUMonitorProtocol,
|
|
|
|
QMPBadPortError,
|
|
|
|
QMPMessage,
|
|
|
|
QMPObject,
|
|
|
|
)
|
2019-02-06 17:29:01 +01:00
|
|
|
|
2021-06-07 22:06:08 +02:00
|
|
|
|
2021-06-07 22:06:39 +02:00
|
|
|
LOG = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2021-06-07 22:06:31 +02:00
|
|
|
class QMPCompleter:
|
2021-06-07 22:06:46 +02:00
|
|
|
"""
|
|
|
|
QMPCompleter provides a readline library tab-complete behavior.
|
|
|
|
"""
|
2021-06-07 22:06:31 +02: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 22:06:46 +02:00
|
|
|
"""Append a new valid completion to the list of possibilities."""
|
2021-06-07 22:06:31 +02:00
|
|
|
return self._matches.append(value)
|
|
|
|
|
|
|
|
def complete(self, text: str, state: int) -> Optional[str]:
|
2021-06-07 22:06:46 +02:00
|
|
|
"""readline.set_completer() callback implementation."""
|
2021-06-07 22:06:31 +02:00
|
|
|
for cmd in self._matches:
|
2010-10-27 21:57:51 +02:00
|
|
|
if cmd.startswith(text):
|
2021-06-07 22:06:19 +02:00
|
|
|
if state == 0:
|
2010-10-27 21:57:51 +02:00
|
|
|
return cmd
|
2021-06-07 22:06:19 +02:00
|
|
|
state -= 1
|
|
|
|
return None
|
2009-11-27 01:59:09 +01:00
|
|
|
|
2021-06-07 22:06:09 +02:00
|
|
|
|
2022-01-11 00:28:53 +01:00
|
|
|
class QMPShellError(QMPError):
|
2021-06-07 22:06:46 +02:00
|
|
|
"""
|
|
|
|
QMP Shell Base error class.
|
|
|
|
"""
|
2010-10-27 21:57:51 +02: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 21:14:02 +02:00
|
|
|
class FuzzyJSON(ast.NodeTransformer):
|
2021-06-07 22:06:17 +02:00
|
|
|
"""
|
|
|
|
This extension of ast.NodeTransformer filters literal "true/false/null"
|
2021-06-07 22:06:30 +02:00
|
|
|
values in a Python AST and replaces them by proper "True/False/None" values
|
|
|
|
that Python can properly evaluate.
|
2021-06-07 22:06:17 +02:00
|
|
|
"""
|
|
|
|
|
2021-06-07 22:06:14 +02:00
|
|
|
@classmethod
|
2021-06-07 22:06:30 +02:00
|
|
|
def visit_Name(cls, # pylint: disable=invalid-name
|
|
|
|
node: ast.Name) -> ast.AST:
|
2021-06-07 22:06:46 +02: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 21:14:02 +02:00
|
|
|
if node.id == 'true':
|
2021-06-07 22:06:30 +02: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 21:14:02 +02:00
|
|
|
if node.id == 'false':
|
2021-06-07 22:06:30 +02: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 21:14:02 +02:00
|
|
|
if node.id == 'null':
|
2021-06-07 22:06:30 +02: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 21:14:02 +02:00
|
|
|
return node
|
|
|
|
|
2021-06-07 22:06:09 +02:00
|
|
|
|
2022-01-11 00:28:53 +01:00
|
|
|
class QMPShell(QEMUMonitorProtocol):
|
2021-06-07 22:06:46 +02: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-11 00:28:53 +01:00
|
|
|
def __init__(self, address: SocketAddrT,
|
2021-06-07 22:06:35 +02:00
|
|
|
pretty: bool = False, verbose: bool = False):
|
|
|
|
super().__init__(address)
|
2021-06-07 22:06:34 +02:00
|
|
|
self._greeting: Optional[QMPMessage] = None
|
2021-06-07 22:06:32 +02:00
|
|
|
self._completer = QMPCompleter()
|
2015-04-29 21:14:03 +02:00
|
|
|
self._transmode = False
|
2021-06-07 22:06:34 +02:00
|
|
|
self._actions: List[QMPMessage] = []
|
2017-04-28 00:36:28 +02:00
|
|
|
self._histfile = os.path.join(os.path.expanduser('~'),
|
|
|
|
'.qmp-shell_history')
|
2021-06-07 22:06:36 +02:00
|
|
|
self.pretty = pretty
|
2021-06-07 22:06:26 +02:00
|
|
|
self.verbose = verbose
|
2010-10-27 21:57:51 +02:00
|
|
|
|
2021-06-07 22:06:38 +02:00
|
|
|
def close(self) -> None:
|
|
|
|
# Hook into context manager of parent to save shell history.
|
|
|
|
self._save_history()
|
|
|
|
super().close()
|
|
|
|
|
2021-06-07 22:06:34 +02:00
|
|
|
def _fill_completion(self) -> None:
|
2017-05-04 14:54:30 +02:00
|
|
|
cmds = self.cmd('query-commands')
|
2018-06-08 14:29:46 +02:00
|
|
|
if 'error' in cmds:
|
2017-05-04 14:54:30 +02:00
|
|
|
return
|
|
|
|
for cmd in cmds['return']:
|
2010-10-27 21:57:51 +02:00
|
|
|
self._completer.append(cmd['name'])
|
|
|
|
|
2021-06-07 22:06:44 +02:00
|
|
|
def _completer_setup(self) -> None:
|
2010-10-27 21:57:51 +02:00
|
|
|
self._completer = QMPCompleter()
|
|
|
|
self._fill_completion()
|
2017-04-28 00:36:28 +02:00
|
|
|
readline.set_history_length(1024)
|
2010-10-27 21:57:51 +02:00
|
|
|
readline.set_completer(self._completer.complete)
|
|
|
|
readline.parse_and_bind("tab: complete")
|
2021-06-07 22:06:09 +02:00
|
|
|
# NB: default delimiters conflict with some command names
|
|
|
|
# (eg. query-), clearing everything as it doesn't seem to matter
|
2010-10-27 21:57:51 +02:00
|
|
|
readline.set_completer_delims('')
|
2017-04-28 00:36:28 +02:00
|
|
|
try:
|
|
|
|
readline.read_history_file(self._histfile)
|
2021-06-07 22:06:21 +02:00
|
|
|
except FileNotFoundError:
|
|
|
|
pass
|
|
|
|
except IOError as err:
|
2021-06-07 22:06:39 +02:00
|
|
|
msg = f"Failed to read history '{self._histfile}': {err!s}"
|
|
|
|
LOG.warning(msg)
|
2017-04-28 00:36:28 +02:00
|
|
|
|
2021-06-07 22:06:38 +02:00
|
|
|
def _save_history(self) -> None:
|
2017-04-28 00:36:28 +02:00
|
|
|
try:
|
|
|
|
readline.write_history_file(self._histfile)
|
2021-06-07 22:06:21 +02:00
|
|
|
except IOError as err:
|
2021-06-07 22:06:39 +02:00
|
|
|
msg = f"Failed to save history file '{self._histfile}': {err!s}"
|
|
|
|
LOG.warning(msg)
|
2010-10-27 21:57:51 +02:00
|
|
|
|
2021-06-07 22:06:14 +02:00
|
|
|
@classmethod
|
2021-06-07 22:06:44 +02: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 21:14:02 +02: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 21:57:51 +02: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 21:14:02 +02:00
|
|
|
return json.loads(val)
|
2010-10-27 21:57:51 +02: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 21:14:02 +02:00
|
|
|
pass
|
|
|
|
# Try once again as FuzzyJSON:
|
|
|
|
try:
|
2021-06-07 22:06:20 +02:00
|
|
|
tree = ast.parse(val, mode='eval')
|
2021-06-07 22:06:30 +02: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 21:14:02 +02:00
|
|
|
pass
|
|
|
|
return val
|
|
|
|
|
2021-06-07 22:06:44 +02:00
|
|
|
def _cli_expr(self,
|
|
|
|
tokens: Sequence[str],
|
2022-01-11 00:28:53 +01: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 21:14:02 +02:00
|
|
|
for arg in tokens:
|
2017-03-02 13:24:29 +01:00
|
|
|
(key, sep, val) = arg.partition('=')
|
|
|
|
if sep != '=':
|
2021-06-07 22:06:09 +02: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 21:14:02 +02:00
|
|
|
|
2021-06-07 22:06:44 +02: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 21:14:02 +02:00
|
|
|
optpath = key.split('.')
|
2014-02-12 04:05:13 +01:00
|
|
|
curpath = []
|
2021-06-07 22:06:20 +02:00
|
|
|
for path in optpath[:-1]:
|
|
|
|
curpath.append(path)
|
|
|
|
obj = parent.get(path, {})
|
2021-06-07 22:06:23 +02:00
|
|
|
if not isinstance(obj, dict):
|
2021-06-07 22:06:09 +02:00
|
|
|
msg = 'Cannot use "{:s}" as both leaf and non-leaf key'
|
|
|
|
raise QMPShellError(msg.format('.'.join(curpath)))
|
2021-06-07 22:06:20 +02:00
|
|
|
parent[path] = obj
|
|
|
|
parent = obj
|
2014-02-12 04:05:13 +01:00
|
|
|
if optpath[-1] in parent:
|
2021-06-07 22:06:23 +02:00
|
|
|
if isinstance(parent[optpath[-1]], dict):
|
2021-06-07 22:06:09 +02:00
|
|
|
msg = 'Cannot use "{:s}" as both leaf and non-leaf key'
|
|
|
|
raise QMPShellError(msg.format('.'.join(curpath)))
|
2021-06-07 22:06:22 +02:00
|
|
|
raise QMPShellError(f'Cannot set "{key}" multiple times')
|
2014-02-12 04:05:13 +01:00
|
|
|
parent[optpath[-1]] = value
|
2015-04-29 21:14:01 +02:00
|
|
|
|
2021-06-07 22:06:44 +02:00
|
|
|
def _build_cmd(self, cmdline: str) -> Optional[QMPMessage]:
|
2015-04-29 21:14:01 +02: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 22:06:09 +02:00
|
|
|
argument_regex = r'''(?:[^\s"']|"(?:\\.|[^"])*"|'(?:\\.|[^'])*')+'''
|
|
|
|
cmdargs = re.findall(argument_regex, cmdline)
|
2021-06-07 22:06:34 +02:00
|
|
|
qmpcmd: QMPMessage
|
2015-04-29 21:14:03 +02:00
|
|
|
|
2021-06-07 22:06:41 +02:00
|
|
|
# Transactional CLI entry:
|
|
|
|
if cmdargs and cmdargs[0] == 'transaction(':
|
2015-04-29 21:14:03 +02:00
|
|
|
self._transmode = True
|
2021-06-07 22:06:41 +02:00
|
|
|
self._actions = []
|
2015-04-29 21:14:03 +02:00
|
|
|
cmdargs.pop(0)
|
2021-06-07 22:06:41 +02:00
|
|
|
|
|
|
|
# Transactional CLI exit:
|
|
|
|
if cmdargs and cmdargs[0] == ')' and self._transmode:
|
2015-04-29 21:14:03 +02:00
|
|
|
self._transmode = False
|
|
|
|
if len(cmdargs) > 1:
|
2021-06-07 22:06:09 +02:00
|
|
|
msg = 'Unexpected input after close of Transaction sub-shell'
|
|
|
|
raise QMPShellError(msg)
|
|
|
|
qmpcmd = {
|
|
|
|
'execute': 'transaction',
|
|
|
|
'arguments': {'actions': self._actions}
|
|
|
|
}
|
2015-04-29 21:14:03 +02:00
|
|
|
return qmpcmd
|
|
|
|
|
2021-06-07 22:06:41 +02:00
|
|
|
# No args, or no args remaining
|
2015-04-29 21:14:03 +02:00
|
|
|
if not cmdargs:
|
|
|
|
return None
|
|
|
|
|
|
|
|
if self._transmode:
|
2021-06-07 22:06:41 +02:00
|
|
|
# Parse and cache this Transactional Action
|
2015-04-29 21:14:03 +02:00
|
|
|
finalize = False
|
2021-06-07 22:06:09 +02:00
|
|
|
action = {'type': cmdargs[0], 'data': {}}
|
2015-04-29 21:14:03 +02:00
|
|
|
if cmdargs[-1] == ')':
|
|
|
|
cmdargs.pop(-1)
|
|
|
|
finalize = True
|
2021-06-07 22:06:44 +02:00
|
|
|
self._cli_expr(cmdargs[1:], action['data'])
|
2015-04-29 21:14:03 +02:00
|
|
|
self._actions.append(action)
|
2021-06-07 22:06:44 +02:00
|
|
|
return self._build_cmd(')') if finalize else None
|
2015-04-29 21:14:03 +02:00
|
|
|
|
|
|
|
# Standard command: parse and return it to be executed.
|
2021-06-07 22:06:09 +02:00
|
|
|
qmpcmd = {'execute': cmdargs[0], 'arguments': {}}
|
2021-06-07 22:06:44 +02:00
|
|
|
self._cli_expr(cmdargs[1:], qmpcmd['arguments'])
|
2010-10-27 21:57:51 +02:00
|
|
|
return qmpcmd
|
|
|
|
|
2021-06-07 22:06:34 +02:00
|
|
|
def _print(self, qmp_message: object) -> None:
|
2021-06-07 22:06:36 +02:00
|
|
|
jsobj = json.dumps(qmp_message,
|
|
|
|
indent=4 if self.pretty else None,
|
|
|
|
sort_keys=self.pretty)
|
2018-06-08 14:29:43 +02:00
|
|
|
print(str(jsobj))
|
2015-04-29 21:14:04 +02:00
|
|
|
|
2021-06-07 22:06:34 +02:00
|
|
|
def _execute_cmd(self, cmdline: str) -> bool:
|
2010-10-27 21:57:51 +02:00
|
|
|
try:
|
2021-06-07 22:06:44 +02:00
|
|
|
qmpcmd = self._build_cmd(cmdline)
|
2021-06-07 22:06:42 +02: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 21:57:51 +02:00
|
|
|
return True
|
2015-04-29 21:14:03 +02:00
|
|
|
# For transaction mode, we may have just cached the action:
|
|
|
|
if qmpcmd is None:
|
|
|
|
return True
|
2021-06-07 22:06:26 +02:00
|
|
|
if self.verbose:
|
2015-04-29 21:14:04 +02:00
|
|
|
self._print(qmpcmd)
|
2010-10-27 21:57:51 +02:00
|
|
|
resp = self.cmd_obj(qmpcmd)
|
|
|
|
if resp is None:
|
2018-06-08 14:29:43 +02:00
|
|
|
print('Disconnected')
|
2010-10-27 21:57:51 +02:00
|
|
|
return False
|
2015-04-29 21:14:04 +02:00
|
|
|
self._print(resp)
|
2010-10-27 21:57:51 +02:00
|
|
|
return True
|
|
|
|
|
2021-06-07 22:06:34 +02:00
|
|
|
def connect(self, negotiate: bool = True) -> None:
|
2021-06-07 22:06:15 +02:00
|
|
|
self._greeting = super().connect(negotiate)
|
2021-06-07 22:06:44 +02:00
|
|
|
self._completer_setup()
|
2009-11-27 01:59:09 +01:00
|
|
|
|
2021-06-07 22:06:34 +02:00
|
|
|
def show_banner(self,
|
|
|
|
msg: str = 'Welcome to the QMP low-level shell!') -> None:
|
2021-06-07 22:06:46 +02:00
|
|
|
"""
|
|
|
|
Print to stdio a greeting, and the QEMU version if available.
|
|
|
|
"""
|
2018-06-08 14:29:43 +02:00
|
|
|
print(msg)
|
2017-05-04 14:54:31 +02:00
|
|
|
if not self._greeting:
|
2018-06-08 14:29:43 +02:00
|
|
|
print('Connected')
|
2017-05-04 14:54:31 +02:00
|
|
|
return
|
2010-10-27 21:57:51 +02:00
|
|
|
version = self._greeting['QMP']['version']['qemu']
|
2021-06-07 22:06:09 +02:00
|
|
|
print("Connected to QEMU {major}.{minor}.{micro}\n".format(**version))
|
2009-11-27 01:59:09 +01:00
|
|
|
|
2021-06-07 22:06:27 +02:00
|
|
|
@property
|
2021-06-07 22:06:34 +02:00
|
|
|
def prompt(self) -> str:
|
2021-06-07 22:06:46 +02:00
|
|
|
"""
|
|
|
|
Return the current shell prompt, including a trailing space.
|
|
|
|
"""
|
2015-04-29 21:14:03 +02:00
|
|
|
if self._transmode:
|
2021-06-07 22:06:27 +02:00
|
|
|
return 'TRANS> '
|
|
|
|
return '(QEMU) '
|
2015-04-29 21:14:03 +02:00
|
|
|
|
2021-06-07 22:06:34 +02:00
|
|
|
def read_exec_command(self) -> bool:
|
2010-10-27 21:57:51 +02:00
|
|
|
"""
|
|
|
|
Read and execute a command.
|
2009-11-27 01:59:09 +01:00
|
|
|
|
2010-10-27 21:57:51 +02:00
|
|
|
@return True if execution was ok, return False if disconnected.
|
|
|
|
"""
|
2009-11-27 01:59:09 +01:00
|
|
|
try:
|
2021-06-07 22:06:28 +02:00
|
|
|
cmdline = input(self.prompt)
|
2009-11-27 01:59:09 +01:00
|
|
|
except EOFError:
|
2018-06-08 14:29:43 +02:00
|
|
|
print()
|
2010-10-27 21:57:51 +02:00
|
|
|
return False
|
2021-06-07 22:06:22 +02:00
|
|
|
|
2010-10-27 21:57:51 +02:00
|
|
|
if cmdline == '':
|
2021-06-07 22:06:20 +02:00
|
|
|
for event in self.get_events():
|
|
|
|
print(event)
|
2010-10-27 21:57:51 +02:00
|
|
|
return True
|
2021-06-07 22:06:22 +02:00
|
|
|
|
|
|
|
return self._execute_cmd(cmdline)
|
2010-10-27 21:57:51 +02:00
|
|
|
|
2021-06-07 22:06:34 +02:00
|
|
|
def repl(self) -> Iterator[None]:
|
2021-06-07 22:06:46 +02:00
|
|
|
"""
|
|
|
|
Return an iterator that implements the REPL.
|
|
|
|
"""
|
2021-06-07 22:06:29 +02:00
|
|
|
self.show_banner()
|
|
|
|
while self.read_exec_command():
|
|
|
|
yield
|
|
|
|
self.close()
|
|
|
|
|
2021-06-07 22:06:09 +02:00
|
|
|
|
2010-10-28 17:28:37 +02:00
|
|
|
class HMPShell(QMPShell):
|
2021-06-07 22:06:46 +02: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-11 00:28:53 +01:00
|
|
|
def __init__(self, address: SocketAddrT,
|
2021-06-07 22:06:34 +02:00
|
|
|
pretty: bool = False, verbose: bool = False):
|
2021-06-07 22:06:26 +02:00
|
|
|
super().__init__(address, pretty, verbose)
|
2021-06-07 22:06:44 +02:00
|
|
|
self._cpu_index = 0
|
2010-10-28 17:28:37 +02:00
|
|
|
|
2021-06-07 22:06:44 +02:00
|
|
|
def _cmd_completion(self) -> None:
|
|
|
|
for cmd in self._cmd_passthrough('help')['return'].split('\r\n'):
|
2010-10-28 17:28:37 +02:00
|
|
|
if cmd and cmd[0] != '[' and cmd[0] != '\t':
|
2021-06-07 22:06:09 +02:00
|
|
|
name = cmd.split()[0] # drop help text
|
2010-10-28 17:28:37 +02: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 22:06:09 +02:00
|
|
|
self._completer.append('help ' + name) # help completion
|
2010-10-28 17:28:37 +02:00
|
|
|
|
2021-06-07 22:06:44 +02:00
|
|
|
def _info_completion(self) -> None:
|
|
|
|
for cmd in self._cmd_passthrough('info')['return'].split('\r\n'):
|
2010-10-28 17:28:37 +02:00
|
|
|
if cmd:
|
|
|
|
self._completer.append('info ' + cmd.split()[1])
|
|
|
|
|
2021-06-07 22:06:44 +02:00
|
|
|
def _other_completion(self) -> None:
|
2010-10-28 17:28:37 +02:00
|
|
|
# special cases
|
|
|
|
self._completer.append('help info')
|
|
|
|
|
2021-06-07 22:06:34 +02:00
|
|
|
def _fill_completion(self) -> None:
|
2021-06-07 22:06:44 +02:00
|
|
|
self._cmd_completion()
|
|
|
|
self._info_completion()
|
|
|
|
self._other_completion()
|
2010-10-28 17:28:37 +02:00
|
|
|
|
2021-06-07 22:06:44 +02:00
|
|
|
def _cmd_passthrough(self, cmdline: str,
|
|
|
|
cpu_index: int = 0) -> QMPMessage:
|
2021-06-07 22:06:09 +02:00
|
|
|
return self.cmd_obj({
|
|
|
|
'execute': 'human-monitor-command',
|
|
|
|
'arguments': {
|
|
|
|
'command-line': cmdline,
|
|
|
|
'cpu-index': cpu_index
|
|
|
|
}
|
|
|
|
})
|
2010-10-28 17:28:37 +02:00
|
|
|
|
2021-06-07 22:06:34 +02:00
|
|
|
def _execute_cmd(self, cmdline: str) -> bool:
|
2010-10-28 17:28:37 +02:00
|
|
|
if cmdline.split()[0] == "cpu":
|
|
|
|
# trap the cpu command, it requires special setting
|
|
|
|
try:
|
|
|
|
idx = int(cmdline.split()[1])
|
2021-06-07 22:06:44 +02:00
|
|
|
if 'return' not in self._cmd_passthrough('info version', idx):
|
2018-06-08 14:29:43 +02:00
|
|
|
print('bad CPU index')
|
2010-10-28 17:28:37 +02:00
|
|
|
return True
|
2021-06-07 22:06:44 +02:00
|
|
|
self._cpu_index = idx
|
2010-10-28 17:28:37 +02:00
|
|
|
except ValueError:
|
2018-06-08 14:29:43 +02:00
|
|
|
print('cpu command takes an integer argument')
|
2010-10-28 17:28:37 +02:00
|
|
|
return True
|
2021-06-07 22:06:44 +02:00
|
|
|
resp = self._cmd_passthrough(cmdline, self._cpu_index)
|
2010-10-28 17:28:37 +02:00
|
|
|
if resp is None:
|
2018-06-08 14:29:43 +02:00
|
|
|
print('Disconnected')
|
2010-10-28 17:28:37 +02:00
|
|
|
return False
|
|
|
|
assert 'return' in resp or 'error' in resp
|
|
|
|
if 'return' in resp:
|
|
|
|
# Success
|
|
|
|
if len(resp['return']) > 0:
|
2018-06-08 14:29:43 +02:00
|
|
|
print(resp['return'], end=' ')
|
2010-10-28 17:28:37 +02:00
|
|
|
else:
|
|
|
|
# Error
|
2018-06-08 14:29:43 +02:00
|
|
|
print('%s: %s' % (resp['error']['class'], resp['error']['desc']))
|
2010-10-28 17:28:37 +02:00
|
|
|
return True
|
|
|
|
|
2021-06-07 22:06:34 +02:00
|
|
|
def show_banner(self, msg: str = 'Welcome to the HMP shell!') -> None:
|
2021-06-07 22:06:10 +02:00
|
|
|
QMPShell.show_banner(self, msg)
|
2010-10-28 17:28:37 +02:00
|
|
|
|
2021-06-07 22:06:09 +02:00
|
|
|
|
2021-06-07 22:06:34 +02:00
|
|
|
def die(msg: str) -> NoReturn:
|
2021-06-07 22:06:46 +02:00
|
|
|
"""Write an error to stderr, then exit with a return code of 1."""
|
2010-10-27 21:57:51 +02:00
|
|
|
sys.stderr.write('ERROR: %s\n' % msg)
|
|
|
|
sys.exit(1)
|
|
|
|
|
2021-06-07 22:06:09 +02:00
|
|
|
|
2021-06-07 22:06:34 +02:00
|
|
|
def main() -> None:
|
2021-06-07 22:06:46 +02:00
|
|
|
"""
|
|
|
|
qmp-shell entry point: parse command line arguments and start the REPL.
|
|
|
|
"""
|
2021-06-07 22:06:24 +02: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')
|
|
|
|
|
|
|
|
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 22:06:25 +02:00
|
|
|
shell_class = HMPShell if args.hmp else QMPShell
|
2021-06-07 22:06:38 +02:00
|
|
|
|
2010-10-27 21:57:51 +02:00
|
|
|
try:
|
2021-06-07 22:06:35 +02:00
|
|
|
address = shell_class.parse_address(args.qmp_server)
|
2022-01-11 00:28:53 +01:00
|
|
|
except QMPBadPortError:
|
2021-06-07 22:06:24 +02:00
|
|
|
parser.error(f"Bad port number: {args.qmp_server}")
|
|
|
|
return # pycharm doesn't know error() is noreturn
|
2010-10-27 21:57:51 +02:00
|
|
|
|
2021-06-07 22:06:38 +02:00
|
|
|
with shell_class(address, args.pretty, args.verbose) as qemu:
|
|
|
|
try:
|
|
|
|
qemu.connect(negotiate=not args.skip_negotiation)
|
2022-01-11 00:28:53 +01: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 22:06:38 +02:00
|
|
|
|
|
|
|
for _ in qemu.repl():
|
|
|
|
pass
|
2009-11-27 01:59:09 +01:00
|
|
|
|
2021-06-07 22:06:09 +02:00
|
|
|
|
2009-11-27 01:59:09 +01:00
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|