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