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 = file_path('disk')
30nbd_sock = file_path('nbd-sock', base_dir=iotests.sock_dir)
31
32
33def create_args(open_timeout):
34    return ['--image-opts', '-c', 'read 0 1M',
35            f'driver=nbd,open-timeout={open_timeout},'
36            f'server.type=unix,server.path={nbd_sock}']
37
38
39def check_fail_to_connect(open_timeout):
40    log(f'Check fail to connect with {open_timeout} seconds of timeout')
41
42    start_t = time.time()
43    qemu_io_log(*create_args(open_timeout), check=False)
44    delta_t = time.time() - start_t
45
46    max_delta = open_timeout + 0.2
47    if open_timeout <= delta_t <= max_delta:
48        log(f'qemu_io finished in {open_timeout}..{max_delta} seconds, OK')
49    else:
50        note = 'too early' if delta_t < open_timeout else 'too long'
51        log(f'qemu_io finished in {delta_t:.1f} seconds, {note}')
52
53
54qemu_img_create('-f', iotests.imgfmt, disk, '1M')
55
56# Start NBD client when NBD server is not yet running. It should not fail, but
57# wait for 5 seconds for the server to be available.
58client = qemu_io_popen(*create_args(5))
59
60time.sleep(1)
61qemu_nbd('-k', nbd_sock, '-f', iotests.imgfmt, disk)
62
63# client should succeed
64log(client.communicate()[0], filters=[iotests.filter_qemu_io])
65
66# Server was started without --persistent flag, so it should be off now. Let's
67# check it and at the same time check that with open-timeout=0 client fails
68# immediately.
69check_fail_to_connect(0)
70
71# Check that we will fail after non-zero timeout if server is still unavailable
72check_fail_to_connect(1)
73