machine - Run QEMU VMs

QEMU development and testing library.

This library provides a few high-level classes for driving QEMU from a test suite, not intended for production use.

QEMUQtestProtocol: send/receive qtest messages.
QEMUMachine: Configure and Boot a QEMU VM
+– QEMUQtestMachine: VM class, with a qtest socket.
class qemu.machine.QEMUMachine(binary: str, args: Sequence[str] = (), wrapper: Sequence[str] = (), name: Optional[str] = None, base_temp_dir: str = '/var/tmp', monitor_address: Optional[Union[Tuple[str, int], str]] = None, socket_scm_helper: Optional[str] = None, sock_dir: Optional[str] = None, drain_console: bool = False, console_log: Optional[str] = None, log_dir: Optional[str] = None, qmp_timer: Optional[float] = None)[source]

Bases: object

A QEMU VM.

Use this object as a context manager to ensure the QEMU process terminates:

with VM(binary) as vm:
    ...
# vm is guaranteed to be shut down here
add_monitor_null()None[source]

This can be used to add an unused monitor instance.

add_fd(fd: int, fdset: int, opaque: str, opts: str = '')qemu.machine.machine._T[source]

Pass a file descriptor to the VM

send_fd_scm(fd: Optional[int] = None, file_path: Optional[str] = None)int[source]

Send an fd or file_path to socket_scm_helper.

Exactly one of fd and file_path must be given. If it is file_path, the helper will open that file and pass its own fd.

static _remove_if_exists(path: str)None[source]

Remove file object at path if it exists

is_running()bool[source]

Returns true if the VM is running.

property _subp: subprocess.Popen[bytes]
exitcode()Optional[int][source]

Returns the exit code if possible, or None.

get_pid()Optional[int][source]

Returns the PID of the running process, or None.

_load_io_log()None[source]
property _base_args: List[str]
property args: List[str]

Returns the list of arguments given to the QEMU binary.

_pre_launch()None[source]
_post_launch()None[source]
_close_qemu_log_file()None[source]
_post_shutdown()None[source]

Called to cleanup the VM instance after the process has exited. May also be called after a failed launch.

launch()None[source]

Launch the VM and make sure we cleanup and expose the command line/output in case of exception

_launch()None[source]

Launch the VM and establish a QMP connection

_early_cleanup()None[source]

Perform any cleanup that needs to happen before the VM exits.

May be invoked by both soft and hard shutdown in failover scenarios. Called additionally by _post_shutdown for comprehensive cleanup.

_hard_shutdown()None[source]

Perform early cleanup, kill the VM, and wait for it to terminate.

Raises

subprocess.Timeout – When timeout is exceeds 60 seconds waiting for the QEMU process to terminate.

_soft_shutdown(timeout: Optional[int], has_quit: bool = False)None[source]

Perform early cleanup, attempt to gracefully shut down the VM, and wait for it to terminate.

Parameters
  • timeout – Timeout in seconds for graceful shutdown. A value of None is an infinite wait.

  • has_quit – When True, don’t attempt to issue ‘quit’ QMP command

Raises
  • ConnectionReset – On QMP communication errors

  • subprocess.TimeoutExpired – When timeout is exceeded waiting for the QEMU process to terminate.

_do_shutdown(timeout: Optional[int], has_quit: bool = False)None[source]

Attempt to shutdown the VM gracefully; fallback to a hard shutdown.

Parameters
  • timeout – Timeout in seconds for graceful shutdown. A value of None is an infinite wait.

  • has_quit – When True, don’t attempt to issue ‘quit’ QMP command

Raises

AbnormalShutdown – When the VM could not be shut down gracefully. The inner exception will likely be ConnectionReset or subprocess.TimeoutExpired. In rare cases, non-graceful termination may result in its own exceptions, likely subprocess.TimeoutExpired.

shutdown(has_quit: bool = False, hard: bool = False, timeout: Optional[int] = 30)None[source]

Terminate the VM (gracefully if possible) and perform cleanup. Cleanup will always be performed.

If the VM has not yet been launched, or shutdown(), wait(), or kill() have already been called, this method does nothing.

Parameters
  • has_quit – When true, do not attempt to issue ‘quit’ QMP command.

  • hard – When true, do not attempt graceful shutdown, and suppress the SIGKILL warning log message.

  • timeout – Optional timeout in seconds for graceful shutdown. Default 30 seconds, A None value is an infinite wait.

kill()None[source]

Terminate the VM forcefully, wait for it to exit, and perform cleanup.

wait(timeout: Optional[int] = 30)None[source]

Wait for the VM to power off and perform post-shutdown cleanup.

Parameters

timeout – Optional timeout in seconds. Default 30 seconds. A value of None is an infinite wait.

set_qmp_monitor(enabled: bool = True)None[source]

Set the QMP monitor.

@param enabled: if False, qmp monitor options will be removed from

the base arguments of the resulting QEMU command line. Default is True.

Note

Call this function before launch().

property _qmp: qemu.qmp.QEMUMonitorProtocol
classmethod _qmp_args(conv_keys: bool, args: Dict[str, Any])Dict[str, object][source]
qmp(cmd: str, args_dict: Optional[Dict[str, object]] = None, conv_keys: Optional[bool] = None, **args: Any)Dict[str, Any][source]

