qemu.aqmp.qmp_client module¶
QMP Protocol Implementation
This module provides the QMPClient
class, which can be used to connect
and send commands to a QMP server such as QEMU. The QMP class can be
used to either connect to a listening server, or used to listen and
accept an incoming connection from that server.
- exception qemu.aqmp.qmp_client.GreetingError(error_message: str, exc: Exception)[source]¶
Bases:
qemu.aqmp.qmp_client._WrappedProtocolError
An exception occurred during the Greeting phase.
- Parameters
error_message – Human-readable string describing the error.
exc – The root-cause exception.
- exception qemu.aqmp.qmp_client.NegotiationError(error_message: str, exc: Exception)[source]¶
Bases:
qemu.aqmp.qmp_client._WrappedProtocolError
An exception occurred during the Negotiation phase.
- Parameters
error_message – Human-readable string describing the error.
exc – The root-cause exception.
- exception qemu.aqmp.qmp_client.ExecuteError(error_response: qemu.aqmp.models.ErrorResponse, sent: qemu.aqmp.message.Message, received: qemu.aqmp.message.Message)[source]¶
Bases:
qemu.aqmp.error.AQMPError
Exception raised by
QMPClient.execute()
on RPC failure.- Parameters
error_response – The RPC error response object.
sent – The sent RPC message that caused the failure.
received – The raw RPC error reply received.
- sent: qemu.aqmp.message.Message¶
The sent
Message
that caused the failure
- received: qemu.aqmp.message.Message¶
The received
Message
that indicated failure
- error: qemu.aqmp.models.ErrorResponse¶
The parsed error response
- exception qemu.aqmp.qmp_client.ExecInterruptedError[source]¶
Bases:
qemu.aqmp.error.AQMPError
Exception raised by
execute()
(et al) when an RPC is interrupted.This error is raised when an
execute()
statement could not be completed. This can occur because the connection itself was terminated before a reply was received.The true cause of the interruption will be available via
disconnect()
.
- exception qemu.aqmp.qmp_client.ServerParseError(error_message: str, msg: qemu.aqmp.message.Message)[source]¶
Bases:
qemu.aqmp.qmp_client._MsgProtocolError
The Server sent a
Message
indicating parsing failure.i.e. A reply has arrived from the server, but it is missing the “ID” field, indicating a parsing error.
- Parameters
error_message – Human-readable string describing the error.
msg – The QMP
Message
that caused the error.
- exception qemu.aqmp.qmp_client.BadReplyError(error_message: str, msg: qemu.aqmp.message.Message, sent: qemu.aqmp.message.Message)[source]¶
Bases:
qemu.aqmp.qmp_client._MsgProtocolError
An execution reply was successfully routed, but not understood.
If a QMP message is received with an ‘id’ field to allow it to be routed, but is otherwise malformed, this exception will be raised.
A reply message is malformed if it is missing either the ‘return’ or ‘error’ keys, or if the ‘error’ value has missing keys or members of the wrong type.
- Parameters
error_message – Human-readable string describing the error.
msg – The malformed reply that was received.
sent – The message that was sent that prompted the error.
- class qemu.aqmp.qmp_client.QMPClient(name: Optional[str] = None)[source]¶
Bases:
qemu.aqmp.protocol.AsyncProtocol
[qemu.aqmp.message.Message
],qemu.aqmp.events.Events
Implements a QMP client connection.
QMP can be used to establish a connection as either the transport client or server, though this class always acts as the QMP client.
- Parameters
name – Optional nickname for the connection, used for logging.
Basic script-style usage looks like this:
qmp = QMPClient('my_virtual_machine_name') await qmp.connect(('127.0.0.1', 1234)) ... res = await qmp.execute('block-query') ... await qmp.disconnect()
Basic async client-style usage looks like this:
class Client: def __init__(self, name: str): self.qmp = QMPClient(name) async def watch_events(self): try: async for event in self.qmp.events: print(f"Event: {event['event']}") except asyncio.CancelledError: return async def run(self, address='/tmp/qemu.socket'): await self.qmp.connect(address) asyncio.create_task(self.watch_events()) await self.qmp.runstate_changed.wait() await self.disconnect()
See
aqmp.events
for more detail on event handling patterns.- logger: logging.Logger = <Logger qemu.aqmp.qmp_client (WARNING)>¶
Logger object used for debugging messages.
- negotiate: bool¶
Whether or not to perform capabilities negotiation upon connection. Implies
await_greeting
.
- execute_msg(msg: qemu.aqmp.message.Message) → object[source]¶
Execute a QMP command and return its value.
- Parameters
msg – The QMP
Message
to execute.- Returns
The command execution return value from the server. The type of object returned depends on the command that was issued, though most in QEMU return a
dict
.- Raises
ValueError – If the QMP
Message
does not have either the ‘execute’ or ‘exec-oob’ fields set.ExecuteError – When the server returns an error response.
ExecInterruptedError – if the connection was terminated early.
- classmethod make_execute_msg(cmd: str, arguments: Optional[Mapping[str, object]] = None, oob: bool = False) → qemu.aqmp.message.Message[source]¶
Create an executable message to be sent by
execute_msg
later.
- async execute(cmd: str, arguments: Optional[Mapping[str, object]] = None, oob: bool = False) → object[source]¶
Execute a QMP command and return its value.
- Parameters
cmd – QMP command name.
arguments – Arguments (if any). Must be JSON-serializable.
oob – If
True
, execute “out of band”.
- Returns
The command execution return value from the server. The type of object returned depends on the command that was issued, though most in QEMU return a
dict
.- Raises
ExecuteError – When the server returns an error response.
ExecInterruptedError – if the connection was terminated early.
- accept(address: Union[str, Tuple[str, int]], ssl: Optional[ssl.SSLContext] = None) → None¶
Accept a connection and begin processing message queues.
If this call fails,
runstate
is guaranteed to be set back toIDLE
.- Parameters
address – Address to listen to; UNIX socket path or TCP address/port.
ssl – SSL context to use, if any.
- Raises
StateError – When the
Runstate
is notIDLE
.ConnectError – If a connection could not be accepted.
- connect(address: Union[str, Tuple[str, int]], ssl: Optional[ssl.SSLContext] = None) → None
Connect to the server and begin processing message queues.
If this call fails,
runstate
is guaranteed to be set back toIDLE
.- Parameters
address – Address to connect to; UNIX socket path or TCP address/port.
ssl – SSL context to use, if any.
- Raises
StateError – When the
Runstate
is notIDLE
.ConnectError – If a connection cannot be made to the server.
- async disconnect() → None
Disconnect and wait for all tasks to fully stop.
If there was an exception that caused the reader/writers to terminate prematurely, it will be raised here.
- Raises
Exception – When the reader or writer terminate unexpectedly.
- listen(*listeners: qemu.aqmp.events.EventListener) → Iterator[None]
Context manager: Temporarily listen with an
EventListener
.Accepts one or more
EventListener
objects and registers them, activating them for the duration of the context block.EventListener
objects will have any pending events in their FIFO queue cleared upon exiting the context block, when they are deactivated.- Parameters
*listeners – One or more EventListeners to activate.
- Raises
ListenerError – If the given listener(s) are already active.
- listener(names: Optional[Union[str, Iterable[str]]] = (), event_filter: Optional[Callable[[qemu.aqmp.message.Message], bool]] = None) → Iterator[qemu.aqmp.events.EventListener]
Context manager: Temporarily listen with a new
EventListener
.Creates an
EventListener
object and registers it, activating it for the duration of the context block.- Parameters
names – One or more names of events to listen for. When not provided, listen for ALL events.
event_filter – An optional event filtering function. When names are also provided, this acts as a secondary filter.
- Returns
The newly created and active
EventListener
.
- register_listener(listener: qemu.aqmp.events.EventListener) → None
Register and activate an
EventListener
.- Parameters
listener – The listener to activate.
- Raises
ListenerError – If the given listener is already registered.
- remove_listener(listener: qemu.aqmp.events.EventListener) → None
Unregister and deactivate an
EventListener
.The removed listener will have its pending events cleared via
clear()
. The listener can be re-registered later when desired.- Parameters
listener – The listener to deactivate.
- Raises
ListenerError – If the given listener is not registered.
- property runstate: qemu.aqmp.protocol.Runstate
The current
Runstate
of the connection.
- async runstate_changed() → qemu.aqmp.protocol.Runstate
Wait for the
runstate
to change, then return that runstate.
- name: Optional[str]
The nickname for this connection, if any.
- events: EventListener¶
Default, all-events
EventListener
.