chiark / gitweb /
09bda9e811a84fc59b897f560272c559a0bba0a5
[chiark-utils.git] / backup / lvm
1 #!/bin/sh
2 # invoked by backup scripts as
3 #    lvm snap $vardir $device $mountpoint
4 #               creates and mounts on $vardir/snap-mount
5 #               creates $vardir/snap-device -> device
6 #    lvm drop $vardir
7
8 set -e
9
10 nargs=$#
11 opmode="$1"
12 vardir="$2"
13 device="$3"
14 mountpoint="$4"
15
16 lvm_lv=chiark-backup
17 lvm_lvtools_opts='-A n'
18 lvm_lvcreate_opts=
19 lvm_lvcreate_args=
20
21 test ! -f /etc/chiark-backup/settings.sh || . /etc/chiark-backup/settings.sh
22
23 case "$nargs.$opmode" in
24 4.snap|2.drop)
25         ;;
26 *)
27         cat >&2 <<'END'
28 usage: .../lvm snap VARDIR DEV MOUNT
29        .../lvm drop VARDIR
30 END
31         exit 1
32         ;;
33 esac
34
35
36 #---------- clean up anything
37
38 snmnt="$vardir/snap-mount"
39 umount -v "$snmnt" || true
40 test ! -d "$snmnt" || rmdir -- "$snmnt"
41
42 set +e
43 old_lv_dev="$(readlink $vardir/snap-device)"
44 rc=$?
45 set -e
46
47 if [ $rc = 0 ]; then
48         set +e
49         lvchange    $lvm_lvtools_opts -a n $old_lv_dev
50         lvremove -f $lvm_lvtools_opts      $old_lv_dev
51         set -e
52         rm $vardir/snap-device
53 fi
54
55 if test "$opmode" = drop; then
56         echo 'lvm snap dropped'
57         exit 0
58 fi
59
60 #---------- create snapshot
61
62 fstype="$(mount | sed -n \
63  "s,^$device on $mountpoint type \([a-z0-9][a-z0-9]*\) .*,-t \1 ,p")"
64
65 if [ -z "$lvm_lvsize_opts" ]; then
66         df="$(df -P -k $device)"
67         blocks="$(printf "%s" "$df" |  sed -n '2,$s,^/dev/[^    ]*[     ][      ]*[0-9][0-9]*[  ][      ]*\([0-9][0-9]*\)[      ].*,\1,p')"
68         lvm_lvsize_opts="-L $blocks"K
69 fi
70
71 lvpath="$(dirname "$device")/$lvm_lv"
72
73 ln -s -- "$lvpath" "$vardir"/snap-device
74
75 sync
76 lvcreate -s \
77         $lvm_lvtools_opts \
78         $lvm_lvsize_opts \
79         -n $lvm_lv \
80         $lvm_lvcreate_opts "$device" $lvm_lvcreate_args
81
82 mkdir -- "$snmnt"
83 mount -v -r $fstype $lvm_mount_opts "$lvpath" "$snmnt"
84
85 echo 'lvm snap activated'