lots of updates, some t11 stuff
[distro-setup] / btrbk-run
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 # todo: if we cancel in the middle of a btrfs send, then run again
18 # immediately, the received subvolume doesn't get a Received UUID:
19 # field, and we won't mount it. Need to figure out a solution that will
20 # fix this.
21
22
23 [[ $EUID == 0 ]] || exec sudo -E "${BASH_SOURCE[0]}" "$@"
24
25 source /usr/local/lib/err
26
27 usage() {
28 cat <<'EOF'
29 btrbk-run [OPTIONS]
30 usually -t TARGET_HOST or -s SOURCE_HOST
31
32 Note, at source location, intentionally not executable, run and read
33 install-my-scripts.
34
35 EOF
36 echo "top of script file:"
37 sed -n '1,/^[# ]*end command line/{p;b};q' "$0"
38 exit $1
39 }
40
41
42
43 pre="${0##*/}: "
44 m() { if $verbose; then printf "$pre%s\n" "$*"; fi; "$@"; }
45 e() { printf "$pre%s\n" "$*"; }
46 die() { printf "$pre%s\n" "$*" >&2; echo "exiting with status 1" >&2; exit 1; }
47 mexit() { echo "$pre: exiting with status $1"; exit $1; }
48
49 # latest $MAIL_HOST
50 if [[ -e /b/bash_unpublished/source-state ]]; then
51 source /b/bash_unpublished/source-state
52 fi
53
54 # note q is owned by root:1000
55
56 mountpoints=()
57
58 rsync_mountpoint=/q
59
60 ret=0
61 # default options
62 conf_only=false
63 dry_run=false # mostly for testing
64 rate_limit=no
65 verbose=true; verbose_arg=-v
66 progress_arg="--progress"
67 incremental_strict=false
68 pull_reexec=false
69
70 default_args_file=/etc/btrbk-run.conf
71 if [[ -s $default_args_file ]]; then
72 set -- $(< $default_args_file) "$@"
73 # i havent used this feature yet, so warn about it
74 echo "$0: warning: default btrbk-run options set in $default_args_file (sleeping 5 seconds):"
75 cat $default_args_file
76 sleep 5
77 fi
78
79 early=false # quit early, just btrbk, no extra remounting etc.
80 cron=false
81 orig_args=("$@")
82 temp=$(getopt -l cron,pull-reexec,help ceil:m:npqrs:t:vh "$@") || usage 1
83 eval set -- "$temp"
84 while true; do
85 case $1 in
86 --cron)
87 cron=true
88 pre=
89 shift
90 ;;
91 # only creates the config file, does not run btrbk
92 -c) conf_only=true; shift ;;
93 -e) early=true; shift ;;
94 -i) incremental_strict=true; shift ;;
95 # bytes per second, suffix k m g
96 -l) rate_limit=$2; shift 2 ;;
97 # Comma separated mountpoints to backup. This has defaults set below.
98 -m) IFS=, mountpoints=($2); unset IFS; shift 2 ;;
99 -n) dry_run=true; dry_run_arg=-n; shift ;;
100 -p) progress_arg="--progress"; shift ;;
101 --pull-reexec) pull_reexec=true; shift ;;
102 -r) archive=false; shift ;;
103 -q) verbose=false; verbose_arg=; progress_arg=; shift ;;
104 # source host to receive a backup from
105 -s)
106 source=$2
107 bbksource=$source
108 if [[ $source == *:* ]]; then
109 bbksource="[$source]"
110 fi
111 shift 2
112 ;;
113 # target hosts to send to. empty is valid for just doing local
114 # snapshot. we have default hosts we will populate.
115 -t) IFS=, targets=($2); unset IFS; shift 2 ;;
116 -v) verbose=true; verbose_arg=-v; shift ;;
117 -h|--help) usage ;;
118 --) shift; break ;;
119 *) die "Internal error!" ;;
120 esac
121 done
122
123 # only tested commands are resume and archive
124 cmd_arg=${1:-run}
125
126 case $cmd_arg in
127 run|resume|archive) : ;;
128 *) die "untested command arg" ;;
129 esac
130
131 if (( $# > 1 )); then
132 die: "only 1 nonoption arg is supported"
133 fi
134
135 if [[ -v targets && $source ]]; then
136 # note, this doesnt need to be the case, but
137 # we would need to think about it.
138 die "error: -t and -s are mutually exclusive"
139 fi
140
141 if $verbose; then
142 printf "options: conf_only=%s\ndry_run=%s\nrate_limit=%s\nverbose=%s\ncmd_arg=%s" "$conf_only" "$dry_run" "$rate_limit" "$verbose" "$cmd_arg"
143 fi
144 ### end options parsing
145
146 # remove path from earlier version of btrbk
147 rm -f /usr/sbin/btrbk
148 # note, this still works as intended if there is no /usr/bin/btrbk
149 if [[ /a/opt/btrbk/btrbk -nt /usr/bin/btrbk ]]; then
150 if [[ -e /b/distro-functions/src/package-manager-abstractions ]]; then
151 . /b/distro-functions/src/package-manager-abstractions
152 pi asciidoctor
153 fi
154 cd /a/opt/btrbk
155 m make install
156 fi
157
158 # TODO: i wonder if there should be an option to send to the default
159 # targets, plus any given on the command line.
160
161
162 amy=false
163 # set default targets
164 if [[ ! -v targets && ! $source ]]; then
165 if [[ $HOSTNAME != "$MAIL_HOST" ]] && $cron ; then
166 echo "MAIL_HOST=$MAIL_HOST, nothing to do"
167 mexit 0
168 else
169 amy=true
170 fi
171
172 at_work=false
173
174 targets=(frodo.b8.nz)
175 case $HOSTNAME in
176 x2|kw)
177 at_work=true
178 ;;&
179 x2|x3|sy|bo)
180 if ping -q -c1 -w1 hal.office.fsf.org \
181 && ip n show 192.168.0.26 | grep . &>/dev/null; then
182 at_work=true
183 fi
184 ;;&
185 kw|x2|x3|sy|bo)
186 if $at_work; then
187 if ping -q -c1 -w1 iank.vpn.office.fsf.org &>/dev/null; then
188 home=iank.vpn.office.fsf.org
189 else
190 home=i.b8.nz
191 fi
192 else
193 home=b8.nz
194 fi
195 ;;&
196 kw)
197 targets+=($home x2.office.fsf.org)
198 ;;
199 x2|x3|sy|bo)
200 targets+=($home)
201 if $at_work; then
202 targets+=(x2.office.fsf.org x2.b8.nz)
203 else
204 targets+=(x2wg.b8.nz)
205 fi
206 ;;
207 kd)
208 targets+=(x2wg.b8.nz x3.b8.nz)
209 if ping -q -c1 -w1 sy.b8.nz &>/dev/null; then
210 targets+=(sy.b8.nz)
211 else
212 targets+=(syw.b8.nz)
213 fi
214 ;;
215 frodo)
216 # no targets
217 targets=()
218 ;;
219 *)
220 die "error: no default targets for this host, use -t"
221 ;;
222 esac
223 fi
224
225 if [[ -v targets ]]; then
226 echo "targets: ${targets[*]}"
227 fi
228
229 if [[ $source ]]; then
230 echo "source: $source"
231 fi
232
233 if [[ ${mountpoints[0]} ]]; then
234 for mp in ${mountpoints[@]}; do
235 if [[ -e /nocow/btrfs-stale/$mp ]]; then
236 die "error: $mp is stale, mount-latest-subvol first"
237 fi
238 done
239 else
240 # set default mountpoints
241 if [[ ${targets[0]} == tp ]]; then
242 prospective_mps=(/a)
243 else
244 case $HOSTNAME in
245 frodo)
246 prospective_mps=(/i)
247 ;;
248 *)
249 prospective_mps=()
250 if [[ $source ]]; then
251 source_state="$(ssh $source cat /a/bin/bash_unpublished/source-state)"
252 eval "$source_state"
253 source_host="$(ssh $source cat /etc/hostname)"
254 if [[ $source_host == "$MAIL_HOST" ]]; then
255 prospective_mps+=(/o)
256 fi
257 else
258 if [[ $HOSTNAME == "$MAIL_HOST" ]]; then
259 # HOST2 is really the mail host if it exists
260 if [[ $HOST2 && $HOST2 != "$HOSTNAME" ]]; then
261 echo "skipping /o because HOST2 is not us"
262 else
263 prospective_mps+=(/o)
264 fi
265 fi
266 fi
267 # note: put q last just in case its specific retention options were to
268 # affect other config sections. I havent tested if that is the case.
269 prospective_mps+=(/a /ar /qr /q)
270 ;;
271 esac
272 fi
273 for mp in ${prospective_mps[@]}; do # default mountpoints to sync
274 if [[ -e /nocow/btrfs-stale/$mp ]]; then
275 e "warning: $mp stale, not adding to default mountpoints"
276 continue
277 fi
278 if awk '{print $2}' /etc/fstab | grep -xF $mp &>/dev/null; then
279 mountpoints+=($mp)
280 fi
281 done
282 fi
283
284 echo "mountpoints: ${mountpoints[*]}"
285
286 ##### end command line parsing ########
287
288 if [[ $source ]]; then
289 if [[ $(ssh $source ps --no-headers -o comm 1) == systemd ]]; then
290 status=$(ssh $source systemctl is-active btrbk.service) || : # normally returns 3
291 case $status in
292 inactive|failed) : ;;
293 *)
294 echo "$0: error: cron btrbk is running on source. exiting out of caution"
295 mexit 1
296 esac
297 fi
298 fi
299
300 # pull_reexec stops us from getting into an infinite loop if there is some
301 # kind of weird problem
302 pulla=false
303 for m in "${mountpoints[@]}"; do
304 if [[ $m == /a ]]; then
305 pulla=true
306 break
307 fi
308 done
309 if ! $pull_reexec && [[ $source ]] && $pulla ; then
310 tmpf=$(mktemp)
311 m rsync -ra $source:/usr/local/bin/{mount-latest-subvol,check-subvol-stale} /usr/local/bin
312 m rsync -ra $source:/usr/local/lib/err /usr/local/lib
313 m scp $source:/a/bin/distro-setup/btrbk-run $tmpf
314 if ! diff -q $tmpf ${BASH_SOURCE[0]}; then
315 e "found different version on host $source. reexecing"
316 install -T $tmpf /usr/local/bin/btrbk-run
317 m /usr/local/bin/btrbk-run --pull-reexec "${orig_args[@]}"
318 mexit 0
319 fi
320 fi
321
322
323 if ! command -v btrbk &>/dev/null; then
324 die "error: no btrbk binary found"
325 fi
326 # if our mountpoints are from stale snapshots,
327 # it doesn't make sense to do a backup.
328 check-subvol-stale ${mountpoints[@]} || die "found stale mountpoints in ${mountpoints[*]}"
329
330 # for an initial run, btrbk requires the dir to exist.
331 mkdir -p /mnt/{root,o}/btrbk
332 local_zone=$(date +%z)
333
334 if [[ $source ]]; then
335 if ! zone=$(ssh root@$source date +%z); then
336 die failed to ssh to root@$source
337 fi
338 if [[ $zone != "$local_zone" ]]; then
339 die "error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
340 fi
341
342 else
343
344 sshable=()
345 sshfail=()
346 min_idle_ms=$((1000 * 60 * 15))
347 for h in ${targets[@]}; do
348 if remote_info=( $(timeout -s 9 6 ssh root@$h "mkdir -p /mnt/root/btrbk /mnt/o/btrbk && date +%z && df --output=size,pcent / | tail -n1") ); then
349 zone=${remote_info[0]}
350 root_size=${remote_info[1]}
351 percent_used=${remote_info[2]%%%}
352
353 if (( ${#remote_info[@]} != 3 )); then
354 die "error: didnt get 3 fields in test ssh to target $h. investigate"
355 fi
356
357
358 # we may be booted into a bootstrap fs or something
359 min_root_kb=$(( 1024 * 1024 * 200 )) # 200 gb
360 if (( root_size < min_root_kb )); then
361 continue
362 fi
363
364 if (( percent_used >= 98 )); then
365 die "error: filesystem on target $h is $percent_used % full"
366 fi
367
368 # This is a separate ssh because xprintidle can fail and thats ok.
369 if $cron && idle_ms=$(timeout -s 9 6 ssh $h DISPLAY=:0 xprintidle); then
370 if (( idle_ms < min_idle_ms )); then
371
372 # Ignore this host. i sometimes use a non-main machine for
373 # testing or web browsing, knowing that everything will be wiped
374 # by the next backup, but I dont want it to happen as Im using
375 # it from cronjob.
376 e "warning: $h: active X session in the last 15 minutes, skipping for now"
377 continue
378 fi
379 fi
380 sshable+=($h)
381 if [[ $zone != "$local_zone" ]]; then
382 die "error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
383 fi
384 else
385 sshfail+=($h)
386 fi
387 done
388 if [[ ! ${sshable[*]} ]] || { ! $cron && [[ ${sshfail[*]} ]]; }; then
389 die "failed to ssh to hosts: ${sshfail[*]}"
390 else
391 if [[ ${sshfail[*]} ]]; then
392 ret=1
393 e "error: failed to ssh to ${sshfail[*]} but continuing with other hosts"
394 fi
395 targets=(${sshable[@]})
396 fi
397 fi
398
399
400 cat >/etc/btrbk.conf <<EOF
401 ssh_identity /q/root/h
402 #ssh_identity /root/.ssh/home
403
404 # Just a guess that local7 is a good facility to pick.
405 # It's a bit odd that the transaction log has to be logged to
406 # a file or syslog, while other output is sent to std out.
407 # The man does not mention a way for them to be together, but
408 # I dunno if setting a log level like warn might also output
409 # transaction info.
410 transaction_syslog local7
411
412 # trying this out
413 stream_compress zstd
414
415 # so we only run one at a time
416 lockfile /var/lock/btrbk.lock
417
418 # default format of short does not accomidate hourly preservation setting
419 timestamp_format long-iso
420
421 # only make a snapshot if things have changed
422 snapshot_create onchange
423 # I could make this different from target_preserve,
424 # if one disk had less space.
425 # for now, keeping them equal.
426 snapshot_preserve 18h 14d 8w 24m
427 snapshot_preserve_min 2h
428 snapshot_dir btrbk
429 # so, total backups = ~58
430 target_preserve 18h 14d 8w 24m
431 target_preserve_min 2h
432
433 # if something fails and it's not obvious, try doing
434 # btrbk -l debug -v dryrun
435
436 rate_limit $rate_limit
437 EOF
438
439 if $incremental_strict; then
440 cat >>/etc/btrbk.conf <<EOF
441 incremental strict
442 EOF
443 fi
444
445 for m in ${mountpoints[@]}; do
446 case $m in
447 /o)
448 vol=/mnt/o
449 ;;
450 *)
451 vol=/mnt/root
452 ;;
453 esac
454
455 sub=${m#/}
456 if [[ $source ]]; then
457 cat >>/etc/btrbk.conf <<EOF
458 volume ssh://$bbksource$vol
459 subvolume $sub
460 target send-receive $vol/btrbk
461 EOF
462 fi
463 if (( ${#targets[@]} )); then
464 cat >>/etc/btrbk.conf <<EOF
465 volume $vol
466 subvolume $sub
467 EOF
468 case $sub in
469 q)
470 # q has sensitive data i dont want to backup for so long
471 cat >>/etc/btrbk.conf <<EOF
472 snapshot_preserve 18h 14d
473 snapshot_preserve_min 2h
474 snapshot_dir btrbk
475 target_preserve 18h 14d
476 target_preserve_min 2h
477 EOF
478 ;;
479 esac
480 for tg in ${targets[@]}; do
481 # handle ipv6
482 if [[ $tg == *:* ]]; then
483 tg="[$tg]"
484 fi
485 cat >>/etc/btrbk.conf <<EOF
486 target send-receive ssh://$tg$vol/btrbk
487 EOF
488 done
489 fi
490 done
491
492 # if $amy; then
493 # # to manually backup amy,
494 # # bbk -e -s amy -m root_ubuntubionic
495 # cat >>/etc/btrbk.conf <<'EOF'
496 # volume ssh://amy/mnt/root
497 # subvolume root_ubuntubionic
498 # target send-receive /mnt/root/btrbk
499 # EOF
500 # fi
501
502 # todo: umount first to ensure we don't have any errors
503 # todo: do some kill fuser stuff to make umount more reliable
504
505
506 if $conf_only; then
507 mexit 0
508 fi
509
510
511
512 if $dry_run; then
513 m btrbk -v -n $cmd_arg
514 mexit 0
515 elif [[ $cmd_arg == archive ]]; then
516 if [[ $source ]]; then
517 m btrbk $verbose_arg $progress_arg $cmd_arg ssh://$source$vol $vol
518 else
519 for tg in ${targets[@]}; do
520 m btrbk $verbose_arg $progress_arg $cmd_arg $vol ssh://$tg$vol
521 done
522 fi
523 mexit 0
524 fi
525 # -q and just using the syslog option seemed nice,
526 # but it doesn't show when a send has a parent and when it doesn't.
527 m btrbk $verbose_arg $progress_arg $cmd_arg
528
529 # todo: tp not valid anymore.
530 # if we have it, sync to systems which don't
531 if mountpoint $rsync_mountpoint >/dev/null; then
532 for tg in ${targets[@]}; do
533 case $tg in
534 tp)
535 dirs=(/p/c/machine_specific/tp)
536 for x in /p/c/machine_specific/*.hosts; do
537 if grep -qxF $tg $x; then
538 dirs+=(${x%.hosts})
539 fi
540 done
541 m rsync -aSAXPH --specials --devices --delete --relative ${dirs[@]} root@$tg:/
542 ;;
543 esac
544 done
545 fi
546
547 if [[ $source ]]; then
548 m mount-latest-subvol
549 else
550 m /a/exe/mount-latest-remote ${targets[@]}
551 fi
552
553 if [[ $ret == 0 ]]; then
554 for tg in ${targets[@]}; do
555 :
556 #ssh root@$tg /a/exe/mail-backup-clean
557 done
558 fi
559
560 mexit $ret
561
562 # todo: move variable data we don't care about backing up
563 # to /nocow and symlink it.
564
565
566 # background on btrbk timezones. with short/long, timestamps use local time.
567 # for long, if your local time moves backwards, by moving timezones or
568 # for an hour when daylight savings changes it, you will temporarily get
569 # a more aggressive retention policy for the overlapping period, and
570 # vice versa for the opposite timezone move. The alternative is using
571 # long-iso, which puts timezone info into the timestamp, which means
572 # that instead of shifting time, you shift the start of day/week/month
573 # which is used for retention to your new local time, which means for
574 # example, if you moved forward by 8 hours, the daily/weekly/monthly
575 # retention will be 8 hours more aggressive since midnight is at a new
576 # time, unless you fake the timzeone using the TZ env variable.
577 # However, in the short term, there will be no inconsistencies.
578 # I don't see any problem with shifting when the day starts for
579 # retention, so I'm using long-iso.
580
581 # note to create a long-iso timestamp: date +%Y%m%dT%H%M%S%z