qemu.py: Call logging.basicConfig() automatically
[qemu.git] / scripts / qemu.py
blob73d6031e028cc2bf9a3c755b163182a4f720b4e7
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 # just in case logging wasn't configured by the main script:
93 logging.basicConfig(level=(logging.DEBUG if debug else logging.WARN))
95 def __enter__(self):
96 return self
98 def __exit__(self, exc_type, exc_val, exc_tb):
99 self.shutdown()
100 return False
102 # This can be used to add an unused monitor instance.
103 def add_monitor_telnet(self, ip, port):
104 args = 'tcp:%s:%d,server,nowait,telnet' % (ip, port)
105 self._args.append('-monitor')
106 self._args.append(args)
108 def add_fd(self, fd, fdset, opaque, opts=''):
109 '''Pass a file descriptor to the VM'''
110 options = ['fd=%d' % fd,
111 'set=%d' % fdset,
112 'opaque=%s' % opaque]
113 if opts:
114 options.append(opts)
116 self._args.append('-add-fd')
117 self._args.append(','.join(options))
118 return self
120 def send_fd_scm(self, fd_file_path):
121 # In iotest.py, the qmp should always use unix socket.
122 assert self._qmp.is_scm_available()
123 if self._socket_scm_helper is None:
124 raise QEMUMachineError("No path to socket_scm_helper set")
125 if not os.path.exists(self._socket_scm_helper):
126 raise QEMUMachineError("%s does not exist" %
127 self._socket_scm_helper)
128 fd_param = ["%s" % self._socket_scm_helper,
129 "%d" % self._qmp.get_sock_fd(),
130 "%s" % fd_file_path]
131 devnull = open(os.path.devnull, 'rb')
132 proc = subprocess.Popen(fd_param, stdin=devnull, stdout=subprocess.PIPE,
133 stderr=subprocess.STDOUT)
134 output = proc.communicate()[0]
135 if output:
136 LOG.debug(output)
138 return proc.returncode
140 @staticmethod
141 def _remove_if_exists(path):
142 '''Remove file object at path if it exists'''
143 try:
144 os.remove(path)
145 except OSError as exception:
146 if exception.errno == errno.ENOENT:
147 return
148 raise
150 def is_running(self):
151 return self._popen is not None and self._popen.returncode is None
153 def exitcode(self):
154 if self._popen is None:
155 return None
156 return self._popen.returncode
158 def get_pid(self):
159 if not self.is_running():
160 return None
161 return self._popen.pid
163 def _load_io_log(self):
164 with open(self._qemu_log_path, "r") as iolog:
165 self._iolog = iolog.read()
167 def _base_args(self):
168 if isinstance(self._monitor_address, tuple):
169 moncdev = "socket,id=mon,host=%s,port=%s" % (
170 self._monitor_address[0],
171 self._monitor_address[1])
172 else:
173 moncdev = 'socket,id=mon,path=%s' % self._monitor_address
174 return ['-chardev', moncdev,
175 '-mon', 'chardev=mon,mode=control',
176 '-display', 'none', '-vga', 'none']
178 def _pre_launch(self):
179 self._qmp = qmp.qmp.QEMUMonitorProtocol(self._monitor_address,
180 server=True,
181 debug=self._debug)
183 def _post_launch(self):
184 self._qmp.accept()
186 def _post_shutdown(self):
187 if not isinstance(self._monitor_address, tuple):
188 self._remove_if_exists(self._monitor_address)
189 self._remove_if_exists(self._qemu_log_path)
191 def launch(self):
192 '''Launch the VM and establish a QMP connection'''
193 self._iolog = None
194 self._qemu_full_args = None
195 devnull = open(os.path.devnull, 'rb')
196 qemulog = open(self._qemu_log_path, 'wb')
197 try:
198 self._pre_launch()
199 self._qemu_full_args = (self._wrapper + [self._binary] +
200 self._base_args() + self._args)
201 self._popen = subprocess.Popen(self._qemu_full_args,
202 stdin=devnull,
203 stdout=qemulog,
204 stderr=subprocess.STDOUT,
205 shell=False)
206 self._post_launch()
207 except:
208 if self.is_running():
209 self._popen.kill()
210 self._popen.wait()
211 self._load_io_log()
212 self._post_shutdown()
214 LOG.debug('Error launching VM')
215 if self._qemu_full_args:
216 LOG.debug('Command: %r', ' '.join(self._qemu_full_args))
217 if self._iolog:
218 LOG.debug('Output: %r', self._iolog)
219 raise
221 def shutdown(self):
222 '''Terminate the VM and clean up'''
223 if self.is_running():
224 try:
225 self._qmp.cmd('quit')
226 self._qmp.close()
227 except:
228 self._popen.kill()
229 self._popen.wait()
231 self._load_io_log()
232 self._post_shutdown()
234 exitcode = self.exitcode()
235 if exitcode is not None and exitcode < 0:
236 msg = 'qemu received signal %i: %s'
237 if self._qemu_full_args:
238 command = ' '.join(self._qemu_full_args)
239 else:
240 command = ''
241 LOG.warn(msg, exitcode, command)
243 def qmp(self, cmd, conv_keys=True, **args):
244 '''Invoke a QMP command and return the response dict'''
245 qmp_args = dict()
246 for key, value in args.iteritems():
247 if conv_keys:
248 qmp_args[key.replace('_', '-')] = value
249 else:
250 qmp_args[key] = value
252 return self._qmp.cmd(cmd, args=qmp_args)
254 def command(self, cmd, conv_keys=True, **args):
256 Invoke a QMP command.
257 On success return the response dict.
258 On failure raise an exception.
260 reply = self.qmp(cmd, conv_keys, **args)
261 if reply is None:
262 raise qmp.qmp.QMPError("Monitor is closed")
263 if "error" in reply:
264 raise MonitorResponseError(reply)
265 return reply["return"]
267 def get_qmp_event(self, wait=False):
268 '''Poll for one queued QMP events and return it'''
269 if len(self._events) > 0:
270 return self._events.pop(0)
271 return self._qmp.pull_event(wait=wait)
273 def get_qmp_events(self, wait=False):
274 '''Poll for queued QMP events and return a list of dicts'''
275 events = self._qmp.get_events(wait=wait)
276 events.extend(self._events)
277 del self._events[:]
278 self._qmp.clear_events()
279 return events
281 def event_wait(self, name, timeout=60.0, match=None):
283 Wait for specified timeout on named event in QMP; optionally filter
284 results by match.
286 The 'match' is checked to be a recursive subset of the 'event'; skips
287 branch processing on match's value None
288 {"foo": {"bar": 1}} matches {"foo": None}
289 {"foo": {"bar": 1}} does not matches {"foo": {"baz": None}}
291 def event_match(event, match=None):
292 if match is None:
293 return True
295 for key in match:
296 if key in event:
297 if isinstance(event[key], dict):
298 if not event_match(event[key], match[key]):
299 return False
300 elif event[key] != match[key]:
301 return False
302 else:
303 return False
305 return True
307 # Search cached events
308 for event in self._events:
309 if (event['event'] == name) and event_match(event, match):
310 self._events.remove(event)
311 return event
313 # Poll for new events
314 while True:
315 event = self._qmp.pull_event(wait=timeout)
316 if (event['event'] == name) and event_match(event, match):
317 return event
318 self._events.append(event)
320 return None
322 def get_log(self):
324 After self.shutdown or failed qemu execution, this returns the output
325 of the qemu process.
327 return self._iolog