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 def __init__(self
, binary
, args
=[], wrapper
=[], name
=None, test_dir
="/var/tmp",
27 monitor_address
=None, socket_scm_helper
=None, debug
=False):
29 name
= "qemu-%d" % os
.getpid()
30 if monitor_address
is None:
31 monitor_address
= os
.path
.join(test_dir
, name
+ "-monitor.sock")
32 self
._monitor
_address
= monitor_address
33 self
._qemu
_log
_path
= os
.path
.join(test_dir
, name
+ ".log")
36 self
._args
= list(args
) # Force copy args in case we modify them
37 self
._wrapper
= wrapper
40 self
._socket
_scm
_helper
= socket_scm_helper
43 # This can be used to add an unused monitor instance.
44 def add_monitor_telnet(self
, ip
, port
):
45 args
= 'tcp:%s:%d,server,nowait,telnet' % (ip
, port
)
46 self
._args
.append('-monitor')
47 self
._args
.append(args
)
49 def add_fd(self
, fd
, fdset
, opaque
, opts
=''):
50 '''Pass a file descriptor to the VM'''
51 options
= ['fd=%d' % fd
,
57 self
._args
.append('-add-fd')
58 self
._args
.append(','.join(options
))
61 def send_fd_scm(self
, fd_file_path
):
62 # In iotest.py, the qmp should always use unix socket.
63 assert self
._qmp
.is_scm_available()
64 if self
._socket
_scm
_helper
is None:
65 print >>sys
.stderr
, "No path to socket_scm_helper set"
67 if os
.path
.exists(self
._socket
_scm
_helper
) == False:
68 print >>sys
.stderr
, "%s does not exist" % self
._socket
_scm
_helper
70 fd_param
= ["%s" % self
._socket
_scm
_helper
,
71 "%d" % self
._qmp
.get_sock_fd(),
73 devnull
= open('/dev/null', 'rb')
74 p
= subprocess
.Popen(fd_param
, stdin
=devnull
, stdout
=sys
.stdout
,
79 def _remove_if_exists(path
):
80 '''Remove file object at path if it exists'''
83 except OSError as exception
:
84 if exception
.errno
== errno
.ENOENT
:
89 return self
._popen
and (self
._popen
.returncode
is None)
92 if self
._popen
is None:
94 return self
._popen
.returncode
97 if not self
.is_running():
99 return self
._popen
.pid
101 def _load_io_log(self
):
102 with
open(self
._qemu
_log
_path
, "r") as fh
:
103 self
._iolog
= fh
.read()
105 def _base_args(self
):
106 if isinstance(self
._monitor
_address
, tuple):
107 moncdev
= "socket,id=mon,host=%s,port=%s" % (
108 self
._monitor
_address
[0],
109 self
._monitor
_address
[1])
111 moncdev
= 'socket,id=mon,path=%s' % self
._monitor
_address
112 return ['-chardev', moncdev
,
113 '-mon', 'chardev=mon,mode=control',
114 '-display', 'none', '-vga', 'none']
116 def _pre_launch(self
):
117 self
._qmp
= qmp
.qmp
.QEMUMonitorProtocol(self
._monitor
_address
, server
=True,
120 def _post_launch(self
):
123 def _post_shutdown(self
):
124 if not isinstance(self
._monitor
_address
, tuple):
125 self
._remove
_if
_exists
(self
._monitor
_address
)
126 self
._remove
_if
_exists
(self
._qemu
_log
_path
)
129 '''Launch the VM and establish a QMP connection'''
130 devnull
= open('/dev/null', 'rb')
131 qemulog
= open(self
._qemu
_log
_path
, 'wb')
134 args
= self
._wrapper
+ [self
._binary
] + self
._base
_args
() + self
._args
135 self
._popen
= subprocess
.Popen(args
, stdin
=devnull
, stdout
=qemulog
,
136 stderr
=subprocess
.STDOUT
, shell
=False)
139 if self
.is_running():
143 self
._post
_shutdown
()
147 '''Terminate the VM and clean up'''
148 if self
.is_running():
150 self
._qmp
.cmd('quit')
155 exitcode
= self
._popen
.wait()
157 sys
.stderr
.write('qemu received signal %i: %s\n' % (-exitcode
, ' '.join(self
._args
)))
159 self
._post
_shutdown
()
161 underscore_to_dash
= string
.maketrans('_', '-')
162 def qmp(self
, cmd
, conv_keys
=True, **args
):
163 '''Invoke a QMP command and return the result dict'''
165 for k
in args
.keys():
167 qmp_args
[k
.translate(self
.underscore_to_dash
)] = args
[k
]
169 qmp_args
[k
] = args
[k
]
171 return self
._qmp
.cmd(cmd
, args
=qmp_args
)
173 def command(self
, cmd
, conv_keys
=True, **args
):
174 reply
= self
.qmp(cmd
, conv_keys
, **args
)
176 raise Exception("Monitor is closed")
178 raise Exception(reply
["error"]["desc"])
179 return reply
["return"]
181 def get_qmp_event(self
, wait
=False):
182 '''Poll for one queued QMP events and return it'''
183 if len(self
._events
) > 0:
184 return self
._events
.pop(0)
185 return self
._qmp
.pull_event(wait
=wait
)
187 def get_qmp_events(self
, wait
=False):
188 '''Poll for queued QMP events and return a list of dicts'''
189 events
= self
._qmp
.get_events(wait
=wait
)
190 events
.extend(self
._events
)
192 self
._qmp
.clear_events()
195 def event_wait(self
, name
, timeout
=60.0, match
=None):
196 # Test if 'match' is a recursive subset of 'event'
197 def event_match(event
, match
=None):
203 if isinstance(event
[key
], dict):
204 if not event_match(event
[key
], match
[key
]):
206 elif event
[key
] != match
[key
]:
213 # Search cached events
214 for event
in self
._events
:
215 if (event
['event'] == name
) and event_match(event
, match
):
216 self
._events
.remove(event
)
219 # Poll for new events
221 event
= self
._qmp
.pull_event(wait
=timeout
)
222 if (event
['event'] == name
) and event_match(event
, match
):
224 self
._events
.append(event
)