1# Common utilities and Python wrappers for qemu-iotests 2# 3# Copyright (C) 2012 IBM Corp. 4# 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. 9# 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. 14# 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/>. 17# 18 19import errno 20import os 21import re 22import subprocess 23import string 24import unittest 25import sys 26sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'scripts')) 27import qtest 28import struct 29import json 30import signal 31 32 33# This will not work if arguments contain spaces but is necessary if we 34# want to support the override options that ./check supports. 35qemu_img_args = [os.environ.get('QEMU_IMG_PROG', 'qemu-img')] 36if os.environ.get('QEMU_IMG_OPTIONS'): 37 qemu_img_args += os.environ['QEMU_IMG_OPTIONS'].strip().split(' ') 38 39qemu_io_args = [os.environ.get('QEMU_IO_PROG', 'qemu-io')] 40if os.environ.get('QEMU_IO_OPTIONS'): 41 qemu_io_args += os.environ['QEMU_IO_OPTIONS'].strip().split(' ') 42 43qemu_nbd_args = [os.environ.get('QEMU_NBD_PROG', 'qemu-nbd')] 44if os.environ.get('QEMU_NBD_OPTIONS'): 45 qemu_nbd_args += os.environ['QEMU_NBD_OPTIONS'].strip().split(' ') 46 47qemu_prog = os.environ.get('QEMU_PROG', 'qemu') 48qemu_opts = os.environ.get('QEMU_OPTIONS', '').strip().split(' ') 49 50imgfmt = os.environ.get('IMGFMT', 'raw') 51imgproto = os.environ.get('IMGPROTO', 'file') 52test_dir = os.environ.get('TEST_DIR') 53output_dir = os.environ.get('OUTPUT_DIR', '.') 54cachemode = os.environ.get('CACHEMODE') 55qemu_default_machine = os.environ.get('QEMU_DEFAULT_MACHINE') 56 57socket_scm_helper = os.environ.get('SOCKET_SCM_HELPER', 'socket_scm_helper') 58debug = False 59 60def qemu_img(*args): 61 '''Run qemu-img and return the exit code''' 62 devnull = open('/dev/null', 'r+') 63 exitcode = subprocess.call(qemu_img_args + list(args), stdin=devnull, stdout=devnull) 64 if exitcode < 0: 65 sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args)))) 66 return exitcode 67 68def qemu_img_verbose(*args): 69 '''Run qemu-img without suppressing its output and return the exit code''' 70 exitcode = subprocess.call(qemu_img_args + list(args)) 71 if exitcode < 0: 72 sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args)))) 73 return exitcode 74 75def qemu_img_pipe(*args): 76 '''Run qemu-img and return its output''' 77 subp = subprocess.Popen(qemu_img_args + list(args), 78 stdout=subprocess.PIPE, 79 stderr=subprocess.STDOUT) 80 exitcode = subp.wait() 81 if exitcode < 0: 82 sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args)))) 83 return subp.communicate()[0] 84 85def qemu_io(*args): 86 '''Run qemu-io and return the stdout data''' 87 args = qemu_io_args + list(args) 88 subp = subprocess.Popen(args, stdout=subprocess.PIPE, 89 stderr=subprocess.STDOUT) 90 exitcode = subp.wait() 91 if exitcode < 0: 92 sys.stderr.write('qemu-io received signal %i: %s\n' % (-exitcode, ' '.join(args))) 93 return subp.communicate()[0] 94 95def qemu_nbd(*args): 96 '''Run qemu-nbd in daemon mode and return the parent's exit code''' 97 return subprocess.call(qemu_nbd_args + ['--fork'] + list(args)) 98 99def compare_images(img1, img2, fmt1=imgfmt, fmt2=imgfmt): 100 '''Return True if two image files are identical''' 101 return qemu_img('compare', '-f', fmt1, 102 '-F', fmt2, img1, img2) == 0 103 104def create_image(name, size): 105 '''Create a fully-allocated raw image with sector markers''' 106 file = open(name, 'w') 107 i = 0 108 while i < size: 109 sector = struct.pack('>l504xl', i / 512, i / 512) 110 file.write(sector) 111 i = i + 512 112 file.close() 113 114def image_size(img): 115 '''Return image's virtual size''' 116 r = qemu_img_pipe('info', '--output=json', '-f', imgfmt, img) 117 return json.loads(r)['virtual-size'] 118 119test_dir_re = re.compile(r"%s" % test_dir) 120def filter_test_dir(msg): 121 return test_dir_re.sub("TEST_DIR", msg) 122 123win32_re = re.compile(r"\r") 124def filter_win32(msg): 125 return win32_re.sub("", msg) 126 127qemu_io_re = re.compile(r"[0-9]* ops; [0-9\/:. sec]* \([0-9\/.inf]* [EPTGMKiBbytes]*\/sec and [0-9\/.inf]* ops\/sec\)") 128def filter_qemu_io(msg): 129 msg = filter_win32(msg) 130 return qemu_io_re.sub("X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)", msg) 131 132chown_re = re.compile(r"chown [0-9]+:[0-9]+") 133def filter_chown(msg): 134 return chown_re.sub("chown UID:GID", msg) 135 136def filter_qmp_event(event): 137 '''Filter a QMP event dict''' 138 event = dict(event) 139 if 'timestamp' in event: 140 event['timestamp']['seconds'] = 'SECS' 141 event['timestamp']['microseconds'] = 'USECS' 142 return event 143 144def log(msg, filters=[]): 145 for flt in filters: 146 msg = flt(msg) 147 print msg 148 149class Timeout: 150 def __init__(self, seconds, errmsg = "Timeout"): 151 self.seconds = seconds 152 self.errmsg = errmsg 153 def __enter__(self): 154 signal.signal(signal.SIGALRM, self.timeout) 155 signal.setitimer(signal.ITIMER_REAL, self.seconds) 156 return self 157 def __exit__(self, type, value, traceback): 158 signal.setitimer(signal.ITIMER_REAL, 0) 159 return False 160 def timeout(self, signum, frame): 161 raise Exception(self.errmsg) 162 163class VM(qtest.QEMUQtestMachine): 164 '''A QEMU VM''' 165 166 def __init__(self, path_suffix=''): 167 name = "qemu%s-%d" % (path_suffix, os.getpid()) 168 super(VM, self).__init__(qemu_prog, qemu_opts, name=name, 169 test_dir=test_dir, 170 socket_scm_helper=socket_scm_helper) 171 if debug: 172 self._debug = True 173 self._num_drives = 0 174 175 def add_device(self, opts): 176 self._args.append('-device') 177 self._args.append(opts) 178 return self 179 180 def add_drive_raw(self, opts): 181 self._args.append('-drive') 182 self._args.append(opts) 183 return self 184 185 def add_drive(self, path, opts='', interface='virtio', format=imgfmt): 186 '''Add a virtio-blk drive to the VM''' 187 options = ['if=%s' % interface, 188 'id=drive%d' % self._num_drives] 189 190 if path is not None: 191 options.append('file=%s' % path) 192 options.append('format=%s' % format) 193 options.append('cache=%s' % cachemode) 194 195 if opts: 196 options.append(opts) 197 198 self._args.append('-drive') 199 self._args.append(','.join(options)) 200 self._num_drives += 1 201 return self 202 203 def add_blockdev(self, opts): 204 self._args.append('-blockdev') 205 if isinstance(opts, str): 206 self._args.append(opts) 207 else: 208 self._args.append(','.join(opts)) 209 return self 210 211 def add_incoming(self, addr): 212 self._args.append('-incoming') 213 self._args.append(addr) 214 return self 215 216 def pause_drive(self, drive, event=None): 217 '''Pause drive r/w operations''' 218 if not event: 219 self.pause_drive(drive, "read_aio") 220 self.pause_drive(drive, "write_aio") 221 return 222 self.qmp('human-monitor-command', 223 command_line='qemu-io %s "break %s bp_%s"' % (drive, event, drive)) 224 225 def resume_drive(self, drive): 226 self.qmp('human-monitor-command', 227 command_line='qemu-io %s "remove_break bp_%s"' % (drive, drive)) 228 229 def hmp_qemu_io(self, drive, cmd): 230 '''Write to a given drive using an HMP command''' 231 return self.qmp('human-monitor-command', 232 command_line='qemu-io %s "%s"' % (drive, cmd)) 233 234 235index_re = re.compile(r'([^\[]+)\[([^\]]+)\]') 236 237class QMPTestCase(unittest.TestCase): 238 '''Abstract base class for QMP test cases''' 239 240 def dictpath(self, d, path): 241 '''Traverse a path in a nested dict''' 242 for component in path.split('/'): 243 m = index_re.match(component) 244 if m: 245 component, idx = m.groups() 246 idx = int(idx) 247 248 if not isinstance(d, dict) or component not in d: 249 self.fail('failed path traversal for "%s" in "%s"' % (path, str(d))) 250 d = d[component] 251 252 if m: 253 if not isinstance(d, list): 254 self.fail('path component "%s" in "%s" is not a list in "%s"' % (component, path, str(d))) 255 try: 256 d = d[idx] 257 except IndexError: 258 self.fail('invalid index "%s" in path "%s" in "%s"' % (idx, path, str(d))) 259 return d 260 261 def flatten_qmp_object(self, obj, output=None, basestr=''): 262 if output is None: 263 output = dict() 264 if isinstance(obj, list): 265 for i in range(len(obj)): 266 self.flatten_qmp_object(obj[i], output, basestr + str(i) + '.') 267 elif isinstance(obj, dict): 268 for key in obj: 269 self.flatten_qmp_object(obj[key], output, basestr + key + '.') 270 else: 271 output[basestr[:-1]] = obj # Strip trailing '.' 272 return output 273 274 def qmp_to_opts(self, obj): 275 obj = self.flatten_qmp_object(obj) 276 output_list = list() 277 for key in obj: 278 output_list += [key + '=' + obj[key]] 279 return ','.join(output_list) 280 281 def assert_qmp_absent(self, d, path): 282 try: 283 result = self.dictpath(d, path) 284 except AssertionError: 285 return 286 self.fail('path "%s" has value "%s"' % (path, str(result))) 287 288 def assert_qmp(self, d, path, value): 289 '''Assert that the value for a specific path in a QMP dict matches''' 290 result = self.dictpath(d, path) 291 self.assertEqual(result, value, 'values not equal "%s" and "%s"' % (str(result), str(value))) 292 293 def assert_no_active_block_jobs(self): 294 result = self.vm.qmp('query-block-jobs') 295 self.assert_qmp(result, 'return', []) 296 297 def assert_has_block_node(self, node_name=None, file_name=None): 298 """Issue a query-named-block-nodes and assert node_name and/or 299 file_name is present in the result""" 300 def check_equal_or_none(a, b): 301 return a == None or b == None or a == b 302 assert node_name or file_name 303 result = self.vm.qmp('query-named-block-nodes') 304 for x in result["return"]: 305 if check_equal_or_none(x.get("node-name"), node_name) and \ 306 check_equal_or_none(x.get("file"), file_name): 307 return 308 self.assertTrue(False, "Cannot find %s %s in result:\n%s" % \ 309 (node_name, file_name, result)) 310 311 def assert_json_filename_equal(self, json_filename, reference): 312 '''Asserts that the given filename is a json: filename and that its 313 content is equal to the given reference object''' 314 self.assertEqual(json_filename[:5], 'json:') 315 self.assertEqual(self.flatten_qmp_object(json.loads(json_filename[5:])), 316 self.flatten_qmp_object(reference)) 317 318 def cancel_and_wait(self, drive='drive0', force=False, resume=False): 319 '''Cancel a block job and wait for it to finish, returning the event''' 320 result = self.vm.qmp('block-job-cancel', device=drive, force=force) 321 self.assert_qmp(result, 'return', {}) 322 323 if resume: 324 self.vm.resume_drive(drive) 325 326 cancelled = False 327 result = None 328 while not cancelled: 329 for event in self.vm.get_qmp_events(wait=True): 330 if event['event'] == 'BLOCK_JOB_COMPLETED' or \ 331 event['event'] == 'BLOCK_JOB_CANCELLED': 332 self.assert_qmp(event, 'data/device', drive) 333 result = event 334 cancelled = True 335 336 self.assert_no_active_block_jobs() 337 return result 338 339 def wait_until_completed(self, drive='drive0', check_offset=True): 340 '''Wait for a block job to finish, returning the event''' 341 completed = False 342 while not completed: 343 for event in self.vm.get_qmp_events(wait=True): 344 if event['event'] == 'BLOCK_JOB_COMPLETED': 345 self.assert_qmp(event, 'data/device', drive) 346 self.assert_qmp_absent(event, 'data/error') 347 if check_offset: 348 self.assert_qmp(event, 'data/offset', event['data']['len']) 349 completed = True 350 351 self.assert_no_active_block_jobs() 352 return event 353 354 def wait_ready(self, drive='drive0'): 355 '''Wait until a block job BLOCK_JOB_READY event''' 356 f = {'data': {'type': 'mirror', 'device': drive } } 357 event = self.vm.event_wait(name='BLOCK_JOB_READY', match=f) 358 359 def wait_ready_and_cancel(self, drive='drive0'): 360 self.wait_ready(drive=drive) 361 event = self.cancel_and_wait(drive=drive) 362 self.assertEquals(event['event'], 'BLOCK_JOB_COMPLETED') 363 self.assert_qmp(event, 'data/type', 'mirror') 364 self.assert_qmp(event, 'data/offset', event['data']['len']) 365 366 def complete_and_wait(self, drive='drive0', wait_ready=True): 367 '''Complete a block job and wait for it to finish''' 368 if wait_ready: 369 self.wait_ready(drive=drive) 370 371 result = self.vm.qmp('block-job-complete', device=drive) 372 self.assert_qmp(result, 'return', {}) 373 374 event = self.wait_until_completed(drive=drive) 375 self.assert_qmp(event, 'data/type', 'mirror') 376 377 def pause_job(self, job_id='job0'): 378 result = self.vm.qmp('block-job-pause', device=job_id) 379 self.assert_qmp(result, 'return', {}) 380 381 with Timeout(1, "Timeout waiting for job to pause"): 382 while True: 383 result = self.vm.qmp('query-block-jobs') 384 for job in result['return']: 385 if job['device'] == job_id and job['paused'] == True and job['busy'] == False: 386 return job 387 388 389def notrun(reason): 390 '''Skip this test suite''' 391 # Each test in qemu-iotests has a number ("seq") 392 seq = os.path.basename(sys.argv[0]) 393 394 open('%s/%s.notrun' % (output_dir, seq), 'wb').write(reason + '\n') 395 print '%s not run: %s' % (seq, reason) 396 sys.exit(0) 397 398def verify_image_format(supported_fmts=[]): 399 if supported_fmts and (imgfmt not in supported_fmts): 400 notrun('not suitable for this image format: %s' % imgfmt) 401 402def verify_platform(supported_oses=['linux']): 403 if True not in [sys.platform.startswith(x) for x in supported_oses]: 404 notrun('not suitable for this OS: %s' % sys.platform) 405 406def supports_quorum(): 407 return 'quorum' in qemu_img_pipe('--help') 408 409def verify_quorum(): 410 '''Skip test suite if quorum support is not available''' 411 if not supports_quorum(): 412 notrun('quorum support missing') 413 414def main(supported_fmts=[], supported_oses=['linux']): 415 '''Run tests''' 416 417 global debug 418 419 # We are using TEST_DIR and QEMU_DEFAULT_MACHINE as proxies to 420 # indicate that we're not being run via "check". There may be 421 # other things set up by "check" that individual test cases rely 422 # on. 423 if test_dir is None or qemu_default_machine is None: 424 sys.stderr.write('Please run this test via the "check" script\n') 425 sys.exit(os.EX_USAGE) 426 427 debug = '-d' in sys.argv 428 verbosity = 1 429 verify_image_format(supported_fmts) 430 verify_platform(supported_oses) 431 432 # We need to filter out the time taken from the output so that qemu-iotest 433 # can reliably diff the results against master output. 434 import StringIO 435 if debug: 436 output = sys.stdout 437 verbosity = 2 438 sys.argv.remove('-d') 439 else: 440 output = StringIO.StringIO() 441 442 class MyTestRunner(unittest.TextTestRunner): 443 def __init__(self, stream=output, descriptions=True, verbosity=verbosity): 444 unittest.TextTestRunner.__init__(self, stream, descriptions, verbosity) 445 446 # unittest.main() will use sys.exit() so expect a SystemExit exception 447 try: 448 unittest.main(testRunner=MyTestRunner) 449 finally: 450 if not debug: 451 sys.stderr.write(re.sub(r'Ran (\d+) tests? in [\d.]+s', r'Ran \1 tests', output.getvalue())) 452