1#!/usr/bin/env python3
2#
3# Test nbd reconnect on open
4#
5# Copyright (c) 2020 Virtuozzo International GmbH
6#
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program.  If not, see <http://www.gnu.org/licenses/>.
19#
20
21import time
22
23import iotests
24from iotests import qemu_img_create, file_path, qemu_io_popen, qemu_nbd, \
25    qemu_io_log, log
26
27iotests.script_initialize(supported_fmts=['qcow2'])
28
29disk, nbd_sock = file_path('disk', 'nbd-sock')
30
31
32def create_args(open_timeout):
33    return ['--image-opts', '-c', 'read 0 1M',
34            f'driver=nbd,open-timeout={open_timeout},'
35            f'server.type=unix,server.path={nbd_sock}']
36
37
38def check_fail_to_connect(open_timeout):
39    log(f'Check fail to connect with {open_timeout} seconds of timeout')
40
41    start_t = time.time()
42    qemu_io_log(*create_args(open_timeout))
43    delta_t = time.time() - start_t
44
45    max_delta = open_timeout + 0.2
46    if open_timeout <= delta_t <= max_delta:
47        log(f'qemu_io finished in {open_timeout}..{max_delta} seconds, OK')
48    else:
49        note = 'too early' if delta_t < open_timeout else 'too long'
50        log(f'qemu_io finished in {delta_t:.1f} seconds, {note}')
51
52
53qemu_img_create('-f', iotests.imgfmt, disk, '1M')
54
55# Start NBD client when NBD server is not yet running. It should not fail, but
56# wait for 5 seconds for the server to be available.
57client = qemu_io_popen(*create_args(5))
58
59time.sleep(1)
60qemu_nbd('-k', nbd_sock, '-f', iotests.imgfmt, disk)
61
62# client should succeed
63log(client.communicate()[0], filters=[iotests.filter_qemu_io])
64
65# Server was started without --persistent flag, so it should be off now. Let's
66# check it and at the same time check that with open-timeout=0 client fails
67# immediately.
68check_fail_to_connect(0)
69
70# Check that we will fail after non-zero timeout if server is still unavailable
71check_fail_to_connect(1)
72