2 # -*- shell-script-mode -*-
4 # Helpers for NBD server related config
6 # Copyright (C) 2018 Red Hat, Inc.
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 2 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
22 nbd_unix_socket
="${SOCK_DIR}/qemu-nbd.sock"
23 nbd_tcp_addr
="127.0.0.1"
24 nbd_pid_file
="${TEST_DIR}/qemu-nbd.pid"
25 nbd_stderr_fifo
="${TEST_DIR}/qemu-nbd.fifo"
27 # If bash version is >= 4.1, this will be overwritten by a dynamically
28 # assigned file descriptor value.
34 if [ -f "$nbd_pid_file" ]; then
35 read NBD_PID
< "$nbd_pid_file"
37 if [ -n "$NBD_PID" ]; then
41 rm -f "$nbd_unix_socket" "$nbd_stderr_fifo"
44 nbd_server_start_unix_socket
()
47 $QEMU_NBD -v -t -k "$nbd_unix_socket" --fork "$@"
50 nbd_server_start_tcp_socket
()
54 mkfifo "$nbd_stderr_fifo"
55 for ((port
= 10809; port
<= 10909; port
++))
57 # Redirect stderr to FIFO, so we can later decide whether we
58 # want to read it or to redirect it to our stderr, depending
59 # on whether the command fails or not
60 $QEMU_NBD -v -t -b $nbd_tcp_addr -p $port --fork "$@" \
61 2> "$nbd_stderr_fifo" &
63 # Taken from common.qemu
64 if [[ "${BASH_VERSINFO[0]}" -ge "5" ||
65 ("${BASH_VERSINFO[0]}" -ge "4" && "${BASH_VERSINFO[1]}" -ge "1") ]]
67 exec {nbd_fifo_fd
}<"$nbd_stderr_fifo"
70 eval "exec ${_nbd_fifo_fd}<'$nbd_stderr_fifo'"
76 # Success, redirect qemu-nbd's stderr to our stderr
78 (cat <&$nbd_fifo_fd >&2) &
79 eval "exec $nbd_fifo_fd>&-"
83 # Failure, read the output
84 output
=$
(cat <&$nbd_fifo_fd)
85 eval "exec $nbd_fifo_fd>&-"
87 if ! echo "$output" |
grep -q "Address already in use"
89 # Unknown error, print it
91 rm -f "$nbd_stderr_fifo"
96 echo "Cannot find free TCP port for nbd in range 10809-10909"
97 rm -f "$nbd_stderr_fifo"