2
0

iotests.py 60 KB

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