2 # Copyright (C) 2016 Ian Kelling
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
8 # http://www.apache.org/licenses/LICENSE-2.0
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.
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
23 [[ $EUID == 0 ]] ||
exec sudo
-E "${BASH_SOURCE[0]}" "$@"
25 source /usr
/local
/lib
/err
29 btrbk-run [OPTIONS] [run|resume|archive]
30 usually -t TARGET_HOST or -s SOURCE_HOST
32 Note, at source location, intentionally not executable, run and read
36 echo "top of script file:"
37 sed -n '1,/^[# ]*end command line/{p;b};q' "$0"
44 script_name
="${BASH_SOURCE[0]}"
45 script_name
="${script_name##*/}"
46 m
() { if $verbose; then printf "$pre %s\n" "$*"; fi; "$@"; }
47 e
() { printf "$pre %s\n" "$*"; }
48 die
() { printf "$pre error: %s\n" "$*" >&2; echo "$pre exiting with status 1" >&2; exit 1; }
49 mexit
() { echo "$pre exiting with status $1"; exit $1; }
52 if [[ -e /b
/bash_unpublished
/source-state
]]; then
53 source /b
/bash_unpublished
/source-state
56 # note q is owned by root:1000
65 dry_run
=false
# mostly for testing
67 verbose
=true
; verbose_arg
=-v
69 if [[ $INVOCATION_ID ]]; then
70 # INVOCATION_ID means running as a systemd service. we cant show progress in this case,
71 # but if we pass the arg, it will insert mbuffer into the command.
74 progress_arg
="--progress"
76 incremental_strict
=false
79 default_args_file
=/etc
/btrbk-run.conf
80 if [[ -s $default_args_file ]]; then
81 # shellcheck disable=SC2046 # we want word splitting
82 set -- $
(< $default_args_file) "$@"
83 # i havent used this feature yet, so warn about it
84 echo "$0: warning: default btrbk-run options set in $default_args_file (sleeping 5 seconds):"
85 cat $default_args_file
95 temp
=$
(getopt
-l check-installed
,fast
,pull-reexec
,help 23cefikl
:m
:npqrs
:t
:vh
"$@") || usage
1
99 # for the rare case we want to run multiple instances at the same time
102 # only creates the config file, does not run btrbk
103 -c) conf_only
=true
;;
107 # quit early, just btrbk, no extra remounting etc.
109 # avoids some default behaviors:
110 # - no skipping hosts where xprintidle haven't been idle recently
111 # - exit if we can't ssh to 1 or more hosts
112 # - still set default hosts despite MAIL_HOST status
114 # skip various checks. when we run twice in a row for
115 # switch mail-host, no need to repeat the same checks again.
117 -i) incremental_strict
=true
;;
118 # note this implies resume and -p
119 -k) kd_spread
=true
;;
120 # bytes per second, suffix k m g
121 -l) rate_limit
=$2; shift ;;
122 # Comma separated mountpoints to backup. This has defaults set below.
123 -m) IFS
=, mountpoints
=($2); unset IFS
; shift ;;
125 # preserve existing snapshots and backups
126 -p) preserve_arg
=-p ;;
127 # internal option for rerunning under newer SOURCE_HOST version.
128 --pull-reexec) pull_reexec
=true
;;
130 -q) verbose
=false
; verbose_arg
=; progress_arg
= ;;
131 # source host to receive a backup from
135 if [[ $source == *:* ]]; then
136 bbksource
="[$source]"
140 # target hosts to send to. empty is valid for just doing local
141 # snapshot. we have default hosts we will populate.
142 -t) IFS
=, targets
=($2); unset IFS
; shift ;;
144 -v) verbose
=true
; verbose_arg
=-v ;;
147 *) die
"Internal error!" ;;
155 uninstalled-file-die
() {
156 die
"uninstalled file $1. run install-my-scripts or rerun with -f"
159 if ! $force && { $check_installed ||
[[ ! $source ]]; } ; then
165 for f
in ${install_bin_files[@]}; do
166 if ! diff -q /a
/bin
/ds
/$f /usr
/local
/bin
/$f; then
167 uninstalled-file-die
$f
170 if ! diff -q /a
/bin
/errhandle
/err
/usr
/local
/lib
/err
; then
171 uninstalled-file-die err
173 if $check_installed; then
180 if [[ $cmd_arg && $cmd_arg != resume
]]; then
181 die
"dont pass -k without resume or empty run arg"
183 if [[ $HOSTNAME == "$MAIL_HOST" ]]; then
184 die
"something went wrong, -k not meant to be run on MAIL_HOST"
186 if [[ $HOSTNAME != kd
]]; then
187 die
"something went wrong, -k only meant to run on kd"
192 add-wireless-target-h
195 if [[ ! $cmd_arg ]]; then
200 std_preserve
="36h 14d 8w 24m"
201 q_preserve
="18h 14d 8w"
206 # This works better than the normal archive command. We have to
207 # specify the mount points, but that is what we are used to doing and
208 # we prefer it. Another difference is that archive works recursively
209 # and we don't care about that. Sometimes we may still want to run
210 # btrbk archive, but it doesn't even use the config file, so just
211 # run it directly, eg:
212 # time s btrbk -v archive /mnt/r7/amy/boot/btrbk ssh://bo/mnt/boot2/btrbk
215 std_preserve
="999h 999d 999w 999m"
216 q_preserve
="$std_preserve"
219 *) die
"untested command arg" ;;
222 if (( $# > 1 )); then
223 die
: "only 1 nonoption arg is supported"
226 if [[ -v targets
&& $source ]]; then
227 # note, this doesnt need to be the case, but
228 # we would need to think about it.
229 die
"error: -t and -s are mutually exclusive"
232 ### end options parsing
234 # remove path from earlier version of btrbk
235 rm -f /usr
/sbin
/btrbk
236 # note, this still works as intended if there is no /usr/bin/btrbk
237 if [[ /a
/opt
/btrbk
/btrbk
-nt /usr
/bin
/btrbk
]]; then
238 if [[ -e /b
/distro-functions
/src
/package-manager-abstractions
]]; then
239 .
/b
/distro-functions
/src
/package-manager-abstractions
246 # TODO: i wonder if there should be an option to send to the default
247 # targets, plus any given on the command line.
263 if [[ $
(dig +short @
10.2.0.1 -x 10.2.0.2 2>&1 ||
:) == kd.b8.nz.
]] \
264 && ip n show
10.2.0.1 |
grep .
&>/dev
/null
; then
266 elif ping -q -c1 -w1 hal.office.fsf.org
&>/dev
/null \
267 && ip n show
192.168.0.26 |
grep .
&>/dev
/null
; then
274 exit-if-no-default-targets
() {
275 if ! $force && [[ $HOSTNAME != "$MAIL_HOST" ]]; then
276 echo "MAIL_HOST=$MAIL_HOST, nothing to do"
280 kw|kd|frodo|x2|x3|sy
) : ;;
282 die
"error: no default targets for this host, use -t"
289 if ping -q -c1 -w1 x3.office.fsf.org
&>/dev
/null
; then
290 targets
+=(x3.office.fsf.org
)
291 elif ping -q -c1 -w1 $h.b8.nz
&>/dev
/null
; then
292 # in case we took it home
295 targets
+=(x3wg.b8.nz
)
299 add-wireless-target-h
() {
300 if ping -q -c1 -w1 $h.b8.nz
&>/dev
/null
; then
302 elif ping -q -c1 -w1 ${h}w.b8.nz
&>/dev
/null
; then
303 targets
+=(${h}w.b8.nz
)
308 # set default targets
309 if [[ ! -v targets
&& ! $source ]]; then
310 exit-if-no-default-targets
313 if ! $kd_spread && [[ $HOSTNAME != x3
]]; then
316 if [[ $HOSTNAME != kd
]]; then
319 wireless_home_hosts
=(
323 for h
in ${wireless_home_hosts[@]}; do
324 if [[ $HOSTNAME != "$h" ]]; then
325 add-wireless-target-h
330 for h
in x2 x3 kw
; do
331 if [[ $HOSTNAME == "$h" ]]; then
334 if ping -q -c1 -w1 $h.office.fsf.org
&>/dev
/null
; then
335 targets
+=($h.office.fsf.org
)
343 if [[ ${mountpoints[0]} ]]; then
344 for mp
in ${mountpoints[@]}; do
345 if [[ -e /nocow
/btrfs-stale
/$mp ]]; then
346 die
"error: $mp is stale, mount-latest-subvol first"
350 # set default mountpoints
351 if [[ ${targets[0]} == tp
]]; then
357 if [[ $source ]]; then
358 source_state
="$(ssh $source cat /a/bin/bash_unpublished/source-state)"
360 source_host
="$(ssh $source cat /etc/hostname)"
361 if [[ $source_host == "$MAIL_HOST" ]]; then
362 prospective_mps
+=(/o
)
364 if [[ $source_host == "$HOST2" ]]; then
365 prospective_mps
+=(/a
/ar /qr
/qd
/q
)
368 if [[ $HOSTNAME == "$MAIL_HOST" ]]; then
369 prospective_mps
+=(/o
)
371 if [[ $HOSTNAME == "$HOST2" ]]; then
372 prospective_mps
+=(/a
/ar /qr
/qd
/q
)
375 prospective_mps
=(/a
/ar /o
/qr
/qd
/q
)
378 # note: put q last just in case its specific retention options were to
379 # affect other config sections. I havent tested if that is the case.
383 for mp
in ${prospective_mps[@]}; do # default mountpoints to sync
384 if [[ -e /nocow
/btrfs-stale
/$mp ]]; then
385 e
"warning: $mp stale, not adding to default mountpoints"
388 if awk '{print $2}' /etc
/fstab |
grep -xF $mp &>/dev
/null
; then
394 if (( ! ${#mountpoints[@]} )); then
395 die didnt get mountpoint arg and had no defaults
398 ##### end command line parsing ########
400 #### begin pre-checks #####
402 # todo: this has a timing problem, since btrbk.timer could activate the service after this check.
403 if ! $fast && [[ $source ]]; then
404 if [[ $
(ssh $source ps
--no-headers -o comm 1) == systemd
]]; then
405 status
=$
(ssh $source systemctl is-active btrbk.service
) ||
: # normally returns 3
407 inactive|failed
) : ;;
409 echo "$0: error: btrbk is running on source. exiting out of caution"
415 if ! command -v btrbk
&>/dev
/null
; then
416 die
"error: no btrbk binary found"
419 if ! $pull_reexec && [[ $source ]] && $pulla && ! $force ; then
420 ssh root@
$source btrbk-run
--check-installed ||
exit 1
423 #### end pre-checks #####
427 mkdir
-p /var
/log
/btrbk
428 # The journal doesnt go back to my oldest backups, and I've found myself
429 # wanting older logs. Not going to bother expiring old logs, since it is
430 # fine if they go back years.
431 log_path
=/var
/log
/btrbk
/$
(date +%F_
%T
%:::z
).log
432 echo copying output to
$log_path
433 exec &> >(pee
cat 'ts "%F %T"|dd of='$log_path' status=none')
437 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"
440 if [[ -v targets
]]; then
441 echo "targets: ${targets[*]}"
444 if [[ $source ]]; then
445 echo "source: $source"
448 echo "mountpoints: ${mountpoints[*]}"
453 # pull_reexec stops us from getting into an infinite loop if there is some
454 # kind of weird problem
456 for m
in "${mountpoints[@]}"; do
457 if [[ $m == /a
]]; then
463 if ! $pull_reexec && [[ $source ]] && $pulla ; then
465 m rsync
-ra $source:/usr
/local
/bin
/{mount-latest-subvol
,check-subvol-stale
} /usr
/local
/bin
466 m rsync
-ra $source:/usr
/local
/lib
/err
/usr
/local
/lib
467 m scp
$source:/a
/bin
/distro-setup
/btrbk-run
$tmpf
468 if ! diff -q $tmpf ${BASH_SOURCE[0]}; then
469 e
"found different version on host $source. reexecing"
470 install -T $tmpf /usr
/local
/bin
/btrbk-run
471 m
/usr
/local
/bin
/btrbk-run
--pull-reexec "${orig_args[@]}"
478 # if our mountpoints are from stale snapshots,
479 # it doesn't make sense to do a backup.
480 m check-subvol-stale
${mountpoints[@]} || die
"found stale mountpoints in ${mountpoints[*]}"
482 # for an initial run, btrbk requires the dir to exist.
483 mkdir
-p /mnt
/{root
,o
}/btrbk
485 local_zone
=$
(date +%z
)
487 if [[ $source ]]; then
491 if ! zone
=$
(ssh root@
$source date +%z
); then
493 echo "$0: warning: failed to ssh to root@$source"
495 die failed to
ssh to root@
$source
498 if [[ $zone != "$local_zone" ]]; then
499 die
"error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
506 for h
in ${targets[@]}; do
507 if $fast ||
$conf_only; then
508 # Use some typical values in this case
509 root_size
=$
(( 1024 * 1024 * 2000 )) #2tb
512 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
513 mapfile
-t tmp_array
<<<"$remote_str"
514 zone
="${tmp_array[0]}"
515 IFS
=" " read -r root_size percent_used
<<<"${tmp_array[1]}"
516 percent_used
=${percent_used%%%}
518 if (( ${#tmp_array[@]} != 2 )); then
519 die
"error: didnt get 2 lines in test ssh to target $h. investigate"
521 case $percent_used in
522 [0-9]|
[1-9][0-9]) : ;;
524 die
"error: didnt get percent disk use in test ssh to target $h. investigate"
532 # we may be booted into a bootstrap fs or something
533 min_root_kb
=$
(( 1024 * 1024 * 200 )) # 200 gb
534 if (( root_size
< min_root_kb
)); then
538 if (( percent_used
>= 98 )); then
539 die
"error: filesystem on target $h is $percent_used % full"
542 # on sy, xprintidle is resetting every 12 seconds even when not
543 # idle, i dunno why, instead we are checking if the screen is locked,
544 # which is good enough.
546 # This is a separate ssh because the command can fail and thatis ok.
549 if lock_info
=$
(timeout
-s 9 6 ssh $h DISPLAY
=:0 xscreensaver-command
-time); then
550 if [[ $lock_info != *non-blanked
* ]]; then
557 # Ignore this host. i sometimes use a non-main machine for
558 # testing or web browsing, knowing that everything will be wiped
559 # by the next backup, but I dont want it to happen as Im using
561 e
"warning: $h: seems to be actively in use, skipping for now"
566 if [[ $zone != "$local_zone" ]]; then
567 die
"error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
570 if [[ ! ${sshable[*]} ]] || { $force && [[ ${sshfail[*]} ]]; }; then
571 die
"failed to ssh to hosts: ${sshfail[*]}"
573 if [[ ${sshfail[*]} ]]; then
575 e
"error: failed to ssh to ${sshfail[*]} but continuing with other hosts"
577 targets
=(${sshable[@]})
582 cat >/etc
/btrbk
$conf_suf.conf
<<EOF
583 ssh_identity /q/root/h
584 #ssh_identity /root/.ssh/home
586 # Just a guess that local7 is a good facility to pick.
587 # It's a bit odd that the transaction log has to be logged to
588 # a file or syslog, while other output is sent to std out.
589 # The man does not mention a way for them to be together, but
590 # I dunno if setting a log level like warn might also output
592 transaction_syslog local7
595 #stream_compress zstd
597 # so we only run one at a time
598 lockfile /var/lock/btrbk$conf_suf.lock
600 # default format of short does not accomidate hourly preservation setting
601 timestamp_format long-iso
603 # only make a snapshot if things have changed
604 snapshot_create onchange
605 # I could make this different from target_preserve,
606 # if one disk had less space.
607 # for now, keeping them equal.
608 snapshot_preserve $std_preserve
609 snapshot_preserve_min 6h
611 # so, total backups = ~58
612 target_preserve $std_preserve
613 target_preserve_min 6h
615 # i tried this when investigating: clone no source subvolume found error
616 #incremental_prefs sro:1 srn:1 sao san:1 aro:1 arn:1
618 # if something fails and it's not obvious, try doing
619 # btrbk -l debug -v dryrun
621 rate_limit $rate_limit
624 if $incremental_strict; then
625 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
633 # q has sensitive data i dont want to backup for so long
634 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
635 snapshot_preserve $q_preserve
636 snapshot_preserve_min 2h
638 target_preserve $q_preserve
639 target_preserve_min 2h
647 mp_count
=${#mountpoints[@]}
648 for (( i
=0; i
< mp_count
- 1 ; i
++ )); do
649 if [[ ${mountpoints[i]} == /q
]]; then
650 unset "mountpoints[i]"
655 for m
in ${mountpoints[@]}; do
666 if [[ $source ]]; then
667 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
668 volume ssh://$bbksource$vol
672 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
673 target send-receive $vol/btrbk
676 if (( ${#targets[@]} )); then
677 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
682 for tg
in ${targets[@]}; do
684 if [[ $tg == *:* ]]; then
687 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
688 target send-receive ssh://$tg$vol/btrbk
694 # todo: umount first to ensure we don't have any errors
695 # todo: do some kill fuser stuff to make umount more reliable
705 m btrbk
-c /etc
/btrbk
$conf_suf.conf
-v -n $cmd_arg
708 # -q and just using the syslog option seemed nice,
709 # but it doesn't show when a send has a parent and when it doesn't.
710 m btrbk
-c /etc
/btrbk
$conf_suf.conf
$preserve_arg $verbose_arg $progress_arg $cmd_arg
716 # todo: tp not valid anymore.
717 # if we have it, sync to systems which don't
718 if mountpoint
$rsync_mountpoint >/dev
/null
; then
719 for tg
in ${targets[@]}; do
722 dirs=(/p
/c
/machine_specific
/tp
)
723 for x
in /p
/c
/machine_specific
/*.hosts
; do
724 if grep -qxF $tg $x; then
728 m rsync
-aSAXPH --specials --devices --delete --relative ${dirs[@]} root@
$tg:/
735 for mp
in "${mountpoints[@]}"; do
736 subvols
+=("${mp##*/}")
738 if [[ $source ]]; then
739 m mount-latest-subvol
"${subvols[@]}"
741 for tg
in ${targets[@]}; do
742 m
/a
/exe
/mount-latest-remote
"$tg" "${subvols[@]}" || ret
=$?
746 if [[ $ret == 0 ]]; then
747 for tg
in ${targets[@]}; do
748 h
=$
(ssh $tg hostname
)
749 if [[ $h == kd
&& $HOSTNAME == x3
&& $HOSTNAME == "$MAIL_HOST" ]]; then
750 ssh root
$tg systemctl
--no-block start btrbk-spread
752 rsync
-a -f"- */" -f"+ *" /var
/log
/btrbk
/ root@
$tg:/var
/log
/btrbk
/$tg
753 ssh root@
$tg /usr
/local
/bin
/mail-backup-clean
755 if [[ $source ]]; then
756 rsync
-a -f"- */" -f"+ *" $source:/var
/log
/btrbk
/ /var
/log
/btrbk
/$source
762 # todo: move variable data we don't care about backing up
763 # to /nocow and symlink it.
766 # background on btrbk timezones. with short/long, timestamps use local time.
767 # for long, if your local time moves backwards, by moving timezones or
768 # for an hour when daylight savings changes it, you will temporarily get
769 # a more aggressive retention policy for the overlapping period, and
770 # vice versa for the opposite timezone move. The alternative is using
771 # long-iso, which puts timezone info into the timestamp, which means
772 # that instead of shifting time, you shift the start of day/week/month
773 # which is used for retention to your new local time, which means for
774 # example, if you moved forward by 8 hours, the daily/weekly/monthly
775 # retention will be 8 hours more aggressive since midnight is at a new
776 # time, unless you fake the timzeone using the TZ env variable.
777 # However, in the short term, there will be no inconsistencies.
778 # I don't see any problem with shifting when the day starts for
779 # retention, so I'm using long-iso.
781 # note to create a long-iso timestamp: date +%Y%m%dT%H%M%S%z