editorial improvements
[rrq/nbd-mount-helper.git] / mount.nbd
1 #!/bin/sh
2 #
3 # Helper script to run an nbd client and mount its device to the given
4 # mount point. This script is invoked by "mount" with
5 # $1 = source (here it's an nbd URL like nbd://server/export
6 # $2 = mount point
7 # $3 = -o
8 # $4 = client and mount options separated by comma
9 #   block-size=N => "-b N"
10 #   connections=N => "-C N"
11 #   timeout=N => "-t N"
12 #
13 # The script starts a nbd-client service client before mounting, and
14 # spawns a cleanup daemon that uses inotify to "discover" unmount to
15 # terminate the service client.
16
17 # Find a free /dev/nbd*
18 for ADM in /dev/nbd* ; do nbd-client -c $ADM > /dev/null || break ; done
19
20 if [ -z "$ADM" ] ; then
21     echo "** No available /dev/nbd* device node" >&2
22     exit 1
23 fi
24
25 if grep -qF " $ADM "  /proc/mounts ; then
26     echo "*** $1 is already mounted" >&2
27     exit 1
28 fi
29
30 # Split up options between partition and loop options
31 POPTS=""
32 LOPTS=""
33 for X in $(echo $4 | tr , ' ') ; do
34     case $X in
35         block-size=*) POPTS="$POPTS -b ${X#*=}" ;;
36         connections=*) POPTS="$POPTS -C ${X#*=}" ;;
37         timeout=*) POPTS="$POPTS -t ${X#*=}" ;;
38         *) LOPTS="$LOPTS,$X" ;;
39     esac
40 done
41
42 # Set up the device node service
43 # $1 = nbd://$host[:$port]/$export
44 read S P N <<EOF
45 $(echo "${1#nbd://}" | sed 's|/| |;s|[ :]| |')
46 EOF
47 [ -z "$N" ] && N=$P && P=
48 [ -z "$P" ] || P="-port $P"
49 POPTS="-persist $POPTS"
50 nbd-client $S $P -name $N $POPTS > /dev/null || exit 1
51
52 sleep 0.2
53 for i in 0 1 2 3 4 5 6 7 8 9 ; do
54     # Loop-mount the nbdfuse "device" and spawn a cleanup daemon
55     if mount -o$LOPTS $ADM "$2" 2> /dev/null ; then
56         # Spawn a process to stop $ADM service when "$2" is umount-ed
57         ( (
58             inotifywait -e delete_self "$2" > /dev/null 2>&1
59             nbd-client -d $ADM
60         ) & ) &
61         exit 0
62     fi
63     sleep 0.2
64 done
65
66 # Coming here if something wrong
67 nbd-client -d $ADM