qemu.py: improve message on negative exit code
[qemu/kevin.git] / scripts / qemu.py
blob9440261ac34fd9eb645ca70bde03953a7d902b38
1 # QEMU library
3 # Copyright (C) 2015-2016 Red Hat Inc.
4 # Copyright (C) 2012 IBM Corp.
6 # Authors:
7 # Fam Zheng <famz@redhat.com>
9 # This work is licensed under the terms of the GNU GPL, version 2. See
10 # the COPYING file in the top-level directory.
12 # Based on qmp.py.
15 import errno
16 import logging
17 import os
18 import sys
19 import subprocess
20 import qmp.qmp
23 LOG = logging.getLogger(__name__)
26 class QEMUMachineError(Exception):
27 """
28 Exception called when an error in QEMUMachine happens.
29 """
32 class MonitorResponseError(qmp.qmp.QMPError):
33 '''
34 Represents erroneous QMP monitor reply
35 '''
36 def __init__(self, reply):
37 try:
38 desc = reply["error"]["desc"]
39 except KeyError:
40 desc = reply
41 super(MonitorResponseError, self).__init__(desc)
42 self.reply = reply
45 class QEMUMachine(object):
46 '''A QEMU VM
48 Use this object as a context manager to ensure the QEMU process terminates::
50 with VM(binary) as vm:
51 ...
52 # vm is guaranteed to be shut down here
53 '''
55 def __init__(self, binary, args=None, wrapper=None, name=None,
56 test_dir="/var/tmp", monitor_address=None,
57 socket_scm_helper=None, debug=False):
58 '''
59 Initialize a QEMUMachine
61 @param binary: path to the qemu binary
62 @param args: list of extra arguments
63 @param wrapper: list of arguments used as prefix to qemu binary
64 @param name: prefix for socket and log file names (default: qemu-PID)
65 @param test_dir: where to create socket and log file
66 @param monitor_address: address for QMP monitor
67 @param socket_scm_helper: helper program, required for send_fd_scm()"
68 @param debug: enable debug mode
69 @note: Qemu process is not started until launch() is used.
70 '''
71 if args is None:
72 args = []
73 if wrapper is None:
74 wrapper = []
75 if name is None:
76 name = "qemu-%d" % os.getpid()
77 if monitor_address is None:
78 monitor_address = os.path.join(test_dir, name + "-monitor.sock")
79 self._monitor_address = monitor_address
80 self._qemu_log_path = os.path.join(test_dir, name + ".log")
81 self._popen = None
82 self._binary = binary
83 self._args = list(args) # Force copy args in case we modify them
84 self._wrapper = wrapper
85 self._events = []
86 self._iolog = None
87 self._socket_scm_helper = socket_scm_helper
88 self._debug = debug
89 self._qmp = None
90 self._qemu_full_args = None
92 def __enter__(self):
93 return self
95 def __exit__(self, exc_type, exc_val, exc_tb):
96 self.shutdown()
97 return False
99 # This can be used to add an unused monitor instance.
100 def add_monitor_telnet(self, ip, port):
101 args = 'tcp:%s:%d,server,nowait,telnet' % (ip, port)
102 self._args.append('-monitor')
103 self._args.append(args)
105 def add_fd(self, fd, fdset, opaque, opts=''):
106 '''Pass a file descriptor to the VM'''
107 options = ['fd=%d' % fd,
108 'set=%d' % fdset,
109 'opaque=%s' % opaque]
110 if opts:
111 options.append(opts)
113 self._args.append('-add-fd')
114 self._args.append(','.join(options))
115 return self
117 def send_fd_scm(self, fd_file_path):
118 # In iotest.py, the qmp should always use unix socket.
119 assert self._qmp.is_scm_available()
120 if self._socket_scm_helper is None:
121 raise QEMUMachineError("No path to socket_scm_helper set")
122 if not os.path.exists(self._socket_scm_helper):
123 raise QEMUMachineError("%s does not exist" %
124 self._socket_scm_helper)
125 fd_param = ["%s" % self._socket_scm_helper,
126 "%d" % self._qmp.get_sock_fd(),
127 "%s" % fd_file_path]
128 devnull = open(os.path.devnull, 'rb')
129 proc = subprocess.Popen(fd_param, stdin=devnull, stdout=subprocess.PIPE,
130 stderr=subprocess.STDOUT)
131 output = proc.communicate()[0]
132 if output:
133 LOG.debug(output)
135 return proc.returncode
137 @staticmethod
138 def _remove_if_exists(path):
139 '''Remove file object at path if it exists'''
140 try:
141 os.remove(path)
142 except OSError as exception:
143 if exception.errno == errno.ENOENT:
144 return
145 raise
147 def is_running(self):
148 return self._popen is not None and self._popen.returncode is None
150 def exitcode(self):
151 if self._popen is None:
152 return None
153 return self._popen.returncode
155 def get_pid(self):
156 if not self.is_running():
157 return None
158 return self._popen.pid
160 def _load_io_log(self):
161 with open(self._qemu_log_path, "r") as iolog:
162 self._iolog = iolog.read()
164 def _base_args(self):
165 if isinstance(self._monitor_address, tuple):
166 moncdev = "socket,id=mon,host=%s,port=%s" % (
167 self._monitor_address[0],
168 self._monitor_address[1])
169 else:
170 moncdev = 'socket,id=mon,path=%s' % self._monitor_address
171 return ['-chardev', moncdev,
172 '-mon', 'chardev=mon,mode=control',
173 '-display', 'none', '-vga', 'none']
175 def _pre_launch(self):
176 self._qmp = qmp.qmp.QEMUMonitorProtocol(self._monitor_address,
177 server=True,
178 debug=self._debug)
180 def _post_launch(self):
181 self._qmp.accept()
183 def _post_shutdown(self):
184 if not isinstance(self._monitor_address, tuple):
185 self._remove_if_exists(self._monitor_address)
186 self._remove_if_exists(self._qemu_log_path)
188 def launch(self):
189 '''Launch the VM and establish a QMP connection'''
190 self._qemu_full_args = None
191 devnull = open(os.path.devnull, 'rb')
192 qemulog = open(self._qemu_log_path, 'wb')
193 try:
194 self._pre_launch()
195 self._qemu_full_args = self._wrapper + [self._binary] +
196 self._base_args() + self._args
197 self._popen = subprocess.Popen(self._qemu_full_args,
198 stdin=devnull,
199 stdout=qemulog,
200 stderr=subprocess.STDOUT,
201 shell=False)
202 self._post_launch()
203 except:
204 if self.is_running():
205 self._popen.kill()
206 self._popen.wait()
207 self._load_io_log()
208 self._post_shutdown()
209 raise
211 def shutdown(self):
212 '''Terminate the VM and clean up'''
213 if self.is_running():
214 try:
215 self._qmp.cmd('quit')
216 self._qmp.close()
217 except:
218 self._popen.kill()
219 self._popen.wait()
221 self._load_io_log()
222 self._post_shutdown()
224 exitcode = self.exitcode()
225 if exitcode is not None and exitcode < 0:
226 msg = 'qemu received signal %i: %s'
227 if self._qemu_full_args:
228 command = ' '.join(self._qemu_full_args)
229 else:
230 command = ''
231 LOG.warn(msg, exitcode, command)
233 def qmp(self, cmd, conv_keys=True, **args):
234 '''Invoke a QMP command and return the response dict'''
235 qmp_args = dict()
236 for key, value in args.iteritems():
237 if conv_keys:
238 qmp_args[key.replace('_', '-')] = value
239 else:
240 qmp_args[key] = value
242 return self._qmp.cmd(cmd, args=qmp_args)
244 def command(self, cmd, conv_keys=True, **args):
246 Invoke a QMP command.
247 On success return the response dict.
248 On failure raise an exception.
250 reply = self.qmp(cmd, conv_keys, **args)
251 if reply is None:
252 raise qmp.qmp.QMPError("Monitor is closed")
253 if "error" in reply:
254 raise MonitorResponseError(reply)
255 return reply["return"]
257 def get_qmp_event(self, wait=False):
258 '''Poll for one queued QMP events and return it'''
259 if len(self._events) > 0:
260 return self._events.pop(0)
261 return self._qmp.pull_event(wait=wait)
263 def get_qmp_events(self, wait=False):
264 '''Poll for queued QMP events and return a list of dicts'''
265 events = self._qmp.get_events(wait=wait)
266 events.extend(self._events)
267 del self._events[:]
268 self._qmp.clear_events()
269 return events
271 def event_wait(self, name, timeout=60.0, match=None):
273 Wait for specified timeout on named event in QMP; optionally filter
274 results by match.
276 The 'match' is checked to be a recursive subset of the 'event'; skips
277 branch processing on match's value None
278 {"foo": {"bar": 1}} matches {"foo": None}
279 {"foo": {"bar": 1}} does not matches {"foo": {"baz": None}}
281 def event_match(event, match=None):
282 if match is None:
283 return True
285 for key in match:
286 if key in event:
287 if isinstance(event[key], dict):
288 if not event_match(event[key], match[key]):
289 return False
290 elif event[key] != match[key]:
291 return False
292 else:
293 return False
295 return True
297 # Search cached events
298 for event in self._events:
299 if (event['event'] == name) and event_match(event, match):
300 self._events.remove(event)
301 return event
303 # Poll for new events
304 while True:
305 event = self._qmp.pull_event(wait=timeout)
306 if (event['event'] == name) and event_match(event, match):
307 return event
308 self._events.append(event)
310 return None
312 def get_log(self):
314 After self.shutdown or failed qemu execution, this returns the output
315 of the qemu process.
317 return self._iolog