blob: b45e69153833956197a658b7091ac0d707f9ab23 [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
16import string
17import os
18import sys
19import subprocess
20import qmp.qmp
21
22
23class QEMUMachine(object):
Stefan Hajnoczid792bc32017-08-24 08:22:00 +010024 '''A QEMU VM
25
26 Use this object as a context manager to ensure the QEMU process terminates::
27
28 with VM(binary) as vm:
29 ...
30 # vm is guaranteed to be shut down here
31 '''
Daniel P. Berrange66613972016-07-20 14:23:10 +010032
Lukáš Doktor2d853c72017-08-18 16:26:04 +020033 def __init__(self, binary, args=[], wrapper=[], name=None,
34 test_dir="/var/tmp", monitor_address=None,
35 socket_scm_helper=None, debug=False):
36 '''
37 Initialize a QEMUMachine
38
39 @param binary: path to the qemu binary
40 @param args: list of extra arguments
41 @param wrapper: list of arguments used as prefix to qemu binary
42 @param name: prefix for socket and log file names (default: qemu-PID)
43 @param test_dir: where to create socket and log file
44 @param monitor_address: address for QMP monitor
45 @param socket_scm_helper: helper program, required for send_fd_scm()"
46 @param debug: enable debug mode
47 @note: Qemu process is not started until launch() is used.
48 '''
Daniel P. Berrange66613972016-07-20 14:23:10 +010049 if name is None:
50 name = "qemu-%d" % os.getpid()
51 if monitor_address is None:
52 monitor_address = os.path.join(test_dir, name + "-monitor.sock")
53 self._monitor_address = monitor_address
54 self._qemu_log_path = os.path.join(test_dir, name + ".log")
55 self._popen = None
56 self._binary = binary
Lukáš Doktor2d853c72017-08-18 16:26:04 +020057 self._args = list(args) # Force copy args in case we modify them
Daniel P. Berrange66613972016-07-20 14:23:10 +010058 self._wrapper = wrapper
59 self._events = []
60 self._iolog = None
Daniel P. Berrange4c44b4a2016-07-26 17:16:07 +010061 self._socket_scm_helper = socket_scm_helper
Daniel P. Berrange66613972016-07-20 14:23:10 +010062 self._debug = debug
Lukáš Doktor2d853c72017-08-18 16:26:04 +020063 self._qmp = None
Daniel P. Berrange66613972016-07-20 14:23:10 +010064
Stefan Hajnoczid792bc32017-08-24 08:22:00 +010065 def __enter__(self):
66 return self
67
68 def __exit__(self, exc_type, exc_val, exc_tb):
69 self.shutdown()
70 return False
71
Daniel P. Berrange66613972016-07-20 14:23:10 +010072 # This can be used to add an unused monitor instance.
73 def add_monitor_telnet(self, ip, port):
74 args = 'tcp:%s:%d,server,nowait,telnet' % (ip, port)
75 self._args.append('-monitor')
76 self._args.append(args)
77
78 def add_fd(self, fd, fdset, opaque, opts=''):
79 '''Pass a file descriptor to the VM'''
80 options = ['fd=%d' % fd,
81 'set=%d' % fdset,
82 'opaque=%s' % opaque]
83 if opts:
84 options.append(opts)
85
86 self._args.append('-add-fd')
87 self._args.append(','.join(options))
88 return self
89
90 def send_fd_scm(self, fd_file_path):
91 # In iotest.py, the qmp should always use unix socket.
92 assert self._qmp.is_scm_available()
Daniel P. Berrange4c44b4a2016-07-26 17:16:07 +010093 if self._socket_scm_helper is None:
94 print >>sys.stderr, "No path to socket_scm_helper set"
Daniel P. Berrange66613972016-07-20 14:23:10 +010095 return -1
Lukáš Doktor2d853c72017-08-18 16:26:04 +020096 if not os.path.exists(self._socket_scm_helper):
Daniel P. Berrange4c44b4a2016-07-26 17:16:07 +010097 print >>sys.stderr, "%s does not exist" % self._socket_scm_helper
98 return -1
99 fd_param = ["%s" % self._socket_scm_helper,
Daniel P. Berrange66613972016-07-20 14:23:10 +0100100 "%d" % self._qmp.get_sock_fd(),
101 "%s" % fd_file_path]
102 devnull = open('/dev/null', 'rb')
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200103 proc = subprocess.Popen(fd_param, stdin=devnull, stdout=sys.stdout,
104 stderr=sys.stderr)
105 return proc.wait()
Daniel P. Berrange66613972016-07-20 14:23:10 +0100106
107 @staticmethod
108 def _remove_if_exists(path):
109 '''Remove file object at path if it exists'''
110 try:
111 os.remove(path)
112 except OSError as exception:
113 if exception.errno == errno.ENOENT:
114 return
115 raise
116
Eduardo Habkost37bbcd52017-05-26 15:11:58 -0300117 def is_running(self):
118 return self._popen and (self._popen.returncode is None)
119
Eduardo Habkostb2b8d982017-05-26 15:11:59 -0300120 def exitcode(self):
121 if self._popen is None:
122 return None
123 return self._popen.returncode
124
Daniel P. Berrange66613972016-07-20 14:23:10 +0100125 def get_pid(self):
Eduardo Habkost37bbcd52017-05-26 15:11:58 -0300126 if not self.is_running():
Daniel P. Berrange66613972016-07-20 14:23:10 +0100127 return None
128 return self._popen.pid
129
130 def _load_io_log(self):
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200131 with open(self._qemu_log_path, "r") as iolog:
132 self._iolog = iolog.read()
Daniel P. Berrange66613972016-07-20 14:23:10 +0100133
134 def _base_args(self):
135 if isinstance(self._monitor_address, tuple):
136 moncdev = "socket,id=mon,host=%s,port=%s" % (
137 self._monitor_address[0],
138 self._monitor_address[1])
139 else:
140 moncdev = 'socket,id=mon,path=%s' % self._monitor_address
141 return ['-chardev', moncdev,
142 '-mon', 'chardev=mon,mode=control',
143 '-display', 'none', '-vga', 'none']
144
145 def _pre_launch(self):
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200146 self._qmp = qmp.qmp.QEMUMonitorProtocol(self._monitor_address,
147 server=True,
Daniel P. Berrange66613972016-07-20 14:23:10 +0100148 debug=self._debug)
149
150 def _post_launch(self):
151 self._qmp.accept()
152
153 def _post_shutdown(self):
154 if not isinstance(self._monitor_address, tuple):
155 self._remove_if_exists(self._monitor_address)
156 self._remove_if_exists(self._qemu_log_path)
157
158 def launch(self):
159 '''Launch the VM and establish a QMP connection'''
160 devnull = open('/dev/null', 'rb')
161 qemulog = open(self._qemu_log_path, 'wb')
162 try:
163 self._pre_launch()
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200164 args = (self._wrapper + [self._binary] + self._base_args() +
165 self._args)
Daniel P. Berrange66613972016-07-20 14:23:10 +0100166 self._popen = subprocess.Popen(args, stdin=devnull, stdout=qemulog,
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200167 stderr=subprocess.STDOUT,
168 shell=False)
Daniel P. Berrange66613972016-07-20 14:23:10 +0100169 self._post_launch()
170 except:
Eduardo Habkost37bbcd52017-05-26 15:11:58 -0300171 if self.is_running():
Daniel P. Berrange66613972016-07-20 14:23:10 +0100172 self._popen.kill()
Eduardo Habkost37bbcd52017-05-26 15:11:58 -0300173 self._popen.wait()
Daniel P. Berrange66613972016-07-20 14:23:10 +0100174 self._load_io_log()
175 self._post_shutdown()
Daniel P. Berrange66613972016-07-20 14:23:10 +0100176 raise
177
178 def shutdown(self):
179 '''Terminate the VM and clean up'''
Eduardo Habkost37bbcd52017-05-26 15:11:58 -0300180 if self.is_running():
Daniel P. Berrange66613972016-07-20 14:23:10 +0100181 try:
182 self._qmp.cmd('quit')
183 self._qmp.close()
184 except:
185 self._popen.kill()
186
187 exitcode = self._popen.wait()
188 if exitcode < 0:
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200189 sys.stderr.write('qemu received signal %i: %s\n'
190 % (-exitcode, ' '.join(self._args)))
Daniel P. Berrange66613972016-07-20 14:23:10 +0100191 self._load_io_log()
192 self._post_shutdown()
Daniel P. Berrange66613972016-07-20 14:23:10 +0100193
194 underscore_to_dash = string.maketrans('_', '-')
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200195
Daniel P. Berrange66613972016-07-20 14:23:10 +0100196 def qmp(self, cmd, conv_keys=True, **args):
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200197 '''Invoke a QMP command and return the response dict'''
Daniel P. Berrange66613972016-07-20 14:23:10 +0100198 qmp_args = dict()
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200199 for key in args.keys():
Daniel P. Berrange66613972016-07-20 14:23:10 +0100200 if conv_keys:
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200201 qmp_args[key.translate(self.underscore_to_dash)] = args[key]
Daniel P. Berrange66613972016-07-20 14:23:10 +0100202 else:
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200203 qmp_args[key] = args[key]
Daniel P. Berrange66613972016-07-20 14:23:10 +0100204
205 return self._qmp.cmd(cmd, args=qmp_args)
206
207 def command(self, cmd, conv_keys=True, **args):
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200208 '''
209 Invoke a QMP command.
210 On success return the response dict.
211 On failure raise an exception.
212 '''
Daniel P. Berrange66613972016-07-20 14:23:10 +0100213 reply = self.qmp(cmd, conv_keys, **args)
214 if reply is None:
215 raise Exception("Monitor is closed")
216 if "error" in reply:
217 raise Exception(reply["error"]["desc"])
218 return reply["return"]
219
220 def get_qmp_event(self, wait=False):
221 '''Poll for one queued QMP events and return it'''
222 if len(self._events) > 0:
223 return self._events.pop(0)
224 return self._qmp.pull_event(wait=wait)
225
226 def get_qmp_events(self, wait=False):
227 '''Poll for queued QMP events and return a list of dicts'''
228 events = self._qmp.get_events(wait=wait)
229 events.extend(self._events)
230 del self._events[:]
231 self._qmp.clear_events()
232 return events
233
234 def event_wait(self, name, timeout=60.0, match=None):
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200235 '''
236 Wait for specified timeout on named event in QMP; optionally filter
237 results by match.
238
239 The 'match' is checked to be a recursive subset of the 'event'; skips
240 branch processing on match's value None
241 {"foo": {"bar": 1}} matches {"foo": None}
242 {"foo": {"bar": 1}} does not matches {"foo": {"baz": None}}
243 '''
Daniel P. Berrange4c44b4a2016-07-26 17:16:07 +0100244 def event_match(event, match=None):
245 if match is None:
246 return True
247
248 for key in match:
249 if key in event:
250 if isinstance(event[key], dict):
251 if not event_match(event[key], match[key]):
252 return False
253 elif event[key] != match[key]:
254 return False
255 else:
256 return False
257
258 return True
259
Daniel P. Berrange66613972016-07-20 14:23:10 +0100260 # Search cached events
261 for event in self._events:
262 if (event['event'] == name) and event_match(event, match):
263 self._events.remove(event)
264 return event
265
266 # Poll for new events
267 while True:
268 event = self._qmp.pull_event(wait=timeout)
269 if (event['event'] == name) and event_match(event, match):
270 return event
271 self._events.append(event)
272
273 return None
274
275 def get_log(self):
Lukáš Doktor2d853c72017-08-18 16:26:04 +0200276 '''
277 After self.shutdown or failed qemu execution, this returns the output
278 of the qemu process.
279 '''
Daniel P. Berrange66613972016-07-20 14:23:10 +0100280 return self._iolog