Invoke a QMP command and return the response dict

command(cmd: str, conv_keys: bool = True, **args: Any)object[source]

Invoke a QMP command. On success return the response dict. On failure raise an exception.

get_qmp_event(wait: bool = False)Optional[Dict[str, Any]][source]

Poll for one queued QMP events and return it

get_qmp_events(wait: bool = False)List[Dict[str, Any]][source]

Poll for queued QMP events and return a list of dicts

static event_match(event: Any, match: Optional[Any])bool[source]

Check if an event matches optional match criteria.

The match criteria takes the form of a matching subdict. The event is checked to be a superset of the subdict, recursively, with matching values whenever the subdict values are not None.

This has a limitation that you cannot explicitly check for None values.

Examples, with the subdict queries on the left:
  • None matches any object.

  • {“foo”: None} matches {“foo”: {“bar”: 1}}

  • {“foo”: None} matches {“foo”: 5}

  • {“foo”: {“abc”: None}} does not match {“foo”: {“bar”: 1}}

  • {“foo”: {“rab”: 2}} matches {“foo”: {“bar”: 1, “rab”: 2}}

event_wait(name: str, timeout: float = 60.0, match: Optional[Dict[str, Any]] = None)Optional[Dict[str, Any]][source]

event_wait waits for and returns a named event from QMP with a timeout.

name: The event to wait for. timeout: QEMUMonitorProtocol.pull_event timeout parameter. match: Optional match criteria. See event_match for details.

events_wait(events: Sequence[Tuple[str, Any]], timeout: float = 60.0)Optional[Dict[str, Any]][source]

events_wait waits for and returns a single named event from QMP. In the case of multiple qualifying events, this function returns the first one.

Parameters
  • events – A sequence of (name, match_criteria) tuples. The match criteria are optional and may be None. See event_match for details.

  • timeout – Optional timeout, in seconds. See QEMUMonitorProtocol.pull_event.

Raises

QMPTimeoutError – If timeout was non-zero and no matching events were found.

Returns

A QMP event matching the filter criteria. If timeout was 0 and no event matched, None.

get_log()Optional[str][source]

After self.shutdown or failed qemu execution, this returns the output of the qemu process.

add_args(*args: str)None[source]

Adds to the list of extra arguments to be given to the QEMU binary

set_machine(machine_type: str)None[source]

Sets the machine type

If set, the machine type will be added to the base arguments of the resulting QEMU command line.

set_console(device_type: Optional[str] = None, console_index: int = 0)None[source]

Sets the device type for a console device

If set, the console device and a backing character device will be added to the base arguments of the resulting QEMU command line.

This is a convenience method that will either use the provided device type, or default to a “-serial chardev:console” command line argument.

The actual setting of command line arguments will be be done at machine launch time, as it depends on the temporary directory to be created.

@param device_type: the device type, such as “isa-serial”. If

None is given (the default value) a “-serial chardev:console” command line argument will be used instead, resorting to the machine’s default device type.

@param console_index: the index of the console device to use.

If not zero, the command line will create ‘index - 1’ consoles and connect them to the ‘null’ backing character device.

property console_socket: socket.socket

Returns a socket connected to the console

property temp_dir: str

Returns a temporary directory to be used for this machine

property log_dir: str

Returns a directory to be used for writing logs

class qemu.machine.QEMUQtestProtocol(address: Union[Tuple[str, int], str], server: bool = False)[source]

Bases: object

QEMUQtestProtocol implements a connection to a qtest socket.

Parameters
  • address – QEMU address, can be either a unix socket path (string) or a tuple in the form ( address, port ) for a TCP connection

  • server – server mode, listens on the socket (bool)

Raises

socket.error – on socket connection errors

Note

No conection is estabalished by __init__(), this is done by the connect() or accept() methods.

_get_sock()socket.socket[source]
connect()None[source]

Connect to the qtest socket.

@raise socket.error on socket connection errors

accept()None[source]

Await connection from QEMU.

@raise socket.error on socket connection errors

cmd(qtest_cmd: str)str[source]

Send a qtest command on the wire.

@param qtest_cmd: qtest command text to be sent

close()None[source]

Close this socket.

settimeout(timeout: Optional[float])None[source]

Set a timeout, in seconds.

class qemu.machine.QEMUQtestMachine(binary: str, args: Sequence[str] = (), wrapper: Sequence[str] = (), name: Optional[str] = None, base_temp_dir: str = '/var/tmp', socket_scm_helper: Optional[str] = None, sock_dir: Optional[str] = None, qmp_timer: Optional[float] = None)[source]

Bases: qemu.machine.machine.QEMUMachine

A QEMU VM, with a qtest socket available.

property _base_args: List[str]
_pre_launch()None[source]
_post_launch()None[source]
_post_shutdown()None[source]

Called to cleanup the VM instance after the process has exited. May also be called after a failed launch.

qtest(cmd: str)str[source]

Send a qtest command to the guest.

Parameters

cmd – qtest command to send

Returns

qtest server response