fixes, logging, and better shellcheck conformance
[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
17 [[ $EUID == 0 ]] || exec sudo -E "${BASH_SOURCE[0]}" "$@"
18
19 source /usr/local/lib/err
20
21 shopt -s nullglob
22
23 usage() {
24 cat <<EOF
25 usage: $0 SUBVOL_MOUNTPOINT... | -p SUBVOL_PATH...
26
27 In git this is not not executable because it's meant to be installed
28 using ./install-my-scripts
29
30 Print the unstale subvol name into /nocow/btrfs-stale/\$subvol
31
32 If latest subvols \$@ are not mounted, print a message to terminal.
33
34 Fresh is opposite of stale. To be fresh, either SUBVOL_MOUNTPOINT is a
35 snapshot of the latest, or the latest snapshot is snapshot of
36 SUBVOL_MOUNTPOINT.
37
38 -p Args are SUBVOL_PATH, not mountpoints from which we derive
39 that information.
40 -v|--verbose Be more verbose
41 -h|--help Print help and exit.
42
43 Note: Uses GNU getopt options parsing style
44 EOF
45 exit $1
46 }
47
48 ##### begin command line parsing ########
49
50 subvol_path=false
51 verbose=false
52 temp=$(getopt -l help,verbose hpv "$@") || usage 1
53 eval set -- "$temp"
54 while true; do
55 case $1 in
56 -p) subvol_path=true ;;
57 -v|--verbose) verbose=true ;;
58 -h|--help) usage ;;
59 --) shift; break ;;
60 *) echo "$0: unexpected args: $*" >&2 ; usage 1 ;;
61 esac
62 shift
63 done
64
65 if [[ ! $1 ]]; then
66 echo "$0: error: expected mountpoint argument"
67 fi
68
69 stale-file() {
70 stale_dir=/nocow/btrfs-stale
71 stale_file=$stale_dir/$vol
72 if $stale; then
73 mkdir -p $stale_dir
74 printf "%s\n" $freshest_snap > $stale_file
75 else
76 rm -f $stale_file
77 fi
78
79 }
80 pre="check-subvol-stale:${SSH_CLIENT:+ $HOSTNAME:}"
81
82 d() {
83 if $verbose; then
84 printf "$pre %s\n" "$*"
85 fi
86 }
87
88 # duplicated in mount-latest-sub
89 # Reassign $1 var from /dev/dm- to corresponding /dev/mapper/
90 mapper-dev() {
91 local mapdev
92 local -n devref=$1
93 if [[ $devref == /dev/dm-* ]]; then
94 for mapdev in /dev/mapper/*; do
95 if [[ $(readlink -f $mapdev) == "$devref" ]]; then
96 devref=$mapdev
97 break
98 fi
99 done
100 fi
101 }
102 tmpf=$(mktemp)
103 d tmpf=$tmpf
104 for d; do
105
106 if $subvol_path; then
107 svp=$d
108 root_dir=${d%/*}
109 subvol_dir=${d##*/}
110 vol=$subvol_dir
111 else
112 vol=${d##*/}
113 # second field, non-comment line == $d
114 dev=$(sed -rn "s,^\s*([^#]\S*)\s+$d\s.*,\1,p" /etc/fstab /etc/mtab|head -n1)
115
116 d dev=$dev
117 subvol_dir=$(sed -rn "s,^\s*[^#]\S*\s+$d\s.*\bsubvol=([a-zA-A/]+).*,\1,p" /etc/fstab /etc/mtab|head -n1)
118 if [[ ! $subvol_dir ]]; then
119 continue
120 fi
121 d subvol_dir=$subvol_dir
122
123 ### begin getting root_dir
124 ### this is duplicated in mount-latest-subvol
125 # note, we need $dev because $d might not be mounted, and we do this loop
126 # because the device in fstab for the rootfs can be different.
127 for devx in $(btrfs fil show $dev| sed -rn 's#.*path (\S+)$#\1#p'); do
128 if [[ $devx == dm-* ]]; then
129 devx=/dev/$devx
130 d mapper-dev $devx
131 mapper-dev devx
132 fi
133 d devx=$devx
134 root_dir=$(sed -rn "s,^\s*$devx\s+(\S+).*\bsubvolid=[05]\b.*,\1,p" /etc/mtab /etc/fstab|head -n1)
135 if [[ $root_dir ]]; then
136 d root_dir=$root_dir
137 break
138 fi
139 done
140 if [[ ! $root_dir ]]; then
141 echo "$0: error could not find root subvol mount for $dev" >&2
142 exit 1
143 fi
144 ### end getting root_dir
145 svp=$root_dir/$subvol_dir # subvolume path
146 d "svp=$svp # subvolume path"
147 fi
148
149 # note: relying on null glob
150 ls_args=($root_dir/btrbk/$subvol_dir.20*)
151 if (( ${#ls_args[@]} )); then
152 # Assumes we are in the 21st century.
153 ls -1dvrq $root_dir/btrbk/$subvol_dir.20* >$tmpf
154 mapfile -t snaps <$tmpf
155 else
156 # no snapshots yet
157 # TODO: make this an error and override with a cli flag
158 echo "$0: warning: no snapshots found at $root_dir/btrbk/$subvol_dir.20*. this is expected for a brand new volume"
159 continue
160 fi
161
162 # last_snap by date.
163 last_snap="${snaps[0]}"
164
165 case $last_snap in
166 $root_dir/btrbk/$subvol_dir.20*) : ;;
167 *)
168 echo "$0: error: unexpected last_snap:$last_snap"
169 exit 1
170 ;;
171 esac
172
173 d last_snap=$last_snap
174 ## alternate slower alternative which would not rely on ls sorting:
175 # last_snap=$(
176 # for s in ${snaps[@]}; do
177 # f=${s##*/}
178 # unix_time=$(date -d $(sed -r 's/(.{4})(..)(.{5})(..)(.*)/\1-\2-\3:\4:\5/' <<<${f#$vol.}) +%s)
179 # printf "%s %s\n" $unix_time $s # part of the pipeline
180 # # sort will fail
181 # done | sort -r | head -n 1 | awk '{print $2}' || [[ ${PIPESTATUS[1]} == 141 || ${PIPESTATUS[0]} == 32 ]]
182 # )
183 # if [[ ! $last_snap ]]; then
184 # # should not happen.
185 # echo "$0: error: could not find latest snapshot for $svp among ${snaps[*]}" >&2
186 # exit 1
187 # fi
188
189 if [[ ! -e $svp ]]; then
190 echo "$0: warning: subvol does not exist: $svp"
191 echo "$0 assuming this host was just for receiving and latest snap is freshest"
192 freshest_snap=$last_snap
193 stale=true
194 stale-file
195 continue
196 fi
197
198 # get info on last received sub
199 last_received=
200 last_received_cgen=0
201 for f in ${snaps[@]}; do
202 show="$(btrfs sub show $f)"
203 if echo "$show" | grep -E "Received UUID:\s+[[:alnum:]]" &>/dev/null; then
204 d found received uuid in $f
205 cgen=$(echo "$show" | sed -rn 's,^\s*Gen at creation:\s+([0-9]+).*,\1,p')
206 if [[ $cgen -gt $last_received_cgen ]]; then
207 last_received_cgen=$cgen
208 last_received=$f
209 elif [[ $last_received ]]; then
210 # optimization: we are looking in reverse order by date, so if
211 # we find one that has a lesser cgen, assume the rest will all
212 # be lesser.
213 break
214 fi
215 fi
216 done
217 d last_received_cgen=$last_received_cgen
218 d last_received=$last_received
219
220
221 # if there is a last_received, we can assume stale or fresh if we are newer/older
222 if [[ $last_received ]]; then
223 svp_cgen=$(btrfs sub show $svp | sed -rn 's,^\s*Gen at creation:\s+([0-9]+).*,\1,p')
224 d svp_cgen=$svp_cgen
225 if [[ $svp_cgen -ge $last_received_cgen ]]; then
226 stale=false
227 else
228 d "$svp stale: it's gen at creation, $svp_cgen, is earlier than the last received snapshot, $last_received's gen at creation: $last_received_cgen"
229 freshest_snap=$last_received
230 stale=true
231 fi
232 stale-file
233 continue
234 fi
235
236 # fallback to using last_snap as the freshest
237 freshest_snap=$last_snap
238 stale=true
239 # fresh if $svp has $last_snap as a snapshot,
240 if btrfs sub show $svp 2>/dev/null | sed '0,/^\s*Snapshot(s):/d;s/^\s*//' | \
241 grep -xF ${last_snap#"$root_dir"/} >/dev/null; then
242 stale=false
243 else # or else $svp is a snapshot of $last_snap. we use a uuid
244 # comparison, which if I remember from the docs, is a bit more
245 # robust, perhaps to renames.
246 last_snap_uuid=$(btrfs sub show $last_snap| awk '$1 == "UUID:" {print $2}')
247 if btrfs sub show $svp| grep "^\s*Parent UUID:\s*$last_snap_uuid$" &>/dev/null; then
248 stale=false
249 fi
250 fi
251
252 stale-file
253 done
254 rm $tmpf