iotests.py 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680
  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. import argparse
  19. import atexit
  20. import bz2
  21. from collections import OrderedDict
  22. import faulthandler
  23. import json
  24. import logging
  25. import os
  26. import re
  27. import shutil
  28. import signal
  29. import struct
  30. import subprocess
  31. import sys
  32. import time
  33. from typing import (Any, Callable, Dict, Iterable, Iterator,
  34. List, Optional, Sequence, TextIO, Tuple, Type, TypeVar)
  35. import unittest
  36. from contextlib import contextmanager
  37. from qemu.machine import qtest
  38. from qemu.qmp.legacy import QMPMessage, QEMUMonitorProtocol
  39. from qemu.utils import VerboseProcessError
  40. # Use this logger for logging messages directly from the iotests module
  41. logger = logging.getLogger('qemu.iotests')
  42. logger.addHandler(logging.NullHandler())
  43. # Use this logger for messages that ought to be used for diff output.
  44. test_logger = logging.getLogger('qemu.iotests.diff_io')
  45. faulthandler.enable()
  46. # This will not work if arguments contain spaces but is necessary if we
  47. # want to support the override options that ./check supports.
  48. qemu_img_args = [os.environ.get('QEMU_IMG_PROG', 'qemu-img')]
  49. if os.environ.get('QEMU_IMG_OPTIONS'):
  50. qemu_img_args += os.environ['QEMU_IMG_OPTIONS'].strip().split(' ')
  51. qemu_io_args = [os.environ.get('QEMU_IO_PROG', 'qemu-io')]
  52. if os.environ.get('QEMU_IO_OPTIONS'):
  53. qemu_io_args += os.environ['QEMU_IO_OPTIONS'].strip().split(' ')
  54. qemu_io_args_no_fmt = [os.environ.get('QEMU_IO_PROG', 'qemu-io')]
  55. if os.environ.get('QEMU_IO_OPTIONS_NO_FMT'):
  56. qemu_io_args_no_fmt += \
  57. os.environ['QEMU_IO_OPTIONS_NO_FMT'].strip().split(' ')
  58. qemu_nbd_prog = os.environ.get('QEMU_NBD_PROG', 'qemu-nbd')
  59. qemu_nbd_args = [qemu_nbd_prog]
  60. if os.environ.get('QEMU_NBD_OPTIONS'):
  61. qemu_nbd_args += os.environ['QEMU_NBD_OPTIONS'].strip().split(' ')
  62. qemu_prog = os.environ.get('QEMU_PROG', 'qemu')
  63. qemu_opts = os.environ.get('QEMU_OPTIONS', '').strip().split(' ')
  64. qsd_prog = os.environ.get('QSD_PROG', 'qemu-storage-daemon')
  65. gdb_qemu_env = os.environ.get('GDB_OPTIONS')
  66. qemu_gdb = []
  67. if gdb_qemu_env:
  68. qemu_gdb = ['gdbserver'] + gdb_qemu_env.strip().split(' ')
  69. qemu_print = os.environ.get('PRINT_QEMU', False)
  70. imgfmt = os.environ.get('IMGFMT', 'raw')
  71. imgproto = os.environ.get('IMGPROTO', 'file')
  72. try:
  73. test_dir = os.environ['TEST_DIR']
  74. sock_dir = os.environ['SOCK_DIR']
  75. cachemode = os.environ['CACHEMODE']
  76. aiomode = os.environ['AIOMODE']
  77. qemu_default_machine = os.environ['QEMU_DEFAULT_MACHINE']
  78. except KeyError:
  79. # We are using these variables as proxies to indicate that we're
  80. # not being run via "check". There may be other things set up by
  81. # "check" that individual test cases rely on.
  82. sys.stderr.write('Please run this test via the "check" script\n')
  83. sys.exit(os.EX_USAGE)
  84. qemu_valgrind = []
  85. if os.environ.get('VALGRIND_QEMU') == "y" and \
  86. os.environ.get('NO_VALGRIND') != "y":
  87. valgrind_logfile = "--log-file=" + test_dir
  88. # %p allows to put the valgrind process PID, since
  89. # we don't know it a priori (subprocess.Popen is
  90. # not yet invoked)
  91. valgrind_logfile += "/%p.valgrind"
  92. qemu_valgrind = ['valgrind', valgrind_logfile, '--error-exitcode=99']
  93. luks_default_secret_object = 'secret,id=keysec0,data=' + \
  94. os.environ.get('IMGKEYSECRET', '')
  95. luks_default_key_secret_opt = 'key-secret=keysec0'
  96. sample_img_dir = os.environ['SAMPLE_IMG_DIR']
  97. @contextmanager
  98. def change_log_level(
  99. logger_name: str, level: int = logging.CRITICAL) -> Iterator[None]:
  100. """
  101. Utility function for temporarily changing the log level of a logger.
  102. This can be used to silence errors that are expected or uninteresting.
  103. """
  104. _logger = logging.getLogger(logger_name)
  105. current_level = _logger.level
  106. _logger.setLevel(level)
  107. try:
  108. yield
  109. finally:
  110. _logger.setLevel(current_level)
  111. def unarchive_sample_image(sample, fname):
  112. sample_fname = os.path.join(sample_img_dir, sample + '.bz2')
  113. with bz2.open(sample_fname) as f_in, open(fname, 'wb') as f_out:
  114. shutil.copyfileobj(f_in, f_out)
  115. def qemu_tool_popen(args: Sequence[str],
  116. connect_stderr: bool = True) -> 'subprocess.Popen[str]':
  117. stderr = subprocess.STDOUT if connect_stderr else None
  118. # pylint: disable=consider-using-with
  119. return subprocess.Popen(args,
  120. stdout=subprocess.PIPE,
  121. stderr=stderr,
  122. universal_newlines=True)
  123. def qemu_tool_pipe_and_status(tool: str, args: Sequence[str],
  124. connect_stderr: bool = True,
  125. drop_successful_output: bool = False) \
  126. -> Tuple[str, int]:
  127. """
  128. Run a tool and return both its output and its exit code
  129. """
  130. with qemu_tool_popen(args, connect_stderr) as subp:
  131. output = subp.communicate()[0]
  132. if subp.returncode < 0:
  133. cmd = ' '.join(args)
  134. sys.stderr.write(f'{tool} received signal \
  135. {-subp.returncode}: {cmd}\n')
  136. if drop_successful_output and subp.returncode == 0:
  137. output = ''
  138. return (output, subp.returncode)
  139. def qemu_img_create_prepare_args(args: List[str]) -> List[str]:
  140. if not args or args[0] != 'create':
  141. return list(args)
  142. args = args[1:]
  143. p = argparse.ArgumentParser(allow_abbrev=False)
  144. # -o option may be specified several times
  145. p.add_argument('-o', action='append', default=[])
  146. p.add_argument('-f')
  147. parsed, remaining = p.parse_known_args(args)
  148. opts_list = parsed.o
  149. result = ['create']
  150. if parsed.f is not None:
  151. result += ['-f', parsed.f]
  152. # IMGOPTS most probably contain options specific for the selected format,
  153. # like extended_l2 or compression_type for qcow2. Test may want to create
  154. # additional images in other formats that doesn't support these options.
  155. # So, use IMGOPTS only for images created in imgfmt format.
  156. imgopts = os.environ.get('IMGOPTS')
  157. if imgopts and parsed.f == imgfmt:
  158. opts_list.insert(0, imgopts)
  159. # default luks support
  160. if parsed.f == 'luks' and \
  161. all('key-secret' not in opts for opts in opts_list):
  162. result += ['--object', luks_default_secret_object]
  163. opts_list.append(luks_default_key_secret_opt)
  164. for opts in opts_list:
  165. result += ['-o', opts]
  166. result += remaining
  167. return result
  168. def qemu_img(*args: str, check: bool = True, combine_stdio: bool = True
  169. ) -> 'subprocess.CompletedProcess[str]':
  170. """
  171. Run qemu_img and return the status code and console output.
  172. This function always prepends QEMU_IMG_OPTIONS and may further alter
  173. the args for 'create' commands.
  174. :param args: command-line arguments to qemu-img.
  175. :param check: Enforce a return code of zero.
  176. :param combine_stdio: set to False to keep stdout/stderr separated.
  177. :raise VerboseProcessError:
  178. When the return code is negative, or on any non-zero exit code
  179. when 'check=True' was provided (the default). This exception has
  180. 'stdout', 'stderr', and 'returncode' properties that may be
  181. inspected to show greater detail. If this exception is not
  182. handled, the command-line, return code, and all console output
  183. will be included at the bottom of the stack trace.
  184. :return:
  185. a CompletedProcess. This object has args, returncode, and stdout
  186. properties. If streams are not combined, it will also have a
  187. stderr property.
  188. """
  189. full_args = qemu_img_args + qemu_img_create_prepare_args(list(args))
  190. subp = subprocess.run(
  191. full_args,
  192. stdout=subprocess.PIPE,
  193. stderr=subprocess.STDOUT if combine_stdio else subprocess.PIPE,
  194. universal_newlines=True,
  195. check=False
  196. )
  197. if check and subp.returncode or (subp.returncode < 0):
  198. raise VerboseProcessError(
  199. subp.returncode, full_args,
  200. output=subp.stdout,
  201. stderr=subp.stderr,
  202. )
  203. return subp
  204. def ordered_qmp(qmsg, conv_keys=True):
  205. # Dictionaries are not ordered prior to 3.6, therefore:
  206. if isinstance(qmsg, list):
  207. return [ordered_qmp(atom) for atom in qmsg]
  208. if isinstance(qmsg, dict):
  209. od = OrderedDict()
  210. for k, v in sorted(qmsg.items()):
  211. if conv_keys:
  212. k = k.replace('_', '-')
  213. od[k] = ordered_qmp(v, conv_keys=False)
  214. return od
  215. return qmsg
  216. def qemu_img_create(*args: str) -> 'subprocess.CompletedProcess[str]':
  217. return qemu_img('create', *args)
  218. def qemu_img_json(*args: str) -> Any:
  219. """
  220. Run qemu-img and return its output as deserialized JSON.
  221. :raise CalledProcessError:
  222. When qemu-img crashes, or returns a non-zero exit code without
  223. producing a valid JSON document to stdout.
  224. :raise JSONDecoderError:
  225. When qemu-img returns 0, but failed to produce a valid JSON document.
  226. :return: A deserialized JSON object; probably a dict[str, Any].
  227. """
  228. try:
  229. res = qemu_img(*args, combine_stdio=False)
  230. except subprocess.CalledProcessError as exc:
  231. # Terminated due to signal. Don't bother.
  232. if exc.returncode < 0:
  233. raise
  234. # Commands like 'check' can return failure (exit codes 2 and 3)
  235. # to indicate command completion, but with errors found. For
  236. # multi-command flexibility, ignore the exact error codes and
  237. # *try* to load JSON.
  238. try:
  239. return json.loads(exc.stdout)
  240. except json.JSONDecodeError:
  241. # Nope. This thing is toast. Raise the /process/ error.
  242. pass
  243. raise
  244. return json.loads(res.stdout)
  245. def qemu_img_measure(*args: str) -> Any:
  246. return qemu_img_json("measure", "--output", "json", *args)
  247. def qemu_img_check(*args: str) -> Any:
  248. return qemu_img_json("check", "--output", "json", *args)
  249. def qemu_img_info(*args: str) -> Any:
  250. return qemu_img_json('info', "--output", "json", *args)
  251. def qemu_img_map(*args: str) -> Any:
  252. return qemu_img_json('map', "--output", "json", *args)
  253. def qemu_img_log(*args: str, check: bool = True
  254. ) -> 'subprocess.CompletedProcess[str]':
  255. result = qemu_img(*args, check=check)
  256. log(result.stdout, filters=[filter_testfiles])
  257. return result
  258. def img_info_log(filename: str, filter_path: Optional[str] = None,
  259. use_image_opts: bool = False, extra_args: Sequence[str] = (),
  260. check: bool = True,
  261. ) -> None:
  262. args = ['info']
  263. if use_image_opts:
  264. args.append('--image-opts')
  265. else:
  266. args += ['-f', imgfmt]
  267. args += extra_args
  268. args.append(filename)
  269. output = qemu_img(*args, check=check).stdout
  270. if not filter_path:
  271. filter_path = filename
  272. log(filter_img_info(output, filter_path))
  273. def qemu_io_wrap_args(args: Sequence[str]) -> List[str]:
  274. if '-f' in args or '--image-opts' in args:
  275. return qemu_io_args_no_fmt + list(args)
  276. else:
  277. return qemu_io_args + list(args)
  278. def qemu_io_popen(*args):
  279. return qemu_tool_popen(qemu_io_wrap_args(args))
  280. def qemu_io(*args):
  281. '''Run qemu-io and return the stdout data'''
  282. return qemu_tool_pipe_and_status('qemu-io', qemu_io_wrap_args(args))[0]
  283. def qemu_io_pipe_and_status(*args):
  284. return qemu_tool_pipe_and_status('qemu-io', qemu_io_wrap_args(args))
  285. def qemu_io_log(*args):
  286. result = qemu_io(*args)
  287. log(result, filters=[filter_testfiles, filter_qemu_io])
  288. return result
  289. def qemu_io_silent(*args):
  290. '''Run qemu-io and return the exit code, suppressing stdout'''
  291. args = qemu_io_wrap_args(args)
  292. result = subprocess.run(args, stdout=subprocess.DEVNULL, check=False)
  293. if result.returncode < 0:
  294. sys.stderr.write('qemu-io received signal %i: %s\n' %
  295. (-result.returncode, ' '.join(args)))
  296. return result.returncode
  297. def qemu_io_silent_check(*args):
  298. '''Run qemu-io and return the true if subprocess returned 0'''
  299. args = qemu_io_wrap_args(args)
  300. result = subprocess.run(args, stdout=subprocess.DEVNULL,
  301. stderr=subprocess.STDOUT, check=False)
  302. return result.returncode == 0
  303. class QemuIoInteractive:
  304. def __init__(self, *args):
  305. self.args = qemu_io_wrap_args(args)
  306. # We need to keep the Popen objext around, and not
  307. # close it immediately. Therefore, disable the pylint check:
  308. # pylint: disable=consider-using-with
  309. self._p = subprocess.Popen(self.args, stdin=subprocess.PIPE,
  310. stdout=subprocess.PIPE,
  311. stderr=subprocess.STDOUT,
  312. universal_newlines=True)
  313. out = self._p.stdout.read(9)
  314. if out != 'qemu-io> ':
  315. # Most probably qemu-io just failed to start.
  316. # Let's collect the whole output and exit.
  317. out += self._p.stdout.read()
  318. self._p.wait(timeout=1)
  319. raise ValueError(out)
  320. def close(self):
  321. self._p.communicate('q\n')
  322. def _read_output(self):
  323. pattern = 'qemu-io> '
  324. n = len(pattern)
  325. pos = 0
  326. s = []
  327. while pos != n:
  328. c = self._p.stdout.read(1)
  329. # check unexpected EOF
  330. assert c != ''
  331. s.append(c)
  332. if c == pattern[pos]:
  333. pos += 1
  334. else:
  335. pos = 0
  336. return ''.join(s[:-n])
  337. def cmd(self, cmd):
  338. # quit command is in close(), '\n' is added automatically
  339. assert '\n' not in cmd
  340. cmd = cmd.strip()
  341. assert cmd not in ('q', 'quit')
  342. self._p.stdin.write(cmd + '\n')
  343. self._p.stdin.flush()
  344. return self._read_output()
  345. class QemuStorageDaemon:
  346. _qmp: Optional[QEMUMonitorProtocol] = None
  347. _qmpsock: Optional[str] = None
  348. # Python < 3.8 would complain if this type were not a string literal
  349. # (importing `annotations` from `__future__` would work; but not on <= 3.6)
  350. _p: 'Optional[subprocess.Popen[bytes]]' = None
  351. def __init__(self, *args: str, instance_id: str = 'a', qmp: bool = False):
  352. assert '--pidfile' not in args
  353. self.pidfile = os.path.join(test_dir, f'qsd-{instance_id}-pid')
  354. all_args = [qsd_prog] + list(args) + ['--pidfile', self.pidfile]
  355. if qmp:
  356. self._qmpsock = os.path.join(sock_dir, f'qsd-{instance_id}.sock')
  357. all_args += ['--chardev',
  358. f'socket,id=qmp-sock,path={self._qmpsock}',
  359. '--monitor', 'qmp-sock']
  360. self._qmp = QEMUMonitorProtocol(self._qmpsock, server=True)
  361. # Cannot use with here, we want the subprocess to stay around
  362. # pylint: disable=consider-using-with
  363. self._p = subprocess.Popen(all_args)
  364. if self._qmp is not None:
  365. self._qmp.accept()
  366. while not os.path.exists(self.pidfile):
  367. if self._p.poll() is not None:
  368. cmd = ' '.join(all_args)
  369. raise RuntimeError(
  370. 'qemu-storage-daemon terminated with exit code ' +
  371. f'{self._p.returncode}: {cmd}')
  372. time.sleep(0.01)
  373. with open(self.pidfile, encoding='utf-8') as f:
  374. self._pid = int(f.read().strip())
  375. assert self._pid == self._p.pid
  376. def qmp(self, cmd: str, args: Optional[Dict[str, object]] = None) \
  377. -> QMPMessage:
  378. assert self._qmp is not None
  379. return self._qmp.cmd(cmd, args)
  380. def stop(self, kill_signal=15):
  381. self._p.send_signal(kill_signal)
  382. self._p.wait()
  383. self._p = None
  384. if self._qmp:
  385. self._qmp.close()
  386. if self._qmpsock is not None:
  387. try:
  388. os.remove(self._qmpsock)
  389. except OSError:
  390. pass
  391. try:
  392. os.remove(self.pidfile)
  393. except OSError:
  394. pass
  395. def __del__(self):
  396. if self._p is not None:
  397. self.stop(kill_signal=9)
  398. def qemu_nbd(*args):
  399. '''Run qemu-nbd in daemon mode and return the parent's exit code'''
  400. return subprocess.call(qemu_nbd_args + ['--fork'] + list(args))
  401. def qemu_nbd_early_pipe(*args: str) -> Tuple[int, str]:
  402. '''Run qemu-nbd in daemon mode and return both the parent's exit code
  403. and its output in case of an error'''
  404. full_args = qemu_nbd_args + ['--fork'] + list(args)
  405. output, returncode = qemu_tool_pipe_and_status('qemu-nbd', full_args,
  406. connect_stderr=False)
  407. return returncode, output if returncode else ''
  408. def qemu_nbd_list_log(*args: str) -> str:
  409. '''Run qemu-nbd to list remote exports'''
  410. full_args = [qemu_nbd_prog, '-L'] + list(args)
  411. output, _ = qemu_tool_pipe_and_status('qemu-nbd', full_args)
  412. log(output, filters=[filter_testfiles, filter_nbd_exports])
  413. return output
  414. @contextmanager
  415. def qemu_nbd_popen(*args):
  416. '''Context manager running qemu-nbd within the context'''
  417. pid_file = file_path("qemu_nbd_popen-nbd-pid-file")
  418. assert not os.path.exists(pid_file)
  419. cmd = list(qemu_nbd_args)
  420. cmd.extend(('--persistent', '--pid-file', pid_file))
  421. cmd.extend(args)
  422. log('Start NBD server')
  423. with subprocess.Popen(cmd) as p:
  424. try:
  425. while not os.path.exists(pid_file):
  426. if p.poll() is not None:
  427. raise RuntimeError(
  428. "qemu-nbd terminated with exit code {}: {}"
  429. .format(p.returncode, ' '.join(cmd)))
  430. time.sleep(0.01)
  431. yield
  432. finally:
  433. if os.path.exists(pid_file):
  434. os.remove(pid_file)
  435. log('Kill NBD server')
  436. p.kill()
  437. p.wait()
  438. def compare_images(img1: str, img2: str,
  439. fmt1: str = imgfmt, fmt2: str = imgfmt) -> bool:
  440. """
  441. Compare two images with QEMU_IMG; return True if they are identical.
  442. :raise CalledProcessError:
  443. when qemu-img crashes or returns a status code of anything other
  444. than 0 (identical) or 1 (different).
  445. """
  446. try:
  447. qemu_img('compare', '-f', fmt1, '-F', fmt2, img1, img2)
  448. return True
  449. except subprocess.CalledProcessError as exc:
  450. if exc.returncode == 1:
  451. return False
  452. raise
  453. def create_image(name, size):
  454. '''Create a fully-allocated raw image with sector markers'''
  455. with open(name, 'wb') as file:
  456. i = 0
  457. while i < size:
  458. sector = struct.pack('>l504xl', i // 512, i // 512)
  459. file.write(sector)
  460. i = i + 512
  461. def image_size(img: str) -> int:
  462. """Return image's virtual size"""
  463. value = qemu_img_info('-f', imgfmt, img)['virtual-size']
  464. if not isinstance(value, int):
  465. type_name = type(value).__name__
  466. raise TypeError("Expected 'int' for 'virtual-size', "
  467. f"got '{value}' of type '{type_name}'")
  468. return value
  469. def is_str(val):
  470. return isinstance(val, str)
  471. test_dir_re = re.compile(r"%s" % test_dir)
  472. def filter_test_dir(msg):
  473. return test_dir_re.sub("TEST_DIR", msg)
  474. win32_re = re.compile(r"\r")
  475. def filter_win32(msg):
  476. return win32_re.sub("", msg)
  477. qemu_io_re = re.compile(r"[0-9]* ops; [0-9\/:. sec]* "
  478. r"\([0-9\/.inf]* [EPTGMKiBbytes]*\/sec "
  479. r"and [0-9\/.inf]* ops\/sec\)")
  480. def filter_qemu_io(msg):
  481. msg = filter_win32(msg)
  482. return qemu_io_re.sub("X ops; XX:XX:XX.X "
  483. "(XXX YYY/sec and XXX ops/sec)", msg)
  484. chown_re = re.compile(r"chown [0-9]+:[0-9]+")
  485. def filter_chown(msg):
  486. return chown_re.sub("chown UID:GID", msg)
  487. def filter_qmp_event(event):
  488. '''Filter a QMP event dict'''
  489. event = dict(event)
  490. if 'timestamp' in event:
  491. event['timestamp']['seconds'] = 'SECS'
  492. event['timestamp']['microseconds'] = 'USECS'
  493. return event
  494. def filter_qmp(qmsg, filter_fn):
  495. '''Given a string filter, filter a QMP object's values.
  496. filter_fn takes a (key, value) pair.'''
  497. # Iterate through either lists or dicts;
  498. if isinstance(qmsg, list):
  499. items = enumerate(qmsg)
  500. elif isinstance(qmsg, dict):
  501. items = qmsg.items()
  502. else:
  503. return filter_fn(None, qmsg)
  504. for k, v in items:
  505. if isinstance(v, (dict, list)):
  506. qmsg[k] = filter_qmp(v, filter_fn)
  507. else:
  508. qmsg[k] = filter_fn(k, v)
  509. return qmsg
  510. def filter_testfiles(msg):
  511. pref1 = os.path.join(test_dir, "%s-" % (os.getpid()))
  512. pref2 = os.path.join(sock_dir, "%s-" % (os.getpid()))
  513. return msg.replace(pref1, 'TEST_DIR/PID-').replace(pref2, 'SOCK_DIR/PID-')
  514. def filter_qmp_testfiles(qmsg):
  515. def _filter(_key, value):
  516. if is_str(value):
  517. return filter_testfiles(value)
  518. return value
  519. return filter_qmp(qmsg, _filter)
  520. def filter_virtio_scsi(output: str) -> str:
  521. return re.sub(r'(virtio-scsi)-(ccw|pci)', r'\1', output)
  522. def filter_qmp_virtio_scsi(qmsg):
  523. def _filter(_key, value):
  524. if is_str(value):
  525. return filter_virtio_scsi(value)
  526. return value
  527. return filter_qmp(qmsg, _filter)
  528. def filter_generated_node_ids(msg):
  529. return re.sub("#block[0-9]+", "NODE_NAME", msg)
  530. def filter_img_info(output, filename):
  531. lines = []
  532. for line in output.split('\n'):
  533. if 'disk size' in line or 'actual-size' in line:
  534. continue
  535. line = line.replace(filename, 'TEST_IMG')
  536. line = filter_testfiles(line)
  537. line = line.replace(imgfmt, 'IMGFMT')
  538. line = re.sub('iters: [0-9]+', 'iters: XXX', line)
  539. line = re.sub('uuid: [-a-f0-9]+',
  540. 'uuid: XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
  541. line)
  542. line = re.sub('cid: [0-9]+', 'cid: XXXXXXXXXX', line)
  543. line = re.sub('(compression type: )(zlib|zstd)', r'\1COMPRESSION_TYPE',
  544. line)
  545. lines.append(line)
  546. return '\n'.join(lines)
  547. def filter_imgfmt(msg):
  548. return msg.replace(imgfmt, 'IMGFMT')
  549. def filter_qmp_imgfmt(qmsg):
  550. def _filter(_key, value):
  551. if is_str(value):
  552. return filter_imgfmt(value)
  553. return value
  554. return filter_qmp(qmsg, _filter)
  555. def filter_nbd_exports(output: str) -> str:
  556. return re.sub(r'((min|opt|max) block): [0-9]+', r'\1: XXX', output)
  557. Msg = TypeVar('Msg', Dict[str, Any], List[Any], str)
  558. def log(msg: Msg,
  559. filters: Iterable[Callable[[Msg], Msg]] = (),
  560. indent: Optional[int] = None) -> None:
  561. """
  562. Logs either a string message or a JSON serializable message (like QMP).
  563. If indent is provided, JSON serializable messages are pretty-printed.
  564. """
  565. for flt in filters:
  566. msg = flt(msg)
  567. if isinstance(msg, (dict, list)):
  568. # Don't sort if it's already sorted
  569. do_sort = not isinstance(msg, OrderedDict)
  570. test_logger.info(json.dumps(msg, sort_keys=do_sort, indent=indent))
  571. else:
  572. test_logger.info(msg)
  573. class Timeout:
  574. def __init__(self, seconds, errmsg="Timeout"):
  575. self.seconds = seconds
  576. self.errmsg = errmsg
  577. def __enter__(self):
  578. if qemu_gdb or qemu_valgrind:
  579. return self
  580. signal.signal(signal.SIGALRM, self.timeout)
  581. signal.setitimer(signal.ITIMER_REAL, self.seconds)
  582. return self
  583. def __exit__(self, exc_type, value, traceback):
  584. if qemu_gdb or qemu_valgrind:
  585. return False
  586. signal.setitimer(signal.ITIMER_REAL, 0)
  587. return False
  588. def timeout(self, signum, frame):
  589. raise Exception(self.errmsg)
  590. def file_pattern(name):
  591. return "{0}-{1}".format(os.getpid(), name)
  592. class FilePath:
  593. """
  594. Context manager generating multiple file names. The generated files are
  595. removed when exiting the context.
  596. Example usage:
  597. with FilePath('a.img', 'b.img') as (img_a, img_b):
  598. # Use img_a and img_b here...
  599. # a.img and b.img are automatically removed here.
  600. By default images are created in iotests.test_dir. To create sockets use
  601. iotests.sock_dir:
  602. with FilePath('a.sock', base_dir=iotests.sock_dir) as sock:
  603. For convenience, calling with one argument yields a single file instead of
  604. a tuple with one item.
  605. """
  606. def __init__(self, *names, base_dir=test_dir):
  607. self.paths = [os.path.join(base_dir, file_pattern(name))
  608. for name in names]
  609. def __enter__(self):
  610. if len(self.paths) == 1:
  611. return self.paths[0]
  612. else:
  613. return self.paths
  614. def __exit__(self, exc_type, exc_val, exc_tb):
  615. for path in self.paths:
  616. try:
  617. os.remove(path)
  618. except OSError:
  619. pass
  620. return False
  621. def try_remove(img):
  622. try:
  623. os.remove(img)
  624. except OSError:
  625. pass
  626. def file_path_remover():
  627. for path in reversed(file_path_remover.paths):
  628. try_remove(path)
  629. def file_path(*names, base_dir=test_dir):
  630. ''' Another way to get auto-generated filename that cleans itself up.
  631. Use is as simple as:
  632. img_a, img_b = file_path('a.img', 'b.img')
  633. sock = file_path('socket')
  634. '''
  635. if not hasattr(file_path_remover, 'paths'):
  636. file_path_remover.paths = []
  637. atexit.register(file_path_remover)
  638. paths = []
  639. for name in names:
  640. filename = file_pattern(name)
  641. path = os.path.join(base_dir, filename)
  642. file_path_remover.paths.append(path)
  643. paths.append(path)
  644. return paths[0] if len(paths) == 1 else paths
  645. def remote_filename(path):
  646. if imgproto == 'file':
  647. return path
  648. elif imgproto == 'ssh':
  649. return "ssh://%s@127.0.0.1:22%s" % (os.environ.get('USER'), path)
  650. else:
  651. raise Exception("Protocol %s not supported" % (imgproto))
  652. class VM(qtest.QEMUQtestMachine):
  653. '''A QEMU VM'''
  654. def __init__(self, path_suffix=''):
  655. name = "qemu%s-%d" % (path_suffix, os.getpid())
  656. timer = 15.0 if not (qemu_gdb or qemu_valgrind) else None
  657. if qemu_gdb and qemu_valgrind:
  658. sys.stderr.write('gdb and valgrind are mutually exclusive\n')
  659. sys.exit(1)
  660. wrapper = qemu_gdb if qemu_gdb else qemu_valgrind
  661. super().__init__(qemu_prog, qemu_opts, wrapper=wrapper,
  662. name=name,
  663. base_temp_dir=test_dir,
  664. sock_dir=sock_dir, qmp_timer=timer)
  665. self._num_drives = 0
  666. def _post_shutdown(self) -> None:
  667. super()._post_shutdown()
  668. if not qemu_valgrind or not self._popen:
  669. return
  670. valgrind_filename = f"{test_dir}/{self._popen.pid}.valgrind"
  671. if self.exitcode() == 99:
  672. with open(valgrind_filename, encoding='utf-8') as f:
  673. print(f.read())
  674. else:
  675. os.remove(valgrind_filename)
  676. def _pre_launch(self) -> None:
  677. super()._pre_launch()
  678. if qemu_print:
  679. # set QEMU binary output to stdout
  680. self._close_qemu_log_file()
  681. def add_object(self, opts):
  682. self._args.append('-object')
  683. self._args.append(opts)
  684. return self
  685. def add_device(self, opts):
  686. self._args.append('-device')
  687. self._args.append(opts)
  688. return self
  689. def add_drive_raw(self, opts):
  690. self._args.append('-drive')
  691. self._args.append(opts)
  692. return self
  693. def add_drive(self, path, opts='', interface='virtio', img_format=imgfmt):
  694. '''Add a virtio-blk drive to the VM'''
  695. options = ['if=%s' % interface,
  696. 'id=drive%d' % self._num_drives]
  697. if path is not None:
  698. options.append('file=%s' % path)
  699. options.append('format=%s' % img_format)
  700. options.append('cache=%s' % cachemode)
  701. options.append('aio=%s' % aiomode)
  702. if opts:
  703. options.append(opts)
  704. if img_format == 'luks' and 'key-secret' not in opts:
  705. # default luks support
  706. if luks_default_secret_object not in self._args:
  707. self.add_object(luks_default_secret_object)
  708. options.append(luks_default_key_secret_opt)
  709. self._args.append('-drive')
  710. self._args.append(','.join(options))
  711. self._num_drives += 1
  712. return self
  713. def add_blockdev(self, opts):
  714. self._args.append('-blockdev')
  715. if isinstance(opts, str):
  716. self._args.append(opts)
  717. else:
  718. self._args.append(','.join(opts))
  719. return self
  720. def add_incoming(self, addr):
  721. self._args.append('-incoming')
  722. self._args.append(addr)
  723. return self
  724. def hmp(self, command_line: str, use_log: bool = False) -> QMPMessage:
  725. cmd = 'human-monitor-command'
  726. kwargs: Dict[str, Any] = {'command-line': command_line}
  727. if use_log:
  728. return self.qmp_log(cmd, **kwargs)
  729. else:
  730. return self.qmp(cmd, **kwargs)
  731. def pause_drive(self, drive: str, event: Optional[str] = None) -> None:
  732. """Pause drive r/w operations"""
  733. if not event:
  734. self.pause_drive(drive, "read_aio")
  735. self.pause_drive(drive, "write_aio")
  736. return
  737. self.hmp(f'qemu-io {drive} "break {event} bp_{drive}"')
  738. def resume_drive(self, drive: str) -> None:
  739. """Resume drive r/w operations"""
  740. self.hmp(f'qemu-io {drive} "remove_break bp_{drive}"')
  741. def hmp_qemu_io(self, drive: str, cmd: str,
  742. use_log: bool = False, qdev: bool = False) -> QMPMessage:
  743. """Write to a given drive using an HMP command"""
  744. d = '-d ' if qdev else ''
  745. return self.hmp(f'qemu-io {d}{drive} "{cmd}"', use_log=use_log)
  746. def flatten_qmp_object(self, obj, output=None, basestr=''):
  747. if output is None:
  748. output = {}
  749. if isinstance(obj, list):
  750. for i, item in enumerate(obj):
  751. self.flatten_qmp_object(item, output, basestr + str(i) + '.')
  752. elif isinstance(obj, dict):
  753. for key in obj:
  754. self.flatten_qmp_object(obj[key], output, basestr + key + '.')
  755. else:
  756. output[basestr[:-1]] = obj # Strip trailing '.'
  757. return output
  758. def qmp_to_opts(self, obj):
  759. obj = self.flatten_qmp_object(obj)
  760. output_list = []
  761. for key in obj:
  762. output_list += [key + '=' + obj[key]]
  763. return ','.join(output_list)
  764. def get_qmp_events_filtered(self, wait=60.0):
  765. result = []
  766. for ev in self.get_qmp_events(wait=wait):
  767. result.append(filter_qmp_event(ev))
  768. return result
  769. def qmp_log(self, cmd, filters=(), indent=None, **kwargs):
  770. full_cmd = OrderedDict((
  771. ("execute", cmd),
  772. ("arguments", ordered_qmp(kwargs))
  773. ))
  774. log(full_cmd, filters, indent=indent)
  775. result = self.qmp(cmd, **kwargs)
  776. log(result, filters, indent=indent)
  777. return result
  778. # Returns None on success, and an error string on failure
  779. def run_job(self, job: str, auto_finalize: bool = True,
  780. auto_dismiss: bool = False,
  781. pre_finalize: Optional[Callable[[], None]] = None,
  782. cancel: bool = False, wait: float = 60.0,
  783. filters: Iterable[Callable[[Any], Any]] = (),
  784. ) -> Optional[str]:
  785. """
  786. run_job moves a job from creation through to dismissal.
  787. :param job: String. ID of recently-launched job
  788. :param auto_finalize: Bool. True if the job was launched with
  789. auto_finalize. Defaults to True.
  790. :param auto_dismiss: Bool. True if the job was launched with
  791. auto_dismiss=True. Defaults to False.
  792. :param pre_finalize: Callback. A callable that takes no arguments to be
  793. invoked prior to issuing job-finalize, if any.
  794. :param cancel: Bool. When true, cancels the job after the pre_finalize
  795. callback.
  796. :param wait: Float. Timeout value specifying how long to wait for any
  797. event, in seconds. Defaults to 60.0.
  798. """
  799. match_device = {'data': {'device': job}}
  800. match_id = {'data': {'id': job}}
  801. events = [
  802. ('BLOCK_JOB_COMPLETED', match_device),
  803. ('BLOCK_JOB_CANCELLED', match_device),
  804. ('BLOCK_JOB_ERROR', match_device),
  805. ('BLOCK_JOB_READY', match_device),
  806. ('BLOCK_JOB_PENDING', match_id),
  807. ('JOB_STATUS_CHANGE', match_id)
  808. ]
  809. error = None
  810. while True:
  811. ev = filter_qmp_event(self.events_wait(events, timeout=wait))
  812. if ev['event'] != 'JOB_STATUS_CHANGE':
  813. log(ev, filters=filters)
  814. continue
  815. status = ev['data']['status']
  816. if status == 'aborting':
  817. result = self.qmp('query-jobs')
  818. for j in result['return']:
  819. if j['id'] == job:
  820. error = j['error']
  821. log('Job failed: %s' % (j['error']), filters=filters)
  822. elif status == 'ready':
  823. self.qmp_log('job-complete', id=job, filters=filters)
  824. elif status == 'pending' and not auto_finalize:
  825. if pre_finalize:
  826. pre_finalize()
  827. if cancel:
  828. self.qmp_log('job-cancel', id=job, filters=filters)
  829. else:
  830. self.qmp_log('job-finalize', id=job, filters=filters)
  831. elif status == 'concluded' and not auto_dismiss:
  832. self.qmp_log('job-dismiss', id=job, filters=filters)
  833. elif status == 'null':
  834. return error
  835. # Returns None on success, and an error string on failure
  836. def blockdev_create(self, options, job_id='job0', filters=None):
  837. if filters is None:
  838. filters = [filter_qmp_testfiles]
  839. result = self.qmp_log('blockdev-create', filters=filters,
  840. job_id=job_id, options=options)
  841. if 'return' in result:
  842. assert result['return'] == {}
  843. job_result = self.run_job(job_id, filters=filters)
  844. else:
  845. job_result = result['error']
  846. log("")
  847. return job_result
  848. def enable_migration_events(self, name):
  849. log('Enabling migration QMP events on %s...' % name)
  850. log(self.qmp('migrate-set-capabilities', capabilities=[
  851. {
  852. 'capability': 'events',
  853. 'state': True
  854. }
  855. ]))
  856. def wait_migration(self, expect_runstate: Optional[str]) -> bool:
  857. while True:
  858. event = self.event_wait('MIGRATION')
  859. # We use the default timeout, and with a timeout, event_wait()
  860. # never returns None
  861. assert event
  862. log(event, filters=[filter_qmp_event])
  863. if event['data']['status'] in ('completed', 'failed'):
  864. break
  865. if event['data']['status'] == 'completed':
  866. # The event may occur in finish-migrate, so wait for the expected
  867. # post-migration runstate
  868. runstate = None
  869. while runstate != expect_runstate:
  870. runstate = self.qmp('query-status')['return']['status']
  871. return True
  872. else:
  873. return False
  874. def node_info(self, node_name):
  875. nodes = self.qmp('query-named-block-nodes')
  876. for x in nodes['return']:
  877. if x['node-name'] == node_name:
  878. return x
  879. return None
  880. def query_bitmaps(self):
  881. res = self.qmp("query-named-block-nodes")
  882. return {device['node-name']: device['dirty-bitmaps']
  883. for device in res['return'] if 'dirty-bitmaps' in device}
  884. def get_bitmap(self, node_name, bitmap_name, recording=None, bitmaps=None):
  885. """
  886. get a specific bitmap from the object returned by query_bitmaps.
  887. :param recording: If specified, filter results by the specified value.
  888. :param bitmaps: If specified, use it instead of call query_bitmaps()
  889. """
  890. if bitmaps is None:
  891. bitmaps = self.query_bitmaps()
  892. for bitmap in bitmaps[node_name]:
  893. if bitmap.get('name', '') == bitmap_name:
  894. if recording is None or bitmap.get('recording') == recording:
  895. return bitmap
  896. return None
  897. def check_bitmap_status(self, node_name, bitmap_name, fields):
  898. ret = self.get_bitmap(node_name, bitmap_name)
  899. return fields.items() <= ret.items()
  900. def assert_block_path(self, root, path, expected_node, graph=None):
  901. """
  902. Check whether the node under the given path in the block graph
  903. is @expected_node.
  904. @root is the node name of the node where the @path is rooted.
  905. @path is a string that consists of child names separated by
  906. slashes. It must begin with a slash.
  907. Examples for @root + @path:
  908. - root="qcow2-node", path="/backing/file"
  909. - root="quorum-node", path="/children.2/file"
  910. Hypothetically, @path could be empty, in which case it would
  911. point to @root. However, in practice this case is not useful
  912. and hence not allowed.
  913. @expected_node may be None. (All elements of the path but the
  914. leaf must still exist.)
  915. @graph may be None or the result of an x-debug-query-block-graph
  916. call that has already been performed.
  917. """
  918. if graph is None:
  919. graph = self.qmp('x-debug-query-block-graph')['return']
  920. iter_path = iter(path.split('/'))
  921. # Must start with a /
  922. assert next(iter_path) == ''
  923. node = next((node for node in graph['nodes'] if node['name'] == root),
  924. None)
  925. # An empty @path is not allowed, so the root node must be present
  926. assert node is not None, 'Root node %s not found' % root
  927. for child_name in iter_path:
  928. assert node is not None, 'Cannot follow path %s%s' % (root, path)
  929. try:
  930. node_id = next(edge['child'] for edge in graph['edges']
  931. if (edge['parent'] == node['id'] and
  932. edge['name'] == child_name))
  933. node = next(node for node in graph['nodes']
  934. if node['id'] == node_id)
  935. except StopIteration:
  936. node = None
  937. if node is None:
  938. assert expected_node is None, \
  939. 'No node found under %s (but expected %s)' % \
  940. (path, expected_node)
  941. else:
  942. assert node['name'] == expected_node, \
  943. 'Found node %s under %s (but expected %s)' % \
  944. (node['name'], path, expected_node)
  945. index_re = re.compile(r'([^\[]+)\[([^\]]+)\]')
  946. class QMPTestCase(unittest.TestCase):
  947. '''Abstract base class for QMP test cases'''
  948. def __init__(self, *args, **kwargs):
  949. super().__init__(*args, **kwargs)
  950. # Many users of this class set a VM property we rely on heavily
  951. # in the methods below.
  952. self.vm = None
  953. def dictpath(self, d, path):
  954. '''Traverse a path in a nested dict'''
  955. for component in path.split('/'):
  956. m = index_re.match(component)
  957. if m:
  958. component, idx = m.groups()
  959. idx = int(idx)
  960. if not isinstance(d, dict) or component not in d:
  961. self.fail(f'failed path traversal for "{path}" in "{d}"')
  962. d = d[component]
  963. if m:
  964. if not isinstance(d, list):
  965. self.fail(f'path component "{component}" in "{path}" '
  966. f'is not a list in "{d}"')
  967. try:
  968. d = d[idx]
  969. except IndexError:
  970. self.fail(f'invalid index "{idx}" in path "{path}" '
  971. f'in "{d}"')
  972. return d
  973. def assert_qmp_absent(self, d, path):
  974. try:
  975. result = self.dictpath(d, path)
  976. except AssertionError:
  977. return
  978. self.fail('path "%s" has value "%s"' % (path, str(result)))
  979. def assert_qmp(self, d, path, value):
  980. '''Assert that the value for a specific path in a QMP dict
  981. matches. When given a list of values, assert that any of
  982. them matches.'''
  983. result = self.dictpath(d, path)
  984. # [] makes no sense as a list of valid values, so treat it as
  985. # an actual single value.
  986. if isinstance(value, list) and value != []:
  987. for v in value:
  988. if result == v:
  989. return
  990. self.fail('no match for "%s" in %s' % (str(result), str(value)))
  991. else:
  992. self.assertEqual(result, value,
  993. '"%s" is "%s", expected "%s"'
  994. % (path, str(result), str(value)))
  995. def assert_no_active_block_jobs(self):
  996. result = self.vm.qmp('query-block-jobs')
  997. self.assert_qmp(result, 'return', [])
  998. def assert_has_block_node(self, node_name=None, file_name=None):
  999. """Issue a query-named-block-nodes and assert node_name and/or
  1000. file_name is present in the result"""
  1001. def check_equal_or_none(a, b):
  1002. return a is None or b is None or a == b
  1003. assert node_name or file_name
  1004. result = self.vm.qmp('query-named-block-nodes')
  1005. for x in result["return"]:
  1006. if check_equal_or_none(x.get("node-name"), node_name) and \
  1007. check_equal_or_none(x.get("file"), file_name):
  1008. return
  1009. self.fail("Cannot find %s %s in result:\n%s" %
  1010. (node_name, file_name, result))
  1011. def assert_json_filename_equal(self, json_filename, reference):
  1012. '''Asserts that the given filename is a json: filename and that its
  1013. content is equal to the given reference object'''
  1014. self.assertEqual(json_filename[:5], 'json:')
  1015. self.assertEqual(
  1016. self.vm.flatten_qmp_object(json.loads(json_filename[5:])),
  1017. self.vm.flatten_qmp_object(reference)
  1018. )
  1019. def cancel_and_wait(self, drive='drive0', force=False,
  1020. resume=False, wait=60.0):
  1021. '''Cancel a block job and wait for it to finish, returning the event'''
  1022. result = self.vm.qmp('block-job-cancel', device=drive, force=force)
  1023. self.assert_qmp(result, 'return', {})
  1024. if resume:
  1025. self.vm.resume_drive(drive)
  1026. cancelled = False
  1027. result = None
  1028. while not cancelled:
  1029. for event in self.vm.get_qmp_events(wait=wait):
  1030. if event['event'] == 'BLOCK_JOB_COMPLETED' or \
  1031. event['event'] == 'BLOCK_JOB_CANCELLED':
  1032. self.assert_qmp(event, 'data/device', drive)
  1033. result = event
  1034. cancelled = True
  1035. elif event['event'] == 'JOB_STATUS_CHANGE':
  1036. self.assert_qmp(event, 'data/id', drive)
  1037. self.assert_no_active_block_jobs()
  1038. return result
  1039. def wait_until_completed(self, drive='drive0', check_offset=True,
  1040. wait=60.0, error=None):
  1041. '''Wait for a block job to finish, returning the event'''
  1042. while True:
  1043. for event in self.vm.get_qmp_events(wait=wait):
  1044. if event['event'] == 'BLOCK_JOB_COMPLETED':
  1045. self.assert_qmp(event, 'data/device', drive)
  1046. if error is None:
  1047. self.assert_qmp_absent(event, 'data/error')
  1048. if check_offset:
  1049. self.assert_qmp(event, 'data/offset',
  1050. event['data']['len'])
  1051. else:
  1052. self.assert_qmp(event, 'data/error', error)
  1053. self.assert_no_active_block_jobs()
  1054. return event
  1055. if event['event'] == 'JOB_STATUS_CHANGE':
  1056. self.assert_qmp(event, 'data/id', drive)
  1057. def wait_ready(self, drive='drive0'):
  1058. """Wait until a BLOCK_JOB_READY event, and return the event."""
  1059. return self.vm.events_wait([
  1060. ('BLOCK_JOB_READY',
  1061. {'data': {'type': 'mirror', 'device': drive}}),
  1062. ('BLOCK_JOB_READY',
  1063. {'data': {'type': 'commit', 'device': drive}})
  1064. ])
  1065. def wait_ready_and_cancel(self, drive='drive0'):
  1066. self.wait_ready(drive=drive)
  1067. event = self.cancel_and_wait(drive=drive)
  1068. self.assertEqual(event['event'], 'BLOCK_JOB_COMPLETED')
  1069. self.assert_qmp(event, 'data/type', 'mirror')
  1070. self.assert_qmp(event, 'data/offset', event['data']['len'])
  1071. def complete_and_wait(self, drive='drive0', wait_ready=True,
  1072. completion_error=None):
  1073. '''Complete a block job and wait for it to finish'''
  1074. if wait_ready:
  1075. self.wait_ready(drive=drive)
  1076. result = self.vm.qmp('block-job-complete', device=drive)
  1077. self.assert_qmp(result, 'return', {})
  1078. event = self.wait_until_completed(drive=drive, error=completion_error)
  1079. self.assertTrue(event['data']['type'] in ['mirror', 'commit'])
  1080. def pause_wait(self, job_id='job0'):
  1081. with Timeout(3, "Timeout waiting for job to pause"):
  1082. while True:
  1083. result = self.vm.qmp('query-block-jobs')
  1084. found = False
  1085. for job in result['return']:
  1086. if job['device'] == job_id:
  1087. found = True
  1088. if job['paused'] and not job['busy']:
  1089. return job
  1090. break
  1091. assert found
  1092. def pause_job(self, job_id='job0', wait=True):
  1093. result = self.vm.qmp('block-job-pause', device=job_id)
  1094. self.assert_qmp(result, 'return', {})
  1095. if wait:
  1096. return self.pause_wait(job_id)
  1097. return result
  1098. def case_skip(self, reason):
  1099. '''Skip this test case'''
  1100. case_notrun(reason)
  1101. self.skipTest(reason)
  1102. def notrun(reason):
  1103. '''Skip this test suite'''
  1104. # Each test in qemu-iotests has a number ("seq")
  1105. seq = os.path.basename(sys.argv[0])
  1106. with open('%s/%s.notrun' % (test_dir, seq), 'w', encoding='utf-8') \
  1107. as outfile:
  1108. outfile.write(reason + '\n')
  1109. logger.warning("%s not run: %s", seq, reason)
  1110. sys.exit(0)
  1111. def case_notrun(reason):
  1112. '''Mark this test case as not having been run (without actually
  1113. skipping it, that is left to the caller). See
  1114. QMPTestCase.case_skip() for a variant that actually skips the
  1115. current test case.'''
  1116. # Each test in qemu-iotests has a number ("seq")
  1117. seq = os.path.basename(sys.argv[0])
  1118. with open('%s/%s.casenotrun' % (test_dir, seq), 'a', encoding='utf-8') \
  1119. as outfile:
  1120. outfile.write(' [case not run] ' + reason + '\n')
  1121. def _verify_image_format(supported_fmts: Sequence[str] = (),
  1122. unsupported_fmts: Sequence[str] = ()) -> None:
  1123. if 'generic' in supported_fmts and \
  1124. os.environ.get('IMGFMT_GENERIC', 'true') == 'true':
  1125. # similar to
  1126. # _supported_fmt generic
  1127. # for bash tests
  1128. supported_fmts = ()
  1129. not_sup = supported_fmts and (imgfmt not in supported_fmts)
  1130. if not_sup or (imgfmt in unsupported_fmts):
  1131. notrun('not suitable for this image format: %s' % imgfmt)
  1132. if imgfmt == 'luks':
  1133. verify_working_luks()
  1134. def _verify_protocol(supported: Sequence[str] = (),
  1135. unsupported: Sequence[str] = ()) -> None:
  1136. assert not (supported and unsupported)
  1137. if 'generic' in supported:
  1138. return
  1139. not_sup = supported and (imgproto not in supported)
  1140. if not_sup or (imgproto in unsupported):
  1141. notrun('not suitable for this protocol: %s' % imgproto)
  1142. def _verify_platform(supported: Sequence[str] = (),
  1143. unsupported: Sequence[str] = ()) -> None:
  1144. if any((sys.platform.startswith(x) for x in unsupported)):
  1145. notrun('not suitable for this OS: %s' % sys.platform)
  1146. if supported:
  1147. if not any((sys.platform.startswith(x) for x in supported)):
  1148. notrun('not suitable for this OS: %s' % sys.platform)
  1149. def _verify_cache_mode(supported_cache_modes: Sequence[str] = ()) -> None:
  1150. if supported_cache_modes and (cachemode not in supported_cache_modes):
  1151. notrun('not suitable for this cache mode: %s' % cachemode)
  1152. def _verify_aio_mode(supported_aio_modes: Sequence[str] = ()) -> None:
  1153. if supported_aio_modes and (aiomode not in supported_aio_modes):
  1154. notrun('not suitable for this aio mode: %s' % aiomode)
  1155. def _verify_formats(required_formats: Sequence[str] = ()) -> None:
  1156. usf_list = list(set(required_formats) - set(supported_formats()))
  1157. if usf_list:
  1158. notrun(f'formats {usf_list} are not whitelisted')
  1159. def _verify_virtio_blk() -> None:
  1160. out = qemu_pipe('-M', 'none', '-device', 'help')
  1161. if 'virtio-blk' not in out:
  1162. notrun('Missing virtio-blk in QEMU binary')
  1163. def _verify_virtio_scsi_pci_or_ccw() -> None:
  1164. out = qemu_pipe('-M', 'none', '-device', 'help')
  1165. if 'virtio-scsi-pci' not in out and 'virtio-scsi-ccw' not in out:
  1166. notrun('Missing virtio-scsi-pci or virtio-scsi-ccw in QEMU binary')
  1167. def _verify_imgopts(unsupported: Sequence[str] = ()) -> None:
  1168. imgopts = os.environ.get('IMGOPTS')
  1169. # One of usage examples for IMGOPTS is "data_file=$TEST_IMG.ext_data_file"
  1170. # but it supported only for bash tests. We don't have a concept of global
  1171. # TEST_IMG in iotests.py, not saying about somehow parsing $variables.
  1172. # So, for simplicity let's just not support any IMGOPTS with '$' inside.
  1173. unsup = list(unsupported) + ['$']
  1174. if imgopts and any(x in imgopts for x in unsup):
  1175. notrun(f'not suitable for this imgopts: {imgopts}')
  1176. def supports_quorum() -> bool:
  1177. return 'quorum' in qemu_img('--help').stdout
  1178. def verify_quorum():
  1179. '''Skip test suite if quorum support is not available'''
  1180. if not supports_quorum():
  1181. notrun('quorum support missing')
  1182. def has_working_luks() -> Tuple[bool, str]:
  1183. """
  1184. Check whether our LUKS driver can actually create images
  1185. (this extends to LUKS encryption for qcow2).
  1186. If not, return the reason why.
  1187. """
  1188. img_file = f'{test_dir}/luks-test.luks'
  1189. res = qemu_img('create', '-f', 'luks',
  1190. '--object', luks_default_secret_object,
  1191. '-o', luks_default_key_secret_opt,
  1192. '-o', 'iter-time=10',
  1193. img_file, '1G',
  1194. check=False)
  1195. try:
  1196. os.remove(img_file)
  1197. except OSError:
  1198. pass
  1199. if res.returncode:
  1200. reason = res.stdout
  1201. for line in res.stdout.splitlines():
  1202. if img_file + ':' in line:
  1203. reason = line.split(img_file + ':', 1)[1].strip()
  1204. break
  1205. return (False, reason)
  1206. else:
  1207. return (True, '')
  1208. def verify_working_luks():
  1209. """
  1210. Skip test suite if LUKS does not work
  1211. """
  1212. (working, reason) = has_working_luks()
  1213. if not working:
  1214. notrun(reason)
  1215. def supports_qcow2_zstd_compression() -> bool:
  1216. img_file = f'{test_dir}/qcow2-zstd-test.qcow2'
  1217. res = qemu_img('create', '-f', 'qcow2', '-o', 'compression_type=zstd',
  1218. img_file, '0',
  1219. check=False)
  1220. try:
  1221. os.remove(img_file)
  1222. except OSError:
  1223. pass
  1224. if res.returncode == 1 and \
  1225. "'compression-type' does not accept value 'zstd'" in res.stdout:
  1226. return False
  1227. else:
  1228. return True
  1229. def verify_qcow2_zstd_compression():
  1230. if not supports_qcow2_zstd_compression():
  1231. notrun('zstd compression not supported')
  1232. def qemu_pipe(*args: str) -> str:
  1233. """
  1234. Run qemu with an option to print something and exit (e.g. a help option).
  1235. :return: QEMU's stdout output.
  1236. """
  1237. full_args = [qemu_prog] + qemu_opts + list(args)
  1238. output, _ = qemu_tool_pipe_and_status('qemu', full_args)
  1239. return output
  1240. def supported_formats(read_only=False):
  1241. '''Set 'read_only' to True to check ro-whitelist
  1242. Otherwise, rw-whitelist is checked'''
  1243. if not hasattr(supported_formats, "formats"):
  1244. supported_formats.formats = {}
  1245. if read_only not in supported_formats.formats:
  1246. format_message = qemu_pipe("-drive", "format=help")
  1247. line = 1 if read_only else 0
  1248. supported_formats.formats[read_only] = \
  1249. format_message.splitlines()[line].split(":")[1].split()
  1250. return supported_formats.formats[read_only]
  1251. def skip_if_unsupported(required_formats=(), read_only=False):
  1252. '''Skip Test Decorator
  1253. Runs the test if all the required formats are whitelisted'''
  1254. def skip_test_decorator(func):
  1255. def func_wrapper(test_case: QMPTestCase, *args: List[Any],
  1256. **kwargs: Dict[str, Any]) -> None:
  1257. if callable(required_formats):
  1258. fmts = required_formats(test_case)
  1259. else:
  1260. fmts = required_formats
  1261. usf_list = list(set(fmts) - set(supported_formats(read_only)))
  1262. if usf_list:
  1263. msg = f'{test_case}: formats {usf_list} are not whitelisted'
  1264. test_case.case_skip(msg)
  1265. else:
  1266. func(test_case, *args, **kwargs)
  1267. return func_wrapper
  1268. return skip_test_decorator
  1269. def skip_for_formats(formats: Sequence[str] = ()) \
  1270. -> Callable[[Callable[[QMPTestCase, List[Any], Dict[str, Any]], None]],
  1271. Callable[[QMPTestCase, List[Any], Dict[str, Any]], None]]:
  1272. '''Skip Test Decorator
  1273. Skips the test for the given formats'''
  1274. def skip_test_decorator(func):
  1275. def func_wrapper(test_case: QMPTestCase, *args: List[Any],
  1276. **kwargs: Dict[str, Any]) -> None:
  1277. if imgfmt in formats:
  1278. msg = f'{test_case}: Skipped for format {imgfmt}'
  1279. test_case.case_skip(msg)
  1280. else:
  1281. func(test_case, *args, **kwargs)
  1282. return func_wrapper
  1283. return skip_test_decorator
  1284. def skip_if_user_is_root(func):
  1285. '''Skip Test Decorator
  1286. Runs the test only without root permissions'''
  1287. def func_wrapper(*args, **kwargs):
  1288. if os.getuid() == 0:
  1289. case_notrun('{}: cannot be run as root'.format(args[0]))
  1290. return None
  1291. else:
  1292. return func(*args, **kwargs)
  1293. return func_wrapper
  1294. # We need to filter out the time taken from the output so that
  1295. # qemu-iotest can reliably diff the results against master output,
  1296. # and hide skipped tests from the reference output.
  1297. class ReproducibleTestResult(unittest.TextTestResult):
  1298. def addSkip(self, test, reason):
  1299. # Same as TextTestResult, but print dot instead of "s"
  1300. unittest.TestResult.addSkip(self, test, reason)
  1301. if self.showAll:
  1302. self.stream.writeln("skipped {0!r}".format(reason))
  1303. elif self.dots:
  1304. self.stream.write(".")
  1305. self.stream.flush()
  1306. class ReproducibleStreamWrapper:
  1307. def __init__(self, stream: TextIO):
  1308. self.stream = stream
  1309. def __getattr__(self, attr):
  1310. if attr in ('stream', '__getstate__'):
  1311. raise AttributeError(attr)
  1312. return getattr(self.stream, attr)
  1313. def write(self, arg=None):
  1314. arg = re.sub(r'Ran (\d+) tests? in [\d.]+s', r'Ran \1 tests', arg)
  1315. arg = re.sub(r' \(skipped=\d+\)', r'', arg)
  1316. self.stream.write(arg)
  1317. class ReproducibleTestRunner(unittest.TextTestRunner):
  1318. def __init__(self, stream: Optional[TextIO] = None,
  1319. resultclass: Type[unittest.TestResult] =
  1320. ReproducibleTestResult,
  1321. **kwargs: Any) -> None:
  1322. rstream = ReproducibleStreamWrapper(stream or sys.stdout)
  1323. super().__init__(stream=rstream, # type: ignore
  1324. descriptions=True,
  1325. resultclass=resultclass,
  1326. **kwargs)
  1327. def execute_unittest(argv: List[str], debug: bool = False) -> None:
  1328. """Executes unittests within the calling module."""
  1329. # Some tests have warnings, especially ResourceWarnings for unclosed
  1330. # files and sockets. Ignore them for now to ensure reproducibility of
  1331. # the test output.
  1332. unittest.main(argv=argv,
  1333. testRunner=ReproducibleTestRunner,
  1334. verbosity=2 if debug else 1,
  1335. warnings=None if sys.warnoptions else 'ignore')
  1336. def execute_setup_common(supported_fmts: Sequence[str] = (),
  1337. supported_platforms: Sequence[str] = (),
  1338. supported_cache_modes: Sequence[str] = (),
  1339. supported_aio_modes: Sequence[str] = (),
  1340. unsupported_fmts: Sequence[str] = (),
  1341. supported_protocols: Sequence[str] = (),
  1342. unsupported_protocols: Sequence[str] = (),
  1343. required_fmts: Sequence[str] = (),
  1344. unsupported_imgopts: Sequence[str] = ()) -> bool:
  1345. """
  1346. Perform necessary setup for either script-style or unittest-style tests.
  1347. :return: Bool; Whether or not debug mode has been requested via the CLI.
  1348. """
  1349. # Note: Python 3.6 and pylint do not like 'Collection' so use 'Sequence'.
  1350. debug = '-d' in sys.argv
  1351. if debug:
  1352. sys.argv.remove('-d')
  1353. logging.basicConfig(level=(logging.DEBUG if debug else logging.WARN))
  1354. _verify_image_format(supported_fmts, unsupported_fmts)
  1355. _verify_protocol(supported_protocols, unsupported_protocols)
  1356. _verify_platform(supported=supported_platforms)
  1357. _verify_cache_mode(supported_cache_modes)
  1358. _verify_aio_mode(supported_aio_modes)
  1359. _verify_formats(required_fmts)
  1360. _verify_virtio_blk()
  1361. _verify_imgopts(unsupported_imgopts)
  1362. return debug
  1363. def execute_test(*args, test_function=None, **kwargs):
  1364. """Run either unittest or script-style tests."""
  1365. debug = execute_setup_common(*args, **kwargs)
  1366. if not test_function:
  1367. execute_unittest(sys.argv, debug)
  1368. else:
  1369. test_function()
  1370. def activate_logging():
  1371. """Activate iotests.log() output to stdout for script-style tests."""
  1372. handler = logging.StreamHandler(stream=sys.stdout)
  1373. formatter = logging.Formatter('%(message)s')
  1374. handler.setFormatter(formatter)
  1375. test_logger.addHandler(handler)
  1376. test_logger.setLevel(logging.INFO)
  1377. test_logger.propagate = False
  1378. # This is called from script-style iotests without a single point of entry
  1379. def script_initialize(*args, **kwargs):
  1380. """Initialize script-style tests without running any tests."""
  1381. activate_logging()
  1382. execute_setup_common(*args, **kwargs)
  1383. # This is called from script-style iotests with a single point of entry
  1384. def script_main(test_function, *args, **kwargs):
  1385. """Run script-style tests outside of the unittest framework"""
  1386. activate_logging()
  1387. execute_test(*args, test_function=test_function, **kwargs)
  1388. # This is called from unittest style iotests
  1389. def main(*args, **kwargs):
  1390. """Run tests using the unittest framework"""
  1391. execute_test(*args, **kwargs)