iotests: add detailed tracebacks to qemu_img() failures
v2 cover iotests: add detailed tracebacks to qemu_img() failures
This series does two things:
(1) Adds more detailed information to terminal output when qemu-img crashes or returns with a non-zero exit code
(2) Ensures that every last call to qemu-img made in the iotest test suite either returns a zero, *or* has its output logged.
This is accomplished by:
- Adding a new subprocess.CalledProcessError exception type that's more verbose than the standard, built-in one
- Rewriting the qemu_img() function to utilize that new Exception
- Modifying every last iotest helper that invokes qemu-img to use qemu_img() or a derivative thereof.
This patchset was inspired by Thomas Huth noticing that iotest 065 would crash in a way that was largely silent, except for async QMP traces when the VM failed to start. The root cause in that case is that iotest 065 did not tolerate zstd support being compiled out of QEMU, so the qemu-img command fails - silently. (And subsequent test actions would then explode nastily with confusing or misleading error messages.)
So, broadly, I rewrote qemu_img() to be a lot stricter by default, and then rebased every other helper function that called into the qemu-img process to use qemu_img().
RFC:
- 'enboxify()' text decoration does not support unicode too well. I think it's important to have some text decoration, but I haven't gotten around to making it smarter. I might remove it for something simpler to avoid having to learn more about unicode.
- At this point, every last qemu-img call is audited, but I did not extend the same treatment to qemu-io, qemu-nbd, etc. I intend to, later. Eventually, I plan to offer something like 'qemu_tool()' as a replacement for 'qemu_tool_pipe_and_status()', and qemu_img() will become a thin wrapper around qemu_tool().
V2:
- Ensure *all* calls to qemu-img go through qemu_img()
- Raise VerboseProcessError on negative return code, even when check=False
- Check logging status for logged variants and revert to Exceptions when logging is off!
John Snow (18):
python/utils: add enboxify() text decoration utility
iotests: add VerboseProcessError
iotests: Remove explicit checks for qemu_img() == 0
iotests: make qemu_img raise on non-zero rc by default
iotests: fortify compare_images() against crashes
iotests: add qemu_img_json()
iotests: use qemu_img_json() when applicable
iotests: add qemu_img_info()
iotests: remove-bitmap-from-backing: use qemu_img_info()
iotests: add qemu_img_map() function
iotests: change supports_quorum to use qemu_img
iotests: replace unchecked calls to qemu_img_pipe()
iotests: remove external calls to qemu_img_pipe()
iotests: move has_working_luks onto qemu_img()
iotests: remove qemu_img_log('create', ...) calls
iotests: remove qemu_img_pipe()
iotests: make qemu_img_log() check log level
iotests: reimplement img_info_log in terms of qemu_img_log
python/qemu/utils/__init__.py | 58 +++++ tests/qemu-iotests/041 | 5 +- tests/qemu-iotests/065 | 7 +- tests/qemu-iotests/149 | 8 +- tests/qemu-iotests/163 | 9 +- tests/qemu-iotests/194 | 4 +- tests/qemu-iotests/202 | 4 +- tests/qemu-iotests/203 | 4 +- tests/qemu-iotests/211 | 6 +- tests/qemu-iotests/216 | 6 +- tests/qemu-iotests/218 | 2 +- tests/qemu-iotests/224 | 11 +- tests/qemu-iotests/228 | 12 +- tests/qemu-iotests/234 | 4 +- tests/qemu-iotests/237 | 3 +- tests/qemu-iotests/237.out | 3 - tests/qemu-iotests/242 | 5 +- tests/qemu-iotests/255 | 8 +- tests/qemu-iotests/255.out | 4 - tests/qemu-iotests/257 | 11 +- tests/qemu-iotests/258 | 4 +- tests/qemu-iotests/262 | 2 +- tests/qemu-iotests/274 | 17 +- tests/qemu-iotests/274.out | 29 --- tests/qemu-iotests/280 | 2 +- tests/qemu-iotests/280.out | 1 - tests/qemu-iotests/296 | 13 +- tests/qemu-iotests/303 | 2 +- tests/qemu-iotests/310 | 14 +- tests/qemu-iotests/iotests.py | 217 ++++++++++++++---- tests/qemu-iotests/tests/block-status-cache | 14 +- tests/qemu-iotests/tests/image-fleecing | 4 +- .../tests/mirror-ready-cancel-error | 6 +- tests/qemu-iotests/tests/mirror-top-perms | 3 +- .../qemu-iotests/tests/parallels-read-bitmap | 6 +- .../tests/remove-bitmap-from-backing | 14 +- .../qemu-iotests/tests/stream-error-on-reset | 4 +- 37 files changed, 334 insertions(+), 192 deletions(-)
Signature · 1 line
2.34.1
PATCH v2 1/18 python/utils: add enboxify() text decoration utility
Quoted 1 line
Quoted 1 line
Quoted 1 line
print(enboxify(msg, width=72, name="commit message"))
┏━ commit message ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ enboxify() takes a chunk of text and wraps it in a text art box that ┃ ┃ adheres to a specified width. An optional title label may be given, ┃ ┃ and any of the individual glyphs used to draw the box may be ┃ ┃ replaced or specified as well. ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
--- python/qemu/utils/__init__.py | 58 +++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+)
python/qemu/utils/__init__.py +58 -0
@@ -15,7 +15,10 @@ # the COPYING file in the top-level directory. # +import os import re +import shutil +import textwrap from typing import Optional # pylint: disable=import-error
@@ -23,6 +26,7 @@ __all__ = ( + 'enboxify', 'get_info_usernet_hostfwd_port', 'kvm_available', 'list_accel',
@@ -43,3 +47,57 @@ def get_info_usernet_hostfwd_port(info_usernet_output: str) -> Optional[int]: if match is not None: return int(match[1]) return None + + +# pylint: disable=too-many-arguments +def enboxify( + content: str = '', + width: Optional[int] = None, + name: Optional[str] = None, + padding: int = 1, + upper_left: str = '┏', + upper_right: str = '┓', + lower_left: str = '┗', + lower_right: str = '┛', + horizontal: str = '━', + vertical: str = '┃', +) -> str: + """ + Wrap some text into a text art box of a given width. + + :param content: The text to wrap into a box. + :param width: The number of columns (including the box itself). + :param name: A label to apply to the upper-left of the box. + :param padding: How many columns of padding to apply inside. + """ + if width is None: + width = shutil.get_terminal_size()[0] + prefix = vertical + (' ' * padding) + suffix = (' ' * padding) + vertical + lwidth = width - len(suffix) + + def _bar(name: Optional[str], top: bool = True) -> str: + ret = upper_left if top else lower_left + right = upper_right if top else lower_right + if name is not None: + ret += f"{horizontal} {name} " + + assert width is not None + filler_len = width - len(ret) - len(right) + ret += f"{horizontal * filler_len}{right}" + return ret + + def _wrap(line: str) -> str: + return os.linesep.join([ + wrapped_line.ljust(lwidth) + suffix + for wrapped_line in textwrap.wrap( + line, width=lwidth, initial_indent=prefix, + subsequent_indent=prefix, replace_whitespace=False, + drop_whitespace=False, break_on_hyphens=False) + ]) + + return os.linesep.join(( + _bar(name, top=True), + os.linesep.join(_wrap(line) for line in content.splitlines()), + _bar(None, top=False), + ))
Signature · 1 line
2.34.1
PATCH v2 2/18 iotests: add VerboseProcessError
In reply to John SnowThis adds an Exception that extends the Python built-in subprocess.CalledProcessError. When this exception is raised, it will still be caught when selecting for the stdlib variant.
The difference is that the str() method of this Exception also adds the stdout/stderr logs. In effect, if this exception goes unhandled, Python will print the output in a nice, highlighted box to the terminal so that it's easy to spot.
This should save some headache from having to re-run test suites with debugging enabled by augmenting the exceptions to print more information in the default case.
--- tests/qemu-iotests/iotests.py | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+)
tests/qemu-iotests/iotests.py +34 -0
@@ -30,6 +30,7 @@ import struct import subprocess import sys +import textwrap import time from typing import (Any, Callable, Dict, Iterable, Iterator, List, Optional, Sequence, TextIO, Tuple, Type, TypeVar)
@@ -39,6 +40,7 @@ from qemu.machine import qtest from qemu.qmp import QMPMessage +from qemu.utils import enboxify # Use this logger for logging messages directly from the iotests module logger = logging.getLogger('qemu.iotests')
@@ -117,6 +119,38 @@ sample_img_dir = os.environ['SAMPLE_IMG_DIR'] +class VerboseProcessError(subprocess.CalledProcessError): + """ + The same as CalledProcessError, but more verbose. + + This is useful for debugging failed calls during test executions. + The return code, signal (if any), and terminal output will be displayed + on unhandled exceptions. + """ + def summary(self) -> str: + return super().__str__() + + def __str__(self) -> str: + lmargin = ' ' + width = shutil.get_terminal_size()[0] - len(lmargin) + sections = [] + + name = 'output' if self.stderr is None else 'stdout' + if self.stdout: + sections.append(enboxify(self.stdout, width, name)) + else: + sections.append(f"{name}: N/A") + + if self.stderr: + sections.append(enboxify(self.stderr, width, 'stderr')) + elif self.stderr is not None: + sections.append("stderr: N/A") + + return os.linesep.join(( + self.summary(), + textwrap.indent(os.linesep.join(sections), prefix=lmargin), + )) + @contextmanager def change_log_level( logger_name: str, level: int = logging.CRITICAL) -> Iterator[None]:
Signature · 1 line
2.34.1
PATCH v2 3/18 iotests: Remove explicit checks for qemu_img() == 0
In reply to John Snowqemu_img() returning zero ought to be the rule, not the exception. Remove all explicit checks against the condition in preparation for making non-zero returns an Exception.
--- tests/qemu-iotests/163 | 9 +++------ tests/qemu-iotests/216 | 6 +++--- tests/qemu-iotests/218 | 2 +- tests/qemu-iotests/224 | 11 +++++------ tests/qemu-iotests/228 | 12 ++++++------ tests/qemu-iotests/257 | 3 +-- tests/qemu-iotests/258 | 4 ++-- tests/qemu-iotests/310 | 14 +++++++------- tests/qemu-iotests/tests/block-status-cache | 3 +-- tests/qemu-iotests/tests/image-fleecing | 4 ++-- tests/qemu-iotests/tests/mirror-ready-cancel-error | 6 ++---- tests/qemu-iotests/tests/mirror-top-perms | 3 +-- .../qemu-iotests/tests/remove-bitmap-from-backing | 8 ++++---- tests/qemu-iotests/tests/stream-error-on-reset | 4 ++-- 14 files changed, 40 insertions(+), 49 deletions(-)
tests/qemu-iotests/163 +3 -6
@@ -107,8 +107,7 @@ class ShrinkBaseClass(iotests.QMPTestCase): if iotests.imgfmt == 'raw': return - self.assertEqual(qemu_img('check', test_img), 0, - "Verifying image corruption") + qemu_img('check', test_img) def test_empty_image(self): qemu_img('resize', '-f', iotests.imgfmt, '--shrink', test_img,
@@ -130,8 +129,7 @@ class ShrinkBaseClass(iotests.QMPTestCase): qemu_img('resize', '-f', iotests.imgfmt, '--shrink', test_img, self.shrink_size) - self.assertEqual(qemu_img("compare", test_img, check_img), 0, - "Verifying image content") + qemu_img("compare", test_img, check_img) self.image_verify()
@@ -146,8 +144,7 @@ class ShrinkBaseClass(iotests.QMPTestCase): qemu_img('resize', '-f', iotests.imgfmt, '--shrink', test_img, self.shrink_size) - self.assertEqual(qemu_img("compare", test_img, check_img), 0, - "Verifying image content") + qemu_img("compare", test_img, check_img) self.image_verify()
tests/qemu-iotests/216 +3 -3
@@ -51,10 +51,10 @@ with iotests.FilePath('base.img') as base_img_path, \ log('--- Setting up images ---') log('') - assert qemu_img('create', '-f', iotests.imgfmt, base_img_path, '64M') == 0 + qemu_img('create', '-f', iotests.imgfmt, base_img_path, '64M') assert qemu_io_silent(base_img_path, '-c', 'write -P 1 0M 1M') == 0 - assert qemu_img('create', '-f', iotests.imgfmt, '-b', base_img_path, - '-F', iotests.imgfmt, top_img_path) == 0 + qemu_img('create', '-f', iotests.imgfmt, '-b', base_img_path, + '-F', iotests.imgfmt, top_img_path) assert qemu_io_silent(top_img_path, '-c', 'write -P 2 1M 1M') == 0 log('Done')
tests/qemu-iotests/218 +1 -1
@@ -145,7 +145,7 @@ log('') with iotests.VM() as vm, \ iotests.FilePath('src.img') as src_img_path: - assert qemu_img('create', '-f', iotests.imgfmt, src_img_path, '64M') == 0 + qemu_img('create', '-f', iotests.imgfmt, src_img_path, '64M') assert qemu_io_silent('-f', iotests.imgfmt, src_img_path, '-c', 'write -P 42 0M 64M') == 0
tests/qemu-iotests/224 +5 -6
@@ -47,12 +47,11 @@ for filter_node_name in False, True: iotests.FilePath('top.img') as top_img_path, \ iotests.VM() as vm: - assert qemu_img('create', '-f', iotests.imgfmt, - base_img_path, '64M') == 0 - assert qemu_img('create', '-f', iotests.imgfmt, '-b', base_img_path, - '-F', iotests.imgfmt, mid_img_path) == 0 - assert qemu_img('create', '-f', iotests.imgfmt, '-b', mid_img_path, - '-F', iotests.imgfmt, top_img_path) == 0 + qemu_img('create', '-f', iotests.imgfmt, base_img_path, '64M') + qemu_img('create', '-f', iotests.imgfmt, '-b', base_img_path, + '-F', iotests.imgfmt, mid_img_path) + qemu_img('create', '-f', iotests.imgfmt, '-b', mid_img_path, + '-F', iotests.imgfmt, top_img_path) # Something to commit assert qemu_io_silent(mid_img_path, '-c', 'write -P 1 0 1M') == 0
tests/qemu-iotests/228 +6 -6
@@ -54,11 +54,11 @@ with iotests.FilePath('base.img') as base_img_path, \ iotests.FilePath('top.img') as top_img_path, \ iotests.VM() as vm: - assert qemu_img('create', '-f', iotests.imgfmt, base_img_path, '64M') == 0 + qemu_img('create', '-f', iotests.imgfmt, base_img_path, '64M') # Choose a funny way to describe the backing filename - assert qemu_img('create', '-f', iotests.imgfmt, '-b', - 'file:' + base_img_path, '-F', iotests.imgfmt, - top_img_path) == 0 + qemu_img('create', '-f', iotests.imgfmt, '-b', + 'file:' + base_img_path, '-F', iotests.imgfmt, + top_img_path) vm.launch()
@@ -172,8 +172,8 @@ with iotests.FilePath('base.img') as base_img_path, \ # (because qemu cannot "canonicalize"/"resolve" the backing # filename unless the backing file is opened implicitly with the # overlay) - assert qemu_img('create', '-f', iotests.imgfmt, '-b', base_img_path, - '-F', iotests.imgfmt, top_img_path) == 0 + qemu_img('create', '-f', iotests.imgfmt, '-b', base_img_path, + '-F', iotests.imgfmt, top_img_path) # You can only reliably override backing options by using a node # reference (or by specifying file.filename, but, well...)
tests/qemu-iotests/257 +1 -2
@@ -240,8 +240,7 @@ def compare_images(image, reference, baseimg=None, expected_match=True): """ expected_ret = 0 if expected_match else 1 if baseimg: - assert qemu_img("rebase", "-u", "-b", baseimg, '-F', iotests.imgfmt, - image) == 0 + qemu_img("rebase", "-u", "-b", baseimg, '-F', iotests.imgfmt, image) ret = qemu_img("compare", image, reference) log('qemu_img compare "{:s}" "{:s}" ==> {:s}, {:s}'.format( image, reference,
tests/qemu-iotests/258 +2 -2
@@ -75,13 +75,13 @@ def test_concurrent_finish(write_to_stream_node): # It is important to use raw for the base layer (so that # permissions are just handed through to the protocol layer) - assert qemu_img('create', '-f', 'raw', node0_path, '64M') == 0 + qemu_img('create', '-f', 'raw', node0_path, '64M') stream_throttle=None commit_throttle=None for path in [node1_path, node2_path, node3_path, node4_path]: - assert qemu_img('create', '-f', iotests.imgfmt, path, '64M') == 0 + qemu_img('create', '-f', iotests.imgfmt, path, '64M') if write_to_stream_node: # This is what (most of the time) makes commit finish
tests/qemu-iotests/310 +7 -7
@@ -43,15 +43,15 @@ with iotests.FilePath('base.img') as base_img_path, \ log('--- Setting up images ---') log('') - assert qemu_img('create', '-f', iotests.imgfmt, base_img_path, '64M') == 0 + qemu_img('create', '-f', iotests.imgfmt, base_img_path, '64M') assert qemu_io_silent(base_img_path, '-c', 'write -P 1 0M 1M') == 0 assert qemu_io_silent(base_img_path, '-c', 'write -P 1 3M 1M') == 0 - assert qemu_img('create', '-f', iotests.imgfmt, '-b', base_img_path, - '-F', iotests.imgfmt, mid_img_path) == 0 + qemu_img('create', '-f', iotests.imgfmt, '-b', base_img_path, + '-F', iotests.imgfmt, mid_img_path) assert qemu_io_silent(mid_img_path, '-c', 'write -P 3 2M 1M') == 0 assert qemu_io_silent(mid_img_path, '-c', 'write -P 3 4M 1M') == 0 - assert qemu_img('create', '-f', iotests.imgfmt, '-b', mid_img_path, - '-F', iotests.imgfmt, top_img_path) == 0 + qemu_img('create', '-f', iotests.imgfmt, '-b', mid_img_path, + '-F', iotests.imgfmt, top_img_path) assert qemu_io_silent(top_img_path, '-c', 'write -P 2 1M 1M') == 0 # 0 1 2 3 4
@@ -105,8 +105,8 @@ with iotests.FilePath('base.img') as base_img_path, \ log('') # Detach backing to check that we can read the data from the top level now - assert qemu_img('rebase', '-u', '-b', '', '-f', iotests.imgfmt, - top_img_path) == 0 + qemu_img('rebase', '-u', '-b', '', '-f', iotests.imgfmt, + top_img_path) assert qemu_io_silent(top_img_path, '-c', 'read -P 0 0 1M') == 0 assert qemu_io_silent(top_img_path, '-c', 'read -P 2 1M 1M') == 0
tests/qemu-iotests/tests/block-status-cache +1 -2
@@ -35,8 +35,7 @@ nbd_sock = os.path.join(iotests.sock_dir, 'nbd.sock') class TestBscWithNbd(iotests.QMPTestCase): def setUp(self) -> None: """Just create an empty image with a read-only NBD server on it""" - assert qemu_img_create('-f', iotests.imgfmt, test_img, - str(image_size)) == 0 + qemu_img_create('-f', iotests.imgfmt, test_img, str(image_size)) # Pass --allocation-depth to enable the qemu:allocation-depth context, # which we are going to query to provoke a block-status inquiry with
tests/qemu-iotests/tests/image-fleecing +2 -2
@@ -53,8 +53,8 @@ def do_test(use_cbw, base_img_path, fleece_img_path, nbd_sock_path, vm): log('--- Setting up images ---') log('') - assert qemu_img('create', '-f', iotests.imgfmt, base_img_path, '64M') == 0 - assert qemu_img('create', '-f', 'qcow2', fleece_img_path, '64M') == 0 + qemu_img('create', '-f', iotests.imgfmt, base_img_path, '64M') + qemu_img('create', '-f', 'qcow2', fleece_img_path, '64M') for p in patterns: qemu_io('-f', iotests.imgfmt,
tests/qemu-iotests/tests/mirror-ready-cancel-error +2 -4
@@ -31,10 +31,8 @@ target = os.path.join(iotests.test_dir, 'target.img') class TestMirrorReadyCancelError(iotests.QMPTestCase): def setUp(self) -> None: - assert iotests.qemu_img_create('-f', iotests.imgfmt, source, - str(image_size)) == 0 - assert iotests.qemu_img_create('-f', iotests.imgfmt, target, - str(image_size)) == 0 + iotests.qemu_img_create('-f', iotests.imgfmt, source, str(image_size)) + iotests.qemu_img_create('-f', iotests.imgfmt, target, str(image_size)) # Ensure that mirror will copy something before READY so the # target format layer will forward the pre-READY flush to its
tests/qemu-iotests/tests/mirror-top-perms +1 -2
@@ -34,8 +34,7 @@ source = os.path.join(iotests.test_dir, 'source.img') class TestMirrorTopPerms(iotests.QMPTestCase): def setUp(self): - assert qemu_img('create', '-f', iotests.imgfmt, source, - str(image_size)) == 0 + qemu_img('create', '-f', iotests.imgfmt, source, str(image_size)) self.vm = iotests.VM() self.vm.add_drive(source) self.vm.add_blockdev(f'null-co,node-name=null,size={image_size}')
tests/qemu-iotests/tests/remove-bitmap-from-backing +4 -4
@@ -27,11 +27,11 @@ iotests.script_initialize(supported_fmts=['qcow2'], top, base = iotests.file_path('top', 'base') size = '1M' -assert qemu_img_create('-f', iotests.imgfmt, base, size) == 0 -assert qemu_img_create('-f', iotests.imgfmt, '-b', base, - '-F', iotests.imgfmt, top, size) == 0 +qemu_img_create('-f', iotests.imgfmt, base, size) +qemu_img_create('-f', iotests.imgfmt, '-b', base, + '-F', iotests.imgfmt, top, size) -assert qemu_img('bitmap', '--add', base, 'bitmap0') == 0 +qemu_img('bitmap', '--add', base, 'bitmap0') # Just assert that our method of checking bitmaps in the image works. assert 'bitmaps' in qemu_img_pipe('info', base)
tests/qemu-iotests/tests/stream-error-on-reset +2 -2
@@ -54,9 +54,9 @@ class TestStreamErrorOnReset(QMPTestCase): to it will result in an error - top image is attached to a virtio-scsi device """ - assert qemu_img_create('-f', imgfmt, base, str(image_size)) == 0 + qemu_img_create('-f', imgfmt, base, str(image_size)) assert qemu_io_silent('-c', f'write 0 {data_size}', base) == 0 - assert qemu_img_create('-f', imgfmt, top, str(image_size)) == 0 + qemu_img_create('-f', imgfmt, top, str(image_size)) self.vm = iotests.VM() self.vm.add_args('-accel', 'tcg') # Make throttling work properly
Signature · 1 line
2.34.1
PATCH v2 4/18 iotests: make qemu_img raise on non-zero rc by default
In reply to John Snowre-write qemu_img() as a function that will by default raise a VerboseProcessException (extended from CalledProcessException) on non-zero return codes. This will produce a stack trace that will show the command line arguments and return code from the failed process run.
Users that want something more flexible (there appears to be only one) can use check=False and manage the return themselves. However, when the return code is negative, the Exception will be raised no matter what. This is done under the belief that there's no legitimate reason, even in negative tests, to see a crash from a tool.
--- tests/qemu-iotests/257 | 8 ++++-- tests/qemu-iotests/iotests.py | 53 +++++++++++++++++++++++++++++++---- 2 files changed, 52 insertions(+), 9 deletions(-)
tests/qemu-iotests/257 +5 -3
@@ -241,11 +241,13 @@ def compare_images(image, reference, baseimg=None, expected_match=True): expected_ret = 0 if expected_match else 1 if baseimg: qemu_img("rebase", "-u", "-b", baseimg, '-F', iotests.imgfmt, image) - ret = qemu_img("compare", image, reference) + + sub = qemu_img("compare", image, reference, check=False) + log('qemu_img compare "{:s}" "{:s}" ==> {:s}, {:s}'.format( image, reference, - "Identical" if ret == 0 else "Mismatch", - "OK!" if ret == expected_ret else "ERROR!"), + "Identical" if sub.returncode == 0 else "Mismatch", + "OK!" if sub.returncode == expected_ret else "ERROR!"), filters=[iotests.filter_testfiles]) def test_bitmap_sync(bsync_mode, msync_mode='bitmap', failure=None):
tests/qemu-iotests/iotests.py +47 -6
71 lines not on this page · raw message
Signature · 1 line
2.34.1
PATCH v2 5/18 iotests: fortify compare_images() against crashes
In reply to John SnowMake this helper function a little stricter about what it allows by default. If qemu_img returns some exit code that implies it didn't actually perform the comparison, treat that as an exceptional circumstance and force the caller to be aware of the peril.
--- tests/qemu-iotests/iotests.py | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-)
tests/qemu-iotests/iotests.py +16 -5
@@ -507,11 +507,22 @@ def qemu_nbd_popen(*args): p.kill() p.wait() -def compare_images(img1, img2, fmt1=imgfmt, fmt2=imgfmt): - '''Return True if two image files are identical''' - res = qemu_img('compare', '-f', fmt1, - '-F', fmt2, img1, img2, check=False) - return res.returncode == 0 +def compare_images(img1: str, img2: str, + fmt1: str = imgfmt, fmt2: str = imgfmt) -> bool: + """ + Compare two images with QEMU_IMG; return True if they are identical. + + :raise CalledProcessError: + when qemu-img crashes or returns a status code of anything other + than 0 (identical) or 1 (different). + """ + try: + qemu_img('compare', '-f', fmt1, '-F', fmt2, img1, img2) + return True + except subprocess.CalledProcessError as exc: + if exc.returncode == 1: + return False + raise def create_image(name, size): '''Create a fully-allocated raw image with sector markers'''
Signature · 1 line
2.34.1
PATCH v2 6/18 iotests: add qemu_img_json()
In reply to John SnowA little helper built on top of qemu_img() that tries to pull a valid JSON document out of the stdout stream.
In the event that the return code is negative (the program crashed), or the code is greater than zero and did not produce valid JSON output, the VerboseProcessError raised by qemu_img is re-raised instead.
In the event that the return code is zero but we can't parse valid JSON, allow the JSON deserialization error to be raised.
--- tests/qemu-iotests/iotests.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+)
tests/qemu-iotests/iotests.py +35 -0
@@ -309,6 +309,41 @@ def ordered_qmp(qmsg, conv_keys=True): def qemu_img_create(*args: str) -> subprocess.CompletedProcess[str]: return qemu_img('create', *args) +def qemu_img_json(*args: str) -> Any: + """ + Run qemu-img and return its output as deserialized JSON. + + :raise CalledProcessError: + When qemu-img crashes, or returns a non-zero exit code without + producing a valid JSON document to stdout. + :raise JSONDecoderError: + When qemu-img returns 0, but failed to produce a valid JSON document. + """ + json_data = ... # json.loads can legitimately return 'None'. + + try: + res = qemu_img(*args, combine_stdio=False) + except subprocess.CalledProcessError as exc: + # Terminated due to signal. Don't bother. + if exc.returncode < 0: + raise + + # Commands like 'check' can return failure (exit codes 2 and 3) + # to indicate command completion, but with errors found. For + # multi-command flexibility, ignore the exact error codes and + # *try* to load JSON. + try: + json_data = json.loads(exc.stdout) + except json.JSONDecodeError: + pass # Nope. This thing is toast. + + if json_data is ...: + raise + + if json_data is ...: + json_data = json.loads(res.stdout) + return json_data + def qemu_img_measure(*args): return json.loads(qemu_img_pipe("measure", "--output", "json", *args))
Signature · 1 line
2.34.1
PATCH v2 7/18 iotests: use qemu_img_json() when applicable
In reply to John SnowThese functions should now give better crash information when something unexpected happens.
--- tests/qemu-iotests/iotests.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-)
tests/qemu-iotests/iotests.py +4 -4
@@ -344,11 +344,11 @@ def qemu_img_json(*args: str) -> Any: json_data = json.loads(res.stdout) return json_data -def qemu_img_measure(*args): - return json.loads(qemu_img_pipe("measure", "--output", "json", *args)) +def qemu_img_measure(*args: str) -> Any: + return qemu_img_json("measure", "--output", "json", *args) -def qemu_img_check(*args): - return json.loads(qemu_img_pipe("check", "--output", "json", *args)) +def qemu_img_check(*args: str) -> Any: + return qemu_img_json("check", "--output", "json", *args) def qemu_img_pipe(*args: str) -> str: '''Run qemu-img and return its output'''
Signature · 1 line
2.34.1
PATCH v2 8/18 iotests: add qemu_img_info()
In reply to John SnowAdd qemu_img_info() by analogy with qemu_img_{measure,check}. Modify image_size() to use this function instead.
--- tests/qemu-iotests/065 | 5 ++--- tests/qemu-iotests/242 | 5 ++--- tests/qemu-iotests/iotests.py | 12 ++++++++---- 3 files changed, 12 insertions(+), 10 deletions(-)
tests/qemu-iotests/065 +2 -3
@@ -24,7 +24,7 @@ import os import re import json import iotests -from iotests import qemu_img, qemu_img_pipe +from iotests import qemu_img, qemu_img_info, qemu_img_pipe import unittest test_img = os.path.join(iotests.test_dir, 'test.img')
@@ -49,8 +49,7 @@ class TestQemuImgInfo(TestImageInfoSpecific): human_compare = None def test_json(self): - data = json.loads(qemu_img_pipe('info', '--output=json', test_img)) - data = data['format-specific'] + data = qemu_img_info(test_img)['format-specific'] self.assertEqual(data['type'], iotests.imgfmt) self.assertEqual(data['data'], self.json_compare)
tests/qemu-iotests/242 +2 -3
@@ -22,7 +22,7 @@ import iotests import json import struct -from iotests import qemu_img_create, qemu_io, qemu_img_pipe, \ +from iotests import qemu_img_create, qemu_io, qemu_img_info, \ file_path, img_info_log, log, filter_qemu_io iotests.script_initialize(supported_fmts=['qcow2'],
@@ -39,8 +39,7 @@ flag_offset = 0x5000f def print_bitmap(extra_args): log('qemu-img info dump:\n') img_info_log(disk, extra_args=extra_args) - result = json.loads(qemu_img_pipe('info', '--force-share', - '--output=json', disk)) + result = qemu_img_info('--force-share', disk) if 'bitmaps' in result['format-specific']['data']: bitmaps = result['format-specific']['data']['bitmaps'] log('The same bitmaps in JSON format:')
tests/qemu-iotests/iotests.py +8 -4
@@ -350,6 +350,9 @@ def qemu_img_measure(*args: str) -> Any: def qemu_img_check(*args: str) -> Any: return qemu_img_json("check", "--output", "json", *args) +def qemu_img_info(*args: str) -> Any: + return qemu_img_json('info', "--output", "json", *args) + def qemu_img_pipe(*args: str) -> str: '''Run qemu-img and return its output''' return qemu_img_pipe_and_status(*args)[0]
@@ -568,10 +571,11 @@ def create_image(name, size): file.write(sector) i = i + 512 -def image_size(img): - '''Return image's virtual size''' - r = qemu_img_pipe('info', '--output=json', '-f', imgfmt, img) - return json.loads(r)['virtual-size'] +def image_size(img: str) -> int: + """Return image's virtual size""" + value = qemu_img_info('-f', imgfmt, img)['virtual-size'] + assert isinstance(value, int) + return value def is_str(val): return isinstance(val, str)
Signature · 1 line
2.34.1
PATCH v2 9/18 iotests: remove-bitmap-from-backing: use qemu_img_info()
In reply to John SnowRemove two more usages of qemu_img_pipe().
--- tests/qemu-iotests/tests/remove-bitmap-from-backing | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-)
tests/qemu-iotests/tests/remove-bitmap-from-backing +3 -3
@@ -19,7 +19,7 @@ # import iotests -from iotests import log, qemu_img_create, qemu_img, qemu_img_pipe +from iotests import log, qemu_img_create, qemu_img, qemu_img_info iotests.script_initialize(supported_fmts=['qcow2'], unsupported_imgopts=['compat'])
@@ -33,7 +33,7 @@ qemu_img_create('-f', iotests.imgfmt, '-b', base, qemu_img('bitmap', '--add', base, 'bitmap0') # Just assert that our method of checking bitmaps in the image works. -assert 'bitmaps' in qemu_img_pipe('info', base) +assert 'bitmaps' in qemu_img_info(base)['format-specific']['data'] vm = iotests.VM().add_drive(top, 'backing.node-name=base') vm.launch()
@@ -68,5 +68,5 @@ if result != {'return': {}}: vm.shutdown() -if 'bitmaps' in qemu_img_pipe('info', base): +if 'bitmaps' in qemu_img_info(base)['format-specific']['data']: log('ERROR: Bitmap is still in the base image')
Signature · 1 line
2.34.1
PATCH v2 10/18 iotests: add qemu_img_map() function
In reply to John SnowBy analogy with qemu_img_{measure, check, info}. Replace calls to qemu_img_pipe('map', '--output=json', ...) with the new function.
--- tests/qemu-iotests/041 | 5 ++--- tests/qemu-iotests/211 | 6 +++--- tests/qemu-iotests/iotests.py | 3 +++ tests/qemu-iotests/tests/block-status-cache | 11 ++++------- tests/qemu-iotests/tests/parallels-read-bitmap | 6 ++---- 5 files changed, 14 insertions(+), 17 deletions(-)
tests/qemu-iotests/041 +2 -3
@@ -24,7 +24,7 @@ import os import re import json import iotests -from iotests import qemu_img, qemu_img_pipe, qemu_io +from iotests import qemu_img, qemu_img_map, qemu_io backing_img = os.path.join(iotests.test_dir, 'backing.img') target_backing_img = os.path.join(iotests.test_dir, 'target-backing.img')
@@ -1360,8 +1360,7 @@ class TestFilters(iotests.QMPTestCase): self.vm.qmp('blockdev-del', node_name='target') - target_map = qemu_img_pipe('map', '--output=json', target_img) - target_map = json.loads(target_map) + target_map = qemu_img_map(target_img) assert target_map[0]['start'] == 0 assert target_map[0]['length'] == 512 * 1024
tests/qemu-iotests/211 +3 -3
@@ -59,7 +59,7 @@ with iotests.FilePath('t.vdi') as disk_path, \ vm.shutdown() iotests.img_info_log(disk_path) - iotests.log(iotests.qemu_img_pipe('map', '--output=json', disk_path)) + iotests.log(iotests.qemu_img_map(disk_path)) # # Successful image creation (explicit defaults)
@@ -83,7 +83,7 @@ with iotests.FilePath('t.vdi') as disk_path, \ vm.shutdown() iotests.img_info_log(disk_path) - iotests.log(iotests.qemu_img_pipe('map', '--output=json', disk_path)) + iotests.log(iotests.qemu_img_map(disk_path)) # # Successful image creation (with non-default options)
@@ -107,7 +107,7 @@ with iotests.FilePath('t.vdi') as disk_path, \ vm.shutdown() iotests.img_info_log(disk_path) - iotests.log(iotests.qemu_img_pipe('map', '--output=json', disk_path)) + iotests.log(iotests.qemu_img_map(disk_path)) # # Invalid BlockdevRef
tests/qemu-iotests/iotests.py +3 -0
@@ -353,6 +353,9 @@ def qemu_img_check(*args: str) -> Any: def qemu_img_info(*args: str) -> Any: return qemu_img_json('info', "--output", "json", *args) +def qemu_img_map(*args: str) -> Any: + return qemu_img_json('map', "--output", "json", *args) + def qemu_img_pipe(*args: str) -> str: '''Run qemu-img and return its output''' return qemu_img_pipe_and_status(*args)[0]
tests/qemu-iotests/tests/block-status-cache +4 -7
@@ -22,7 +22,7 @@ import os import signal import iotests -from iotests import qemu_img_create, qemu_img_pipe, qemu_nbd +from iotests import qemu_img_create, qemu_img_map, qemu_nbd image_size = 1 * 1024 * 1024
@@ -76,8 +76,7 @@ class TestBscWithNbd(iotests.QMPTestCase): # to allocate the first sector to facilitate alignment probing), and # then the rest to be zero. The BSC will thus contain (if anything) # one range covering the first sector. - map_pre = qemu_img_pipe('map', '--output=json', '--image-opts', - nbd_img_opts) + map_pre = qemu_img_map('--image-opts', nbd_img_opts) # qemu:allocation-depth maps for want_zero=false. # want_zero=false should (with the file driver, which the server is
@@ -111,14 +110,12 @@ class TestBscWithNbd(iotests.QMPTestCase): # never loop too many times here. for _ in range(2): # (Ignore the result, this is just to contaminate the cache) - qemu_img_pipe('map', '--output=json', '--image-opts', - nbd_img_opts_alloc_depth) + qemu_img_map('--image-opts', nbd_img_opts_alloc_depth) # Now let's see whether the cache reports everything as data, or # whether we get correct information (i.e. the same as we got on our # first attempt). - map_post = qemu_img_pipe('map', '--output=json', '--image-opts', - nbd_img_opts) + map_post = qemu_img_map('--image-opts', nbd_img_opts) if map_pre != map_post: print('ERROR: Map information differs before and after querying ' +
tests/qemu-iotests/tests/parallels-read-bitmap +2 -4
@@ -18,9 +18,8 @@ # along with this program. If not, see <http://www.gnu.org/licenses/>. # -import json import iotests -from iotests import qemu_nbd_popen, qemu_img_pipe, log, file_path +from iotests import qemu_nbd_popen, qemu_img_map, log, file_path iotests.script_initialize(supported_fmts=['parallels'])
@@ -36,8 +35,7 @@ iotests.unarchive_sample_image('parallels-with-bitmap', disk) with qemu_nbd_popen('--read-only', f'--socket={nbd_sock}', f'--bitmap={bitmap}', '-f', iotests.imgfmt, disk): - out = qemu_img_pipe('map', '--output=json', '--image-opts', nbd_opts) - chunks = json.loads(out) + chunks = qemu_img_map('--image-opts', nbd_opts) cluster = 64 * 1024 log('dirty clusters (cluster size is 64K):')
Signature · 1 line
2.34.1
PATCH v2 11/18 iotests: change supports_quorum to use qemu_img
In reply to John SnowSimilar to other recent changes: use the qemu_img invocation that supports throwing loud, nasty exceptions when it fails for surprising reasons.
(Why would "--help" ever fail? I don't know, but consistency is like a well-manicured bonsai.)
--- tests/qemu-iotests/iotests.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
tests/qemu-iotests/iotests.py +2 -2
@@ -1428,8 +1428,8 @@ def _verify_imgopts(unsupported: Sequence[str] = ()) -> None: notrun(f'not suitable for this imgopts: {imgopts}') -def supports_quorum(): - return 'quorum' in qemu_img_pipe('--help') +def supports_quorum() -> bool: + return 'quorum' in qemu_img('--help').stdout def verify_quorum(): '''Skip test suite if quorum support is not available'''
Signature · 1 line
2.34.1
PATCH v2 12/18 iotests: replace unchecked calls to qemu_img_pipe()
In reply to John Snowqemu_img_pipe() discards the return code in favor of returning just the output. Some tests using this function don't save, log, or check the output either, though. Replace those calls to a checked version as appropriate.
Tests affected are 194, 202, 203, 234, 262, and 303.
--- tests/qemu-iotests/194 | 4 ++-- tests/qemu-iotests/202 | 4 ++-- tests/qemu-iotests/203 | 4 ++-- tests/qemu-iotests/234 | 4 ++-- tests/qemu-iotests/262 | 2 +- tests/qemu-iotests/303 | 2 +- 6 files changed, 10 insertions(+), 10 deletions(-)
tests/qemu-iotests/194 +2 -2
@@ -33,8 +33,8 @@ with iotests.FilePath('source.img') as source_img_path, \ iotests.VM('dest') as dest_vm: img_size = '1G' - iotests.qemu_img_pipe('create', '-f', iotests.imgfmt, source_img_path, img_size) - iotests.qemu_img_pipe('create', '-f', iotests.imgfmt, dest_img_path, img_size) + iotests.qemu_img_create('-f', iotests.imgfmt, source_img_path, img_size) + iotests.qemu_img_create('-f', iotests.imgfmt, dest_img_path, img_size) iotests.log('Launching VMs...') (source_vm.add_drive(source_img_path)
tests/qemu-iotests/202 +2 -2
@@ -35,8 +35,8 @@ with iotests.FilePath('disk0.img') as disk0_img_path, \ iotests.VM() as vm: img_size = '10M' - iotests.qemu_img_pipe('create', '-f', iotests.imgfmt, disk0_img_path, img_size) - iotests.qemu_img_pipe('create', '-f', iotests.imgfmt, disk1_img_path, img_size) + iotests.qemu_img_create('-f', iotests.imgfmt, disk0_img_path, img_size) + iotests.qemu_img_create('-f', iotests.imgfmt, disk1_img_path, img_size) iotests.log('Launching VM...') vm.launch()
tests/qemu-iotests/203 +2 -2
@@ -33,8 +33,8 @@ with iotests.FilePath('disk0.img') as disk0_img_path, \ iotests.VM() as vm: img_size = '10M' - iotests.qemu_img_pipe('create', '-f', iotests.imgfmt, disk0_img_path, img_size) - iotests.qemu_img_pipe('create', '-f', iotests.imgfmt, disk1_img_path, img_size) + iotests.qemu_img_create('-f', iotests.imgfmt, disk0_img_path, img_size) + iotests.qemu_img_create('-f', iotests.imgfmt, disk1_img_path, img_size) iotests.log('Launching VM...') (vm.add_object('iothread,id=iothread0')
tests/qemu-iotests/234 +2 -2
@@ -34,8 +34,8 @@ with iotests.FilePath('img') as img_path, \ iotests.VM(path_suffix='a') as vm_a, \ iotests.VM(path_suffix='b') as vm_b: - iotests.qemu_img_pipe('create', '-f', iotests.imgfmt, backing_path, '64M') - iotests.qemu_img_pipe('create', '-f', iotests.imgfmt, img_path, '64M') + iotests.qemu_img_create('-f', iotests.imgfmt, backing_path, '64M') + iotests.qemu_img_create('-f', iotests.imgfmt, img_path, '64M') os.mkfifo(fifo_a) os.mkfifo(fifo_b)
tests/qemu-iotests/262 +1 -1
@@ -51,7 +51,7 @@ with iotests.FilePath('img') as img_path, \ vm.add_device('virtio-blk,drive=%s,iothread=iothread0' % root) - iotests.qemu_img_pipe('create', '-f', iotests.imgfmt, img_path, '64M') + iotests.qemu_img_create('-f', iotests.imgfmt, img_path, '64M') os.mkfifo(fifo)
tests/qemu-iotests/303 +1 -1
@@ -38,7 +38,7 @@ def create_bitmap(bitmap_number, disabled): if disabled: args.append('--disable') - iotests.qemu_img_pipe(*args) + iotests.qemu_img(*args) def write_to_disk(offset, size):
Signature · 1 line
2.34.1
PATCH v2 13/18 iotests: remove external calls to qemu_img_pipe()
In reply to John SnowSeveral cases here rely on the knowledge that qemu_img_pipe() suppresses *all* output on a successful case when the command being issued is 'create'.
065: This call's output is inspected, but it appears as if it's expected
to succeed. Replace this call with the checked qemu_img() variant instead to get better diagnostics if/when qemu-img itself fails.
149: If the check_cipher_support check activates, we'll skip the
test. Otherwise, we re-raise the Exception and assert that the image creation works.
237: We are only testing blanks against the output.
Remove them and use a simpler checked variant.
296: One create and one amend call. The create call is expected to
always succeed, but it needs a print statement to keep the output file looking nice. The amend call is an intentional negative test; use check=False and log the output.
After this patch, the only uses of qemu_img_pipe are internal to iotests.py and will be removed in subsequent patches.
--- tests/qemu-iotests/065 | 4 ++-- tests/qemu-iotests/149 | 8 ++++++-- tests/qemu-iotests/237 | 3 +-- tests/qemu-iotests/237.out | 3 --- tests/qemu-iotests/296 | 13 +++++++------ 5 files changed, 16 insertions(+), 15 deletions(-)
tests/qemu-iotests/065 +2 -2
@@ -24,7 +24,7 @@ import os import re import json import iotests -from iotests import qemu_img, qemu_img_info, qemu_img_pipe +from iotests import qemu_img, qemu_img_info import unittest test_img = os.path.join(iotests.test_dir, 'test.img')
@@ -54,7 +54,7 @@ class TestQemuImgInfo(TestImageInfoSpecific): self.assertEqual(data['data'], self.json_compare) def test_human(self): - data = qemu_img_pipe('info', '--output=human', test_img).split('\n') + data = qemu_img('info', '--output=human', test_img).stdout.split('\n') data = data[(data.index('Format specific information:') + 1) :data.index('')] for field in data:
tests/qemu-iotests/149 +6 -2
@@ -265,8 +265,12 @@ def qemu_img_create(config, size_mb): "%dM" % size_mb] iotests.log("qemu-img " + " ".join(args), filters=[iotests.filter_test_dir]) - iotests.log(check_cipher_support(config, iotests.qemu_img_pipe(*args)), - filters=[iotests.filter_test_dir]) + try: + iotests.qemu_img(*args) + except subprocess.CalledProcessError as exc: + iotests.log(check_cipher_support(config, exc.output), + filters=[iotests.filter_test_dir]) + raise def qemu_io_image_args(config, dev=False): """Get the args for access an image or device with qemu-io"""
tests/qemu-iotests/237 +1 -2
@@ -165,8 +165,7 @@ with iotests.FilePath('t.vmdk') as disk_path, \ iotests.log("") for path in [ extent1_path, extent2_path, extent3_path ]: - msg = iotests.qemu_img_pipe('create', '-f', imgfmt, path, '0') - iotests.log(msg, [iotests.filter_testfiles]) + iotests.qemu_img_create('-f', imgfmt, path, '0') vm.add_blockdev('driver=file,filename=%s,node-name=ext1' % (extent1_path)) vm.add_blockdev('driver=file,filename=%s,node-name=ext2' % (extent2_path))
tests/qemu-iotests/237.out +0 -3
@@ -129,9 +129,6 @@ Job failed: Cannot find device='this doesn't exist' nor node-name='this doesn't === Other subformats === - - - == Missing extent == {"execute": "blockdev-create", "arguments": {"job-id": "job0", "options": {"driver": "vmdk", "file": "node0", "size": 33554432, "subformat": "monolithicFlat"}}}
tests/qemu-iotests/296 +7 -6
@@ -76,7 +76,7 @@ class EncryptionSetupTestCase(iotests.QMPTestCase): # create the encrypted block device using qemu-img def createImg(self, file, secret): - output = iotests.qemu_img_pipe( + iotests.qemu_img( 'create', '--object', *secret.to_cmdline_object(), '-f', iotests.imgfmt,
@@ -85,7 +85,7 @@ class EncryptionSetupTestCase(iotests.QMPTestCase): file, '1M') - iotests.log(output, filters=[iotests.filter_test_dir]) + print('') # Keeps 296.out prettier. # attempts to add a key using qemu-img def addKey(self, file, secret, new_secret):
@@ -99,7 +99,7 @@ class EncryptionSetupTestCase(iotests.QMPTestCase): } } - output = iotests.qemu_img_pipe( + ret = iotests.qemu_img( 'amend', '--object', *secret.to_cmdline_object(), '--object', *new_secret.to_cmdline_object(),
@@ -108,10 +108,11 @@ class EncryptionSetupTestCase(iotests.QMPTestCase): '-o', 'new-secret=' + new_secret.id(), '-o', 'iter-time=10', - "json:" + json.dumps(image_options) - ) + "json:" + json.dumps(image_options), + check=False # Expected to fail, output is logged. + ) - iotests.log(output, filters=[iotests.filter_test_dir]) + iotests.log(ret.stdout, filters=[iotests.filter_test_dir]) ########################################################################### # open an encrypted block device
Signature · 1 line
2.34.1
PATCH v2 14/18 iotests: move has_working_luks onto qemu_img()
In reply to John SnowAdmittedly a mostly lateral move; the diagnostics are slightly better on program crash.
--- tests/qemu-iotests/iotests.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-)
tests/qemu-iotests/iotests.py +9 -9
@@ -1445,20 +1445,20 @@ def has_working_luks() -> Tuple[bool, str]: """ img_file = f'{test_dir}/luks-test.luks' - (output, status) = \ - qemu_img_pipe_and_status('create', '-f', 'luks', - '--object', luks_default_secret_object, - '-o', luks_default_key_secret_opt, - '-o', 'iter-time=10', - img_file, '1G') + res = qemu_img('create', '-f', 'luks', + '--object', luks_default_secret_object, + '-o', luks_default_key_secret_opt, + '-o', 'iter-time=10', + img_file, '1G', + check=False) try: os.remove(img_file) except OSError: pass - if status != 0: - reason = output - for line in output.splitlines(): + if res.returncode: + reason = res.stdout + for line in res.stdout.splitlines(): if img_file + ':' in line: reason = line.split(img_file + ':', 1)[1].strip() break
Signature · 1 line
2.34.1
PATCH v2 15/18 iotests: remove qemu_img_log('create', ...) calls
In reply to John Snowqemu_img_log() calls into qemu_img_pipe(), which always removes output for 'create' commands on success anyway. Replace all of these calls to the simpler qemu_img_create(...) which doesn't log, but raises a detailed exception object on failure instead.
Blank lines are removed from output files where appropriate.
--- tests/qemu-iotests/255 | 8 ++++---- tests/qemu-iotests/255.out | 4 ---- tests/qemu-iotests/274 | 17 ++++++++--------- tests/qemu-iotests/274.out | 29 ----------------------------- tests/qemu-iotests/280 | 2 +- tests/qemu-iotests/280.out | 1 - 6 files changed, 13 insertions(+), 48 deletions(-)
tests/qemu-iotests/255 +4 -4
@@ -42,8 +42,8 @@ with iotests.FilePath('t.qcow2') as disk_path, \ size_str = str(size) iotests.create_image(base_path, size) - iotests.qemu_img_log('create', '-f', iotests.imgfmt, mid_path, size_str) - iotests.qemu_img_log('create', '-f', iotests.imgfmt, disk_path, size_str) + iotests.qemu_img_create('-f', iotests.imgfmt, mid_path, size_str) + iotests.qemu_img_create('-f', iotests.imgfmt, disk_path, size_str) # Create a backing chain like this: # base <- [throttled: bps-read=4096] <- mid <- overlay
@@ -92,8 +92,8 @@ with iotests.FilePath('src.qcow2') as src_path, \ size = 128 * 1024 * 1024 size_str = str(size) - iotests.qemu_img_log('create', '-f', iotests.imgfmt, src_path, size_str) - iotests.qemu_img_log('create', '-f', iotests.imgfmt, dst_path, size_str) + iotests.qemu_img_create('-f', iotests.imgfmt, src_path, size_str) + iotests.qemu_img_create('-f', iotests.imgfmt, dst_path, size_str) iotests.log(iotests.qemu_io('-f', iotests.imgfmt, '-c', 'write 0 1M', src_path),
tests/qemu-iotests/255.out +0 -4
@@ -3,8 +3,6 @@ Finishing a commit job with background reads === Create backing chain and start VM === - - === Start background read requests === === Run a commit job ===
@@ -21,8 +19,6 @@ Closing the VM while a job is being cancelled === Create images and start VM === - - wrote 1048576/1048576 bytes at offset 0 1 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
tests/qemu-iotests/274 +8 -9
@@ -31,12 +31,11 @@ size_long = 2 * 1024 * 1024 size_diff = size_long - size_short def create_chain() -> None: - iotests.qemu_img_log('create', '-f', iotests.imgfmt, base, - str(size_long)) - iotests.qemu_img_log('create', '-f', iotests.imgfmt, '-b', base, - '-F', iotests.imgfmt, mid, str(size_short)) - iotests.qemu_img_log('create', '-f', iotests.imgfmt, '-b', mid, - '-F', iotests.imgfmt, top, str(size_long)) + iotests.qemu_img_create('-f', iotests.imgfmt, base, str(size_long)) + iotests.qemu_img_create('-f', iotests.imgfmt, '-b', base, + '-F', iotests.imgfmt, mid, str(size_short)) + iotests.qemu_img_create('-f', iotests.imgfmt, '-b', mid, + '-F', iotests.imgfmt, top, str(size_long)) iotests.qemu_io_log('-c', 'write -P 1 0 %d' % size_long, base)
@@ -160,9 +159,9 @@ with iotests.FilePath('base') as base, \ ('off', '512k', '256k', '500k', '436k')]: iotests.log('=== preallocation=%s ===' % prealloc) - iotests.qemu_img_log('create', '-f', iotests.imgfmt, base, base_size) - iotests.qemu_img_log('create', '-f', iotests.imgfmt, '-b', base, - '-F', iotests.imgfmt, top, top_size_old) + iotests.qemu_img_create('-f', iotests.imgfmt, base, base_size) + iotests.qemu_img_create('-f', iotests.imgfmt, '-b', base, + '-F', iotests.imgfmt, top, top_size_old) iotests.qemu_io_log('-c', 'write -P 1 %s 64k' % off, base) # After this, top_size_old to base_size should be allocated/zeroed.
tests/qemu-iotests/274.out +0 -29
@@ -1,7 +1,4 @@ == Commit tests == - - - wrote 2097152/2097152 bytes at offset 0 2 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
@@ -63,9 +60,6 @@ read 1048576/1048576 bytes at offset 1048576 1 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec) === Testing HMP commit (top -> mid) === - - - wrote 2097152/2097152 bytes at offset 0 2 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
@@ -92,9 +86,6 @@ read 1048576/1048576 bytes at offset 1048576 1 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec) === Testing QMP active commit (top -> mid) === - - - wrote 2097152/2097152 bytes at offset 0 2 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
@@ -127,9 +118,6 @@ read 1048576/1048576 bytes at offset 1048576 1 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec) === Testing qemu-img commit (top -> base) === - - - wrote 2097152/2097152 bytes at offset 0 2 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
@@ -154,9 +142,6 @@ read 1048576/1048576 bytes at offset 1048576 1 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec) === Testing QMP active commit (top -> base) === - - - wrote 2097152/2097152 bytes at offset 0 2 MiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
@@ -190,8 +175,6 @@ read 1048576/1048576 bytes at offset 1048576 == Resize tests == === preallocation=off === - - wrote 65536/65536 bytes at offset 5368709120 64 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
@@ -207,8 +190,6 @@ read 65536/65536 bytes at offset 5368709120 { "start": 1073741824, "length": 7516192768, "depth": 0, "present": true, "zero": true, "data": false}] === preallocation=metadata === - - wrote 65536/65536 bytes at offset 33285996544 64 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
@@ -229,8 +210,6 @@ read 65536/65536 bytes at offset 33285996544 { "start": 34896609280, "length": 536870912, "depth": 0, "present": true, "zero": true, "data": false, "offset": 2685075456}] === preallocation=falloc === - - wrote 65536/65536 bytes at offset 9437184 64 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
@@ -246,8 +225,6 @@ read 65536/65536 bytes at offset 9437184 { "start": 5242880, "length": 10485760, "depth": 0, "present": true, "zero": false, "data": true, "offset": 327680}] === preallocation=full === - - wrote 65536/65536 bytes at offset 11534336 64 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
@@ -263,8 +240,6 @@ read 65536/65536 bytes at offset 11534336 { "start": 8388608, "length": 4194304, "depth": 0, "present": true, "zero": false, "data": true, "offset": 327680}] === preallocation=off === - - wrote 65536/65536 bytes at offset 259072 64 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
@@ -281,8 +256,6 @@ read 65536/65536 bytes at offset 259072 { "start": 262144, "length": 262144, "depth": 0, "present": true, "zero": true, "data": false}] === preallocation=off === - - wrote 65536/65536 bytes at offset 344064 64 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
@@ -298,8 +271,6 @@ read 65536/65536 bytes at offset 344064 { "start": 262144, "length": 262144, "depth": 0, "present": true, "zero": true, "data": false}] === preallocation=off === - - wrote 65536/65536 bytes at offset 446464 64 KiB, X ops; XX:XX:XX.X (XXX YYY/sec and XXX ops/sec)
tests/qemu-iotests/280 +1 -1
@@ -33,7 +33,7 @@ with iotests.FilePath('base') as base_path , \ iotests.FilePath('top') as top_path, \ iotests.VM() as vm: - iotests.qemu_img_log('create', '-f', iotests.imgfmt, base_path, '64M') + iotests.qemu_img_create('-f', iotests.imgfmt, base_path, '64M') iotests.log('=== Launch VM ===') vm.add_object('iothread,id=iothread0')
tests/qemu-iotests/280.out +0 -1
@@ -1,4 +1,3 @@ - === Launch VM === Enabling migration QMP events on VM... {"return": {}}
Signature · 1 line
2.34.1
PATCH v2 16/18 iotests: remove qemu_img_pipe()
In reply to John SnowWith the exceptional 'create' calls removed in the prior commit, change qemu_img_log() and img_info_log() to call qemu_img() directly instead.
In keeping with the spirit of diff-based tests, allow these calls to qemu_img() to return an unchecked non-zero status code -- because any error we'd see from the output is going into the log anyway.
Every last call to qemu-img is now either checked for a return code of zero or has its output logged. It should be very hard to accidentally ignore the return code *or* output from qemu-img now; intentional malice remains unhandled.
--- tests/qemu-iotests/iotests.py | 26 +++++++------------------- 1 file changed, 7 insertions(+), 19 deletions(-)
tests/qemu-iotests/iotests.py +7 -19
@@ -240,15 +240,6 @@ def qemu_img_create_prepare_args(args: List[str]) -> List[str]: return result -def qemu_img_pipe_and_status(*args: str) -> Tuple[str, int]: - """ - Run qemu-img and return both its output and its exit code - """ - is_create = bool(args and args[0] == 'create') - full_args = qemu_img_args + qemu_img_create_prepare_args(list(args)) - return qemu_tool_pipe_and_status('qemu-img', full_args, - drop_successful_output=is_create) - def qemu_img(*args: str, check: bool = True, combine_stdio: bool = True ) -> subprocess.CompletedProcess[str]: """
@@ -356,17 +347,14 @@ def qemu_img_info(*args: str) -> Any: def qemu_img_map(*args: str) -> Any: return qemu_img_json('map', "--output", "json", *args) -def qemu_img_pipe(*args: str) -> str: - '''Run qemu-img and return its output''' - return qemu_img_pipe_and_status(*args)[0] - -def qemu_img_log(*args): - result = qemu_img_pipe(*args) - log(result, filters=[filter_testfiles]) +def qemu_img_log(*args: str) -> subprocess.CompletedProcess[str]: + result = qemu_img(*args, check=False) + log(result.stdout, filters=[filter_testfiles]) return result -def img_info_log(filename, filter_path=None, use_image_opts=False, - extra_args=()): +def img_info_log(filename: str, filter_path: Optional[str] = None, + use_image_opts: bool = False, extra_args: Sequence[str] = (), + ) -> None: args = ['info'] if use_image_opts: args.append('--image-opts')
@@ -375,7 +363,7 @@ def img_info_log(filename, filter_path=None, use_image_opts=False, args += extra_args args.append(filename) - output = qemu_img_pipe(*args) + output = qemu_img(*args, check=False).stdout if not filter_path: filter_path = filename log(filter_img_info(output, filter_path))
Signature · 1 line
2.34.1
PATCH v2 17/18 iotests: make qemu_img_log() check log level
In reply to John SnowImprove qemu_img_log() to actually check if logging is turned on. If it isn't, revert to the behavior of qemu_img(). This is done so that there really is no way to avoid scrutinizing qemu-ing subprocess calls by accident. You're gonna have to work for it.
--- tests/qemu-iotests/iotests.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-)
tests/qemu-iotests/iotests.py +12 -1
@@ -348,7 +348,13 @@ def qemu_img_map(*args: str) -> Any: return qemu_img_json('map', "--output", "json", *args) def qemu_img_log(*args: str) -> subprocess.CompletedProcess[str]: - result = qemu_img(*args, check=False) + """ + Logged, unchecked variant of qemu_img() that allows non-zero exit codes. + + If logging is perceived to be disabled, this function will behave + like qemu_img() and prohibit non-zero return codes. + """ + result = qemu_img(*args, check=not logging_enabled()) log(result.stdout, filters=[filter_testfiles]) return result
@@ -1635,6 +1641,11 @@ def activate_logging(): test_logger.setLevel(logging.INFO) test_logger.propagate = False +def logging_enabled() -> bool: + """Return True if iotest logging is active.""" + return (test_logger.hasHandlers() + and test_logger.getEffectiveLevel() >= logging.INFO) + # This is called from script-style iotests without a single point of entry def script_initialize(*args, **kwargs): """Initialize script-style tests without running any tests."""
Signature · 1 line
2.34.1
PATCH v2 18/18 iotests: reimplement img_info_log in terms of qemu_img_log
In reply to John SnowNow every last call to qemu_img is certifiably either checked or logged.
--- tests/qemu-iotests/iotests.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-)
tests/qemu-iotests/iotests.py +10 -4
@@ -347,15 +347,20 @@ def qemu_img_info(*args: str) -> Any: def qemu_img_map(*args: str) -> Any: return qemu_img_json('map', "--output", "json", *args) -def qemu_img_log(*args: str) -> subprocess.CompletedProcess[str]: +def qemu_img_log( + *args: str, + filters: Iterable[Callable[[str], str]] = (), +) -> subprocess.CompletedProcess[str]: """ Logged, unchecked variant of qemu_img() that allows non-zero exit codes. If logging is perceived to be disabled, this function will behave like qemu_img() and prohibit non-zero return codes. + + By default, output will be filtered through filter_testfiles(). """ result = qemu_img(*args, check=not logging_enabled()) - log(result.stdout, filters=[filter_testfiles]) + log(result.stdout, filters=filters or [filter_testfiles]) return result def img_info_log(filename: str, filter_path: Optional[str] = None,
@@ -369,10 +374,11 @@ def img_info_log(filename: str, filter_path: Optional[str] = None, args += extra_args args.append(filename) - output = qemu_img(*args, check=False).stdout if not filter_path: filter_path = filename - log(filter_img_info(output, filter_path)) + qemu_img_log( + *args, + filters=[lambda output: filter_img_info(output, filter_path)]) def qemu_io_wrap_args(args: Sequence[str]) -> List[str]: if '-f' in args or '--image-opts' in args:
Signature · 1 line
2.34.1