All of lore.kernel.org
 help / color / mirror / Atom feed
From: Eric Blake <eblake@redhat.com>
To: Guillaume Vincke <guillaume.vincke@ovhcloud.com>
Cc: qemu-devel@nongnu.org, qemu-block@nongnu.org,
	 Vladimir Sementsov-Ogievskiy <vsementsov@yandex-team.ru>,
	Kevin Wolf <kwolf@redhat.com>, Hanna Reitz <hreitz@redhat.com>
Subject: Re: [PATCH v4 3/3] iotests: Add coverage for NBD connect thread start delay
Date: Tue, 1 Dec 2026 11:05:34 -0600	[thread overview]
Message-ID: <aw75OAttRL8QCaVW@redhat.com> (raw)
In-Reply-To: <20261130124444.256725-4-guillaume.vincke@ovhcloud.com>

On Mon, Nov 30, 2026 at 01:44:44PM +0100, Guillaume Vincke wrote:
> Test the connect thread starting condition with reconnect-delay=0 when
> the server disconnects after a successful handshake but before running
> operations. Prior to the change to nbd_co_establish_connection(), this
> test would demonstrate two I/O errors. The tests 264 and 277 covering
> reconnection do not use reconnect-delay=0 so this case is not exercised.
> 
> Add a test that provokes multiple errors in order to put an NBD client
> in the above-mentioned situation and shows that the first operation
> starts the connect thread and leads to successful subsequent I/O.
> 
> Add a second test that runs the same actions on a TLS-backed
> connection. When qemu-nbd closes, it leaves nothing in the socket, so
> the closed channel is already detected. As other NBD servers send a

s/send/may send/

> close_notify before closing, this test uses a minimal custom NBD server
> to mimic them. Before shutting it down, the server socket is set to
> non-blocking to avoid waiting for a close_notify response from the
> client, as it will never arrive from a parked channel.
> 
> Signed-off-by: Guillaume Vincke <guillaume.vincke@ovhcloud.com>
> ---
>  tests/qemu-iotests/tests/nbd-stale-connection |  70 ++++++
>  .../tests/nbd-stale-connection.out            |  17 ++
>  .../tests/nbd-stale-tls-connection            | 205 ++++++++++++++++++
>  .../tests/nbd-stale-tls-connection.out        |  14 ++
>  4 files changed, 306 insertions(+)
>  create mode 100755 tests/qemu-iotests/tests/nbd-stale-connection
>  create mode 100644 tests/qemu-iotests/tests/nbd-stale-connection.out
>  create mode 100755 tests/qemu-iotests/tests/nbd-stale-tls-connection
>  create mode 100644 tests/qemu-iotests/tests/nbd-stale-tls-connection.out

Tested-by: Eric Blake <eblake@redhat.com>

> 
> diff --git a/tests/qemu-iotests/tests/nbd-stale-connection b/tests/qemu-iotests/tests/nbd-stale-connection
> new file mode 100755
> index 0000000000..5f559fa22d
> --- /dev/null
> +++ b/tests/qemu-iotests/tests/nbd-stale-connection
> @@ -0,0 +1,70 @@
> +#!/usr/bin/env python3
> +# group: quick

> +++ b/tests/qemu-iotests/tests/nbd-stale-tls-connection
> @@ -0,0 +1,205 @@
> +#!/usr/bin/env python3
> +# group: quick

For both tests, why not also in auto?


