3 # Copyright (C) 2015-2016 Red Hat Inc.
4 # Copyright (C) 2012 IBM Corp.
7 # Fam Zheng <famz@redhat.com>
9 # This work is licensed under the terms of the GNU GPL, version 2. See
10 # the COPYING file in the top-level directory.
24 LOG
= logging
.getLogger(__name__
)
27 class QEMUMachineError(Exception):
29 Exception called when an error in QEMUMachine happens.
33 class MonitorResponseError(qmp
.qmp
.QMPError
):
35 Represents erroneous QMP monitor reply
37 def __init__(self
, reply
):
39 desc
= reply
["error"]["desc"]
42 super(MonitorResponseError
, self
).__init
__(desc
)
46 class QEMUMachine(object):
49 Use this object as a context manager to ensure the QEMU process terminates::
51 with VM(binary) as vm:
53 # vm is guaranteed to be shut down here
56 def __init__(self
, binary
, args
=None, wrapper
=None, name
=None,
57 test_dir
="/var/tmp", monitor_address
=None,
58 socket_scm_helper
=None):
60 Initialize a QEMUMachine
62 @param binary: path to the qemu binary
63 @param args: list of extra arguments
64 @param wrapper: list of arguments used as prefix to qemu binary
65 @param name: prefix for socket and log file names (default: qemu-PID)
66 @param test_dir: where to create socket and log file
67 @param monitor_address: address for QMP monitor
68 @param socket_scm_helper: helper program, required for send_fd_scm()"
69 @note: Qemu process is not started until launch() is used.
76 name
= "qemu-%d" % os
.getpid()
78 self
._monitor
_address
= monitor_address
79 self
._vm
_monitor
= None
80 self
._qemu
_log
_path
= None
81 self
._qemu
_log
_file
= None
84 self
._args
= list(args
) # Force copy args in case we modify them
85 self
._wrapper
= wrapper
88 self
._socket
_scm
_helper
= socket_scm_helper
90 self
._qemu
_full
_args
= None
91 self
._test
_dir
= test_dir
93 self
._launched
= False
95 # just in case logging wasn't configured by the main script:
101 def __exit__(self
, exc_type
, exc_val
, exc_tb
):
105 # This can be used to add an unused monitor instance.
106 def add_monitor_telnet(self
, ip
, port
):
107 args
= 'tcp:%s:%d,server,nowait,telnet' % (ip
, port
)
108 self
._args
.append('-monitor')
109 self
._args
.append(args
)
111 def add_fd(self
, fd
, fdset
, opaque
, opts
=''):
112 '''Pass a file descriptor to the VM'''
113 options
= ['fd=%d' % fd
,
115 'opaque=%s' % opaque
]
119 self
._args
.append('-add-fd')
120 self
._args
.append(','.join(options
))
123 def send_fd_scm(self
, fd_file_path
):
124 # In iotest.py, the qmp should always use unix socket.
125 assert self
._qmp
.is_scm_available()
126 if self
._socket
_scm
_helper
is None:
127 raise QEMUMachineError("No path to socket_scm_helper set")
128 if not os
.path
.exists(self
._socket
_scm
_helper
):
129 raise QEMUMachineError("%s does not exist" %
130 self
._socket
_scm
_helper
)
131 fd_param
= ["%s" % self
._socket
_scm
_helper
,
132 "%d" % self
._qmp
.get_sock_fd(),
134 devnull
= open(os
.path
.devnull
, 'rb')
135 proc
= subprocess
.Popen(fd_param
, stdin
=devnull
, stdout
=subprocess
.PIPE
,
136 stderr
=subprocess
.STDOUT
)
137 output
= proc
.communicate()[0]
141 return proc
.returncode
144 def _remove_if_exists(path
):
145 '''Remove file object at path if it exists'''
148 except OSError as exception
:
149 if exception
.errno
== errno
.ENOENT
:
153 def is_running(self
):
154 return self
._popen
is not None and self
._popen
.poll() is None
157 if self
._popen
is None:
159 return self
._popen
.poll()
162 if not self
.is_running():
164 return self
._popen
.pid
166 def _load_io_log(self
):
167 if self
._qemu
_log
_path
is not None:
168 with
open(self
._qemu
_log
_path
, "r") as iolog
:
169 self
._iolog
= iolog
.read()
171 def _base_args(self
):
172 if isinstance(self
._monitor
_address
, tuple):
173 moncdev
= "socket,id=mon,host=%s,port=%s" % (
174 self
._monitor
_address
[0],
175 self
._monitor
_address
[1])
177 moncdev
= 'socket,id=mon,path=%s' % self
._vm
_monitor
178 return ['-chardev', moncdev
,
179 '-mon', 'chardev=mon,mode=control',
180 '-display', 'none', '-vga', 'none']
182 def _pre_launch(self
):
183 self
._temp
_dir
= tempfile
.mkdtemp(dir=self
._test
_dir
)
184 if self
._monitor
_address
is not None:
185 self
._vm
_monitor
= self
._monitor
_address
187 self
._vm
_monitor
= os
.path
.join(self
._temp
_dir
,
188 self
._name
+ "-monitor.sock")
189 self
._qemu
_log
_path
= os
.path
.join(self
._temp
_dir
, self
._name
+ ".log")
190 self
._qemu
_log
_file
= open(self
._qemu
_log
_path
, 'wb')
192 self
._qmp
= qmp
.qmp
.QEMUMonitorProtocol(self
._vm
_monitor
,
195 def _post_launch(self
):
198 def _post_shutdown(self
):
199 if self
._qemu
_log
_file
is not None:
200 self
._qemu
_log
_file
.close()
201 self
._qemu
_log
_file
= None
203 self
._qemu
_log
_path
= None
205 if self
._temp
_dir
is not None:
206 shutil
.rmtree(self
._temp
_dir
)
207 self
._temp
_dir
= None
211 Launch the VM and make sure we cleanup and expose the
212 command line/output in case of exception
216 raise QEMUMachineError('VM already launched')
219 self
._qemu
_full
_args
= None
222 self
._launched
= True
226 LOG
.debug('Error launching VM')
227 if self
._qemu
_full
_args
:
228 LOG
.debug('Command: %r', ' '.join(self
._qemu
_full
_args
))
230 LOG
.debug('Output: %r', self
._iolog
)
234 '''Launch the VM and establish a QMP connection'''
235 devnull
= open(os
.path
.devnull
, 'rb')
237 self
._qemu
_full
_args
= (self
._wrapper
+ [self
._binary
] +
238 self
._base
_args
() + self
._args
)
239 self
._popen
= subprocess
.Popen(self
._qemu
_full
_args
,
241 stdout
=self
._qemu
_log
_file
,
242 stderr
=subprocess
.STDOUT
,
247 '''Wait for the VM to power off'''
251 self
._post
_shutdown
()
254 '''Terminate the VM and clean up'''
255 if self
.is_running():
257 self
._qmp
.cmd('quit')
264 self
._post
_shutdown
()
266 exitcode
= self
.exitcode()
267 if exitcode
is not None and exitcode
< 0:
268 msg
= 'qemu received signal %i: %s'
269 if self
._qemu
_full
_args
:
270 command
= ' '.join(self
._qemu
_full
_args
)
273 LOG
.warn(msg
, exitcode
, command
)
275 self
._launched
= False
277 def qmp(self
, cmd
, conv_keys
=True, **args
):
278 '''Invoke a QMP command and return the response dict'''
280 for key
, value
in args
.items():
282 qmp_args
[key
.replace('_', '-')] = value
284 qmp_args
[key
] = value
286 return self
._qmp
.cmd(cmd
, args
=qmp_args
)
288 def command(self
, cmd
, conv_keys
=True, **args
):
290 Invoke a QMP command.
291 On success return the response dict.
292 On failure raise an exception.
294 reply
= self
.qmp(cmd
, conv_keys
, **args
)
296 raise qmp
.qmp
.QMPError("Monitor is closed")
298 raise MonitorResponseError(reply
)
299 return reply
["return"]
301 def get_qmp_event(self
, wait
=False):
302 '''Poll for one queued QMP events and return it'''
303 if len(self
._events
) > 0:
304 return self
._events
.pop(0)
305 return self
._qmp
.pull_event(wait
=wait
)
307 def get_qmp_events(self
, wait
=False):
308 '''Poll for queued QMP events and return a list of dicts'''
309 events
= self
._qmp
.get_events(wait
=wait
)
310 events
.extend(self
._events
)
312 self
._qmp
.clear_events()
315 def event_wait(self
, name
, timeout
=60.0, match
=None):
317 Wait for specified timeout on named event in QMP; optionally filter
320 The 'match' is checked to be a recursive subset of the 'event'; skips
321 branch processing on match's value None
322 {"foo": {"bar": 1}} matches {"foo": None}
323 {"foo": {"bar": 1}} does not matches {"foo": {"baz": None}}
325 def event_match(event
, match
=None):
331 if isinstance(event
[key
], dict):
332 if not event_match(event
[key
], match
[key
]):
334 elif event
[key
] != match
[key
]:
341 # Search cached events
342 for event
in self
._events
:
343 if (event
['event'] == name
) and event_match(event
, match
):
344 self
._events
.remove(event
)
347 # Poll for new events
349 event
= self
._qmp
.pull_event(wait
=timeout
)
350 if (event
['event'] == name
) and event_match(event
, match
):
352 self
._events
.append(event
)
358 After self.shutdown or failed qemu execution, this returns the output