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