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