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"
44 m
() { if $verbose; then printf "$pre%s\n" "$*"; fi; "$@"; }
45 e
() { printf "$pre%s\n" "$*"; }
46 die
() { printf "$pre%s\n" "$*" >&2; echo "exiting with status 1" >&2; exit 1; }
47 mexit
() { echo "$pre: exiting with status $1"; exit $1; }
50 if [[ -e /b
/bash_unpublished
/source-state
]]; then
51 source /b
/bash_unpublished
/source-state
54 # note q is owned by root:1000
63 dry_run
=false
# mostly for testing
65 verbose
=true
; verbose_arg
=-v
66 if [[ $INVOCATION_ID ]]; then
67 # INVOCATION_ID means running as a systemd service. we cant show progress in this case,
68 # but if we pass the arg, it will insert mbuffer into the command.
71 progress_arg
="--progress"
73 incremental_strict
=false
76 default_args_file
=/etc
/btrbk-run.conf
77 if [[ -s $default_args_file ]]; then
78 set -- $
(< $default_args_file) "$@"
79 # i havent used this feature yet, so warn about it
80 echo "$0: warning: default btrbk-run options set in $default_args_file (sleeping 5 seconds):"
81 cat $default_args_file
88 temp
=$
(getopt
-l cron
,pull-reexec
,help ceil
:m
:npqrs
:t
:vh
"$@") || usage
1
92 # some behaviors specific to running under cron:
93 # - skip hosts where xprintidle haven't been idle recently
94 # - if we can't ssh to 1 or more hosts, still do the rest
95 # - if we aren't MAIL_HOST and no -m or -s, just exit
101 # only creates the config file, does not run btrbk
102 -c) conf_only
=true
; shift ;;
103 # quit early, just btrbk, no extra remounting etc.
104 -e) early
=true
; shift ;;
105 -i) incremental_strict
=true
; shift ;;
106 # bytes per second, suffix k m g
107 -l) rate_limit
=$2; shift 2 ;;
108 # Comma separated mountpoints to backup. This has defaults set below.
109 -m) IFS
=, mountpoints
=($2); unset IFS
; shift 2 ;;
110 -n) dry_run
=true
; dry_run_arg
=-n; shift ;;
112 -p) progress_arg
=; shift ;;
113 # internal option for rerunning under newer SOURCE_HOST version.
114 --pull-reexec) pull_reexec
=true
; shift ;;
116 -q) verbose
=false
; verbose_arg
=; progress_arg
=; shift ;;
117 # source host to receive a backup from
121 if [[ $source == *:* ]]; then
122 bbksource
="[$source]"
126 # target hosts to send to. empty is valid for just doing local
127 # snapshot. we have default hosts we will populate.
128 -t) IFS
=, targets
=($2); unset IFS
; shift 2 ;;
130 -v) verbose
=true
; verbose_arg
=-v; shift ;;
133 *) die
"Internal error!" ;;
140 std_preserve
="18h 14d 8w 24m"
146 # This works better than the normal archive command. We have to
147 # specify the mount points, but that is what we are used to doing and
148 # we prefer it. Another difference is that archive works recursively
149 # and we don't care about that. Sometimes we may still want to run
150 # btrbk archive, but it doesn't even use the config file, so just
151 # run it directly, eg:
152 # time s btrbk -v archive /mnt/r7/amy/boot/btrbk ssh://bo/mnt/boot2/btrbk
155 std_preserve
="999h 999d 999w 999m"
156 q_preserve
="$std_preserve"
159 *) die
"untested command arg" ;;
162 if (( $# > 1 )); then
163 die
: "only 1 nonoption arg is supported"
166 if [[ -v targets
&& $source ]]; then
167 # note, this doesnt need to be the case, but
168 # we would need to think about it.
169 die
"error: -t and -s are mutually exclusive"
173 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"
175 ### end options parsing
177 # remove path from earlier version of btrbk
178 rm -f /usr
/sbin
/btrbk
179 # note, this still works as intended if there is no /usr/bin/btrbk
180 if [[ /a
/opt
/btrbk
/btrbk
-nt /usr
/bin
/btrbk
]]; then
181 if [[ -e /b
/distro-functions
/src
/package-manager-abstractions
]]; then
182 .
/b
/distro-functions
/src
/package-manager-abstractions
189 # TODO: i wonder if there should be an option to send to the default
190 # targets, plus any given on the command line.
194 # set default targets
195 if [[ ! -v targets
&& ! $source ]]; then
196 if [[ $HOSTNAME != "$MAIL_HOST" ]] && $cron ; then
197 echo "MAIL_HOST=$MAIL_HOST, nothing to do"
205 # todo, fix this up once frodo is back
206 # targets=(frodo.b8.nz)
212 if ping -q -c1 -w1 hal.office.fsf.org \
213 && ip n show
192.168.0.26 |
grep .
&>/dev
/null
; then
219 if ping -q -c1 -w1 iank.vpn.office.fsf.org
&>/dev
/null
; then
220 home
=iank.vpn.office.fsf.org
232 targets
+=($home x2.office.fsf.org
)
237 targets
+=(x2.office.fsf.org x2.b8.nz
)
239 targets
+=(x2wg.b8.nz
)
243 if ping -q -c1 -w1 x2.office.fsf.org
&>/dev
/null
; then
244 targets
+=(x2.office.fsf.org
)
246 targets
+=(x2wg.b8.nz
)
248 if ping -q -c1 -w1 sy.b8.nz
&>/dev
/null
; then
253 if ping -q -c1 -w1 x3.b8.nz
&>/dev
/null
; then
264 die
"error: no default targets for this host, use -t"
269 if [[ -v targets
]]; then
270 echo "targets: ${targets[*]}"
273 if [[ $source ]]; then
274 echo "source: $source"
277 if [[ ${mountpoints[0]} ]]; then
278 for mp
in ${mountpoints[@]}; do
279 if [[ -e /nocow
/btrfs-stale
/$mp ]]; then
280 die
"error: $mp is stale, mount-latest-subvol first"
284 # set default mountpoints
285 if [[ ${targets[0]} == tp
]]; then
294 if [[ $source ]]; then
295 source_state
="$(ssh $source cat /a/bin/bash_unpublished/source-state)"
297 source_host
="$(ssh $source cat /etc/hostname)"
298 if [[ $source_host == "$MAIL_HOST" ]]; then
299 prospective_mps
+=(/o
)
301 if [[ $source_host == "$HOST2" ]]; then
302 prospective_mps
+=(/a
/ar /qr
/q
)
305 if [[ $HOSTNAME == "$MAIL_HOST" ]]; then
306 prospective_mps
+=(/o
)
308 if [[ $HOSTNAME == "$HOST2" ]]; then
309 prospective_mps
+=(/a
/ar /qr
/q
)
312 # note: put q last just in case its specific retention options were to
313 # affect other config sections. I havent tested if that is the case.
317 for mp
in ${prospective_mps[@]}; do # default mountpoints to sync
318 if [[ -e /nocow
/btrfs-stale
/$mp ]]; then
319 e
"warning: $mp stale, not adding to default mountpoints"
322 if awk '{print $2}' /etc
/fstab |
grep -xF $mp &>/dev
/null
; then
328 echo "mountpoints: ${mountpoints[*]}"
330 ##### end command line parsing ########
332 if [[ $source ]]; then
333 if [[ $
(ssh $source ps
--no-headers -o comm 1) == systemd
]]; then
334 status
=$
(ssh $source systemctl is-active btrbk.service
) ||
: # normally returns 3
336 inactive|failed
) : ;;
338 echo "$0: error: cron btrbk is running on source. exiting out of caution"
344 # pull_reexec stops us from getting into an infinite loop if there is some
345 # kind of weird problem
347 for m
in "${mountpoints[@]}"; do
348 if [[ $m == /a
]]; then
353 if ! $pull_reexec && [[ $source ]] && $pulla ; then
355 m rsync
-ra $source:/usr
/local
/bin
/{mount-latest-subvol
,check-subvol-stale
} /usr
/local
/bin
356 m rsync
-ra $source:/usr
/local
/lib
/err
/usr
/local
/lib
357 m scp
$source:/a
/bin
/distro-setup
/btrbk-run
$tmpf
358 if ! diff -q $tmpf ${BASH_SOURCE[0]}; then
359 e
"found different version on host $source. reexecing"
360 install -T $tmpf /usr
/local
/bin
/btrbk-run
361 m
/usr
/local
/bin
/btrbk-run
--pull-reexec "${orig_args[@]}"
367 if ! command -v btrbk
&>/dev
/null
; then
368 die
"error: no btrbk binary found"
370 # if our mountpoints are from stale snapshots,
371 # it doesn't make sense to do a backup.
372 check-subvol-stale
${mountpoints[@]} || die
"found stale mountpoints in ${mountpoints[*]}"
374 # for an initial run, btrbk requires the dir to exist.
375 mkdir
-p /mnt
/{root
,o
}/btrbk
376 local_zone
=$
(date +%z
)
378 if [[ $source ]]; then
379 if ! zone
=$
(ssh root@
$source date +%z
); then
381 echo "$0: warning: failed to ssh to root@$source"
383 die failed to
ssh to root@
$source
386 if [[ $zone != "$local_zone" ]]; then
387 die
"error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
394 min_idle_ms
=$
((1000 * 60 * 15))
395 for h
in ${targets[@]}; do
396 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
397 zone
=${remote_info[0]}
398 root_size
=${remote_info[1]}
399 percent_used
=${remote_info[2]%%%}
401 if (( ${#remote_info[@]} != 3 )); then
402 die
"error: didnt get 3 fields in test ssh to target $h. investigate"
404 elif $conf_only; then
405 # Use some typical values in this case
406 root_size
=$
(( 1024 * 1024 * 2000 )) #2tb
414 # we may be booted into a bootstrap fs or something
415 min_root_kb
=$
(( 1024 * 1024 * 200 )) # 200 gb
416 if (( root_size
< min_root_kb
)); then
420 if (( percent_used
>= 98 )); then
421 die
"error: filesystem on target $h is $percent_used % full"
424 # This is a separate ssh because xprintidle can fail and thats ok.
425 if $cron && idle_ms
=$
(timeout
-s 9 6 ssh $h DISPLAY
=:0 xprintidle
); then
426 if (( idle_ms
< min_idle_ms
)); then
428 # Ignore this host. i sometimes use a non-main machine for
429 # testing or web browsing, knowing that everything will be wiped
430 # by the next backup, but I dont want it to happen as Im using
432 e
"warning: $h: active X session in the last 15 minutes, skipping for now"
437 if [[ $zone != "$local_zone" ]]; then
438 die
"error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
441 if [[ ! ${sshable[*]} ]] || { ! $cron && [[ ${sshfail[*]} ]]; }; then
442 die
"failed to ssh to hosts: ${sshfail[*]}"
444 if [[ ${sshfail[*]} ]]; then
446 e
"error: failed to ssh to ${sshfail[*]} but continuing with other hosts"
448 targets
=(${sshable[@]})
453 cat >/etc
/btrbk.conf
<<EOF
454 ssh_identity /q/root/h
455 #ssh_identity /root/.ssh/home
457 # Just a guess that local7 is a good facility to pick.
458 # It's a bit odd that the transaction log has to be logged to
459 # a file or syslog, while other output is sent to std out.
460 # The man does not mention a way for them to be together, but
461 # I dunno if setting a log level like warn might also output
463 transaction_syslog local7
468 # so we only run one at a time
469 lockfile /var/lock/btrbk.lock
471 # default format of short does not accomidate hourly preservation setting
472 timestamp_format long-iso
474 # only make a snapshot if things have changed
475 snapshot_create onchange
476 # I could make this different from target_preserve,
477 # if one disk had less space.
478 # for now, keeping them equal.
479 snapshot_preserve $std_preserve
480 snapshot_preserve_min 2h
482 # so, total backups = ~58
483 target_preserve $std_preserve
484 target_preserve_min 2h
486 # if something fails and it's not obvious, try doing
487 # btrbk -l debug -v dryrun
489 rate_limit $rate_limit
492 if $incremental_strict; then
493 cat >>/etc
/btrbk.conf
<<EOF
498 for m
in ${mountpoints[@]}; do
509 if [[ $source ]]; then
510 cat >>/etc
/btrbk.conf
<<EOF
511 volume ssh://$bbksource$vol
513 target send-receive $vol/btrbk
516 if (( ${#targets[@]} )); then
517 cat >>/etc
/btrbk.conf
<<EOF
523 # q has sensitive data i dont want to backup for so long
524 cat >>/etc
/btrbk.conf
<<EOF
525 snapshot_preserve $std_preserve
526 snapshot_preserve_min 2h
528 target_preserve $std_preserve
529 target_preserve_min 2h
533 for tg
in ${targets[@]}; do
535 if [[ $tg == *:* ]]; then
538 cat >>/etc
/btrbk.conf
<<EOF
539 target send-receive ssh://$tg$vol/btrbk
546 # # to manually backup amy,
547 # # bbk -e -s amy -m root_ubuntubionic
548 # cat >>/etc/btrbk.conf <<'EOF'
549 # volume ssh://amy/mnt/root
550 # subvolume root_ubuntubionic
551 # target send-receive /mnt/root/btrbk
555 # todo: umount first to ensure we don't have any errors
556 # todo: do some kill fuser stuff to make umount more reliable
566 m btrbk
-v -n $cmd_arg
569 # -q and just using the syslog option seemed nice,
570 # but it doesn't show when a send has a parent and when it doesn't.
571 m btrbk
$preserve_arg $verbose_arg $progress_arg $cmd_arg
573 # todo: tp not valid anymore.
574 # if we have it, sync to systems which don't
575 if mountpoint
$rsync_mountpoint >/dev
/null
; then
576 for tg
in ${targets[@]}; do
579 dirs=(/p
/c
/machine_specific
/tp
)
580 for x
in /p
/c
/machine_specific
/*.hosts
; do
581 if grep -qxF $tg $x; then
585 m rsync
-aSAXPH --specials --devices --delete --relative ${dirs[@]} root@
$tg:/
591 if [[ $source ]]; then
592 m mount-latest-subvol
594 m
/a
/exe
/mount-latest-remote
${targets[@]}
597 if [[ $ret == 0 ]]; then
598 for tg
in ${targets[@]}; do
600 #ssh root@$tg /a/exe/mail-backup-clean
606 # todo: move variable data we don't care about backing up
607 # to /nocow and symlink it.
610 # background on btrbk timezones. with short/long, timestamps use local time.
611 # for long, if your local time moves backwards, by moving timezones or
612 # for an hour when daylight savings changes it, you will temporarily get
613 # a more aggressive retention policy for the overlapping period, and
614 # vice versa for the opposite timezone move. The alternative is using
615 # long-iso, which puts timezone info into the timestamp, which means
616 # that instead of shifting time, you shift the start of day/week/month
617 # which is used for retention to your new local time, which means for
618 # example, if you moved forward by 8 hours, the daily/weekly/monthly
619 # retention will be 8 hours more aggressive since midnight is at a new
620 # time, unless you fake the timzeone using the TZ env variable.
621 # However, in the short term, there will be no inconsistencies.
622 # I don't see any problem with shifting when the day starts for
623 # retention, so I'm using long-iso.
625 # note to create a long-iso timestamp: date +%Y%m%dT%H%M%S%z