scripts: add a 'debug' parameter to QEMUMonitorProtocol
[qemu/kevin.git] / scripts / qmp / qmp.py
blob70e927e08d929cf45ba844c9587e824859fd075c
1 # QEMU Monitor Protocol Python class
3 # Copyright (C) 2009, 2010 Red Hat Inc.
5 # Authors:
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.
11 import json
12 import errno
13 import socket
14 import sys
16 class QMPError(Exception):
17 pass
19 class QMPConnectError(QMPError):
20 pass
22 class QMPCapabilitiesError(QMPError):
23 pass
25 class QMPTimeoutError(QMPError):
26 pass
28 class QEMUMonitorProtocol:
29 def __init__(self, address, server=False, debug=False):
30 """
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
35 connection
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
39 accept() methods
40 """
41 self.__events = []
42 self.__address = address
43 self._debug = debug
44 self.__sock = self.__get_sock()
45 if server:
46 self.__sock.bind(self.__address)
47 self.__sock.listen(1)
49 def __get_sock(self):
50 if isinstance(self.__address, tuple):
51 family = socket.AF_INET
52 else:
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'):
59 raise QMPConnectError
60 # Greeting seems ok, negotiate capabilities
61 resp = self.cmd('qmp_capabilities')
62 if "return" in resp:
63 return greeting
64 raise QMPCapabilitiesError
66 def __json_read(self, only_event=False):
67 while True:
68 data = self.__sockfile.readline()
69 if not data:
70 return
71 resp = json.loads(data)
72 if 'event' in resp:
73 if self._debug:
74 print >>sys.stderr, "QMP:<<< %s" % resp
75 self.__events.append(resp)
76 if not only_event:
77 continue
78 return resp
80 error = socket.error
82 def __get_events(self, wait=False):
83 """
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
90 period elapses.
91 @raise QMPConnectError: If wait is True but no events could be retrieved
92 or if some other error occurred.
93 """
95 # Check for new events regardless and pull them into the cache:
96 self.__sock.setblocking(0)
97 try:
98 self.__json_read()
99 except socket.error as err:
100 if err[0] == errno.EAGAIN:
101 # No data available
102 pass
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)
110 try:
111 ret = self.__json_read(only_event=True)
112 except socket.timeout:
113 raise QMPTimeoutError("Timeout waiting for event")
114 except:
115 raise QMPConnectError("Error while reading from socket")
116 if ret is None:
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()
131 if negotiate:
132 return self.__negotiate_capabilities()
134 def accept(self):
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
153 been closed
155 if self._debug:
156 print >>sys.stderr, "QMP:>>> %s" % qmp_cmd
157 try:
158 self.__sock.sendall(json.dumps(qmp_cmd))
159 except socket.error as err:
160 if err[0] == errno.EPIPE:
161 return
162 raise socket.error(err)
163 resp = self.__json_read()
164 if self._debug:
165 print >>sys.stderr, "QMP:<<< %s" % resp
166 return 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 }
177 if args:
178 qmp_cmd['arguments'] = args
179 if id:
180 qmp_cmd['id'] = id
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'])
187 return ret['return']
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
197 period elapses.
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)
205 if self.__events:
206 return self.__events.pop(0)
207 return None
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
217 period elapses.
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)
224 return self.__events
226 def clear_events(self):
228 Clear current list of pending events.
230 self.__events = []
232 def close(self):
233 self.__sock.close()
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