2019-12-27 14:40:58 +01:00
|
|
|
""" QEMU Monitor Protocol Python class """
|
2010-10-27 21:43:34 +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.
|
|
|
|
|
2010-10-27 21:43:34 +02:00
|
|
|
import json
|
|
|
|
import errno
|
|
|
|
import socket
|
2017-10-05 19:20:12 +02:00
|
|
|
import logging
|
2020-05-14 07:53:43 +02:00
|
|
|
from typing import (
|
2020-07-10 07:22:05 +02:00
|
|
|
Any,
|
2020-07-10 07:22:09 +02:00
|
|
|
cast,
|
2020-07-10 07:22:05 +02:00
|
|
|
Dict,
|
2020-05-14 07:53:43 +02:00
|
|
|
Optional,
|
|
|
|
TextIO,
|
2020-05-14 07:53:44 +02:00
|
|
|
Type,
|
2020-07-10 07:22:05 +02:00
|
|
|
Tuple,
|
|
|
|
Union,
|
2020-05-14 07:53:43 +02:00
|
|
|
)
|
2020-05-14 07:53:44 +02:00
|
|
|
from types import TracebackType
|
2009-11-27 01:59:09 +01:00
|
|
|
|
2017-08-18 16:26:09 +02:00
|
|
|
|
2020-07-10 07:22:05 +02:00
|
|
|
# QMPMessage is a QMP Message of any kind.
|
|
|
|
# e.g. {'yee': 'haw'}
|
|
|
|
#
|
|
|
|
# QMPReturnValue is the inner value of return values only.
|
|
|
|
# {'return': {}} is the QMPMessage,
|
|
|
|
# {} is the QMPReturnValue.
|
|
|
|
QMPMessage = Dict[str, Any]
|
|
|
|
QMPReturnValue = Dict[str, Any]
|
|
|
|
|
|
|
|
InternetAddrT = Tuple[str, str]
|
|
|
|
UnixAddrT = str
|
|
|
|
SocketAddrT = Union[InternetAddrT, UnixAddrT]
|
|
|
|
|
|
|
|
|
2009-11-27 01:59:09 +01:00
|
|
|
class QMPError(Exception):
|
2019-12-27 14:40:58 +01:00
|
|
|
"""
|
|
|
|
QMP base exception
|
|
|
|
"""
|
2009-11-27 01:59:09 +01:00
|
|
|
|
2017-08-18 16:26:09 +02:00
|
|
|
|
2009-11-27 01:59:09 +01:00
|
|
|
class QMPConnectError(QMPError):
|
2019-12-27 14:40:58 +01:00
|
|
|
"""
|
|
|
|
QMP connection exception
|
|
|
|
"""
|
2009-11-27 01:59:09 +01:00
|
|
|
|
2017-08-18 16:26:09 +02:00
|
|
|
|
2010-10-27 21:43:34 +02:00
|
|
|
class QMPCapabilitiesError(QMPError):
|
2019-12-27 14:40:58 +01:00
|
|
|
"""
|
|
|
|
QMP negotiate capabilities exception
|
|
|
|
"""
|
2010-10-27 21:43:34 +02:00
|
|
|
|
2017-08-18 16:26:09 +02:00
|
|
|
|
2015-04-18 01:50:06 +02:00
|
|
|
class QMPTimeoutError(QMPError):
|
2019-12-27 14:40:58 +01:00
|
|
|
"""
|
|
|
|
QMP timeout exception
|
|
|
|
"""
|
2015-04-18 01:50:06 +02:00
|
|
|
|
2017-08-18 16:26:09 +02:00
|
|
|
|
2020-07-10 07:22:10 +02:00
|
|
|
class QMPProtocolError(QMPError):
|
|
|
|
"""
|
|
|
|
QMP protocol error; unexpected response
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
2020-07-10 07:22:07 +02:00
|
|
|
class QMPResponseError(QMPError):
|
|
|
|
"""
|
|
|
|
Represents erroneous QMP monitor reply
|
|
|
|
"""
|
|
|
|
def __init__(self, reply: QMPMessage):
|
|
|
|
try:
|
|
|
|
desc = reply['error']['desc']
|
|
|
|
except KeyError:
|
|
|
|
desc = reply
|
|
|
|
super().__init__(desc)
|
|
|
|
self.reply = reply
|
|
|
|
|
|
|
|
|
2019-12-27 14:40:58 +01:00
|
|
|
class QEMUMonitorProtocol:
|
|
|
|
"""
|
|
|
|
Provide an API to connect to QEMU via QEMU Monitor Protocol (QMP) and then
|
|
|
|
allow to handle commands and events.
|
|
|
|
"""
|
2017-08-18 16:26:09 +02:00
|
|
|
|
2017-10-05 19:20:12 +02:00
|
|
|
#: Logger object for debugging messages
|
|
|
|
logger = logging.getLogger('QMP')
|
2017-08-18 16:26:09 +02:00
|
|
|
|
2020-03-16 11:32:03 +01:00
|
|
|
def __init__(self, address, server=False, nickname=None):
|
2010-10-27 21:43:34 +02:00
|
|
|
"""
|
|
|
|
Create a QEMUMonitorProtocol class.
|
|
|
|
|
|
|
|
@param address: QEMU address, can be either a unix socket path (string)
|
|
|
|
or a tuple in the form ( address, port ) for a TCP
|
|
|
|
connection
|
2011-05-25 20:48:01 +02:00
|
|
|
@param server: server mode listens on the socket (bool)
|
2019-12-27 14:40:57 +01:00
|
|
|
@raise OSError on socket connection errors
|
2011-05-25 20:48:01 +02:00
|
|
|
@note No connection is established, this is done by the connect() or
|
|
|
|
accept() methods
|
2010-10-27 21:43:34 +02:00
|
|
|
"""
|
|
|
|
self.__events = []
|
|
|
|
self.__address = address
|
|
|
|
self.__sock = self.__get_sock()
|
2020-05-14 07:53:43 +02:00
|
|
|
self.__sockfile: Optional[TextIO] = None
|
2020-03-16 11:32:03 +01:00
|
|
|
self._nickname = nickname
|
|
|
|
if self._nickname:
|
|
|
|
self.logger = logging.getLogger('QMP').getChild(self._nickname)
|
2011-05-25 20:48:01 +02:00
|
|
|
if server:
|
2016-07-20 15:23:12 +02:00
|
|
|
self.__sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
2011-05-25 20:48:01 +02:00
|
|
|
self.__sock.bind(self.__address)
|
|
|
|
self.__sock.listen(1)
|
2010-10-27 21:43:34 +02:00
|
|
|
|
|
|
|
def __get_sock(self):
|
|
|
|
if isinstance(self.__address, tuple):
|
|
|
|
family = socket.AF_INET
|
|
|
|
else:
|
|
|
|
family = socket.AF_UNIX
|
|
|
|
return socket.socket(family, socket.SOCK_STREAM)
|
|
|
|
|
2011-05-25 20:48:01 +02:00
|
|
|
def __negotiate_capabilities(self):
|
|
|
|
greeting = self.__json_read()
|
2017-08-18 16:26:09 +02:00
|
|
|
if greeting is None or "QMP" not in greeting:
|
2011-05-25 20:48:01 +02:00
|
|
|
raise QMPConnectError
|
|
|
|
# Greeting seems ok, negotiate capabilities
|
|
|
|
resp = self.cmd('qmp_capabilities')
|
2020-01-20 08:12:02 +01:00
|
|
|
if resp and "return" in resp:
|
2011-05-25 20:48:01 +02:00
|
|
|
return greeting
|
|
|
|
raise QMPCapabilitiesError
|
|
|
|
|
2011-05-25 20:48:00 +02:00
|
|
|
def __json_read(self, only_event=False):
|
2020-05-14 07:53:51 +02:00
|
|
|
assert self.__sockfile is not None
|
2010-10-27 21:43:34 +02:00
|
|
|
while True:
|
|
|
|
data = self.__sockfile.readline()
|
|
|
|
if not data:
|
2019-12-27 14:40:58 +01:00
|
|
|
return None
|
2020-07-10 07:22:09 +02:00
|
|
|
# By definition, any JSON received from QMP is a QMPMessage,
|
|
|
|
# and we are asserting only at static analysis time that it
|
|
|
|
# has a particular shape.
|
|
|
|
resp: QMPMessage = json.loads(data)
|
2010-10-27 21:43:34 +02:00
|
|
|
if 'event' in resp:
|
2017-10-05 19:20:12 +02:00
|
|
|
self.logger.debug("<<< %s", resp)
|
2010-10-27 21:43:34 +02:00
|
|
|
self.__events.append(resp)
|
2011-05-25 20:48:00 +02:00
|
|
|
if not only_event:
|
|
|
|
continue
|
2010-10-27 21:43:34 +02:00
|
|
|
return resp
|
|
|
|
|
2015-04-18 01:50:06 +02:00
|
|
|
def __get_events(self, wait=False):
|
|
|
|
"""
|
|
|
|
Check for new events in the stream and cache them in __events.
|
|
|
|
|
|
|
|
@param wait (bool): block until an event is available.
|
|
|
|
@param wait (float): If wait is a float, treat it as a timeout value.
|
|
|
|
|
|
|
|
@raise QMPTimeoutError: If a timeout float is provided and the timeout
|
|
|
|
period elapses.
|
2017-08-18 16:26:09 +02:00
|
|
|
@raise QMPConnectError: If wait is True but no events could be
|
|
|
|
retrieved or if some other error occurred.
|
2015-04-18 01:50:06 +02:00
|
|
|
"""
|
|
|
|
|
|
|
|
# Check for new events regardless and pull them into the cache:
|
2020-05-14 07:53:45 +02:00
|
|
|
self.__sock.setblocking(False)
|
2015-04-18 01:50:06 +02:00
|
|
|
try:
|
|
|
|
self.__json_read()
|
2019-12-27 14:40:57 +01:00
|
|
|
except OSError as err:
|
|
|
|
if err.errno == errno.EAGAIN:
|
2015-04-18 01:50:06 +02:00
|
|
|
# No data available
|
|
|
|
pass
|
2020-05-14 07:53:45 +02:00
|
|
|
self.__sock.setblocking(True)
|
2015-04-18 01:50:06 +02:00
|
|
|
|
|
|
|
# Wait for new events, if needed.
|
|
|
|
# if wait is 0.0, this means "no wait" and is also implicitly false.
|
|
|
|
if not self.__events and wait:
|
|
|
|
if isinstance(wait, float):
|
|
|
|
self.__sock.settimeout(wait)
|
|
|
|
try:
|
|
|
|
ret = self.__json_read(only_event=True)
|
|
|
|
except socket.timeout:
|
|
|
|
raise QMPTimeoutError("Timeout waiting for event")
|
|
|
|
except:
|
|
|
|
raise QMPConnectError("Error while reading from socket")
|
|
|
|
if ret is None:
|
|
|
|
raise QMPConnectError("Error while reading from socket")
|
|
|
|
self.__sock.settimeout(None)
|
|
|
|
|
2020-02-04 15:11:10 +01:00
|
|
|
def __enter__(self):
|
|
|
|
# Implement context manager enter function.
|
|
|
|
return self
|
|
|
|
|
2020-05-14 07:53:44 +02:00
|
|
|
def __exit__(self,
|
|
|
|
# pylint: disable=duplicate-code
|
|
|
|
# see https://github.com/PyCQA/pylint/issues/3619
|
|
|
|
exc_type: Optional[Type[BaseException]],
|
|
|
|
exc_val: Optional[BaseException],
|
|
|
|
exc_tb: Optional[TracebackType]) -> None:
|
2020-02-04 15:11:10 +01:00
|
|
|
# Implement context manager exit function.
|
|
|
|
self.close()
|
|
|
|
|
2012-09-14 14:44:20 +02:00
|
|
|
def connect(self, negotiate=True):
|
2010-10-27 21:43:34 +02:00
|
|
|
"""
|
|
|
|
Connect to the QMP Monitor and perform capabilities negotiation.
|
|
|
|
|
2019-12-27 14:40:58 +01:00
|
|
|
@return QMP greeting dict, or None if negotiate is false
|
2019-12-27 14:40:57 +01:00
|
|
|
@raise OSError on socket connection errors
|
2010-10-27 21:43:34 +02:00
|
|
|
@raise QMPConnectError if the greeting is not received
|
|
|
|
@raise QMPCapabilitiesError if fails to negotiate capabilities
|
|
|
|
"""
|
|
|
|
self.__sock.connect(self.__address)
|
2020-05-14 07:53:43 +02:00
|
|
|
self.__sockfile = self.__sock.makefile(mode='r')
|
2012-09-14 14:44:20 +02:00
|
|
|
if negotiate:
|
|
|
|
return self.__negotiate_capabilities()
|
2019-12-27 14:40:58 +01:00
|
|
|
return None
|
2011-05-25 20:48:01 +02:00
|
|
|
|
2020-02-04 15:11:09 +01:00
|
|
|
def accept(self, timeout=15.0):
|
2011-05-25 20:48:01 +02:00
|
|
|
"""
|
|
|
|
Await connection from QMP Monitor and perform capabilities negotiation.
|
|
|
|
|
2020-02-04 15:11:09 +01:00
|
|
|
@param timeout: timeout in seconds (nonnegative float number, or
|
|
|
|
None). The value passed will set the behavior of the
|
2020-05-29 00:21:29 +02:00
|
|
|
underneath QMP socket as described in [1].
|
|
|
|
Default value is set to 15.0.
|
2011-05-25 20:48:01 +02:00
|
|
|
@return QMP greeting dict
|
2019-12-27 14:40:57 +01:00
|
|
|
@raise OSError on socket connection errors
|
2011-05-25 20:48:01 +02:00
|
|
|
@raise QMPConnectError if the greeting is not received
|
|
|
|
@raise QMPCapabilitiesError if fails to negotiate capabilities
|
2020-02-04 15:11:09 +01:00
|
|
|
|
|
|
|
[1]
|
|
|
|
https://docs.python.org/3/library/socket.html#socket.socket.settimeout
|
2011-05-25 20:48:01 +02:00
|
|
|
"""
|
2020-02-04 15:11:09 +01:00
|
|
|
self.__sock.settimeout(timeout)
|
2011-05-25 20:48:01 +02:00
|
|
|
self.__sock, _ = self.__sock.accept()
|
2020-05-14 07:53:43 +02:00
|
|
|
self.__sockfile = self.__sock.makefile(mode='r')
|
2011-05-25 20:48:01 +02:00
|
|
|
return self.__negotiate_capabilities()
|
2009-11-27 01:59:09 +01:00
|
|
|
|
2020-07-10 07:22:08 +02:00
|
|
|
def cmd_obj(self, qmp_cmd: QMPMessage) -> QMPMessage:
|
2010-10-27 21:43:34 +02:00
|
|
|
"""
|
|
|
|
Send a QMP command to the QMP Monitor.
|
2009-11-27 01:59:09 +01:00
|
|
|
|
2010-10-27 21:43:34 +02:00
|
|
|
@param qmp_cmd: QMP command to be sent as a Python dict
|
2020-07-10 07:22:08 +02:00
|
|
|
@return QMP response as a Python dict
|
2010-10-27 21:43:34 +02:00
|
|
|
"""
|
2017-10-05 19:20:12 +02:00
|
|
|
self.logger.debug(">>> %s", qmp_cmd)
|
2020-07-10 07:22:08 +02:00
|
|
|
self.__sock.sendall(json.dumps(qmp_cmd).encode('utf-8'))
|
2016-07-20 15:23:09 +02:00
|
|
|
resp = self.__json_read()
|
2020-07-10 07:22:08 +02:00
|
|
|
if resp is None:
|
|
|
|
raise QMPConnectError("Unexpected empty reply from server")
|
2017-10-05 19:20:12 +02:00
|
|
|
self.logger.debug("<<< %s", resp)
|
2016-07-20 15:23:09 +02:00
|
|
|
return resp
|
2009-11-27 01:59:09 +01:00
|
|
|
|
2017-08-18 16:26:12 +02:00
|
|
|
def cmd(self, name, args=None, cmd_id=None):
|
2010-10-27 21:43:34 +02:00
|
|
|
"""
|
|
|
|
Build a QMP command and send it to the QMP Monitor.
|
2009-11-27 01:59:09 +01:00
|
|
|
|
2010-10-27 21:43:34 +02:00
|
|
|
@param name: command name (string)
|
|
|
|
@param args: command arguments (dict)
|
2017-08-18 16:26:12 +02:00
|
|
|
@param cmd_id: command id (dict, list, string or int)
|
2010-10-27 21:43:34 +02:00
|
|
|
"""
|
2017-08-18 16:26:09 +02:00
|
|
|
qmp_cmd = {'execute': name}
|
2010-10-27 21:43:34 +02:00
|
|
|
if args:
|
|
|
|
qmp_cmd['arguments'] = args
|
2017-08-18 16:26:12 +02:00
|
|
|
if cmd_id:
|
|
|
|
qmp_cmd['id'] = cmd_id
|
2010-10-27 21:43:34 +02:00
|
|
|
return self.cmd_obj(qmp_cmd)
|
|
|
|
|
2012-02-20 23:28:29 +01:00
|
|
|
def command(self, cmd, **kwds):
|
2017-08-18 16:26:09 +02:00
|
|
|
"""
|
|
|
|
Build and send a QMP command to the monitor, report errors if any
|
|
|
|
"""
|
2012-02-20 23:28:29 +01:00
|
|
|
ret = self.cmd(cmd, kwds)
|
2020-07-10 07:22:07 +02:00
|
|
|
if 'error' in ret:
|
|
|
|
raise QMPResponseError(ret)
|
2020-07-10 07:22:10 +02:00
|
|
|
if 'return' not in ret:
|
|
|
|
raise QMPProtocolError(
|
|
|
|
"'return' key not found in QMP response '{}'".format(str(ret))
|
|
|
|
)
|
2020-07-10 07:22:09 +02:00
|
|
|
return cast(QMPReturnValue, ret['return'])
|
2012-02-20 23:28:29 +01:00
|
|
|
|
2012-10-18 16:49:29 +02:00
|
|
|
def pull_event(self, wait=False):
|
|
|
|
"""
|
2017-08-18 16:26:09 +02:00
|
|
|
Pulls a single event.
|
2012-10-18 16:49:29 +02:00
|
|
|
|
2015-04-18 01:50:06 +02:00
|
|
|
@param wait (bool): block until an event is available.
|
|
|
|
@param wait (float): If wait is a float, treat it as a timeout value.
|
|
|
|
|
|
|
|
@raise QMPTimeoutError: If a timeout float is provided and the timeout
|
|
|
|
period elapses.
|
2017-08-18 16:26:09 +02:00
|
|
|
@raise QMPConnectError: If wait is True but no events could be
|
|
|
|
retrieved or if some other error occurred.
|
2015-04-18 01:50:06 +02:00
|
|
|
|
|
|
|
@return The first available QMP event, or None.
|
2012-10-18 16:49:29 +02:00
|
|
|
"""
|
2015-04-18 01:50:06 +02:00
|
|
|
self.__get_events(wait)
|
|
|
|
|
|
|
|
if self.__events:
|
|
|
|
return self.__events.pop(0)
|
|
|
|
return None
|
2012-10-18 16:49:29 +02:00
|
|
|
|
2011-05-25 20:48:00 +02:00
|
|
|
def get_events(self, wait=False):
|
2010-10-27 21:43:34 +02:00
|
|
|
"""
|
|
|
|
Get a list of available QMP events.
|
2011-05-25 20:48:00 +02:00
|
|
|
|
2015-04-18 01:50:06 +02:00
|
|
|
@param wait (bool): block until an event is available.
|
|
|
|
@param wait (float): If wait is a float, treat it as a timeout value.
|
2014-02-24 06:45:01 +01:00
|
|
|
|
2015-04-18 01:50:06 +02:00
|
|
|
@raise QMPTimeoutError: If a timeout float is provided and the timeout
|
|
|
|
period elapses.
|
2017-08-18 16:26:09 +02:00
|
|
|
@raise QMPConnectError: If wait is True but no events could be
|
|
|
|
retrieved or if some other error occurred.
|
2015-04-18 01:50:06 +02:00
|
|
|
|
|
|
|
@return The list of available QMP events.
|
|
|
|
"""
|
|
|
|
self.__get_events(wait)
|
2010-10-27 21:43:34 +02:00
|
|
|
return self.__events
|
|
|
|
|
|
|
|
def clear_events(self):
|
|
|
|
"""
|
|
|
|
Clear current list of pending events.
|
|
|
|
"""
|
|
|
|
self.__events = []
|
|
|
|
|
|
|
|
def close(self):
|
2019-12-27 14:40:58 +01:00
|
|
|
"""
|
|
|
|
Close the socket and socket file.
|
|
|
|
"""
|
2020-02-04 15:11:10 +01:00
|
|
|
if self.__sock:
|
|
|
|
self.__sock.close()
|
|
|
|
if self.__sockfile:
|
|
|
|
self.__sockfile.close()
|
2012-09-14 14:44:21 +02:00
|
|
|
|
|
|
|
def settimeout(self, timeout):
|
2019-12-27 14:40:58 +01:00
|
|
|
"""
|
|
|
|
Set the socket timeout.
|
|
|
|
|
|
|
|
@param timeout (float): timeout in seconds, or None.
|
|
|
|
@note This is a wrap around socket.settimeout
|
|
|
|
"""
|
2012-09-14 14:44:21 +02:00
|
|
|
self.__sock.settimeout(timeout)
|
2013-09-06 05:24:33 +02:00
|
|
|
|
|
|
|
def get_sock_fd(self):
|
2019-12-27 14:40:58 +01:00
|
|
|
"""
|
|
|
|
Get the socket file descriptor.
|
|
|
|
|
|
|
|
@return The file descriptor number.
|
|
|
|
"""
|
2013-09-06 05:24:33 +02:00
|
|
|
return self.__sock.fileno()
|
|
|
|
|
|
|
|
def is_scm_available(self):
|
2019-12-27 14:40:58 +01:00
|
|
|
"""
|
|
|
|
Check if the socket allows for SCM_RIGHTS.
|
|
|
|
|
|
|
|
@return True if SCM_RIGHTS is available, otherwise False.
|
|
|
|
"""
|
2013-09-06 05:24:33 +02:00
|
|
|
return self.__sock.family == socket.AF_UNIX
|