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
94 def __exit__(self
, exc_type
, exc_val
, exc_tb
):
98 # This can be used to add an unused monitor instance.
99 def add_monitor_telnet(self
, ip
, port
):
100 args
= 'tcp:%s:%d,server,nowait,telnet' % (ip
, port
)
101 self
._args
.append('-monitor')
102 self
._args
.append(args
)
104 def add_fd(self
, fd
, fdset
, opaque
, opts
=''):
105 '''Pass a file descriptor to the VM'''
106 options
= ['fd=%d' % fd
,
108 'opaque=%s' % opaque
]
112 self
._args
.append('-add-fd')
113 self
._args
.append(','.join(options
))
116 def send_fd_scm(self
, fd_file_path
):
117 # In iotest.py, the qmp should always use unix socket.
118 assert self
._qmp
.is_scm_available()
119 if self
._socket
_scm
_helper
is None:
120 raise QEMUMachineError("No path to socket_scm_helper set")
121 if not os
.path
.exists(self
._socket
_scm
_helper
):
122 raise QEMUMachineError("%s does not exist" %
123 self
._socket
_scm
_helper
)
124 fd_param
= ["%s" % self
._socket
_scm
_helper
,
125 "%d" % self
._qmp
.get_sock_fd(),
127 devnull
= open('/dev/null', 'rb')
128 proc
= subprocess
.Popen(fd_param
, stdin
=devnull
, stdout
=subprocess
.PIPE
,
129 stderr
=subprocess
.STDOUT
)
130 output
= proc
.communicate()[0]
134 return proc
.returncode
137 def _remove_if_exists(path
):
138 '''Remove file object at path if it exists'''
141 except OSError as exception
:
142 if exception
.errno
== errno
.ENOENT
:
146 def is_running(self
):
147 return self
._popen
is not None and self
._popen
.returncode
is None
150 if self
._popen
is None:
152 return self
._popen
.returncode
155 if not self
.is_running():
157 return self
._popen
.pid
159 def _load_io_log(self
):
160 with
open(self
._qemu
_log
_path
, "r") as iolog
:
161 self
._iolog
= iolog
.read()
163 def _base_args(self
):
164 if isinstance(self
._monitor
_address
, tuple):
165 moncdev
= "socket,id=mon,host=%s,port=%s" % (
166 self
._monitor
_address
[0],
167 self
._monitor
_address
[1])
169 moncdev
= 'socket,id=mon,path=%s' % self
._monitor
_address
170 return ['-chardev', moncdev
,
171 '-mon', 'chardev=mon,mode=control',
172 '-display', 'none', '-vga', 'none']
174 def _pre_launch(self
):
175 self
._qmp
= qmp
.qmp
.QEMUMonitorProtocol(self
._monitor
_address
,
179 def _post_launch(self
):
182 def _post_shutdown(self
):
183 if not isinstance(self
._monitor
_address
, tuple):
184 self
._remove
_if
_exists
(self
._monitor
_address
)
185 self
._remove
_if
_exists
(self
._qemu
_log
_path
)
188 '''Launch the VM and establish a QMP connection'''
189 devnull
= open('/dev/null', 'rb')
190 qemulog
= open(self
._qemu
_log
_path
, 'wb')
193 args
= (self
._wrapper
+ [self
._binary
] + self
._base
_args
() +
195 self
._popen
= subprocess
.Popen(args
, stdin
=devnull
, stdout
=qemulog
,
196 stderr
=subprocess
.STDOUT
,
200 if self
.is_running():
204 self
._post
_shutdown
()
208 '''Terminate the VM and clean up'''
209 if self
.is_running():
211 self
._qmp
.cmd('quit')
216 exitcode
= self
._popen
.wait()
218 LOG
.warn('qemu received signal %i: %s', -exitcode
,
219 ' '.join(self
._args
))
221 self
._post
_shutdown
()
223 def qmp(self
, cmd
, conv_keys
=True, **args
):
224 '''Invoke a QMP command and return the response dict'''
226 for key
, value
in args
.iteritems():
228 qmp_args
[key
.replace('_', '-')] = value
230 qmp_args
[key
] = value
232 return self
._qmp
.cmd(cmd
, args
=qmp_args
)
234 def command(self
, cmd
, conv_keys
=True, **args
):
236 Invoke a QMP command.
237 On success return the response dict.
238 On failure raise an exception.
240 reply
= self
.qmp(cmd
, conv_keys
, **args
)
242 raise qmp
.qmp
.QMPError("Monitor is closed")
244 raise MonitorResponseError(reply
)
245 return reply
["return"]
247 def get_qmp_event(self
, wait
=False):
248 '''Poll for one queued QMP events and return it'''
249 if len(self
._events
) > 0:
250 return self
._events
.pop(0)
251 return self
._qmp
.pull_event(wait
=wait
)
253 def get_qmp_events(self
, wait
=False):
254 '''Poll for queued QMP events and return a list of dicts'''
255 events
= self
._qmp
.get_events(wait
=wait
)
256 events
.extend(self
._events
)
258 self
._qmp
.clear_events()
261 def event_wait(self
, name
, timeout
=60.0, match
=None):
263 Wait for specified timeout on named event in QMP; optionally filter
266 The 'match' is checked to be a recursive subset of the 'event'; skips
267 branch processing on match's value None
268 {"foo": {"bar": 1}} matches {"foo": None}
269 {"foo": {"bar": 1}} does not matches {"foo": {"baz": None}}
271 def event_match(event
, match
=None):
277 if isinstance(event
[key
], dict):
278 if not event_match(event
[key
], match
[key
]):
280 elif event
[key
] != match
[key
]:
287 # Search cached events
288 for event
in self
._events
:
289 if (event
['event'] == name
) and event_match(event
, match
):
290 self
._events
.remove(event
)
293 # Poll for new events
295 event
= self
._qmp
.pull_event(wait
=timeout
)
296 if (event
['event'] == name
) and event_match(event
, match
):
298 self
._events
.append(event
)
304 After self.shutdown or failed qemu execution, this returns the output