3 # Copyright (C) 2015-2016 Red Hat Inc.
4 # Copyright (C) 2012 IBM Corp.
9 # This work is licensed under the terms of the GNU GPL, version 2. See
10 # the COPYING file in the top-level directory.
23 class QEMUMachine(object):
26 Use this object as a context manager to ensure the QEMU process terminates::
28 with VM(binary) as vm:
30 # vm is guaranteed to be shut down here
33 def __init__(self, binary, args=None, wrapper=None, name=None,
34 test_dir="/var/tmp", monitor_address=None,
35 socket_scm_helper=None, debug=False):
37 Initialize a QEMUMachine
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.
54 name = "qemu-%d" % os.getpid()
55 if monitor_address is None:
56 monitor_address = os.path.join(test_dir, name + "-monitor.sock")
57 self._monitor_address = monitor_address
58 self._qemu_log_path = os.path.join(test_dir, name + ".log")
61 self._args = list(args) # Force copy args in case we modify them
62 self._wrapper = wrapper
65 self._socket_scm_helper = socket_scm_helper
72 def __exit__(self, exc_type, exc_val, exc_tb):
76 # This can be used to add an unused monitor instance.
77 def add_monitor_telnet(self, ip, port):
78 args = 'tcp:%s:%d,server,nowait,telnet' % (ip, port)
79 self._args.append('-monitor')
80 self._args.append(args)
82 def add_fd(self, fd, fdset, opaque, opts=''):
83 '''Pass a file descriptor to the VM'''
84 options = ['fd=%d' % fd,
90 self._args.append('-add-fd')
91 self._args.append(','.join(options))
94 def send_fd_scm(self, fd_file_path):
95 # In iotest.py, the qmp should always use unix socket.
96 assert self._qmp.is_scm_available()
97 if self._socket_scm_helper is None:
98 print >>sys.stderr, "No path to socket_scm_helper set"
100 if not os.path.exists(self._socket_scm_helper):
101 print >>sys.stderr, "%s does not exist" % self._socket_scm_helper
103 fd_param = ["%s" % self._socket_scm_helper,
104 "%d" % self._qmp.get_sock_fd(),
106 devnull = open('/dev/null', 'rb')
107 proc = subprocess.Popen(fd_param, stdin=devnull, stdout=sys.stdout,
112 def _remove_if_exists(path):
113 '''Remove file object at path if it exists'''
116 except OSError as exception:
117 if exception.errno == errno.ENOENT:
121 def is_running(self):
122 return self._popen and (self._popen.returncode is None)
125 if self._popen is None:
127 return self._popen.returncode
130 if not self.is_running():
132 return self._popen.pid
134 def _load_io_log(self):
135 with open(self._qemu_log_path, "r") as iolog:
136 self._iolog = iolog.read()
138 def _base_args(self):
139 if isinstance(self._monitor_address, tuple):
140 moncdev = "socket,id=mon,host=%s,port=%s" % (
141 self._monitor_address[0],
142 self._monitor_address[1])
144 moncdev = 'socket,id=mon,path=%s' % self._monitor_address
145 return ['-chardev', moncdev,
146 '-mon', 'chardev=mon,mode=control',
147 '-display', 'none', '-vga', 'none']
149 def _pre_launch(self):
150 self._qmp = qmp.qmp.QEMUMonitorProtocol(self._monitor_address,
154 def _post_launch(self):
157 def _post_shutdown(self):
158 if not isinstance(self._monitor_address, tuple):
159 self._remove_if_exists(self._monitor_address)
160 self._remove_if_exists(self._qemu_log_path)
163 '''Launch the VM and establish a QMP connection'''
164 devnull = open('/dev/null', 'rb')
165 qemulog = open(self._qemu_log_path, 'wb')
168 args = (self._wrapper + [self._binary] + self._base_args() +
170 self._popen = subprocess.Popen(args, stdin=devnull, stdout=qemulog,
171 stderr=subprocess.STDOUT,
175 if self.is_running():
179 self._post_shutdown()
183 '''Terminate the VM and clean up'''
184 if self.is_running():
186 self._qmp.cmd('quit')
191 exitcode = self._popen.wait()
193 sys.stderr.write('qemu received signal %i: %s\n'
194 % (-exitcode, ' '.join(self._args)))
196 self._post_shutdown()
198 underscore_to_dash = string.maketrans('_', '-')
200 def qmp(self, cmd, conv_keys=True, **args):
201 '''Invoke a QMP command and return the response dict'''
203 for key, value in args.iteritems():
205 qmp_args[key.translate(self.underscore_to_dash)] = value
207 qmp_args[key] = value
209 return self._qmp.cmd(cmd, args=qmp_args)
211 def command(self, cmd, conv_keys=True, **args):
213 Invoke a QMP command.
214 On success return the response dict.
215 On failure raise an exception.
217 reply = self.qmp(cmd, conv_keys, **args)
219 raise Exception("Monitor is closed")
221 raise Exception(reply["error"]["desc"])
222 return reply["return"]
224 def get_qmp_event(self, wait=False):
225 '''Poll for one queued QMP events and return it'''
226 if len(self._events) > 0:
227 return self._events.pop(0)
228 return self._qmp.pull_event(wait=wait)
230 def get_qmp_events(self, wait=False):
231 '''Poll for queued QMP events and return a list of dicts'''
232 events = self._qmp.get_events(wait=wait)
233 events.extend(self._events)
235 self._qmp.clear_events()
238 def event_wait(self, name, timeout=60.0, match=None):
240 Wait for specified timeout on named event in QMP; optionally filter
243 The 'match' is checked to be a recursive subset of the 'event'; skips
244 branch processing on match's value None
245 {"foo": {"bar": 1}} matches {"foo": None}
246 {"foo": {"bar": 1}} does not matches {"foo": {"baz": None}}
248 def event_match(event, match=None):
254 if isinstance(event[key], dict):
255 if not event_match(event[key], match[key]):
257 elif event[key] != match[key]:
264 # Search cached events
265 for event in self._events:
266 if (event['event'] == name) and event_match(event, match):
267 self._events.remove(event)
270 # Poll for new events
272 event = self._qmp.pull_event(wait=timeout)
273 if (event['event'] == name) and event_match(event, match):
275 self._events.append(event)
281 After self.shutdown or failed qemu execution, this returns the output