2019-06-27 23:28:15 +02:00
|
|
|
"""
|
|
|
|
QEMU machine module:
|
|
|
|
|
|
|
|
The machine module primarily provides the QEMUMachine class,
|
|
|
|
which provides facilities for managing the lifetime of a QEMU VM.
|
|
|
|
"""
|
|
|
|
|
2019-06-27 23:28:14 +02:00
|
|
|
# Copyright (C) 2015-2016 Red Hat Inc.
|
|
|
|
# Copyright (C) 2012 IBM Corp.
|
|
|
|
#
|
|
|
|
# Authors:
|
|
|
|
# Fam Zheng <famz@redhat.com>
|
|
|
|
#
|
|
|
|
# This work is licensed under the terms of the GNU GPL, version 2. See
|
|
|
|
# the COPYING file in the top-level directory.
|
|
|
|
#
|
|
|
|
# Based on qmp.py.
|
|
|
|
#
|
|
|
|
|
|
|
|
import errno
|
2020-10-07 01:58:06 +02:00
|
|
|
from itertools import chain
|
2019-06-27 23:28:14 +02:00
|
|
|
import logging
|
|
|
|
import os
|
|
|
|
import shutil
|
2020-07-10 07:06:48 +02:00
|
|
|
import signal
|
2020-10-07 01:58:08 +02:00
|
|
|
import socket
|
2020-10-07 01:57:58 +02:00
|
|
|
import subprocess
|
2019-06-27 23:28:14 +02:00
|
|
|
import tempfile
|
2020-05-14 07:53:44 +02:00
|
|
|
from types import TracebackType
|
2020-10-07 01:58:03 +02:00
|
|
|
from typing import (
|
|
|
|
Any,
|
2020-10-07 01:58:08 +02:00
|
|
|
BinaryIO,
|
2020-10-07 01:58:03 +02:00
|
|
|
Dict,
|
|
|
|
List,
|
|
|
|
Optional,
|
2020-10-07 01:58:06 +02:00
|
|
|
Sequence,
|
|
|
|
Tuple,
|
2020-10-07 01:58:03 +02:00
|
|
|
Type,
|
|
|
|
)
|
2020-10-07 01:57:58 +02:00
|
|
|
|
2021-05-27 23:16:59 +02:00
|
|
|
from qemu.qmp import ( # pylint: disable=import-error
|
2021-05-27 23:16:53 +02:00
|
|
|
QEMUMonitorProtocol,
|
|
|
|
QMPMessage,
|
|
|
|
QMPReturnValue,
|
|
|
|
SocketAddrT,
|
|
|
|
)
|
|
|
|
|
|
|
|
from . import console_socket
|
2019-06-27 23:28:14 +02:00
|
|
|
|
|
|
|
|
|
|
|
LOG = logging.getLogger(__name__)
|
|
|
|
|
2020-05-29 00:21:29 +02:00
|
|
|
|
2019-06-27 23:28:14 +02:00
|
|
|
class QEMUMachineError(Exception):
|
|
|
|
"""
|
|
|
|
Exception called when an error in QEMUMachine happens.
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
class QEMUMachineAddDeviceError(QEMUMachineError):
|
|
|
|
"""
|
|
|
|
Exception raised when a request to add a device can not be fulfilled
|
|
|
|
|
|
|
|
The failures are caused by limitations, lack of information or conflicting
|
|
|
|
requests on the QEMUMachine methods. This exception does not represent
|
|
|
|
failures reported by the QEMU binary itself.
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
2020-07-10 07:06:47 +02:00
|
|
|
class AbnormalShutdown(QEMUMachineError):
|
|
|
|
"""
|
|
|
|
Exception raised when a graceful shutdown was requested, but not performed.
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
2020-05-29 00:21:28 +02:00
|
|
|
class QEMUMachine:
|
2019-06-27 23:28:14 +02:00
|
|
|
"""
|
2020-10-07 01:58:08 +02:00
|
|
|
A QEMU VM.
|
2019-06-27 23:28:14 +02:00
|
|
|
|
2020-05-29 00:21:29 +02:00
|
|
|
Use this object as a context manager to ensure
|
|
|
|
the QEMU process terminates::
|
2019-06-27 23:28:14 +02:00
|
|
|
|
|
|
|
with VM(binary) as vm:
|
|
|
|
...
|
|
|
|
# vm is guaranteed to be shut down here
|
|
|
|
"""
|
2021-06-29 23:43:11 +02:00
|
|
|
# pylint: disable=too-many-instance-attributes, too-many-public-methods
|
2019-06-27 23:28:14 +02:00
|
|
|
|
2020-10-07 01:58:06 +02:00
|
|
|
def __init__(self,
|
|
|
|
binary: str,
|
|
|
|
args: Sequence[str] = (),
|
|
|
|
wrapper: Sequence[str] = (),
|
|
|
|
name: Optional[str] = None,
|
2021-02-11 23:01:42 +01:00
|
|
|
base_temp_dir: str = "/var/tmp",
|
2020-10-07 01:57:59 +02:00
|
|
|
monitor_address: Optional[SocketAddrT] = None,
|
2020-10-07 01:58:08 +02:00
|
|
|
socket_scm_helper: Optional[str] = None,
|
|
|
|
sock_dir: Optional[str] = None,
|
|
|
|
drain_console: bool = False,
|
|
|
|
console_log: Optional[str] = None):
|
2019-06-27 23:28:14 +02:00
|
|
|
'''
|
|
|
|
Initialize a QEMUMachine
|
|
|
|
|
|
|
|
@param binary: path to the qemu binary
|
|
|
|
@param args: list of extra arguments
|
|
|
|
@param wrapper: list of arguments used as prefix to qemu binary
|
|
|
|
@param name: prefix for socket and log file names (default: qemu-PID)
|
2021-05-27 23:16:51 +02:00
|
|
|
@param base_temp_dir: default location where temp files are created
|
2019-06-27 23:28:14 +02:00
|
|
|
@param monitor_address: address for QMP monitor
|
|
|
|
@param socket_scm_helper: helper program, required for send_fd_scm()
|
2021-02-11 23:01:42 +01:00
|
|
|
@param sock_dir: where to create socket (defaults to base_temp_dir)
|
2020-07-01 15:56:24 +02:00
|
|
|
@param drain_console: (optional) True to drain console socket to buffer
|
2020-10-07 01:58:00 +02:00
|
|
|
@param console_log: (optional) path to console log file
|
2019-06-27 23:28:14 +02:00
|
|
|
@note: Qemu process is not started until launch() is used.
|
|
|
|
'''
|
2021-06-29 23:43:11 +02:00
|
|
|
# pylint: disable=too-many-arguments
|
|
|
|
|
2020-10-07 01:58:00 +02:00
|
|
|
# Direct user configuration
|
|
|
|
|
|
|
|
self._binary = binary
|
|
|
|
self._args = list(args)
|
|
|
|
self._wrapper = wrapper
|
|
|
|
|
|
|
|
self._name = name or "qemu-%d" % os.getpid()
|
2021-02-11 23:01:42 +01:00
|
|
|
self._base_temp_dir = base_temp_dir
|
|
|
|
self._sock_dir = sock_dir or self._base_temp_dir
|
2020-10-07 01:58:00 +02:00
|
|
|
self._socket_scm_helper = socket_scm_helper
|
|
|
|
|
2020-10-07 01:57:59 +02:00
|
|
|
if monitor_address is not None:
|
|
|
|
self._monitor_address = monitor_address
|
|
|
|
self._remove_monitor_sockfile = False
|
|
|
|
else:
|
|
|
|
self._monitor_address = os.path.join(
|
2020-10-07 01:58:00 +02:00
|
|
|
self._sock_dir, f"{self._name}-monitor.sock"
|
2020-10-07 01:57:59 +02:00
|
|
|
)
|
|
|
|
self._remove_monitor_sockfile = True
|
2020-10-07 01:58:00 +02:00
|
|
|
|
|
|
|
self._console_log_path = console_log
|
|
|
|
if self._console_log_path:
|
|
|
|
# In order to log the console, buffering needs to be enabled.
|
|
|
|
self._drain_console = True
|
|
|
|
else:
|
|
|
|
self._drain_console = drain_console
|
|
|
|
|
|
|
|
# Runstate
|
2020-10-07 01:58:08 +02:00
|
|
|
self._qemu_log_path: Optional[str] = None
|
|
|
|
self._qemu_log_file: Optional[BinaryIO] = None
|
2020-10-07 01:58:05 +02:00
|
|
|
self._popen: Optional['subprocess.Popen[bytes]'] = None
|
2020-10-07 01:58:08 +02:00
|
|
|
self._events: List[QMPMessage] = []
|
|
|
|
self._iolog: Optional[str] = None
|
2019-12-11 19:55:35 +01:00
|
|
|
self._qmp_set = True # Enable QMP monitor by default.
|
2021-05-27 23:16:53 +02:00
|
|
|
self._qmp_connection: Optional[QEMUMonitorProtocol] = None
|
2020-10-07 01:58:06 +02:00
|
|
|
self._qemu_full_args: Tuple[str, ...] = ()
|
2020-10-07 01:58:08 +02:00
|
|
|
self._temp_dir: Optional[str] = None
|
2019-06-27 23:28:14 +02:00
|
|
|
self._launched = False
|
2020-10-07 01:58:08 +02:00
|
|
|
self._machine: Optional[str] = None
|
2020-01-21 00:51:56 +01:00
|
|
|
self._console_index = 0
|
2019-06-27 23:28:14 +02:00
|
|
|
self._console_set = False
|
2020-10-07 01:58:08 +02:00
|
|
|
self._console_device_type: Optional[str] = None
|
2020-10-07 01:58:01 +02:00
|
|
|
self._console_address = os.path.join(
|
|
|
|
self._sock_dir, f"{self._name}-console.sock"
|
|
|
|
)
|
2020-10-07 01:58:08 +02:00
|
|
|
self._console_socket: Optional[socket.socket] = None
|
|
|
|
self._remove_files: List[str] = []
|
2020-07-10 07:06:48 +02:00
|
|
|
self._user_killed = False
|
2019-06-27 23:28:14 +02:00
|
|
|
|
2020-10-07 01:58:08 +02:00
|
|
|
def __enter__(self) -> 'QEMUMachine':
|
2019-06-27 23:28:14 +02:00
|
|
|
return self
|
|
|
|
|
2020-05-14 07:53:44 +02:00
|
|
|
def __exit__(self,
|
|
|
|
exc_type: Optional[Type[BaseException]],
|
|
|
|
exc_val: Optional[BaseException],
|
|
|
|
exc_tb: Optional[TracebackType]) -> None:
|
2019-06-27 23:28:14 +02:00
|
|
|
self.shutdown()
|
|
|
|
|
2020-10-07 01:58:08 +02:00
|
|
|
def add_monitor_null(self) -> None:
|
2019-06-27 23:28:15 +02:00
|
|
|
"""
|
|
|
|
This can be used to add an unused monitor instance.
|
|
|
|
"""
|
2019-06-27 23:28:14 +02:00
|
|
|
self._args.append('-monitor')
|
|
|
|
self._args.append('null')
|
|
|
|
|
2020-10-07 01:58:08 +02:00
|
|
|
def add_fd(self, fd: int, fdset: int,
|
|
|
|
opaque: str, opts: str = '') -> 'QEMUMachine':
|
2019-06-27 23:28:14 +02:00
|
|
|
"""
|
|
|
|
Pass a file descriptor to the VM
|
|
|
|
"""
|
|
|
|
options = ['fd=%d' % fd,
|
|
|
|
'set=%d' % fdset,
|
|
|
|
'opaque=%s' % opaque]
|
|
|
|
if opts:
|
|
|
|
options.append(opts)
|
|
|
|
|
|
|
|
# This did not exist before 3.4, but since then it is
|
|
|
|
# mandatory for our purpose
|
|
|
|
if hasattr(os, 'set_inheritable'):
|
|
|
|
os.set_inheritable(fd, True)
|
|
|
|
|
|
|
|
self._args.append('-add-fd')
|
|
|
|
self._args.append(','.join(options))
|
|
|
|
return self
|
|
|
|
|
2020-10-07 01:58:08 +02:00
|
|
|
def send_fd_scm(self, fd: Optional[int] = None,
|
|
|
|
file_path: Optional[str] = None) -> int:
|
2019-06-27 23:28:15 +02:00
|
|
|
"""
|
|
|
|
Send an fd or file_path to socket_scm_helper.
|
|
|
|
|
|
|
|
Exactly one of fd and file_path must be given.
|
|
|
|
If it is file_path, the helper will open that file and pass its own fd.
|
|
|
|
"""
|
2019-06-27 23:28:14 +02:00
|
|
|
# In iotest.py, the qmp should always use unix socket.
|
|
|
|
assert self._qmp.is_scm_available()
|
|
|
|
if self._socket_scm_helper is None:
|
|
|
|
raise QEMUMachineError("No path to socket_scm_helper set")
|
|
|
|
if not os.path.exists(self._socket_scm_helper):
|
|
|
|
raise QEMUMachineError("%s does not exist" %
|
|
|
|
self._socket_scm_helper)
|
|
|
|
|
|
|
|
# This did not exist before 3.4, but since then it is
|
|
|
|
# mandatory for our purpose
|
|
|
|
if hasattr(os, 'set_inheritable'):
|
|
|
|
os.set_inheritable(self._qmp.get_sock_fd(), True)
|
|
|
|
if fd is not None:
|
|
|
|
os.set_inheritable(fd, True)
|
|
|
|
|
|
|
|
fd_param = ["%s" % self._socket_scm_helper,
|
|
|
|
"%d" % self._qmp.get_sock_fd()]
|
|
|
|
|
|
|
|
if file_path is not None:
|
|
|
|
assert fd is None
|
|
|
|
fd_param.append(file_path)
|
|
|
|
else:
|
|
|
|
assert fd is not None
|
|
|
|
fd_param.append(str(fd))
|
|
|
|
|
2021-05-27 23:16:47 +02:00
|
|
|
proc = subprocess.run(
|
|
|
|
fd_param,
|
|
|
|
stdin=subprocess.DEVNULL,
|
|
|
|
stdout=subprocess.PIPE,
|
|
|
|
stderr=subprocess.STDOUT,
|
|
|
|
check=False,
|
|
|
|
close_fds=False,
|
2020-05-29 00:21:29 +02:00
|
|
|
)
|
2021-05-27 23:16:47 +02:00
|
|
|
if proc.stdout:
|
|
|
|
LOG.debug(proc.stdout)
|
2019-06-27 23:28:14 +02:00
|
|
|
|
|
|
|
return proc.returncode
|
|
|
|
|
|
|
|
@staticmethod
|
2020-10-07 01:58:08 +02:00
|
|
|
def _remove_if_exists(path: str) -> None:
|
2019-06-27 23:28:14 +02:00
|
|
|
"""
|
|
|
|
Remove file object at path if it exists
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
os.remove(path)
|
|
|
|
except OSError as exception:
|
|
|
|
if exception.errno == errno.ENOENT:
|
|
|
|
return
|
|
|
|
raise
|
|
|
|
|
2020-10-07 01:58:08 +02:00
|
|
|
def is_running(self) -> bool:
|
2019-06-27 23:28:15 +02:00
|
|
|
"""Returns true if the VM is running."""
|
2019-06-27 23:28:14 +02:00
|
|
|
return self._popen is not None and self._popen.poll() is None
|
|
|
|
|
2020-10-07 01:58:05 +02:00
|
|
|
@property
|
|
|
|
def _subp(self) -> 'subprocess.Popen[bytes]':
|
|
|
|
if self._popen is None:
|
|
|
|
raise QEMUMachineError('Subprocess pipe not present')
|
|
|
|
return self._popen
|
|
|
|
|
2020-10-07 01:58:08 +02:00
|
|
|
def exitcode(self) -> Optional[int]:
|
2019-06-27 23:28:15 +02:00
|
|
|
"""Returns the exit code if possible, or None."""
|
2019-06-27 23:28:14 +02:00
|
|
|
if self._popen is None:
|
|
|
|
return None
|
|
|
|
return self._popen.poll()
|
|
|
|
|
2020-10-07 01:58:08 +02:00
|
|
|
def get_pid(self) -> Optional[int]:
|
2019-06-27 23:28:15 +02:00
|
|
|
"""Returns the PID of the running process, or None."""
|
2019-06-27 23:28:14 +02:00
|
|
|
if not self.is_running():
|
|
|
|
return None
|
2020-10-07 01:58:05 +02:00
|
|
|
return self._subp.pid
|
2019-06-27 23:28:14 +02:00
|
|
|
|
2020-10-07 01:58:08 +02:00
|
|
|
def _load_io_log(self) -> None:
|
2019-06-27 23:28:14 +02:00
|
|
|
if self._qemu_log_path is not None:
|
|
|
|
with open(self._qemu_log_path, "r") as iolog:
|
|
|
|
self._iolog = iolog.read()
|
|
|
|
|
2020-10-07 01:58:01 +02:00
|
|
|
@property
|
|
|
|
def _base_args(self) -> List[str]:
|
2019-12-11 19:55:35 +01:00
|
|
|
args = ['-display', 'none', '-vga', 'none']
|
2020-10-07 01:57:59 +02:00
|
|
|
|
2019-12-11 19:55:35 +01:00
|
|
|
if self._qmp_set:
|
|
|
|
if isinstance(self._monitor_address, tuple):
|
2020-10-07 01:57:59 +02:00
|
|
|
moncdev = "socket,id=mon,host={},port={}".format(
|
|
|
|
*self._monitor_address
|
|
|
|
)
|
2019-12-11 19:55:35 +01:00
|
|
|
else:
|
2020-10-07 01:57:59 +02:00
|
|
|
moncdev = f"socket,id=mon,path={self._monitor_address}"
|
2019-12-11 19:55:35 +01:00
|
|
|
args.extend(['-chardev', moncdev, '-mon',
|
|
|
|
'chardev=mon,mode=control'])
|
2020-10-07 01:57:59 +02:00
|
|
|
|
2019-06-27 23:28:14 +02:00
|
|
|
if self._machine is not None:
|
|
|
|
args.extend(['-machine', self._machine])
|
2020-05-29 00:21:28 +02:00
|
|
|
for _ in range(self._console_index):
|
2020-01-21 00:51:56 +01:00
|
|
|
args.extend(['-serial', 'null'])
|
2019-06-27 23:28:14 +02:00
|
|
|
if self._console_set:
|
2020-11-13 09:10:52 +01:00
|
|
|
chardev = ('socket,id=console,path=%s,server=on,wait=off' %
|
2019-06-27 23:28:14 +02:00
|
|
|
self._console_address)
|
|
|
|
args.extend(['-chardev', chardev])
|
|
|
|
if self._console_device_type is None:
|
|
|
|
args.extend(['-serial', 'chardev:console'])
|
|
|
|
else:
|
|
|
|
device = '%s,chardev=console' % self._console_device_type
|
|
|
|
args.extend(['-device', device])
|
|
|
|
return args
|
|
|
|
|
2020-10-07 01:58:08 +02:00
|
|
|
def _pre_launch(self) -> None:
|
2021-02-11 23:01:42 +01:00
|
|
|
self._qemu_log_path = os.path.join(self.temp_dir, self._name + ".log")
|
2019-06-27 23:28:14 +02:00
|
|
|
|
2020-10-07 01:58:01 +02:00
|
|
|
if self._console_set:
|
|
|
|
self._remove_files.append(self._console_address)
|
|
|
|
|
2019-12-11 19:55:35 +01:00
|
|
|
if self._qmp_set:
|
2020-10-07 01:57:59 +02:00
|
|
|
if self._remove_monitor_sockfile:
|
|
|
|
assert isinstance(self._monitor_address, str)
|
|
|
|
self._remove_files.append(self._monitor_address)
|
2021-05-27 23:16:53 +02:00
|
|
|
self._qmp_connection = QEMUMonitorProtocol(
|
2020-10-07 01:57:59 +02:00
|
|
|
self._monitor_address,
|
|
|
|
server=True,
|
|
|
|
nickname=self._name
|
|
|
|
)
|
2019-06-27 23:28:14 +02:00
|
|
|
|
2021-05-27 23:16:49 +02:00
|
|
|
# NOTE: Make sure any opened resources are *definitely* freed in
|
|
|
|
# _post_shutdown()!
|
|
|
|
# pylint: disable=consider-using-with
|
|
|
|
self._qemu_log_file = open(self._qemu_log_path, 'wb')
|
|
|
|
|
2020-10-07 01:58:08 +02:00
|
|
|
def _post_launch(self) -> None:
|
2020-10-07 01:58:04 +02:00
|
|
|
if self._qmp_connection:
|
2019-12-11 19:55:35 +01:00
|
|
|
self._qmp.accept()
|
2019-06-27 23:28:14 +02:00
|
|
|
|
2020-10-07 01:58:08 +02:00
|
|
|
def _post_shutdown(self) -> None:
|
2020-07-10 07:06:42 +02:00
|
|
|
"""
|
|
|
|
Called to cleanup the VM instance after the process has exited.
|
|
|
|
May also be called after a failed launch.
|
|
|
|
"""
|
|
|
|
# Comprehensive reset for the failed launch case:
|
|
|
|
self._early_cleanup()
|
|
|
|
|
2020-10-07 01:58:04 +02:00
|
|
|
if self._qmp_connection:
|
2020-07-10 07:06:39 +02:00
|
|
|
self._qmp.close()
|
2020-10-07 01:58:04 +02:00
|
|
|
self._qmp_connection = None
|
2020-07-10 07:06:39 +02:00
|
|
|
|
2019-06-27 23:28:14 +02:00
|
|
|
if self._qemu_log_file is not None:
|
|
|
|
self._qemu_log_file.close()
|
|
|
|
self._qemu_log_file = None
|
|
|
|
|
2021-02-11 23:01:41 +01:00
|
|
|
self._load_io_log()
|
|
|
|
|
2019-06-27 23:28:14 +02:00
|
|
|
self._qemu_log_path = None
|
|
|
|
|
|
|
|
if self._temp_dir is not None:
|
|
|
|
shutil.rmtree(self._temp_dir)
|
|
|
|
self._temp_dir = None
|
|
|
|
|
2019-10-17 15:31:34 +02:00
|
|
|
while len(self._remove_files) > 0:
|
|
|
|
self._remove_if_exists(self._remove_files.pop())
|
|
|
|
|
2020-07-10 07:06:38 +02:00
|
|
|
exitcode = self.exitcode()
|
2020-07-10 07:06:48 +02:00
|
|
|
if (exitcode is not None and exitcode < 0
|
|
|
|
and not (self._user_killed and exitcode == -signal.SIGKILL)):
|
2020-07-10 07:06:38 +02:00
|
|
|
msg = 'qemu received signal %i; command: "%s"'
|
|
|
|
if self._qemu_full_args:
|
|
|
|
command = ' '.join(self._qemu_full_args)
|
|
|
|
else:
|
|
|
|
command = ''
|
|
|
|
LOG.warning(msg, -int(exitcode), command)
|
|
|
|
|
2020-07-10 07:06:48 +02:00
|
|
|
self._user_killed = False
|
2020-07-10 07:06:38 +02:00
|
|
|
self._launched = False
|
|
|
|
|
2020-10-07 01:58:08 +02:00
|
|
|
def launch(self) -> None:
|
2019-06-27 23:28:14 +02:00
|
|
|
"""
|
|
|
|
Launch the VM and make sure we cleanup and expose the
|
|
|
|
command line/output in case of exception
|
|
|
|
"""
|
|
|
|
|
|
|
|
if self._launched:
|
|
|
|
raise QEMUMachineError('VM already launched')
|
|
|
|
|
|
|
|
self._iolog = None
|
2020-10-07 01:58:06 +02:00
|
|
|
self._qemu_full_args = ()
|
2019-06-27 23:28:14 +02:00
|
|
|
try:
|
|
|
|
self._launch()
|
|
|
|
self._launched = True
|
|
|
|
except:
|
2020-07-10 07:06:42 +02:00
|
|
|
self._post_shutdown()
|
2019-06-27 23:28:14 +02:00
|
|
|
|
|
|
|
LOG.debug('Error launching VM')
|
|
|
|
if self._qemu_full_args:
|
|
|
|
LOG.debug('Command: %r', ' '.join(self._qemu_full_args))
|
|
|
|
if self._iolog:
|
|
|
|
LOG.debug('Output: %r', self._iolog)
|
|
|
|
raise
|
|
|
|
|
2020-10-07 01:58:08 +02:00
|
|
|
def _launch(self) -> None:
|
2019-06-27 23:28:14 +02:00
|
|
|
"""
|
|
|
|
Launch the VM and establish a QMP connection
|
|
|
|
"""
|
|
|
|
self._pre_launch()
|
2020-10-07 01:58:06 +02:00
|
|
|
self._qemu_full_args = tuple(
|
|
|
|
chain(self._wrapper,
|
|
|
|
[self._binary],
|
|
|
|
self._base_args,
|
|
|
|
self._args)
|
|
|
|
)
|
2019-06-27 23:28:14 +02:00
|
|
|
LOG.debug('VM launch command: %r', ' '.join(self._qemu_full_args))
|
2021-05-27 23:16:50 +02:00
|
|
|
|
|
|
|
# Cleaning up of this subprocess is guaranteed by _do_shutdown.
|
|
|
|
# pylint: disable=consider-using-with
|
2019-06-27 23:28:14 +02:00
|
|
|
self._popen = subprocess.Popen(self._qemu_full_args,
|
2021-05-27 23:16:46 +02:00
|
|
|
stdin=subprocess.DEVNULL,
|
2019-06-27 23:28:14 +02:00
|
|
|
stdout=self._qemu_log_file,
|
|
|
|
stderr=subprocess.STDOUT,
|
|
|
|
shell=False,
|
|
|
|
close_fds=False)
|
|
|
|
self._post_launch()
|
|
|
|
|
2020-07-10 07:06:40 +02:00
|
|
|
def _early_cleanup(self) -> None:
|
|
|
|
"""
|
|
|
|
Perform any cleanup that needs to happen before the VM exits.
|
2020-07-10 07:06:42 +02:00
|
|
|
|
2020-07-10 07:06:47 +02:00
|
|
|
May be invoked by both soft and hard shutdown in failover scenarios.
|
2020-07-10 07:06:42 +02:00
|
|
|
Called additionally by _post_shutdown for comprehensive cleanup.
|
2020-07-10 07:06:40 +02:00
|
|
|
"""
|
|
|
|
# If we keep the console socket open, we may deadlock waiting
|
|
|
|
# for QEMU to exit, while QEMU is waiting for the socket to
|
|
|
|
# become writeable.
|
|
|
|
if self._console_socket is not None:
|
|
|
|
self._console_socket.close()
|
|
|
|
self._console_socket = None
|
|
|
|
|
2020-07-10 07:06:47 +02:00
|
|
|
def _hard_shutdown(self) -> None:
|
|
|
|
"""
|
|
|
|
Perform early cleanup, kill the VM, and wait for it to terminate.
|
|
|
|
|
|
|
|
:raise subprocess.Timeout: When timeout is exceeds 60 seconds
|
|
|
|
waiting for the QEMU process to terminate.
|
|
|
|
"""
|
|
|
|
self._early_cleanup()
|
2020-10-07 01:58:05 +02:00
|
|
|
self._subp.kill()
|
|
|
|
self._subp.wait(timeout=60)
|
2020-07-10 07:06:47 +02:00
|
|
|
|
2020-07-20 18:02:52 +02:00
|
|
|
def _soft_shutdown(self, timeout: Optional[int],
|
|
|
|
has_quit: bool = False) -> None:
|
2020-07-10 07:06:47 +02:00
|
|
|
"""
|
|
|
|
Perform early cleanup, attempt to gracefully shut down the VM, and wait
|
|
|
|
for it to terminate.
|
|
|
|
|
2020-07-20 18:02:52 +02:00
|
|
|
:param timeout: Timeout in seconds for graceful shutdown.
|
|
|
|
A value of None is an infinite wait.
|
2020-07-10 07:06:47 +02:00
|
|
|
:param has_quit: When True, don't attempt to issue 'quit' QMP command
|
|
|
|
|
|
|
|
:raise ConnectionReset: On QMP communication errors
|
|
|
|
:raise subprocess.TimeoutExpired: When timeout is exceeded waiting for
|
|
|
|
the QEMU process to terminate.
|
|
|
|
"""
|
|
|
|
self._early_cleanup()
|
|
|
|
|
2020-10-07 01:58:04 +02:00
|
|
|
if self._qmp_connection:
|
2020-07-10 07:06:47 +02:00
|
|
|
if not has_quit:
|
|
|
|
# Might raise ConnectionReset
|
|
|
|
self._qmp.cmd('quit')
|
|
|
|
|
|
|
|
# May raise subprocess.TimeoutExpired
|
2020-10-07 01:58:05 +02:00
|
|
|
self._subp.wait(timeout=timeout)
|
2020-07-10 07:06:47 +02:00
|
|
|
|
2020-07-20 18:02:52 +02:00
|
|
|
def _do_shutdown(self, timeout: Optional[int],
|
|
|
|
has_quit: bool = False) -> None:
|
2020-07-10 07:06:47 +02:00
|
|
|
"""
|
|
|
|
Attempt to shutdown the VM gracefully; fallback to a hard shutdown.
|
|
|
|
|
2020-07-20 18:02:52 +02:00
|
|
|
:param timeout: Timeout in seconds for graceful shutdown.
|
|
|
|
A value of None is an infinite wait.
|
2020-07-10 07:06:47 +02:00
|
|
|
:param has_quit: When True, don't attempt to issue 'quit' QMP command
|
|
|
|
|
|
|
|
:raise AbnormalShutdown: When the VM could not be shut down gracefully.
|
|
|
|
The inner exception will likely be ConnectionReset or
|
|
|
|
subprocess.TimeoutExpired. In rare cases, non-graceful termination
|
|
|
|
may result in its own exceptions, likely subprocess.TimeoutExpired.
|
|
|
|
"""
|
|
|
|
try:
|
2020-07-20 18:02:52 +02:00
|
|
|
self._soft_shutdown(timeout, has_quit)
|
2020-07-10 07:06:47 +02:00
|
|
|
except Exception as exc:
|
|
|
|
self._hard_shutdown()
|
|
|
|
raise AbnormalShutdown("Could not perform graceful shutdown") \
|
|
|
|
from exc
|
|
|
|
|
2020-07-10 07:06:43 +02:00
|
|
|
def shutdown(self, has_quit: bool = False,
|
|
|
|
hard: bool = False,
|
2020-07-20 18:02:52 +02:00
|
|
|
timeout: Optional[int] = 30) -> None:
|
2019-06-27 23:28:14 +02:00
|
|
|
"""
|
2020-07-10 07:06:47 +02:00
|
|
|
Terminate the VM (gracefully if possible) and perform cleanup.
|
|
|
|
Cleanup will always be performed.
|
|
|
|
|
|
|
|
If the VM has not yet been launched, or shutdown(), wait(), or kill()
|
|
|
|
have already been called, this method does nothing.
|
|
|
|
|
|
|
|
:param has_quit: When true, do not attempt to issue 'quit' QMP command.
|
|
|
|
:param hard: When true, do not attempt graceful shutdown, and
|
|
|
|
suppress the SIGKILL warning log message.
|
|
|
|
:param timeout: Optional timeout in seconds for graceful shutdown.
|
2020-07-20 18:02:52 +02:00
|
|
|
Default 30 seconds, A `None` value is an infinite wait.
|
2019-06-27 23:28:14 +02:00
|
|
|
"""
|
2020-07-10 07:06:42 +02:00
|
|
|
if not self._launched:
|
|
|
|
return
|
|
|
|
|
2020-07-10 07:06:47 +02:00
|
|
|
try:
|
2020-02-17 16:02:42 +01:00
|
|
|
if hard:
|
2020-07-10 07:06:48 +02:00
|
|
|
self._user_killed = True
|
2020-07-10 07:06:47 +02:00
|
|
|
self._hard_shutdown()
|
|
|
|
else:
|
2020-07-20 18:02:52 +02:00
|
|
|
self._do_shutdown(timeout, has_quit)
|
2020-07-10 07:06:47 +02:00
|
|
|
finally:
|
|
|
|
self._post_shutdown()
|
2019-06-27 23:28:14 +02:00
|
|
|
|
2020-10-07 01:58:08 +02:00
|
|
|
def kill(self) -> None:
|
2020-07-10 07:06:47 +02:00
|
|
|
"""
|
|
|
|
Terminate the VM forcefully, wait for it to exit, and perform cleanup.
|
|
|
|
"""
|
2020-02-17 16:02:42 +01:00
|
|
|
self.shutdown(hard=True)
|
|
|
|
|
2020-07-20 18:02:52 +02:00
|
|
|
def wait(self, timeout: Optional[int] = 30) -> None:
|
2020-07-10 07:06:44 +02:00
|
|
|
"""
|
|
|
|
Wait for the VM to power off and perform post-shutdown cleanup.
|
|
|
|
|
2020-07-20 18:02:52 +02:00
|
|
|
:param timeout: Optional timeout in seconds. Default 30 seconds.
|
|
|
|
A value of `None` is an infinite wait.
|
2020-07-10 07:06:44 +02:00
|
|
|
"""
|
|
|
|
self.shutdown(has_quit=True, timeout=timeout)
|
|
|
|
|
2020-10-07 01:58:08 +02:00
|
|
|
def set_qmp_monitor(self, enabled: bool = True) -> None:
|
2019-12-11 19:55:35 +01:00
|
|
|
"""
|
|
|
|
Set the QMP monitor.
|
|
|
|
|
|
|
|
@param enabled: if False, qmp monitor options will be removed from
|
|
|
|
the base arguments of the resulting QEMU command
|
|
|
|
line. Default is True.
|
2021-06-29 23:43:23 +02:00
|
|
|
|
|
|
|
.. note:: Call this function before launch().
|
2019-12-11 19:55:35 +01:00
|
|
|
"""
|
2020-10-07 01:58:04 +02:00
|
|
|
self._qmp_set = enabled
|
|
|
|
|
|
|
|
@property
|
2021-05-27 23:16:53 +02:00
|
|
|
def _qmp(self) -> QEMUMonitorProtocol:
|
2020-10-07 01:58:04 +02:00
|
|
|
if self._qmp_connection is None:
|
|
|
|
raise QEMUMachineError("Attempt to access QMP with no connection")
|
|
|
|
return self._qmp_connection
|
2019-12-11 19:55:35 +01:00
|
|
|
|
2020-10-07 01:58:03 +02:00
|
|
|
@classmethod
|
|
|
|
def _qmp_args(cls, _conv_keys: bool = True, **args: Any) -> Dict[str, Any]:
|
2019-06-27 23:28:14 +02:00
|
|
|
qmp_args = dict()
|
|
|
|
for key, value in args.items():
|
2020-10-07 01:58:03 +02:00
|
|
|
if _conv_keys:
|
2019-06-27 23:28:14 +02:00
|
|
|
qmp_args[key.replace('_', '-')] = value
|
|
|
|
else:
|
|
|
|
qmp_args[key] = value
|
2020-10-07 01:58:03 +02:00
|
|
|
return qmp_args
|
2019-06-27 23:28:14 +02:00
|
|
|
|
2020-10-07 01:58:03 +02:00
|
|
|
def qmp(self, cmd: str,
|
|
|
|
conv_keys: bool = True,
|
|
|
|
**args: Any) -> QMPMessage:
|
|
|
|
"""
|
|
|
|
Invoke a QMP command and return the response dict
|
|
|
|
"""
|
|
|
|
qmp_args = self._qmp_args(conv_keys, **args)
|
2019-06-27 23:28:14 +02:00
|
|
|
return self._qmp.cmd(cmd, args=qmp_args)
|
|
|
|
|
2020-10-07 01:58:08 +02:00
|
|
|
def command(self, cmd: str,
|
|
|
|
conv_keys: bool = True,
|
|
|
|
**args: Any) -> QMPReturnValue:
|
2019-06-27 23:28:14 +02:00
|
|
|
"""
|
|
|
|
Invoke a QMP command.
|
|
|
|
On success return the response dict.
|
|
|
|
On failure raise an exception.
|
|
|
|
"""
|
2020-10-07 01:58:03 +02:00
|
|
|
qmp_args = self._qmp_args(conv_keys, **args)
|
|
|
|
return self._qmp.command(cmd, **qmp_args)
|
2019-06-27 23:28:14 +02:00
|
|
|
|
2020-10-07 01:58:08 +02:00
|
|
|
def get_qmp_event(self, wait: bool = False) -> Optional[QMPMessage]:
|
2019-06-27 23:28:14 +02:00
|
|
|
"""
|
|
|
|
Poll for one queued QMP events and return it
|
|
|
|
"""
|
2019-06-27 23:28:15 +02:00
|
|
|
if self._events:
|
2019-06-27 23:28:14 +02:00
|
|
|
return self._events.pop(0)
|
|
|
|
return self._qmp.pull_event(wait=wait)
|
|
|
|
|
2020-10-07 01:58:08 +02:00
|
|
|
def get_qmp_events(self, wait: bool = False) -> List[QMPMessage]:
|
2019-06-27 23:28:14 +02:00
|
|
|
"""
|
|
|
|
Poll for queued QMP events and return a list of dicts
|
|
|
|
"""
|
|
|
|
events = self._qmp.get_events(wait=wait)
|
|
|
|
events.extend(self._events)
|
|
|
|
del self._events[:]
|
|
|
|
self._qmp.clear_events()
|
|
|
|
return events
|
|
|
|
|
|
|
|
@staticmethod
|
2020-10-07 01:58:08 +02:00
|
|
|
def event_match(event: Any, match: Optional[Any]) -> bool:
|
2019-06-27 23:28:14 +02:00
|
|
|
"""
|
|
|
|
Check if an event matches optional match criteria.
|
|
|
|
|
|
|
|
The match criteria takes the form of a matching subdict. The event is
|
|
|
|
checked to be a superset of the subdict, recursively, with matching
|
|
|
|
values whenever the subdict values are not None.
|
|
|
|
|
|
|
|
This has a limitation that you cannot explicitly check for None values.
|
|
|
|
|
|
|
|
Examples, with the subdict queries on the left:
|
|
|
|
- None matches any object.
|
|
|
|
- {"foo": None} matches {"foo": {"bar": 1}}
|
|
|
|
- {"foo": None} matches {"foo": 5}
|
|
|
|
- {"foo": {"abc": None}} does not match {"foo": {"bar": 1}}
|
|
|
|
- {"foo": {"rab": 2}} matches {"foo": {"bar": 1, "rab": 2}}
|
|
|
|
"""
|
|
|
|
if match is None:
|
|
|
|
return True
|
|
|
|
|
|
|
|
try:
|
|
|
|
for key in match:
|
|
|
|
if key in event:
|
|
|
|
if not QEMUMachine.event_match(event[key], match[key]):
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
except TypeError:
|
|
|
|
# either match or event wasn't iterable (not a dict)
|
2020-10-07 01:58:08 +02:00
|
|
|
return bool(match == event)
|
2019-06-27 23:28:14 +02:00
|
|
|
|
2020-10-07 01:58:08 +02:00
|
|
|
def event_wait(self, name: str,
|
|
|
|
timeout: float = 60.0,
|
|
|
|
match: Optional[QMPMessage] = None) -> Optional[QMPMessage]:
|
2019-06-27 23:28:14 +02:00
|
|
|
"""
|
|
|
|
event_wait waits for and returns a named event from QMP with a timeout.
|
|
|
|
|
|
|
|
name: The event to wait for.
|
|
|
|
timeout: QEMUMonitorProtocol.pull_event timeout parameter.
|
|
|
|
match: Optional match criteria. See event_match for details.
|
|
|
|
"""
|
|
|
|
return self.events_wait([(name, match)], timeout)
|
|
|
|
|
2020-10-07 01:58:08 +02:00
|
|
|
def events_wait(self,
|
|
|
|
events: Sequence[Tuple[str, Any]],
|
|
|
|
timeout: float = 60.0) -> Optional[QMPMessage]:
|
2019-06-27 23:28:14 +02:00
|
|
|
"""
|
2020-10-07 01:58:02 +02:00
|
|
|
events_wait waits for and returns a single named event from QMP.
|
|
|
|
In the case of multiple qualifying events, this function returns the
|
|
|
|
first one.
|
2019-06-27 23:28:14 +02:00
|
|
|
|
2020-10-07 01:58:02 +02:00
|
|
|
:param events: A sequence of (name, match_criteria) tuples.
|
|
|
|
The match criteria are optional and may be None.
|
|
|
|
See event_match for details.
|
|
|
|
:param timeout: Optional timeout, in seconds.
|
|
|
|
See QEMUMonitorProtocol.pull_event.
|
|
|
|
|
|
|
|
:raise QMPTimeoutError: If timeout was non-zero and no matching events
|
|
|
|
were found.
|
|
|
|
:return: A QMP event matching the filter criteria.
|
|
|
|
If timeout was 0 and no event matched, None.
|
2019-06-27 23:28:14 +02:00
|
|
|
"""
|
2020-10-07 01:58:08 +02:00
|
|
|
def _match(event: QMPMessage) -> bool:
|
2019-06-27 23:28:14 +02:00
|
|
|
for name, match in events:
|
2019-06-27 23:28:15 +02:00
|
|
|
if event['event'] == name and self.event_match(event, match):
|
2019-06-27 23:28:14 +02:00
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2020-10-07 01:58:02 +02:00
|
|
|
event: Optional[QMPMessage]
|
|
|
|
|
2019-06-27 23:28:14 +02:00
|
|
|
# Search cached events
|
|
|
|
for event in self._events:
|
|
|
|
if _match(event):
|
|
|
|
self._events.remove(event)
|
|
|
|
return event
|
|
|
|
|
|
|
|
# Poll for new events
|
|
|
|
while True:
|
|
|
|
event = self._qmp.pull_event(wait=timeout)
|
2020-10-07 01:58:02 +02:00
|
|
|
if event is None:
|
|
|
|
# NB: None is only returned when timeout is false-ish.
|
|
|
|
# Timeouts raise QMPTimeoutError instead!
|
|
|
|
break
|
2019-06-27 23:28:14 +02:00
|
|
|
if _match(event):
|
|
|
|
return event
|
|
|
|
self._events.append(event)
|
|
|
|
|
|
|
|
return None
|
|
|
|
|
2020-10-07 01:58:08 +02:00
|
|
|
def get_log(self) -> Optional[str]:
|
2019-06-27 23:28:14 +02:00
|
|
|
"""
|
|
|
|
After self.shutdown or failed qemu execution, this returns the output
|
|
|
|
of the qemu process.
|
|
|
|
"""
|
|
|
|
return self._iolog
|
|
|
|
|
2020-10-07 01:58:08 +02:00
|
|
|
def add_args(self, *args: str) -> None:
|
2019-06-27 23:28:14 +02:00
|
|
|
"""
|
|
|
|
Adds to the list of extra arguments to be given to the QEMU binary
|
|
|
|
"""
|
|
|
|
self._args.extend(args)
|
|
|
|
|
2020-10-07 01:58:08 +02:00
|
|
|
def set_machine(self, machine_type: str) -> None:
|
2019-06-27 23:28:14 +02:00
|
|
|
"""
|
|
|
|
Sets the machine type
|
|
|
|
|
|
|
|
If set, the machine type will be added to the base arguments
|
|
|
|
of the resulting QEMU command line.
|
|
|
|
"""
|
|
|
|
self._machine = machine_type
|
|
|
|
|
2020-10-07 01:58:08 +02:00
|
|
|
def set_console(self,
|
|
|
|
device_type: Optional[str] = None,
|
|
|
|
console_index: int = 0) -> None:
|
2019-06-27 23:28:14 +02:00
|
|
|
"""
|
|
|
|
Sets the device type for a console device
|
|
|
|
|
|
|
|
If set, the console device and a backing character device will
|
|
|
|
be added to the base arguments of the resulting QEMU command
|
|
|
|
line.
|
|
|
|
|
|
|
|
This is a convenience method that will either use the provided
|
|
|
|
device type, or default to a "-serial chardev:console" command
|
|
|
|
line argument.
|
|
|
|
|
|
|
|
The actual setting of command line arguments will be be done at
|
|
|
|
machine launch time, as it depends on the temporary directory
|
|
|
|
to be created.
|
|
|
|
|
|
|
|
@param device_type: the device type, such as "isa-serial". If
|
|
|
|
None is given (the default value) a "-serial
|
|
|
|
chardev:console" command line argument will
|
|
|
|
be used instead, resorting to the machine's
|
|
|
|
default device type.
|
2020-01-21 00:51:56 +01:00
|
|
|
@param console_index: the index of the console device to use.
|
|
|
|
If not zero, the command line will create
|
|
|
|
'index - 1' consoles and connect them to
|
|
|
|
the 'null' backing character device.
|
2019-06-27 23:28:14 +02:00
|
|
|
"""
|
|
|
|
self._console_set = True
|
|
|
|
self._console_device_type = device_type
|
2020-01-21 00:51:56 +01:00
|
|
|
self._console_index = console_index
|
2019-06-27 23:28:14 +02:00
|
|
|
|
|
|
|
@property
|
2020-10-07 01:58:08 +02:00
|
|
|
def console_socket(self) -> socket.socket:
|
2019-06-27 23:28:14 +02:00
|
|
|
"""
|
|
|
|
Returns a socket connected to the console
|
|
|
|
"""
|
|
|
|
if self._console_socket is None:
|
2020-07-24 08:45:08 +02:00
|
|
|
self._console_socket = console_socket.ConsoleSocket(
|
|
|
|
self._console_address,
|
|
|
|
file=self._console_log_path,
|
|
|
|
drain=self._drain_console)
|
2019-06-27 23:28:14 +02:00
|
|
|
return self._console_socket
|
2021-02-11 23:01:42 +01:00
|
|
|
|
|
|
|
@property
|
|
|
|
def temp_dir(self) -> str:
|
|
|
|
"""
|
|
|
|
Returns a temporary directory to be used for this machine
|
|
|
|
"""
|
|
|
|
if self._temp_dir is None:
|
|
|
|
self._temp_dir = tempfile.mkdtemp(prefix="qemu-machine-",
|
|
|
|
dir=self._base_temp_dir)
|
|
|
|
return self._temp_dir
|