iotests.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  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. import io
  32. from collections import OrderedDict
  33. sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'python'))
  34. from qemu import qtest
  35. # This will not work if arguments contain spaces but is necessary if we
  36. # want to support the override options that ./check supports.
  37. qemu_img_args = [os.environ.get('QEMU_IMG_PROG', 'qemu-img')]
  38. if os.environ.get('QEMU_IMG_OPTIONS'):
  39. 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(' ')
  43. qemu_nbd_args = [os.environ.get('QEMU_NBD_PROG', 'qemu-nbd')]
  44. if os.environ.get('QEMU_NBD_OPTIONS'):
  45. qemu_nbd_args += os.environ['QEMU_NBD_OPTIONS'].strip().split(' ')
  46. qemu_prog = os.environ.get('QEMU_PROG', 'qemu')
  47. qemu_opts = os.environ.get('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')
  51. output_dir = os.environ.get('OUTPUT_DIR', '.')
  52. cachemode = os.environ.get('CACHEMODE')
  53. qemu_default_machine = os.environ.get('QEMU_DEFAULT_MACHINE')
  54. socket_scm_helper = os.environ.get('SOCKET_SCM_HELPER', 'socket_scm_helper')
  55. debug = False
  56. luks_default_secret_object = 'secret,id=keysec0,data=' + \
  57. os.environ.get('IMGKEYSECRET', '')
  58. luks_default_key_secret_opt = 'key-secret=keysec0'
  59. def qemu_img(*args):
  60. '''Run qemu-img and return the exit code'''
  61. devnull = open('/dev/null', 'r+')
  62. exitcode = subprocess.call(qemu_img_args + list(args), stdin=devnull, stdout=devnull)
  63. if exitcode < 0:
  64. sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args))))
  65. return exitcode
  66. def ordered_qmp(qmsg, conv_keys=True):
  67. # Dictionaries are not ordered prior to 3.6, therefore:
  68. if isinstance(qmsg, list):
  69. return [ordered_qmp(atom) for atom in qmsg]
  70. if isinstance(qmsg, dict):
  71. od = OrderedDict()
  72. for k, v in sorted(qmsg.items()):
  73. if conv_keys:
  74. k = k.replace('_', '-')
  75. od[k] = ordered_qmp(v, conv_keys=False)
  76. return od
  77. return qmsg
  78. def qemu_img_create(*args):
  79. args = list(args)
  80. # default luks support
  81. if '-f' in args and args[args.index('-f') + 1] == 'luks':
  82. if '-o' in args:
  83. i = args.index('-o')
  84. if 'key-secret' not in args[i + 1]:
  85. args[i + 1].append(luks_default_key_secret_opt)
  86. args.insert(i + 2, '--object')
  87. args.insert(i + 3, luks_default_secret_object)
  88. else:
  89. args = ['-o', luks_default_key_secret_opt,
  90. '--object', luks_default_secret_object] + args
  91. args.insert(0, 'create')
  92. return qemu_img(*args)
  93. def qemu_img_verbose(*args):
  94. '''Run qemu-img without suppressing its output and return the exit code'''
  95. exitcode = subprocess.call(qemu_img_args + list(args))
  96. if exitcode < 0:
  97. sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args))))
  98. return exitcode
  99. def qemu_img_pipe(*args):
  100. '''Run qemu-img and return its output'''
  101. subp = subprocess.Popen(qemu_img_args + list(args),
  102. stdout=subprocess.PIPE,
  103. stderr=subprocess.STDOUT,
  104. universal_newlines=True)
  105. exitcode = subp.wait()
  106. if exitcode < 0:
  107. sys.stderr.write('qemu-img received signal %i: %s\n' % (-exitcode, ' '.join(qemu_img_args + list(args))))
  108. return subp.communicate()[0]
  109. def qemu_img_log(*args):
  110. result = qemu_img_pipe(*args)
  111. log(result, filters=[filter_testfiles])
  112. return result
  113. def img_info_log(filename, filter_path=None, imgopts=False, extra_args=[]):
  114. args = [ 'info' ]
  115. if imgopts:
  116. args.append('--image-opts')
  117. else:
  118. args += [ '-f', imgfmt ]
  119. args += extra_args
  120. args.append(filename)
  121. output = qemu_img_pipe(*args)
  122. if not filter_path:
  123. filter_path = filename
  124. log(filter_img_info(output, filter_path))
  125. def qemu_io(*args):
  126. '''Run qemu-io and return the stdout data'''
  127. args = qemu_io_args + list(args)
  128. subp = subprocess.Popen(args, stdout=subprocess.PIPE,
  129. stderr=subprocess.STDOUT,
  130. universal_newlines=True)
  131. exitcode = subp.wait()
  132. if exitcode < 0:
  133. sys.stderr.write('qemu-io received signal %i: %s\n' % (-exitcode, ' '.join(args)))
  134. return subp.communicate()[0]
  135. def qemu_io_silent(*args):
  136. '''Run qemu-io and return the exit code, suppressing stdout'''
  137. args = qemu_io_args + list(args)
  138. exitcode = subprocess.call(args, stdout=open('/dev/null', 'w'))
  139. if exitcode < 0:
  140. sys.stderr.write('qemu-io received signal %i: %s\n' %
  141. (-exitcode, ' '.join(args)))
  142. return exitcode
  143. class QemuIoInteractive:
  144. def __init__(self, *args):
  145. self.args = qemu_io_args + list(args)
  146. self._p = subprocess.Popen(self.args, stdin=subprocess.PIPE,
  147. stdout=subprocess.PIPE,
  148. stderr=subprocess.STDOUT,
  149. universal_newlines=True)
  150. assert self._p.stdout.read(9) == 'qemu-io> '
  151. def close(self):
  152. self._p.communicate('q\n')
  153. def _read_output(self):
  154. pattern = 'qemu-io> '
  155. n = len(pattern)
  156. pos = 0
  157. s = []
  158. while pos != n:
  159. c = self._p.stdout.read(1)
  160. # check unexpected EOF
  161. assert c != ''
  162. s.append(c)
  163. if c == pattern[pos]:
  164. pos += 1
  165. else:
  166. pos = 0
  167. return ''.join(s[:-n])
  168. def cmd(self, cmd):
  169. # quit command is in close(), '\n' is added automatically
  170. assert '\n' not in cmd
  171. cmd = cmd.strip()
  172. assert cmd != 'q' and cmd != 'quit'
  173. self._p.stdin.write(cmd + '\n')
  174. self._p.stdin.flush()
  175. return self._read_output()
  176. def qemu_nbd(*args):
  177. '''Run qemu-nbd in daemon mode and return the parent's exit code'''
  178. return subprocess.call(qemu_nbd_args + ['--fork'] + list(args))
  179. def qemu_nbd_pipe(*args):
  180. '''Run qemu-nbd in daemon mode and return both the parent's exit code
  181. and its output'''
  182. subp = subprocess.Popen(qemu_nbd_args + ['--fork'] + list(args),
  183. stdout=subprocess.PIPE,
  184. stderr=subprocess.STDOUT,
  185. universal_newlines=True)
  186. exitcode = subp.wait()
  187. if exitcode < 0:
  188. sys.stderr.write('qemu-nbd received signal %i: %s\n' %
  189. (-exitcode,
  190. ' '.join(qemu_nbd_args + ['--fork'] + list(args))))
  191. return exitcode, subp.communicate()[0]
  192. def compare_images(img1, img2, fmt1=imgfmt, fmt2=imgfmt):
  193. '''Return True if two image files are identical'''
  194. return qemu_img('compare', '-f', fmt1,
  195. '-F', fmt2, img1, img2) == 0
  196. def create_image(name, size):
  197. '''Create a fully-allocated raw image with sector markers'''
  198. file = open(name, 'wb')
  199. i = 0
  200. while i < size:
  201. sector = struct.pack('>l504xl', i // 512, i // 512)
  202. file.write(sector)
  203. i = i + 512
  204. file.close()
  205. def image_size(img):
  206. '''Return image's virtual size'''
  207. r = qemu_img_pipe('info', '--output=json', '-f', imgfmt, img)
  208. return json.loads(r)['virtual-size']
  209. def is_str(val):
  210. if sys.version_info.major >= 3:
  211. return isinstance(val, str)
  212. else:
  213. return isinstance(val, str) or isinstance(val, unicode)
  214. test_dir_re = re.compile(r"%s" % test_dir)
  215. def filter_test_dir(msg):
  216. return test_dir_re.sub("TEST_DIR", msg)
  217. win32_re = re.compile(r"\r")
  218. def filter_win32(msg):
  219. return win32_re.sub("", msg)
  220. qemu_io_re = re.compile(r"[0-9]* ops; [0-9\/:. sec]* \([0-9\/.inf]* [EPTGMKiBbytes]*\/sec and [0-9\/.inf]* ops\/sec\)")
  221. def filter_qemu_io(msg):
  222. msg = filter_win32(msg)
  223. return qemu_io_re.sub("X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)", msg)
  224. chown_re = re.compile(r"chown [0-9]+:[0-9]+")
  225. def filter_chown(msg):
  226. return chown_re.sub("chown UID:GID", msg)
  227. def filter_qmp_event(event):
  228. '''Filter a QMP event dict'''
  229. event = dict(event)
  230. if 'timestamp' in event:
  231. event['timestamp']['seconds'] = 'SECS'
  232. event['timestamp']['microseconds'] = 'USECS'
  233. return event
  234. def filter_qmp(qmsg, filter_fn):
  235. '''Given a string filter, filter a QMP object's values.
  236. filter_fn takes a (key, value) pair.'''
  237. # Iterate through either lists or dicts;
  238. if isinstance(qmsg, list):
  239. items = enumerate(qmsg)
  240. else:
  241. items = qmsg.items()
  242. for k, v in items:
  243. if isinstance(v, list) or isinstance(v, dict):
  244. qmsg[k] = filter_qmp(v, filter_fn)
  245. else:
  246. qmsg[k] = filter_fn(k, v)
  247. return qmsg
  248. def filter_testfiles(msg):
  249. prefix = os.path.join(test_dir, "%s-" % (os.getpid()))
  250. return msg.replace(prefix, 'TEST_DIR/PID-')
  251. def filter_qmp_testfiles(qmsg):
  252. def _filter(key, value):
  253. if is_str(value):
  254. return filter_testfiles(value)
  255. return value
  256. return filter_qmp(qmsg, _filter)
  257. def filter_generated_node_ids(msg):
  258. return re.sub("#block[0-9]+", "NODE_NAME", msg)
  259. def filter_img_info(output, filename):
  260. lines = []
  261. for line in output.split('\n'):
  262. if 'disk size' in line or 'actual-size' in line:
  263. continue
  264. line = line.replace(filename, 'TEST_IMG') \
  265. .replace(imgfmt, 'IMGFMT')
  266. line = re.sub('iters: [0-9]+', 'iters: XXX', line)
  267. line = re.sub('uuid: [-a-f0-9]+', 'uuid: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX', line)
  268. line = re.sub('cid: [0-9]+', 'cid: XXXXXXXXXX', line)
  269. lines.append(line)
  270. return '\n'.join(lines)
  271. def filter_imgfmt(msg):
  272. return msg.replace(imgfmt, 'IMGFMT')
  273. def filter_qmp_imgfmt(qmsg):
  274. def _filter(key, value):
  275. if is_str(value):
  276. return filter_imgfmt(value)
  277. return value
  278. return filter_qmp(qmsg, _filter)
  279. def log(msg, filters=[], indent=None):
  280. '''Logs either a string message or a JSON serializable message (like QMP).
  281. If indent is provided, JSON serializable messages are pretty-printed.'''
  282. for flt in filters:
  283. msg = flt(msg)
  284. if isinstance(msg, dict) or isinstance(msg, list):
  285. # Python < 3.4 needs to know not to add whitespace when pretty-printing:
  286. separators = (', ', ': ') if indent is None else (',', ': ')
  287. # Don't sort if it's already sorted
  288. do_sort = not isinstance(msg, OrderedDict)
  289. print(json.dumps(msg, sort_keys=do_sort,
  290. indent=indent, separators=separators))
  291. else:
  292. print(msg)
  293. class Timeout:
  294. def __init__(self, seconds, errmsg = "Timeout"):
  295. self.seconds = seconds
  296. self.errmsg = errmsg
  297. def __enter__(self):
  298. signal.signal(signal.SIGALRM, self.timeout)
  299. signal.setitimer(signal.ITIMER_REAL, self.seconds)
  300. return self
  301. def __exit__(self, type, value, traceback):
  302. signal.setitimer(signal.ITIMER_REAL, 0)
  303. return False
  304. def timeout(self, signum, frame):
  305. raise Exception(self.errmsg)
  306. class FilePath(object):
  307. '''An auto-generated filename that cleans itself up.
  308. Use this context manager to generate filenames and ensure that the file
  309. gets deleted::
  310. with TestFilePath('test.img') as img_path:
  311. qemu_img('create', img_path, '1G')
  312. # migration_sock_path is automatically deleted
  313. '''
  314. def __init__(self, name):
  315. filename = '{0}-{1}'.format(os.getpid(), name)
  316. self.path = os.path.join(test_dir, filename)
  317. def __enter__(self):
  318. return self.path
  319. def __exit__(self, exc_type, exc_val, exc_tb):
  320. try:
  321. os.remove(self.path)
  322. except OSError:
  323. pass
  324. return False
  325. def file_path_remover():
  326. for path in reversed(file_path_remover.paths):
  327. try:
  328. os.remove(path)
  329. except OSError:
  330. pass
  331. def file_path(*names):
  332. ''' Another way to get auto-generated filename that cleans itself up.
  333. Use is as simple as:
  334. img_a, img_b = file_path('a.img', 'b.img')
  335. sock = file_path('socket')
  336. '''
  337. if not hasattr(file_path_remover, 'paths'):
  338. file_path_remover.paths = []
  339. atexit.register(file_path_remover)
  340. paths = []
  341. for name in names:
  342. filename = '{0}-{1}'.format(os.getpid(), name)
  343. path = os.path.join(test_dir, filename)
  344. file_path_remover.paths.append(path)
  345. paths.append(path)
  346. return paths[0] if len(paths) == 1 else paths
  347. def remote_filename(path):
  348. if imgproto == 'file':
  349. return path
  350. elif imgproto == 'ssh':
  351. return "ssh://%s@127.0.0.1:22%s" % (os.environ.get('USER'), path)
  352. else:
  353. raise Exception("Protocol %s not supported" % (imgproto))
  354. class VM(qtest.QEMUQtestMachine):
  355. '''A QEMU VM'''
  356. def __init__(self, path_suffix=''):
  357. name = "qemu%s-%d" % (path_suffix, os.getpid())
  358. super(VM, self).__init__(qemu_prog, qemu_opts, name=name,
  359. test_dir=test_dir,
  360. socket_scm_helper=socket_scm_helper)
  361. self._num_drives = 0
  362. def add_object(self, opts):
  363. self._args.append('-object')
  364. self._args.append(opts)
  365. return self
  366. def add_device(self, opts):
  367. self._args.append('-device')
  368. self._args.append(opts)
  369. return self
  370. def add_drive_raw(self, opts):
  371. self._args.append('-drive')
  372. self._args.append(opts)
  373. return self
  374. def add_drive(self, path, opts='', interface='virtio', format=imgfmt):
  375. '''Add a virtio-blk drive to the VM'''
  376. options = ['if=%s' % interface,
  377. 'id=drive%d' % self._num_drives]
  378. if path is not None:
  379. options.append('file=%s' % path)
  380. options.append('format=%s' % format)
  381. options.append('cache=%s' % cachemode)
  382. if opts:
  383. options.append(opts)
  384. if format == 'luks' and 'key-secret' not in opts:
  385. # default luks support
  386. if luks_default_secret_object not in self._args:
  387. self.add_object(luks_default_secret_object)
  388. options.append(luks_default_key_secret_opt)
  389. self._args.append('-drive')
  390. self._args.append(','.join(options))
  391. self._num_drives += 1
  392. return self
  393. def add_blockdev(self, opts):
  394. self._args.append('-blockdev')
  395. if isinstance(opts, str):
  396. self._args.append(opts)
  397. else:
  398. self._args.append(','.join(opts))
  399. return self
  400. def add_incoming(self, addr):
  401. self._args.append('-incoming')
  402. self._args.append(addr)
  403. return self
  404. def pause_drive(self, drive, event=None):
  405. '''Pause drive r/w operations'''
  406. if not event:
  407. self.pause_drive(drive, "read_aio")
  408. self.pause_drive(drive, "write_aio")
  409. return
  410. self.qmp('human-monitor-command',
  411. command_line='qemu-io %s "break %s bp_%s"' % (drive, event, drive))
  412. def resume_drive(self, drive):
  413. self.qmp('human-monitor-command',
  414. command_line='qemu-io %s "remove_break bp_%s"' % (drive, drive))
  415. def hmp_qemu_io(self, drive, cmd):
  416. '''Write to a given drive using an HMP command'''
  417. return self.qmp('human-monitor-command',
  418. command_line='qemu-io %s "%s"' % (drive, cmd))
  419. def flatten_qmp_object(self, obj, output=None, basestr=''):
  420. if output is None:
  421. output = dict()
  422. if isinstance(obj, list):
  423. for i in range(len(obj)):
  424. self.flatten_qmp_object(obj[i], output, basestr + str(i) + '.')
  425. elif isinstance(obj, dict):
  426. for key in obj:
  427. self.flatten_qmp_object(obj[key], output, basestr + key + '.')
  428. else:
  429. output[basestr[:-1]] = obj # Strip trailing '.'
  430. return output
  431. def qmp_to_opts(self, obj):
  432. obj = self.flatten_qmp_object(obj)
  433. output_list = list()
  434. for key in obj:
  435. output_list += [key + '=' + obj[key]]
  436. return ','.join(output_list)
  437. def get_qmp_events_filtered(self, wait=True):
  438. result = []
  439. for ev in self.get_qmp_events(wait=wait):
  440. result.append(filter_qmp_event(ev))
  441. return result
  442. def qmp_log(self, cmd, filters=[], indent=None, **kwargs):
  443. full_cmd = OrderedDict((
  444. ("execute", cmd),
  445. ("arguments", ordered_qmp(kwargs))
  446. ))
  447. log(full_cmd, filters, indent=indent)
  448. result = self.qmp(cmd, **kwargs)
  449. log(result, filters, indent=indent)
  450. return result
  451. # Returns None on success, and an error string on failure
  452. def run_job(self, job, auto_finalize=True, auto_dismiss=False,
  453. pre_finalize=None):
  454. error = None
  455. while True:
  456. for ev in self.get_qmp_events_filtered(wait=True):
  457. if ev['event'] == 'JOB_STATUS_CHANGE':
  458. status = ev['data']['status']
  459. if status == 'aborting':
  460. result = self.qmp('query-jobs')
  461. for j in result['return']:
  462. if j['id'] == job:
  463. error = j['error']
  464. log('Job failed: %s' % (j['error']))
  465. elif status == 'pending' and not auto_finalize:
  466. if pre_finalize:
  467. pre_finalize()
  468. self.qmp_log('job-finalize', id=job)
  469. elif status == 'concluded' and not auto_dismiss:
  470. self.qmp_log('job-dismiss', id=job)
  471. elif status == 'null':
  472. return error
  473. else:
  474. log(ev)
  475. def node_info(self, node_name):
  476. nodes = self.qmp('query-named-block-nodes')
  477. for x in nodes['return']:
  478. if x['node-name'] == node_name:
  479. return x
  480. return None
  481. index_re = re.compile(r'([^\[]+)\[([^\]]+)\]')
  482. class QMPTestCase(unittest.TestCase):
  483. '''Abstract base class for QMP test cases'''
  484. def dictpath(self, d, path):
  485. '''Traverse a path in a nested dict'''
  486. for component in path.split('/'):
  487. m = index_re.match(component)
  488. if m:
  489. component, idx = m.groups()
  490. idx = int(idx)
  491. if not isinstance(d, dict) or component not in d:
  492. self.fail('failed path traversal for "%s" in "%s"' % (path, str(d)))
  493. d = d[component]
  494. if m:
  495. if not isinstance(d, list):
  496. self.fail('path component "%s" in "%s" is not a list in "%s"' % (component, path, str(d)))
  497. try:
  498. d = d[idx]
  499. except IndexError:
  500. self.fail('invalid index "%s" in path "%s" in "%s"' % (idx, path, str(d)))
  501. return d
  502. def assert_qmp_absent(self, d, path):
  503. try:
  504. result = self.dictpath(d, path)
  505. except AssertionError:
  506. return
  507. self.fail('path "%s" has value "%s"' % (path, str(result)))
  508. def assert_qmp(self, d, path, value):
  509. '''Assert that the value for a specific path in a QMP dict
  510. matches. When given a list of values, assert that any of
  511. them matches.'''
  512. result = self.dictpath(d, path)
  513. # [] makes no sense as a list of valid values, so treat it as
  514. # an actual single value.
  515. if isinstance(value, list) and value != []:
  516. for v in value:
  517. if result == v:
  518. return
  519. self.fail('no match for "%s" in %s' % (str(result), str(value)))
  520. else:
  521. self.assertEqual(result, value,
  522. 'values not equal "%s" and "%s"'
  523. % (str(result), str(value)))
  524. def assert_no_active_block_jobs(self):
  525. result = self.vm.qmp('query-block-jobs')
  526. self.assert_qmp(result, 'return', [])
  527. def assert_has_block_node(self, node_name=None, file_name=None):
  528. """Issue a query-named-block-nodes and assert node_name and/or
  529. file_name is present in the result"""
  530. def check_equal_or_none(a, b):
  531. return a == None or b == None or a == b
  532. assert node_name or file_name
  533. result = self.vm.qmp('query-named-block-nodes')
  534. for x in result["return"]:
  535. if check_equal_or_none(x.get("node-name"), node_name) and \
  536. check_equal_or_none(x.get("file"), file_name):
  537. return
  538. self.assertTrue(False, "Cannot find %s %s in result:\n%s" % \
  539. (node_name, file_name, result))
  540. def assert_json_filename_equal(self, json_filename, reference):
  541. '''Asserts that the given filename is a json: filename and that its
  542. content is equal to the given reference object'''
  543. self.assertEqual(json_filename[:5], 'json:')
  544. self.assertEqual(self.vm.flatten_qmp_object(json.loads(json_filename[5:])),
  545. self.vm.flatten_qmp_object(reference))
  546. def cancel_and_wait(self, drive='drive0', force=False, resume=False):
  547. '''Cancel a block job and wait for it to finish, returning the event'''
  548. result = self.vm.qmp('block-job-cancel', device=drive, force=force)
  549. self.assert_qmp(result, 'return', {})
  550. if resume:
  551. self.vm.resume_drive(drive)
  552. cancelled = False
  553. result = None
  554. while not cancelled:
  555. for event in self.vm.get_qmp_events(wait=True):
  556. if event['event'] == 'BLOCK_JOB_COMPLETED' or \
  557. event['event'] == 'BLOCK_JOB_CANCELLED':
  558. self.assert_qmp(event, 'data/device', drive)
  559. result = event
  560. cancelled = True
  561. elif event['event'] == 'JOB_STATUS_CHANGE':
  562. self.assert_qmp(event, 'data/id', drive)
  563. self.assert_no_active_block_jobs()
  564. return result
  565. def wait_until_completed(self, drive='drive0', check_offset=True):
  566. '''Wait for a block job to finish, returning the event'''
  567. while True:
  568. for event in self.vm.get_qmp_events(wait=True):
  569. if event['event'] == 'BLOCK_JOB_COMPLETED':
  570. self.assert_qmp(event, 'data/device', drive)
  571. self.assert_qmp_absent(event, 'data/error')
  572. if check_offset:
  573. self.assert_qmp(event, 'data/offset', event['data']['len'])
  574. self.assert_no_active_block_jobs()
  575. return event
  576. elif event['event'] == 'JOB_STATUS_CHANGE':
  577. self.assert_qmp(event, 'data/id', drive)
  578. def wait_ready(self, drive='drive0'):
  579. '''Wait until a block job BLOCK_JOB_READY event'''
  580. f = {'data': {'type': 'mirror', 'device': drive } }
  581. event = self.vm.event_wait(name='BLOCK_JOB_READY', match=f)
  582. def wait_ready_and_cancel(self, drive='drive0'):
  583. self.wait_ready(drive=drive)
  584. event = self.cancel_and_wait(drive=drive)
  585. self.assertEqual(event['event'], 'BLOCK_JOB_COMPLETED')
  586. self.assert_qmp(event, 'data/type', 'mirror')
  587. self.assert_qmp(event, 'data/offset', event['data']['len'])
  588. def complete_and_wait(self, drive='drive0', wait_ready=True):
  589. '''Complete a block job and wait for it to finish'''
  590. if wait_ready:
  591. self.wait_ready(drive=drive)
  592. result = self.vm.qmp('block-job-complete', device=drive)
  593. self.assert_qmp(result, 'return', {})
  594. event = self.wait_until_completed(drive=drive)
  595. self.assert_qmp(event, 'data/type', 'mirror')
  596. def pause_wait(self, job_id='job0'):
  597. with Timeout(1, "Timeout waiting for job to pause"):
  598. while True:
  599. result = self.vm.qmp('query-block-jobs')
  600. found = False
  601. for job in result['return']:
  602. if job['device'] == job_id:
  603. found = True
  604. if job['paused'] == True and job['busy'] == False:
  605. return job
  606. break
  607. assert found
  608. def pause_job(self, job_id='job0', wait=True):
  609. result = self.vm.qmp('block-job-pause', device=job_id)
  610. self.assert_qmp(result, 'return', {})
  611. if wait:
  612. return self.pause_wait(job_id)
  613. return result
  614. def notrun(reason):
  615. '''Skip this test suite'''
  616. # Each test in qemu-iotests has a number ("seq")
  617. seq = os.path.basename(sys.argv[0])
  618. open('%s/%s.notrun' % (output_dir, seq), 'w').write(reason + '\n')
  619. print('%s not run: %s' % (seq, reason))
  620. sys.exit(0)
  621. def case_notrun(reason):
  622. '''Skip this test case'''
  623. # Each test in qemu-iotests has a number ("seq")
  624. seq = os.path.basename(sys.argv[0])
  625. open('%s/%s.casenotrun' % (output_dir, seq), 'a').write(
  626. ' [case not run] ' + reason + '\n')
  627. def verify_image_format(supported_fmts=[], unsupported_fmts=[]):
  628. assert not (supported_fmts and unsupported_fmts)
  629. if 'generic' in supported_fmts and \
  630. os.environ.get('IMGFMT_GENERIC', 'true') == 'true':
  631. # similar to
  632. # _supported_fmt generic
  633. # for bash tests
  634. return
  635. not_sup = supported_fmts and (imgfmt not in supported_fmts)
  636. if not_sup or (imgfmt in unsupported_fmts):
  637. notrun('not suitable for this image format: %s' % imgfmt)
  638. def verify_protocol(supported=[], unsupported=[]):
  639. assert not (supported and unsupported)
  640. if 'generic' in supported:
  641. return
  642. not_sup = supported and (imgproto not in supported)
  643. if not_sup or (imgproto in unsupported):
  644. notrun('not suitable for this protocol: %s' % imgproto)
  645. def verify_platform(supported_oses=['linux']):
  646. if True not in [sys.platform.startswith(x) for x in supported_oses]:
  647. notrun('not suitable for this OS: %s' % sys.platform)
  648. def verify_cache_mode(supported_cache_modes=[]):
  649. if supported_cache_modes and (cachemode not in supported_cache_modes):
  650. notrun('not suitable for this cache mode: %s' % cachemode)
  651. def supports_quorum():
  652. return 'quorum' in qemu_img_pipe('--help')
  653. def verify_quorum():
  654. '''Skip test suite if quorum support is not available'''
  655. if not supports_quorum():
  656. notrun('quorum support missing')
  657. def qemu_pipe(*args):
  658. '''Run qemu with an option to print something and exit (e.g. a help option),
  659. and return its output'''
  660. args = [qemu_prog] + qemu_opts + list(args)
  661. subp = subprocess.Popen(args, stdout=subprocess.PIPE,
  662. stderr=subprocess.STDOUT,
  663. universal_newlines=True)
  664. exitcode = subp.wait()
  665. if exitcode < 0:
  666. sys.stderr.write('qemu received signal %i: %s\n' % (-exitcode,
  667. ' '.join(args)))
  668. return subp.communicate()[0]
  669. def supported_formats(read_only=False):
  670. '''Set 'read_only' to True to check ro-whitelist
  671. Otherwise, rw-whitelist is checked'''
  672. format_message = qemu_pipe("-drive", "format=help")
  673. line = 1 if read_only else 0
  674. return format_message.splitlines()[line].split(":")[1].split()
  675. def skip_if_unsupported(required_formats=[], read_only=False):
  676. '''Skip Test Decorator
  677. Runs the test if all the required formats are whitelisted'''
  678. def skip_test_decorator(func):
  679. def func_wrapper(*args, **kwargs):
  680. usf_list = list(set(required_formats) -
  681. set(supported_formats(read_only)))
  682. if usf_list:
  683. case_notrun('{}: formats {} are not whitelisted'.format(
  684. args[0], usf_list))
  685. else:
  686. return func(*args, **kwargs)
  687. return func_wrapper
  688. return skip_test_decorator
  689. def main(supported_fmts=[], supported_oses=['linux'], supported_cache_modes=[],
  690. unsupported_fmts=[]):
  691. '''Run tests'''
  692. global debug
  693. # We are using TEST_DIR and QEMU_DEFAULT_MACHINE as proxies to
  694. # indicate that we're not being run via "check". There may be
  695. # other things set up by "check" that individual test cases rely
  696. # on.
  697. if test_dir is None or qemu_default_machine is None:
  698. sys.stderr.write('Please run this test via the "check" script\n')
  699. sys.exit(os.EX_USAGE)
  700. debug = '-d' in sys.argv
  701. verbosity = 1
  702. verify_image_format(supported_fmts, unsupported_fmts)
  703. verify_platform(supported_oses)
  704. verify_cache_mode(supported_cache_modes)
  705. if debug:
  706. output = sys.stdout
  707. verbosity = 2
  708. sys.argv.remove('-d')
  709. else:
  710. # We need to filter out the time taken from the output so that
  711. # qemu-iotest can reliably diff the results against master output.
  712. if sys.version_info.major >= 3:
  713. output = io.StringIO()
  714. else:
  715. # io.StringIO is for unicode strings, which is not what
  716. # 2.x's test runner emits.
  717. output = io.BytesIO()
  718. logging.basicConfig(level=(logging.DEBUG if debug else logging.WARN))
  719. class MyTestRunner(unittest.TextTestRunner):
  720. def __init__(self, stream=output, descriptions=True, verbosity=verbosity):
  721. unittest.TextTestRunner.__init__(self, stream, descriptions, verbosity)
  722. # unittest.main() will use sys.exit() so expect a SystemExit exception
  723. try:
  724. unittest.main(testRunner=MyTestRunner)
  725. finally:
  726. if not debug:
  727. sys.stderr.write(re.sub(r'Ran (\d+) tests? in [\d.]+s', r'Ran \1 tests', output.getvalue()))