> +#
> +# Test the NBD client stale TLS-backed channel discard
> +#
> +# Copyright (C) 2026 OVHcloud
> +#
> +# SPDX-License-Identifier: GPL-2.0-or-later
> +
> +import atexit
> +import os
> +import shutil
> +import socket
> +import ssl
> +import struct
> +import subprocess
> +import threading
> +import time
> +
> +import iotests
> +
> +
> +iotests.script_initialize(supported_fmts=['qcow2'])
> +if shutil.which('openssl') is None:
> +    iotests.notrun('openssl not found')
> +nbd_sock = iotests.file_path('nbd-sock', base_dir=iotests.sock_dir)
> +disk = iotests.file_path('disk')
> +iotests.qemu_img_create('-f', iotests.imgfmt, disk, '1M')
> +volume_size = 1 * 1024 * 1024
> +
> +tls_dir = os.path.join(iotests.test_dir, 'tls')
> +os.mkdir(tls_dir)
> +atexit.register(shutil.rmtree, tls_dir, True)
> +
> +
> +def openssl_req(*args):
> +    common = ['openssl',
> +              'req', '-x509',
> +              '-newkey', 'ed25519',
> +              '-nodes',
> +              '-days', '1']
> +    cmd = common + list(args)
> +    subprocess.run(cmd, check=True, cwd=tls_dir,
> +                   stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

This creates a new throwaway certificate every time the test is
run. Should we be trying to minimize the consumption of host entropy
by reusing a (longer-lived) throwaway certificate that can be shared
between multiple tests, instead of this one-shot approach?  At least,
that's what nbdkit does - its TLS tests reuse a common certificate
with 1-year lifespan.  I'm not opposed to your approach, just making
sure we think about whether it has any drawbacks to CI testing.

> +
> +
> +openssl_req('-subj', '/CN=ca',
> +            '-keyout', 'ca-key.pem',
> +            '-out', 'ca-cert.pem')
> +openssl_req('-CA', 'ca-cert.pem',
> +            '-CAkey', 'ca-key.pem',
> +            '-subj', '/CN=localhost',
> +            '-addext', 'basicConstraints=CA:FALSE',
> +            '-keyout', 'server-key.pem',
> +            '-out', 'server-cert.pem')
> +tls_object = (
> +    f'tls-creds-x509,id=tls0,endpoint=server,dir={tls_dir},verify-peer=off'
> +)
> +
> +
> +def recv_exact(conn, length):
> +    buff = b''
> +    while len(buff) < length:
> +        chunk = conn.recv(length - len(buff))
> +        if not chunk:
> +            raise ConnectionError("Failed to read")
> +        buff += chunk
> +    return buff
> +
> +
> +class MockTLSNBDServer:
> +    NBD_INIT_MAGIC = 0x4e42444d41474943  # "NBDMAGIC"
> +    NBD_OPTS_MAGIC = 0x49484156454f5054  # "IHAVEOPT"
> +    NBD_REP_MAGIC = 0x0003e889045565a9
> +    NBD_FLAG_FIXED_NEWSTYLE = 1
> +    NBD_FLAG_NO_ZEROES = 2
> +    NBD_OPT_STARTTLS = 5
> +    NBD_OPT_GO = 7
> +    NBD_REP_ACK = 1
> +    NBD_REP_INFO = 3
> +    NBD_REP_ERR_UNSUP = 0x80000001  # (1 << 31) | 1
> +    NBD_INFO_EXPORT = 0
> +    NBD_FLAG_HAS_FLAGS = 1

I'm impressed that you went ahead and basically implemented a
bare-bones TLS server just to test this. I don't know if it is worth
merging some of this implementation with
qemu-iotests/nbd-fault-injector.py to be more reusable across other
NBD TLS tests.  Still, './run tests/qemu-iotests/check 297' (our
linter test) didn't complain about too much code repetition, so I'm
not going to hold up this series by insisting on such refactoring.

> +
> +    def __init__(self):
> +        self._thread = threading.Thread(target=self.run)
> +        self._close = threading.Event()
> +        self._sock = socket.socket(socket.AF_UNIX)
> +        self._ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
> +        self._ssl_ctx.load_cert_chain(os.path.join(tls_dir, 'server-cert.pem'),
> +                                      os.path.join(tls_dir, 'server-key.pem'))
> +
> +    def __enter__(self):
> +        if os.path.exists(nbd_sock):
> +            os.remove(nbd_sock)
> +        self._sock.bind(nbd_sock)
> +        self._sock.listen(1)
> +        self._thread.start()
> +        return self
> +
> +    def __exit__(self, exc_type, exc, tb):
> +        self._close.set()
> +        self._thread.join()
> +        os.remove(nbd_sock)
> +
> +    @staticmethod
> +    def send_reply(conn, opt, resp, data=b''):
> +        conn.sendall(struct.pack(
> +            '>QIII', MockTLSNBDServer.NBD_REP_MAGIC,
> +            opt, resp, len(data)) + data)
> +
> +    def run(self):
> +        conn, _ = self._sock.accept()
> +        conn.sendall(struct.pack(
> +            '>QQH', self.NBD_INIT_MAGIC, self.NBD_OPTS_MAGIC,
> +            self.NBD_FLAG_FIXED_NEWSTYLE | self.NBD_FLAG_NO_ZEROES))
> +        recv_exact(conn, 4)
> +        while True:
> +            _, opt, length = struct.unpack('>QII', recv_exact(conn, 16))
> +            recv_exact(conn, length)
> +
> +            if opt == self.NBD_OPT_STARTTLS:
> +                self.send_reply(conn, opt, self.NBD_REP_ACK)
> +                conn = self._ssl_ctx.wrap_socket(conn, server_side=True)
> +            elif opt == self.NBD_OPT_GO:
> +                data = struct.pack(
> +                    '>HQH', self.NBD_INFO_EXPORT,
> +                    volume_size, self.NBD_FLAG_HAS_FLAGS)
> +                self.send_reply(conn, opt, self.NBD_REP_INFO, data)
> +                self.send_reply(conn, opt, self.NBD_REP_ACK)
> +                break

This server appears to accept NBD_OPT_GO even when NBD_OPT_STARTTLS
was not attempted first. In the context of the test, this doesn't
matter (the client is QEMU configured to request TLS), but it may
cause oddities if this mock server is reused in more places with a
client that does not want TLS.  Again, not a show-stopper; our mock
server does NOT need to aim for 100% NBD protocol compliance, just
enough that it lets the test cover the client code we care about.

> +            else:
> +                self.send_reply(conn, opt, self.NBD_REP_ERR_UNSUP)
> +
> +        conn.setblocking(False)  # don't wait for the peer's close_notify
> +        self._close.wait()
> +        try:
> +            conn.unwrap()
> +        except ssl.SSLWantReadError:
> +            # a parked channel does not reply
> +            pass
> +        conn.close()
> +        self._sock.close()
> +

-- 
Eric Blake, Principal Software Engineer
Red Hat, Inc.
Virtualization:  qemu.org | libguestfs.org



      reply	other threads:[~2026-12-01 17:06 UTC|newest]

Thread overview: 7+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-11-30 12:44 [PATCH v4 0/3] nbd/client-connection: Fix client returning a closed channel Guillaume Vincke
2026-11-30 12:44 ` [PATCH v4 1/3] " Guillaume Vincke
2026-12-01 17:14   ` Daniel P. Berrangé
2026-11-30 12:44 ` [PATCH v4 2/3] nbd/client-connection: Fix client returning a closed TLS channel Guillaume Vincke
2026-12-01 16:23   ` Eric Blake
2026-11-30 12:44 ` [PATCH v4 3/3] iotests: Add coverage for NBD connect thread start delay Guillaume Vincke
2026-12-01 17:05   ` Eric Blake [this message]

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=aw75OAttRL8QCaVW@redhat.com \
    --to=eblake@redhat.com \
    --cc=guillaume.vincke@ovhcloud.com \
    --cc=hreitz@redhat.com \
    --cc=kwolf@redhat.com \
    --cc=qemu-block@nongnu.org \
    --cc=qemu-devel@nongnu.org \
    --cc=vsementsov@yandex-team.ru \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.