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 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; }
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 cron
,fast
,pull-reexec
,help 23cefikl
:m
:npqrs
:t
:vh
"$@") || usage
1
99 # some behaviors specific to running under cron:
100 # - skip hosts where xprintidle haven't been idle recently
101 # - if we can't ssh to 1 or more hosts, still do the rest
102 # - if we aren't MAIL_HOST and no -m or -s, just exit
107 # for the rare case we want to run multiple instances at the same time
110 # only creates the config file, does not run btrbk
111 -c) conf_only
=true
;;
112 # quit early, just btrbk, no extra remounting etc.
115 # skip various checks. when we run twice in a row for
116 # switch mail-host, no need to repeat the same checks again.
118 -i) incremental_strict
=true
;;
119 # note this implies resume, cron and -p
120 -k) kd_spread
=true
;;
121 # bytes per second, suffix k m g
122 -l) rate_limit
=$2; shift ;;
123 # Comma separated mountpoints to backup. This has defaults set below.
124 -m) IFS
=, mountpoints
=($2); unset IFS
; shift ;;
126 # preserve existing snapshots and backups
127 -p) preserve_arg
=-p ;;
128 # internal option for rerunning under newer SOURCE_HOST version.
129 --pull-reexec) pull_reexec
=true
;;
131 -q) verbose
=false
; verbose_arg
=; progress_arg
= ;;
132 # source host to receive a backup from
136 if [[ $source == *:* ]]; then
137 bbksource
="[$source]"
141 # target hosts to send to. empty is valid for just doing local
142 # snapshot. we have default hosts we will populate.
143 -t) IFS
=, targets
=($2); unset IFS
; shift ;;
145 -v) verbose
=true
; verbose_arg
=-v ;;
148 *) die
"Internal error!" ;;
156 if [[ $cmd_arg && $cmd_arg != resume
]]; then
157 die
"dont pass -k without resume or empty run arg"
159 if [[ $HOSTNAME == "$MAIL_HOST" ]]; then
160 die
"something went wrong, -k not meant to be run on MAIL_HOST"
167 if [[ ! $cmd_arg ]]; then
172 std_preserve
="36h 14d 8w 24m"
173 q_preserve
="18h 14d 8w"
178 # This works better than the normal archive command. We have to
179 # specify the mount points, but that is what we are used to doing and
180 # we prefer it. Another difference is that archive works recursively
181 # and we don't care about that. Sometimes we may still want to run
182 # btrbk archive, but it doesn't even use the config file, so just
183 # run it directly, eg:
184 # time s btrbk -v archive /mnt/r7/amy/boot/btrbk ssh://bo/mnt/boot2/btrbk
187 std_preserve
="999h 999d 999w 999m"
188 q_preserve
="$std_preserve"
191 *) die
"untested command arg" ;;
194 if (( $# > 1 )); then
195 die
: "only 1 nonoption arg is supported"
198 if [[ -v targets
&& $source ]]; then
199 # note, this doesnt need to be the case, but
200 # we would need to think about it.
201 die
"error: -t and -s are mutually exclusive"
204 ### end options parsing
206 # remove path from earlier version of btrbk
207 rm -f /usr
/sbin
/btrbk
208 # note, this still works as intended if there is no /usr/bin/btrbk
209 if [[ /a
/opt
/btrbk
/btrbk
-nt /usr
/bin
/btrbk
]]; then
210 if [[ -e /b
/distro-functions
/src
/package-manager-abstractions
]]; then
211 .
/b
/distro-functions
/src
/package-manager-abstractions
218 # TODO: i wonder if there should be an option to send to the default
219 # targets, plus any given on the command line.
222 # set default targets
223 if [[ ! -v targets
&& ! $source ]]; then
224 if $cron && ! $kd_spread && [[ $HOSTNAME != "$MAIL_HOST" ]]; then
225 echo "MAIL_HOST=$MAIL_HOST, nothing to do"
233 kw|kd|frodo|x2|x3|sy
) : ;;
235 die
"error: no default targets for this host, use -t"
247 if [[ $
(dig +short @
10.2.0.1 -x 10.2.0.2 2>&1 ||
:) == kd.b8.nz.
]] \
248 && ip n show
10.2.0.1 |
grep .
&>/dev
/null
; then
250 elif ping -q -c1 -w1 hal.office.fsf.org
&>/dev
/null \
251 && ip n show
192.168.0.26 |
grep .
&>/dev
/null
; then
257 if ! $kd_spread && [[ $HOSTNAME != x3
]]; then
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
)
268 if [[ $HOSTNAME != kd
]]; then
271 wireless_home_hosts
=(
275 for h
in ${wireless_home_hosts[@]}; do
276 if [[ $HOSTNAME != "$h" ]]; then
277 if ping -q -c1 -w1 $h.b8.nz
&>/dev
/null
; then
279 elif ping -q -c1 -w1 ${h}w.b8.nz
&>/dev
/null
; then
280 targets
+=(${h}w.b8.nz
)
286 for h
in x2 x3 kw
; do
287 if [[ $HOSTNAME == "$h" ]]; then
290 if ping -q -c1 -w1 $h.office.fsf.org
&>/dev
/null
; then
291 targets
+=($h.office.fsf.org
)
301 if [[ ${mountpoints[0]} ]]; then
302 for mp
in ${mountpoints[@]}; do
303 if [[ -e /nocow
/btrfs-stale
/$mp ]]; then
304 die
"error: $mp is stale, mount-latest-subvol first"
308 # set default mountpoints
309 if [[ ${targets[0]} == tp
]]; then
315 if [[ $source ]]; then
316 source_state
="$(ssh $source cat /a/bin/bash_unpublished/source-state)"
318 source_host
="$(ssh $source cat /etc/hostname)"
319 if [[ $source_host == "$MAIL_HOST" ]]; then
320 prospective_mps
+=(/o
)
322 if [[ $source_host == "$HOST2" ]]; then
323 prospective_mps
+=(/a
/ar /qr
/qd
/q
)
326 if [[ $HOSTNAME == "$MAIL_HOST" ]]; then
327 prospective_mps
+=(/o
)
329 if [[ $HOSTNAME == "$HOST2" ]]; then
330 prospective_mps
+=(/a
/ar /qr
/qd
/q
)
333 prospective_mps
=(/a
/ar /o
/qr
/qd
/q
)
336 # note: put q last just in case its specific retention options were to
337 # affect other config sections. I havent tested if that is the case.
341 for mp
in ${prospective_mps[@]}; do # default mountpoints to sync
342 if [[ -e /nocow
/btrfs-stale
/$mp ]]; then
343 e
"warning: $mp stale, not adding to default mountpoints"
346 if awk '{print $2}' /etc
/fstab |
grep -xF $mp &>/dev
/null
; then
352 if (( ! ${#mountpoints[@]} )); then
353 die didnt get mountpoint arg and had no defaults
356 ##### end command line parsing ########
358 #### begin pre-checks #####
360 # todo: this has a timing problem, since btrbk.timer could activate the service after this check.
361 if ! $fast && [[ $source ]]; then
362 if [[ $
(ssh $source ps
--no-headers -o comm 1) == systemd
]]; then
363 status
=$
(ssh $source systemctl is-active btrbk.service
) ||
: # normally returns 3
365 inactive|failed
) : ;;
367 echo "$0: error: cron btrbk is running on source. exiting out of caution"
373 if ! command -v btrbk
&>/dev
/null
; then
374 die
"error: no btrbk binary found"
378 #### end pre-checks #####
380 mkdir
-p /var
/log
/btrbk
381 # The journal doesnt go back to my oldest backups, and I've found myself
382 # wanting older logs. Not going to bother expiring old logs, since it is
383 # fine if they go back years.
384 log_path
=/var
/log
/btrbk
/$
(date +%F_
%T
%:::z
).log
385 echo copying output to
$log_path
386 exec &> >(ts
"%F %T" |
tee -a $log_path)
390 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"
393 if [[ -v targets
]]; then
394 echo "targets: ${targets[*]}"
397 if [[ $source ]]; then
398 echo "source: $source"
401 echo "mountpoints: ${mountpoints[*]}"
405 # pull_reexec stops us from getting into an infinite loop if there is some
406 # kind of weird problem
408 for m
in "${mountpoints[@]}"; do
409 if [[ $m == /a
]]; then
414 if ! $pull_reexec && [[ $source ]] && $pulla ; then
416 m rsync
-ra $source:/usr
/local
/bin
/{mount-latest-subvol
,check-subvol-stale
} /usr
/local
/bin
417 m rsync
-ra $source:/usr
/local
/lib
/err
/usr
/local
/lib
418 m scp
$source:/a
/bin
/distro-setup
/btrbk-run
$tmpf
419 if ! diff -q $tmpf ${BASH_SOURCE[0]}; then
420 e
"found different version on host $source. reexecing"
421 install -T $tmpf /usr
/local
/bin
/btrbk-run
422 m
/usr
/local
/bin
/btrbk-run
--pull-reexec "${orig_args[@]}"
429 # if our mountpoints are from stale snapshots,
430 # it doesn't make sense to do a backup.
431 m check-subvol-stale
${mountpoints[@]} || die
"found stale mountpoints in ${mountpoints[*]}"
433 # for an initial run, btrbk requires the dir to exist.
434 mkdir
-p /mnt
/{root
,o
}/btrbk
436 local_zone
=$
(date +%z
)
438 if [[ $source ]]; then
442 if ! zone
=$
(ssh root@
$source date +%z
); then
444 echo "$0: warning: failed to ssh to root@$source"
446 die failed to
ssh to root@
$source
449 if [[ $zone != "$local_zone" ]]; then
450 die
"error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
457 for h
in ${targets[@]}; do
458 if $fast ||
$conf_only; then
459 # Use some typical values in this case
460 root_size
=$
(( 1024 * 1024 * 2000 )) #2tb
463 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
464 mapfile
-t tmp_array
<<<"$remote_str"
465 zone
="${tmp_array[0]}"
466 IFS
=" " read -r root_size percent_used
<<<"${tmp_array[1]}"
467 percent_used
=${percent_used%%%}
469 if (( ${#tmp_array[@]} != 2 )); then
470 die
"error: didnt get 2 lines in test ssh to target $h. investigate"
472 case $percent_used in
473 [0-9]|
[1-9][0-9]) : ;;
475 die
"error: didnt get percent disk use in test ssh to target $h. investigate"
483 # we may be booted into a bootstrap fs or something
484 min_root_kb
=$
(( 1024 * 1024 * 200 )) # 200 gb
485 if (( root_size
< min_root_kb
)); then
489 if (( percent_used
>= 98 )); then
490 die
"error: filesystem on target $h is $percent_used % full"
493 # on sy, xprintidle is resetting every 12 seconds even when not
494 # idle, i dunno why, instead we are checking if the screen is locked,
495 # which is good enough.
497 # This is a separate ssh because the command can fail and thatis ok.
498 if $cron && ! $force; then
500 if lock_info
=$
(timeout
-s 9 6 ssh $h DISPLAY
=:0 xscreensaver-command
-time); then
501 if [[ $lock_info != *non-blanked
* ]]; then
508 # Ignore this host. i sometimes use a non-main machine for
509 # testing or web browsing, knowing that everything will be wiped
510 # by the next backup, but I dont want it to happen as Im using
512 e
"warning: $h: seems to be actively in use, skipping for now"
517 if [[ $zone != "$local_zone" ]]; then
518 die
"error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
521 if [[ ! ${sshable[*]} ]] || { ! $cron && [[ ${sshfail[*]} ]]; }; then
522 die
"failed to ssh to hosts: ${sshfail[*]}"
524 if [[ ${sshfail[*]} ]]; then
526 e
"error: failed to ssh to ${sshfail[*]} but continuing with other hosts"
528 targets
=(${sshable[@]})
533 cat >/etc
/btrbk
$conf_suf.conf
<<EOF
534 ssh_identity /q/root/h
535 #ssh_identity /root/.ssh/home
537 # Just a guess that local7 is a good facility to pick.
538 # It's a bit odd that the transaction log has to be logged to
539 # a file or syslog, while other output is sent to std out.
540 # The man does not mention a way for them to be together, but
541 # I dunno if setting a log level like warn might also output
543 transaction_syslog local7
546 #stream_compress zstd
548 # so we only run one at a time
549 lockfile /var/lock/btrbk$conf_suf.lock
551 # default format of short does not accomidate hourly preservation setting
552 timestamp_format long-iso
554 # only make a snapshot if things have changed
555 snapshot_create onchange
556 # I could make this different from target_preserve,
557 # if one disk had less space.
558 # for now, keeping them equal.
559 snapshot_preserve $std_preserve
560 snapshot_preserve_min 6h
562 # so, total backups = ~58
563 target_preserve $std_preserve
564 target_preserve_min 6h
566 # i tried this when investigating: clone no source subvolume found error
567 #incremental_prefs sro:1 srn:1 sao san:1 aro:1 arn:1
569 # if something fails and it's not obvious, try doing
570 # btrbk -l debug -v dryrun
572 rate_limit $rate_limit
575 if $incremental_strict; then
576 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
584 # q has sensitive data i dont want to backup for so long
585 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
586 snapshot_preserve $q_preserve
587 snapshot_preserve_min 2h
589 target_preserve $q_preserve
590 target_preserve_min 2h
598 mp_count
=${#mountpoints[@]}
599 for (( i
=0; i
< mp_count
- 1 ; i
++ )); do
600 if [[ ${mountpoints[i]} == /q
]]; then
601 unset "mountpoints[i]"
606 for m
in ${mountpoints[@]}; do
617 if [[ $source ]]; then
618 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
619 volume ssh://$bbksource$vol
623 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
624 target send-receive $vol/btrbk
627 if (( ${#targets[@]} )); then
628 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
633 for tg
in ${targets[@]}; do
635 if [[ $tg == *:* ]]; then
638 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
639 target send-receive ssh://$tg$vol/btrbk
645 # todo: umount first to ensure we don't have any errors
646 # todo: do some kill fuser stuff to make umount more reliable
656 m btrbk
-c /etc
/btrbk
$conf_suf.conf
-v -n $cmd_arg
659 # -q and just using the syslog option seemed nice,
660 # but it doesn't show when a send has a parent and when it doesn't.
661 m btrbk
-c /etc
/btrbk
$conf_suf.conf
$preserve_arg $verbose_arg $progress_arg $cmd_arg
667 # todo: tp not valid anymore.
668 # if we have it, sync to systems which don't
669 if mountpoint
$rsync_mountpoint >/dev
/null
; then
670 for tg
in ${targets[@]}; do
673 dirs=(/p
/c
/machine_specific
/tp
)
674 for x
in /p
/c
/machine_specific
/*.hosts
; do
675 if grep -qxF $tg $x; then
679 m rsync
-aSAXPH --specials --devices --delete --relative ${dirs[@]} root@
$tg:/
686 for mp
in "${mountpoints[@]}"; do
687 subvols
+=("${mp##*/}")
689 if [[ $source ]]; then
690 m mount-latest-subvol
"${subvols[@]}"
692 for tg
in ${targets[@]}; do
693 m
/a
/exe
/mount-latest-remote
"$tg" "${subvols[@]}" || ret
=$?
697 if [[ $ret == 0 ]]; then
698 for tg
in ${targets[@]}; do
699 h
=$
(ssh $tg hostname
)
700 if [[ $h == kd
&& $HOSTNAME == x3
&& $HOSTNAME == "$MAIL_HOST" ]]; then
701 ssh root
$tg systemctl
--no-block start btrbk-spread
703 rsync
-a -f"- */" -f"+ *" /var
/log
/btrbk
/ root@
$tg:/var
/log
/btrbk
/$tg
704 ssh root@
$tg /usr
/local
/bin
/mail-backup-clean
706 if [[ $source ]]; then
707 rsync
-a -f"- */" -f"+ *" $source:/var
/log
/btrbk
/ /var
/log
/btrbk
/$source
713 # todo: move variable data we don't care about backing up
714 # to /nocow and symlink it.
717 # background on btrbk timezones. with short/long, timestamps use local time.
718 # for long, if your local time moves backwards, by moving timezones or
719 # for an hour when daylight savings changes it, you will temporarily get
720 # a more aggressive retention policy for the overlapping period, and
721 # vice versa for the opposite timezone move. The alternative is using
722 # long-iso, which puts timezone info into the timestamp, which means
723 # that instead of shifting time, you shift the start of day/week/month
724 # which is used for retention to your new local time, which means for
725 # example, if you moved forward by 8 hours, the daily/weekly/monthly
726 # retention will be 8 hours more aggressive since midnight is at a new
727 # time, unless you fake the timzeone using the TZ env variable.
728 # However, in the short term, there will be no inconsistencies.
729 # I don't see any problem with shifting when the day starts for
730 # retention, so I'm using long-iso.
732 # note to create a long-iso timestamp: date +%Y%m%dT%H%M%S%z