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
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
94 temp
=$
(getopt
-l cron
,fast
,pull-reexec
,help 23ceikl
:m
:npqrs
:t
:vh
"$@") || usage
1
98 # some behaviors specific to running under cron:
99 # - skip hosts where xprintidle haven't been idle recently
100 # - if we can't ssh to 1 or more hosts, still do the rest
101 # - if we aren't MAIL_HOST and no -m or -s, just exit
106 # for the rare case we want to run multiple instances at the same time
109 # only creates the config file, does not run btrbk
110 -c) conf_only
=true
;;
111 # quit early, just btrbk, no extra remounting etc.
113 # skip various checks. when we run twice in a row for
114 # switch mail-host, no need to repeat the same checks again.
116 -i) incremental_strict
=true
;;
117 # note this implies resume
118 -k) kd_spread_maybe
=true
;;
119 # bytes per second, suffix k m g
120 -l) rate_limit
=$2; shift ;;
121 # Comma separated mountpoints to backup. This has defaults set below.
122 -m) IFS
=, mountpoints
=($2); unset IFS
; shift ;;
126 # internal option for rerunning under newer SOURCE_HOST version.
127 --pull-reexec) pull_reexec
=true
;;
129 -q) verbose
=false
; verbose_arg
=; progress_arg
= ;;
130 # source host to receive a backup from
134 if [[ $source == *:* ]]; then
135 bbksource
="[$source]"
139 # target hosts to send to. empty is valid for just doing local
140 # snapshot. we have default hosts we will populate.
141 -t) IFS
=, targets
=($2); unset IFS
; shift ;;
143 -v) verbose
=true
; verbose_arg
=-v ;;
146 *) die
"Internal error!" ;;
151 if $kd_spread_maybe; then
152 if [[ $1 && $1 != resume
]]; then
153 die
"dont pass -k without resume or empty run arg"
162 std_preserve
="36h 14d 8w 24m"
163 q_preserve
="18h 14d 8w"
168 # This works better than the normal archive command. We have to
169 # specify the mount points, but that is what we are used to doing and
170 # we prefer it. Another difference is that archive works recursively
171 # and we don't care about that. Sometimes we may still want to run
172 # btrbk archive, but it doesn't even use the config file, so just
173 # run it directly, eg:
174 # time s btrbk -v archive /mnt/r7/amy/boot/btrbk ssh://bo/mnt/boot2/btrbk
177 std_preserve
="999h 999d 999w 999m"
178 q_preserve
="$std_preserve"
181 *) die
"untested command arg" ;;
184 if (( $# > 1 )); then
185 die
: "only 1 nonoption arg is supported"
188 if [[ -v targets
&& $source ]]; then
189 # note, this doesnt need to be the case, but
190 # we would need to think about it.
191 die
"error: -t and -s are mutually exclusive"
194 ### end options parsing
196 # remove path from earlier version of btrbk
197 rm -f /usr
/sbin
/btrbk
198 # note, this still works as intended if there is no /usr/bin/btrbk
199 if [[ /a
/opt
/btrbk
/btrbk
-nt /usr
/bin
/btrbk
]]; then
200 if [[ -e /b
/distro-functions
/src
/package-manager-abstractions
]]; then
201 .
/b
/distro-functions
/src
/package-manager-abstractions
208 # TODO: i wonder if there should be an option to send to the default
209 # targets, plus any given on the command line.
214 # set default targets
215 if [[ ! -v targets
&& ! $source ]]; then
217 if [[ $HOSTNAME != "$MAIL_HOST" ]]; then
218 if $kd_spread_maybe && [[ $HOSTNAME == kd
&& $MAIL_HOST == x3
]]; then
219 if ping -q -c1 -w1 x3.office.fsf.org
&>/dev
/null
; then
220 work_host
=x3.office.fsf.org
221 elif ping -q -c1 -w1 x3wg.b8.nz
&>/dev
/null
; then
224 if [[ $work_host ]]; then
225 source_state
="$(ssh $work_host cat /a/bin/bash_unpublished/source-state)"
227 if [[ $MAIL_HOST == x3
]]; then
230 echo "MAIL_HOST=$MAIL_HOST, nothing to do"
234 echo "MAIL_HOST=$MAIL_HOST, nothing to do"
238 echo "MAIL_HOST=$MAIL_HOST, nothing to do"
248 kw|kd|frodo|x2|x3|sy
) : ;;
250 die
"error: no default targets for this host, use -t"
262 if [[ $
(dig +short @
10.2.0.1 -x 10.2.0.2 2>&1 ||
:) == kd.b8.nz.
]] \
263 && ip n show
10.2.0.1 |
grep .
&>/dev
/null
; then
265 elif ping -q -c1 -w1 hal.office.fsf.org
&>/dev
/null \
266 && ip n show
192.168.0.26 |
grep .
&>/dev
/null
; then
272 if ! $kd_spread && [[ $HOSTNAME != x3
]]; then
274 if ping -q -c1 -w1 x3.office.fsf.org
&>/dev
/null
; then
275 targets
+=(x3.office.fsf.org
)
276 elif ping -q -c1 -w1 $h.b8.nz
&>/dev
/null
; then
277 # in case we took it home
280 targets
+=(x3wg.b8.nz
)
283 # temporarily disabled while doing recovery
284 # for h in frodo kd; do
286 if [[ $HOSTNAME == "$h" ]]; then
292 if [[ $HOSTNAME == "$h" ]]; then
295 if ping -q -c1 -w1 $h.b8.nz
&>/dev
/null
; then
297 elif ping -q -c1 -w1 ${h}w.b8.nz
&>/dev
/null
; then
298 targets
+=(${h}w.b8.nz
)
303 for h
in x2 x3 kw
; do
304 if [[ $HOSTNAME == "$h" ]]; then
307 if ping -q -c1 -w1 $h.office.fsf.org
&>/dev
/null
; then
308 targets
+=($h.office.fsf.org
)
319 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"
323 if [[ -v targets
]]; then
324 echo "targets: ${targets[*]}"
327 if [[ $source ]]; then
328 echo "source: $source"
331 if [[ ${mountpoints[0]} ]]; then
332 for mp
in ${mountpoints[@]}; do
333 if [[ -e /nocow
/btrfs-stale
/$mp ]]; then
334 die
"error: $mp is stale, mount-latest-subvol first"
338 # set default mountpoints
339 if [[ ${targets[0]} == tp
]]; then
345 if [[ $source ]]; then
346 source_state
="$(ssh $source cat /a/bin/bash_unpublished/source-state)"
348 source_host
="$(ssh $source cat /etc/hostname)"
349 if [[ $source_host == "$MAIL_HOST" ]]; then
350 prospective_mps
+=(/o
)
352 if [[ $source_host == "$HOST2" ]]; then
353 prospective_mps
+=(/a
/ar /qr
/q
)
356 if [[ $HOSTNAME == "$MAIL_HOST" ]]; then
357 prospective_mps
+=(/o
)
359 if [[ $HOSTNAME == "$HOST2" ]]; then
360 prospective_mps
+=(/a
/ar /qr
/q
)
363 prospective_mps
=(/a
/ar /o
/qr
/q
)
366 # note: put q last just in case its specific retention options were to
367 # affect other config sections. I havent tested if that is the case.
371 for mp
in ${prospective_mps[@]}; do # default mountpoints to sync
372 if [[ -e /nocow
/btrfs-stale
/$mp ]]; then
373 e
"warning: $mp stale, not adding to default mountpoints"
376 if awk '{print $2}' /etc
/fstab |
grep -xF $mp &>/dev
/null
; then
382 if (( ! ${#mountpoints[@]} )); then
383 die didnt get mountpoint arg and had no defaults
386 echo "mountpoints: ${mountpoints[*]}"
388 ##### end command line parsing ########
390 # todo: this has a timing problem, since btrbk.timer could activate the service after this check.
391 if ! $fast && [[ $source ]]; then
392 if [[ $
(ssh $source ps
--no-headers -o comm 1) == systemd
]]; then
393 status
=$
(ssh $source systemctl is-active btrbk.service
) ||
: # normally returns 3
395 inactive|failed
) : ;;
397 echo "$0: error: cron btrbk is running on source. exiting out of caution"
403 # pull_reexec stops us from getting into an infinite loop if there is some
404 # kind of weird problem
406 for m
in "${mountpoints[@]}"; do
407 if [[ $m == /a
]]; then
412 if ! $pull_reexec && [[ $source ]] && $pulla ; then
414 m rsync
-ra $source:/usr
/local
/bin
/{mount-latest-subvol
,check-subvol-stale
} /usr
/local
/bin
415 m rsync
-ra $source:/usr
/local
/lib
/err
/usr
/local
/lib
416 m scp
$source:/a
/bin
/distro-setup
/btrbk-run
$tmpf
417 if ! diff -q $tmpf ${BASH_SOURCE[0]}; then
418 e
"found different version on host $source. reexecing"
419 install -T $tmpf /usr
/local
/bin
/btrbk-run
420 m
/usr
/local
/bin
/btrbk-run
--pull-reexec "${orig_args[@]}"
426 if ! command -v btrbk
&>/dev
/null
; then
427 die
"error: no btrbk binary found"
431 # if our mountpoints are from stale snapshots,
432 # it doesn't make sense to do a backup.
433 m check-subvol-stale
${mountpoints[@]} || die
"found stale mountpoints in ${mountpoints[*]}"
435 # for an initial run, btrbk requires the dir to exist.
436 mkdir
-p /mnt
/{root
,o
}/btrbk
438 local_zone
=$
(date +%z
)
440 if [[ $source ]]; then
444 if ! zone
=$
(ssh root@
$source date +%z
); then
446 echo "$0: warning: failed to ssh to root@$source"
448 die failed to
ssh to root@
$source
451 if [[ $zone != "$local_zone" ]]; then
452 die
"error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
459 for h
in ${targets[@]}; do
460 if $fast ||
$conf_only; then
461 # Use some typical values in this case
462 root_size
=$
(( 1024 * 1024 * 2000 )) #2tb
465 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
466 mapfile
-t tmp_array
<<<"$remote_str"
467 zone
="${tmp_array[0]}"
468 IFS
=" " read -r root_size percent_used
<<<"${tmp_array[1]}"
469 percent_used
=${percent_used%%%}
471 if (( ${#tmp_array[@]} != 2 )); then
472 die
"error: didnt get 2 lines in test ssh to target $h. investigate"
474 case $percent_used in
475 [0-9]|
[1-9][0-9]) : ;;
477 die
"error: didnt get percent disk use in test ssh to target $h. investigate"
485 # we may be booted into a bootstrap fs or something
486 min_root_kb
=$
(( 1024 * 1024 * 200 )) # 200 gb
487 if (( root_size
< min_root_kb
)); then
491 if (( percent_used
>= 98 )); then
492 die
"error: filesystem on target $h is $percent_used % full"
495 # on sy, xprintidle is resetting every 12 seconds even when not
496 # idle, i dunno why, instead we are checking if the screen is locked,
497 # which is good enough.
499 # This is a separate ssh because the command can fail and thatis ok.
502 if lock_info
=$
(timeout
-s 9 6 ssh $h DISPLAY
=:0 xscreensaver-command
-time); then
503 if [[ $lock_info != *non-blanked
* ]]; then
510 # Ignore this host. i sometimes use a non-main machine for
511 # testing or web browsing, knowing that everything will be wiped
512 # by the next backup, but I dont want it to happen as Im using
514 e
"warning: $h: seems to be actively in use, skipping for now"
519 if [[ $zone != "$local_zone" ]]; then
520 die
"error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
523 if [[ ! ${sshable[*]} ]] || { ! $cron && [[ ${sshfail[*]} ]]; }; then
524 die
"failed to ssh to hosts: ${sshfail[*]}"
526 if [[ ${sshfail[*]} ]]; then
528 e
"error: failed to ssh to ${sshfail[*]} but continuing with other hosts"
530 targets
=(${sshable[@]})
535 cat >/etc
/btrbk
$conf_suf.conf
<<EOF
536 ssh_identity /q/root/h
537 #ssh_identity /root/.ssh/home
539 # Just a guess that local7 is a good facility to pick.
540 # It's a bit odd that the transaction log has to be logged to
541 # a file or syslog, while other output is sent to std out.
542 # The man does not mention a way for them to be together, but
543 # I dunno if setting a log level like warn might also output
545 transaction_syslog local7
548 #stream_compress zstd
550 # so we only run one at a time
551 lockfile /var/lock/btrbk$conf_suf.lock
553 # default format of short does not accomidate hourly preservation setting
554 timestamp_format long-iso
556 # only make a snapshot if things have changed
557 snapshot_create onchange
558 # I could make this different from target_preserve,
559 # if one disk had less space.
560 # for now, keeping them equal.
561 snapshot_preserve $std_preserve
562 snapshot_preserve_min 6h
564 # so, total backups = ~58
565 target_preserve $std_preserve
566 target_preserve_min 6h
568 # i tried this when investigating: clone no source subvolume found error
569 #incremental_prefs sro:1 srn:1 sao san:1 aro:1 arn:1
571 # if something fails and it's not obvious, try doing
572 # btrbk -l debug -v dryrun
574 rate_limit $rate_limit
577 if $incremental_strict; then
578 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
586 # q has sensitive data i dont want to backup for so long
587 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
588 snapshot_preserve $q_preserve
589 snapshot_preserve_min 2h
591 target_preserve $q_preserve
592 target_preserve_min 2h
600 mp_count
=${#mountpoints[@]}
601 for (( i
=0; i
< mp_count
- 1 ; i
++ )); do
602 if [[ ${mountpoints[i]} == /q
]]; then
603 unset "mountpoints[i]"
608 for m
in ${mountpoints[@]}; do
619 if [[ $source ]]; then
620 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
621 volume ssh://$bbksource$vol
625 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
626 target send-receive $vol/btrbk
629 if (( ${#targets[@]} )); then
630 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
635 for tg
in ${targets[@]}; do
637 if [[ $tg == *:* ]]; then
640 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
641 target send-receive ssh://$tg$vol/btrbk
647 # todo: umount first to ensure we don't have any errors
648 # todo: do some kill fuser stuff to make umount more reliable
658 m btrbk
-c /etc
/btrbk
$conf_suf.conf
-v -n $cmd_arg
661 # -q and just using the syslog option seemed nice,
662 # but it doesn't show when a send has a parent and when it doesn't.
663 m btrbk
-c /etc
/btrbk
$conf_suf.conf
$preserve_arg $verbose_arg $progress_arg $cmd_arg
669 # todo: tp not valid anymore.
670 # if we have it, sync to systems which don't
671 if mountpoint
$rsync_mountpoint >/dev
/null
; then
672 for tg
in ${targets[@]}; do
675 dirs=(/p
/c
/machine_specific
/tp
)
676 for x
in /p
/c
/machine_specific
/*.hosts
; do
677 if grep -qxF $tg $x; then
681 m rsync
-aSAXPH --specials --devices --delete --relative ${dirs[@]} root@
$tg:/
688 for mp
in "${mountpoints[@]}"; do
689 subvols
+=("${mp##*/}")
691 if [[ $source ]]; then
692 m mount-latest-subvol
"${subvols[@]}"
694 for tg
in ${targets[@]}; do
695 m
/a
/exe
/mount-latest-remote
"$tg" "${subvols[@]}" || ret
=$?
699 if [[ $ret == 0 ]]; then
700 for tg
in ${targets[@]}; do
702 ssh root@
$tg /a
/exe
/mail-backup-clean
708 # todo: move variable data we don't care about backing up
709 # to /nocow and symlink it.
712 # background on btrbk timezones. with short/long, timestamps use local time.
713 # for long, if your local time moves backwards, by moving timezones or
714 # for an hour when daylight savings changes it, you will temporarily get
715 # a more aggressive retention policy for the overlapping period, and
716 # vice versa for the opposite timezone move. The alternative is using
717 # long-iso, which puts timezone info into the timestamp, which means
718 # that instead of shifting time, you shift the start of day/week/month
719 # which is used for retention to your new local time, which means for
720 # example, if you moved forward by 8 hours, the daily/weekly/monthly
721 # retention will be 8 hours more aggressive since midnight is at a new
722 # time, unless you fake the timzeone using the TZ env variable.
723 # However, in the short term, there will be no inconsistencies.
724 # I don't see any problem with shifting when the day starts for
725 # retention, so I'm using long-iso.
727 # note to create a long-iso timestamp: date +%Y%m%dT%H%M%S%z