John Snow | 306dfcd | 2019-06-27 17:28:15 -0400 | [diff] [blame] | 1 | """ |
| 2 | QEMU machine module: |
| 3 | |
| 4 | The machine module primarily provides the QEMUMachine class, |
| 5 | which provides facilities for managing the lifetime of a QEMU VM. |
| 6 | """ |
| 7 | |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 8 | # Copyright (C) 2015-2016 Red Hat Inc. |
| 9 | # Copyright (C) 2012 IBM Corp. |
| 10 | # |
| 11 | # Authors: |
| 12 | # Fam Zheng <famz@redhat.com> |
| 13 | # |
| 14 | # This work is licensed under the terms of the GNU GPL, version 2. See |
| 15 | # the COPYING file in the top-level directory. |
| 16 | # |
| 17 | # Based on qmp.py. |
| 18 | # |
| 19 | |
| 20 | import errno |
John Snow | aad3f3b | 2020-10-06 19:58:06 -0400 | [diff] [blame] | 21 | from itertools import chain |
John Snow | 5690b43 | 2021-09-16 14:22:47 -0400 | [diff] [blame] | 22 | import locale |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 23 | import logging |
| 24 | import os |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 25 | import shutil |
John Snow | de6e08b | 2020-07-10 01:06:48 -0400 | [diff] [blame] | 26 | import signal |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 27 | import socket |
John Snow | 932ca4b | 2020-10-06 19:57:58 -0400 | [diff] [blame] | 28 | import subprocess |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 29 | import tempfile |
John Snow | 1dda040 | 2020-05-14 01:53:44 -0400 | [diff] [blame] | 30 | from types import TracebackType |
John Snow | aaa81ec | 2020-10-06 19:58:03 -0400 | [diff] [blame] | 31 | from typing import ( |
| 32 | Any, |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 33 | BinaryIO, |
John Snow | aaa81ec | 2020-10-06 19:58:03 -0400 | [diff] [blame] | 34 | Dict, |
| 35 | List, |
| 36 | Optional, |
John Snow | aad3f3b | 2020-10-06 19:58:06 -0400 | [diff] [blame] | 37 | Sequence, |
| 38 | Tuple, |
John Snow | aaa81ec | 2020-10-06 19:58:03 -0400 | [diff] [blame] | 39 | Type, |
Vladimir Sementsov-Ogievskiy | 15c3b86 | 2021-08-24 11:38:47 +0300 | [diff] [blame] | 40 | TypeVar, |
John Snow | aaa81ec | 2020-10-06 19:58:03 -0400 | [diff] [blame] | 41 | ) |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 42 | |
John Snow | d1e0476 | 2021-05-27 17:16:59 -0400 | [diff] [blame] | 43 | from qemu.qmp import ( # pylint: disable=import-error |
John Snow | beb6b57 | 2021-05-27 17:16:53 -0400 | [diff] [blame] | 44 | QEMUMonitorProtocol, |
| 45 | QMPMessage, |
| 46 | QMPReturnValue, |
| 47 | SocketAddrT, |
| 48 | ) |
| 49 | |
| 50 | from . import console_socket |
John Snow | 932ca4b | 2020-10-06 19:57:58 -0400 | [diff] [blame] | 51 | |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 52 | |
| 53 | LOG = logging.getLogger(__name__) |
| 54 | |
John Snow | 8dfac2e | 2020-05-28 18:21:29 -0400 | [diff] [blame] | 55 | |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 56 | class QEMUMachineError(Exception): |
| 57 | """ |
| 58 | Exception called when an error in QEMUMachine happens. |
| 59 | """ |
| 60 | |
| 61 | |
| 62 | class QEMUMachineAddDeviceError(QEMUMachineError): |
| 63 | """ |
| 64 | Exception raised when a request to add a device can not be fulfilled |
| 65 | |
| 66 | The failures are caused by limitations, lack of information or conflicting |
| 67 | requests on the QEMUMachine methods. This exception does not represent |
| 68 | failures reported by the QEMU binary itself. |
| 69 | """ |
| 70 | |
| 71 | |
John Snow | 193bf1c | 2020-07-10 01:06:47 -0400 | [diff] [blame] | 72 | class AbnormalShutdown(QEMUMachineError): |
| 73 | """ |
| 74 | Exception raised when a graceful shutdown was requested, but not performed. |
| 75 | """ |
| 76 | |
| 77 | |
Vladimir Sementsov-Ogievskiy | 15c3b86 | 2021-08-24 11:38:47 +0300 | [diff] [blame] | 78 | _T = TypeVar('_T', bound='QEMUMachine') |
| 79 | |
| 80 | |
John Snow | 9b8ccd6 | 2020-05-28 18:21:28 -0400 | [diff] [blame] | 81 | class QEMUMachine: |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 82 | """ |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 83 | A QEMU VM. |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 84 | |
John Snow | 8dfac2e | 2020-05-28 18:21:29 -0400 | [diff] [blame] | 85 | Use this object as a context manager to ensure |
| 86 | the QEMU process terminates:: |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 87 | |
| 88 | with VM(binary) as vm: |
| 89 | ... |
| 90 | # vm is guaranteed to be shut down here |
| 91 | """ |
John Snow | 82e6517 | 2021-06-29 17:43:11 -0400 | [diff] [blame] | 92 | # pylint: disable=too-many-instance-attributes, too-many-public-methods |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 93 | |
John Snow | aad3f3b | 2020-10-06 19:58:06 -0400 | [diff] [blame] | 94 | def __init__(self, |
| 95 | binary: str, |
| 96 | args: Sequence[str] = (), |
| 97 | wrapper: Sequence[str] = (), |
| 98 | name: Optional[str] = None, |
Cleber Rosa | 2ca6e26 | 2021-02-11 17:01:42 -0500 | [diff] [blame] | 99 | base_temp_dir: str = "/var/tmp", |
John Snow | c4e6023 | 2020-10-06 19:57:59 -0400 | [diff] [blame] | 100 | monitor_address: Optional[SocketAddrT] = None, |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 101 | socket_scm_helper: Optional[str] = None, |
| 102 | sock_dir: Optional[str] = None, |
| 103 | drain_console: bool = False, |
Cleber Rosa | b306e26 | 2021-02-11 16:55:05 -0500 | [diff] [blame] | 104 | console_log: Optional[str] = None, |
Emanuele Giuseppe Esposito | e2f948a | 2021-08-09 11:00:59 +0200 | [diff] [blame] | 105 | log_dir: Optional[str] = None, |
| 106 | qmp_timer: Optional[float] = None): |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 107 | ''' |
| 108 | Initialize a QEMUMachine |
| 109 | |
| 110 | @param binary: path to the qemu binary |
| 111 | @param args: list of extra arguments |
| 112 | @param wrapper: list of arguments used as prefix to qemu binary |
| 113 | @param name: prefix for socket and log file names (default: qemu-PID) |
John Snow | 859aeb6 | 2021-05-27 17:16:51 -0400 | [diff] [blame] | 114 | @param base_temp_dir: default location where temp files are created |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 115 | @param monitor_address: address for QMP monitor |
| 116 | @param socket_scm_helper: helper program, required for send_fd_scm() |
Cleber Rosa | 2ca6e26 | 2021-02-11 17:01:42 -0500 | [diff] [blame] | 117 | @param sock_dir: where to create socket (defaults to base_temp_dir) |
Robert Foley | 0fc8f66 | 2020-07-01 14:56:24 +0100 | [diff] [blame] | 118 | @param drain_console: (optional) True to drain console socket to buffer |
John Snow | c5e61a6 | 2020-10-06 19:58:00 -0400 | [diff] [blame] | 119 | @param console_log: (optional) path to console log file |
Cleber Rosa | b306e26 | 2021-02-11 16:55:05 -0500 | [diff] [blame] | 120 | @param log_dir: where to create and keep log files |
Emanuele Giuseppe Esposito | e2f948a | 2021-08-09 11:00:59 +0200 | [diff] [blame] | 121 | @param qmp_timer: (optional) default QMP socket timeout |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 122 | @note: Qemu process is not started until launch() is used. |
| 123 | ''' |
John Snow | 82e6517 | 2021-06-29 17:43:11 -0400 | [diff] [blame] | 124 | # pylint: disable=too-many-arguments |
| 125 | |
John Snow | c5e61a6 | 2020-10-06 19:58:00 -0400 | [diff] [blame] | 126 | # Direct user configuration |
| 127 | |
| 128 | self._binary = binary |
John Snow | c5e61a6 | 2020-10-06 19:58:00 -0400 | [diff] [blame] | 129 | self._args = list(args) |
John Snow | c5e61a6 | 2020-10-06 19:58:00 -0400 | [diff] [blame] | 130 | self._wrapper = wrapper |
Emanuele Giuseppe Esposito | e2f948a | 2021-08-09 11:00:59 +0200 | [diff] [blame] | 131 | self._qmp_timer = qmp_timer |
John Snow | c5e61a6 | 2020-10-06 19:58:00 -0400 | [diff] [blame] | 132 | |
| 133 | self._name = name or "qemu-%d" % os.getpid() |
Cleber Rosa | 2ca6e26 | 2021-02-11 17:01:42 -0500 | [diff] [blame] | 134 | self._base_temp_dir = base_temp_dir |
| 135 | self._sock_dir = sock_dir or self._base_temp_dir |
Cleber Rosa | b306e26 | 2021-02-11 16:55:05 -0500 | [diff] [blame] | 136 | self._log_dir = log_dir |
John Snow | c5e61a6 | 2020-10-06 19:58:00 -0400 | [diff] [blame] | 137 | self._socket_scm_helper = socket_scm_helper |
| 138 | |
John Snow | c4e6023 | 2020-10-06 19:57:59 -0400 | [diff] [blame] | 139 | if monitor_address is not None: |
| 140 | self._monitor_address = monitor_address |
| 141 | self._remove_monitor_sockfile = False |
| 142 | else: |
| 143 | self._monitor_address = os.path.join( |
John Snow | c5e61a6 | 2020-10-06 19:58:00 -0400 | [diff] [blame] | 144 | self._sock_dir, f"{self._name}-monitor.sock" |
John Snow | c4e6023 | 2020-10-06 19:57:59 -0400 | [diff] [blame] | 145 | ) |
| 146 | self._remove_monitor_sockfile = True |
John Snow | c5e61a6 | 2020-10-06 19:58:00 -0400 | [diff] [blame] | 147 | |
| 148 | self._console_log_path = console_log |
| 149 | if self._console_log_path: |
| 150 | # In order to log the console, buffering needs to be enabled. |
| 151 | self._drain_console = True |
| 152 | else: |
| 153 | self._drain_console = drain_console |
| 154 | |
| 155 | # Runstate |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 156 | self._qemu_log_path: Optional[str] = None |
| 157 | self._qemu_log_file: Optional[BinaryIO] = None |
John Snow | 9223fda | 2020-10-06 19:58:05 -0400 | [diff] [blame] | 158 | self._popen: Optional['subprocess.Popen[bytes]'] = None |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 159 | self._events: List[QMPMessage] = [] |
| 160 | self._iolog: Optional[str] = None |
Wainer dos Santos Moschetta | 74b56bb | 2019-12-11 13:55:35 -0500 | [diff] [blame] | 161 | self._qmp_set = True # Enable QMP monitor by default. |
John Snow | beb6b57 | 2021-05-27 17:16:53 -0400 | [diff] [blame] | 162 | self._qmp_connection: Optional[QEMUMonitorProtocol] = None |
John Snow | aad3f3b | 2020-10-06 19:58:06 -0400 | [diff] [blame] | 163 | self._qemu_full_args: Tuple[str, ...] = () |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 164 | self._temp_dir: Optional[str] = None |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 165 | self._launched = False |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 166 | self._machine: Optional[str] = None |
Philippe Mathieu-Daudé | 746f244 | 2020-01-21 00:51:56 +0100 | [diff] [blame] | 167 | self._console_index = 0 |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 168 | self._console_set = False |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 169 | self._console_device_type: Optional[str] = None |
John Snow | 652809d | 2020-10-06 19:58:01 -0400 | [diff] [blame] | 170 | self._console_address = os.path.join( |
| 171 | self._sock_dir, f"{self._name}-console.sock" |
| 172 | ) |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 173 | self._console_socket: Optional[socket.socket] = None |
| 174 | self._remove_files: List[str] = [] |
John Snow | de6e08b | 2020-07-10 01:06:48 -0400 | [diff] [blame] | 175 | self._user_killed = False |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 176 | |
Vladimir Sementsov-Ogievskiy | 15c3b86 | 2021-08-24 11:38:47 +0300 | [diff] [blame] | 177 | def __enter__(self: _T) -> _T: |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 178 | return self |
| 179 | |
John Snow | 1dda040 | 2020-05-14 01:53:44 -0400 | [diff] [blame] | 180 | def __exit__(self, |
| 181 | exc_type: Optional[Type[BaseException]], |
| 182 | exc_val: Optional[BaseException], |
| 183 | exc_tb: Optional[TracebackType]) -> None: |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 184 | self.shutdown() |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 185 | |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 186 | def add_monitor_null(self) -> None: |
John Snow | 306dfcd | 2019-06-27 17:28:15 -0400 | [diff] [blame] | 187 | """ |
| 188 | This can be used to add an unused monitor instance. |
| 189 | """ |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 190 | self._args.append('-monitor') |
| 191 | self._args.append('null') |
| 192 | |
Vladimir Sementsov-Ogievskiy | 15c3b86 | 2021-08-24 11:38:47 +0300 | [diff] [blame] | 193 | def add_fd(self: _T, fd: int, fdset: int, |
| 194 | opaque: str, opts: str = '') -> _T: |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 195 | """ |
| 196 | Pass a file descriptor to the VM |
| 197 | """ |
| 198 | options = ['fd=%d' % fd, |
| 199 | 'set=%d' % fdset, |
| 200 | 'opaque=%s' % opaque] |
| 201 | if opts: |
| 202 | options.append(opts) |
| 203 | |
| 204 | # This did not exist before 3.4, but since then it is |
| 205 | # mandatory for our purpose |
| 206 | if hasattr(os, 'set_inheritable'): |
| 207 | os.set_inheritable(fd, True) |
| 208 | |
| 209 | self._args.append('-add-fd') |
| 210 | self._args.append(','.join(options)) |
| 211 | return self |
| 212 | |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 213 | def send_fd_scm(self, fd: Optional[int] = None, |
| 214 | file_path: Optional[str] = None) -> int: |
John Snow | 306dfcd | 2019-06-27 17:28:15 -0400 | [diff] [blame] | 215 | """ |
| 216 | Send an fd or file_path to socket_scm_helper. |
| 217 | |
| 218 | Exactly one of fd and file_path must be given. |
| 219 | If it is file_path, the helper will open that file and pass its own fd. |
| 220 | """ |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 221 | # In iotest.py, the qmp should always use unix socket. |
| 222 | assert self._qmp.is_scm_available() |
| 223 | if self._socket_scm_helper is None: |
| 224 | raise QEMUMachineError("No path to socket_scm_helper set") |
| 225 | if not os.path.exists(self._socket_scm_helper): |
| 226 | raise QEMUMachineError("%s does not exist" % |
| 227 | self._socket_scm_helper) |
| 228 | |
| 229 | # This did not exist before 3.4, but since then it is |
| 230 | # mandatory for our purpose |
| 231 | if hasattr(os, 'set_inheritable'): |
| 232 | os.set_inheritable(self._qmp.get_sock_fd(), True) |
| 233 | if fd is not None: |
| 234 | os.set_inheritable(fd, True) |
| 235 | |
| 236 | fd_param = ["%s" % self._socket_scm_helper, |
| 237 | "%d" % self._qmp.get_sock_fd()] |
| 238 | |
| 239 | if file_path is not None: |
| 240 | assert fd is None |
| 241 | fd_param.append(file_path) |
| 242 | else: |
| 243 | assert fd is not None |
| 244 | fd_param.append(str(fd)) |
| 245 | |
John Snow | 14b4179 | 2021-05-27 17:16:47 -0400 | [diff] [blame] | 246 | proc = subprocess.run( |
| 247 | fd_param, |
| 248 | stdin=subprocess.DEVNULL, |
| 249 | stdout=subprocess.PIPE, |
| 250 | stderr=subprocess.STDOUT, |
| 251 | check=False, |
| 252 | close_fds=False, |
John Snow | 8dfac2e | 2020-05-28 18:21:29 -0400 | [diff] [blame] | 253 | ) |
John Snow | 14b4179 | 2021-05-27 17:16:47 -0400 | [diff] [blame] | 254 | if proc.stdout: |
| 255 | LOG.debug(proc.stdout) |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 256 | |
| 257 | return proc.returncode |
| 258 | |
| 259 | @staticmethod |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 260 | def _remove_if_exists(path: str) -> None: |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 261 | """ |
| 262 | Remove file object at path if it exists |
| 263 | """ |
| 264 | try: |
| 265 | os.remove(path) |
| 266 | except OSError as exception: |
| 267 | if exception.errno == errno.ENOENT: |
| 268 | return |
| 269 | raise |
| 270 | |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 271 | def is_running(self) -> bool: |
John Snow | 306dfcd | 2019-06-27 17:28:15 -0400 | [diff] [blame] | 272 | """Returns true if the VM is running.""" |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 273 | return self._popen is not None and self._popen.poll() is None |
| 274 | |
John Snow | 9223fda | 2020-10-06 19:58:05 -0400 | [diff] [blame] | 275 | @property |
| 276 | def _subp(self) -> 'subprocess.Popen[bytes]': |
| 277 | if self._popen is None: |
| 278 | raise QEMUMachineError('Subprocess pipe not present') |
| 279 | return self._popen |
| 280 | |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 281 | def exitcode(self) -> Optional[int]: |
John Snow | 306dfcd | 2019-06-27 17:28:15 -0400 | [diff] [blame] | 282 | """Returns the exit code if possible, or None.""" |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 283 | if self._popen is None: |
| 284 | return None |
| 285 | return self._popen.poll() |
| 286 | |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 287 | def get_pid(self) -> Optional[int]: |
John Snow | 306dfcd | 2019-06-27 17:28:15 -0400 | [diff] [blame] | 288 | """Returns the PID of the running process, or None.""" |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 289 | if not self.is_running(): |
| 290 | return None |
John Snow | 9223fda | 2020-10-06 19:58:05 -0400 | [diff] [blame] | 291 | return self._subp.pid |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 292 | |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 293 | def _load_io_log(self) -> None: |
John Snow | 5690b43 | 2021-09-16 14:22:47 -0400 | [diff] [blame] | 294 | # Assume that the output encoding of QEMU's terminal output is |
| 295 | # defined by our locale. If indeterminate, allow open() to fall |
| 296 | # back to the platform default. |
| 297 | _, encoding = locale.getlocale() |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 298 | if self._qemu_log_path is not None: |
John Snow | 5690b43 | 2021-09-16 14:22:47 -0400 | [diff] [blame] | 299 | with open(self._qemu_log_path, "r", encoding=encoding) as iolog: |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 300 | self._iolog = iolog.read() |
| 301 | |
John Snow | 652809d | 2020-10-06 19:58:01 -0400 | [diff] [blame] | 302 | @property |
| 303 | def _base_args(self) -> List[str]: |
Wainer dos Santos Moschetta | 74b56bb | 2019-12-11 13:55:35 -0500 | [diff] [blame] | 304 | args = ['-display', 'none', '-vga', 'none'] |
John Snow | c4e6023 | 2020-10-06 19:57:59 -0400 | [diff] [blame] | 305 | |
Wainer dos Santos Moschetta | 74b56bb | 2019-12-11 13:55:35 -0500 | [diff] [blame] | 306 | if self._qmp_set: |
| 307 | if isinstance(self._monitor_address, tuple): |
John Snow | c4e6023 | 2020-10-06 19:57:59 -0400 | [diff] [blame] | 308 | moncdev = "socket,id=mon,host={},port={}".format( |
| 309 | *self._monitor_address |
| 310 | ) |
Wainer dos Santos Moschetta | 74b56bb | 2019-12-11 13:55:35 -0500 | [diff] [blame] | 311 | else: |
John Snow | c4e6023 | 2020-10-06 19:57:59 -0400 | [diff] [blame] | 312 | moncdev = f"socket,id=mon,path={self._monitor_address}" |
Wainer dos Santos Moschetta | 74b56bb | 2019-12-11 13:55:35 -0500 | [diff] [blame] | 313 | args.extend(['-chardev', moncdev, '-mon', |
| 314 | 'chardev=mon,mode=control']) |
John Snow | c4e6023 | 2020-10-06 19:57:59 -0400 | [diff] [blame] | 315 | |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 316 | if self._machine is not None: |
| 317 | args.extend(['-machine', self._machine]) |
John Snow | 9b8ccd6 | 2020-05-28 18:21:28 -0400 | [diff] [blame] | 318 | for _ in range(self._console_index): |
Philippe Mathieu-Daudé | 746f244 | 2020-01-21 00:51:56 +0100 | [diff] [blame] | 319 | args.extend(['-serial', 'null']) |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 320 | if self._console_set: |
Paolo Bonzini | 991c180 | 2020-11-13 03:10:52 -0500 | [diff] [blame] | 321 | chardev = ('socket,id=console,path=%s,server=on,wait=off' % |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 322 | self._console_address) |
| 323 | args.extend(['-chardev', chardev]) |
| 324 | if self._console_device_type is None: |
| 325 | args.extend(['-serial', 'chardev:console']) |
| 326 | else: |
| 327 | device = '%s,chardev=console' % self._console_device_type |
| 328 | args.extend(['-device', device]) |
| 329 | return args |
| 330 | |
Wainer dos Santos Moschetta | 555fe0c | 2021-04-30 10:34:12 -0300 | [diff] [blame] | 331 | @property |
| 332 | def args(self) -> List[str]: |
| 333 | """Returns the list of arguments given to the QEMU binary.""" |
| 334 | return self._args |
| 335 | |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 336 | def _pre_launch(self) -> None: |
John Snow | 652809d | 2020-10-06 19:58:01 -0400 | [diff] [blame] | 337 | if self._console_set: |
| 338 | self._remove_files.append(self._console_address) |
| 339 | |
Wainer dos Santos Moschetta | 74b56bb | 2019-12-11 13:55:35 -0500 | [diff] [blame] | 340 | if self._qmp_set: |
John Snow | c4e6023 | 2020-10-06 19:57:59 -0400 | [diff] [blame] | 341 | if self._remove_monitor_sockfile: |
| 342 | assert isinstance(self._monitor_address, str) |
| 343 | self._remove_files.append(self._monitor_address) |
John Snow | beb6b57 | 2021-05-27 17:16:53 -0400 | [diff] [blame] | 344 | self._qmp_connection = QEMUMonitorProtocol( |
John Snow | c4e6023 | 2020-10-06 19:57:59 -0400 | [diff] [blame] | 345 | self._monitor_address, |
| 346 | server=True, |
| 347 | nickname=self._name |
| 348 | ) |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 349 | |
John Snow | 63c33f3 | 2021-05-27 17:16:49 -0400 | [diff] [blame] | 350 | # NOTE: Make sure any opened resources are *definitely* freed in |
| 351 | # _post_shutdown()! |
| 352 | # pylint: disable=consider-using-with |
Cleber Rosa | b306e26 | 2021-02-11 16:55:05 -0500 | [diff] [blame] | 353 | self._qemu_log_path = os.path.join(self.log_dir, self._name + ".log") |
John Snow | 63c33f3 | 2021-05-27 17:16:49 -0400 | [diff] [blame] | 354 | self._qemu_log_file = open(self._qemu_log_path, 'wb') |
| 355 | |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 356 | def _post_launch(self) -> None: |
John Snow | be1183e | 2020-10-06 19:58:04 -0400 | [diff] [blame] | 357 | if self._qmp_connection: |
Emanuele Giuseppe Esposito | e2f948a | 2021-08-09 11:00:59 +0200 | [diff] [blame] | 358 | self._qmp.accept(self._qmp_timer) |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 359 | |
Emanuele Giuseppe Esposito | eb7a91d | 2021-08-09 11:01:13 +0200 | [diff] [blame] | 360 | def _close_qemu_log_file(self) -> None: |
| 361 | if self._qemu_log_file is not None: |
| 362 | self._qemu_log_file.close() |
| 363 | self._qemu_log_file = None |
| 364 | |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 365 | def _post_shutdown(self) -> None: |
John Snow | a3842cb | 2020-07-10 01:06:42 -0400 | [diff] [blame] | 366 | """ |
| 367 | Called to cleanup the VM instance after the process has exited. |
| 368 | May also be called after a failed launch. |
| 369 | """ |
| 370 | # Comprehensive reset for the failed launch case: |
| 371 | self._early_cleanup() |
| 372 | |
John Snow | be1183e | 2020-10-06 19:58:04 -0400 | [diff] [blame] | 373 | if self._qmp_connection: |
John Snow | 671940e | 2020-07-10 01:06:39 -0400 | [diff] [blame] | 374 | self._qmp.close() |
John Snow | be1183e | 2020-10-06 19:58:04 -0400 | [diff] [blame] | 375 | self._qmp_connection = None |
John Snow | 671940e | 2020-07-10 01:06:39 -0400 | [diff] [blame] | 376 | |
Emanuele Giuseppe Esposito | eb7a91d | 2021-08-09 11:01:13 +0200 | [diff] [blame] | 377 | self._close_qemu_log_file() |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 378 | |
Cleber Rosa | 3c1e16c | 2021-02-11 17:01:41 -0500 | [diff] [blame] | 379 | self._load_io_log() |
| 380 | |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 381 | self._qemu_log_path = None |
| 382 | |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 383 | if self._temp_dir is not None: |
| 384 | shutil.rmtree(self._temp_dir) |
| 385 | self._temp_dir = None |
| 386 | |
Max Reitz | 32558ce | 2019-10-17 15:31:34 +0200 | [diff] [blame] | 387 | while len(self._remove_files) > 0: |
| 388 | self._remove_if_exists(self._remove_files.pop()) |
| 389 | |
John Snow | 14661d9 | 2020-07-10 01:06:38 -0400 | [diff] [blame] | 390 | exitcode = self.exitcode() |
John Snow | de6e08b | 2020-07-10 01:06:48 -0400 | [diff] [blame] | 391 | if (exitcode is not None and exitcode < 0 |
| 392 | and not (self._user_killed and exitcode == -signal.SIGKILL)): |
John Snow | 14661d9 | 2020-07-10 01:06:38 -0400 | [diff] [blame] | 393 | msg = 'qemu received signal %i; command: "%s"' |
| 394 | if self._qemu_full_args: |
| 395 | command = ' '.join(self._qemu_full_args) |
| 396 | else: |
| 397 | command = '' |
| 398 | LOG.warning(msg, -int(exitcode), command) |
| 399 | |
John Snow | de6e08b | 2020-07-10 01:06:48 -0400 | [diff] [blame] | 400 | self._user_killed = False |
John Snow | 14661d9 | 2020-07-10 01:06:38 -0400 | [diff] [blame] | 401 | self._launched = False |
| 402 | |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 403 | def launch(self) -> None: |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 404 | """ |
| 405 | Launch the VM and make sure we cleanup and expose the |
| 406 | command line/output in case of exception |
| 407 | """ |
| 408 | |
| 409 | if self._launched: |
| 410 | raise QEMUMachineError('VM already launched') |
| 411 | |
| 412 | self._iolog = None |
John Snow | aad3f3b | 2020-10-06 19:58:06 -0400 | [diff] [blame] | 413 | self._qemu_full_args = () |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 414 | try: |
| 415 | self._launch() |
| 416 | self._launched = True |
| 417 | except: |
John Snow | a3842cb | 2020-07-10 01:06:42 -0400 | [diff] [blame] | 418 | self._post_shutdown() |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 419 | |
| 420 | LOG.debug('Error launching VM') |
| 421 | if self._qemu_full_args: |
| 422 | LOG.debug('Command: %r', ' '.join(self._qemu_full_args)) |
| 423 | if self._iolog: |
| 424 | LOG.debug('Output: %r', self._iolog) |
| 425 | raise |
| 426 | |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 427 | def _launch(self) -> None: |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 428 | """ |
| 429 | Launch the VM and establish a QMP connection |
| 430 | """ |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 431 | self._pre_launch() |
John Snow | aad3f3b | 2020-10-06 19:58:06 -0400 | [diff] [blame] | 432 | self._qemu_full_args = tuple( |
| 433 | chain(self._wrapper, |
| 434 | [self._binary], |
| 435 | self._base_args, |
| 436 | self._args) |
| 437 | ) |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 438 | LOG.debug('VM launch command: %r', ' '.join(self._qemu_full_args)) |
John Snow | a0eae17 | 2021-05-27 17:16:50 -0400 | [diff] [blame] | 439 | |
| 440 | # Cleaning up of this subprocess is guaranteed by _do_shutdown. |
| 441 | # pylint: disable=consider-using-with |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 442 | self._popen = subprocess.Popen(self._qemu_full_args, |
John Snow | 07b7123 | 2021-05-27 17:16:46 -0400 | [diff] [blame] | 443 | stdin=subprocess.DEVNULL, |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 444 | stdout=self._qemu_log_file, |
| 445 | stderr=subprocess.STDOUT, |
| 446 | shell=False, |
| 447 | close_fds=False) |
| 448 | self._post_launch() |
| 449 | |
John Snow | e2c97f1 | 2020-07-10 01:06:40 -0400 | [diff] [blame] | 450 | def _early_cleanup(self) -> None: |
| 451 | """ |
| 452 | Perform any cleanup that needs to happen before the VM exits. |
John Snow | a3842cb | 2020-07-10 01:06:42 -0400 | [diff] [blame] | 453 | |
John Snow | 193bf1c | 2020-07-10 01:06:47 -0400 | [diff] [blame] | 454 | May be invoked by both soft and hard shutdown in failover scenarios. |
John Snow | a3842cb | 2020-07-10 01:06:42 -0400 | [diff] [blame] | 455 | Called additionally by _post_shutdown for comprehensive cleanup. |
John Snow | e2c97f1 | 2020-07-10 01:06:40 -0400 | [diff] [blame] | 456 | """ |
| 457 | # If we keep the console socket open, we may deadlock waiting |
| 458 | # for QEMU to exit, while QEMU is waiting for the socket to |
| 459 | # become writeable. |
| 460 | if self._console_socket is not None: |
| 461 | self._console_socket.close() |
| 462 | self._console_socket = None |
| 463 | |
John Snow | 193bf1c | 2020-07-10 01:06:47 -0400 | [diff] [blame] | 464 | def _hard_shutdown(self) -> None: |
| 465 | """ |
| 466 | Perform early cleanup, kill the VM, and wait for it to terminate. |
| 467 | |
| 468 | :raise subprocess.Timeout: When timeout is exceeds 60 seconds |
| 469 | waiting for the QEMU process to terminate. |
| 470 | """ |
| 471 | self._early_cleanup() |
John Snow | 9223fda | 2020-10-06 19:58:05 -0400 | [diff] [blame] | 472 | self._subp.kill() |
| 473 | self._subp.wait(timeout=60) |
John Snow | 193bf1c | 2020-07-10 01:06:47 -0400 | [diff] [blame] | 474 | |
John Snow | 8226a4b | 2020-07-20 12:02:52 -0400 | [diff] [blame] | 475 | def _soft_shutdown(self, timeout: Optional[int], |
| 476 | has_quit: bool = False) -> None: |
John Snow | 193bf1c | 2020-07-10 01:06:47 -0400 | [diff] [blame] | 477 | """ |
| 478 | Perform early cleanup, attempt to gracefully shut down the VM, and wait |
| 479 | for it to terminate. |
| 480 | |
John Snow | 8226a4b | 2020-07-20 12:02:52 -0400 | [diff] [blame] | 481 | :param timeout: Timeout in seconds for graceful shutdown. |
| 482 | A value of None is an infinite wait. |
John Snow | 193bf1c | 2020-07-10 01:06:47 -0400 | [diff] [blame] | 483 | :param has_quit: When True, don't attempt to issue 'quit' QMP command |
John Snow | 193bf1c | 2020-07-10 01:06:47 -0400 | [diff] [blame] | 484 | |
| 485 | :raise ConnectionReset: On QMP communication errors |
| 486 | :raise subprocess.TimeoutExpired: When timeout is exceeded waiting for |
| 487 | the QEMU process to terminate. |
| 488 | """ |
| 489 | self._early_cleanup() |
| 490 | |
John Snow | be1183e | 2020-10-06 19:58:04 -0400 | [diff] [blame] | 491 | if self._qmp_connection: |
John Snow | 193bf1c | 2020-07-10 01:06:47 -0400 | [diff] [blame] | 492 | if not has_quit: |
| 493 | # Might raise ConnectionReset |
| 494 | self._qmp.cmd('quit') |
| 495 | |
| 496 | # May raise subprocess.TimeoutExpired |
John Snow | 9223fda | 2020-10-06 19:58:05 -0400 | [diff] [blame] | 497 | self._subp.wait(timeout=timeout) |
John Snow | 193bf1c | 2020-07-10 01:06:47 -0400 | [diff] [blame] | 498 | |
John Snow | 8226a4b | 2020-07-20 12:02:52 -0400 | [diff] [blame] | 499 | def _do_shutdown(self, timeout: Optional[int], |
| 500 | has_quit: bool = False) -> None: |
John Snow | 193bf1c | 2020-07-10 01:06:47 -0400 | [diff] [blame] | 501 | """ |
| 502 | Attempt to shutdown the VM gracefully; fallback to a hard shutdown. |
| 503 | |
John Snow | 8226a4b | 2020-07-20 12:02:52 -0400 | [diff] [blame] | 504 | :param timeout: Timeout in seconds for graceful shutdown. |
| 505 | A value of None is an infinite wait. |
John Snow | 193bf1c | 2020-07-10 01:06:47 -0400 | [diff] [blame] | 506 | :param has_quit: When True, don't attempt to issue 'quit' QMP command |
John Snow | 193bf1c | 2020-07-10 01:06:47 -0400 | [diff] [blame] | 507 | |
| 508 | :raise AbnormalShutdown: When the VM could not be shut down gracefully. |
| 509 | The inner exception will likely be ConnectionReset or |
| 510 | subprocess.TimeoutExpired. In rare cases, non-graceful termination |
| 511 | may result in its own exceptions, likely subprocess.TimeoutExpired. |
| 512 | """ |
| 513 | try: |
John Snow | 8226a4b | 2020-07-20 12:02:52 -0400 | [diff] [blame] | 514 | self._soft_shutdown(timeout, has_quit) |
John Snow | 193bf1c | 2020-07-10 01:06:47 -0400 | [diff] [blame] | 515 | except Exception as exc: |
| 516 | self._hard_shutdown() |
| 517 | raise AbnormalShutdown("Could not perform graceful shutdown") \ |
| 518 | from exc |
| 519 | |
John Snow | c9b3045 | 2020-07-10 01:06:43 -0400 | [diff] [blame] | 520 | def shutdown(self, has_quit: bool = False, |
| 521 | hard: bool = False, |
John Snow | 8226a4b | 2020-07-20 12:02:52 -0400 | [diff] [blame] | 522 | timeout: Optional[int] = 30) -> None: |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 523 | """ |
John Snow | 193bf1c | 2020-07-10 01:06:47 -0400 | [diff] [blame] | 524 | Terminate the VM (gracefully if possible) and perform cleanup. |
| 525 | Cleanup will always be performed. |
| 526 | |
| 527 | If the VM has not yet been launched, or shutdown(), wait(), or kill() |
| 528 | have already been called, this method does nothing. |
| 529 | |
| 530 | :param has_quit: When true, do not attempt to issue 'quit' QMP command. |
| 531 | :param hard: When true, do not attempt graceful shutdown, and |
| 532 | suppress the SIGKILL warning log message. |
| 533 | :param timeout: Optional timeout in seconds for graceful shutdown. |
John Snow | 8226a4b | 2020-07-20 12:02:52 -0400 | [diff] [blame] | 534 | Default 30 seconds, A `None` value is an infinite wait. |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 535 | """ |
John Snow | a3842cb | 2020-07-10 01:06:42 -0400 | [diff] [blame] | 536 | if not self._launched: |
| 537 | return |
| 538 | |
John Snow | 193bf1c | 2020-07-10 01:06:47 -0400 | [diff] [blame] | 539 | try: |
Vladimir Sementsov-Ogievskiy | e0e925a | 2020-02-17 18:02:42 +0300 | [diff] [blame] | 540 | if hard: |
John Snow | de6e08b | 2020-07-10 01:06:48 -0400 | [diff] [blame] | 541 | self._user_killed = True |
John Snow | 193bf1c | 2020-07-10 01:06:47 -0400 | [diff] [blame] | 542 | self._hard_shutdown() |
| 543 | else: |
John Snow | 8226a4b | 2020-07-20 12:02:52 -0400 | [diff] [blame] | 544 | self._do_shutdown(timeout, has_quit) |
John Snow | 193bf1c | 2020-07-10 01:06:47 -0400 | [diff] [blame] | 545 | finally: |
| 546 | self._post_shutdown() |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 547 | |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 548 | def kill(self) -> None: |
John Snow | 193bf1c | 2020-07-10 01:06:47 -0400 | [diff] [blame] | 549 | """ |
| 550 | Terminate the VM forcefully, wait for it to exit, and perform cleanup. |
| 551 | """ |
Vladimir Sementsov-Ogievskiy | e0e925a | 2020-02-17 18:02:42 +0300 | [diff] [blame] | 552 | self.shutdown(hard=True) |
| 553 | |
John Snow | 8226a4b | 2020-07-20 12:02:52 -0400 | [diff] [blame] | 554 | def wait(self, timeout: Optional[int] = 30) -> None: |
John Snow | 8952805 | 2020-07-10 01:06:44 -0400 | [diff] [blame] | 555 | """ |
| 556 | Wait for the VM to power off and perform post-shutdown cleanup. |
| 557 | |
John Snow | 8226a4b | 2020-07-20 12:02:52 -0400 | [diff] [blame] | 558 | :param timeout: Optional timeout in seconds. Default 30 seconds. |
| 559 | A value of `None` is an infinite wait. |
John Snow | 8952805 | 2020-07-10 01:06:44 -0400 | [diff] [blame] | 560 | """ |
| 561 | self.shutdown(has_quit=True, timeout=timeout) |
| 562 | |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 563 | def set_qmp_monitor(self, enabled: bool = True) -> None: |
Wainer dos Santos Moschetta | 74b56bb | 2019-12-11 13:55:35 -0500 | [diff] [blame] | 564 | """ |
| 565 | Set the QMP monitor. |
| 566 | |
| 567 | @param enabled: if False, qmp monitor options will be removed from |
| 568 | the base arguments of the resulting QEMU command |
| 569 | line. Default is True. |
John Snow | 5c02c86 | 2021-06-29 17:43:23 -0400 | [diff] [blame] | 570 | |
| 571 | .. note:: Call this function before launch(). |
Wainer dos Santos Moschetta | 74b56bb | 2019-12-11 13:55:35 -0500 | [diff] [blame] | 572 | """ |
John Snow | be1183e | 2020-10-06 19:58:04 -0400 | [diff] [blame] | 573 | self._qmp_set = enabled |
| 574 | |
| 575 | @property |
John Snow | beb6b57 | 2021-05-27 17:16:53 -0400 | [diff] [blame] | 576 | def _qmp(self) -> QEMUMonitorProtocol: |
John Snow | be1183e | 2020-10-06 19:58:04 -0400 | [diff] [blame] | 577 | if self._qmp_connection is None: |
| 578 | raise QEMUMachineError("Attempt to access QMP with no connection") |
| 579 | return self._qmp_connection |
Wainer dos Santos Moschetta | 74b56bb | 2019-12-11 13:55:35 -0500 | [diff] [blame] | 580 | |
John Snow | aaa81ec | 2020-10-06 19:58:03 -0400 | [diff] [blame] | 581 | @classmethod |
Vladimir Sementsov-Ogievskiy | c7daa57 | 2021-08-24 11:38:45 +0300 | [diff] [blame] | 582 | def _qmp_args(cls, conv_keys: bool, |
| 583 | args: Dict[str, Any]) -> Dict[str, object]: |
| 584 | if conv_keys: |
| 585 | return {k.replace('_', '-'): v for k, v in args.items()} |
| 586 | |
| 587 | return args |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 588 | |
John Snow | aaa81ec | 2020-10-06 19:58:03 -0400 | [diff] [blame] | 589 | def qmp(self, cmd: str, |
Vladimir Sementsov-Ogievskiy | 3f3c9b4 | 2021-08-24 11:38:46 +0300 | [diff] [blame] | 590 | args_dict: Optional[Dict[str, object]] = None, |
| 591 | conv_keys: Optional[bool] = None, |
John Snow | aaa81ec | 2020-10-06 19:58:03 -0400 | [diff] [blame] | 592 | **args: Any) -> QMPMessage: |
| 593 | """ |
| 594 | Invoke a QMP command and return the response dict |
| 595 | """ |
Vladimir Sementsov-Ogievskiy | 3f3c9b4 | 2021-08-24 11:38:46 +0300 | [diff] [blame] | 596 | if args_dict is not None: |
| 597 | assert not args |
| 598 | assert conv_keys is None |
| 599 | args = args_dict |
| 600 | conv_keys = False |
| 601 | |
| 602 | if conv_keys is None: |
| 603 | conv_keys = True |
| 604 | |
Vladimir Sementsov-Ogievskiy | c7daa57 | 2021-08-24 11:38:45 +0300 | [diff] [blame] | 605 | qmp_args = self._qmp_args(conv_keys, args) |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 606 | return self._qmp.cmd(cmd, args=qmp_args) |
| 607 | |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 608 | def command(self, cmd: str, |
| 609 | conv_keys: bool = True, |
| 610 | **args: Any) -> QMPReturnValue: |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 611 | """ |
| 612 | Invoke a QMP command. |
| 613 | On success return the response dict. |
| 614 | On failure raise an exception. |
| 615 | """ |
Vladimir Sementsov-Ogievskiy | c7daa57 | 2021-08-24 11:38:45 +0300 | [diff] [blame] | 616 | qmp_args = self._qmp_args(conv_keys, args) |
John Snow | aaa81ec | 2020-10-06 19:58:03 -0400 | [diff] [blame] | 617 | return self._qmp.command(cmd, **qmp_args) |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 618 | |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 619 | def get_qmp_event(self, wait: bool = False) -> Optional[QMPMessage]: |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 620 | """ |
| 621 | Poll for one queued QMP events and return it |
| 622 | """ |
John Snow | 306dfcd | 2019-06-27 17:28:15 -0400 | [diff] [blame] | 623 | if self._events: |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 624 | return self._events.pop(0) |
| 625 | return self._qmp.pull_event(wait=wait) |
| 626 | |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 627 | def get_qmp_events(self, wait: bool = False) -> List[QMPMessage]: |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 628 | """ |
| 629 | Poll for queued QMP events and return a list of dicts |
| 630 | """ |
| 631 | events = self._qmp.get_events(wait=wait) |
| 632 | events.extend(self._events) |
| 633 | del self._events[:] |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 634 | return events |
| 635 | |
| 636 | @staticmethod |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 637 | def event_match(event: Any, match: Optional[Any]) -> bool: |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 638 | """ |
| 639 | Check if an event matches optional match criteria. |
| 640 | |
| 641 | The match criteria takes the form of a matching subdict. The event is |
| 642 | checked to be a superset of the subdict, recursively, with matching |
| 643 | values whenever the subdict values are not None. |
| 644 | |
| 645 | This has a limitation that you cannot explicitly check for None values. |
| 646 | |
| 647 | Examples, with the subdict queries on the left: |
| 648 | - None matches any object. |
| 649 | - {"foo": None} matches {"foo": {"bar": 1}} |
| 650 | - {"foo": None} matches {"foo": 5} |
| 651 | - {"foo": {"abc": None}} does not match {"foo": {"bar": 1}} |
| 652 | - {"foo": {"rab": 2}} matches {"foo": {"bar": 1, "rab": 2}} |
| 653 | """ |
| 654 | if match is None: |
| 655 | return True |
| 656 | |
| 657 | try: |
| 658 | for key in match: |
| 659 | if key in event: |
| 660 | if not QEMUMachine.event_match(event[key], match[key]): |
| 661 | return False |
| 662 | else: |
| 663 | return False |
| 664 | return True |
| 665 | except TypeError: |
| 666 | # either match or event wasn't iterable (not a dict) |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 667 | return bool(match == event) |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 668 | |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 669 | def event_wait(self, name: str, |
| 670 | timeout: float = 60.0, |
| 671 | match: Optional[QMPMessage] = None) -> Optional[QMPMessage]: |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 672 | """ |
| 673 | event_wait waits for and returns a named event from QMP with a timeout. |
| 674 | |
| 675 | name: The event to wait for. |
| 676 | timeout: QEMUMonitorProtocol.pull_event timeout parameter. |
| 677 | match: Optional match criteria. See event_match for details. |
| 678 | """ |
| 679 | return self.events_wait([(name, match)], timeout) |
| 680 | |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 681 | def events_wait(self, |
| 682 | events: Sequence[Tuple[str, Any]], |
| 683 | timeout: float = 60.0) -> Optional[QMPMessage]: |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 684 | """ |
John Snow | 1847a4a | 2020-10-06 19:58:02 -0400 | [diff] [blame] | 685 | events_wait waits for and returns a single named event from QMP. |
| 686 | In the case of multiple qualifying events, this function returns the |
| 687 | first one. |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 688 | |
John Snow | 1847a4a | 2020-10-06 19:58:02 -0400 | [diff] [blame] | 689 | :param events: A sequence of (name, match_criteria) tuples. |
| 690 | The match criteria are optional and may be None. |
| 691 | See event_match for details. |
| 692 | :param timeout: Optional timeout, in seconds. |
| 693 | See QEMUMonitorProtocol.pull_event. |
| 694 | |
| 695 | :raise QMPTimeoutError: If timeout was non-zero and no matching events |
| 696 | were found. |
| 697 | :return: A QMP event matching the filter criteria. |
| 698 | If timeout was 0 and no event matched, None. |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 699 | """ |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 700 | def _match(event: QMPMessage) -> bool: |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 701 | for name, match in events: |
John Snow | 306dfcd | 2019-06-27 17:28:15 -0400 | [diff] [blame] | 702 | if event['event'] == name and self.event_match(event, match): |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 703 | return True |
| 704 | return False |
| 705 | |
John Snow | 1847a4a | 2020-10-06 19:58:02 -0400 | [diff] [blame] | 706 | event: Optional[QMPMessage] |
| 707 | |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 708 | # Search cached events |
| 709 | for event in self._events: |
| 710 | if _match(event): |
| 711 | self._events.remove(event) |
| 712 | return event |
| 713 | |
| 714 | # Poll for new events |
| 715 | while True: |
| 716 | event = self._qmp.pull_event(wait=timeout) |
John Snow | 1847a4a | 2020-10-06 19:58:02 -0400 | [diff] [blame] | 717 | if event is None: |
| 718 | # NB: None is only returned when timeout is false-ish. |
| 719 | # Timeouts raise QMPTimeoutError instead! |
| 720 | break |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 721 | if _match(event): |
| 722 | return event |
| 723 | self._events.append(event) |
| 724 | |
| 725 | return None |
| 726 | |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 727 | def get_log(self) -> Optional[str]: |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 728 | """ |
| 729 | After self.shutdown or failed qemu execution, this returns the output |
| 730 | of the qemu process. |
| 731 | """ |
| 732 | return self._iolog |
| 733 | |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 734 | def add_args(self, *args: str) -> None: |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 735 | """ |
| 736 | Adds to the list of extra arguments to be given to the QEMU binary |
| 737 | """ |
| 738 | self._args.extend(args) |
| 739 | |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 740 | def set_machine(self, machine_type: str) -> None: |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 741 | """ |
| 742 | Sets the machine type |
| 743 | |
| 744 | If set, the machine type will be added to the base arguments |
| 745 | of the resulting QEMU command line. |
| 746 | """ |
| 747 | self._machine = machine_type |
| 748 | |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 749 | def set_console(self, |
| 750 | device_type: Optional[str] = None, |
| 751 | console_index: int = 0) -> None: |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 752 | """ |
| 753 | Sets the device type for a console device |
| 754 | |
| 755 | If set, the console device and a backing character device will |
| 756 | be added to the base arguments of the resulting QEMU command |
| 757 | line. |
| 758 | |
| 759 | This is a convenience method that will either use the provided |
| 760 | device type, or default to a "-serial chardev:console" command |
| 761 | line argument. |
| 762 | |
| 763 | The actual setting of command line arguments will be be done at |
| 764 | machine launch time, as it depends on the temporary directory |
| 765 | to be created. |
| 766 | |
| 767 | @param device_type: the device type, such as "isa-serial". If |
| 768 | None is given (the default value) a "-serial |
| 769 | chardev:console" command line argument will |
| 770 | be used instead, resorting to the machine's |
| 771 | default device type. |
Philippe Mathieu-Daudé | 746f244 | 2020-01-21 00:51:56 +0100 | [diff] [blame] | 772 | @param console_index: the index of the console device to use. |
| 773 | If not zero, the command line will create |
| 774 | 'index - 1' consoles and connect them to |
| 775 | the 'null' backing character device. |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 776 | """ |
| 777 | self._console_set = True |
| 778 | self._console_device_type = device_type |
Philippe Mathieu-Daudé | 746f244 | 2020-01-21 00:51:56 +0100 | [diff] [blame] | 779 | self._console_index = console_index |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 780 | |
| 781 | @property |
John Snow | f12a282 | 2020-10-06 19:58:08 -0400 | [diff] [blame] | 782 | def console_socket(self) -> socket.socket: |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 783 | """ |
| 784 | Returns a socket connected to the console |
| 785 | """ |
| 786 | if self._console_socket is None: |
Robert Foley | 80ded8e | 2020-07-24 07:45:08 +0100 | [diff] [blame] | 787 | self._console_socket = console_socket.ConsoleSocket( |
| 788 | self._console_address, |
| 789 | file=self._console_log_path, |
| 790 | drain=self._drain_console) |
John Snow | abf0bf9 | 2019-06-27 17:28:14 -0400 | [diff] [blame] | 791 | return self._console_socket |
Cleber Rosa | 2ca6e26 | 2021-02-11 17:01:42 -0500 | [diff] [blame] | 792 | |
| 793 | @property |
| 794 | def temp_dir(self) -> str: |
| 795 | """ |
| 796 | Returns a temporary directory to be used for this machine |
| 797 | """ |
| 798 | if self._temp_dir is None: |
| 799 | self._temp_dir = tempfile.mkdtemp(prefix="qemu-machine-", |
| 800 | dir=self._base_temp_dir) |
| 801 | return self._temp_dir |
Cleber Rosa | b306e26 | 2021-02-11 16:55:05 -0500 | [diff] [blame] | 802 | |
| 803 | @property |
| 804 | def log_dir(self) -> str: |
| 805 | """ |
| 806 | Returns a directory to be used for writing logs |
| 807 | """ |
| 808 | if self._log_dir is None: |
| 809 | return self.temp_dir |
| 810 | return self._log_dir |