fix mistake from recent commit
[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 # usage: mount-latest-subvol
17 #
18 # Note, at source location, intentionally not executable, run and read
19 # install-my-scripts.
20
21 cd /
22 [[ $EUID == 0 ]] || exec sudo -E "$BASH_SOURCE" "$@"
23
24 errcatch() {
25 set -E; shopt -s extdebug
26 _err-trap() {
27 err=$?
28 exec >&2
29 set +x
30 echo "${BASH_SOURCE[1]}:${BASH_LINENO[0]}:in \`$BASH_COMMAND' returned $err"
31 bash-trace 2
32 echo "$0: exiting with code $err"
33 exit $err
34 }
35 trap _err-trap ERR
36 set -o pipefail
37 }
38 bash-trace() {
39 local -i argc_index=0 frame i start=${1:-1} max_indent=8 indent
40 local source
41 local extdebug=false
42 if [[ $(shopt -p extdebug) == *-s* ]]; then
43 extdebug=true
44 fi
45
46 for ((frame=0; frame < ${#FUNCNAME[@]}-1; frame++)); do
47 argc=${BASH_ARGC[frame]}
48 argc_index+=$argc
49 ((frame < start)) && continue
50 if (( ${#BASH_SOURCE[@]} > 1 )); then
51 source="${BASH_SOURCE[frame+1]}:${BASH_LINENO[frame]}:"
52 fi
53 indent=$((frame-start+1))
54 indent=$((indent < max_indent ? indent : max_indent))
55 printf "%${indent}s↳%sin \`%s" '' "$source" "${FUNCNAME[frame]}"
56 if $extdebug; then
57 for ((i=argc_index-1; i >= argc_index-argc; i--)); do
58 printf " %s" "${BASH_ARGV[i]}"
59 done
60 fi
61 echo \'
62 done
63 }
64 errcatch
65
66 tu() {
67 while read -r line; do
68 file="$1"
69 grep -xFq "$line" "$file" || tee -a "$file"<<<"$line"
70 done
71 }
72 e() { printf "%s\n" "$*"; "$@"; }
73 mnt() {
74 dir=$1
75 if ! mountpoint $dir &>/dev/null; then
76 mkdir -p $dir
77 e mount $dir
78 fi
79 }
80 fstab() {
81 while read -r start mpoint end; do
82 l="$start $mpoint $end"
83 # kill off any lines that duplicate the mount point.
84 sed --follow-symlinks -ri "\%$l%b;\%^\s*\S+\s+$mpoint\s%d" /etc/fstab
85 tu /etc/fstab <<<"$l"
86 done
87 }
88 pid-check() {
89 for p in ${pids}; do
90 for m in ${my_pids[@]}; do
91 if (( p == m )); then
92 echo "$0: error: pids to kill includes our pid or a parent. ps output:" >&2
93 ps -f -p $p
94 exit 1
95 fi
96 done
97 done
98 }
99 kill-dir() {
100 for sig; do
101 echo kill-dir $sig
102 found_pids=false
103 if pids=$(timeout 4 lsof -t $dir); then
104 found_pids=true
105 timeout 4 lsof -w $dir
106 pid-check
107 kill -$sig $pids
108 fi
109 # fuser will find open sockets that lsof won't, for example from gpg-agent.
110 # note: -v shows kernel processes, which then doesn't return true when we want
111 if pids=$(timeout 4 fuser -m $dir 2>/dev/null); then
112 pid-check
113 found_pids=true
114 fuser -$sig -mvk $dir
115 fi
116 sleep .5
117 if ! $found_pids; then
118 return 0
119 fi
120 done
121 return 1
122 }
123
124 force=false
125 if [[ $1 == -f ]]; then
126 force=true
127 fi
128
129 ret=0
130
131 ##### begin setup fstab for subvols we care about ######
132 root_dev=$(awk '$2 == "/" {print $1}' /etc/mtab)
133
134
135 if cryptsetup status $root_dev &>/dev/null; then
136 crypt_dev=$root_dev
137 else # if we are in a recovery boot, find the next best crypt device
138 noauto=,noauto
139 for dev in $(dmsetup ls --target crypt | awk '{print $1}'); do
140 dev=/dev/mapper/$dev
141 if awk '{print $1}' /etc/mtab | grep -Fx $dev &>/dev/null; then
142 crypt_dev=$dev
143 break
144 fi
145 done
146 fi
147
148
149 fstab <<EOF
150 $crypt_dev /a btrfs noatime,subvol=a$noauto 0 0
151 EOF
152
153 shopt -s nullglob
154
155 # ssh and probably some other things care about parent directory
156 # ownership, and ssh doesn\'t allow any group writable parent
157 # directories, so we are forced to use a directory structure similar
158 # to home directories
159 f=(/mnt/root/btrbk/q.*)
160 if [[ -e $f ]]; then
161 fstab <<EOF
162 $crypt_dev /q btrfs noatime,subvol=q,gid=1000$noauto 0 0
163 /q/p /p none bind$noauto 0 0
164 EOF
165 fi
166
167 f=(/mnt/root/btrbk/o.*)
168 if [[ -e $f ]]; then
169 fstab <<EOF
170 $crypt_dev /o btrfs noatime,subvol=o$noauto 0 0
171 /o/m /m none bind$noauto 0 0
172 EOF
173 fi
174
175 if [[ $HOSTNAME == frodo ]]; then
176 fstab <<EOF
177 $crypt_dev /i btrfs noatime,subvol=i$noauto 0 0
178 EOF
179 fi
180 ##### end setup fstab for subvols we care about ######
181
182 # get pids that this program depends on so we dont kill them
183 my_pids=($$ $PPID)
184 loop_limit=30
185 count=0
186 while [[ ${my_pids[-1]} != 1 && ${my_pids[-1]} != ${my_pids[-2]} && $count -lt $loop_limit ]]; do
187 count=$((count + 1))
188 p=$(ps -p ${my_pids[-1]} -o ppid=)
189 if [[ $p == 0 || ! $p ]]; then
190 break
191 fi
192 my_pids+=($p)
193 done
194
195
196 for vol in q a o i; do
197 d=/$vol
198 if ! awk '{print $2}' /etc/fstab | grep -xF $d &>/dev/null; then
199 continue
200 fi
201
202
203 ##### begin building up list of bind mounts ######
204 binds=() # list of bind mounts
205 roots=($d) # list of bind mounts, plus the original mount
206 while true; do
207 new_roots=()
208 for r in ${roots[@]}; do
209 # eg. when r=/q/p, for lines like
210 # /q/p /p none bind 0 0
211 # output /p
212 new_roots+=($(sed -rn "s#^$r/\S+\s+(\S+)\s+none\s+bind\s.*#\1#p" /etc/fstab))
213 done
214 (( ${#new_roots} )) || break
215 binds+=(${new_roots[@]})
216 roots=( ${new_roots[@]} )
217 done
218 ##### end building up list of bind mounts ######
219
220
221 # if latest is already mounted, make sure binds are mounted and move on
222 e check-subvol-stale $d
223 # populated by check-subvol-stale if stale
224 if ! fresh_snap=$(</nocow/btrfs-stale/$vol); then
225 mnt $d
226 for b in ${binds[@]}; do
227 mnt $b
228 done
229 continue
230 fi
231
232 umount_ret=true
233 unmounted=()
234 for dir in $(echo $d ${binds[*]}\ |tac -s\ ); do
235 if mountpoint $dir; then
236 if e umount -R $dir; then
237 unmounted+=($dir)
238 else
239 if ! kill-dir TERM TERM TERM INT INT HUP HUP; then
240 if $force; then kill-dir KILL; fi
241 fi
242
243 if e umount -R $dir; then
244 unmounted+=($dir)
245 else
246 echo "$0: failed to umount $dir"
247 umount_ret=false
248 ret=1
249 continue
250 fi
251 fi
252 fi
253 done
254
255 if ! $umount_ret; then
256 for dir in ${unmounted[@]}; do
257 mnt $dir
258 done
259 continue
260 fi
261
262 # todo: decipher /mnt/root, like we do in check-subvol-stale
263 cd /mnt/root
264 if [[ -e $vol ]]; then
265 e mv $vol $vol.leaf.$(date +%Y-%m-%dT%H:%M:%S%z)
266 leaf_vols=($vol.leaf.*)
267 for leaf in ${leaf_vols[@]}; do
268 leaf_secs=$(date -d ${leaf#$vol.leaf.} +%s)
269 if (( $(date +%s) - 60*60*24*60 > leaf_secs )); then # 60 days
270 e btrfs sub del $leaf
271 fi
272 done
273 fi
274 # Note, we make a few assumptions in this script, like
275 # $d was not a different subvol id than $vol, and
276 # things otherwise didn't get mounted very strangely.
277 e btrfs sub snapshot $fresh_snap $vol
278 for dir in $d ${binds[@]}; do
279 e mnt $dir
280 done
281 stale_dir=/nocow/btrfs-stale
282 rm -f $stale_dir/$d
283 done
284
285 ### disabled
286 if [[ $HOSTNAME == kdxxxxxxxxx ]]; then
287 # partitioned it with fai partitioner outside of fai,
288 # because it\'s worth it to have 1% space reserved for boot and
289 # swap partitions in case I ever want to boot off those drives.
290 # as root:
291 # . /a/bin/fai/fai-wrapper
292 # eval-fai-classfile /a/bin/fai/fai/config/class/51-multi-boot
293 # fai-setclass ROTATIONAL
294 # export LUKS_DIR=/q/root/luks/
295 # # because the partition nums existed already
296 # fai-setclass REPARTITION
297 # /a/bin/fai/fai/config/hooks/partition.DEFAULT
298
299 devs=(
300 ata-TOSHIBA_MD04ACA500_84REK6NTFS9A-part1
301 ata-TOSHIBA_MD04ACA500_84R2K773FS9A-part1
302 ata-TOSHIBA_MD04ACA500_8471K430FS9A-part1
303 ata-TOSHIBA_MD04ACA500_8481K493FS9A-part1
304 )
305 first=true
306 for dev in ${devs[@]}; do
307 if $first; then
308 first=false
309 tu /etc/fstab <<EOF
310 /dev/mapper/crypt_dev_$dev /i btrfs noatime,subvol=i,noauto 0 0
311 /dev/mapper/crypt_dev_$dev /mnt/iroot btrfs noatime,subvolid=0,noauto 0 0
312 EOF
313 fi
314 tu /etc/crypttab <<EOF
315 crypt_dev_$dev /dev/disk/by-id/$dev /q/root/luks/host-kd discard,luks
316 EOF
317 if [[ ! -e /dev/mapper/crypt_dev_$dev ]]; then
318 cryptdisks_start crypt_dev_$dev
319 fi
320 done
321 # note, could do an else here and have some kind of mount for /i
322 # on other hosts.
323 fi
324
325 exit $ret