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.
22 class MonitorResponseError(qmp.qmp.QMPError):
24 Represents erroneous QMP monitor reply
26 def __init__(self, reply):
28 desc = reply["error"]["desc"]
31 super(MonitorResponseError, self).__init__(desc)
35 class QEMUMachine(object):
38 Use this object as a context manager to ensure the QEMU process terminates::
40 with VM(binary) as vm:
42 # vm is guaranteed to be shut down here
45 def __init__(self, binary, args=None, wrapper=None, name=None,
46 test_dir="/var/tmp", monitor_address=None,
47 socket_scm_helper=None, debug=False):
49 Initialize a QEMUMachine
51 @param binary: path to the qemu binary
52 @param args: list of extra arguments
53 @param wrapper: list of arguments used as prefix to qemu binary
54 @param name: prefix for socket and log file names (default: qemu-PID)
55 @param test_dir: where to create socket and log file
56 @param monitor_address: address for QMP monitor
57 @param socket_scm_helper: helper program, required for send_fd_scm()"
58 @param debug: enable debug mode
59 @note: Qemu process is not started until launch() is used.
66 name = "qemu-%d" % os.getpid()
67 if monitor_address is None:
68 monitor_address = os.path.join(test_dir, name + "-monitor.sock")
69 self._monitor_address = monitor_address
70 self._qemu_log_path = os.path.join(test_dir, name + ".log")
73 self._args = list(args) # Force copy args in case we modify them
74 self._wrapper = wrapper
77 self._socket_scm_helper = socket_scm_helper
84 def __exit__(self, exc_type, exc_val, exc_tb):
88 # This can be used to add an unused monitor instance.
89 def add_monitor_telnet(self, ip, port):
90 args = 'tcp:%s:%d,server,nowait,telnet' % (ip, port)
91 self._args.append('-monitor')
92 self._args.append(args)
94 def add_fd(self, fd, fdset, opaque, opts=''):
95 '''Pass a file descriptor to the VM'''
96 options = ['fd=%d' % fd,
102 self._args.append('-add-fd')
103 self._args.append(','.join(options))
106 def send_fd_scm(self, fd_file_path):
107 # In iotest.py, the qmp should always use unix socket.
108 assert self._qmp.is_scm_available()
109 if self._socket_scm_helper is None:
110 print >>sys.stderr, "No path to socket_scm_helper set"
112 if not os.path.exists(self._socket_scm_helper):
113 print >>sys.stderr, "%s does not exist" % self._socket_scm_helper
115 fd_param = ["%s" % self._socket_scm_helper,
116 "%d" % self._qmp.get_sock_fd(),
118 devnull = open('/dev/null', 'rb')
119 proc = subprocess.Popen(fd_param, stdin=devnull, stdout=sys.stdout,
124 def _remove_if_exists(path):
125 '''Remove file object at path if it exists'''
128 except OSError as exception:
129 if exception.errno == errno.ENOENT:
133 def is_running(self):
134 return self._popen and (self._popen.returncode is None)
137 if self._popen is None:
139 return self._popen.returncode
142 if not self.is_running():
144 return self._popen.pid
146 def _load_io_log(self):
147 with open(self._qemu_log_path, "r") as iolog:
148 self._iolog = iolog.read()
150 def _base_args(self):
151 if isinstance(self._monitor_address, tuple):
152 moncdev = "socket,id=mon,host=%s,port=%s" % (
153 self._monitor_address[0],
154 self._monitor_address[1])
156 moncdev = 'socket,id=mon,path=%s' % self._monitor_address
157 return ['-chardev', moncdev,
158 '-mon', 'chardev=mon,mode=control',
159 '-display', 'none', '-vga', 'none']
161 def _pre_launch(self):
162 self._qmp = qmp.qmp.QEMUMonitorProtocol(self._monitor_address,
166 def _post_launch(self):
169 def _post_shutdown(self):
170 if not isinstance(self._monitor_address, tuple):
171 self._remove_if_exists(self._monitor_address)
172 self._remove_if_exists(self._qemu_log_path)
175 '''Launch the VM and establish a QMP connection'''
176 devnull = open('/dev/null', 'rb')
177 qemulog = open(self._qemu_log_path, 'wb')
180 args = (self._wrapper + [self._binary] + self._base_args() +
182 self._popen = subprocess.Popen(args, stdin=devnull, stdout=qemulog,
183 stderr=subprocess.STDOUT,
187 if self.is_running():
191 self._post_shutdown()
195 '''Terminate the VM and clean up'''
196 if self.is_running():
198 self._qmp.cmd('quit')
203 exitcode = self._popen.wait()
205 sys.stderr.write('qemu received signal %i: %s\n'
206 % (-exitcode, ' '.join(self._args)))
208 self._post_shutdown()
210 def qmp(self, cmd, conv_keys=True, **args):
211 '''Invoke a QMP command and return the response dict'''
213 for key, value in args.iteritems():
215 qmp_args[key.replace('_', '-')] = value
217 qmp_args[key] = value
219 return self._qmp.cmd(cmd, args=qmp_args)
221 def command(self, cmd, conv_keys=True, **args):
223 Invoke a QMP command.
224 On success return the response dict.
225 On failure raise an exception.
227 reply = self.qmp(cmd, conv_keys, **args)
229 raise qmp.qmp.QMPError("Monitor is closed")
231 raise MonitorResponseError(reply)
232 return reply["return"]
234 def get_qmp_event(self, wait=False):
235 '''Poll for one queued QMP events and return it'''
236 if len(self._events) > 0:
237 return self._events.pop(0)
238 return self._qmp.pull_event(wait=wait)
240 def get_qmp_events(self, wait=False):
241 '''Poll for queued QMP events and return a list of dicts'''
242 events = self._qmp.get_events(wait=wait)
243 events.extend(self._events)
245 self._qmp.clear_events()
248 def event_wait(self, name, timeout=60.0, match=None):
250 Wait for specified timeout on named event in QMP; optionally filter
253 The 'match' is checked to be a recursive subset of the 'event'; skips
254 branch processing on match's value None
255 {"foo": {"bar": 1}} matches {"foo": None}
256 {"foo": {"bar": 1}} does not matches {"foo": {"baz": None}}
258 def event_match(event, match=None):
264 if isinstance(event[key], dict):
265 if not event_match(event[key], match[key]):
267 elif event[key] != match[key]:
274 # Search cached events
275 for event in self._events:
276 if (event['event'] == name) and event_match(event, match):
277 self._events.remove(event)
280 # Poll for new events
282 event = self._qmp.pull_event(wait=timeout)
283 if (event['event'] == name) and event_match(event, match):
285 self._events.append(event)
291 After self.shutdown or failed qemu execution, this returns the output