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
:
91 return self
._popen
.pid
93 def _load_io_log(self
):
94 with
open(self
._qemu
_log
_path
, "r") as fh
:
95 self
._iolog
= fh
.read()
98 if isinstance(self
._monitor
_address
, tuple):
99 moncdev
= "socket,id=mon,host=%s,port=%s" % (
100 self
._monitor
_address
[0],
101 self
._monitor
_address
[1])
103 moncdev
= 'socket,id=mon,path=%s' % self
._monitor
_address
104 return ['-chardev', moncdev
,
105 '-mon', 'chardev=mon,mode=control',
106 '-display', 'none', '-vga', 'none']
108 def _pre_launch(self
):
109 self
._qmp
= qmp
.qmp
.QEMUMonitorProtocol(self
._monitor
_address
, server
=True,
112 def _post_launch(self
):
115 def _post_shutdown(self
):
116 if not isinstance(self
._monitor
_address
, tuple):
117 self
._remove
_if
_exists
(self
._monitor
_address
)
118 self
._remove
_if
_exists
(self
._qemu
_log
_path
)
121 '''Launch the VM and establish a QMP connection'''
122 devnull
= open('/dev/null', 'rb')
123 qemulog
= open(self
._qemu
_log
_path
, 'wb')
126 args
= self
._wrapper
+ [self
._binary
] + self
._base
_args
() + self
._args
127 self
._popen
= subprocess
.Popen(args
, stdin
=devnull
, stdout
=qemulog
,
128 stderr
=subprocess
.STDOUT
, shell
=False)
134 self
._post
_shutdown
()
139 '''Terminate the VM and clean up'''
140 if not self
._popen
is None:
142 self
._qmp
.cmd('quit')
147 exitcode
= self
._popen
.wait()
149 sys
.stderr
.write('qemu received signal %i: %s\n' % (-exitcode
, ' '.join(self
._args
)))
151 self
._post
_shutdown
()
154 underscore_to_dash
= string
.maketrans('_', '-')
155 def qmp(self
, cmd
, conv_keys
=True, **args
):
156 '''Invoke a QMP command and return the result dict'''
158 for k
in args
.keys():
160 qmp_args
[k
.translate(self
.underscore_to_dash
)] = args
[k
]
162 qmp_args
[k
] = args
[k
]
164 return self
._qmp
.cmd(cmd
, args
=qmp_args
)
166 def command(self
, cmd
, conv_keys
=True, **args
):
167 reply
= self
.qmp(cmd
, conv_keys
, **args
)
169 raise Exception("Monitor is closed")
171 raise Exception(reply
["error"]["desc"])
172 return reply
["return"]
174 def get_qmp_event(self
, wait
=False):
175 '''Poll for one queued QMP events and return it'''
176 if len(self
._events
) > 0:
177 return self
._events
.pop(0)
178 return self
._qmp
.pull_event(wait
=wait
)
180 def get_qmp_events(self
, wait
=False):
181 '''Poll for queued QMP events and return a list of dicts'''
182 events
= self
._qmp
.get_events(wait
=wait
)
183 events
.extend(self
._events
)
185 self
._qmp
.clear_events()
188 def event_wait(self
, name
, timeout
=60.0, match
=None):
189 # Test if 'match' is a recursive subset of 'event'
190 def event_match(event
, match
=None):
196 if isinstance(event
[key
], dict):
197 if not event_match(event
[key
], match
[key
]):
199 elif event
[key
] != match
[key
]:
206 # Search cached events
207 for event
in self
._events
:
208 if (event
['event'] == name
) and event_match(event
, match
):
209 self
._events
.remove(event
)
212 # Poll for new events
214 event
= self
._qmp
.pull_event(wait
=timeout
)
215 if (event
['event'] == name
) and event_match(event
, match
):
217 self
._events
.append(event
)