blob: 5e02dd8e78775232abce925460de73bf7e6dae5a [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
Amador Pahimdab91d92017-09-01 13:28:20 +020090 self._qemu_full_args = None
Daniel P. Berrange66613972016-07-20 14:23:10 +010091
Stefan Hajnoczid792bc32017-08-24 08:22:00 +010092 def __enter__(self):
93 return self
94
95 def __exit__(self, exc_type, exc_val, exc_tb):
96 self.shutdown()
97 return False
98
Daniel P. Berrange66613972016-07-20 14:23:10 +010099 # 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)
104
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)
112
113 self._args.append('-add-fd')
114 self._args.append(','.join(options))
115 return self
116
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()
Daniel P. Berrange4c44b4a2016-07-26 17:16:07 +0100120 if self._socket_scm_helper is None:
Amador Pahim4738b0a2017-09-01 13:28:18 +0200121 raise QEMUMachineError("No path to socket_scm_helper set")
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200122 if not os.path.exists(self._socket_scm_helper):
Amador Pahim4738b0a2017-09-01 13:28:18 +0200123 raise QEMUMachineError("%s does not exist" %
124 self._socket_scm_helper)
Daniel P. Berrange4c44b4a2016-07-26 17:16:07 +0100125 fd_param = ["%s" % self._socket_scm_helper,
Daniel P. Berrange66613972016-07-20 14:23:10 +0100126 "%d" % self._qmp.get_sock_fd(),
127 "%s" % fd_file_path]
Amador Pahim63e0ba52017-09-01 13:28:19 +0200128 devnull = open(os.path.devnull, 'rb')
Amador Pahim4738b0a2017-09-01 13:28:18 +0200129 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)
134
135 return proc.returncode
Daniel P. Berrange66613972016-07-20 14:23:10 +0100136
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
146
Eduardo Habkost37bbcd52017-05-26 15:11:58 -0300147 def is_running(self):
Amador Pahimf6cf7f52017-09-01 13:28:17 +0200148 return self._popen is not None and self._popen.returncode is None
Eduardo Habkost37bbcd52017-05-26 15:11:58 -0300149
Eduardo Habkostb2b8d982017-05-26 15:11:59 -0300150 def exitcode(self):
151 if self._popen is None:
152 return None
153 return self._popen.returncode
154
Daniel P. Berrange66613972016-07-20 14:23:10 +0100155 def get_pid(self):
Eduardo Habkost37bbcd52017-05-26 15:11:58 -0300156 if not self.is_running():
Daniel P. Berrange66613972016-07-20 14:23:10 +0100157 return None
158 return self._popen.pid
159
160 def _load_io_log(self):
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200161 with open(self._qemu_log_path, "r") as iolog:
162 self._iolog = iolog.read()
Daniel P. Berrange66613972016-07-20 14:23:10 +0100163
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']
174
175 def _pre_launch(self):
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200176 self._qmp = qmp.qmp.QEMUMonitorProtocol(self._monitor_address,
177 server=True,
Daniel P. Berrange66613972016-07-20 14:23:10 +0100178 debug=self._debug)
179
180 def _post_launch(self):
181 self._qmp.accept()
182
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)
187
188 def launch(self):
189 '''Launch the VM and establish a QMP connection'''
Amador Pahimb92a0012017-09-01 13:28:21 +0200190 self._iolog = None
Amador Pahimdab91d92017-09-01 13:28:20 +0200191 self._qemu_full_args = None
Amador Pahim63e0ba52017-09-01 13:28:19 +0200192 devnull = open(os.path.devnull, 'rb')
Daniel P. Berrange66613972016-07-20 14:23:10 +0100193 qemulog = open(self._qemu_log_path, 'wb')
194 try:
195 self._pre_launch()
Kevin Wolff75637b2017-09-18 07:25:24 +0200196 self._qemu_full_args = (self._wrapper + [self._binary] +
197 self._base_args() + self._args)
Amador Pahimdab91d92017-09-01 13:28:20 +0200198 self._popen = subprocess.Popen(self._qemu_full_args,
199 stdin=devnull,
200 stdout=qemulog,
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200201 stderr=subprocess.STDOUT,
202 shell=False)
Daniel P. Berrange66613972016-07-20 14:23:10 +0100203 self._post_launch()
204 except:
Eduardo Habkost37bbcd52017-05-26 15:11:58 -0300205 if self.is_running():
Daniel P. Berrange66613972016-07-20 14:23:10 +0100206 self._popen.kill()
Eduardo Habkost37bbcd52017-05-26 15:11:58 -0300207 self._popen.wait()
Daniel P. Berrange66613972016-07-20 14:23:10 +0100208 self._load_io_log()
209 self._post_shutdown()
Amador Pahimb92a0012017-09-01 13:28:21 +0200210
211 LOG.debug('Error launching VM')
212 if self._qemu_full_args:
213 LOG.debug('Command: %r', ' '.join(self._qemu_full_args))
214 if self._iolog:
215 LOG.debug('Output: %r', self._iolog)
Daniel P. Berrange66613972016-07-20 14:23:10 +0100216 raise
217
218 def shutdown(self):
219 '''Terminate the VM and clean up'''
Eduardo Habkost37bbcd52017-05-26 15:11:58 -0300220 if self.is_running():
Daniel P. Berrange66613972016-07-20 14:23:10 +0100221 try:
222 self._qmp.cmd('quit')
223 self._qmp.close()
224 except:
225 self._popen.kill()
Amador Pahimdab91d92017-09-01 13:28:20 +0200226 self._popen.wait()
Daniel P. Berrange66613972016-07-20 14:23:10 +0100227
Daniel P. Berrange66613972016-07-20 14:23:10 +0100228 self._load_io_log()
229 self._post_shutdown()
Daniel P. Berrange66613972016-07-20 14:23:10 +0100230
Amador Pahimdab91d92017-09-01 13:28:20 +0200231 exitcode = self.exitcode()
232 if exitcode is not None and exitcode < 0:
233 msg = 'qemu received signal %i: %s'
234 if self._qemu_full_args:
235 command = ' '.join(self._qemu_full_args)
236 else:
237 command = ''
238 LOG.warn(msg, exitcode, command)
239
Daniel P. Berrange66613972016-07-20 14:23:10 +0100240 def qmp(self, cmd, conv_keys=True, **args):
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200241 '''Invoke a QMP command and return the response dict'''
Daniel P. Berrange66613972016-07-20 14:23:10 +0100242 qmp_args = dict()
Lukáš Doktor7f33ca72017-08-18 16:26:06 +0200243 for key, value in args.iteritems():
Daniel P. Berrange66613972016-07-20 14:23:10 +0100244 if conv_keys:
Lukáš Doktor41f714b2017-08-18 16:26:07 +0200245 qmp_args[key.replace('_', '-')] = value
Daniel P. Berrange66613972016-07-20 14:23:10 +0100246 else:
Lukáš Doktor7f33ca72017-08-18 16:26:06 +0200247 qmp_args[key] = value
Daniel P. Berrange66613972016-07-20 14:23:10 +0100248
249 return self._qmp.cmd(cmd, args=qmp_args)
250
251 def command(self, cmd, conv_keys=True, **args):
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200252 '''
253 Invoke a QMP command.
254 On success return the response dict.
255 On failure raise an exception.
256 '''
Daniel P. Berrange66613972016-07-20 14:23:10 +0100257 reply = self.qmp(cmd, conv_keys, **args)
258 if reply is None:
Lukáš Doktora004e242017-08-18 16:26:08 +0200259 raise qmp.qmp.QMPError("Monitor is closed")
Daniel P. Berrange66613972016-07-20 14:23:10 +0100260 if "error" in reply:
Lukáš Doktora004e242017-08-18 16:26:08 +0200261 raise MonitorResponseError(reply)
Daniel P. Berrange66613972016-07-20 14:23:10 +0100262 return reply["return"]
263
264 def get_qmp_event(self, wait=False):
265 '''Poll for one queued QMP events and return it'''
266 if len(self._events) > 0:
267 return self._events.pop(0)
268 return self._qmp.pull_event(wait=wait)
269
270 def get_qmp_events(self, wait=False):
271 '''Poll for queued QMP events and return a list of dicts'''
272 events = self._qmp.get_events(wait=wait)
273 events.extend(self._events)
274 del self._events[:]
275 self._qmp.clear_events()
276 return events
277
278 def event_wait(self, name, timeout=60.0, match=None):
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200279 '''
280 Wait for specified timeout on named event in QMP; optionally filter
281 results by match.
282
283 The 'match' is checked to be a recursive subset of the 'event'; skips
284 branch processing on match's value None
285 {"foo": {"bar": 1}} matches {"foo": None}
286 {"foo": {"bar": 1}} does not matches {"foo": {"baz": None}}
287 '''
Daniel P. Berrange4c44b4a2016-07-26 17:16:07 +0100288 def event_match(event, match=None):
289 if match is None:
290 return True
291
292 for key in match:
293 if key in event:
294 if isinstance(event[key], dict):
295 if not event_match(event[key], match[key]):
296 return False
297 elif event[key] != match[key]:
298 return False
299 else:
300 return False
301
302 return True
303
Daniel P. Berrange66613972016-07-20 14:23:10 +0100304 # Search cached events
305 for event in self._events:
306 if (event['event'] == name) and event_match(event, match):
307 self._events.remove(event)
308 return event
309
310 # Poll for new events
311 while True:
312 event = self._qmp.pull_event(wait=timeout)
313 if (event['event'] == name) and event_match(event, match):
314 return event
315 self._events.append(event)
316
317 return None
318
319 def get_log(self):
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200320 '''
321 After self.shutdown or failed qemu execution, this returns the output
322 of the qemu process.
323 '''
Daniel P. Berrange66613972016-07-20 14:23:10 +0100324 return self._iolog