1 # QEMU Monitor Protocol Python class
3 # Copyright (C) 2009, 2010 Red Hat Inc.
6 # Luiz Capitulino <lcapitulino@redhat.com>
8 # This work is licensed under the terms of the GNU GPL, version 2. See
9 # the COPYING file in the top-level directory.
16 class QMPError(Exception):
19 class QMPConnectError(QMPError
):
22 class QMPCapabilitiesError(QMPError
):
25 class QMPTimeoutError(QMPError
):
28 class QEMUMonitorProtocol
:
29 def __init__(self
, address
, server
=False, debug
=False):
31 Create a QEMUMonitorProtocol class.
33 @param address: QEMU address, can be either a unix socket path (string)
34 or a tuple in the form ( address, port ) for a TCP
36 @param server: server mode listens on the socket (bool)
37 @raise socket.error on socket connection errors
38 @note No connection is established, this is done by the connect() or
42 self
.__address
= address
44 self
.__sock
= self
.__get
_sock
()
46 self
.__sock
.bind(self
.__address
)
50 if isinstance(self
.__address
, tuple):
51 family
= socket
.AF_INET
53 family
= socket
.AF_UNIX
54 return socket
.socket(family
, socket
.SOCK_STREAM
)
56 def __negotiate_capabilities(self
):
57 greeting
= self
.__json
_read
()
58 if greeting
is None or not greeting
.has_key('QMP'):
60 # Greeting seems ok, negotiate capabilities
61 resp
= self
.cmd('qmp_capabilities')
64 raise QMPCapabilitiesError
66 def __json_read(self
, only_event
=False):
68 data
= self
.__sockfile
.readline()
71 resp
= json
.loads(data
)
74 print >>sys
.stderr
, "QMP:<<< %s" % resp
75 self
.__events
.append(resp
)
82 def __get_events(self
, wait
=False):
84 Check for new events in the stream and cache them in __events.
86 @param wait (bool): block until an event is available.
87 @param wait (float): If wait is a float, treat it as a timeout value.
89 @raise QMPTimeoutError: If a timeout float is provided and the timeout
91 @raise QMPConnectError: If wait is True but no events could be retrieved
92 or if some other error occurred.
95 # Check for new events regardless and pull them into the cache:
96 self
.__sock
.setblocking(0)
99 except socket
.error
as err
:
100 if err
[0] == errno
.EAGAIN
:
103 self
.__sock
.setblocking(1)
105 # Wait for new events, if needed.
106 # if wait is 0.0, this means "no wait" and is also implicitly false.
107 if not self
.__events
and wait
:
108 if isinstance(wait
, float):
109 self
.__sock
.settimeout(wait
)
111 ret
= self
.__json
_read
(only_event
=True)
112 except socket
.timeout
:
113 raise QMPTimeoutError("Timeout waiting for event")
115 raise QMPConnectError("Error while reading from socket")
117 raise QMPConnectError("Error while reading from socket")
118 self
.__sock
.settimeout(None)
120 def connect(self
, negotiate
=True):
122 Connect to the QMP Monitor and perform capabilities negotiation.
124 @return QMP greeting dict
125 @raise socket.error on socket connection errors
126 @raise QMPConnectError if the greeting is not received
127 @raise QMPCapabilitiesError if fails to negotiate capabilities
129 self
.__sock
.connect(self
.__address
)
130 self
.__sockfile
= self
.__sock
.makefile()
132 return self
.__negotiate
_capabilities
()
136 Await connection from QMP Monitor and perform capabilities negotiation.
138 @return QMP greeting dict
139 @raise socket.error on socket connection errors
140 @raise QMPConnectError if the greeting is not received
141 @raise QMPCapabilitiesError if fails to negotiate capabilities
143 self
.__sock
, _
= self
.__sock
.accept()
144 self
.__sockfile
= self
.__sock
.makefile()
145 return self
.__negotiate
_capabilities
()
147 def cmd_obj(self
, qmp_cmd
):
149 Send a QMP command to the QMP Monitor.
151 @param qmp_cmd: QMP command to be sent as a Python dict
152 @return QMP response as a Python dict or None if the connection has
156 print >>sys
.stderr
, "QMP:>>> %s" % qmp_cmd
158 self
.__sock
.sendall(json
.dumps(qmp_cmd
))
159 except socket
.error
as err
:
160 if err
[0] == errno
.EPIPE
:
162 raise socket
.error(err
)
163 resp
= self
.__json
_read
()
165 print >>sys
.stderr
, "QMP:<<< %s" % resp
168 def cmd(self
, name
, args
=None, id=None):
170 Build a QMP command and send it to the QMP Monitor.
172 @param name: command name (string)
173 @param args: command arguments (dict)
174 @param id: command id (dict, list, string or int)
176 qmp_cmd
= { 'execute': name
}
178 qmp_cmd
['arguments'] = args
181 return self
.cmd_obj(qmp_cmd
)
183 def command(self
, cmd
, **kwds
):
184 ret
= self
.cmd(cmd
, kwds
)
185 if ret
.has_key('error'):
186 raise Exception(ret
['error']['desc'])
189 def pull_event(self
, wait
=False):
191 Get and delete the first available QMP event.
193 @param wait (bool): block until an event is available.
194 @param wait (float): If wait is a float, treat it as a timeout value.
196 @raise QMPTimeoutError: If a timeout float is provided and the timeout
198 @raise QMPConnectError: If wait is True but no events could be retrieved
199 or if some other error occurred.
201 @return The first available QMP event, or None.
203 self
.__get
_events
(wait
)
206 return self
.__events
.pop(0)
209 def get_events(self
, wait
=False):
211 Get a list of available QMP events.
213 @param wait (bool): block until an event is available.
214 @param wait (float): If wait is a float, treat it as a timeout value.
216 @raise QMPTimeoutError: If a timeout float is provided and the timeout
218 @raise QMPConnectError: If wait is True but no events could be retrieved
219 or if some other error occurred.
221 @return The list of available QMP events.
223 self
.__get
_events
(wait
)
226 def clear_events(self
):
228 Clear current list of pending events.
234 self
.__sockfile
.close()
236 timeout
= socket
.timeout
238 def settimeout(self
, timeout
):
239 self
.__sock
.settimeout(timeout
)
241 def get_sock_fd(self
):
242 return self
.__sock
.fileno()
244 def is_scm_available(self
):
245 return self
.__sock
.family
== socket
.AF_UNIX