blob: 8d3d24dd2b864a89454ffaf42946ef1d124086b6 [file] [log] [blame]
Daniel P. Berrange66613972016-07-20 14:23:10 +01001# QEMU library
2#
3# Copyright (C) 2015-2016 Red Hat Inc.
4# Copyright (C) 2012 IBM Corp.
5#
6# Authors:
7# Fam Zheng <famz@redhat.com>
8#
9# This work is licensed under the terms of the GNU GPL, version 2. See
10# the COPYING file in the top-level directory.
11#
12# Based on qmp.py.
13#
14
15import errno
Amador Pahim4738b0a2017-09-01 13:28:18 +020016import logging
Daniel P. Berrange66613972016-07-20 14:23:10 +010017import os
18import sys
19import subprocess
20import qmp.qmp
21
22
Amador Pahim4738b0a2017-09-01 13:28:18 +020023LOG = logging.getLogger(__name__)
24
25
26class QEMUMachineError(Exception):
27 """
28 Exception called when an error in QEMUMachine happens.
29 """
30
31
Lukáš Doktora004e242017-08-18 16:26:08 +020032class 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
43
44
Daniel P. Berrange66613972016-07-20 14:23:10 +010045class QEMUMachine(object):
Stefan Hajnoczid792bc32017-08-24 08:22:00 +010046 '''A QEMU VM
47
48 Use this object as a context manager to ensure the QEMU process terminates::
49
50 with VM(binary) as vm:
51 ...
52 # vm is guaranteed to be shut down here
53 '''
Daniel P. Berrange66613972016-07-20 14:23:10 +010054
Lukáš Doktor2782fc52017-08-18 16:26:05 +020055 def __init__(self, binary, args=None, wrapper=None, name=None,
Lukáš Doktor2d853c72017-08-18 16:26:04 +020056 test_dir="/var/tmp", monitor_address=None,
57 socket_scm_helper=None, debug=False):
58 '''
59 Initialize a QEMUMachine
60
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 '''
Lukáš Doktor2782fc52017-08-18 16:26:05 +020071 if args is None:
72 args = []
73 if wrapper is None:
74 wrapper = []
Daniel P. Berrange66613972016-07-20 14:23:10 +010075 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
Lukáš Doktor2d853c72017-08-18 16:26:04 +020083 self._args = list(args) # Force copy args in case we modify them
Daniel P. Berrange66613972016-07-20 14:23:10 +010084 self._wrapper = wrapper
85 self._events = []
86 self._iolog = None
Daniel P. Berrange4c44b4a2016-07-26 17:16:07 +010087 self._socket_scm_helper = socket_scm_helper
Daniel P. Berrange66613972016-07-20 14:23:10 +010088 self._debug = debug
Lukáš Doktor2d853c72017-08-18 16:26:04 +020089 self._qmp = None
Daniel P. Berrange66613972016-07-20 14:23:10 +010090
Stefan Hajnoczid792bc32017-08-24 08:22:00 +010091 def __enter__(self):
92 return self
93
94 def __exit__(self, exc_type, exc_val, exc_tb):
95 self.shutdown()
96 return False
97
Daniel P. Berrange66613972016-07-20 14:23:10 +010098 # This can be used to add an unused monitor instance.
99 def add_monitor_telnet(self, ip, port):
100 args = 'tcp:%s:%d,server,nowait,telnet' % (ip, port)
101 self._args.append('-monitor')
102 self._args.append(args)
103
104 def add_fd(self, fd, fdset, opaque, opts=''):
105 '''Pass a file descriptor to the VM'''
106 options = ['fd=%d' % fd,
107 'set=%d' % fdset,
108 'opaque=%s' % opaque]
109 if opts:
110 options.append(opts)
111
112 self._args.append('-add-fd')
113 self._args.append(','.join(options))
114 return self
115
116 def send_fd_scm(self, fd_file_path):
117 # In iotest.py, the qmp should always use unix socket.
118 assert self._qmp.is_scm_available()
Daniel P. Berrange4c44b4a2016-07-26 17:16:07 +0100119 if self._socket_scm_helper is None:
Amador Pahim4738b0a2017-09-01 13:28:18 +0200120 raise QEMUMachineError("No path to socket_scm_helper set")
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200121 if not os.path.exists(self._socket_scm_helper):
Amador Pahim4738b0a2017-09-01 13:28:18 +0200122 raise QEMUMachineError("%s does not exist" %
123 self._socket_scm_helper)
Daniel P. Berrange4c44b4a2016-07-26 17:16:07 +0100124 fd_param = ["%s" % self._socket_scm_helper,
Daniel P. Berrange66613972016-07-20 14:23:10 +0100125 "%d" % self._qmp.get_sock_fd(),
126 "%s" % fd_file_path]
127 devnull = open('/dev/null', 'rb')
Amador Pahim4738b0a2017-09-01 13:28:18 +0200128 proc = subprocess.Popen(fd_param, stdin=devnull, stdout=subprocess.PIPE,
129 stderr=subprocess.STDOUT)
130 output = proc.communicate()[0]
131 if output:
132 LOG.debug(output)
133
134 return proc.returncode
Daniel P. Berrange66613972016-07-20 14:23:10 +0100135
136 @staticmethod
137 def _remove_if_exists(path):
138 '''Remove file object at path if it exists'''
139 try:
140 os.remove(path)
141 except OSError as exception:
142 if exception.errno == errno.ENOENT:
143 return
144 raise
145
Eduardo Habkost37bbcd52017-05-26 15:11:58 -0300146 def is_running(self):
Amador Pahimf6cf7f52017-09-01 13:28:17 +0200147 return self._popen is not None and self._popen.returncode is None
Eduardo Habkost37bbcd52017-05-26 15:11:58 -0300148
Eduardo Habkostb2b8d982017-05-26 15:11:59 -0300149 def exitcode(self):
150 if self._popen is None:
151 return None
152 return self._popen.returncode
153
Daniel P. Berrange66613972016-07-20 14:23:10 +0100154 def get_pid(self):
Eduardo Habkost37bbcd52017-05-26 15:11:58 -0300155 if not self.is_running():
Daniel P. Berrange66613972016-07-20 14:23:10 +0100156 return None
157 return self._popen.pid
158
159 def _load_io_log(self):
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200160 with open(self._qemu_log_path, "r") as iolog:
161 self._iolog = iolog.read()
Daniel P. Berrange66613972016-07-20 14:23:10 +0100162
163 def _base_args(self):
164 if isinstance(self._monitor_address, tuple):
165 moncdev = "socket,id=mon,host=%s,port=%s" % (
166 self._monitor_address[0],
167 self._monitor_address[1])
168 else:
169 moncdev = 'socket,id=mon,path=%s' % self._monitor_address
170 return ['-chardev', moncdev,
171 '-mon', 'chardev=mon,mode=control',
172 '-display', 'none', '-vga', 'none']
173
174 def _pre_launch(self):
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200175 self._qmp = qmp.qmp.QEMUMonitorProtocol(self._monitor_address,
176 server=True,
Daniel P. Berrange66613972016-07-20 14:23:10 +0100177 debug=self._debug)
178
179 def _post_launch(self):
180 self._qmp.accept()
181
182 def _post_shutdown(self):
183 if not isinstance(self._monitor_address, tuple):
184 self._remove_if_exists(self._monitor_address)
185 self._remove_if_exists(self._qemu_log_path)
186
187 def launch(self):
188 '''Launch the VM and establish a QMP connection'''
189 devnull = open('/dev/null', 'rb')
190 qemulog = open(self._qemu_log_path, 'wb')
191 try:
192 self._pre_launch()
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200193 args = (self._wrapper + [self._binary] + self._base_args() +
194 self._args)
Daniel P. Berrange66613972016-07-20 14:23:10 +0100195 self._popen = subprocess.Popen(args, stdin=devnull, stdout=qemulog,
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200196 stderr=subprocess.STDOUT,
197 shell=False)
Daniel P. Berrange66613972016-07-20 14:23:10 +0100198 self._post_launch()
199 except:
Eduardo Habkost37bbcd52017-05-26 15:11:58 -0300200 if self.is_running():
Daniel P. Berrange66613972016-07-20 14:23:10 +0100201 self._popen.kill()
Eduardo Habkost37bbcd52017-05-26 15:11:58 -0300202 self._popen.wait()
Daniel P. Berrange66613972016-07-20 14:23:10 +0100203 self._load_io_log()
204 self._post_shutdown()
Daniel P. Berrange66613972016-07-20 14:23:10 +0100205 raise
206
207 def shutdown(self):
208 '''Terminate the VM and clean up'''
Eduardo Habkost37bbcd52017-05-26 15:11:58 -0300209 if self.is_running():
Daniel P. Berrange66613972016-07-20 14:23:10 +0100210 try:
211 self._qmp.cmd('quit')
212 self._qmp.close()
213 except:
214 self._popen.kill()
215
216 exitcode = self._popen.wait()
217 if exitcode < 0:
Amador Pahim4738b0a2017-09-01 13:28:18 +0200218 LOG.warn('qemu received signal %i: %s', -exitcode,
219 ' '.join(self._args))
Daniel P. Berrange66613972016-07-20 14:23:10 +0100220 self._load_io_log()
221 self._post_shutdown()
Daniel P. Berrange66613972016-07-20 14:23:10 +0100222
Daniel P. Berrange66613972016-07-20 14:23:10 +0100223 def qmp(self, cmd, conv_keys=True, **args):
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200224 '''Invoke a QMP command and return the response dict'''
Daniel P. Berrange66613972016-07-20 14:23:10 +0100225 qmp_args = dict()
Lukáš Doktor7f33ca72017-08-18 16:26:06 +0200226 for key, value in args.iteritems():
Daniel P. Berrange66613972016-07-20 14:23:10 +0100227 if conv_keys:
Lukáš Doktor41f714b2017-08-18 16:26:07 +0200228 qmp_args[key.replace('_', '-')] = value
Daniel P. Berrange66613972016-07-20 14:23:10 +0100229 else:
Lukáš Doktor7f33ca72017-08-18 16:26:06 +0200230 qmp_args[key] = value
Daniel P. Berrange66613972016-07-20 14:23:10 +0100231
232 return self._qmp.cmd(cmd, args=qmp_args)
233
234 def command(self, cmd, conv_keys=True, **args):
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200235 '''
236 Invoke a QMP command.
237 On success return the response dict.
238 On failure raise an exception.
239 '''
Daniel P. Berrange66613972016-07-20 14:23:10 +0100240 reply = self.qmp(cmd, conv_keys, **args)
241 if reply is None:
Lukáš Doktora004e242017-08-18 16:26:08 +0200242 raise qmp.qmp.QMPError("Monitor is closed")
Daniel P. Berrange66613972016-07-20 14:23:10 +0100243 if "error" in reply:
Lukáš Doktora004e242017-08-18 16:26:08 +0200244 raise MonitorResponseError(reply)
Daniel P. Berrange66613972016-07-20 14:23:10 +0100245 return reply["return"]
246
247 def get_qmp_event(self, wait=False):
248 '''Poll for one queued QMP events and return it'''
249 if len(self._events) > 0:
250 return self._events.pop(0)
251 return self._qmp.pull_event(wait=wait)
252
253 def get_qmp_events(self, wait=False):
254 '''Poll for queued QMP events and return a list of dicts'''
255 events = self._qmp.get_events(wait=wait)
256 events.extend(self._events)
257 del self._events[:]
258 self._qmp.clear_events()
259 return events
260
261 def event_wait(self, name, timeout=60.0, match=None):
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200262 '''
263 Wait for specified timeout on named event in QMP; optionally filter
264 results by match.
265
266 The 'match' is checked to be a recursive subset of the 'event'; skips
267 branch processing on match's value None
268 {"foo": {"bar": 1}} matches {"foo": None}
269 {"foo": {"bar": 1}} does not matches {"foo": {"baz": None}}
270 '''
Daniel P. Berrange4c44b4a2016-07-26 17:16:07 +0100271 def event_match(event, match=None):
272 if match is None:
273 return True
274
275 for key in match:
276 if key in event:
277 if isinstance(event[key], dict):
278 if not event_match(event[key], match[key]):
279 return False
280 elif event[key] != match[key]:
281 return False
282 else:
283 return False
284
285 return True
286
Daniel P. Berrange66613972016-07-20 14:23:10 +0100287 # Search cached events
288 for event in self._events:
289 if (event['event'] == name) and event_match(event, match):
290 self._events.remove(event)
291 return event
292
293 # Poll for new events
294 while True:
295 event = self._qmp.pull_event(wait=timeout)
296 if (event['event'] == name) and event_match(event, match):
297 return event
298 self._events.append(event)
299
300 return None
301
302 def get_log(self):
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200303 '''
304 After self.shutdown or failed qemu execution, this returns the output
305 of the qemu process.
306 '''
Daniel P. Berrange66613972016-07-20 14:23:10 +0100307 return self._iolog