various minor improvements
[distro-setup] / check-subvol-stale
1 #!/bin/bash
2 # Copyright (C) 2016 Ian Kelling
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15
16 # usage: $0 SUBVOL_MOUNTPOINT...
17 # if latest subvols $@ are not mounted, exit 1, print message, and touch /nocow/btrfs-stale/$subvol
18
19 [[ $EUID == 0 ]] || exec sudo -E "$BASH_SOURCE" "$@"
20
21 set -eE -o pipefail
22 trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" returned $?" >&2' ERR
23
24 shopt -s nullglob
25
26 if [[ ! $@ ]]; then
27 echo "$0: error: expected mountpoint argument"
28 fi
29
30 ret=0
31 for d; do
32 vol=${d##*/}
33 cd /mnt/root/btrbk
34 snaps=($vol.20*)
35 if [[ ! $snaps ]]; then
36 # no snapshots yet
37 continue
38 fi
39 # when a btrbk bugfix makes it into the distro,
40 # we might replace this with btrbk list latest /mnt/root/$vol | ...
41 # note: this is duplicated in mount-latest-subvol
42 last_snap=$(
43 for f in ${snaps[@]}; do
44 printf "%s %s\n" $(date -d $(sed -r 's/(.{4})(..)(.{5})(..)(.*)/\1-\2-\3:\4:\5/' <<<${f#$vol.}) +%s) $f
45 done | sort -r | head -n 1 | awk '{print $2}'
46 )
47 if [[ ! $last_snap ]]; then
48 echo "$d stale"
49 ret=1
50 continue
51 fi
52 stale=true
53 if btrfs sub show $d 2>/dev/null | sed '0,/^\t*Snapshot(s):/d;s/^\s*//' | \
54 grep -xF btrbk/$last_snap &>/dev/null; then
55 stale=false
56 else
57 last_uuid=$(btrfs sub show $last_snap| awk '$1 == "UUID:" {print $2}')
58 if btrfs sub show $d| grep "^\s*Parent UUID:\s*$last_uuid$" &>/dev/null; then
59 stale=false
60 fi
61 fi
62 stale_dir=/nocow/btrfs-stale
63 stale_file=$stale_dir/$vol
64 if $stale; then
65 mkdir -p $stale_dir
66 printf "%s\n" $last_snap > $stale_file
67 echo "$d stale"
68 ret=1
69 continue
70 else
71 rm -f $stale_file
72 fi
73 done
74 exit $ret
75