blob: ad529fd92a6022150fd0156d005d6c7175565574 [file] [log] [blame]
John Snow306dfcd2019-06-27 17:28:15 -04001"""
2QEMU machine module:
3
4The machine module primarily provides the QEMUMachine class,
5which provides facilities for managing the lifetime of a QEMU VM.
6"""
7
John Snowabf0bf92019-06-27 17:28:14 -04008# 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
20import errno
John Snowaad3f3b2020-10-06 19:58:06 -040021from itertools import chain
John Snow5690b432021-09-16 14:22:47 -040022import locale
John Snowabf0bf92019-06-27 17:28:14 -040023import logging
24import os
John Snowabf0bf92019-06-27 17:28:14 -040025import shutil
John Snowde6e08b2020-07-10 01:06:48 -040026import signal
John Snowf12a2822020-10-06 19:58:08 -040027import socket
John Snow932ca4b2020-10-06 19:57:58 -040028import subprocess
John Snowabf0bf92019-06-27 17:28:14 -040029import tempfile
John Snow1dda0402020-05-14 01:53:44 -040030from types import TracebackType
John Snowaaa81ec2020-10-06 19:58:03 -040031from typing import (
32 Any,
John Snowf12a2822020-10-06 19:58:08 -040033 BinaryIO,
John Snowaaa81ec2020-10-06 19:58:03 -040034 Dict,
35 List,
36 Optional,
John Snowaad3f3b2020-10-06 19:58:06 -040037 Sequence,
38 Tuple,
John Snowaaa81ec2020-10-06 19:58:03 -040039 Type,
Vladimir Sementsov-Ogievskiy15c3b862021-08-24 11:38:47 +030040 TypeVar,
John Snowaaa81ec2020-10-06 19:58:03 -040041)
John Snowabf0bf92019-06-27 17:28:14 -040042
John Snowd1e04762021-05-27 17:16:59 -040043from qemu.qmp import ( # pylint: disable=import-error
John Snowbeb6b572021-05-27 17:16:53 -040044 QMPMessage,
45 QMPReturnValue,
46 SocketAddrT,
47)
48
49from . import console_socket
John Snow932ca4b2020-10-06 19:57:58 -040050
John Snowabf0bf92019-06-27 17:28:14 -040051
John Snow76cd3582021-10-26 13:56:12 -040052if os.environ.get('QEMU_PYTHON_LEGACY_QMP'):
53 from qemu.qmp import QEMUMonitorProtocol
54else:
55 from qemu.aqmp.legacy import QEMUMonitorProtocol
56
57
John Snowabf0bf92019-06-27 17:28:14 -040058LOG = logging.getLogger(__name__)
59
John Snow8dfac2e2020-05-28 18:21:29 -040060
John Snowabf0bf92019-06-27 17:28:14 -040061class QEMUMachineError(Exception):
62 """
63 Exception called when an error in QEMUMachine happens.
64 """
65
66
67class QEMUMachineAddDeviceError(QEMUMachineError):
68 """
69 Exception raised when a request to add a device can not be fulfilled
70
71 The failures are caused by limitations, lack of information or conflicting
72 requests on the QEMUMachine methods. This exception does not represent
73 failures reported by the QEMU binary itself.
74 """
75
76
John Snow193bf1c2020-07-10 01:06:47 -040077class AbnormalShutdown(QEMUMachineError):
78 """
79 Exception raised when a graceful shutdown was requested, but not performed.
80 """
81
82
Vladimir Sementsov-Ogievskiy15c3b862021-08-24 11:38:47 +030083_T = TypeVar('_T', bound='QEMUMachine')
84
85
John Snow9b8ccd62020-05-28 18:21:28 -040086class QEMUMachine:
John Snowabf0bf92019-06-27 17:28:14 -040087 """
John Snowf12a2822020-10-06 19:58:08 -040088 A QEMU VM.
John Snowabf0bf92019-06-27 17:28:14 -040089
John Snow8dfac2e2020-05-28 18:21:29 -040090 Use this object as a context manager to ensure
91 the QEMU process terminates::
John Snowabf0bf92019-06-27 17:28:14 -040092
93 with VM(binary) as vm:
94 ...
95 # vm is guaranteed to be shut down here
96 """
John Snow82e65172021-06-29 17:43:11 -040097 # pylint: disable=too-many-instance-attributes, too-many-public-methods
John Snowabf0bf92019-06-27 17:28:14 -040098
John Snowaad3f3b2020-10-06 19:58:06 -040099 def __init__(self,
100 binary: str,
101 args: Sequence[str] = (),
102 wrapper: Sequence[str] = (),
103 name: Optional[str] = None,
Cleber Rosa2ca6e262021-02-11 17:01:42 -0500104 base_temp_dir: str = "/var/tmp",
John Snowc4e60232020-10-06 19:57:59 -0400105 monitor_address: Optional[SocketAddrT] = None,
John Snowf12a2822020-10-06 19:58:08 -0400106 sock_dir: Optional[str] = None,
107 drain_console: bool = False,
Cleber Rosab306e262021-02-11 16:55:05 -0500108 console_log: Optional[str] = None,
Emanuele Giuseppe Espositoe2f948a2021-08-09 11:00:59 +0200109 log_dir: Optional[str] = None,
110 qmp_timer: Optional[float] = None):
John Snowabf0bf92019-06-27 17:28:14 -0400111 '''
112 Initialize a QEMUMachine
113
114 @param binary: path to the qemu binary
115 @param args: list of extra arguments
116 @param wrapper: list of arguments used as prefix to qemu binary
117 @param name: prefix for socket and log file names (default: qemu-PID)
John Snow859aeb62021-05-27 17:16:51 -0400118 @param base_temp_dir: default location where temp files are created
John Snowabf0bf92019-06-27 17:28:14 -0400119 @param monitor_address: address for QMP monitor
Cleber Rosa2ca6e262021-02-11 17:01:42 -0500120 @param sock_dir: where to create socket (defaults to base_temp_dir)
Robert Foley0fc8f662020-07-01 14:56:24 +0100121 @param drain_console: (optional) True to drain console socket to buffer
John Snowc5e61a62020-10-06 19:58:00 -0400122 @param console_log: (optional) path to console log file
Cleber Rosab306e262021-02-11 16:55:05 -0500123 @param log_dir: where to create and keep log files
Emanuele Giuseppe Espositoe2f948a2021-08-09 11:00:59 +0200124 @param qmp_timer: (optional) default QMP socket timeout
John Snowabf0bf92019-06-27 17:28:14 -0400125 @note: Qemu process is not started until launch() is used.
126 '''
John Snow82e65172021-06-29 17:43:11 -0400127 # pylint: disable=too-many-arguments
128
John Snowc5e61a62020-10-06 19:58:00 -0400129 # Direct user configuration
130
131 self._binary = binary
John Snowc5e61a62020-10-06 19:58:00 -0400132 self._args = list(args)
John Snowc5e61a62020-10-06 19:58:00 -0400133 self._wrapper = wrapper
Emanuele Giuseppe Espositoe2f948a2021-08-09 11:00:59 +0200134 self._qmp_timer = qmp_timer
John Snowc5e61a62020-10-06 19:58:00 -0400135
John Snow72b17fe2021-11-18 15:46:16 -0500136 self._name = name or f"qemu-{os.getpid()}-{id(self):02x}"
John Snow87bf1fe2021-11-18 15:46:14 -0500137 self._temp_dir: Optional[str] = None
Cleber Rosa2ca6e262021-02-11 17:01:42 -0500138 self._base_temp_dir = base_temp_dir
John Snow87bf1fe2021-11-18 15:46:14 -0500139 self._sock_dir = sock_dir
Cleber Rosab306e262021-02-11 16:55:05 -0500140 self._log_dir = log_dir
John Snowc5e61a62020-10-06 19:58:00 -0400141
John Snowc4e60232020-10-06 19:57:59 -0400142 if monitor_address is not None:
143 self._monitor_address = monitor_address
John Snowc4e60232020-10-06 19:57:59 -0400144 else:
145 self._monitor_address = os.path.join(
John Snow87bf1fe2021-11-18 15:46:14 -0500146 self.sock_dir, f"{self._name}-monitor.sock"
John Snowc4e60232020-10-06 19:57:59 -0400147 )
John Snowc5e61a62020-10-06 19:58:00 -0400148
149 self._console_log_path = console_log
150 if self._console_log_path:
151 # In order to log the console, buffering needs to be enabled.
152 self._drain_console = True
153 else:
154 self._drain_console = drain_console
155
156 # Runstate
John Snowf12a2822020-10-06 19:58:08 -0400157 self._qemu_log_path: Optional[str] = None
158 self._qemu_log_file: Optional[BinaryIO] = None
John Snow9223fda2020-10-06 19:58:05 -0400159 self._popen: Optional['subprocess.Popen[bytes]'] = None
John Snowf12a2822020-10-06 19:58:08 -0400160 self._events: List[QMPMessage] = []
161 self._iolog: Optional[str] = None
Wainer dos Santos Moschetta74b56bb2019-12-11 13:55:35 -0500162 self._qmp_set = True # Enable QMP monitor by default.
John Snowbeb6b572021-05-27 17:16:53 -0400163 self._qmp_connection: Optional[QEMUMonitorProtocol] = None
John Snowaad3f3b2020-10-06 19:58:06 -0400164 self._qemu_full_args: Tuple[str, ...] = ()
John Snowabf0bf92019-06-27 17:28:14 -0400165 self._launched = False
John Snowf12a2822020-10-06 19:58:08 -0400166 self._machine: Optional[str] = None
Philippe Mathieu-Daudé746f2442020-01-21 00:51:56 +0100167 self._console_index = 0
John Snowabf0bf92019-06-27 17:28:14 -0400168 self._console_set = False
John Snowf12a2822020-10-06 19:58:08 -0400169 self._console_device_type: Optional[str] = None
John Snow652809d2020-10-06 19:58:01 -0400170 self._console_address = os.path.join(
John Snow87bf1fe2021-11-18 15:46:14 -0500171 self.sock_dir, f"{self._name}-console.sock"
John Snow652809d2020-10-06 19:58:01 -0400172 )
John Snowf12a2822020-10-06 19:58:08 -0400173 self._console_socket: Optional[socket.socket] = None
174 self._remove_files: List[str] = []
John Snowde6e08b2020-07-10 01:06:48 -0400175 self._user_killed = False
John Snowb9420e42021-10-26 13:56:05 -0400176 self._quit_issued = False
John Snowabf0bf92019-06-27 17:28:14 -0400177
Vladimir Sementsov-Ogievskiy15c3b862021-08-24 11:38:47 +0300178 def __enter__(self: _T) -> _T:
John Snowabf0bf92019-06-27 17:28:14 -0400179 return self
180
John Snow1dda0402020-05-14 01:53:44 -0400181 def __exit__(self,
182 exc_type: Optional[Type[BaseException]],
183 exc_val: Optional[BaseException],
184 exc_tb: Optional[TracebackType]) -> None:
John Snowabf0bf92019-06-27 17:28:14 -0400185 self.shutdown()
John Snowabf0bf92019-06-27 17:28:14 -0400186
John Snowf12a2822020-10-06 19:58:08 -0400187 def add_monitor_null(self) -> None:
John Snow306dfcd2019-06-27 17:28:15 -0400188 """
189 This can be used to add an unused monitor instance.
190 """
John Snowabf0bf92019-06-27 17:28:14 -0400191 self._args.append('-monitor')
192 self._args.append('null')
193
Vladimir Sementsov-Ogievskiy15c3b862021-08-24 11:38:47 +0300194 def add_fd(self: _T, fd: int, fdset: int,
195 opaque: str, opts: str = '') -> _T:
John Snowabf0bf92019-06-27 17:28:14 -0400196 """
197 Pass a file descriptor to the VM
198 """
199 options = ['fd=%d' % fd,
200 'set=%d' % fdset,
201 'opaque=%s' % opaque]
202 if opts:
203 options.append(opts)
204
205 # This did not exist before 3.4, but since then it is
206 # mandatory for our purpose
207 if hasattr(os, 'set_inheritable'):
208 os.set_inheritable(fd, True)
209
210 self._args.append('-add-fd')
211 self._args.append(','.join(options))
212 return self
213
John Snowf12a2822020-10-06 19:58:08 -0400214 def send_fd_scm(self, fd: Optional[int] = None,
215 file_path: Optional[str] = None) -> int:
John Snow306dfcd2019-06-27 17:28:15 -0400216 """
John Snow514d00d2021-09-22 20:49:30 -0400217 Send an fd or file_path to the remote via SCM_RIGHTS.
John Snow306dfcd2019-06-27 17:28:15 -0400218
John Snow514d00d2021-09-22 20:49:30 -0400219 Exactly one of fd and file_path must be given. If it is
220 file_path, the file will be opened read-only and the new file
221 descriptor will be sent to the remote.
John Snow306dfcd2019-06-27 17:28:15 -0400222 """
John Snowabf0bf92019-06-27 17:28:14 -0400223 if file_path is not None:
224 assert fd is None
John Snow514d00d2021-09-22 20:49:30 -0400225 with open(file_path, "rb") as passfile:
226 fd = passfile.fileno()
227 self._qmp.send_fd_scm(fd)
John Snowabf0bf92019-06-27 17:28:14 -0400228 else:
229 assert fd is not None
John Snow514d00d2021-09-22 20:49:30 -0400230 self._qmp.send_fd_scm(fd)
John Snowabf0bf92019-06-27 17:28:14 -0400231
John Snow514d00d2021-09-22 20:49:30 -0400232 return 0
John Snowabf0bf92019-06-27 17:28:14 -0400233
234 @staticmethod
John Snowf12a2822020-10-06 19:58:08 -0400235 def _remove_if_exists(path: str) -> None:
John Snowabf0bf92019-06-27 17:28:14 -0400236 """
237 Remove file object at path if it exists
238 """
239 try:
240 os.remove(path)
241 except OSError as exception:
242 if exception.errno == errno.ENOENT:
243 return
244 raise
245
John Snowf12a2822020-10-06 19:58:08 -0400246 def is_running(self) -> bool:
John Snow306dfcd2019-06-27 17:28:15 -0400247 """Returns true if the VM is running."""
John Snowabf0bf92019-06-27 17:28:14 -0400248 return self._popen is not None and self._popen.poll() is None
249
John Snow9223fda2020-10-06 19:58:05 -0400250 @property
251 def _subp(self) -> 'subprocess.Popen[bytes]':
252 if self._popen is None:
253 raise QEMUMachineError('Subprocess pipe not present')
254 return self._popen
255
John Snowf12a2822020-10-06 19:58:08 -0400256 def exitcode(self) -> Optional[int]:
John Snow306dfcd2019-06-27 17:28:15 -0400257 """Returns the exit code if possible, or None."""
John Snowabf0bf92019-06-27 17:28:14 -0400258 if self._popen is None:
259 return None
260 return self._popen.poll()
261
John Snowf12a2822020-10-06 19:58:08 -0400262 def get_pid(self) -> Optional[int]:
John Snow306dfcd2019-06-27 17:28:15 -0400263 """Returns the PID of the running process, or None."""
John Snowabf0bf92019-06-27 17:28:14 -0400264 if not self.is_running():
265 return None
John Snow9223fda2020-10-06 19:58:05 -0400266 return self._subp.pid
John Snowabf0bf92019-06-27 17:28:14 -0400267
John Snowf12a2822020-10-06 19:58:08 -0400268 def _load_io_log(self) -> None:
John Snow5690b432021-09-16 14:22:47 -0400269 # Assume that the output encoding of QEMU's terminal output is
270 # defined by our locale. If indeterminate, allow open() to fall
271 # back to the platform default.
272 _, encoding = locale.getlocale()
John Snowabf0bf92019-06-27 17:28:14 -0400273 if self._qemu_log_path is not None:
John Snow5690b432021-09-16 14:22:47 -0400274 with open(self._qemu_log_path, "r", encoding=encoding) as iolog:
John Snowabf0bf92019-06-27 17:28:14 -0400275 self._iolog = iolog.read()
276
John Snow652809d2020-10-06 19:58:01 -0400277 @property
278 def _base_args(self) -> List[str]:
Wainer dos Santos Moschetta74b56bb2019-12-11 13:55:35 -0500279 args = ['-display', 'none', '-vga', 'none']
John Snowc4e60232020-10-06 19:57:59 -0400280
Wainer dos Santos Moschetta74b56bb2019-12-11 13:55:35 -0500281 if self._qmp_set:
282 if isinstance(self._monitor_address, tuple):
John Snowc4e60232020-10-06 19:57:59 -0400283 moncdev = "socket,id=mon,host={},port={}".format(
284 *self._monitor_address
285 )
Wainer dos Santos Moschetta74b56bb2019-12-11 13:55:35 -0500286 else:
John Snowc4e60232020-10-06 19:57:59 -0400287 moncdev = f"socket,id=mon,path={self._monitor_address}"
Wainer dos Santos Moschetta74b56bb2019-12-11 13:55:35 -0500288 args.extend(['-chardev', moncdev, '-mon',
289 'chardev=mon,mode=control'])
John Snowc4e60232020-10-06 19:57:59 -0400290
John Snowabf0bf92019-06-27 17:28:14 -0400291 if self._machine is not None:
292 args.extend(['-machine', self._machine])
John Snow9b8ccd62020-05-28 18:21:28 -0400293 for _ in range(self._console_index):
Philippe Mathieu-Daudé746f2442020-01-21 00:51:56 +0100294 args.extend(['-serial', 'null'])
John Snowabf0bf92019-06-27 17:28:14 -0400295 if self._console_set:
Paolo Bonzini991c1802020-11-13 03:10:52 -0500296 chardev = ('socket,id=console,path=%s,server=on,wait=off' %
John Snowabf0bf92019-06-27 17:28:14 -0400297 self._console_address)
298 args.extend(['-chardev', chardev])
299 if self._console_device_type is None:
300 args.extend(['-serial', 'chardev:console'])
301 else:
302 device = '%s,chardev=console' % self._console_device_type
303 args.extend(['-device', device])
304 return args
305
Wainer dos Santos Moschetta555fe0c2021-04-30 10:34:12 -0300306 @property
307 def args(self) -> List[str]:
308 """Returns the list of arguments given to the QEMU binary."""
309 return self._args
310
John Snowf12a2822020-10-06 19:58:08 -0400311 def _pre_launch(self) -> None:
John Snow652809d2020-10-06 19:58:01 -0400312 if self._console_set:
313 self._remove_files.append(self._console_address)
314
Wainer dos Santos Moschetta74b56bb2019-12-11 13:55:35 -0500315 if self._qmp_set:
John Snow6eeb3de2021-11-18 15:46:15 -0500316 if isinstance(self._monitor_address, str):
John Snowc4e60232020-10-06 19:57:59 -0400317 self._remove_files.append(self._monitor_address)
John Snowbeb6b572021-05-27 17:16:53 -0400318 self._qmp_connection = QEMUMonitorProtocol(
John Snowc4e60232020-10-06 19:57:59 -0400319 self._monitor_address,
320 server=True,
321 nickname=self._name
322 )
John Snowabf0bf92019-06-27 17:28:14 -0400323
John Snow63c33f32021-05-27 17:16:49 -0400324 # NOTE: Make sure any opened resources are *definitely* freed in
325 # _post_shutdown()!
326 # pylint: disable=consider-using-with
Cleber Rosab306e262021-02-11 16:55:05 -0500327 self._qemu_log_path = os.path.join(self.log_dir, self._name + ".log")
John Snow63c33f32021-05-27 17:16:49 -0400328 self._qemu_log_file = open(self._qemu_log_path, 'wb')
329
John Snowf12a2822020-10-06 19:58:08 -0400330 def _post_launch(self) -> None:
John Snowbe1183e2020-10-06 19:58:04 -0400331 if self._qmp_connection:
Emanuele Giuseppe Espositoe2f948a2021-08-09 11:00:59 +0200332 self._qmp.accept(self._qmp_timer)
John Snowabf0bf92019-06-27 17:28:14 -0400333
Emanuele Giuseppe Espositoeb7a91d2021-08-09 11:01:13 +0200334 def _close_qemu_log_file(self) -> None:
335 if self._qemu_log_file is not None:
336 self._qemu_log_file.close()
337 self._qemu_log_file = None
338
John Snowf12a2822020-10-06 19:58:08 -0400339 def _post_shutdown(self) -> None:
John Snowa3842cb2020-07-10 01:06:42 -0400340 """
341 Called to cleanup the VM instance after the process has exited.
342 May also be called after a failed launch.
343 """
344 # Comprehensive reset for the failed launch case:
345 self._early_cleanup()
346
John Snow49a608b2021-10-26 13:56:06 -0400347 try:
348 self._close_qmp_connection()
349 except Exception as err: # pylint: disable=broad-except
350 LOG.warning(
351 "Exception closing QMP connection: %s",
352 str(err) if str(err) else type(err).__name__
353 )
354 finally:
355 assert self._qmp_connection is None
John Snow671940e2020-07-10 01:06:39 -0400356
Emanuele Giuseppe Espositoeb7a91d2021-08-09 11:01:13 +0200357 self._close_qemu_log_file()
John Snowabf0bf92019-06-27 17:28:14 -0400358
Cleber Rosa3c1e16c2021-02-11 17:01:41 -0500359 self._load_io_log()
360
John Snowabf0bf92019-06-27 17:28:14 -0400361 self._qemu_log_path = None
362
John Snowabf0bf92019-06-27 17:28:14 -0400363 if self._temp_dir is not None:
364 shutil.rmtree(self._temp_dir)
365 self._temp_dir = None
366
Max Reitz32558ce2019-10-17 15:31:34 +0200367 while len(self._remove_files) > 0:
368 self._remove_if_exists(self._remove_files.pop())
369
John Snow14661d92020-07-10 01:06:38 -0400370 exitcode = self.exitcode()
John Snowde6e08b2020-07-10 01:06:48 -0400371 if (exitcode is not None and exitcode < 0
372 and not (self._user_killed and exitcode == -signal.SIGKILL)):
John Snow14661d92020-07-10 01:06:38 -0400373 msg = 'qemu received signal %i; command: "%s"'
374 if self._qemu_full_args:
375 command = ' '.join(self._qemu_full_args)
376 else:
377 command = ''
378 LOG.warning(msg, -int(exitcode), command)
379
John Snowb9420e42021-10-26 13:56:05 -0400380 self._quit_issued = False
John Snowde6e08b2020-07-10 01:06:48 -0400381 self._user_killed = False
John Snow14661d92020-07-10 01:06:38 -0400382 self._launched = False
383
John Snowf12a2822020-10-06 19:58:08 -0400384 def launch(self) -> None:
John Snowabf0bf92019-06-27 17:28:14 -0400385 """
386 Launch the VM and make sure we cleanup and expose the
387 command line/output in case of exception
388 """
389
390 if self._launched:
391 raise QEMUMachineError('VM already launched')
392
393 self._iolog = None
John Snowaad3f3b2020-10-06 19:58:06 -0400394 self._qemu_full_args = ()
John Snowabf0bf92019-06-27 17:28:14 -0400395 try:
396 self._launch()
397 self._launched = True
398 except:
John Snowa3842cb2020-07-10 01:06:42 -0400399 self._post_shutdown()
John Snowabf0bf92019-06-27 17:28:14 -0400400
401 LOG.debug('Error launching VM')
402 if self._qemu_full_args:
403 LOG.debug('Command: %r', ' '.join(self._qemu_full_args))
404 if self._iolog:
405 LOG.debug('Output: %r', self._iolog)
406 raise
407
John Snowf12a2822020-10-06 19:58:08 -0400408 def _launch(self) -> None:
John Snowabf0bf92019-06-27 17:28:14 -0400409 """
410 Launch the VM and establish a QMP connection
411 """
John Snowabf0bf92019-06-27 17:28:14 -0400412 self._pre_launch()
John Snowaad3f3b2020-10-06 19:58:06 -0400413 self._qemu_full_args = tuple(
414 chain(self._wrapper,
415 [self._binary],
416 self._base_args,
417 self._args)
418 )
John Snowabf0bf92019-06-27 17:28:14 -0400419 LOG.debug('VM launch command: %r', ' '.join(self._qemu_full_args))
John Snowa0eae172021-05-27 17:16:50 -0400420
421 # Cleaning up of this subprocess is guaranteed by _do_shutdown.
422 # pylint: disable=consider-using-with
John Snowabf0bf92019-06-27 17:28:14 -0400423 self._popen = subprocess.Popen(self._qemu_full_args,
John Snow07b71232021-05-27 17:16:46 -0400424 stdin=subprocess.DEVNULL,
John Snowabf0bf92019-06-27 17:28:14 -0400425 stdout=self._qemu_log_file,
426 stderr=subprocess.STDOUT,
427 shell=False,
428 close_fds=False)
429 self._post_launch()
430
John Snow49a608b2021-10-26 13:56:06 -0400431 def _close_qmp_connection(self) -> None:
432 """
433 Close the underlying QMP connection, if any.
434
435 Dutifully report errors that occurred while closing, but assume
436 that any error encountered indicates an abnormal termination
437 process and not a failure to close.
438 """
439 if self._qmp_connection is None:
440 return
441
442 try:
443 self._qmp.close()
444 except EOFError:
445 # EOF can occur as an Exception here when using the Async
446 # QMP backend. It indicates that the server closed the
447 # stream. If we successfully issued 'quit' at any point,
448 # then this was expected. If the remote went away without
449 # our permission, it's worth reporting that as an abnormal
450 # shutdown case.
451 if not (self._user_killed or self._quit_issued):
452 raise
453 finally:
454 self._qmp_connection = None
455
John Snowe2c97f12020-07-10 01:06:40 -0400456 def _early_cleanup(self) -> None:
457 """
458 Perform any cleanup that needs to happen before the VM exits.
John Snowa3842cb2020-07-10 01:06:42 -0400459
John Snow193bf1c2020-07-10 01:06:47 -0400460 May be invoked by both soft and hard shutdown in failover scenarios.
John Snowa3842cb2020-07-10 01:06:42 -0400461 Called additionally by _post_shutdown for comprehensive cleanup.
John Snowe2c97f12020-07-10 01:06:40 -0400462 """
463 # If we keep the console socket open, we may deadlock waiting
464 # for QEMU to exit, while QEMU is waiting for the socket to
465 # become writeable.
466 if self._console_socket is not None:
467 self._console_socket.close()
468 self._console_socket = None
469
John Snow193bf1c2020-07-10 01:06:47 -0400470 def _hard_shutdown(self) -> None:
471 """
472 Perform early cleanup, kill the VM, and wait for it to terminate.
473
474 :raise subprocess.Timeout: When timeout is exceeds 60 seconds
475 waiting for the QEMU process to terminate.
476 """
477 self._early_cleanup()
John Snow9223fda2020-10-06 19:58:05 -0400478 self._subp.kill()
479 self._subp.wait(timeout=60)
John Snow193bf1c2020-07-10 01:06:47 -0400480
John Snowb9420e42021-10-26 13:56:05 -0400481 def _soft_shutdown(self, timeout: Optional[int]) -> None:
John Snow193bf1c2020-07-10 01:06:47 -0400482 """
483 Perform early cleanup, attempt to gracefully shut down the VM, and wait
484 for it to terminate.
485
John Snow8226a4b2020-07-20 12:02:52 -0400486 :param timeout: Timeout in seconds for graceful shutdown.
487 A value of None is an infinite wait.
John Snow193bf1c2020-07-10 01:06:47 -0400488
489 :raise ConnectionReset: On QMP communication errors
490 :raise subprocess.TimeoutExpired: When timeout is exceeded waiting for
491 the QEMU process to terminate.
492 """
493 self._early_cleanup()
494
John Snowbe1183e2020-10-06 19:58:04 -0400495 if self._qmp_connection:
John Snow49a608b2021-10-26 13:56:06 -0400496 try:
497 if not self._quit_issued:
498 # May raise ExecInterruptedError or StateError if the
499 # connection dies or has *already* died.
500 self.qmp('quit')
501 finally:
502 # Regardless, we want to quiesce the connection.
503 self._close_qmp_connection()
John Snow193bf1c2020-07-10 01:06:47 -0400504
505 # May raise subprocess.TimeoutExpired
John Snow9223fda2020-10-06 19:58:05 -0400506 self._subp.wait(timeout=timeout)
John Snow193bf1c2020-07-10 01:06:47 -0400507
John Snowb9420e42021-10-26 13:56:05 -0400508 def _do_shutdown(self, timeout: Optional[int]) -> None:
John Snow193bf1c2020-07-10 01:06:47 -0400509 """
510 Attempt to shutdown the VM gracefully; fallback to a hard shutdown.
511
John Snow8226a4b2020-07-20 12:02:52 -0400512 :param timeout: Timeout in seconds for graceful shutdown.
513 A value of None is an infinite wait.
John Snow193bf1c2020-07-10 01:06:47 -0400514
515 :raise AbnormalShutdown: When the VM could not be shut down gracefully.
516 The inner exception will likely be ConnectionReset or
517 subprocess.TimeoutExpired. In rare cases, non-graceful termination
518 may result in its own exceptions, likely subprocess.TimeoutExpired.
519 """
520 try:
John Snowb9420e42021-10-26 13:56:05 -0400521 self._soft_shutdown(timeout)
John Snow193bf1c2020-07-10 01:06:47 -0400522 except Exception as exc:
523 self._hard_shutdown()
524 raise AbnormalShutdown("Could not perform graceful shutdown") \
525 from exc
526
John Snowb9420e42021-10-26 13:56:05 -0400527 def shutdown(self,
John Snowc9b30452020-07-10 01:06:43 -0400528 hard: bool = False,
John Snow8226a4b2020-07-20 12:02:52 -0400529 timeout: Optional[int] = 30) -> None:
John Snowabf0bf92019-06-27 17:28:14 -0400530 """
John Snow193bf1c2020-07-10 01:06:47 -0400531 Terminate the VM (gracefully if possible) and perform cleanup.
532 Cleanup will always be performed.
533
534 If the VM has not yet been launched, or shutdown(), wait(), or kill()
535 have already been called, this method does nothing.
536
John Snow193bf1c2020-07-10 01:06:47 -0400537 :param hard: When true, do not attempt graceful shutdown, and
538 suppress the SIGKILL warning log message.
539 :param timeout: Optional timeout in seconds for graceful shutdown.
John Snow8226a4b2020-07-20 12:02:52 -0400540 Default 30 seconds, A `None` value is an infinite wait.
John Snowabf0bf92019-06-27 17:28:14 -0400541 """
John Snowa3842cb2020-07-10 01:06:42 -0400542 if not self._launched:
543 return
544
John Snow193bf1c2020-07-10 01:06:47 -0400545 try:
Vladimir Sementsov-Ogievskiye0e925a2020-02-17 18:02:42 +0300546 if hard:
John Snowde6e08b2020-07-10 01:06:48 -0400547 self._user_killed = True
John Snow193bf1c2020-07-10 01:06:47 -0400548 self._hard_shutdown()
549 else:
John Snowb9420e42021-10-26 13:56:05 -0400550 self._do_shutdown(timeout)
John Snow193bf1c2020-07-10 01:06:47 -0400551 finally:
552 self._post_shutdown()
John Snowabf0bf92019-06-27 17:28:14 -0400553
John Snowf12a2822020-10-06 19:58:08 -0400554 def kill(self) -> None:
John Snow193bf1c2020-07-10 01:06:47 -0400555 """
556 Terminate the VM forcefully, wait for it to exit, and perform cleanup.
557 """
Vladimir Sementsov-Ogievskiye0e925a2020-02-17 18:02:42 +0300558 self.shutdown(hard=True)
559
John Snow8226a4b2020-07-20 12:02:52 -0400560 def wait(self, timeout: Optional[int] = 30) -> None:
John Snow89528052020-07-10 01:06:44 -0400561 """
562 Wait for the VM to power off and perform post-shutdown cleanup.
563
John Snow8226a4b2020-07-20 12:02:52 -0400564 :param timeout: Optional timeout in seconds. Default 30 seconds.
565 A value of `None` is an infinite wait.
John Snow89528052020-07-10 01:06:44 -0400566 """
John Snowb9420e42021-10-26 13:56:05 -0400567 self._quit_issued = True
568 self.shutdown(timeout=timeout)
John Snow89528052020-07-10 01:06:44 -0400569
John Snowf12a2822020-10-06 19:58:08 -0400570 def set_qmp_monitor(self, enabled: bool = True) -> None:
Wainer dos Santos Moschetta74b56bb2019-12-11 13:55:35 -0500571 """
572 Set the QMP monitor.
573
574 @param enabled: if False, qmp monitor options will be removed from
575 the base arguments of the resulting QEMU command
576 line. Default is True.
John Snow5c02c862021-06-29 17:43:23 -0400577
578 .. note:: Call this function before launch().
Wainer dos Santos Moschetta74b56bb2019-12-11 13:55:35 -0500579 """
John Snowbe1183e2020-10-06 19:58:04 -0400580 self._qmp_set = enabled
581
582 @property
John Snowbeb6b572021-05-27 17:16:53 -0400583 def _qmp(self) -> QEMUMonitorProtocol:
John Snowbe1183e2020-10-06 19:58:04 -0400584 if self._qmp_connection is None:
585 raise QEMUMachineError("Attempt to access QMP with no connection")
586 return self._qmp_connection
Wainer dos Santos Moschetta74b56bb2019-12-11 13:55:35 -0500587
John Snowaaa81ec2020-10-06 19:58:03 -0400588 @classmethod
Vladimir Sementsov-Ogievskiyc7daa572021-08-24 11:38:45 +0300589 def _qmp_args(cls, conv_keys: bool,
590 args: Dict[str, Any]) -> Dict[str, object]:
591 if conv_keys:
592 return {k.replace('_', '-'): v for k, v in args.items()}
593
594 return args
John Snowabf0bf92019-06-27 17:28:14 -0400595
John Snowaaa81ec2020-10-06 19:58:03 -0400596 def qmp(self, cmd: str,
Vladimir Sementsov-Ogievskiy3f3c9b42021-08-24 11:38:46 +0300597 args_dict: Optional[Dict[str, object]] = None,
598 conv_keys: Optional[bool] = None,
John Snowaaa81ec2020-10-06 19:58:03 -0400599 **args: Any) -> QMPMessage:
600 """
601 Invoke a QMP command and return the response dict
602 """
Vladimir Sementsov-Ogievskiy3f3c9b42021-08-24 11:38:46 +0300603 if args_dict is not None:
604 assert not args
605 assert conv_keys is None
606 args = args_dict
607 conv_keys = False
608
609 if conv_keys is None:
610 conv_keys = True
611
Vladimir Sementsov-Ogievskiyc7daa572021-08-24 11:38:45 +0300612 qmp_args = self._qmp_args(conv_keys, args)
John Snowb9420e42021-10-26 13:56:05 -0400613 ret = self._qmp.cmd(cmd, args=qmp_args)
614 if cmd == 'quit' and 'error' not in ret and 'return' in ret:
615 self._quit_issued = True
616 return ret
John Snowabf0bf92019-06-27 17:28:14 -0400617
John Snowf12a2822020-10-06 19:58:08 -0400618 def command(self, cmd: str,
619 conv_keys: bool = True,
620 **args: Any) -> QMPReturnValue:
John Snowabf0bf92019-06-27 17:28:14 -0400621 """
622 Invoke a QMP command.
623 On success return the response dict.
624 On failure raise an exception.
625 """
Vladimir Sementsov-Ogievskiyc7daa572021-08-24 11:38:45 +0300626 qmp_args = self._qmp_args(conv_keys, args)
John Snowb9420e42021-10-26 13:56:05 -0400627 ret = self._qmp.command(cmd, **qmp_args)
628 if cmd == 'quit':
629 self._quit_issued = True
630 return ret
John Snowabf0bf92019-06-27 17:28:14 -0400631
John Snowf12a2822020-10-06 19:58:08 -0400632 def get_qmp_event(self, wait: bool = False) -> Optional[QMPMessage]:
John Snowabf0bf92019-06-27 17:28:14 -0400633 """
634 Poll for one queued QMP events and return it
635 """
John Snow306dfcd2019-06-27 17:28:15 -0400636 if self._events:
John Snowabf0bf92019-06-27 17:28:14 -0400637 return self._events.pop(0)
638 return self._qmp.pull_event(wait=wait)
639
John Snowf12a2822020-10-06 19:58:08 -0400640 def get_qmp_events(self, wait: bool = False) -> List[QMPMessage]:
John Snowabf0bf92019-06-27 17:28:14 -0400641 """
642 Poll for queued QMP events and return a list of dicts
643 """
644 events = self._qmp.get_events(wait=wait)
645 events.extend(self._events)
646 del self._events[:]
John Snowabf0bf92019-06-27 17:28:14 -0400647 return events
648
649 @staticmethod
John Snowf12a2822020-10-06 19:58:08 -0400650 def event_match(event: Any, match: Optional[Any]) -> bool:
John Snowabf0bf92019-06-27 17:28:14 -0400651 """
652 Check if an event matches optional match criteria.
653
654 The match criteria takes the form of a matching subdict. The event is
655 checked to be a superset of the subdict, recursively, with matching
656 values whenever the subdict values are not None.
657
658 This has a limitation that you cannot explicitly check for None values.
659
660 Examples, with the subdict queries on the left:
661 - None matches any object.
662 - {"foo": None} matches {"foo": {"bar": 1}}
663 - {"foo": None} matches {"foo": 5}
664 - {"foo": {"abc": None}} does not match {"foo": {"bar": 1}}
665 - {"foo": {"rab": 2}} matches {"foo": {"bar": 1, "rab": 2}}
666 """
667 if match is None:
668 return True
669
670 try:
671 for key in match:
672 if key in event:
673 if not QEMUMachine.event_match(event[key], match[key]):
674 return False
675 else:
676 return False
677 return True
678 except TypeError:
679 # either match or event wasn't iterable (not a dict)
John Snowf12a2822020-10-06 19:58:08 -0400680 return bool(match == event)
John Snowabf0bf92019-06-27 17:28:14 -0400681
John Snowf12a2822020-10-06 19:58:08 -0400682 def event_wait(self, name: str,
683 timeout: float = 60.0,
684 match: Optional[QMPMessage] = None) -> Optional[QMPMessage]:
John Snowabf0bf92019-06-27 17:28:14 -0400685 """
686 event_wait waits for and returns a named event from QMP with a timeout.
687
688 name: The event to wait for.
689 timeout: QEMUMonitorProtocol.pull_event timeout parameter.
690 match: Optional match criteria. See event_match for details.
691 """
692 return self.events_wait([(name, match)], timeout)
693
John Snowf12a2822020-10-06 19:58:08 -0400694 def events_wait(self,
695 events: Sequence[Tuple[str, Any]],
696 timeout: float = 60.0) -> Optional[QMPMessage]:
John Snowabf0bf92019-06-27 17:28:14 -0400697 """
John Snow1847a4a2020-10-06 19:58:02 -0400698 events_wait waits for and returns a single named event from QMP.
699 In the case of multiple qualifying events, this function returns the
700 first one.
John Snowabf0bf92019-06-27 17:28:14 -0400701
John Snow1847a4a2020-10-06 19:58:02 -0400702 :param events: A sequence of (name, match_criteria) tuples.
703 The match criteria are optional and may be None.
704 See event_match for details.
705 :param timeout: Optional timeout, in seconds.
706 See QEMUMonitorProtocol.pull_event.
707
708 :raise QMPTimeoutError: If timeout was non-zero and no matching events
709 were found.
710 :return: A QMP event matching the filter criteria.
711 If timeout was 0 and no event matched, None.
John Snowabf0bf92019-06-27 17:28:14 -0400712 """
John Snowf12a2822020-10-06 19:58:08 -0400713 def _match(event: QMPMessage) -> bool:
John Snowabf0bf92019-06-27 17:28:14 -0400714 for name, match in events:
John Snow306dfcd2019-06-27 17:28:15 -0400715 if event['event'] == name and self.event_match(event, match):
John Snowabf0bf92019-06-27 17:28:14 -0400716 return True
717 return False
718
John Snow1847a4a2020-10-06 19:58:02 -0400719 event: Optional[QMPMessage]
720
John Snowabf0bf92019-06-27 17:28:14 -0400721 # Search cached events
722 for event in self._events:
723 if _match(event):
724 self._events.remove(event)
725 return event
726
727 # Poll for new events
728 while True:
729 event = self._qmp.pull_event(wait=timeout)
John Snow1847a4a2020-10-06 19:58:02 -0400730 if event is None:
731 # NB: None is only returned when timeout is false-ish.
732 # Timeouts raise QMPTimeoutError instead!
733 break
John Snowabf0bf92019-06-27 17:28:14 -0400734 if _match(event):
735 return event
736 self._events.append(event)
737
738 return None
739
John Snowf12a2822020-10-06 19:58:08 -0400740 def get_log(self) -> Optional[str]:
John Snowabf0bf92019-06-27 17:28:14 -0400741 """
742 After self.shutdown or failed qemu execution, this returns the output
743 of the qemu process.
744 """
745 return self._iolog
746
John Snowf12a2822020-10-06 19:58:08 -0400747 def add_args(self, *args: str) -> None:
John Snowabf0bf92019-06-27 17:28:14 -0400748 """
749 Adds to the list of extra arguments to be given to the QEMU binary
750 """
751 self._args.extend(args)
752
John Snowf12a2822020-10-06 19:58:08 -0400753 def set_machine(self, machine_type: str) -> None:
John Snowabf0bf92019-06-27 17:28:14 -0400754 """
755 Sets the machine type
756
757 If set, the machine type will be added to the base arguments
758 of the resulting QEMU command line.
759 """
760 self._machine = machine_type
761
John Snowf12a2822020-10-06 19:58:08 -0400762 def set_console(self,
763 device_type: Optional[str] = None,
764 console_index: int = 0) -> None:
John Snowabf0bf92019-06-27 17:28:14 -0400765 """
766 Sets the device type for a console device
767
768 If set, the console device and a backing character device will
769 be added to the base arguments of the resulting QEMU command
770 line.
771
772 This is a convenience method that will either use the provided
773 device type, or default to a "-serial chardev:console" command
774 line argument.
775
776 The actual setting of command line arguments will be be done at
777 machine launch time, as it depends on the temporary directory
778 to be created.
779
780 @param device_type: the device type, such as "isa-serial". If
781 None is given (the default value) a "-serial
782 chardev:console" command line argument will
783 be used instead, resorting to the machine's
784 default device type.
Philippe Mathieu-Daudé746f2442020-01-21 00:51:56 +0100785 @param console_index: the index of the console device to use.
786 If not zero, the command line will create
787 'index - 1' consoles and connect them to
788 the 'null' backing character device.
John Snowabf0bf92019-06-27 17:28:14 -0400789 """
790 self._console_set = True
791 self._console_device_type = device_type
Philippe Mathieu-Daudé746f2442020-01-21 00:51:56 +0100792 self._console_index = console_index
John Snowabf0bf92019-06-27 17:28:14 -0400793
794 @property
John Snowf12a2822020-10-06 19:58:08 -0400795 def console_socket(self) -> socket.socket:
John Snowabf0bf92019-06-27 17:28:14 -0400796 """
797 Returns a socket connected to the console
798 """
799 if self._console_socket is None:
Robert Foley80ded8e2020-07-24 07:45:08 +0100800 self._console_socket = console_socket.ConsoleSocket(
801 self._console_address,
802 file=self._console_log_path,
803 drain=self._drain_console)
John Snowabf0bf92019-06-27 17:28:14 -0400804 return self._console_socket
Cleber Rosa2ca6e262021-02-11 17:01:42 -0500805
806 @property
807 def temp_dir(self) -> str:
808 """
809 Returns a temporary directory to be used for this machine
810 """
811 if self._temp_dir is None:
812 self._temp_dir = tempfile.mkdtemp(prefix="qemu-machine-",
813 dir=self._base_temp_dir)
814 return self._temp_dir
Cleber Rosab306e262021-02-11 16:55:05 -0500815
816 @property
John Snow87bf1fe2021-11-18 15:46:14 -0500817 def sock_dir(self) -> str:
818 """
819 Returns the directory used for sockfiles by this machine.
820 """
821 if self._sock_dir:
822 return self._sock_dir
823 return self.temp_dir
824
825 @property
Cleber Rosab306e262021-02-11 16:55:05 -0500826 def log_dir(self) -> str:
827 """
828 Returns a directory to be used for writing logs
829 """
830 if self._log_dir is None:
831 return self.temp_dir
832 return self._log_dir