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 '''Run qemu-nbd in daemon mode and return the parent's exit code'''
98 return subprocess.call(qemu_nbd_args + ['--fork'] + list(args))
100 def compare_images(img1, img2, fmt1=imgfmt, fmt2=imgfmt):
101 '''Return True if two image files are identical'''
102 return qemu_img('compare', '-f', fmt1,
103 '-F', fmt2, img1, img2) == 0
105 def create_image(name, size):
106 '''Create a fully-allocated raw image with sector markers'''
107 file = open(name, 'w')
110 sector = struct.pack('>l504xl', i / 512, i / 512)
116 '''Return image's virtual size'''
117 r = qemu_img_pipe('info', '--output=json', '-f', imgfmt, img)
118 return json.loads(r)['virtual-size']
120 test_dir_re = re.compile(r"%s" % test_dir)
121 def filter_test_dir(msg):
122 return test_dir_re.sub("TEST_DIR", msg)
124 win32_re = re.compile(r"\r")
125 def filter_win32(msg):
126 return win32_re.sub("", msg)
128 qemu_io_re = re.compile(r"[0-9]* ops; [0-9\/:. sec]* \([0-9\/.inf]* [EPTGMKiBbytes]*\/sec and [0-9\/.inf]* ops\/sec\)")
129 def filter_qemu_io(msg):
130 msg = filter_win32(msg)
131 return qemu_io_re.sub("X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)", msg)
133 chown_re = re.compile(r"chown [0-9]+:[0-9]+")
134 def filter_chown(msg):
135 return chown_re.sub("chown UID:GID", msg)
137 def filter_qmp_event(event):
138 '''Filter a QMP event dict'''
140 if 'timestamp' in event:
141 event['timestamp']['seconds'] = 'SECS'
142 event['timestamp']['microseconds'] = 'USECS'
145 def log(msg, filters=[]):
151 def __init__(self, seconds, errmsg = "Timeout"):
152 self.seconds = seconds
155 signal.signal(signal.SIGALRM, self.timeout)
156 signal.setitimer(signal.ITIMER_REAL, self.seconds)
158 def __exit__(self, type, value, traceback):
159 signal.setitimer(signal.ITIMER_REAL, 0)
161 def timeout(self, signum, frame):
162 raise Exception(self.errmsg)
165 class FilePath(object):
166 '''An auto-generated filename that cleans itself up.
168 Use this context manager to generate filenames and ensure that the file
171 with TestFilePath('test.img') as img_path:
172 qemu_img('create', img_path, '1G')
173 # migration_sock_path is automatically deleted
175 def __init__(self, name):
176 filename = '{0}-{1}'.format(os.getpid(), name)
177 self.path = os.path.join(test_dir, filename)
182 def __exit__(self, exc_type, exc_val, exc_tb):
190 class VM(qtest.QEMUQtestMachine):
193 def __init__(self, path_suffix=''):
194 name = "qemu%s-%d" % (path_suffix, os.getpid())
195 super(VM, self).__init__(qemu_prog, qemu_opts, name=name,
197 socket_scm_helper=socket_scm_helper)
200 def add_object(self, opts):
201 self._args.append('-object')
202 self._args.append(opts)
205 def add_device(self, opts):
206 self._args.append('-device')
207 self._args.append(opts)
210 def add_drive_raw(self, opts):
211 self._args.append('-drive')
212 self._args.append(opts)
215 def add_drive(self, path, opts='', interface='virtio', format=imgfmt):
216 '''Add a virtio-blk drive to the VM'''
217 options = ['if=%s' % interface,
218 'id=drive%d' % self._num_drives]
221 options.append('file=%s' % path)
222 options.append('format=%s' % format)
223 options.append('cache=%s' % cachemode)
228 self._args.append('-drive')
229 self._args.append(','.join(options))
230 self._num_drives += 1
233 def add_blockdev(self, opts):
234 self._args.append('-blockdev')
235 if isinstance(opts, str):
236 self._args.append(opts)
238 self._args.append(','.join(opts))
241 def add_incoming(self, addr):
242 self._args.append('-incoming')
243 self._args.append(addr)
246 def pause_drive(self, drive, event=None):
247 '''Pause drive r/w operations'''
249 self.pause_drive(drive, "read_aio")
250 self.pause_drive(drive, "write_aio")
252 self.qmp('human-monitor-command',
253 command_line='qemu-io %s "break %s bp_%s"' % (drive, event, drive))
255 def resume_drive(self, drive):
256 self.qmp('human-monitor-command',
257 command_line='qemu-io %s "remove_break bp_%s"' % (drive, drive))
259 def hmp_qemu_io(self, drive, cmd):
260 '''Write to a given drive using an HMP command'''
261 return self.qmp('human-monitor-command',
262 command_line='qemu-io %s "%s"' % (drive, cmd))
265 index_re = re.compile(r'([^\[]+)\[([^\]]+)\]')
267 class QMPTestCase(unittest.TestCase):
268 '''Abstract base class for QMP test cases'''
270 def dictpath(self, d, path):
271 '''Traverse a path in a nested dict'''
272 for component in path.split('/'):
273 m = index_re.match(component)
275 component, idx = m.groups()
278 if not isinstance(d, dict) or component not in d:
279 self.fail('failed path traversal for "%s" in "%s"' % (path, str(d)))
283 if not isinstance(d, list):
284 self.fail('path component "%s" in "%s" is not a list in "%s"' % (component, path, str(d)))
288 self.fail('invalid index "%s" in path "%s" in "%s"' % (idx, path, str(d)))
291 def flatten_qmp_object(self, obj, output=None, basestr=''):
294 if isinstance(obj, list):
295 for i in range(len(obj)):
296 self.flatten_qmp_object(obj[i], output, basestr + str(i) + '.')
297 elif isinstance(obj, dict):
299 self.flatten_qmp_object(obj[key], output, basestr + key + '.')
301 output[basestr[:-1]] = obj # Strip trailing '.'
304 def qmp_to_opts(self, obj):
305 obj = self.flatten_qmp_object(obj)
308 output_list += [key + '=' + obj[key]]
309 return ','.join(output_list)
311 def assert_qmp_absent(self, d, path):
313 result = self.dictpath(d, path)
314 except AssertionError:
316 self.fail('path "%s" has value "%s"' % (path, str(result)))
318 def assert_qmp(self, d, path, value):
319 '''Assert that the value for a specific path in a QMP dict matches'''
320 result = self.dictpath(d, path)
321 self.assertEqual(result, value, 'values not equal "%s" and "%s"' % (str(result), str(value)))
323 def assert_no_active_block_jobs(self):
324 result = self.vm.qmp('query-block-jobs')
325 self.assert_qmp(result, 'return', [])
327 def assert_has_block_node(self, node_name=None, file_name=None):
328 """Issue a query-named-block-nodes and assert node_name and/or
329 file_name is present in the result"""
330 def check_equal_or_none(a, b):
331 return a == None or b == None or a == b
332 assert node_name or file_name
333 result = self.vm.qmp('query-named-block-nodes')
334 for x in result["return"]:
335 if check_equal_or_none(x.get("node-name"), node_name) and \
336 check_equal_or_none(x.get("file"), file_name):
338 self.assertTrue(False, "Cannot find %s %s in result:\n%s" % \
339 (node_name, file_name, result))
341 def assert_json_filename_equal(self, json_filename, reference):
342 '''Asserts that the given filename is a json: filename and that its
343 content is equal to the given reference object'''
344 self.assertEqual(json_filename[:5], 'json:')
345 self.assertEqual(self.flatten_qmp_object(json.loads(json_filename[5:])),
346 self.flatten_qmp_object(reference))
348 def cancel_and_wait(self, drive='drive0', force=False, resume=False):
349 '''Cancel a block job and wait for it to finish, returning the event'''
350 result = self.vm.qmp('block-job-cancel', device=drive, force=force)
351 self.assert_qmp(result, 'return', {})
354 self.vm.resume_drive(drive)
359 for event in self.vm.get_qmp_events(wait=True):
360 if event['event'] == 'BLOCK_JOB_COMPLETED' or \
361 event['event'] == 'BLOCK_JOB_CANCELLED':
362 self.assert_qmp(event, 'data/device', drive)
366 self.assert_no_active_block_jobs()
369 def wait_until_completed(self, drive='drive0', check_offset=True):
370 '''Wait for a block job to finish, returning the event'''
373 for event in self.vm.get_qmp_events(wait=True):
374 if event['event'] == 'BLOCK_JOB_COMPLETED':
375 self.assert_qmp(event, 'data/device', drive)
376 self.assert_qmp_absent(event, 'data/error')
378 self.assert_qmp(event, 'data/offset', event['data']['len'])
381 self.assert_no_active_block_jobs()
384 def wait_ready(self, drive='drive0'):
385 '''Wait until a block job BLOCK_JOB_READY event'''
386 f = {'data': {'type': 'mirror', 'device': drive } }
387 event = self.vm.event_wait(name='BLOCK_JOB_READY', match=f)
389 def wait_ready_and_cancel(self, drive='drive0'):
390 self.wait_ready(drive=drive)
391 event = self.cancel_and_wait(drive=drive)
392 self.assertEquals(event['event'], 'BLOCK_JOB_COMPLETED')
393 self.assert_qmp(event, 'data/type', 'mirror')
394 self.assert_qmp(event, 'data/offset', event['data']['len'])
396 def complete_and_wait(self, drive='drive0', wait_ready=True):
397 '''Complete a block job and wait for it to finish'''
399 self.wait_ready(drive=drive)
401 result = self.vm.qmp('block-job-complete', device=drive)
402 self.assert_qmp(result, 'return', {})
404 event = self.wait_until_completed(drive=drive)
405 self.assert_qmp(event, 'data/type', 'mirror')
407 def pause_job(self, job_id='job0'):
408 result = self.vm.qmp('block-job-pause', device=job_id)
409 self.assert_qmp(result, 'return', {})
411 with Timeout(1, "Timeout waiting for job to pause"):
413 result = self.vm.qmp('query-block-jobs')
414 for job in result['return']:
415 if job['device'] == job_id and job['paused'] == True and job['busy'] == False:
420 '''Skip this test suite'''
421 # Each test in qemu-iotests has a number ("seq")
422 seq = os.path.basename(sys.argv[0])
424 open('%s/%s.notrun' % (output_dir, seq), 'wb').write(reason + '\n')
425 print '%s not run: %s' % (seq, reason)
428 def verify_image_format(supported_fmts=[], unsupported_fmts=[]):
429 if supported_fmts and (imgfmt not in supported_fmts):
430 notrun('not suitable for this image format: %s' % imgfmt)
431 if unsupported_fmts and (imgfmt in unsupported_fmts):
432 notrun('not suitable for this image format: %s' % imgfmt)
434 def verify_platform(supported_oses=['linux']):
435 if True not in [sys.platform.startswith(x) for x in supported_oses]:
436 notrun('not suitable for this OS: %s' % sys.platform)
438 def supports_quorum():
439 return 'quorum' in qemu_img_pipe('--help')
442 '''Skip test suite if quorum support is not available'''
443 if not supports_quorum():
444 notrun('quorum support missing')
446 def main(supported_fmts=[], supported_oses=['linux']):
451 # We are using TEST_DIR and QEMU_DEFAULT_MACHINE as proxies to
452 # indicate that we're not being run via "check". There may be
453 # other things set up by "check" that individual test cases rely
455 if test_dir is None or qemu_default_machine is None:
456 sys.stderr.write('Please run this test via the "check" script\n')
457 sys.exit(os.EX_USAGE)
459 debug = '-d' in sys.argv
461 verify_image_format(supported_fmts)
462 verify_platform(supported_oses)
464 # We need to filter out the time taken from the output so that qemu-iotest
465 # can reliably diff the results against master output.
470 sys.argv.remove('-d')
472 output = StringIO.StringIO()
474 logging.basicConfig(level=(logging.DEBUG if debug else logging.WARN))
476 class MyTestRunner(unittest.TextTestRunner):
477 def __init__(self, stream=output, descriptions=True, verbosity=verbosity):
478 unittest.TextTestRunner.__init__(self, stream, descriptions, verbosity)
480 # unittest.main() will use sys.exit() so expect a SystemExit exception
482 unittest.main(testRunner=MyTestRunner)
485 sys.stderr.write(re.sub(r'Ran (\d+) tests? in [\d.]+s', r'Ran \1 tests', output.getvalue()))