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 class QEMUMachine(object):
26 Use this object as a context manager to ensure the QEMU process terminates::
28 with VM(binary) as vm:
30 # vm is guaranteed to be shut down here
33 def __init__(self
, binary
, args
=[], wrapper
=[], name
=None, test_dir
="/var/tmp",
34 monitor_address
=None, socket_scm_helper
=None, debug
=False):
36 name
= "qemu-%d" % os
.getpid()
37 if monitor_address
is None:
38 monitor_address
= os
.path
.join(test_dir
, name
+ "-monitor.sock")
39 self
._monitor
_address
= monitor_address
40 self
._qemu
_log
_path
= os
.path
.join(test_dir
, name
+ ".log")
43 self
._args
= list(args
) # Force copy args in case we modify them
44 self
._wrapper
= wrapper
47 self
._socket
_scm
_helper
= socket_scm_helper
53 def __exit__(self
, exc_type
, exc_val
, exc_tb
):
57 # This can be used to add an unused monitor instance.
58 def add_monitor_telnet(self
, ip
, port
):
59 args
= 'tcp:%s:%d,server,nowait,telnet' % (ip
, port
)
60 self
._args
.append('-monitor')
61 self
._args
.append(args
)
63 def add_fd(self
, fd
, fdset
, opaque
, opts
=''):
64 '''Pass a file descriptor to the VM'''
65 options
= ['fd=%d' % fd
,
71 self
._args
.append('-add-fd')
72 self
._args
.append(','.join(options
))
75 def send_fd_scm(self
, fd_file_path
):
76 # In iotest.py, the qmp should always use unix socket.
77 assert self
._qmp
.is_scm_available()
78 if self
._socket
_scm
_helper
is None:
79 print >>sys
.stderr
, "No path to socket_scm_helper set"
81 if os
.path
.exists(self
._socket
_scm
_helper
) == False:
82 print >>sys
.stderr
, "%s does not exist" % self
._socket
_scm
_helper
84 fd_param
= ["%s" % self
._socket
_scm
_helper
,
85 "%d" % self
._qmp
.get_sock_fd(),
87 devnull
= open('/dev/null', 'rb')
88 p
= subprocess
.Popen(fd_param
, stdin
=devnull
, stdout
=sys
.stdout
,
93 def _remove_if_exists(path
):
94 '''Remove file object at path if it exists'''
97 except OSError as exception
:
98 if exception
.errno
== errno
.ENOENT
:
102 def is_running(self
):
103 return self
._popen
and (self
._popen
.returncode
is None)
106 if self
._popen
is None:
108 return self
._popen
.returncode
111 if not self
.is_running():
113 return self
._popen
.pid
115 def _load_io_log(self
):
116 with
open(self
._qemu
_log
_path
, "r") as fh
:
117 self
._iolog
= fh
.read()
119 def _base_args(self
):
120 if isinstance(self
._monitor
_address
, tuple):
121 moncdev
= "socket,id=mon,host=%s,port=%s" % (
122 self
._monitor
_address
[0],
123 self
._monitor
_address
[1])
125 moncdev
= 'socket,id=mon,path=%s' % self
._monitor
_address
126 return ['-chardev', moncdev
,
127 '-mon', 'chardev=mon,mode=control',
128 '-display', 'none', '-vga', 'none']
130 def _pre_launch(self
):
131 self
._qmp
= qmp
.qmp
.QEMUMonitorProtocol(self
._monitor
_address
, server
=True,
134 def _post_launch(self
):
137 def _post_shutdown(self
):
138 if not isinstance(self
._monitor
_address
, tuple):
139 self
._remove
_if
_exists
(self
._monitor
_address
)
140 self
._remove
_if
_exists
(self
._qemu
_log
_path
)
143 '''Launch the VM and establish a QMP connection'''
144 devnull
= open('/dev/null', 'rb')
145 qemulog
= open(self
._qemu
_log
_path
, 'wb')
148 args
= self
._wrapper
+ [self
._binary
] + self
._base
_args
() + self
._args
149 self
._popen
= subprocess
.Popen(args
, stdin
=devnull
, stdout
=qemulog
,
150 stderr
=subprocess
.STDOUT
, shell
=False)
153 if self
.is_running():
157 self
._post
_shutdown
()
161 '''Terminate the VM and clean up'''
162 if self
.is_running():
164 self
._qmp
.cmd('quit')
169 exitcode
= self
._popen
.wait()
171 sys
.stderr
.write('qemu received signal %i: %s\n' % (-exitcode
, ' '.join(self
._args
)))
173 self
._post
_shutdown
()
175 underscore_to_dash
= string
.maketrans('_', '-')
176 def qmp(self
, cmd
, conv_keys
=True, **args
):
177 '''Invoke a QMP command and return the result dict'''
179 for k
in args
.keys():
181 qmp_args
[k
.translate(self
.underscore_to_dash
)] = args
[k
]
183 qmp_args
[k
] = args
[k
]
185 return self
._qmp
.cmd(cmd
, args
=qmp_args
)
187 def command(self
, cmd
, conv_keys
=True, **args
):
188 reply
= self
.qmp(cmd
, conv_keys
, **args
)
190 raise Exception("Monitor is closed")
192 raise Exception(reply
["error"]["desc"])
193 return reply
["return"]
195 def get_qmp_event(self
, wait
=False):
196 '''Poll for one queued QMP events and return it'''
197 if len(self
._events
) > 0:
198 return self
._events
.pop(0)
199 return self
._qmp
.pull_event(wait
=wait
)
201 def get_qmp_events(self
, wait
=False):
202 '''Poll for queued QMP events and return a list of dicts'''
203 events
= self
._qmp
.get_events(wait
=wait
)
204 events
.extend(self
._events
)
206 self
._qmp
.clear_events()
209 def event_wait(self
, name
, timeout
=60.0, match
=None):
210 # Test if 'match' is a recursive subset of 'event'
211 def event_match(event
, match
=None):
217 if isinstance(event
[key
], dict):
218 if not event_match(event
[key
], match
[key
]):
220 elif event
[key
] != match
[key
]:
227 # Search cached events
228 for event
in self
._events
:
229 if (event
['event'] == name
) and event_match(event
, match
):
230 self
._events
.remove(event
)
233 # Poll for new events
235 event
= self
._qmp
.pull_event(wait
=timeout
)
236 if (event
['event'] == name
) and event_match(event
, match
):
238 self
._events
.append(event
)