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
93 temp
=$
(getopt
-l cron
,fast
,pull-reexec
,help 23ceil
:m
:npqrs
:t
:vh
"$@") || usage
1
97 # some behaviors specific to running under cron:
98 # - skip hosts where xprintidle haven't been idle recently
99 # - if we can't ssh to 1 or more hosts, still do the rest
100 # - if we aren't MAIL_HOST and no -m or -s, just exit
105 # for the rare case we want to run multiple instances at the same time
108 # only creates the config file, does not run btrbk
109 -c) conf_only
=true
;;
110 # quit early, just btrbk, no extra remounting etc.
112 # skip various checks. when we run twice in a row for
113 # switch mail-host, no need to repeat the same checks again.
115 -i) incremental_strict
=true
;;
116 # bytes per second, suffix k m g
117 -l) rate_limit
=$2; shift ;;
118 # Comma separated mountpoints to backup. This has defaults set below.
119 -m) IFS
=, mountpoints
=($2); unset IFS
; shift ;;
123 # internal option for rerunning under newer SOURCE_HOST version.
124 --pull-reexec) pull_reexec
=true
;;
126 -q) verbose
=false
; verbose_arg
=; progress_arg
= ;;
127 # source host to receive a backup from
131 if [[ $source == *:* ]]; then
132 bbksource
="[$source]"
136 # target hosts to send to. empty is valid for just doing local
137 # snapshot. we have default hosts we will populate.
138 -t) IFS
=, targets
=($2); unset IFS
; shift ;;
140 -v) verbose
=true
; verbose_arg
=-v ;;
143 *) die
"Internal error!" ;;
151 std_preserve
="36h 14d 8w 24m"
152 q_preserve
="18h 14d 8w"
157 # This works better than the normal archive command. We have to
158 # specify the mount points, but that is what we are used to doing and
159 # we prefer it. Another difference is that archive works recursively
160 # and we don't care about that. Sometimes we may still want to run
161 # btrbk archive, but it doesn't even use the config file, so just
162 # run it directly, eg:
163 # time s btrbk -v archive /mnt/r7/amy/boot/btrbk ssh://bo/mnt/boot2/btrbk
166 std_preserve
="999h 999d 999w 999m"
167 q_preserve
="$std_preserve"
170 *) die
"untested command arg" ;;
173 if (( $# > 1 )); then
174 die
: "only 1 nonoption arg is supported"
177 if [[ -v targets
&& $source ]]; then
178 # note, this doesnt need to be the case, but
179 # we would need to think about it.
180 die
"error: -t and -s are mutually exclusive"
184 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"
186 ### end options parsing
188 # remove path from earlier version of btrbk
189 rm -f /usr
/sbin
/btrbk
190 # note, this still works as intended if there is no /usr/bin/btrbk
191 if [[ /a
/opt
/btrbk
/btrbk
-nt /usr
/bin
/btrbk
]]; then
192 if [[ -e /b
/distro-functions
/src
/package-manager-abstractions
]]; then
193 .
/b
/distro-functions
/src
/package-manager-abstractions
200 # TODO: i wonder if there should be an option to send to the default
201 # targets, plus any given on the command line.
206 # set default targets
207 if [[ ! -v targets
&& ! $source ]]; then
209 if [[ $HOSTNAME != "$MAIL_HOST" ]]; then
210 if [[ $HOSTNAME == kd
&& $MAIL_HOST == x3
]]; then
211 if ping -q -c1 -w1 x3.office.fsf.org
&>/dev
/null
; then
212 work_host
=x3.office.fsf.org
213 elif ping -q -c1 -w1 x3wg.b8.nz
&>/dev
/null
; then
216 if [[ $work_host ]]; then
217 source_state
="$(ssh $work_host cat /a/bin/bash_unpublished/source-state)"
219 if [[ $MAIL_HOST == x3
]]; then
222 echo "MAIL_HOST=$MAIL_HOST, nothing to do"
226 echo "MAIL_HOST=$MAIL_HOST, nothing to do"
230 echo "MAIL_HOST=$MAIL_HOST, nothing to do"
240 kw|kd|frodo|x2|x3|sy
) : ;;
242 die
"error: no default targets for this host, use -t"
254 if [[ $
(dig +short @
10.2.0.1 -x 10.2.0.2 2>&1 ||
:) == kd.b8.nz.
]] \
255 && ip n show
10.2.0.1 |
grep .
&>/dev
/null
; then
257 elif ping -q -c1 -w1 hal.office.fsf.org
&>/dev
/null \
258 && ip n show
192.168.0.26 |
grep .
&>/dev
/null
; then
264 if ! $kd_spread && [[ $HOSTNAME != x3
]]; then
266 if ping -q -c1 -w1 x3.office.fsf.org
&>/dev
/null
; then
267 targets
+=(x3.office.fsf.org
)
268 elif ping -q -c1 -w1 $h.b8.nz
&>/dev
/null
; then
269 # in case we took it home
272 targets
+=(x3wg.b8.nz
)
275 # temporarily disabled while doing recovery
276 # for h in frodo kd; do
278 if [[ $HOSTNAME == "$h" ]]; then
284 if [[ $HOSTNAME == "$h" ]]; then
287 if ping -q -c1 -w1 $h.b8.nz
&>/dev
/null
; then
289 elif ping -q -c1 -w1 ${h}w.b8.nz
&>/dev
/null
; then
290 targets
+=(${h}w.b8.nz
)
294 if ping -q -c1 -w1 iank.vpn.office.fsf.org
&>/dev
/null
; then
295 targets
+=(iank.vpn.office.fsf.org
)
299 for h
in x2 x3 kw
; do
300 if [[ $HOSTNAME == "$h" ]]; then
303 if ping -q -c1 -w1 $h.office.fsf.org
&>/dev
/null
; then
304 targets
+=($h.office.fsf.org
)
314 if [[ -v targets
]]; then
315 echo "targets: ${targets[*]}"
318 if [[ $source ]]; then
319 echo "source: $source"
322 if [[ ${mountpoints[0]} ]]; then
323 for mp
in ${mountpoints[@]}; do
324 if [[ -e /nocow
/btrfs-stale
/$mp ]]; then
325 die
"error: $mp is stale, mount-latest-subvol first"
329 # set default mountpoints
330 if [[ ${targets[0]} == tp
]]; then
336 if [[ $source ]]; then
337 source_state
="$(ssh $source cat /a/bin/bash_unpublished/source-state)"
339 source_host
="$(ssh $source cat /etc/hostname)"
340 if [[ $source_host == "$MAIL_HOST" ]]; then
341 prospective_mps
+=(/o
)
343 if [[ $source_host == "$HOST2" ]]; then
344 prospective_mps
+=(/a
/ar /qr
/q
)
347 if [[ $HOSTNAME == "$MAIL_HOST" ]]; then
348 prospective_mps
+=(/o
)
350 if [[ $HOSTNAME == "$HOST2" ]]; then
351 prospective_mps
+=(/a
/ar /qr
/q
)
354 prospective_mps
=(/a
/ar /o
/qr
/q
)
357 # note: put q last just in case its specific retention options were to
358 # affect other config sections. I havent tested if that is the case.
362 for mp
in ${prospective_mps[@]}; do # default mountpoints to sync
363 if [[ -e /nocow
/btrfs-stale
/$mp ]]; then
364 e
"warning: $mp stale, not adding to default mountpoints"
367 if awk '{print $2}' /etc
/fstab |
grep -xF $mp &>/dev
/null
; then
373 if (( ! ${#mountpoints[@]} )); then
374 die didnt get mountpoint arg and had no defaults
377 echo "mountpoints: ${mountpoints[*]}"
379 ##### end command line parsing ########
381 # todo: this has a timing problem, since btrbk.timer could activate the service after this check.
382 if ! $fast && [[ $source ]]; then
383 if [[ $
(ssh $source ps
--no-headers -o comm 1) == systemd
]]; then
384 status
=$
(ssh $source systemctl is-active btrbk.service
) ||
: # normally returns 3
386 inactive|failed
) : ;;
388 echo "$0: error: cron btrbk is running on source. exiting out of caution"
394 # pull_reexec stops us from getting into an infinite loop if there is some
395 # kind of weird problem
397 for m
in "${mountpoints[@]}"; do
398 if [[ $m == /a
]]; then
403 if ! $pull_reexec && [[ $source ]] && $pulla ; then
405 m rsync
-ra $source:/usr
/local
/bin
/{mount-latest-subvol
,check-subvol-stale
} /usr
/local
/bin
406 m rsync
-ra $source:/usr
/local
/lib
/err
/usr
/local
/lib
407 m scp
$source:/a
/bin
/distro-setup
/btrbk-run
$tmpf
408 if ! diff -q $tmpf ${BASH_SOURCE[0]}; then
409 e
"found different version on host $source. reexecing"
410 install -T $tmpf /usr
/local
/bin
/btrbk-run
411 m
/usr
/local
/bin
/btrbk-run
--pull-reexec "${orig_args[@]}"
417 if ! command -v btrbk
&>/dev
/null
; then
418 die
"error: no btrbk binary found"
422 # if our mountpoints are from stale snapshots,
423 # it doesn't make sense to do a backup.
424 m check-subvol-stale
${mountpoints[@]} || die
"found stale mountpoints in ${mountpoints[*]}"
426 # for an initial run, btrbk requires the dir to exist.
427 mkdir
-p /mnt
/{root
,o
}/btrbk
429 local_zone
=$
(date +%z
)
431 if [[ $source ]]; then
435 if ! zone
=$
(ssh root@
$source date +%z
); then
437 echo "$0: warning: failed to ssh to root@$source"
439 die failed to
ssh to root@
$source
442 if [[ $zone != "$local_zone" ]]; then
443 die
"error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
450 min_idle_ms
=$
((1000 * 60 * 15))
451 for h
in ${targets[@]}; do
452 if $fast ||
$conf_only; then
453 # Use some typical values in this case
454 root_size
=$
(( 1024 * 1024 * 2000 )) #2tb
457 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
458 mapfile
-t tmp_array
<<<"$remote_str"
459 zone
="${tmp_array[0]}"
460 IFS
=" " read -r root_size percent_used
<<<"${tmp_array[1]}"
461 percent_used
=${percent_used%%%}
463 if (( ${#tmp_array[@]} != 2 )); then
464 die
"error: didnt get 2 lines in test ssh to target $h. investigate"
466 case $percent_used in
467 [0-9]|
[1-9][0-9]) : ;;
469 die
"error: didnt get percent disk use in test ssh to target $h. investigate"
477 # we may be booted into a bootstrap fs or something
478 min_root_kb
=$
(( 1024 * 1024 * 200 )) # 200 gb
479 if (( root_size
< min_root_kb
)); then
483 if (( percent_used
>= 98 )); then
484 die
"error: filesystem on target $h is $percent_used % full"
487 # This is a separate ssh because xprintidle can fail and thats ok.
488 if $cron && idle_ms
=$
(timeout
-s 9 6 ssh $h DISPLAY
=:0 xprintidle
); then
489 if (( idle_ms
< min_idle_ms
)); then
491 # Ignore this host. i sometimes use a non-main machine for
492 # testing or web browsing, knowing that everything will be wiped
493 # by the next backup, but I dont want it to happen as Im using
495 e
"warning: $h: active X session in the last 15 minutes, skipping for now"
500 if [[ $zone != "$local_zone" ]]; then
501 die
"error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
504 if [[ ! ${sshable[*]} ]] || { ! $cron && [[ ${sshfail[*]} ]]; }; then
505 die
"failed to ssh to hosts: ${sshfail[*]}"
507 if [[ ${sshfail[*]} ]]; then
509 e
"error: failed to ssh to ${sshfail[*]} but continuing with other hosts"
511 targets
=(${sshable[@]})
516 cat >/etc
/btrbk
$conf_suf.conf
<<EOF
517 ssh_identity /q/root/h
518 #ssh_identity /root/.ssh/home
520 # Just a guess that local7 is a good facility to pick.
521 # It's a bit odd that the transaction log has to be logged to
522 # a file or syslog, while other output is sent to std out.
523 # The man does not mention a way for them to be together, but
524 # I dunno if setting a log level like warn might also output
526 transaction_syslog local7
529 #stream_compress zstd
531 # so we only run one at a time
532 lockfile /var/lock/btrbk$conf_suf.lock
534 # default format of short does not accomidate hourly preservation setting
535 timestamp_format long-iso
537 # only make a snapshot if things have changed
538 snapshot_create onchange
539 # I could make this different from target_preserve,
540 # if one disk had less space.
541 # for now, keeping them equal.
542 snapshot_preserve $std_preserve
543 snapshot_preserve_min 2h
545 # so, total backups = ~58
546 target_preserve $std_preserve
547 target_preserve_min 2h
549 # i tried this when investigating: clone no source subvolume found error
550 #incremental_prefs sro:1 srn:1 sao san:1 aro:1 arn:1
552 # if something fails and it's not obvious, try doing
553 # btrbk -l debug -v dryrun
555 rate_limit $rate_limit
558 if $incremental_strict; then
559 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
567 # q has sensitive data i dont want to backup for so long
568 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
569 snapshot_preserve $q_preserve
570 snapshot_preserve_min 2h
572 target_preserve $q_preserve
573 target_preserve_min 2h
581 mp_count
=${#mountpoints[@]}
582 for (( i
=0; i
< mp_count
- 1 ; i
++ )); do
583 if [[ ${mountpoints[i]} == /q
]]; then
584 unset "mountpoints[i]"
589 for m
in ${mountpoints[@]}; do
600 if [[ $source ]]; then
601 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
602 volume ssh://$bbksource$vol
606 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
607 target send-receive $vol/btrbk
610 if (( ${#targets[@]} )); then
611 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
616 for tg
in ${targets[@]}; do
618 if [[ $tg == *:* ]]; then
621 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
622 target send-receive ssh://$tg$vol/btrbk
628 # todo: umount first to ensure we don't have any errors
629 # todo: do some kill fuser stuff to make umount more reliable
639 m btrbk
-c /etc
/btrbk
$conf_suf.conf
-v -n $cmd_arg
642 # -q and just using the syslog option seemed nice,
643 # but it doesn't show when a send has a parent and when it doesn't.
644 m btrbk
-c /etc
/btrbk
$conf_suf.conf
$preserve_arg $verbose_arg $progress_arg $cmd_arg
650 # todo: tp not valid anymore.
651 # if we have it, sync to systems which don't
652 if mountpoint
$rsync_mountpoint >/dev
/null
; then
653 for tg
in ${targets[@]}; do
656 dirs=(/p
/c
/machine_specific
/tp
)
657 for x
in /p
/c
/machine_specific
/*.hosts
; do
658 if grep -qxF $tg $x; then
662 m rsync
-aSAXPH --specials --devices --delete --relative ${dirs[@]} root@
$tg:/
669 for mp
in "${mountpoints[@]}"; do
670 subvols
+=("${mp##*/}")
672 if [[ $source ]]; then
673 m mount-latest-subvol
"${subvols[@]}"
675 for tg
in ${targets[@]}; do
676 m
/a
/exe
/mount-latest-remote
"$tg" "${subvols[@]}" || ret
=$?
680 if [[ $ret == 0 ]]; then
681 for tg
in ${targets[@]}; do
683 #ssh root@$tg /a/exe/mail-backup-clean
689 # todo: move variable data we don't care about backing up
690 # to /nocow and symlink it.
693 # background on btrbk timezones. with short/long, timestamps use local time.
694 # for long, if your local time moves backwards, by moving timezones or
695 # for an hour when daylight savings changes it, you will temporarily get
696 # a more aggressive retention policy for the overlapping period, and
697 # vice versa for the opposite timezone move. The alternative is using
698 # long-iso, which puts timezone info into the timestamp, which means
699 # that instead of shifting time, you shift the start of day/week/month
700 # which is used for retention to your new local time, which means for
701 # example, if you moved forward by 8 hours, the daily/weekly/monthly
702 # retention will be 8 hours more aggressive since midnight is at a new
703 # time, unless you fake the timzeone using the TZ env variable.
704 # However, in the short term, there will be no inconsistencies.
705 # I don't see any problem with shifting when the day starts for
706 # retention, so I'm using long-iso.
708 # note to create a long-iso timestamp: date +%Y%m%dT%H%M%S%z