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.
23 LOG
= logging
.getLogger(__name__
)
26 class QEMUMachineError(Exception):
28 Exception called when an error in QEMUMachine happens.
32 class MonitorResponseError(qmp
.qmp
.QMPError
):
34 Represents erroneous QMP monitor reply
36 def __init__(self
, reply
):
38 desc
= reply
["error"]["desc"]
41 super(MonitorResponseError
, self
).__init
__(desc
)
45 class QEMUMachine(object):
48 Use this object as a context manager to ensure the QEMU process terminates::
50 with VM(binary) as vm:
52 # vm is guaranteed to be shut down here
55 def __init__(self
, binary
, args
=None, wrapper
=None, name
=None,
56 test_dir
="/var/tmp", monitor_address
=None,
57 socket_scm_helper
=None, debug
=False):
59 Initialize a QEMUMachine
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.
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")
83 self
._args
= list(args
) # Force copy args in case we modify them
84 self
._wrapper
= wrapper
87 self
._socket
_scm
_helper
= socket_scm_helper
90 self
._qemu
_full
_args
= None
92 # just in case logging wasn't configured by the main script:
93 logging
.basicConfig(level
=(logging
.DEBUG
if debug
else logging
.WARN
))
98 def __exit__(self
, exc_type
, exc_val
, exc_tb
):
102 # This can be used to add an unused monitor instance.
103 def add_monitor_telnet(self
, ip
, port
):
104 args
= 'tcp:%s:%d,server,nowait,telnet' % (ip
, port
)
105 self
._args
.append('-monitor')
106 self
._args
.append(args
)
108 def add_fd(self
, fd
, fdset
, opaque
, opts
=''):
109 '''Pass a file descriptor to the VM'''
110 options
= ['fd=%d' % fd
,
112 'opaque=%s' % opaque
]
116 self
._args
.append('-add-fd')
117 self
._args
.append(','.join(options
))
120 def send_fd_scm(self
, fd_file_path
):
121 # In iotest.py, the qmp should always use unix socket.
122 assert self
._qmp
.is_scm_available()
123 if self
._socket
_scm
_helper
is None:
124 raise QEMUMachineError("No path to socket_scm_helper set")
125 if not os
.path
.exists(self
._socket
_scm
_helper
):
126 raise QEMUMachineError("%s does not exist" %
127 self
._socket
_scm
_helper
)
128 fd_param
= ["%s" % self
._socket
_scm
_helper
,
129 "%d" % self
._qmp
.get_sock_fd(),
131 devnull
= open(os
.path
.devnull
, 'rb')
132 proc
= subprocess
.Popen(fd_param
, stdin
=devnull
, stdout
=subprocess
.PIPE
,
133 stderr
=subprocess
.STDOUT
)
134 output
= proc
.communicate()[0]
138 return proc
.returncode
141 def _remove_if_exists(path
):
142 '''Remove file object at path if it exists'''
145 except OSError as exception
:
146 if exception
.errno
== errno
.ENOENT
:
150 def is_running(self
):
151 return self
._popen
is not None and self
._popen
.returncode
is None
154 if self
._popen
is None:
156 return self
._popen
.returncode
159 if not self
.is_running():
161 return self
._popen
.pid
163 def _load_io_log(self
):
164 with
open(self
._qemu
_log
_path
, "r") as iolog
:
165 self
._iolog
= iolog
.read()
167 def _base_args(self
):
168 if isinstance(self
._monitor
_address
, tuple):
169 moncdev
= "socket,id=mon,host=%s,port=%s" % (
170 self
._monitor
_address
[0],
171 self
._monitor
_address
[1])
173 moncdev
= 'socket,id=mon,path=%s' % self
._monitor
_address
174 return ['-chardev', moncdev
,
175 '-mon', 'chardev=mon,mode=control',
176 '-display', 'none', '-vga', 'none']
178 def _pre_launch(self
):
179 self
._qmp
= qmp
.qmp
.QEMUMonitorProtocol(self
._monitor
_address
,
183 def _post_launch(self
):
186 def _post_shutdown(self
):
187 if not isinstance(self
._monitor
_address
, tuple):
188 self
._remove
_if
_exists
(self
._monitor
_address
)
189 self
._remove
_if
_exists
(self
._qemu
_log
_path
)
192 '''Launch the VM and establish a QMP connection'''
194 self
._qemu
_full
_args
= None
195 devnull
= open(os
.path
.devnull
, 'rb')
196 qemulog
= open(self
._qemu
_log
_path
, 'wb')
199 self
._qemu
_full
_args
= (self
._wrapper
+ [self
._binary
] +
200 self
._base
_args
() + self
._args
)
201 self
._popen
= subprocess
.Popen(self
._qemu
_full
_args
,
204 stderr
=subprocess
.STDOUT
,
208 if self
.is_running():
212 self
._post
_shutdown
()
214 LOG
.debug('Error launching VM')
215 if self
._qemu
_full
_args
:
216 LOG
.debug('Command: %r', ' '.join(self
._qemu
_full
_args
))
218 LOG
.debug('Output: %r', self
._iolog
)
222 '''Wait for the VM to power off'''
226 self
._post
_shutdown
()
229 '''Terminate the VM and clean up'''
230 if self
.is_running():
232 self
._qmp
.cmd('quit')
239 self
._post
_shutdown
()
241 exitcode
= self
.exitcode()
242 if exitcode
is not None and exitcode
< 0:
243 msg
= 'qemu received signal %i: %s'
244 if self
._qemu
_full
_args
:
245 command
= ' '.join(self
._qemu
_full
_args
)
248 LOG
.warn(msg
, exitcode
, command
)
250 def qmp(self
, cmd
, conv_keys
=True, **args
):
251 '''Invoke a QMP command and return the response dict'''
253 for key
, value
in args
.iteritems():
255 qmp_args
[key
.replace('_', '-')] = value
257 qmp_args
[key
] = value
259 return self
._qmp
.cmd(cmd
, args
=qmp_args
)
261 def command(self
, cmd
, conv_keys
=True, **args
):
263 Invoke a QMP command.
264 On success return the response dict.
265 On failure raise an exception.
267 reply
= self
.qmp(cmd
, conv_keys
, **args
)
269 raise qmp
.qmp
.QMPError("Monitor is closed")
271 raise MonitorResponseError(reply
)
272 return reply
["return"]
274 def get_qmp_event(self
, wait
=False):
275 '''Poll for one queued QMP events and return it'''
276 if len(self
._events
) > 0:
277 return self
._events
.pop(0)
278 return self
._qmp
.pull_event(wait
=wait
)
280 def get_qmp_events(self
, wait
=False):
281 '''Poll for queued QMP events and return a list of dicts'''
282 events
= self
._qmp
.get_events(wait
=wait
)
283 events
.extend(self
._events
)
285 self
._qmp
.clear_events()
288 def event_wait(self
, name
, timeout
=60.0, match
=None):
290 Wait for specified timeout on named event in QMP; optionally filter
293 The 'match' is checked to be a recursive subset of the 'event'; skips
294 branch processing on match's value None
295 {"foo": {"bar": 1}} matches {"foo": None}
296 {"foo": {"bar": 1}} does not matches {"foo": {"baz": None}}
298 def event_match(event
, match
=None):
304 if isinstance(event
[key
], dict):
305 if not event_match(event
[key
], match
[key
]):
307 elif event
[key
] != match
[key
]:
314 # Search cached events
315 for event
in self
._events
:
316 if (event
['event'] == name
) and event_match(event
, match
):
317 self
._events
.remove(event
)
320 # Poll for new events
322 event
= self
._qmp
.pull_event(wait
=timeout
)
323 if (event
['event'] == name
) and event_match(event
, match
):
325 self
._events
.append(event
)
331 After self.shutdown or failed qemu execution, this returns the output