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/>.
26 sys
.path
.append(os
.path
.join(os
.path
.dirname(__file__
), '..', '..', 'scripts'))
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_nbd_args
= [os
.environ
.get('QEMU_NBD_PROG', 'qemu-nbd')]
45 if os
.environ
.get('QEMU_NBD_OPTIONS'):
46 qemu_nbd_args
+= os
.environ
['QEMU_NBD_OPTIONS'].strip().split(' ')
48 qemu_prog
= os
.environ
.get('QEMU_PROG', 'qemu')
49 qemu_opts
= os
.environ
.get('QEMU_OPTIONS', '').strip().split(' ')
51 imgfmt
= os
.environ
.get('IMGFMT', 'raw')
52 imgproto
= os
.environ
.get('IMGPROTO', 'file')
53 test_dir
= os
.environ
.get('TEST_DIR')
54 output_dir
= os
.environ
.get('OUTPUT_DIR', '.')
55 cachemode
= os
.environ
.get('CACHEMODE')
56 qemu_default_machine
= os
.environ
.get('QEMU_DEFAULT_MACHINE')
58 socket_scm_helper
= os
.environ
.get('SOCKET_SCM_HELPER', 'socket_scm_helper')
62 '''Run qemu-img and return the exit code'''
63 devnull
= open('/dev/null', 'r+')
64 exitcode
= subprocess
.call(qemu_img_args
+ list(args
), stdin
=devnull
, stdout
=devnull
)
66 sys
.stderr
.write('qemu-img received signal %i: %s\n' % (-exitcode
, ' '.join(qemu_img_args
+ list(args
))))
69 def qemu_img_verbose(*args
):
70 '''Run qemu-img without suppressing its output and return the exit code'''
71 exitcode
= subprocess
.call(qemu_img_args
+ list(args
))
73 sys
.stderr
.write('qemu-img received signal %i: %s\n' % (-exitcode
, ' '.join(qemu_img_args
+ list(args
))))
76 def qemu_img_pipe(*args
):
77 '''Run qemu-img and return its output'''
78 subp
= subprocess
.Popen(qemu_img_args
+ list(args
),
79 stdout
=subprocess
.PIPE
,
80 stderr
=subprocess
.STDOUT
)
81 exitcode
= subp
.wait()
83 sys
.stderr
.write('qemu-img received signal %i: %s\n' % (-exitcode
, ' '.join(qemu_img_args
+ list(args
))))
84 return subp
.communicate()[0]
87 '''Run qemu-io and return the stdout data'''
88 args
= qemu_io_args
+ list(args
)
89 subp
= subprocess
.Popen(args
, stdout
=subprocess
.PIPE
,
90 stderr
=subprocess
.STDOUT
)
91 exitcode
= subp
.wait()
93 sys
.stderr
.write('qemu-io received signal %i: %s\n' % (-exitcode
, ' '.join(args
)))
94 return subp
.communicate()[0]
97 class QemuIoInteractive
:
98 def __init__(self
, *args
):
99 self
.args
= qemu_io_args
+ list(args
)
100 self
._p
= subprocess
.Popen(self
.args
, stdin
=subprocess
.PIPE
,
101 stdout
=subprocess
.PIPE
,
102 stderr
=subprocess
.STDOUT
)
103 assert self
._p
.stdout
.read(9) == 'qemu-io> '
106 self
._p
.communicate('q\n')
108 def _read_output(self
):
109 pattern
= 'qemu-io> '
114 c
= self
._p
.stdout
.read(1)
115 # check unexpected EOF
118 if c
== pattern
[pos
]:
123 return ''.join(s
[:-n
])
126 # quit command is in close(), '\n' is added automatically
127 assert '\n' not in cmd
129 assert cmd
!= 'q' and cmd
!= 'quit'
130 self
._p
.stdin
.write(cmd
+ '\n')
131 return self
._read
_output
()
135 '''Run qemu-nbd in daemon mode and return the parent's exit code'''
136 return subprocess
.call(qemu_nbd_args
+ ['--fork'] + list(args
))
138 def compare_images(img1
, img2
, fmt1
=imgfmt
, fmt2
=imgfmt
):
139 '''Return True if two image files are identical'''
140 return qemu_img('compare', '-f', fmt1
,
141 '-F', fmt2
, img1
, img2
) == 0
143 def create_image(name
, size
):
144 '''Create a fully-allocated raw image with sector markers'''
145 file = open(name
, 'w')
148 sector
= struct
.pack('>l504xl', i
/ 512, i
/ 512)
154 '''Return image's virtual size'''
155 r
= qemu_img_pipe('info', '--output=json', '-f', imgfmt
, img
)
156 return json
.loads(r
)['virtual-size']
158 test_dir_re
= re
.compile(r
"%s" % test_dir
)
159 def filter_test_dir(msg
):
160 return test_dir_re
.sub("TEST_DIR", msg
)
162 win32_re
= re
.compile(r
"\r")
163 def filter_win32(msg
):
164 return win32_re
.sub("", msg
)
166 qemu_io_re
= re
.compile(r
"[0-9]* ops; [0-9\/:. sec]* \([0-9\/.inf]* [EPTGMKiBbytes]*\/sec and [0-9\/.inf]* ops\/sec\)")
167 def filter_qemu_io(msg
):
168 msg
= filter_win32(msg
)
169 return qemu_io_re
.sub("X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)", msg
)
171 chown_re
= re
.compile(r
"chown [0-9]+:[0-9]+")
172 def filter_chown(msg
):
173 return chown_re
.sub("chown UID:GID", msg
)
175 def filter_qmp_event(event
):
176 '''Filter a QMP event dict'''
178 if 'timestamp' in event
:
179 event
['timestamp']['seconds'] = 'SECS'
180 event
['timestamp']['microseconds'] = 'USECS'
183 def log(msg
, filters
=[]):
189 def __init__(self
, seconds
, errmsg
= "Timeout"):
190 self
.seconds
= seconds
193 signal
.signal(signal
.SIGALRM
, self
.timeout
)
194 signal
.setitimer(signal
.ITIMER_REAL
, self
.seconds
)
196 def __exit__(self
, type, value
, traceback
):
197 signal
.setitimer(signal
.ITIMER_REAL
, 0)
199 def timeout(self
, signum
, frame
):
200 raise Exception(self
.errmsg
)
203 class FilePath(object):
204 '''An auto-generated filename that cleans itself up.
206 Use this context manager to generate filenames and ensure that the file
209 with TestFilePath('test.img') as img_path:
210 qemu_img('create', img_path, '1G')
211 # migration_sock_path is automatically deleted
213 def __init__(self
, name
):
214 filename
= '{0}-{1}'.format(os
.getpid(), name
)
215 self
.path
= os
.path
.join(test_dir
, filename
)
220 def __exit__(self
, exc_type
, exc_val
, exc_tb
):
228 class VM(qtest
.QEMUQtestMachine
):
231 def __init__(self
, path_suffix
=''):
232 name
= "qemu%s-%d" % (path_suffix
, os
.getpid())
233 super(VM
, self
).__init
__(qemu_prog
, qemu_opts
, name
=name
,
235 socket_scm_helper
=socket_scm_helper
)
238 def add_object(self
, opts
):
239 self
._args
.append('-object')
240 self
._args
.append(opts
)
243 def add_device(self
, opts
):
244 self
._args
.append('-device')
245 self
._args
.append(opts
)
248 def add_drive_raw(self
, opts
):
249 self
._args
.append('-drive')
250 self
._args
.append(opts
)
253 def add_drive(self
, path
, opts
='', interface
='virtio', format
=imgfmt
):
254 '''Add a virtio-blk drive to the VM'''
255 options
= ['if=%s' % interface
,
256 'id=drive%d' % self
._num
_drives
]
259 options
.append('file=%s' % path
)
260 options
.append('format=%s' % format
)
261 options
.append('cache=%s' % cachemode
)
266 self
._args
.append('-drive')
267 self
._args
.append(','.join(options
))
268 self
._num
_drives
+= 1
271 def add_blockdev(self
, opts
):
272 self
._args
.append('-blockdev')
273 if isinstance(opts
, str):
274 self
._args
.append(opts
)
276 self
._args
.append(','.join(opts
))
279 def add_incoming(self
, addr
):
280 self
._args
.append('-incoming')
281 self
._args
.append(addr
)
284 def pause_drive(self
, drive
, event
=None):
285 '''Pause drive r/w operations'''
287 self
.pause_drive(drive
, "read_aio")
288 self
.pause_drive(drive
, "write_aio")
290 self
.qmp('human-monitor-command',
291 command_line
='qemu-io %s "break %s bp_%s"' % (drive
, event
, drive
))
293 def resume_drive(self
, drive
):
294 self
.qmp('human-monitor-command',
295 command_line
='qemu-io %s "remove_break bp_%s"' % (drive
, drive
))
297 def hmp_qemu_io(self
, drive
, cmd
):
298 '''Write to a given drive using an HMP command'''
299 return self
.qmp('human-monitor-command',
300 command_line
='qemu-io %s "%s"' % (drive
, cmd
))
303 index_re
= re
.compile(r
'([^\[]+)\[([^\]]+)\]')
305 class QMPTestCase(unittest
.TestCase
):
306 '''Abstract base class for QMP test cases'''
308 def dictpath(self
, d
, path
):
309 '''Traverse a path in a nested dict'''
310 for component
in path
.split('/'):
311 m
= index_re
.match(component
)
313 component
, idx
= m
.groups()
316 if not isinstance(d
, dict) or component
not in d
:
317 self
.fail('failed path traversal for "%s" in "%s"' % (path
, str(d
)))
321 if not isinstance(d
, list):
322 self
.fail('path component "%s" in "%s" is not a list in "%s"' % (component
, path
, str(d
)))
326 self
.fail('invalid index "%s" in path "%s" in "%s"' % (idx
, path
, str(d
)))
329 def flatten_qmp_object(self
, obj
, output
=None, basestr
=''):
332 if isinstance(obj
, list):
333 for i
in range(len(obj
)):
334 self
.flatten_qmp_object(obj
[i
], output
, basestr
+ str(i
) + '.')
335 elif isinstance(obj
, dict):
337 self
.flatten_qmp_object(obj
[key
], output
, basestr
+ key
+ '.')
339 output
[basestr
[:-1]] = obj
# Strip trailing '.'
342 def qmp_to_opts(self
, obj
):
343 obj
= self
.flatten_qmp_object(obj
)
346 output_list
+= [key
+ '=' + obj
[key
]]
347 return ','.join(output_list
)
349 def assert_qmp_absent(self
, d
, path
):
351 result
= self
.dictpath(d
, path
)
352 except AssertionError:
354 self
.fail('path "%s" has value "%s"' % (path
, str(result
)))
356 def assert_qmp(self
, d
, path
, value
):
357 '''Assert that the value for a specific path in a QMP dict matches'''
358 result
= self
.dictpath(d
, path
)
359 self
.assertEqual(result
, value
, 'values not equal "%s" and "%s"' % (str(result
), str(value
)))
361 def assert_no_active_block_jobs(self
):
362 result
= self
.vm
.qmp('query-block-jobs')
363 self
.assert_qmp(result
, 'return', [])
365 def assert_has_block_node(self
, node_name
=None, file_name
=None):
366 """Issue a query-named-block-nodes and assert node_name and/or
367 file_name is present in the result"""
368 def check_equal_or_none(a
, b
):
369 return a
== None or b
== None or a
== b
370 assert node_name
or file_name
371 result
= self
.vm
.qmp('query-named-block-nodes')
372 for x
in result
["return"]:
373 if check_equal_or_none(x
.get("node-name"), node_name
) and \
374 check_equal_or_none(x
.get("file"), file_name
):
376 self
.assertTrue(False, "Cannot find %s %s in result:\n%s" % \
377 (node_name
, file_name
, result
))
379 def assert_json_filename_equal(self
, json_filename
, reference
):
380 '''Asserts that the given filename is a json: filename and that its
381 content is equal to the given reference object'''
382 self
.assertEqual(json_filename
[:5], 'json:')
383 self
.assertEqual(self
.flatten_qmp_object(json
.loads(json_filename
[5:])),
384 self
.flatten_qmp_object(reference
))
386 def cancel_and_wait(self
, drive
='drive0', force
=False, resume
=False):
387 '''Cancel a block job and wait for it to finish, returning the event'''
388 result
= self
.vm
.qmp('block-job-cancel', device
=drive
, force
=force
)
389 self
.assert_qmp(result
, 'return', {})
392 self
.vm
.resume_drive(drive
)
397 for event
in self
.vm
.get_qmp_events(wait
=True):
398 if event
['event'] == 'BLOCK_JOB_COMPLETED' or \
399 event
['event'] == 'BLOCK_JOB_CANCELLED':
400 self
.assert_qmp(event
, 'data/device', drive
)
404 self
.assert_no_active_block_jobs()
407 def wait_until_completed(self
, drive
='drive0', check_offset
=True):
408 '''Wait for a block job to finish, returning the event'''
411 for event
in self
.vm
.get_qmp_events(wait
=True):
412 if event
['event'] == 'BLOCK_JOB_COMPLETED':
413 self
.assert_qmp(event
, 'data/device', drive
)
414 self
.assert_qmp_absent(event
, 'data/error')
416 self
.assert_qmp(event
, 'data/offset', event
['data']['len'])
419 self
.assert_no_active_block_jobs()
422 def wait_ready(self
, drive
='drive0'):
423 '''Wait until a block job BLOCK_JOB_READY event'''
424 f
= {'data': {'type': 'mirror', 'device': drive
} }
425 event
= self
.vm
.event_wait(name
='BLOCK_JOB_READY', match
=f
)
427 def wait_ready_and_cancel(self
, drive
='drive0'):
428 self
.wait_ready(drive
=drive
)
429 event
= self
.cancel_and_wait(drive
=drive
)
430 self
.assertEquals(event
['event'], 'BLOCK_JOB_COMPLETED')
431 self
.assert_qmp(event
, 'data/type', 'mirror')
432 self
.assert_qmp(event
, 'data/offset', event
['data']['len'])
434 def complete_and_wait(self
, drive
='drive0', wait_ready
=True):
435 '''Complete a block job and wait for it to finish'''
437 self
.wait_ready(drive
=drive
)
439 result
= self
.vm
.qmp('block-job-complete', device
=drive
)
440 self
.assert_qmp(result
, 'return', {})
442 event
= self
.wait_until_completed(drive
=drive
)
443 self
.assert_qmp(event
, 'data/type', 'mirror')
445 def pause_job(self
, job_id
='job0'):
446 result
= self
.vm
.qmp('block-job-pause', device
=job_id
)
447 self
.assert_qmp(result
, 'return', {})
449 with
Timeout(1, "Timeout waiting for job to pause"):
451 result
= self
.vm
.qmp('query-block-jobs')
452 for job
in result
['return']:
453 if job
['device'] == job_id
and job
['paused'] == True and job
['busy'] == False:
458 '''Skip this test suite'''
459 # Each test in qemu-iotests has a number ("seq")
460 seq
= os
.path
.basename(sys
.argv
[0])
462 open('%s/%s.notrun' % (output_dir
, seq
), 'wb').write(reason
+ '\n')
463 print '%s not run: %s' % (seq
, reason
)
466 def verify_image_format(supported_fmts
=[], unsupported_fmts
=[]):
467 if supported_fmts
and (imgfmt
not in supported_fmts
):
468 notrun('not suitable for this image format: %s' % imgfmt
)
469 if unsupported_fmts
and (imgfmt
in unsupported_fmts
):
470 notrun('not suitable for this image format: %s' % imgfmt
)
472 def verify_platform(supported_oses
=['linux']):
473 if True not in [sys
.platform
.startswith(x
) for x
in supported_oses
]:
474 notrun('not suitable for this OS: %s' % sys
.platform
)
476 def supports_quorum():
477 return 'quorum' in qemu_img_pipe('--help')
480 '''Skip test suite if quorum support is not available'''
481 if not supports_quorum():
482 notrun('quorum support missing')
484 def main(supported_fmts
=[], supported_oses
=['linux']):
489 # We are using TEST_DIR and QEMU_DEFAULT_MACHINE as proxies to
490 # indicate that we're not being run via "check". There may be
491 # other things set up by "check" that individual test cases rely
493 if test_dir
is None or qemu_default_machine
is None:
494 sys
.stderr
.write('Please run this test via the "check" script\n')
495 sys
.exit(os
.EX_USAGE
)
497 debug
= '-d' in sys
.argv
499 verify_image_format(supported_fmts
)
500 verify_platform(supported_oses
)
502 # We need to filter out the time taken from the output so that qemu-iotest
503 # can reliably diff the results against master output.
508 sys
.argv
.remove('-d')
510 output
= StringIO
.StringIO()
512 logging
.basicConfig(level
=(logging
.DEBUG
if debug
else logging
.WARN
))
514 class MyTestRunner(unittest
.TextTestRunner
):
515 def __init__(self
, stream
=output
, descriptions
=True, verbosity
=verbosity
):
516 unittest
.TextTestRunner
.__init
__(self
, stream
, descriptions
, verbosity
)
518 # unittest.main() will use sys.exit() so expect a SystemExit exception
520 unittest
.main(testRunner
=MyTestRunner
)
523 sys
.stderr
.write(re
.sub(r
'Ran (\d+) tests? in [\d.]+s', r
'Ran \1 tests', output
.getvalue()))