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"
43 script_name
="${BASH_SOURCE[0]}"
44 script_name
="${script_name##*/}"
45 m
() { if $verbose; then printf "%s\n" "$*"; fi; "$@"; }
46 e
() { printf "%s\n" "$*"; }
47 die
() { printf "%s\n" "$*" >&2; echo "exiting with status 1" >&2; exit 1; }
48 mexit
() { echo ": exiting with status $1"; exit $1; }
51 if [[ -e /b
/bash_unpublished
/source-state
]]; then
52 source /b
/bash_unpublished
/source-state
55 # note q is owned by root:1000
64 dry_run
=false
# mostly for testing
66 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.
73 progress_arg
="--progress"
75 incremental_strict
=false
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
93 temp
=$
(getopt
-l fast
,pull-reexec
,help 23cefikl
:m
:npqrs
:t
:vh
"$@") || usage
1
97 # for the rare case we want to run multiple instances at the same time
100 # only creates the config file, does not run btrbk
101 -c) conf_only
=true
;;
102 # quit early, just btrbk, no extra remounting etc.
104 # avoids some default behaviors:
105 # - no skipping hosts where xprintidle haven't been idle recently
106 # - exit if we can't ssh to 1 or more hosts
107 # - still set default hosts despite MAIL_HOST status
109 # skip various checks. when we run twice in a row for
110 # switch mail-host, no need to repeat the same checks again.
112 -i) incremental_strict
=true
;;
113 # note this implies resume and -p
114 -k) kd_spread
=true
;;
115 # bytes per second, suffix k m g
116 -l) rate_limit
=$2; shift ;;
117 # Comma separated mountpoints to backup. This has defaults set below.
118 -m) IFS
=, mountpoints
=($2); unset IFS
; shift ;;
120 # preserve existing snapshots and backups
121 -p) preserve_arg
=-p ;;
122 # internal option for rerunning under newer SOURCE_HOST version.
123 --pull-reexec) pull_reexec
=true
;;
125 -q) verbose
=false
; verbose_arg
=; progress_arg
= ;;
126 # source host to receive a backup from
130 if [[ $source == *:* ]]; then
131 bbksource
="[$source]"
135 # target hosts to send to. empty is valid for just doing local
136 # snapshot. we have default hosts we will populate.
137 -t) IFS
=, targets
=($2); unset IFS
; shift ;;
139 -v) verbose
=true
; verbose_arg
=-v ;;
142 *) die
"Internal error!" ;;
150 if [[ $cmd_arg && $cmd_arg != resume
]]; then
151 die
"dont pass -k without resume or empty run arg"
153 if [[ $HOSTNAME == "$MAIL_HOST" ]]; then
154 die
"something went wrong, -k not meant to be run on MAIL_HOST"
156 if [[ $HOSTNAME != kd
]]; then
157 die
"something went wrong, -k only meant to run on kd"
162 add-wireless-target-h
165 if [[ ! $cmd_arg ]]; then
170 std_preserve
="36h 14d 8w 24m"
171 q_preserve
="18h 14d 8w"
176 # This works better than the normal archive command. We have to
177 # specify the mount points, but that is what we are used to doing and
178 # we prefer it. Another difference is that archive works recursively
179 # and we don't care about that. Sometimes we may still want to run
180 # btrbk archive, but it doesn't even use the config file, so just
181 # run it directly, eg:
182 # time s btrbk -v archive /mnt/r7/amy/boot/btrbk ssh://bo/mnt/boot2/btrbk
185 std_preserve
="999h 999d 999w 999m"
186 q_preserve
="$std_preserve"
189 *) die
"untested command arg" ;;
192 if (( $# > 1 )); then
193 die
: "only 1 nonoption arg is supported"
196 if [[ -v targets
&& $source ]]; then
197 # note, this doesnt need to be the case, but
198 # we would need to think about it.
199 die
"error: -t and -s are mutually exclusive"
202 ### end options parsing
204 # remove path from earlier version of btrbk
205 rm -f /usr
/sbin
/btrbk
206 # note, this still works as intended if there is no /usr/bin/btrbk
207 if [[ /a
/opt
/btrbk
/btrbk
-nt /usr
/bin
/btrbk
]]; then
208 if [[ -e /b
/distro-functions
/src
/package-manager-abstractions
]]; then
209 .
/b
/distro-functions
/src
/package-manager-abstractions
216 # TODO: i wonder if there should be an option to send to the default
217 # targets, plus any given on the command line.
233 if [[ $
(dig +short @
10.2.0.1 -x 10.2.0.2 2>&1 ||
:) == kd.b8.nz.
]] \
234 && ip n show
10.2.0.1 |
grep .
&>/dev
/null
; then
236 elif ping -q -c1 -w1 hal.office.fsf.org
&>/dev
/null \
237 && ip n show
192.168.0.26 |
grep .
&>/dev
/null
; then
244 exit-if-no-default-targets
() {
245 if ! $force && [[ $HOSTNAME != "$MAIL_HOST" ]]; then
246 echo "MAIL_HOST=$MAIL_HOST, nothing to do"
250 kw|kd|frodo|x2|x3|sy
) : ;;
252 die
"error: no default targets for this host, use -t"
259 if ping -q -c1 -w1 x3.office.fsf.org
&>/dev
/null
; then
260 targets
+=(x3.office.fsf.org
)
261 elif ping -q -c1 -w1 $h.b8.nz
&>/dev
/null
; then
262 # in case we took it home
265 targets
+=(x3wg.b8.nz
)
269 add-wireless-target-h
() {
270 if ping -q -c1 -w1 $h.b8.nz
&>/dev
/null
; then
272 elif ping -q -c1 -w1 ${h}w.b8.nz
&>/dev
/null
; then
273 targets
+=(${h}w.b8.nz
)
278 # set default targets
279 if [[ ! -v targets
&& ! $source ]]; then
280 exit-if-no-default-targets
283 if ! $kd_spread && [[ $HOSTNAME != x3
]]; then
286 if [[ $HOSTNAME != kd
]]; then
289 wireless_home_hosts
=(
293 for h
in ${wireless_home_hosts[@]}; do
294 if [[ $HOSTNAME != "$h" ]]; then
295 add-wireless-target-h
300 for h
in x2 x3 kw
; do
301 if [[ $HOSTNAME == "$h" ]]; then
304 if ping -q -c1 -w1 $h.office.fsf.org
&>/dev
/null
; then
305 targets
+=($h.office.fsf.org
)
313 if [[ ${mountpoints[0]} ]]; then
314 for mp
in ${mountpoints[@]}; do
315 if [[ -e /nocow
/btrfs-stale
/$mp ]]; then
316 die
"error: $mp is stale, mount-latest-subvol first"
320 # set default mountpoints
321 if [[ ${targets[0]} == tp
]]; then
327 if [[ $source ]]; then
328 source_state
="$(ssh $source cat /a/bin/bash_unpublished/source-state)"
330 source_host
="$(ssh $source cat /etc/hostname)"
331 if [[ $source_host == "$MAIL_HOST" ]]; then
332 prospective_mps
+=(/o
)
334 if [[ $source_host == "$HOST2" ]]; then
335 prospective_mps
+=(/a
/ar /qr
/qd
/q
)
338 if [[ $HOSTNAME == "$MAIL_HOST" ]]; then
339 prospective_mps
+=(/o
)
341 if [[ $HOSTNAME == "$HOST2" ]]; then
342 prospective_mps
+=(/a
/ar /qr
/qd
/q
)
345 prospective_mps
=(/a
/ar /o
/qr
/qd
/q
)
348 # note: put q last just in case its specific retention options were to
349 # affect other config sections. I havent tested if that is the case.
353 for mp
in ${prospective_mps[@]}; do # default mountpoints to sync
354 if [[ -e /nocow
/btrfs-stale
/$mp ]]; then
355 e
"warning: $mp stale, not adding to default mountpoints"
358 if awk '{print $2}' /etc
/fstab |
grep -xF $mp &>/dev
/null
; then
364 if (( ! ${#mountpoints[@]} )); then
365 die didnt get mountpoint arg and had no defaults
368 ##### end command line parsing ########
370 #### begin pre-checks #####
372 # todo: this has a timing problem, since btrbk.timer could activate the service after this check.
373 if ! $fast && [[ $source ]]; then
374 if [[ $
(ssh $source ps
--no-headers -o comm 1) == systemd
]]; then
375 status
=$
(ssh $source systemctl is-active btrbk.service
) ||
: # normally returns 3
377 inactive|failed
) : ;;
379 echo "$0: error: btrbk is running on source. exiting out of caution"
385 if ! command -v btrbk
&>/dev
/null
; then
386 die
"error: no btrbk binary found"
390 #### end pre-checks #####
392 mkdir
-p /var
/log
/btrbk
393 # The journal doesnt go back to my oldest backups, and I've found myself
394 # wanting older logs. Not going to bother expiring old logs, since it is
395 # fine if they go back years.
396 log_path
=/var
/log
/btrbk
/$
(date +%F_
%T
%:::z
).log
397 echo copying output to
$log_path
398 exec &> >(ts
"%F %T" |
tee -a $log_path)
402 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"
405 if [[ -v targets
]]; then
406 echo "targets: ${targets[*]}"
409 if [[ $source ]]; then
410 echo "source: $source"
413 echo "mountpoints: ${mountpoints[*]}"
417 # pull_reexec stops us from getting into an infinite loop if there is some
418 # kind of weird problem
420 for m
in "${mountpoints[@]}"; do
421 if [[ $m == /a
]]; then
426 if ! $pull_reexec && [[ $source ]] && $pulla ; then
428 m rsync
-ra $source:/usr
/local
/bin
/{mount-latest-subvol
,check-subvol-stale
} /usr
/local
/bin
429 m rsync
-ra $source:/usr
/local
/lib
/err
/usr
/local
/lib
430 m scp
$source:/a
/bin
/distro-setup
/btrbk-run
$tmpf
431 if ! diff -q $tmpf ${BASH_SOURCE[0]}; then
432 e
"found different version on host $source. reexecing"
433 install -T $tmpf /usr
/local
/bin
/btrbk-run
434 m
/usr
/local
/bin
/btrbk-run
--pull-reexec "${orig_args[@]}"
441 # if our mountpoints are from stale snapshots,
442 # it doesn't make sense to do a backup.
443 m check-subvol-stale
${mountpoints[@]} || die
"found stale mountpoints in ${mountpoints[*]}"
445 # for an initial run, btrbk requires the dir to exist.
446 mkdir
-p /mnt
/{root
,o
}/btrbk
448 local_zone
=$
(date +%z
)
450 if [[ $source ]]; then
454 if ! zone
=$
(ssh root@
$source date +%z
); then
456 echo "$0: warning: failed to ssh to root@$source"
458 die failed to
ssh to root@
$source
461 if [[ $zone != "$local_zone" ]]; then
462 die
"error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
469 for h
in ${targets[@]}; do
470 if $fast ||
$conf_only; then
471 # Use some typical values in this case
472 root_size
=$
(( 1024 * 1024 * 2000 )) #2tb
475 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
476 mapfile
-t tmp_array
<<<"$remote_str"
477 zone
="${tmp_array[0]}"
478 IFS
=" " read -r root_size percent_used
<<<"${tmp_array[1]}"
479 percent_used
=${percent_used%%%}
481 if (( ${#tmp_array[@]} != 2 )); then
482 die
"error: didnt get 2 lines in test ssh to target $h. investigate"
484 case $percent_used in
485 [0-9]|
[1-9][0-9]) : ;;
487 die
"error: didnt get percent disk use in test ssh to target $h. investigate"
495 # we may be booted into a bootstrap fs or something
496 min_root_kb
=$
(( 1024 * 1024 * 200 )) # 200 gb
497 if (( root_size
< min_root_kb
)); then
501 if (( percent_used
>= 98 )); then
502 die
"error: filesystem on target $h is $percent_used % full"
505 # on sy, xprintidle is resetting every 12 seconds even when not
506 # idle, i dunno why, instead we are checking if the screen is locked,
507 # which is good enough.
509 # This is a separate ssh because the command can fail and thatis ok.
512 if lock_info
=$
(timeout
-s 9 6 ssh $h DISPLAY
=:0 xscreensaver-command
-time); then
513 if [[ $lock_info != *non-blanked
* ]]; then
520 # Ignore this host. i sometimes use a non-main machine for
521 # testing or web browsing, knowing that everything will be wiped
522 # by the next backup, but I dont want it to happen as Im using
524 e
"warning: $h: seems to be actively in use, skipping for now"
529 if [[ $zone != "$local_zone" ]]; then
530 die
"error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
533 if [[ ! ${sshable[*]} ]] || { $force && [[ ${sshfail[*]} ]]; }; then
534 die
"failed to ssh to hosts: ${sshfail[*]}"
536 if [[ ${sshfail[*]} ]]; then
538 e
"error: failed to ssh to ${sshfail[*]} but continuing with other hosts"
540 targets
=(${sshable[@]})
545 cat >/etc
/btrbk
$conf_suf.conf
<<EOF
546 ssh_identity /q/root/h
547 #ssh_identity /root/.ssh/home
549 # Just a guess that local7 is a good facility to pick.
550 # It's a bit odd that the transaction log has to be logged to
551 # a file or syslog, while other output is sent to std out.
552 # The man does not mention a way for them to be together, but
553 # I dunno if setting a log level like warn might also output
555 transaction_syslog local7
558 #stream_compress zstd
560 # so we only run one at a time
561 lockfile /var/lock/btrbk$conf_suf.lock
563 # default format of short does not accomidate hourly preservation setting
564 timestamp_format long-iso
566 # only make a snapshot if things have changed
567 snapshot_create onchange
568 # I could make this different from target_preserve,
569 # if one disk had less space.
570 # for now, keeping them equal.
571 snapshot_preserve $std_preserve
572 snapshot_preserve_min 6h
574 # so, total backups = ~58
575 target_preserve $std_preserve
576 target_preserve_min 6h
578 # i tried this when investigating: clone no source subvolume found error
579 #incremental_prefs sro:1 srn:1 sao san:1 aro:1 arn:1
581 # if something fails and it's not obvious, try doing
582 # btrbk -l debug -v dryrun
584 rate_limit $rate_limit
587 if $incremental_strict; then
588 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
596 # q has sensitive data i dont want to backup for so long
597 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
598 snapshot_preserve $q_preserve
599 snapshot_preserve_min 2h
601 target_preserve $q_preserve
602 target_preserve_min 2h
610 mp_count
=${#mountpoints[@]}
611 for (( i
=0; i
< mp_count
- 1 ; i
++ )); do
612 if [[ ${mountpoints[i]} == /q
]]; then
613 unset "mountpoints[i]"
618 for m
in ${mountpoints[@]}; do
629 if [[ $source ]]; then
630 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
631 volume ssh://$bbksource$vol
635 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
636 target send-receive $vol/btrbk
639 if (( ${#targets[@]} )); then
640 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
645 for tg
in ${targets[@]}; do
647 if [[ $tg == *:* ]]; then
650 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
651 target send-receive ssh://$tg$vol/btrbk
657 # todo: umount first to ensure we don't have any errors
658 # todo: do some kill fuser stuff to make umount more reliable
668 m btrbk
-c /etc
/btrbk
$conf_suf.conf
-v -n $cmd_arg
671 # -q and just using the syslog option seemed nice,
672 # but it doesn't show when a send has a parent and when it doesn't.
673 m btrbk
-c /etc
/btrbk
$conf_suf.conf
$preserve_arg $verbose_arg $progress_arg $cmd_arg
679 # todo: tp not valid anymore.
680 # if we have it, sync to systems which don't
681 if mountpoint
$rsync_mountpoint >/dev
/null
; then
682 for tg
in ${targets[@]}; do
685 dirs=(/p
/c
/machine_specific
/tp
)
686 for x
in /p
/c
/machine_specific
/*.hosts
; do
687 if grep -qxF $tg $x; then
691 m rsync
-aSAXPH --specials --devices --delete --relative ${dirs[@]} root@
$tg:/
698 for mp
in "${mountpoints[@]}"; do
699 subvols
+=("${mp##*/}")
701 if [[ $source ]]; then
702 m mount-latest-subvol
"${subvols[@]}"
704 for tg
in ${targets[@]}; do
705 m
/a
/exe
/mount-latest-remote
"$tg" "${subvols[@]}" || ret
=$?
709 if [[ $ret == 0 ]]; then
710 for tg
in ${targets[@]}; do
711 h
=$
(ssh $tg hostname
)
712 if [[ $h == kd
&& $HOSTNAME == x3
&& $HOSTNAME == "$MAIL_HOST" ]]; then
713 ssh root
$tg systemctl
--no-block start btrbk-spread
715 rsync
-a -f"- */" -f"+ *" /var
/log
/btrbk
/ root@
$tg:/var
/log
/btrbk
/$tg
716 ssh root@
$tg /usr
/local
/bin
/mail-backup-clean
718 if [[ $source ]]; then
719 rsync
-a -f"- */" -f"+ *" $source:/var
/log
/btrbk
/ /var
/log
/btrbk
/$source
725 # todo: move variable data we don't care about backing up
726 # to /nocow and symlink it.
729 # background on btrbk timezones. with short/long, timestamps use local time.
730 # for long, if your local time moves backwards, by moving timezones or
731 # for an hour when daylight savings changes it, you will temporarily get
732 # a more aggressive retention policy for the overlapping period, and
733 # vice versa for the opposite timezone move. The alternative is using
734 # long-iso, which puts timezone info into the timestamp, which means
735 # that instead of shifting time, you shift the start of day/week/month
736 # which is used for retention to your new local time, which means for
737 # example, if you moved forward by 8 hours, the daily/weekly/monthly
738 # retention will be 8 hours more aggressive since midnight is at a new
739 # time, unless you fake the timzeone using the TZ env variable.
740 # However, in the short term, there will be no inconsistencies.
741 # I don't see any problem with shifting when the day starts for
742 # retention, so I'm using long-iso.
744 # note to create a long-iso timestamp: date +%Y%m%dT%H%M%S%z