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 set -- $
(< $default_args_file) "$@"
81 # i havent used this feature yet, so warn about it
82 echo "$0: warning: default btrbk-run options set in $default_args_file (sleeping 5 seconds):"
83 cat $default_args_file
91 temp
=$
(getopt
-l cron
,pull-reexec
,help 23ceil
:m
:npqrs
:t
:vh
"$@") || usage
1
95 # some behaviors specific to running under cron:
96 # - skip hosts where xprintidle haven't been idle recently
97 # - if we can't ssh to 1 or more hosts, still do the rest
98 # - if we aren't MAIL_HOST and no -m or -s, just exit
103 # for the rare case we want to run multiple instances at the same time
106 # only creates the config file, does not run btrbk
107 -c) conf_only
=true
;;
108 # quit early, just btrbk, no extra remounting etc.
110 -i) incremental_strict
=true
;;
111 # bytes per second, suffix k m g
112 -l) rate_limit
=$2; shift ;;
113 # Comma separated mountpoints to backup. This has defaults set below.
114 -m) IFS
=, mountpoints
=($2); unset IFS
; shift ;;
118 # internal option for rerunning under newer SOURCE_HOST version.
119 --pull-reexec) pull_reexec
=true
;;
121 -q) verbose
=false
; verbose_arg
=; progress_arg
= ;;
122 # source host to receive a backup from
126 if [[ $source == *:* ]]; then
127 bbksource
="[$source]"
131 # target hosts to send to. empty is valid for just doing local
132 # snapshot. we have default hosts we will populate.
133 -t) IFS
=, targets
=($2); unset IFS
; shift ;;
135 -v) verbose
=true
; verbose_arg
=-v ;;
138 *) die
"Internal error!" ;;
146 std_preserve
="36h 14d 8w 24m"
147 q_preserve
="18h 14d 8w"
152 # This works better than the normal archive command. We have to
153 # specify the mount points, but that is what we are used to doing and
154 # we prefer it. Another difference is that archive works recursively
155 # and we don't care about that. Sometimes we may still want to run
156 # btrbk archive, but it doesn't even use the config file, so just
157 # run it directly, eg:
158 # time s btrbk -v archive /mnt/r7/amy/boot/btrbk ssh://bo/mnt/boot2/btrbk
161 std_preserve
="999h 999d 999w 999m"
162 q_preserve
="$std_preserve"
165 *) die
"untested command arg" ;;
168 if (( $# > 1 )); then
169 die
: "only 1 nonoption arg is supported"
172 if [[ -v targets
&& $source ]]; then
173 # note, this doesnt need to be the case, but
174 # we would need to think about it.
175 die
"error: -t and -s are mutually exclusive"
179 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"
181 ### end options parsing
183 # remove path from earlier version of btrbk
184 rm -f /usr
/sbin
/btrbk
185 # note, this still works as intended if there is no /usr/bin/btrbk
186 if [[ /a
/opt
/btrbk
/btrbk
-nt /usr
/bin
/btrbk
]]; then
187 if [[ -e /b
/distro-functions
/src
/package-manager-abstractions
]]; then
188 .
/b
/distro-functions
/src
/package-manager-abstractions
195 # TODO: i wonder if there should be an option to send to the default
196 # targets, plus any given on the command line.
201 # set default targets
202 if [[ ! -v targets
&& ! $source ]]; then
204 if [[ $HOSTNAME != "$MAIL_HOST" ]]; then
205 if [[ $HOSTNAME == kd
&& $MAIL_HOST = x2
]]; then
208 echo "MAIL_HOST=$MAIL_HOST, nothing to do"
221 kw|kd|frodo|x2|x3|sy
) : ;;
223 die
"error: no default targets for this host, use -t"
235 if [[ $
(dig +short @
10.2.0.1 -x 10.2.0.2 2>&1 ||
:) == kd.b8.nz.
]] \
236 && ip n show
10.2.0.1 |
grep .
&>/dev
/null
; then
238 elif ping -q -c1 -w1 hal.office.fsf.org
&>/dev
/null \
239 && ip n show
192.168.0.26 |
grep .
&>/dev
/null
; then
246 if ping -q -c1 -w1 x3.office.fsf.org
&>/dev
/null
; then
247 targets
+=(x3.office.fsf.org
)
249 targets
+=(x3wg.b8.nz
)
251 for h
in frodo kd
; do
252 if [[ $HOSTNAME == "$h" ]]; then
257 for h
in x2 x3 sy
; do
258 if [[ $HOSTNAME == "$h" ]]; then
261 if ping -q -c1 -w1 $h.b8.nz
&>/dev
/null
; then
263 elif ping -q -c1 -w1 ${h}w.b8.nz
&>/dev
/null
; then
264 targets
+=(${h}w.b8.nz
)
268 if ping -q -c1 -w1 iank.vpn.office.fsf.org
&>/dev
/null
; then
269 targets
+=(iank.vpn.office.fsf.org
)
273 for h
in x2 x3 kw
; do
274 if [[ $HOSTNAME == "$h" ]]; then
277 if ping -q -c1 -w1 $h.office.fsf.org
&>/dev
/null
; then
278 targets
+=($h.office.fsf.org
)
288 if [[ -v targets
]]; then
289 echo "targets: ${targets[*]}"
292 if [[ $source ]]; then
293 echo "source: $source"
296 if [[ ${mountpoints[0]} ]]; then
297 for mp
in ${mountpoints[@]}; do
298 if [[ -e /nocow
/btrfs-stale
/$mp ]]; then
299 die
"error: $mp is stale, mount-latest-subvol first"
303 # set default mountpoints
304 if [[ ${targets[0]} == tp
]]; then
310 if [[ $source ]]; then
311 source_state
="$(ssh $source cat /a/bin/bash_unpublished/source-state)"
313 source_host
="$(ssh $source cat /etc/hostname)"
314 if [[ $source_host == "$MAIL_HOST" ]]; then
315 prospective_mps
+=(/o
)
317 if [[ $source_host == "$HOST2" ]]; then
318 prospective_mps
+=(/a
/ar /qr
/q
)
321 if [[ $HOSTNAME == "$MAIL_HOST" ]]; then
322 prospective_mps
+=(/o
)
324 if [[ $HOSTNAME == "$HOST2" ]]; then
325 prospective_mps
+=(/a
/ar /qr
/q
)
328 # note: put q last just in case its specific retention options were to
329 # affect other config sections. I havent tested if that is the case.
333 for mp
in ${prospective_mps[@]}; do # default mountpoints to sync
334 if [[ -e /nocow
/btrfs-stale
/$mp ]]; then
335 e
"warning: $mp stale, not adding to default mountpoints"
338 if awk '{print $2}' /etc
/fstab |
grep -xF $mp &>/dev
/null
; then
344 echo "mountpoints: ${mountpoints[*]}"
346 ##### end command line parsing ########
348 if [[ $source ]]; then
349 if [[ $
(ssh $source ps
--no-headers -o comm 1) == systemd
]]; then
350 status
=$
(ssh $source systemctl is-active btrbk.service
) ||
: # normally returns 3
352 inactive|failed
) : ;;
354 echo "$0: error: cron btrbk is running on source. exiting out of caution"
360 # pull_reexec stops us from getting into an infinite loop if there is some
361 # kind of weird problem
363 for m
in "${mountpoints[@]}"; do
364 if [[ $m == /a
]]; then
369 if ! $pull_reexec && [[ $source ]] && $pulla ; then
371 m rsync
-ra $source:/usr
/local
/bin
/{mount-latest-subvol
,check-subvol-stale
} /usr
/local
/bin
372 m rsync
-ra $source:/usr
/local
/lib
/err
/usr
/local
/lib
373 m scp
$source:/a
/bin
/distro-setup
/btrbk-run
$tmpf
374 if ! diff -q $tmpf ${BASH_SOURCE[0]}; then
375 e
"found different version on host $source. reexecing"
376 install -T $tmpf /usr
/local
/bin
/btrbk-run
377 m
/usr
/local
/bin
/btrbk-run
--pull-reexec "${orig_args[@]}"
383 if ! command -v btrbk
&>/dev
/null
; then
384 die
"error: no btrbk binary found"
386 # if our mountpoints are from stale snapshots,
387 # it doesn't make sense to do a backup.
388 m check-subvol-stale
${mountpoints[@]} || die
"found stale mountpoints in ${mountpoints[*]}"
390 # for an initial run, btrbk requires the dir to exist.
391 mkdir
-p /mnt
/{root
,o
}/btrbk
392 local_zone
=$
(date +%z
)
394 if [[ $source ]]; then
395 if ! zone
=$
(ssh root@
$source date +%z
); then
397 echo "$0: warning: failed to ssh to root@$source"
399 die failed to
ssh to root@
$source
402 if [[ $zone != "$local_zone" ]]; then
403 die
"error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
410 min_idle_ms
=$
((1000 * 60 * 15))
411 for h
in ${targets[@]}; do
412 if remote_info
=( $
(timeout
-s 9 6 ssh root@
$h "mkdir -p /mnt/root/btrbk /mnt/o/btrbk && date +%z && df --output=size,pcent / | tail -n1") ); then
413 zone
=${remote_info[0]}
414 root_size
=${remote_info[1]}
415 percent_used
=${remote_info[2]%%%}
417 if (( ${#remote_info[@]} != 3 )); then
418 die
"error: didnt get 3 fields in test ssh to target $h. investigate"
420 elif $conf_only; then
421 # Use some typical values in this case
422 root_size
=$
(( 1024 * 1024 * 2000 )) #2tb
430 # we may be booted into a bootstrap fs or something
431 min_root_kb
=$
(( 1024 * 1024 * 200 )) # 200 gb
432 if (( root_size
< min_root_kb
)); then
436 if (( percent_used
>= 98 )); then
437 die
"error: filesystem on target $h is $percent_used % full"
440 # This is a separate ssh because xprintidle can fail and thats ok.
441 if $cron && idle_ms
=$
(timeout
-s 9 6 ssh $h DISPLAY
=:0 xprintidle
); then
442 if (( idle_ms
< min_idle_ms
)); then
444 # Ignore this host. i sometimes use a non-main machine for
445 # testing or web browsing, knowing that everything will be wiped
446 # by the next backup, but I dont want it to happen as Im using
448 e
"warning: $h: active X session in the last 15 minutes, skipping for now"
453 if [[ $zone != "$local_zone" ]]; then
454 die
"error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
457 if [[ ! ${sshable[*]} ]] || { ! $cron && [[ ${sshfail[*]} ]]; }; then
458 die
"failed to ssh to hosts: ${sshfail[*]}"
460 if [[ ${sshfail[*]} ]]; then
462 e
"error: failed to ssh to ${sshfail[*]} but continuing with other hosts"
464 targets
=(${sshable[@]})
469 cat >/etc
/btrbk
$conf_suf.conf
<<EOF
470 ssh_identity /q/root/h
471 #ssh_identity /root/.ssh/home
473 # Just a guess that local7 is a good facility to pick.
474 # It's a bit odd that the transaction log has to be logged to
475 # a file or syslog, while other output is sent to std out.
476 # The man does not mention a way for them to be together, but
477 # I dunno if setting a log level like warn might also output
479 transaction_syslog local7
482 #stream_compress zstd
484 # so we only run one at a time
485 lockfile /var/lock/btrbk$conf_suf.lock
487 # default format of short does not accomidate hourly preservation setting
488 timestamp_format long-iso
490 # only make a snapshot if things have changed
491 snapshot_create onchange
492 # I could make this different from target_preserve,
493 # if one disk had less space.
494 # for now, keeping them equal.
495 snapshot_preserve $std_preserve
496 snapshot_preserve_min 2h
498 # so, total backups = ~58
499 target_preserve $std_preserve
500 target_preserve_min 2h
502 # if something fails and it's not obvious, try doing
503 # btrbk -l debug -v dryrun
505 rate_limit $rate_limit
508 if $incremental_strict; then
509 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
517 # q has sensitive data i dont want to backup for so long
518 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
519 snapshot_preserve $q_preserve
520 snapshot_preserve_min 2h
522 target_preserve $q_preserve
523 target_preserve_min 2h
531 mp_count
=${#mountpoints[@]}
532 for (( i
=0; i
< mp_count
- 1 ; i
++ )); do
533 if [[ ${mountpoints[i]} == /q
]]; then
539 for m
in ${mountpoints[@]}; do
550 if [[ $source ]]; then
551 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
552 volume ssh://$bbksource$vol
556 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
557 target send-receive $vol/btrbk
560 if (( ${#targets[@]} )); then
561 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
566 for tg
in ${targets[@]}; do
568 if [[ $tg == *:* ]]; then
571 cat >>/etc
/btrbk
$conf_suf.conf
<<EOF
572 target send-receive ssh://$tg$vol/btrbk
578 # todo: umount first to ensure we don't have any errors
579 # todo: do some kill fuser stuff to make umount more reliable
589 m btrbk
-c /etc
/btrbk
$conf_suf.conf
-v -n $cmd_arg
592 # -q and just using the syslog option seemed nice,
593 # but it doesn't show when a send has a parent and when it doesn't.
594 m btrbk
-c /etc
/btrbk
$conf_suf.conf
$preserve_arg $verbose_arg $progress_arg $cmd_arg
600 # todo: tp not valid anymore.
601 # if we have it, sync to systems which don't
602 if mountpoint
$rsync_mountpoint >/dev
/null
; then
603 for tg
in ${targets[@]}; do
606 dirs=(/p
/c
/machine_specific
/tp
)
607 for x
in /p
/c
/machine_specific
/*.hosts
; do
608 if grep -qxF $tg $x; then
612 m rsync
-aSAXPH --specials --devices --delete --relative ${dirs[@]} root@
$tg:/
618 if [[ $source ]]; then
619 m mount-latest-subvol
621 m
/a
/exe
/mount-latest-remote
${targets[@]}
624 if [[ $ret == 0 ]]; then
625 for tg
in ${targets[@]}; do
627 #ssh root@$tg /a/exe/mail-backup-clean
633 # todo: move variable data we don't care about backing up
634 # to /nocow and symlink it.
637 # background on btrbk timezones. with short/long, timestamps use local time.
638 # for long, if your local time moves backwards, by moving timezones or
639 # for an hour when daylight savings changes it, you will temporarily get
640 # a more aggressive retention policy for the overlapping period, and
641 # vice versa for the opposite timezone move. The alternative is using
642 # long-iso, which puts timezone info into the timestamp, which means
643 # that instead of shifting time, you shift the start of day/week/month
644 # which is used for retention to your new local time, which means for
645 # example, if you moved forward by 8 hours, the daily/weekly/monthly
646 # retention will be 8 hours more aggressive since midnight is at a new
647 # time, unless you fake the timzeone using the TZ env variable.
648 # However, in the short term, there will be no inconsistencies.
649 # I don't see any problem with shifting when the day starts for
650 # retention, so I'm using long-iso.
652 # note to create a long-iso timestamp: date +%Y%m%dT%H%M%S%z