common.nbd (2884B)
1 #!/usr/bin/env bash 2 # -*- shell-script-mode -*- 3 # 4 # Helpers for NBD server related config 5 # 6 # Copyright (C) 2018 Red Hat, Inc. 7 # 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. 12 # 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. 17 # 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/>. 20 # 21 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" 26 27 # If bash version is >= 4.1, this will be overwritten by a dynamically 28 # assigned file descriptor value. 29 nbd_fifo_fd=10 30 31 nbd_server_stop() 32 { 33 local NBD_PID 34 if [ -f "$nbd_pid_file" ]; then 35 read NBD_PID < "$nbd_pid_file" 36 rm -f "$nbd_pid_file" 37 if [ -n "$NBD_PID" ]; then 38 kill "$NBD_PID" 39 fi 40 fi 41 rm -f "$nbd_unix_socket" "$nbd_stderr_fifo" 42 } 43 44 nbd_server_start_unix_socket() 45 { 46 nbd_server_stop 47 $QEMU_NBD -v -t -k "$nbd_unix_socket" --fork "$@" 48 } 49 50 nbd_server_start_tcp_socket() 51 { 52 nbd_server_stop 53 54 mkfifo "$nbd_stderr_fifo" 55 for ((port = 10809; port <= 10909; port++)) 56 do 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" & 62 63 # Taken from common.qemu 64 if [[ "${BASH_VERSINFO[0]}" -ge "5" || 65 ("${BASH_VERSINFO[0]}" -ge "4" && "${BASH_VERSINFO[1]}" -ge "1") ]] 66 then 67 exec {nbd_fifo_fd}<"$nbd_stderr_fifo" 68 else 69 let _nbd_fifo_fd++ 70 eval "exec ${_nbd_fifo_fd}<'$nbd_stderr_fifo'" 71 fi 72 wait $! 73 74 if test $? == 0 75 then 76 # Success, redirect qemu-nbd's stderr to our stderr 77 nbd_tcp_port=$port 78 (cat <&$nbd_fifo_fd >&2) & 79 eval "exec $nbd_fifo_fd>&-" 80 return 81 fi 82 83 # Failure, read the output 84 output=$(cat <&$nbd_fifo_fd) 85 eval "exec $nbd_fifo_fd>&-" 86 87 if ! echo "$output" | grep -q "Address already in use" 88 then 89 # Unknown error, print it 90 echo "$output" >&2 91 rm -f "$nbd_stderr_fifo" 92 exit 1 93 fi 94 done 95 96 echo "Cannot find free TCP port for nbd in range 10809-10909" 97 rm -f "$nbd_stderr_fifo" 98 exit 1 99 }