93a085a8e20e764e85d43153480f1a58b924507d
[distro-setup] / mount-latest-subvol
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 script=$(readlink -f -- "$BASH_SOURCE")
17 cd /
18 [[ $EUID == 0 ]] || exec sudo -E "$script" "$@"
19
20 source /usr/local/lib/err
21
22 usage() {
23 cat <<EOF
24 Usage: ${0##*/} [OPTIONS]
25
26 -h|--help Print help and exit.
27 -f|--force Use kill -9 to try fixing unmount errors
28 -v|--verbose Be more verbose
29
30
31 Note: In git this is not not executable because it's meant to be installed
32 using ./install-my-scripts
33
34 Note: Uses util-linux getopt option parsing: spaces between args and
35 options, short options can be combined, options before args.
36 EOF
37 exit $1
38 }
39
40 all_vols=(q a o i ar qr)
41
42
43 tu() {
44 while read -r line; do
45 file="$1"
46 grep -xFq "$line" "$file" || tee -a "$file"<<<"$line"
47 done
48 }
49 d() {
50 if $verbose; then
51 printf "%s\n" "$*"
52 fi
53 }
54 m() {
55 if $verbose; then
56 printf "%s\n" "$*"
57 fi
58 "$@"
59 }
60 x() {
61 printf "%s\n" "$*"
62 "$@"
63 }
64
65 mnt() {
66 dir=$1
67 if ! mountpoint -q $dir; then
68 mkdir -p $dir
69 m mount $dir
70 fi
71 }
72 fstab() {
73 while read -r start mpoint end; do
74 l="$start $mpoint $end"
75 # kill off any lines that duplicate the mount point.
76 sed --follow-symlinks -ri "\%$l%b;\%^\s*\S+\s+$mpoint\s%d" /etc/fstab
77 tu /etc/fstab <<<"$l"
78 done
79 }
80 pid-check() {
81 for p in ${pids}; do
82 for m in ${my_pids[@]}; do
83 if (( p == m )); then
84 echo "$0: error: pids to kill includes our pid or a parent. ps output:" >&2
85 ps -f -p $p
86 exit 1
87 fi
88 done
89 done
90 }
91 kill-dir() {
92 for sig; do
93 echo kill-dir $sig
94 found_pids=false
95 if pids=$(timeout 4 lsof -t $dir); then
96 found_pids=true
97 timeout 4 lsof -w $dir
98 pid-check
99 kill -$sig $pids
100 fi
101 # fuser will find open sockets that lsof won't, for example from gpg-agent.
102 # note: -v shows kernel processes, which then doesn't return true when we want
103 if pids=$(timeout 4 fuser -m $dir 2>/dev/null); then
104 pid-check
105 found_pids=true
106 fuser -$sig -mvk $dir
107 fi
108 sleep .5
109 if ! $found_pids; then
110 return 0
111 fi
112 done
113 return 1
114 }
115 umount-kill() {
116 dir=$1
117 if mountpoint -q $dir; then
118 if m umount -R $dir; then
119 unmounted+=($dir)
120 else
121 if ! kill-dir TERM TERM TERM INT INT HUP HUP TERM TERM TERM INT INT HUP HUP; then
122 if $force; then kill-dir KILL; fi
123 fi
124
125 if m umount -R $dir; then
126 unmounted+=($dir)
127 else
128 echo "$0: failed to umount $dir"
129 umount_ret=false
130 ret=1
131 fi
132 fi
133 fi
134 }
135
136 # duplicated in check-subvol
137 # Reassign $1 var from /dev/dm- to corresponding /dev/mapper/
138 mapper-dev() {
139 local mapdev
140 local -n devref=$1
141 if [[ $devref == /dev/dm-* ]]; then
142 for mapdev in /dev/mapper/*; do
143 if [[ $(readlink -f $mapdev) == "$devref" ]]; then
144 devref=$mapdev
145 break
146 fi
147 done
148 fi
149 }
150
151
152 ##### begin command line parsing ########
153
154 # you can remove this if you do not have options which can have args with spaces or empty.
155
156 verbose=true
157 force=false
158 temp=$(getopt -l help,force,verbose hfv "$@") || usage 1
159 eval set -- "$temp"
160 while true; do
161 case $1 in
162 -f|--force) force=true ;;
163 -v|--verbose) verbose=true ;;
164 -h|--help) usage ;;
165 --) shift; break ;;
166 *) echo "$0: unexpected args: $*" >&2 ; usage 1 ;;
167 esac
168 shift
169 done
170
171 ##### end command line parsing ########
172
173 ret=0
174
175 ##### begin setup fstab for subvols we care about ######
176
177 if [[ -e /mnt/root/root2-crypttab ]]; then
178 tu /etc/crypttab </mnt/root/root2-crypttab
179 while read -r mapper_dev _; do
180 if [[ ! -e /dev/mapper/$mapper_dev ]]; then
181 m cryptdisks_start $mapper_dev
182 fi
183 done < <(cat /mnt/root/root2-crypttab)
184 fi
185 if [[ -e /mnt/root/root2-fstab ]]; then
186 tu /etc/fstab </mnt/root/root2-fstab
187 mnt /mnt/root2
188 mnt /mnt/boot2
189 fi
190
191 do_o=true
192 root_dev=$(awk '$2 == "/" {print $1}' /etc/mtab)
193 mapper-dev root_dev
194 o_dev=$(awk '$2 == "/mnt/o" {print $1}' /etc/mtab)
195 mapper-dev o_dev
196
197 if [[ $o_dev == "$root_dev" ]]; then
198 do_o=false
199 fi
200
201 # root2_dev=$(awk '$2 == "/mnt/root2" {print $1}' /etc/mtab)
202 # mapper-dev root2_dev
203 # # dont bother with the above for crypt2_dev
204 # crypt2_dev=$root2_dev
205
206
207 if cryptsetup status $root_dev &>/dev/null; then
208 crypt_dev=$root_dev
209 else # if we are in a recovery boot, find the next best crypt device
210 mopts=,noauto
211 do_o=false
212 for dev in $(dmsetup ls --target crypt | awk '{print $1}'); do
213 dev=/dev/mapper/$dev
214 if awk '{print $1}' /etc/mtab | grep -Fx $dev &>/dev/null; then
215 crypt_dev=$dev
216 break
217 fi
218 done
219 fi
220
221
222
223 # dont tax the cpus of old laptops
224 if ((`nproc` > 2)); then
225 mopts+=,compress=zstd
226 fi
227
228 fstab <<EOF
229 $crypt_dev /a btrfs noatime,subvol=a$mopts 0 0
230 EOF
231
232 shopt -s nullglob
233
234 # ssh and probably some other things care about parent directory
235 # ownership, and ssh doesn\'t allow any group writable parent
236 # directories, so we are forced to use a directory structure similar
237 # to home directories
238 f=(/mnt/root/btrbk/q.*); f=${f[0]}
239 if [[ -e $f ]]; then
240 fstab <<EOF
241 $crypt_dev /q btrfs noatime,subvol=q,gid=1000$mopts 0 0
242 /q/p /p none bind$mopts 0 0
243 EOF
244 fi
245
246 f=(/mnt/root/btrbk/qr.*); f=${f[0]}
247 if [[ -e $f ]]; then
248 fstab <<EOF
249 $crypt_dev /qr btrfs noatime,subvol=qr$mopts 0 0
250 EOF
251 fi
252
253 f=(/mnt/root/btrbk/ar.*); f=${f[0]}
254 if [[ -e $f ]]; then
255 fstab <<EOF
256 $crypt_dev /ar btrfs noatime,subvol=ar,uid=1000,gid=1000$mopts 0 0
257 EOF
258 fi
259
260
261 f=(/mnt/o/btrbk/o.*); f=${f[0]}
262 if [[ -e $f ]]; then
263 fstab <<EOF
264 $o_dev /o btrfs noatime,subvol=o$mopts 0 0
265 /o/m /m none bind$mopts 0 0
266 EOF
267 else
268 do_o=false
269 fi
270
271 if [[ $HOSTNAME == frodo ]]; then
272 fstab <<EOF
273 $crypt_dev /i btrfs noatime,subvol=i$mopts 0 0
274 EOF
275 fi
276
277
278
279 ##### end setup fstab for subvols we care about ######
280
281 ### begin get pids that this program depends on so we dont kill them
282 my_pids=($$ $PPID)
283 loop_limit=30
284 count=0
285 while [[ ${my_pids[-1]} != 1 && ${my_pids[-1]} != ${my_pids[-2]} && $count -lt $loop_limit ]]; do
286 count=$((count + 1))
287 p=$(ps -p ${my_pids[-1]} -o ppid=)
288 if [[ $p == 0 || ! $p ]]; then
289 break
290 fi
291 my_pids+=($p)
292 done
293 ### end get pids that this program depends on so we dont kill them
294
295 for vol in ${all_vols[@]}; do
296 d=/$vol
297 if ! awk '{print $2}' /etc/fstab | grep -xF $d &>/dev/null; then
298 continue
299 fi
300
301
302 ##### begin building up list of bind mounts ######
303 binds=() # list of bind mounts
304 roots=($d)
305 while true; do
306 new_roots=()
307 for r in ${roots[@]}; do
308 # eg. when r=/q/p, for lines like
309 # /q/p /p none bind 0 0
310 # output /p
311 new_roots+=($(sed -rn "s#^$r/\S+\s+(\S+)\s+none\s+(\S+,|)bind[[:space:],].*#\1#p" /etc/fstab))
312 done
313 (( ${#new_roots} )) || break
314 binds+=(${new_roots[@]})
315 # roots is used to recursively find binds of binds if they exist.
316 roots=( ${new_roots[@]} )
317 done
318 ##### end building up list of bind mounts ######
319
320
321 # if latest is already mounted, make sure binds are mounted and move on
322 m check-subvol-stale $d
323 # populated by check-subvol-stale if stale
324 if ! fresh_snap=$(cat /nocow/btrfs-stale/$vol 2>/dev/null); then
325 mnt $d
326 did=$(stat -c%d $d)
327 for b in ${binds[@]}; do
328 if mountpoint -q $b; then
329 bid=$(stat -c%d $b)
330 if [[ $did != $bid ]]; then
331 umount-kill $b
332 fi
333 fi
334 mnt $b
335 done
336 continue
337 fi
338
339 ## not using arbtt at the moment
340 # if [[ $vol == q ]]; then
341 # ## allow to fail, user might not be logged in
342 # x sudo -u $(id -nu 1000) XDG_RUNTIME_DIR=/run/user/1000 systemctl --user stop arbtt ||:
343 # fi
344 umount_ret=true
345 unmounted=()
346 for dir in $(echo $d ${binds[*]}\ |tac -s\ ); do
347 umount-kill $dir
348 done
349
350 # if we unmounted some but not all, restore them and move on
351 if ! $umount_ret; then
352 for dir in ${unmounted[@]}; do
353 mnt $dir
354 done
355 continue
356 fi
357
358 #### begin dealing with leaf vols ####
359
360 ### begin getting root_dir
361 ### this is duplicated in check-subvol-stale
362
363 dev=$(sed -rn "s,^\s*([^#]\S*)\s+$d\s.*,\1,p" /etc/fstab /etc/mtab|head -n1)
364 d dev=$dev
365 # note, we need $dev because $d might not be mounted, and we do this loop
366 # because the device in fstab for the rootfs can be different.
367 for devx in $(btrfs fil show $dev| sed -rn 's#.*path (\S+)$#\1#p'); do
368 if [[ $devx == dm-* ]]; then
369 devx=/dev/$devx
370 mapper-dev devx
371 fi
372 d devx=$devx
373 root_dir=$(sed -rn "s,^\s*$devx\s+(\S+).*\bsubvolid=[05]\b.*,\1,p" /etc/mtab /etc/fstab|head -n1)
374 if [[ $root_dir ]]; then
375 d root_dir=$root_dir
376 break
377 fi
378 done
379 if [[ ! $root_dir ]]; then
380 echo "$0: error could not find root subvol mount for $dev" >&2
381 exit 1
382 fi
383 ### end getting root_dir
384
385 cd $root_dir
386 if [[ -e $vol ]]; then
387 leaf=$vol.leaf.$(date +%Y-%m-%dT%H:%M:%S%z)
388 m mv $vol $leaf
389 m btrfs property set -ts $leaf ro true
390
391 ### begin check if leaf is different, delete it if not ###
392 if [[ -e /a/opt/btrfs-snapshots-diff/btrfs-snapshots-diff.py ]]; then
393 source /a/bin/distro-functions/src/package-manager-abstractions
394 #pi python-jmespath # dependency of btrfs-snapshots-diff
395 # todo: need python3 port of btrfs-snapshots-diff, py2 no exist on nabia
396 parentid=$(btrfs sub show $leaf | awk '$1 == "Parent" && $2 == "UUID:" {print $3}')
397 bsubs=(btrbk/$vol.*)
398 bsub=
399 # go in reverse order as its more likely to be at the end
400 for ((i=${#bsubs[@]}-1; i>=0; i--)); do
401 if [[ $parentid == $(btrfs sub show ${bsubs[i]} | awk '$1 == "UUID:" {print $2}') ]]; then
402 bsub=${bsubs[i]}
403 break
404 fi
405 done
406 if [[ $bsub ]]; then
407 tmp=$(mktemp)
408 # in testing, same subvol is 136 bytes. allow some overhead. 32 happens sometimes under systemd.
409 # $ errno 32
410 # EPIPE 32 Broken pipe
411 btrfs send --no-data -p $bsub $leaf | head -c 1000 > $tmp || [[ $? == 141 || ${PIPESTATUS[0]} == 32 ]]
412 if (( $(stat -c%s $tmp) < 1000)); then
413 # example output for an empty diff:
414 # Found a valid Btrfs stream header, version 1
415 # o.leaf.2019-05-15T14:00:50-0400;snapshot: uuid=ba045ea30737dd449003f1ee40ec12d0, ctrasid=109533, clone_uuid=3c7e3544e486834aa71d89e5b8f30056, clone_ctransid=109533
416 lines=$(/a/opt/btrfs-snapshots-diff/btrfs-snapshots-diff.py -s -f $tmp | \
417 grep -vxF "Found a valid Btrfs stream header, version 1" | \
418 grep -cv "^[^;]*;snapshot: ") ||:
419 if [[ $lines == 0 ]]; then
420 # rotate in case we find a bug, weve got 2 old ones
421 tmpleaf=($vol.tmpleaf2.*)
422 if (( ${#tmpleaf[@]} )); then
423 x btrfs sub del ${tmpleaf[@]}
424 fi
425 tmpleaf=($vol.tmpleaf1.*)
426 if (( ${#tmpleaf[@]} )); then
427 x mv ${tmpleaf[0]} $vol.tmpleaf2.${tmpleaf[0]#$vol.tmpleaf1.}
428 fi
429 echo suspected identical: $bsub $leaf
430 x mv $leaf $vol.tmpleaf1.${leaf#$vol.leaf.}
431 fi
432 fi
433 fi
434 fi
435 ### end check if leaf is different, delete it if not ###
436
437 ## begin expire leaf vols ##
438 leaf_vols=($vol.leaf.*)
439 count=${#leaf_vols[@]}
440 leaf_limit_time=$(( EPOCHSECONDS - 60*60*24*60 )) # 60 days
441 leaf_new_limit_time=$(( EPOCHSECONDS - 60*60*24 )) # 1 day
442 # this goes backwards from oldest. leaf_new_limit_time is just in case
443 # the order gets screwed up or something.
444 for leaf in ${leaf_vols[@]}; do
445 leaf_time=$(date -d ${leaf#$vol.leaf.} +%s)
446 if (( leaf_limit_time > leaf_time || ( leaf_new_limit_time > leaf_time && count > 15 ) )); then
447 x btrfs sub del $leaf
448 fi
449 count=$((count-1))
450 done
451 ## end expire leaf vols ##
452 fi
453 #### end dealing with leaf vols ####
454
455 # Note, we make a few assumptions in this script, like
456 # $d was not a different subvol id than $vol, and
457 # things otherwise didn't get mounted very strangely.
458 m btrfs sub snapshot $fresh_snap $vol
459 for dir in $d ${binds[@]}; do
460 m mnt $dir
461 done
462
463 ## arbtt disabled for now
464 # if [[ $vol == q ]]; then
465 # # maybe this will fail if X is not running
466 # x sudo -u $(id -nu 1000) XDG_RUNTIME_DIR=/run/user/1000 systemctl --user start arbtt ||:
467 # fi
468
469 stale_dir=/nocow/btrfs-stale
470 rm -f $stale_dir/$d
471 done
472
473
474
475 for dir in /mnt/r7/amy/{root/root,boot/boot}_ubuntubionic /mnt/{root2/root,boot2/boot}_ubuntubionic; do
476 vol=${dir##*/}
477 root_dir=${dir%/*}
478 if [[ ! -d $root_dir ]]; then
479 # this only exists on host kd currently
480 continue
481 fi
482 # if latest is already mounted, make sure binds are mounted and move on
483 m check-subvol-stale -p $dir
484 # populated by check-subvol-stale if stale
485 if ! fresh_snap=$(cat /nocow/btrfs-stale/$vol 2>/dev/null); then
486 continue
487 fi
488 if [[ -d $dir ]]; then
489 if ! kill-dir TERM TERM TERM INT INT HUP HUP TERM TERM TERM INT INT HUP HUP; then
490 if $force; then kill-dir KILL; fi
491 fi
492 m btrfs sub del $dir
493 fi
494 m btrfs sub snapshot $fresh_snap $dir
495 rm -f /nocow/btrfs-stale/$vol
496 done
497
498 exit $ret
499
500