iotests.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. from __future__ import print_function
  2. # Common utilities and Python wrappers for qemu-iotests
  3. #
  4. # Copyright (C) 2012 IBM Corp.
  5. #
  6. # This program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 2 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. #
  19. import errno
  20. import os
  21. import re
  22. import subprocess
  23. import string
  24. import unittest
  25. import sys
  26. import struct
  27. import json
  28. import signal
  29. import logging
  30. import atexit
  31. sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'scripts'))
  32. import qtest
  33. # This will not work if arguments contain spaces but is necessary if we
  34. # want to support the override options that ./check supports.
  35. qemu_img_args = [os.environ.get('QEMU_IMG_PROG', 'qemu-img')]
  36. if os.environ.get('QEMU_IMG_OPTIONS'):
  37. qemu_img_args += os.environ['QEMU_IMG_OPTIONS'].strip().split(' ')
  38. qemu_io_args = [os.environ.get('QEMU_IO_PROG', 'qemu-io')]
  39. if os.environ.get('QEMU_IO_OPTIONS'):
  40. qemu_io_args += os.environ['QEMU_IO_OPTIONS'].strip().split(' ')
  41. qemu_nbd_args = [os.environ.get('QEMU_NBD_PROG', 'qemu-nbd')]
  42. if os.environ.get('QEMU_NBD_OPTIONS'):
  43. qemu_nbd_args += os.environ['QEMU_NBD_OPTIONS'].strip().split(' ')
  44. qemu_prog = os.environ.get('QEMU_PROG', 'qemu')
  45. qemu_opts = os.environ.get('QEMU_OPTIONS', '').strip().split(' ')
  46. imgfmt = os.environ.get('IMGFMT', 'raw')
  47. imgproto = os.environ.get('IMGPROTO', 'file')
  48. test_dir = os.environ.get('TEST_DIR')
  49. output_dir = os.environ.get('OUTPUT_DIR', '.')
  50. cachemode = os.environ.get('CACHEMODE')
  51. qemu_default_machine = os.environ.get('QEMU_DEFAULT_MACHINE')
  52. socket_scm_helper = os.environ.get('SOCKET_SCM_HELPER', 'socket_scm_helper')
  53. debug = False
  54. luks_default_secret_object = 'secret,id=keysec0,data=' + \
  55. os.environ['IMGKEYSECRET']
  56. luks_default_key_secret_opt = 'key-secret=keysec0'
  57. def qemu_img(*args):
  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)
  61. if exitcode < 0:
  62. sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args))))
  63. return exitcode
  64. def qemu_img_create(*args):
  65. args = list(args)
  66. # default luks support
  67. if '-f' in args and args[args.index('-f') + 1] == 'luks':
  68. if '-o' in args:
  69. i = args.index('-o')
  70. if 'key-secret' not in args[i + 1]:
  71. args[i + 1].append(luks_default_key_secret_opt)
  72. args.insert(i + 2, '--object')
  73. args.insert(i + 3, luks_default_secret_object)
  74. else:
  75. args = ['-o', luks_default_key_secret_opt,
  76. '--object', luks_default_secret_object] + args
  77. args.insert(0, 'create')
  78. return qemu_img(*args)
  79. def qemu_img_verbose(*args):
  80. '''Run qemu-img without suppressing its output and return the exit code'''
  81. exitcode = subprocess.call(qemu_img_args + list(args))
  82. if exitcode < 0:
  83. sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args))))
  84. return exitcode
  85. def qemu_img_pipe(*args):
  86. '''Run qemu-img and return its output'''
  87. subp = subprocess.Popen(qemu_img_args + list(args),
  88. stdout=subprocess.PIPE,
  89. stderr=subprocess.STDOUT)
  90. exitcode = subp.wait()
  91. if exitcode < 0:
  92. sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args))))
  93. return subp.communicate()[0]
  94. def img_info_log(filename, filter_path=None, imgopts=False, extra_args=[]):
  95. args = [ 'info' ]
  96. if imgopts:
  97. args.append('--image-opts')
  98. else:
  99. args += [ '-f', imgfmt ]
  100. args += extra_args
  101. args.append(filename)
  102. output = qemu_img_pipe(*args)
  103. if not filter_path:
  104. filter_path = filename
  105. log(filter_img_info(output, filter_path))
  106. def qemu_io(*args):
  107. '''Run qemu-io and return the stdout data'''
  108. args = qemu_io_args + list(args)
  109. subp = subprocess.Popen(args, stdout=subprocess.PIPE,
  110. stderr=subprocess.STDOUT)
  111. exitcode = subp.wait()
  112. if exitcode < 0:
  113. sys.stderr.write('qemu-io received signal %i: %s\n' % (-exitcode, ' '.join(args)))
  114. return subp.communicate()[0]
  115. class QemuIoInteractive:
  116. def __init__(self, *args):
  117. self.args = qemu_io_args + list(args)
  118. self._p = subprocess.Popen(self.args, stdin=subprocess.PIPE,
  119. stdout=subprocess.PIPE,
  120. stderr=subprocess.STDOUT)
  121. assert self._p.stdout.read(9) == 'qemu-io> '
  122. def close(self):
  123. self._p.communicate('q\n')
  124. def _read_output(self):
  125. pattern = 'qemu-io> '
  126. n = len(pattern)
  127. pos = 0
  128. s = []
  129. while pos != n:
  130. c = self._p.stdout.read(1)
  131. # check unexpected EOF
  132. assert c != ''
  133. s.append(c)
  134. if c == pattern[pos]:
  135. pos += 1
  136. else:
  137. pos = 0
  138. return ''.join(s[:-n])
  139. def cmd(self, cmd):
  140. # quit command is in close(), '\n' is added automatically
  141. assert '\n' not in cmd
  142. cmd = cmd.strip()
  143. assert cmd != 'q' and cmd != 'quit'
  144. self._p.stdin.write(cmd + '\n')
  145. return self._read_output()
  146. def qemu_nbd(*args):
  147. '''Run qemu-nbd in daemon mode and return the parent's exit code'''
  148. return subprocess.call(qemu_nbd_args + ['--fork'] + list(args))
  149. def compare_images(img1, img2, fmt1=imgfmt, fmt2=imgfmt):
  150. '''Return True if two image files are identical'''
  151. return qemu_img('compare', '-f', fmt1,
  152. '-F', fmt2, img1, img2) == 0
  153. def create_image(name, size):
  154. '''Create a fully-allocated raw image with sector markers'''
  155. file = open(name, 'w')
  156. i = 0
  157. while i < size:
  158. sector = struct.pack('>l504xl', i / 512, i / 512)
  159. file.write(sector)
  160. i = i + 512
  161. file.close()
  162. def image_size(img):
  163. '''Return image's virtual size'''
  164. r = qemu_img_pipe('info', '--output=json', '-f', imgfmt, img)
  165. return json.loads(r)['virtual-size']
  166. test_dir_re = re.compile(r"%s" % test_dir)
  167. def filter_test_dir(msg):
  168. return test_dir_re.sub("TEST_DIR", msg)
  169. win32_re = re.compile(r"\r")
  170. def filter_win32(msg):
  171. return win32_re.sub("", msg)
  172. qemu_io_re = re.compile(r"[0-9]* ops; [0-9\/:. sec]* \([0-9\/.inf]* [EPTGMKiBbytes]*\/sec and [0-9\/.inf]* ops\/sec\)")
  173. def filter_qemu_io(msg):
  174. msg = filter_win32(msg)
  175. return qemu_io_re.sub("X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)", msg)
  176. chown_re = re.compile(r"chown [0-9]+:[0-9]+")
  177. def filter_chown(msg):
  178. return chown_re.sub("chown UID:GID", msg)
  179. def filter_qmp_event(event):
  180. '''Filter a QMP event dict'''
  181. event = dict(event)
  182. if 'timestamp' in event:
  183. event['timestamp']['seconds'] = 'SECS'
  184. event['timestamp']['microseconds'] = 'USECS'
  185. return event
  186. def filter_testfiles(msg):
  187. prefix = os.path.join(test_dir, "%s-" % (os.getpid()))
  188. return msg.replace(prefix, 'TEST_DIR/PID-')
  189. def filter_img_info(output, filename):
  190. lines = []
  191. for line in output.split('\n'):
  192. if 'disk size' in line or 'actual-size' in line:
  193. continue
  194. line = line.replace(filename, 'TEST_IMG') \
  195. .replace(imgfmt, 'IMGFMT')
  196. line = re.sub('iters: [0-9]+', 'iters: XXX', line)
  197. line = re.sub('uuid: [-a-f0-9]+', 'uuid: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX', line)
  198. lines.append(line)
  199. return '\n'.join(lines)
  200. def log(msg, filters=[]):
  201. for flt in filters:
  202. msg = flt(msg)
  203. print(msg)
  204. class Timeout:
  205. def __init__(self, seconds, errmsg = "Timeout"):
  206. self.seconds = seconds
  207. self.errmsg = errmsg
  208. def __enter__(self):
  209. signal.signal(signal.SIGALRM, self.timeout)
  210. signal.setitimer(signal.ITIMER_REAL, self.seconds)
  211. return self
  212. def __exit__(self, type, value, traceback):
  213. signal.setitimer(signal.ITIMER_REAL, 0)
  214. return False
  215. def timeout(self, signum, frame):
  216. raise Exception(self.errmsg)
  217. class FilePath(object):
  218. '''An auto-generated filename that cleans itself up.
  219. Use this context manager to generate filenames and ensure that the file
  220. gets deleted::
  221. with TestFilePath('test.img') as img_path:
  222. qemu_img('create', img_path, '1G')
  223. # migration_sock_path is automatically deleted
  224. '''
  225. def __init__(self, name):
  226. filename = '{0}-{1}'.format(os.getpid(), name)
  227. self.path = os.path.join(test_dir, filename)
  228. def __enter__(self):
  229. return self.path
  230. def __exit__(self, exc_type, exc_val, exc_tb):
  231. try:
  232. os.remove(self.path)
  233. except OSError:
  234. pass
  235. return False
  236. def file_path_remover():
  237. for path in reversed(file_path_remover.paths):
  238. try:
  239. os.remove(path)
  240. except OSError:
  241. pass
  242. def file_path(*names):
  243. ''' Another way to get auto-generated filename that cleans itself up.
  244. Use is as simple as:
  245. img_a, img_b = file_path('a.img', 'b.img')
  246. sock = file_path('socket')
  247. '''
  248. if not hasattr(file_path_remover, 'paths'):
  249. file_path_remover.paths = []
  250. atexit.register(file_path_remover)
  251. paths = []
  252. for name in names:
  253. filename = '{0}-{1}'.format(os.getpid(), name)
  254. path = os.path.join(test_dir, filename)
  255. file_path_remover.paths.append(path)
  256. paths.append(path)
  257. return paths[0] if len(paths) == 1 else paths
  258. def remote_filename(path):
  259. if imgproto == 'file':
  260. return path
  261. elif imgproto == 'ssh':
  262. return "ssh://127.0.0.1%s" % (path)
  263. else:
  264. raise Exception("Protocol %s not supported" % (imgproto))
  265. class VM(qtest.QEMUQtestMachine):
  266. '''A QEMU VM'''
  267. def __init__(self, path_suffix=''):
  268. name = "qemu%s-%d" % (path_suffix, os.getpid())
  269. super(VM, self).__init__(qemu_prog, qemu_opts, name=name,
  270. test_dir=test_dir,
  271. socket_scm_helper=socket_scm_helper)
  272. self._num_drives = 0
  273. def add_object(self, opts):
  274. self._args.append('-object')
  275. self._args.append(opts)
  276. return self
  277. def add_device(self, opts):
  278. self._args.append('-device')
  279. self._args.append(opts)
  280. return self
  281. def add_drive_raw(self, opts):
  282. self._args.append('-drive')
  283. self._args.append(opts)
  284. return self
  285. def add_drive(self, path, opts='', interface='virtio', format=imgfmt):
  286. '''Add a virtio-blk drive to the VM'''
  287. options = ['if=%s' % interface,
  288. 'id=drive%d' % self._num_drives]
  289. if path is not None:
  290. options.append('file=%s' % path)
  291. options.append('format=%s' % format)
  292. options.append('cache=%s' % cachemode)
  293. if opts:
  294. options.append(opts)
  295. if format == 'luks' and 'key-secret' not in opts:
  296. # default luks support
  297. if luks_default_secret_object not in self._args:
  298. self.add_object(luks_default_secret_object)
  299. options.append(luks_default_key_secret_opt)
  300. self._args.append('-drive')
  301. self._args.append(','.join(options))
  302. self._num_drives += 1
  303. return self
  304. def add_blockdev(self, opts):
  305. self._args.append('-blockdev')
  306. if isinstance(opts, str):
  307. self._args.append(opts)
  308. else:
  309. self._args.append(','.join(opts))
  310. return self
  311. def add_incoming(self, addr):
  312. self._args.append('-incoming')
  313. self._args.append(addr)
  314. return self
  315. def pause_drive(self, drive, event=None):
  316. '''Pause drive r/w operations'''
  317. if not event:
  318. self.pause_drive(drive, "read_aio")
  319. self.pause_drive(drive, "write_aio")
  320. return
  321. self.qmp('human-monitor-command',
  322. command_line='qemu-io %s "break %s bp_%s"' % (drive, event, drive))
  323. def resume_drive(self, drive):
  324. self.qmp('human-monitor-command',
  325. command_line='qemu-io %s "remove_break bp_%s"' % (drive, drive))
  326. def hmp_qemu_io(self, drive, cmd):
  327. '''Write to a given drive using an HMP command'''
  328. return self.qmp('human-monitor-command',
  329. command_line='qemu-io %s "%s"' % (drive, cmd))
  330. def flatten_qmp_object(self, obj, output=None, basestr=''):
  331. if output is None:
  332. output = dict()
  333. if isinstance(obj, list):
  334. for i in range(len(obj)):
  335. self.flatten_qmp_object(obj[i], output, basestr + str(i) + '.')
  336. elif isinstance(obj, dict):
  337. for key in obj:
  338. self.flatten_qmp_object(obj[key], output, basestr + key + '.')
  339. else:
  340. output[basestr[:-1]] = obj # Strip trailing '.'
  341. return output
  342. def qmp_to_opts(self, obj):
  343. obj = self.flatten_qmp_object(obj)
  344. output_list = list()
  345. for key in obj:
  346. output_list += [key + '=' + obj[key]]
  347. return ','.join(output_list)
  348. def get_qmp_events_filtered(self, wait=True):
  349. result = []
  350. for ev in self.get_qmp_events(wait=wait):
  351. result.append(filter_qmp_event(ev))
  352. return result
  353. def qmp_log(self, cmd, filters=[filter_testfiles], **kwargs):
  354. logmsg = "{'execute': '%s', 'arguments': %s}" % (cmd, kwargs)
  355. log(logmsg, filters)
  356. result = self.qmp(cmd, **kwargs)
  357. log(str(result), filters)
  358. return result
  359. def run_job(self, job, auto_finalize=True, auto_dismiss=False):
  360. while True:
  361. for ev in self.get_qmp_events_filtered(wait=True):
  362. if ev['event'] == 'JOB_STATUS_CHANGE':
  363. status = ev['data']['status']
  364. if status == 'aborting':
  365. result = self.qmp('query-jobs')
  366. for j in result['return']:
  367. if j['id'] == job:
  368. log('Job failed: %s' % (j['error']))
  369. elif status == 'pending' and not auto_finalize:
  370. self.qmp_log('job-finalize', id=job)
  371. elif status == 'concluded' and not auto_dismiss:
  372. self.qmp_log('job-dismiss', id=job)
  373. elif status == 'null':
  374. return
  375. else:
  376. iotests.log(ev)
  377. index_re = re.compile(r'([^\[]+)\[([^\]]+)\]')
  378. class QMPTestCase(unittest.TestCase):
  379. '''Abstract base class for QMP test cases'''
  380. def dictpath(self, d, path):
  381. '''Traverse a path in a nested dict'''
  382. for component in path.split('/'):
  383. m = index_re.match(component)
  384. if m:
  385. component, idx = m.groups()
  386. idx = int(idx)
  387. if not isinstance(d, dict) or component not in d:
  388. self.fail('failed path traversal for "%s" in "%s"' % (path, str(d)))
  389. d = d[component]
  390. if m:
  391. if not isinstance(d, list):
  392. self.fail('path component "%s" in "%s" is not a list in "%s"' % (component, path, str(d)))
  393. try:
  394. d = d[idx]
  395. except IndexError:
  396. self.fail('invalid index "%s" in path "%s" in "%s"' % (idx, path, str(d)))
  397. return d
  398. def assert_qmp_absent(self, d, path):
  399. try:
  400. result = self.dictpath(d, path)
  401. except AssertionError:
  402. return
  403. self.fail('path "%s" has value "%s"' % (path, str(result)))
  404. def assert_qmp(self, d, path, value):
  405. '''Assert that the value for a specific path in a QMP dict matches'''
  406. result = self.dictpath(d, path)
  407. self.assertEqual(result, value, 'values not equal "%s" and "%s"' % (str(result), str(value)))
  408. def assert_no_active_block_jobs(self):
  409. result = self.vm.qmp('query-block-jobs')
  410. self.assert_qmp(result, 'return', [])
  411. def assert_has_block_node(self, node_name=None, file_name=None):
  412. """Issue a query-named-block-nodes and assert node_name and/or
  413. file_name is present in the result"""
  414. def check_equal_or_none(a, b):
  415. return a == None or b == None or a == b
  416. assert node_name or file_name
  417. result = self.vm.qmp('query-named-block-nodes')
  418. for x in result["return"]:
  419. if check_equal_or_none(x.get("node-name"), node_name) and \
  420. check_equal_or_none(x.get("file"), file_name):
  421. return
  422. self.assertTrue(False, "Cannot find %s %s in result:\n%s" % \
  423. (node_name, file_name, result))
  424. def assert_json_filename_equal(self, json_filename, reference):
  425. '''Asserts that the given filename is a json: filename and that its
  426. content is equal to the given reference object'''
  427. self.assertEqual(json_filename[:5], 'json:')
  428. self.assertEqual(self.vm.flatten_qmp_object(json.loads(json_filename[5:])),
  429. self.vm.flatten_qmp_object(reference))
  430. def cancel_and_wait(self, drive='drive0', force=False, resume=False):
  431. '''Cancel a block job and wait for it to finish, returning the event'''
  432. result = self.vm.qmp('block-job-cancel', device=drive, force=force)
  433. self.assert_qmp(result, 'return', {})
  434. if resume:
  435. self.vm.resume_drive(drive)
  436. cancelled = False
  437. result = None
  438. while not cancelled:
  439. for event in self.vm.get_qmp_events(wait=True):
  440. if event['event'] == 'BLOCK_JOB_COMPLETED' or \
  441. event['event'] == 'BLOCK_JOB_CANCELLED':
  442. self.assert_qmp(event, 'data/device', drive)
  443. result = event
  444. cancelled = True
  445. elif event['event'] == 'JOB_STATUS_CHANGE':
  446. self.assert_qmp(event, 'data/id', drive)
  447. self.assert_no_active_block_jobs()
  448. return result
  449. def wait_until_completed(self, drive='drive0', check_offset=True):
  450. '''Wait for a block job to finish, returning the event'''
  451. while True:
  452. for event in self.vm.get_qmp_events(wait=True):
  453. if event['event'] == 'BLOCK_JOB_COMPLETED':
  454. self.assert_qmp(event, 'data/device', drive)
  455. self.assert_qmp_absent(event, 'data/error')
  456. if check_offset:
  457. self.assert_qmp(event, 'data/offset', event['data']['len'])
  458. self.assert_no_active_block_jobs()
  459. return event
  460. elif event['event'] == 'JOB_STATUS_CHANGE':
  461. self.assert_qmp(event, 'data/id', drive)
  462. def wait_ready(self, drive='drive0'):
  463. '''Wait until a block job BLOCK_JOB_READY event'''
  464. f = {'data': {'type': 'mirror', 'device': drive } }
  465. event = self.vm.event_wait(name='BLOCK_JOB_READY', match=f)
  466. def wait_ready_and_cancel(self, drive='drive0'):
  467. self.wait_ready(drive=drive)
  468. event = self.cancel_and_wait(drive=drive)
  469. self.assertEquals(event['event'], 'BLOCK_JOB_COMPLETED')
  470. self.assert_qmp(event, 'data/type', 'mirror')
  471. self.assert_qmp(event, 'data/offset', event['data']['len'])
  472. def complete_and_wait(self, drive='drive0', wait_ready=True):
  473. '''Complete a block job and wait for it to finish'''
  474. if wait_ready:
  475. self.wait_ready(drive=drive)
  476. result = self.vm.qmp('block-job-complete', device=drive)
  477. self.assert_qmp(result, 'return', {})
  478. event = self.wait_until_completed(drive=drive)
  479. self.assert_qmp(event, 'data/type', 'mirror')
  480. def pause_wait(self, job_id='job0'):
  481. with Timeout(1, "Timeout waiting for job to pause"):
  482. while True:
  483. result = self.vm.qmp('query-block-jobs')
  484. for job in result['return']:
  485. if job['device'] == job_id and job['paused'] == True and job['busy'] == False:
  486. return job
  487. def pause_job(self, job_id='job0', wait=True):
  488. result = self.vm.qmp('block-job-pause', device=job_id)
  489. self.assert_qmp(result, 'return', {})
  490. if wait:
  491. return self.pause_wait(job_id)
  492. return result
  493. def notrun(reason):
  494. '''Skip this test suite'''
  495. # Each test in qemu-iotests has a number ("seq")
  496. seq = os.path.basename(sys.argv[0])
  497. open('%s/%s.notrun' % (output_dir, seq), 'wb').write(reason + '\n')
  498. print('%s not run: %s' % (seq, reason))
  499. sys.exit(0)
  500. def verify_image_format(supported_fmts=[], unsupported_fmts=[]):
  501. assert not (supported_fmts and unsupported_fmts)
  502. if 'generic' in supported_fmts and \
  503. os.environ.get('IMGFMT_GENERIC', 'true') == 'true':
  504. # similar to
  505. # _supported_fmt generic
  506. # for bash tests
  507. return
  508. not_sup = supported_fmts and (imgfmt not in supported_fmts)
  509. if not_sup or (imgfmt in unsupported_fmts):
  510. notrun('not suitable for this image format: %s' % imgfmt)
  511. def verify_protocol(supported=[], unsupported=[]):
  512. assert not (supported and unsupported)
  513. if 'generic' in supported:
  514. return
  515. not_sup = supported and (imgproto not in supported)
  516. if not_sup or (imgproto in unsupported):
  517. notrun('not suitable for this protocol: %s' % imgproto)
  518. def verify_platform(supported_oses=['linux']):
  519. if True not in [sys.platform.startswith(x) for x in supported_oses]:
  520. notrun('not suitable for this OS: %s' % sys.platform)
  521. def verify_cache_mode(supported_cache_modes=[]):
  522. if supported_cache_modes and (cachemode not in supported_cache_modes):
  523. notrun('not suitable for this cache mode: %s' % cachemode)
  524. def supports_quorum():
  525. return 'quorum' in qemu_img_pipe('--help')
  526. def verify_quorum():
  527. '''Skip test suite if quorum support is not available'''
  528. if not supports_quorum():
  529. notrun('quorum support missing')
  530. def main(supported_fmts=[], supported_oses=['linux'], supported_cache_modes=[],
  531. unsupported_fmts=[]):
  532. '''Run tests'''
  533. global debug
  534. # We are using TEST_DIR and QEMU_DEFAULT_MACHINE as proxies to
  535. # indicate that we're not being run via "check". There may be
  536. # other things set up by "check" that individual test cases rely
  537. # on.
  538. if test_dir is None or qemu_default_machine is None:
  539. sys.stderr.write('Please run this test via the "check" script\n')
  540. sys.exit(os.EX_USAGE)
  541. debug = '-d' in sys.argv
  542. verbosity = 1
  543. verify_image_format(supported_fmts, unsupported_fmts)
  544. verify_platform(supported_oses)
  545. verify_cache_mode(supported_cache_modes)
  546. # We need to filter out the time taken from the output so that qemu-iotest
  547. # can reliably diff the results against master output.
  548. import StringIO
  549. if debug:
  550. output = sys.stdout
  551. verbosity = 2
  552. sys.argv.remove('-d')
  553. else:
  554. output = StringIO.StringIO()
  555. logging.basicConfig(level=(logging.DEBUG if debug else logging.WARN))
  556. class MyTestRunner(unittest.TextTestRunner):
  557. def __init__(self, stream=output, descriptions=True, verbosity=verbosity):
  558. unittest.TextTestRunner.__init__(self, stream, descriptions, verbosity)
  559. # unittest.main() will use sys.exit() so expect a SystemExit exception
  560. try:
  561. unittest.main(testRunner=MyTestRunner)
  562. finally:
  563. if not debug:
  564. sys.stderr.write(re.sub(r'Ran (\d+) tests? in [\d.]+s', r'Ran \1 tests', output.getvalue()))