iotests.py 59 KB

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