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):
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 @note: Qemu process is not started until launch() is used.
75 name
= "qemu-%d" % os
.getpid()
76 if monitor_address
is None:
77 monitor_address
= os
.path
.join(test_dir
, name
+ "-monitor.sock")
78 self
._monitor
_address
= monitor_address
79 self
._qemu
_log
_path
= os
.path
.join(test_dir
, name
+ ".log")
82 self
._args
= list(args
) # Force copy args in case we modify them
83 self
._wrapper
= wrapper
86 self
._socket
_scm
_helper
= socket_scm_helper
88 self
._qemu
_full
_args
= None
90 # just in case logging wasn't configured by the main script:
96 def __exit__(self
, exc_type
, exc_val
, exc_tb
):
100 # This can be used to add an unused monitor instance.
101 def add_monitor_telnet(self
, ip
, port
):
102 args
= 'tcp:%s:%d,server,nowait,telnet' % (ip
, port
)
103 self
._args
.append('-monitor')
104 self
._args
.append(args
)
106 def add_fd(self
, fd
, fdset
, opaque
, opts
=''):
107 '''Pass a file descriptor to the VM'''
108 options
= ['fd=%d' % fd
,
110 'opaque=%s' % opaque
]
114 self
._args
.append('-add-fd')
115 self
._args
.append(','.join(options
))
118 def send_fd_scm(self
, fd_file_path
):
119 # In iotest.py, the qmp should always use unix socket.
120 assert self
._qmp
.is_scm_available()
121 if self
._socket
_scm
_helper
is None:
122 raise QEMUMachineError("No path to socket_scm_helper set")
123 if not os
.path
.exists(self
._socket
_scm
_helper
):
124 raise QEMUMachineError("%s does not exist" %
125 self
._socket
_scm
_helper
)
126 fd_param
= ["%s" % self
._socket
_scm
_helper
,
127 "%d" % self
._qmp
.get_sock_fd(),
129 devnull
= open(os
.path
.devnull
, 'rb')
130 proc
= subprocess
.Popen(fd_param
, stdin
=devnull
, stdout
=subprocess
.PIPE
,
131 stderr
=subprocess
.STDOUT
)
132 output
= proc
.communicate()[0]
136 return proc
.returncode
139 def _remove_if_exists(path
):
140 '''Remove file object at path if it exists'''
143 except OSError as exception
:
144 if exception
.errno
== errno
.ENOENT
:
148 def is_running(self
):
149 return self
._popen
is not None and self
._popen
.returncode
is None
152 if self
._popen
is None:
154 return self
._popen
.returncode
157 if not self
.is_running():
159 return self
._popen
.pid
161 def _load_io_log(self
):
162 with
open(self
._qemu
_log
_path
, "r") as iolog
:
163 self
._iolog
= iolog
.read()
165 def _base_args(self
):
166 if isinstance(self
._monitor
_address
, tuple):
167 moncdev
= "socket,id=mon,host=%s,port=%s" % (
168 self
._monitor
_address
[0],
169 self
._monitor
_address
[1])
171 moncdev
= 'socket,id=mon,path=%s' % self
._monitor
_address
172 return ['-chardev', moncdev
,
173 '-mon', 'chardev=mon,mode=control',
174 '-display', 'none', '-vga', 'none']
176 def _pre_launch(self
):
177 self
._qmp
= qmp
.qmp
.QEMUMonitorProtocol(self
._monitor
_address
,
180 def _post_launch(self
):
183 def _post_shutdown(self
):
184 if not isinstance(self
._monitor
_address
, tuple):
185 self
._remove
_if
_exists
(self
._monitor
_address
)
186 self
._remove
_if
_exists
(self
._qemu
_log
_path
)
189 '''Launch the VM and establish a QMP connection'''
191 self
._qemu
_full
_args
= None
192 devnull
= open(os
.path
.devnull
, 'rb')
193 qemulog
= open(self
._qemu
_log
_path
, 'wb')
196 self
._qemu
_full
_args
= (self
._wrapper
+ [self
._binary
] +
197 self
._base
_args
() + self
._args
)
198 self
._popen
= subprocess
.Popen(self
._qemu
_full
_args
,
201 stderr
=subprocess
.STDOUT
,
205 if self
.is_running():
209 self
._post
_shutdown
()
211 LOG
.debug('Error launching VM')
212 if self
._qemu
_full
_args
:
213 LOG
.debug('Command: %r', ' '.join(self
._qemu
_full
_args
))
215 LOG
.debug('Output: %r', self
._iolog
)
219 '''Wait for the VM to power off'''
223 self
._post
_shutdown
()
226 '''Terminate the VM and clean up'''
227 if self
.is_running():
229 self
._qmp
.cmd('quit')
236 self
._post
_shutdown
()
238 exitcode
= self
.exitcode()
239 if exitcode
is not None and exitcode
< 0:
240 msg
= 'qemu received signal %i: %s'
241 if self
._qemu
_full
_args
:
242 command
= ' '.join(self
._qemu
_full
_args
)
245 LOG
.warn(msg
, exitcode
, command
)
247 def qmp(self
, cmd
, conv_keys
=True, **args
):
248 '''Invoke a QMP command and return the response dict'''
250 for key
, value
in args
.iteritems():
252 qmp_args
[key
.replace('_', '-')] = value
254 qmp_args
[key
] = value
256 return self
._qmp
.cmd(cmd
, args
=qmp_args
)
258 def command(self
, cmd
, conv_keys
=True, **args
):
260 Invoke a QMP command.
261 On success return the response dict.
262 On failure raise an exception.
264 reply
= self
.qmp(cmd
, conv_keys
, **args
)
266 raise qmp
.qmp
.QMPError("Monitor is closed")
268 raise MonitorResponseError(reply
)
269 return reply
["return"]
271 def get_qmp_event(self
, wait
=False):
272 '''Poll for one queued QMP events and return it'''
273 if len(self
._events
) > 0:
274 return self
._events
.pop(0)
275 return self
._qmp
.pull_event(wait
=wait
)
277 def get_qmp_events(self
, wait
=False):
278 '''Poll for queued QMP events and return a list of dicts'''
279 events
= self
._qmp
.get_events(wait
=wait
)
280 events
.extend(self
._events
)
282 self
._qmp
.clear_events()
285 def event_wait(self
, name
, timeout
=60.0, match
=None):
287 Wait for specified timeout on named event in QMP; optionally filter
290 The 'match' is checked to be a recursive subset of the 'event'; skips
291 branch processing on match's value None
292 {"foo": {"bar": 1}} matches {"foo": None}
293 {"foo": {"bar": 1}} does not matches {"foo": {"baz": None}}
295 def event_match(event
, match
=None):
301 if isinstance(event
[key
], dict):
302 if not event_match(event
[key
], match
[key
]):
304 elif event
[key
] != match
[key
]:
311 # Search cached events
312 for event
in self
._events
:
313 if (event
['event'] == name
) and event_match(event
, match
):
314 self
._events
.remove(event
)
317 # Poll for new events
319 event
= self
._qmp
.pull_event(wait
=timeout
)
320 if (event
['event'] == name
) and event_match(event
, match
):
322 self
._events
.append(event
)
328 After self.shutdown or failed qemu execution, this returns the output