1 # Common utilities and Python wrappers for qemu-iotests
3 # Copyright (C) 2012 IBM Corp.
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
25 sys
.path
.append(os
.path
.join(os
.path
.dirname(__file__
), '..', '..', 'scripts'))
26 sys
.path
.append(os
.path
.join(os
.path
.dirname(__file__
), '..', '..', 'scripts', 'qmp'))
31 __all__
= ['imgfmt', 'imgproto', 'test_dir' 'qemu_img', 'qemu_io',
32 'VM', 'QMPTestCase', 'notrun', 'main']
34 # This will not work if arguments contain spaces but is necessary if we
35 # want to support the override options that ./check supports.
36 qemu_img_args
= [os
.environ
.get('QEMU_IMG_PROG', 'qemu-img')]
37 if os
.environ
.get('QEMU_IMG_OPTIONS'):
38 qemu_img_args
+= os
.environ
['QEMU_IMG_OPTIONS'].strip().split(' ')
40 qemu_io_args
= [os
.environ
.get('QEMU_IO_PROG', 'qemu-io')]
41 if os
.environ
.get('QEMU_IO_OPTIONS'):
42 qemu_io_args
+= os
.environ
['QEMU_IO_OPTIONS'].strip().split(' ')
44 qemu_args
= [os
.environ
.get('QEMU_PROG', 'qemu')]
45 if os
.environ
.get('QEMU_OPTIONS'):
46 qemu_args
+= os
.environ
['QEMU_OPTIONS'].strip().split(' ')
48 imgfmt
= os
.environ
.get('IMGFMT', 'raw')
49 imgproto
= os
.environ
.get('IMGPROTO', 'file')
50 test_dir
= os
.environ
.get('TEST_DIR', '/var/tmp')
51 output_dir
= os
.environ
.get('OUTPUT_DIR', '.')
52 cachemode
= os
.environ
.get('CACHEMODE')
53 qemu_default_machine
= os
.environ
.get('QEMU_DEFAULT_MACHINE')
55 socket_scm_helper
= os
.environ
.get('SOCKET_SCM_HELPER', 'socket_scm_helper')
58 '''Run qemu-img and return the exit code'''
59 devnull
= open('/dev/null', 'r+')
60 exitcode
= subprocess
.call(qemu_img_args
+ list(args
), stdin
=devnull
, stdout
=devnull
)
62 sys
.stderr
.write('qemu-img received signal %i: %s\n' % (-exitcode
, ' '.join(qemu_img_args
+ list(args
))))
65 def qemu_img_verbose(*args
):
66 '''Run qemu-img without suppressing its output and return the exit code'''
67 exitcode
= subprocess
.call(qemu_img_args
+ list(args
))
69 sys
.stderr
.write('qemu-img received signal %i: %s\n' % (-exitcode
, ' '.join(qemu_img_args
+ list(args
))))
72 def qemu_img_pipe(*args
):
73 '''Run qemu-img and return its output'''
74 subp
= subprocess
.Popen(qemu_img_args
+ list(args
), stdout
=subprocess
.PIPE
)
75 exitcode
= subp
.wait()
77 sys
.stderr
.write('qemu-img received signal %i: %s\n' % (-exitcode
, ' '.join(qemu_img_args
+ list(args
))))
78 return subp
.communicate()[0]
81 '''Run qemu-io and return the stdout data'''
82 args
= qemu_io_args
+ list(args
)
83 subp
= subprocess
.Popen(args
, stdout
=subprocess
.PIPE
)
84 exitcode
= subp
.wait()
86 sys
.stderr
.write('qemu-io received signal %i: %s\n' % (-exitcode
, ' '.join(args
)))
87 return subp
.communicate()[0]
89 def compare_images(img1
, img2
):
90 '''Return True if two image files are identical'''
91 return qemu_img('compare', '-f', imgfmt
,
92 '-F', imgfmt
, img1
, img2
) == 0
94 def create_image(name
, size
):
95 '''Create a fully-allocated raw image with sector markers'''
96 file = open(name
, 'w')
99 sector
= struct
.pack('>l504xl', i
/ 512, i
/ 512)
104 # Test if 'match' is a recursive subset of 'event'
105 def event_match(event
, match
=None):
111 if isinstance(event
[key
], dict):
112 if not event_match(event
[key
], match
[key
]):
114 elif event
[key
] != match
[key
]:
125 self
._monitor
_path
= os
.path
.join(test_dir
, 'qemu-mon.%d' % os
.getpid())
126 self
._qemu
_log
_path
= os
.path
.join(test_dir
, 'qemu-log.%d' % os
.getpid())
127 self
._qtest
_path
= os
.path
.join(test_dir
, 'qemu-qtest.%d' % os
.getpid())
128 self
._args
= qemu_args
+ ['-chardev',
129 'socket,id=mon,path=' + self
._monitor
_path
,
130 '-mon', 'chardev=mon,mode=control',
131 '-qtest', 'unix:path=' + self
._qtest
_path
,
132 '-machine', 'accel=qtest',
133 '-display', 'none', '-vga', 'none']
137 # This can be used to add an unused monitor instance.
138 def add_monitor_telnet(self
, ip
, port
):
139 args
= 'tcp:%s:%d,server,nowait,telnet' % (ip
, port
)
140 self
._args
.append('-monitor')
141 self
._args
.append(args
)
143 def add_drive_raw(self
, opts
):
144 self
._args
.append('-drive')
145 self
._args
.append(opts
)
148 def add_drive(self
, path
, opts
='', interface
='virtio'):
149 '''Add a virtio-blk drive to the VM'''
150 options
= ['if=%s' % interface
,
151 'id=drive%d' % self
._num
_drives
]
154 options
.append('file=%s' % path
)
155 options
.append('format=%s' % imgfmt
)
156 options
.append('cache=%s' % cachemode
)
161 self
._args
.append('-drive')
162 self
._args
.append(','.join(options
))
163 self
._num
_drives
+= 1
166 def pause_drive(self
, drive
, event
=None):
167 '''Pause drive r/w operations'''
169 self
.pause_drive(drive
, "read_aio")
170 self
.pause_drive(drive
, "write_aio")
172 self
.qmp('human-monitor-command',
173 command_line
='qemu-io %s "break %s bp_%s"' % (drive
, event
, drive
))
175 def resume_drive(self
, drive
):
176 self
.qmp('human-monitor-command',
177 command_line
='qemu-io %s "remove_break bp_%s"' % (drive
, drive
))
179 def hmp_qemu_io(self
, drive
, cmd
):
180 '''Write to a given drive using an HMP command'''
181 return self
.qmp('human-monitor-command',
182 command_line
='qemu-io %s "%s"' % (drive
, cmd
))
184 def add_fd(self
, fd
, fdset
, opaque
, opts
=''):
185 '''Pass a file descriptor to the VM'''
186 options
= ['fd=%d' % fd
,
188 'opaque=%s' % opaque
]
192 self
._args
.append('-add-fd')
193 self
._args
.append(','.join(options
))
196 def send_fd_scm(self
, fd_file_path
):
197 # In iotest.py, the qmp should always use unix socket.
198 assert self
._qmp
.is_scm_available()
199 bin
= socket_scm_helper
200 if os
.path
.exists(bin
) == False:
201 print "Scm help program does not present, path '%s'." % bin
203 fd_param
= ["%s" % bin
,
204 "%d" % self
._qmp
.get_sock_fd(),
206 devnull
= open('/dev/null', 'rb')
207 p
= subprocess
.Popen(fd_param
, stdin
=devnull
, stdout
=sys
.stdout
,
212 '''Launch the VM and establish a QMP connection'''
213 devnull
= open('/dev/null', 'rb')
214 qemulog
= open(self
._qemu
_log
_path
, 'wb')
216 self
._qmp
= qmp
.QEMUMonitorProtocol(self
._monitor
_path
, server
=True)
217 self
._qtest
= qtest
.QEMUQtestProtocol(self
._qtest
_path
, server
=True)
218 self
._popen
= subprocess
.Popen(self
._args
, stdin
=devnull
, stdout
=qemulog
,
219 stderr
=subprocess
.STDOUT
)
223 os
.remove(self
._monitor
_path
)
227 '''Terminate the VM and clean up'''
228 if not self
._popen
is None:
229 self
._qmp
.cmd('quit')
230 exitcode
= self
._popen
.wait()
232 sys
.stderr
.write('qemu received signal %i: %s\n' % (-exitcode
, ' '.join(self
._args
)))
233 os
.remove(self
._monitor
_path
)
234 os
.remove(self
._qtest
_path
)
235 os
.remove(self
._qemu
_log
_path
)
238 underscore_to_dash
= string
.maketrans('_', '-')
239 def qmp(self
, cmd
, conv_keys
=True, **args
):
240 '''Invoke a QMP command and return the result dict'''
242 for k
in args
.keys():
244 qmp_args
[k
.translate(self
.underscore_to_dash
)] = args
[k
]
246 qmp_args
[k
] = args
[k
]
248 return self
._qmp
.cmd(cmd
, args
=qmp_args
)
250 def qtest(self
, cmd
):
251 '''Send a qtest command to guest'''
252 return self
._qtest
.cmd(cmd
)
254 def get_qmp_event(self
, wait
=False):
255 '''Poll for one queued QMP events and return it'''
256 if len(self
._events
) > 0:
257 return self
._events
.pop(0)
258 return self
._qmp
.pull_event(wait
=wait
)
260 def get_qmp_events(self
, wait
=False):
261 '''Poll for queued QMP events and return a list of dicts'''
262 events
= self
._qmp
.get_events(wait
=wait
)
263 events
.extend(self
._events
)
265 self
._qmp
.clear_events()
268 def event_wait(self
, name
='BLOCK_JOB_COMPLETED', timeout
=60.0, match
=None):
269 # Search cached events
270 for event
in self
._events
:
271 if (event
['event'] == name
) and event_match(event
, match
):
272 self
._events
.remove(event
)
275 # Poll for new events
277 event
= self
._qmp
.pull_event(wait
=timeout
)
278 if (event
['event'] == name
) and event_match(event
, match
):
280 self
._events
.append(event
)
284 index_re
= re
.compile(r
'([^\[]+)\[([^\]]+)\]')
286 class QMPTestCase(unittest
.TestCase
):
287 '''Abstract base class for QMP test cases'''
289 def dictpath(self
, d
, path
):
290 '''Traverse a path in a nested dict'''
291 for component
in path
.split('/'):
292 m
= index_re
.match(component
)
294 component
, idx
= m
.groups()
297 if not isinstance(d
, dict) or component
not in d
:
298 self
.fail('failed path traversal for "%s" in "%s"' % (path
, str(d
)))
302 if not isinstance(d
, list):
303 self
.fail('path component "%s" in "%s" is not a list in "%s"' % (component
, path
, str(d
)))
307 self
.fail('invalid index "%s" in path "%s" in "%s"' % (idx
, path
, str(d
)))
310 def assert_qmp_absent(self
, d
, path
):
312 result
= self
.dictpath(d
, path
)
313 except AssertionError:
315 self
.fail('path "%s" has value "%s"' % (path
, str(result
)))
317 def assert_qmp(self
, d
, path
, value
):
318 '''Assert that the value for a specific path in a QMP dict matches'''
319 result
= self
.dictpath(d
, path
)
320 self
.assertEqual(result
, value
, 'values not equal "%s" and "%s"' % (str(result
), str(value
)))
322 def assert_no_active_block_jobs(self
):
323 result
= self
.vm
.qmp('query-block-jobs')
324 self
.assert_qmp(result
, 'return', [])
326 def cancel_and_wait(self
, drive
='drive0', force
=False, resume
=False):
327 '''Cancel a block job and wait for it to finish, returning the event'''
328 result
= self
.vm
.qmp('block-job-cancel', device
=drive
, force
=force
)
329 self
.assert_qmp(result
, 'return', {})
332 self
.vm
.resume_drive(drive
)
337 for event
in self
.vm
.get_qmp_events(wait
=True):
338 if event
['event'] == 'BLOCK_JOB_COMPLETED' or \
339 event
['event'] == 'BLOCK_JOB_CANCELLED':
340 self
.assert_qmp(event
, 'data/device', drive
)
344 self
.assert_no_active_block_jobs()
347 def wait_until_completed(self
, drive
='drive0', check_offset
=True):
348 '''Wait for a block job to finish, returning the event'''
351 for event
in self
.vm
.get_qmp_events(wait
=True):
352 if event
['event'] == 'BLOCK_JOB_COMPLETED':
353 self
.assert_qmp(event
, 'data/device', drive
)
354 self
.assert_qmp_absent(event
, 'data/error')
356 self
.assert_qmp(event
, 'data/offset', event
['data']['len'])
359 self
.assert_no_active_block_jobs()
362 def wait_ready(self
, drive
='drive0'):
363 '''Wait until a block job BLOCK_JOB_READY event'''
364 f
= {'data': {'type': 'mirror', 'device': drive
} }
365 event
= self
.vm
.event_wait(name
='BLOCK_JOB_READY', match
=f
)
367 def wait_ready_and_cancel(self
, drive
='drive0'):
368 self
.wait_ready(drive
=drive
)
369 event
= self
.cancel_and_wait(drive
=drive
)
370 self
.assertEquals(event
['event'], 'BLOCK_JOB_COMPLETED')
371 self
.assert_qmp(event
, 'data/type', 'mirror')
372 self
.assert_qmp(event
, 'data/offset', event
['data']['len'])
374 def complete_and_wait(self
, drive
='drive0', wait_ready
=True):
375 '''Complete a block job and wait for it to finish'''
377 self
.wait_ready(drive
=drive
)
379 result
= self
.vm
.qmp('block-job-complete', device
=drive
)
380 self
.assert_qmp(result
, 'return', {})
382 event
= self
.wait_until_completed(drive
=drive
)
383 self
.assert_qmp(event
, 'data/type', 'mirror')
386 '''Skip this test suite'''
387 # Each test in qemu-iotests has a number ("seq")
388 seq
= os
.path
.basename(sys
.argv
[0])
390 open('%s/%s.notrun' % (output_dir
, seq
), 'wb').write(reason
+ '\n')
391 print '%s not run: %s' % (seq
, reason
)
394 def main(supported_fmts
=[], supported_oses
=['linux']):
397 debug
= '-d' in sys
.argv
399 if supported_fmts
and (imgfmt
not in supported_fmts
):
400 notrun('not suitable for this image format: %s' % imgfmt
)
402 if True not in [sys
.platform
.startswith(x
) for x
in supported_oses
]:
403 notrun('not suitable for this OS: %s' % sys
.platform
)
405 # We need to filter out the time taken from the output so that qemu-iotest
406 # can reliably diff the results against master output.
411 sys
.argv
.remove('-d')
413 output
= StringIO
.StringIO()
415 class MyTestRunner(unittest
.TextTestRunner
):
416 def __init__(self
, stream
=output
, descriptions
=True, verbosity
=verbosity
):
417 unittest
.TextTestRunner
.__init
__(self
, stream
, descriptions
, verbosity
)
419 # unittest.main() will use sys.exit() so expect a SystemExit exception
421 unittest
.main(testRunner
=MyTestRunner
)
424 sys
.stderr
.write(re
.sub(r
'Ran (\d+) tests? in [\d.]+s', r
'Ran \1 tests', output
.getvalue()))