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