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##*/}"
47 if $dry_run ||
$conf_only; then
48 printf "$pre dry-run: %s\n" "$*"
50 printf "$pre running: %s\n" "$*"
54 m
() { if $verbose; then printf "$pre %s\n" "$*"; fi; "$@"; }
55 e
() { printf "$pre %s\n" "$*"; }
56 die
() { printf "$pre error: %s\n" "$*" >&2; echo "$pre exiting with status 1" >&2; exit 1; }
57 mexit
() { echo "$pre exiting with status $1"; exit $1; }
59 uninstalled-file-die
() {
60 die
"uninstalled file $1. run install-my-scripts or rerun with -f"
72 if [[ $
(dig +short @
10.2.0.1 -x 10.2.0.2 2>&1 ||
:) == kd.b8.nz.
]] \
73 && ip n show
10.2.0.1 |
grep .
&>/dev
/null
; then
75 elif ping -q -c1 -w1 hal.office.fsf.org
&>/dev
/null \
76 && ip n show
192.168.0.26 |
grep .
&>/dev
/null
; then
83 exit-if-no-default-targets
() {
84 if ! $force && [[ $HOSTNAME != "$MAIL_HOST" ]]; then
85 echo "MAIL_HOST=$MAIL_HOST, nothing to do"
89 kw|kd|frodo|x2|x3|sy
) : ;;
91 die
"error: no default targets for this host, use -t"
98 if ping -q -c1 -w1 x3.office.fsf.org
&>/dev
/null
; then
99 targets
+=(x3.office.fsf.org
)
100 elif ping -q -c1 -w1 $h.b8.nz
&>/dev
/null
; then
101 # in case we took it home
104 targets
+=(x3wg.b8.nz
)
108 add-wireless-target-h
() {
109 if ping -q -c1 -w1 $h.b8.nz
&>/dev
/null
; then
111 elif ping -q -c1 -w1 ${h}w.b8.nz
&>/dev
/null
; then
112 targets
+=(${h}w.b8.nz
)
119 # q has sensitive data i dont want to backup for so long
120 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
121 snapshot_preserve $q_preserve
122 snapshot_preserve_min 2h
124 target_preserve $q_preserve
125 target_preserve_min 2h
134 if [[ -e /b
/bash_unpublished
/source-state
]]; then
135 source /b
/bash_unpublished
/source-state
138 # note q is owned by root:1000
147 dry_run
=false
# mostly for testing
149 verbose
=true
; verbose_arg
=-v
151 if [[ $INVOCATION_ID ]]; then
152 # INVOCATION_ID means running as a systemd service. we cant show progress in this case,
153 # but if we pass the arg, it will insert mbuffer into the command.
156 progress_arg
="--progress"
158 incremental_strict
=false
161 default_args_file
=/etc
/btrbk-run.conf
162 if [[ -s $default_args_file ]]; then
163 # shellcheck disable=SC2046 # we want word splitting
164 set -- $
(< $default_args_file) "$@"
165 # i havent used this feature yet, so warn about it
166 echo "$0: warning: default btrbk-run options set in $default_args_file (sleeping 5 seconds):"
167 cat $default_args_file
171 once_args_file
=/etc
/btrbk-run-once.conf
172 if mv -f $once_args_file $once_args_file-tmp 2> >(sed '/No such file or directory/d'); then
173 # shellcheck disable=SC2046 # we want word splitting
174 set -- $
(< $once_args_file-tmp) "$@"
175 # i havent used this feature yet, so warn about it
176 echo "$0: btrbk-run options set in $once_args_file:"
177 cat $once_args_file-tmp
178 rm -f $once_args_file-tmp
186 check_installed
=false
188 temp
=$
(getopt
-l check-installed
,fast
,pull-reexec
,help 23cefikl
:m
:npqrs
:t
:vh
"$@") || usage
1
192 # for the rare case we want to run multiple instances at the same time
195 # only creates the config file, does not run btrbk
196 -c) conf_only
=true
;;
200 # quit early, just btrbk, no extra remounting etc.
202 # avoids some default behaviors:
203 # - no skipping hosts where xprintidle haven't been idle recently
204 # - exit if we can't ssh to 1 or more hosts
205 # - still set default hosts despite MAIL_HOST status
207 # skip various checks. when we run twice in a row for
208 # switch mail-host, no need to repeat the same checks again.
210 -i) incremental_strict
=true
;;
211 # note this implies resume and -p because it is just meant to make
212 # other hosts have the same snapshots, not do any expiry or new
214 -k) kd_spread
=true
;;
215 # bytes per second, suffix k m g
216 -l) rate_limit
=$2; shift ;;
217 # Comma separated mountpoints to backup. This has defaults set below.
218 -m) IFS
=, mountpoints
=($2); unset IFS
; shift ;;
220 # preserve existing snapshots and backups
221 -p) preserve_arg
=-p ;;
222 # internal option for rerunning under newer SOURCE_HOST version.
223 --pull-reexec) pull_reexec
=true
;;
225 -q) verbose
=false
; verbose_arg
=; progress_arg
= ;;
226 # source host to receive a backup from
230 if [[ $source == *:* ]]; then
231 bbksource
="[$source]"
235 # target hosts to send to. empty is valid for just doing local
236 # snapshot. we have default hosts we will populate.
237 -t) IFS
=, targets
=($2); unset IFS
; shift ;;
239 -v) verbose
=true
; verbose_arg
=-v ;;
242 *) die
"Internal error!" ;;
251 if ! $force && { $check_installed ||
[[ ! $source ]]; } ; then
257 for f
in ${install_bin_files[@]}; do
258 if ! diff -q /a
/bin
/ds
/$f /usr
/local
/bin
/$f; then
259 uninstalled-file-die
$f
262 if ! diff -q /a
/bin
/errhandle
/err
/usr
/local
/lib
/err
; then
263 uninstalled-file-die err
265 if $check_installed; then
272 if [[ $cmd_arg && $cmd_arg != resume
]]; then
273 die
"dont pass -k without resume or empty run arg"
275 if [[ $HOSTNAME == "$MAIL_HOST" ]]; then
276 die
"something went wrong, -k not meant to be run on MAIL_HOST"
278 if [[ $HOSTNAME != kd
]]; then
279 die
"something went wrong, -k only meant to run on kd"
284 add-wireless-target-h
287 if [[ ! $cmd_arg ]]; then
292 std_preserve
="36h 14d 8w 24m"
293 q_preserve
="18h 14d 8w"
298 # This works better than the normal archive command. We have to
299 # specify the mount points, but that is what we are used to doing and
300 # we prefer it. Another difference is that archive works recursively
301 # and we don't care about that. Sometimes we may still want to run
302 # btrbk archive, but it doesn't even use the config file, so just
303 # run it directly, eg:
304 # time s btrbk -v archive /mnt/r7/amy/boot/btrbk ssh://bo/mnt/boot2/btrbk
307 std_preserve
="999h 999d 999w 999m"
308 q_preserve
="$std_preserve"
311 *) die
"untested command arg" ;;
314 if (( $# > 1 )); then
315 die
: "only 1 nonoption arg is supported"
318 if [[ -v targets
&& $source ]]; then
319 # note, this doesnt need to be the case, but
320 # we would need to think about it.
321 die
"error: -t and -s are mutually exclusive"
324 ### end options parsing
326 # remove path from earlier version of btrbk
327 rm -f /usr
/sbin
/btrbk
328 # note, this still works as intended if there is no /usr/bin/btrbk
329 if [[ /a
/opt
/btrbk
/btrbk
-nt /usr
/bin
/btrbk
]]; then
330 if [[ -e /b
/distro-functions
/src
/package-manager-abstractions
]]; then
331 .
/b
/distro-functions
/src
/package-manager-abstractions
338 # TODO: i wonder if there should be an option to send to the default
339 # targets, plus any given on the command line.
346 # set default targets
347 if [[ ! -v targets
&& ! $source ]]; then
348 exit-if-no-default-targets
351 if ! $kd_spread && [[ $HOSTNAME != x3
]]; then
354 if [[ $HOSTNAME != kd
]]; then
357 wireless_home_hosts
=(
361 for h
in ${wireless_home_hosts[@]}; do
362 if [[ $HOSTNAME != "$h" ]]; then
363 add-wireless-target-h
368 for h
in x2 x3 kw
; do
369 if [[ $HOSTNAME == "$h" ]]; then
372 if ping -q -c1 -w1 $h.office.fsf.org
&>/dev
/null
; then
373 targets
+=($h.office.fsf.org
)
381 if [[ ${mountpoints[0]} ]]; then
382 for mp
in ${mountpoints[@]}; do
383 if [[ -e /nocow
/btrfs-stale
/$mp ]]; then
384 die
"error: $mp is stale, mount-latest-subvol first"
388 # set default mountpoints
389 if [[ ${targets[0]} == tp
]]; then
395 if [[ $source ]]; then
396 source_state
="$(ssh $source 'cat /a/bin/bash_unpublished/source-state; echo source_host=$HOSTNAME')"
398 # shellcheck disable=SC2154 # assigned in the above eval.
399 if [[ $source_host == "$MAIL_HOST" ]]; then
400 prospective_mps
+=(/o
)
402 if [[ $source_host == "$HOST2" ]]; then
403 prospective_mps
+=(/a
/ar /qr
/qd
/q
)
406 if [[ $HOSTNAME == "$MAIL_HOST" ]]; then
407 prospective_mps
+=(/o
)
409 if [[ $HOSTNAME == "$HOST2" ]]; then
410 prospective_mps
+=(/a
/ar /qr
/qd
/q
)
413 prospective_mps
=(/a
/ar /o
/qr
/qd
/q
)
416 # note: put q last just in case its specific retention options were to
417 # affect other config sections. I havent tested if that is the case.
421 for mp
in ${prospective_mps[@]}; do # default mountpoints to sync
422 if [[ -e /nocow
/btrfs-stale
/$mp ]]; then
423 e
"warning: $mp stale, not adding to default mountpoints"
426 if awk '{print $2}' /etc
/fstab |
grep -xF $mp &>/dev
/null
; then
432 tmp
=$
(( ${#mountpoints[@]} == 0 ))
434 die didnt get mountpoint arg and had no defaults
437 ##### end command line parsing ########
439 #### begin pre-checks #####
441 # todo: this has a timing problem, since btrbk.timer could activate the service after this check.
442 if ! $fast && [[ $source ]]; then
443 if [[ $
(ssh $source ps
--no-headers -o comm 1) == systemd
]]; then
444 status
=$
(ssh $source systemctl is-active btrbk.service
) ||
: # normally returns 3
446 inactive|failed
) : ;;
448 echo "$0: error: btrbk is running on source. exiting out of caution"
454 if ! command -v btrbk
&>/dev
/null
; then
455 die
"error: no btrbk binary found"
458 if ! $pull_reexec && [[ $source ]] && $pulla && ! $force ; then
459 ssh root@
$source btrbk-run
--check-installed ||
exit 1
462 #### end pre-checks #####
466 mkdir
-p /var
/log
/btrbk
467 # The journal doesnt go back to my oldest backups, and I've found myself
468 # wanting older logs. Not going to bother expiring old logs, since it is
469 # fine if they go back years.
470 log_path
=/var
/log
/btrbk
/$
(date +%F_
%T
%:::z
).log
471 echo copying output to
$log_path
472 exec &> >(pee
cat 'ts "%F %T"|dd of='$log_path' status=none')
476 printf " options: conf_only=%s\ndry_run=%s\nrate_limit=%s\nverbose=%s\ncmd_arg=%s\n" "$conf_only" "$dry_run" "$rate_limit" "$verbose" "$cmd_arg"
479 if [[ -v targets
]]; then
480 echo "targets: ${targets[*]}"
483 if [[ $source ]]; then
484 echo "source: $source"
487 echo "mountpoints: ${mountpoints[*]}"
492 # pull_reexec stops us from getting into an infinite loop if there is some
493 # kind of weird problem
495 for m
in "${mountpoints[@]}"; do
496 if [[ $m == /a
]]; then
502 if ! $pull_reexec && [[ $source ]] && $pulla ; then
504 m rsync
-ra $source:/usr
/local
/bin
/{mount-latest-subvol
,check-subvol-stale
} /usr
/local
/bin
505 m rsync
-ra $source:/usr
/local
/lib
/err
/usr
/local
/lib
506 m scp
$source:/a
/bin
/distro-setup
/btrbk-run
$tmpf
507 if ! diff -q $tmpf ${BASH_SOURCE[0]}; then
508 e
"found different version on host $source. reexecing"
509 install -T $tmpf /usr
/local
/bin
/btrbk-run
510 m
/usr
/local
/bin
/btrbk-run
--pull-reexec "${orig_args[@]}"
517 # if our mountpoints are from stale snapshots,
518 # it doesn't make sense to do a backup.
519 m check-subvol-stale
${mountpoints[@]} || die
"found stale mountpoints in ${mountpoints[*]}"
521 # for an initial run, btrbk requires the dir to exist.
522 mkdir
-p /mnt
/{root
,o
}/btrbk
524 local_zone
=$
(date +%z
)
526 if [[ $source ]]; then
530 if ! zone
=$
(ssh root@
$source date +%z
); then
532 echo "$0: warning: failed to ssh to root@$source"
534 die failed to
ssh to root@
$source
537 if [[ $zone != "$local_zone" ]]; then
538 die
"error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
545 for h
in ${targets[@]}; do
546 if $fast ||
$conf_only; then
547 # Use some typical values in this case
548 root_size
=$
(( 1024 * 1024 * 2000 )) #2tb
551 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
552 mapfile
-t tmp_array
<<<"$remote_str"
553 zone
="${tmp_array[0]}"
554 IFS
=" " read -r root_size percent_used
<<<"${tmp_array[1]}"
555 percent_used
=${percent_used%%%}
557 tmp
=$
(( ${#tmp_array[@]} != 2 ))
559 die
"error: didnt get 2 lines in test ssh to target $h. investigate"
561 case $percent_used in
562 [0-9]|
[1-9][0-9]) : ;;
564 die
"error: didnt get percent disk use in test ssh to target $h. investigate"
572 # we may be booted into a bootstrap fs or something
573 min_root_kb
=$
(( 1024 * 1024 * 200 )) # 200 gb
574 tmp
=$
(( root_size
< min_root_kb
))
579 tmp
=$
(( percent_used
>= 98 ))
581 die
"error: filesystem on target $h is $percent_used % full"
584 # on sy, xprintidle is resetting every 12 seconds even when not
585 # idle, i dunno why, instead we are checking if the screen is locked,
586 # which is good enough.
588 # This is a separate ssh because the command can fail and thatis ok.
591 if lock_info
=$
(timeout
-s 9 6 ssh $h DISPLAY
=:0 xscreensaver-command
-time); then
592 if [[ $lock_info != *non-blanked
* ]]; then
599 # Ignore this host. i sometimes use a non-main machine for
600 # testing or web browsing, knowing that everything will be wiped
601 # by the next backup, but I dont want it to happen as Im using
603 e
"warning: $h: seems to be actively in use, skipping for now"
608 if [[ $zone != "$local_zone" ]]; then
609 die
"error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
612 if [[ ! ${sshable[*]} ]] || { $force && [[ ${sshfail[*]} ]]; }; then
613 die
"failed to ssh to hosts: ${sshfail[*]}"
615 if [[ ${sshfail[*]} ]]; then
617 e
"error: failed to ssh to ${sshfail[*]} but continuing with other hosts"
619 targets
=(${sshable[@]})
624 cat >/etc
/btrbk
$conf_suf.conf
<<EOF
625 ssh_identity /q/root/h
626 #ssh_identity /root/.ssh/home
628 # Just a guess that local7 is a good facility to pick.
629 # It's a bit odd that the transaction log has to be logged to
630 # a file or syslog, while other output is sent to std out.
631 # The man does not mention a way for them to be together, but
632 # I dunno if setting a log level like warn might also output
634 transaction_syslog local7
637 #stream_compress zstd
639 # so we only run one at a time
640 lockfile /var/lock/btrbk$conf_suf.lock
642 # default format of short does not accomidate hourly preservation setting
643 timestamp_format long-iso
645 # only make a snapshot if things have changed
646 snapshot_create onchange
647 # I could make this different from target_preserve,
648 # if one disk had less space.
649 # for now, keeping them equal.
650 snapshot_preserve $std_preserve
651 snapshot_preserve_min 6h
653 # so, total backups = ~58
654 target_preserve $std_preserve
655 target_preserve_min 6h
657 # it seems very likely that not doing this could result in clone source not found
658 # errors, for example when expiry happens differently on different hosts,
659 # also, as btrbk does by default, if a failed send happens, on the next run it
660 # will warn about a stray subvolume, but then create a backup of a newer subvol
661 # and use an older subvol as the parent.
662 incremental_prefs sao:1
664 # if something fails and it's not obvious, try doing
665 # btrbk -l debug -v dryrun
667 rate_limit $rate_limit
670 if $incremental_strict; then
671 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
678 mp_count
=${#mountpoints[@]}
679 for (( i
=0; i
< mp_count
- 1 ; i
++ )); do
680 if [[ ${mountpoints[i]} == /q
]]; then
681 unset "mountpoints[i]"
690 declare -A source_snaps
692 for m
in ${mountpoints[@]}; do
703 snap_list_cmds
+=("echo $vol/btrbk/$sub.*;")
705 if [[ $source ]]; then
706 tmp_a
=($vol/btrbk
/$sub.
*)
707 tg_snaps
+=("${tmp_a[*]}")
708 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
709 volume ssh://$bbksource$vol
713 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
714 target send-receive $vol/btrbk
716 else # we have targets
717 for snap
in "$vol/btrbk/$sub."*; do
718 source_snaps
[$snap]=t
721 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
726 for tg
in ${targets[@]}; do
728 if [[ $tg == *:* ]]; then
731 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
732 target send-receive ssh://$tg$vol/btrbk
738 # Delete any subvols on the receiving host that don't exist on the
739 # sending host. Otherwise, the receiving host could have snapshots that
740 # aren't on the sending side, and thus become odd leaf subvols, and then
741 # btrbk could try to use them when we sync back, creating a weird tree
742 # instead of linear parent/child relationship. Maybe this could lead to
743 # a missing source subvol error, so lets avoid it.
745 get-orphan-tg-snaps
() {
747 for (( i
=0; i
< ${#mountpoints[@]}; i
++ )); do
748 orphan_start_count
=${#orphan_tg_snaps[@]}
750 for tg_snap
in ${tg_snaps[$i]}; do
751 tg_snap_count
=$
(( tg_snap_count
+ 1 ))
752 if [[ ! ${source_snaps[$tg_snap]} ]]; then
753 orphan_tg_snaps
+=("$tg_snap")
756 orphan_mp_count
=$
(( ${#orphan_tg_snaps[@]} - orphan_start_count
))
758 tmp
=$
(( tg_snap_count
> 1 && tg_snap_count
== orphan_mp_count
))
760 die
"something went wrong checking orphans on $tg: for mountpoint ${mountpoints[$i]}, $orphan_mp_count"
765 if [[ $source ]]; then
766 for snap
in $
(ssh root@
$source "shopt -s nullglob; ${snap_list_cmds[*]}"); do
767 source_snaps
[$snap]=t
770 tmp
=$
(( ${#orphan_tg_snaps[*]} >= 1 ))
772 d btrfs sub del
${orphan_tg_snaps[*]}
774 else # we have targets
775 for tg
in ${targets[@]}; do
776 tmp_str
=$
(ssh root@
$tg "shopt -s nullglob; ${snap_list_cmds[*]}")
777 mapfile
-t tg_snaps
<<<"$tmp_str"
779 tmp
=$
(( ${#orphan_tg_snaps[*]} >= 1 ))
781 d
ssh root@
$tg "btrfs sub del ${orphan_tg_snaps[*]}"
786 # todo: umount first to ensure we don't have any errors
787 # todo: do some kill fuser stuff to make umount more reliable
797 m btrbk
-c /etc
/btrbk
$conf_suf.conf
-v -n $cmd_arg
800 # -q and just using the syslog option seemed nice,
801 # but it doesn't show when a send has a parent and when it doesn't.
802 m btrbk
-c /etc
/btrbk
$conf_suf.conf
$preserve_arg $verbose_arg $progress_arg $cmd_arg
808 # todo: tp not valid anymore.
809 # if we have it, sync to systems which don't
810 if mountpoint
$rsync_mountpoint >/dev
/null
; then
811 for tg
in ${targets[@]}; do
814 dirs=(/p
/c
/machine_specific
/tp
)
815 for x
in /p
/c
/machine_specific
/*.hosts
; do
816 if grep -qxF $tg $x; then
820 m rsync
-aSAXPH --specials --devices --delete --relative ${dirs[@]} root@
$tg:/
827 for mp
in "${mountpoints[@]}"; do
828 subvols
+=("${mp##*/}")
830 if [[ $source ]]; then
831 m mount-latest-subvol
"${subvols[@]}"
833 for tg
in ${targets[@]}; do
834 m
/a
/exe
/mount-latest-remote
"$tg" "${subvols[@]}" || ret
=$?
838 # todo, we get hostnames earlier, reuse that.
839 if [[ $ret == 0 ]]; then
840 for tg
in ${targets[@]}; do
841 h
=$
(ssh $tg hostname
)
842 if [[ $h == kd
&& $HOSTNAME == x3
&& $HOSTNAME == "$MAIL_HOST" ]]; then
843 m
ssh root@
$tg 'btrbk-spread-wrap &>/dev/null </dev/null &'
845 rsync
-a -f"- */" -f"+ *" /var
/log
/btrbk
/ root@
$tg:/var
/log
/btrbk
/$tg
846 ssh root@
$tg /usr
/local
/bin
/mail-backup-clean
848 if [[ $source ]]; then
849 rsync
-a -f"- */" -f"+ *" $source:/var
/log
/btrbk
/ /var
/log
/btrbk
/$source
855 # todo: move variable data we don't care about backing up
856 # to /nocow and symlink it.
859 # background on btrbk timezones. with short/long, timestamps use local time.
860 # for long, if your local time moves backwards, by moving timezones or
861 # for an hour when daylight savings changes it, you will temporarily get
862 # a more aggressive retention policy for the overlapping period, and
863 # vice versa for the opposite timezone move. The alternative is using
864 # long-iso, which puts timezone info into the timestamp, which means
865 # that instead of shifting time, you shift the start of day/week/month
866 # which is used for retention to your new local time, which means for
867 # example, if you moved forward by 8 hours, the daily/weekly/monthly
868 # retention will be 8 hours more aggressive since midnight is at a new
869 # time, unless you fake the timzeone using the TZ env variable.
870 # However, in the short term, there will be no inconsistencies.
871 # I don't see any problem with shifting when the day starts for
872 # retention, so I'm using long-iso.
874 # note to create a long-iso timestamp: date +%Y%m%dT%H%M%S%z