1 # QEMU Monitor Protocol Python class
3 # Copyright (C) 2009, 2010 Red Hat Inc.
8 # This work is licensed under the terms of the GNU GPL, version 2. See
9 # the COPYING file in the top-level directory.
17 class QMPError(Exception):
21 class QMPConnectError(QMPError):
25 class QMPCapabilitiesError(QMPError):
29 class QMPTimeoutError(QMPError):
33 class QEMUMonitorProtocol(object):
35 #: Logger object for debugging messages
36 logger = logging.getLogger('QMP')
37 #: Socket's error class
40 timeout = socket.timeout
42 def __init__(self, address, server=False):
44 Create a QEMUMonitorProtocol class.
46 @param address: QEMU address, can be either a unix socket path (string)
47 or a tuple in the form ( address, port ) for a TCP
49 @param server: server mode listens on the socket (bool)
50 @raise socket.error on socket connection errors
51 @note No connection is established, this is done by the connect() or
55 self.__address = address
56 self.__sock = self.__get_sock()
57 self.__sockfile = None
59 self.__sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
60 self.__sock.bind(self.__address)
64 if isinstance(self.__address, tuple):
65 family = socket.AF_INET
67 family = socket.AF_UNIX
68 return socket.socket(family, socket.SOCK_STREAM)
70 def __negotiate_capabilities(self):
71 greeting = self.__json_read()
72 if greeting is None or "QMP" not in greeting:
74 # Greeting seems ok, negotiate capabilities
75 resp = self.cmd('qmp_capabilities')
78 raise QMPCapabilitiesError
80 def __json_read(self, only_event=False):
82 data = self.__sockfile.readline()
85 resp = json.loads(data)
87 self.logger.debug("<<< %s", resp)
88 self.__events.append(resp)
93 def __get_events(self, wait=False):
95 Check for new events in the stream and cache them in __events.
97 @param wait (bool): block until an event is available.
98 @param wait (float): If wait is a float, treat it as a timeout value.
100 @raise QMPTimeoutError: If a timeout float is provided and the timeout
102 @raise QMPConnectError: If wait is True but no events could be
103 retrieved or if some other error occurred.
106 # Check for new events regardless and pull them into the cache:
107 self.__sock.setblocking(0)
110 except socket.error as err:
111 if err[0] == errno.EAGAIN:
114 self.__sock.setblocking(1)
116 # Wait for new events, if needed.
117 # if wait is 0.0, this means "no wait" and is also implicitly false.
118 if not self.__events and wait:
119 if isinstance(wait, float):
120 self.__sock.settimeout(wait)
122 ret = self.__json_read(only_event=True)
123 except socket.timeout:
124 raise QMPTimeoutError("Timeout waiting for event")
126 raise QMPConnectError("Error while reading from socket")
128 raise QMPConnectError("Error while reading from socket")
129 self.__sock.settimeout(None)
131 def connect(self, negotiate=True):
133 Connect to the QMP Monitor and perform capabilities negotiation.
135 @return QMP greeting dict
136 @raise socket.error on socket connection errors
137 @raise QMPConnectError if the greeting is not received
138 @raise QMPCapabilitiesError if fails to negotiate capabilities
140 self.__sock.connect(self.__address)
141 self.__sockfile = self.__sock.makefile()
143 return self.__negotiate_capabilities()
147 Await connection from QMP Monitor and perform capabilities negotiation.
149 @return QMP greeting dict
150 @raise socket.error on socket connection errors
151 @raise QMPConnectError if the greeting is not received
152 @raise QMPCapabilitiesError if fails to negotiate capabilities
154 self.__sock.settimeout(15)
155 self.__sock, _ = self.__sock.accept()
156 self.__sockfile = self.__sock.makefile()
157 return self.__negotiate_capabilities()
159 def cmd_obj(self, qmp_cmd):
161 Send a QMP command to the QMP Monitor.
163 @param qmp_cmd: QMP command to be sent as a Python dict
164 @return QMP response as a Python dict or None if the connection has
167 self.logger.debug(">>> %s", qmp_cmd)
169 self.__sock.sendall(json.dumps(qmp_cmd).encode('utf-8'))
170 except socket.error as err:
171 if err[0] == errno.EPIPE:
173 raise socket.error(err)
174 resp = self.__json_read()
175 self.logger.debug("<<< %s", resp)
178 def cmd(self, name, args=None, cmd_id=None):
180 Build a QMP command and send it to the QMP Monitor.
182 @param name: command name (string)
183 @param args: command arguments (dict)
184 @param cmd_id: command id (dict, list, string or int)
186 qmp_cmd = {'execute': name}
188 qmp_cmd['arguments'] = args
190 qmp_cmd['id'] = cmd_id
191 return self.cmd_obj(qmp_cmd)
193 def command(self, cmd, **kwds):
195 Build and send a QMP command to the monitor, report errors if any
197 ret = self.cmd(cmd, kwds)
199 raise Exception(ret['error']['desc'])
202 def pull_event(self, wait=False):
204 Pulls a single event.
206 @param wait (bool): block until an event is available.
207 @param wait (float): If wait is a float, treat it as a timeout value.
209 @raise QMPTimeoutError: If a timeout float is provided and the timeout
211 @raise QMPConnectError: If wait is True but no events could be
212 retrieved or if some other error occurred.
214 @return The first available QMP event, or None.
216 self.__get_events(wait)
219 return self.__events.pop(0)
222 def get_events(self, wait=False):
224 Get a list of available QMP events.
226 @param wait (bool): block until an event is available.
227 @param wait (float): If wait is a float, treat it as a timeout value.
229 @raise QMPTimeoutError: If a timeout float is provided and the timeout
231 @raise QMPConnectError: If wait is True but no events could be
232 retrieved or if some other error occurred.
234 @return The list of available QMP events.
236 self.__get_events(wait)
239 def clear_events(self):
241 Clear current list of pending events.
247 self.__sockfile.close()
249 def settimeout(self, timeout):
250 self.__sock.settimeout(timeout)
252 def get_sock_fd(self):
253 return self.__sock.fileno()
255 def is_scm_available(self):
256 return self.__sock.family == socket.AF_UNIX