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
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 progress_arg
="--progress"
67 incremental_strict
=false
70 default_args_file
=/etc
/btrbk-run.conf
71 if [[ -s $default_args_file ]]; then
72 set -- $
(< $default_args_file) "$@"
73 # i havent used this feature yet, so warn about it
74 echo "$0: warning: default btrbk-run options set in $default_args_file (sleeping 5 seconds):"
75 cat $default_args_file
79 early
=false
# quit early, just btrbk, no extra remounting etc.
82 temp
=$
(getopt
-l cron
,pull-reexec
,help ceil
:m
:npqrs
:t
:vh
"$@") || usage
1
91 # only creates the config file, does not run btrbk
92 -c) conf_only
=true
; shift ;;
93 -e) early
=true
; shift ;;
94 -i) incremental_strict
=true
; shift ;;
95 # bytes per second, suffix k m g
96 -l) rate_limit
=$2; shift 2 ;;
97 # Comma separated mountpoints to backup. This has defaults set below.
98 -m) IFS
=, mountpoints
=($2); unset IFS
; shift 2 ;;
99 -n) dry_run
=true
; dry_run_arg
=-n; shift ;;
100 -p) progress_arg
="--progress"; shift ;;
101 --pull-reexec) pull_reexec
=true
; shift ;;
102 -r) archive
=false
; shift ;;
103 -q) verbose
=false
; verbose_arg
=; progress_arg
=; shift ;;
104 # source host to receive a backup from
108 if [[ $source == *:* ]]; then
109 bbksource
="[$source]"
113 # target hosts to send to. empty is valid for just doing local
114 # snapshot. we have default hosts we will populate.
115 -t) IFS
=, targets
=($2); unset IFS
; shift 2 ;;
116 -v) verbose
=true
; verbose_arg
=-v; shift ;;
119 *) die
"Internal error!" ;;
123 # only tested commands are resume and archive
127 run|resume|archive
) : ;;
128 *) die
"untested command arg" ;;
131 if (( $# > 1 )); then
132 die
: "only 1 nonoption arg is supported"
135 if [[ -v targets
&& $source ]]; then
136 # note, this doesnt need to be the case, but
137 # we would need to think about it.
138 die
"error: -t and -s are mutually exclusive"
142 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"
144 ### end options parsing
146 # remove path from earlier version of btrbk
147 rm -f /usr
/sbin
/btrbk
148 # note, this still works as intended if there is no /usr/bin/btrbk
149 if [[ /a
/opt
/btrbk
/btrbk
-nt /usr
/bin
/btrbk
]]; then
150 if [[ -e /b
/distro-functions
/src
/package-manager-abstractions
]]; then
151 .
/b
/distro-functions
/src
/package-manager-abstractions
158 # TODO: i wonder if there should be an option to send to the default
159 # targets, plus any given on the command line.
163 # set default targets
164 if [[ ! -v targets
&& ! $source ]]; then
165 if [[ $HOSTNAME != "$MAIL_HOST" ]] && $cron ; then
166 echo "MAIL_HOST=$MAIL_HOST, nothing to do"
174 targets
=(frodo.b8.nz
)
180 if ping -q -c1 -w1 hal.office.fsf.org \
181 && ip n show
192.168.0.26 |
grep .
&>/dev
/null
; then
187 if ping -q -c1 -w1 iank.vpn.office.fsf.org
&>/dev
/null
; then
188 home
=iank.vpn.office.fsf.org
197 targets
+=($home x2.office.fsf.org
)
202 targets
+=(x2.office.fsf.org x2.b8.nz
)
204 targets
+=(x2wg.b8.nz
)
208 targets
+=(x2wg.b8.nz x3.b8.nz
)
209 if ping -q -c1 -w1 sy.b8.nz
&>/dev
/null
; then
220 die
"error: no default targets for this host, use -t"
225 if [[ -v targets
]]; then
226 echo "targets: ${targets[*]}"
229 if [[ $source ]]; then
230 echo "source: $source"
233 if [[ ${mountpoints[0]} ]]; then
234 for mp
in ${mountpoints[@]}; do
235 if [[ -e /nocow
/btrfs-stale
/$mp ]]; then
236 die
"error: $mp is stale, mount-latest-subvol first"
240 # set default mountpoints
241 if [[ ${targets[0]} == tp
]]; then
250 if [[ $source ]]; then
251 source_state
="$(ssh $source cat /a/bin/bash_unpublished/source-state)"
253 source_host
="$(ssh $source cat /etc/hostname)"
254 if [[ $source_host == "$MAIL_HOST" ]]; then
255 prospective_mps
+=(/o
)
258 if [[ $HOSTNAME == "$MAIL_HOST" ]]; then
259 # HOST2 is really the mail host if it exists
260 if [[ $HOST2 && $HOST2 != "$HOSTNAME" ]]; then
261 echo "skipping /o because HOST2 is not us"
263 prospective_mps
+=(/o
)
267 # note: put q last just in case its specific retention options were to
268 # affect other config sections. I havent tested if that is the case.
269 prospective_mps
+=(/a
/ar /qr
/q
)
273 for mp
in ${prospective_mps[@]}; do # default mountpoints to sync
274 if [[ -e /nocow
/btrfs-stale
/$mp ]]; then
275 e
"warning: $mp stale, not adding to default mountpoints"
278 if awk '{print $2}' /etc
/fstab |
grep -xF $mp &>/dev
/null
; then
284 echo "mountpoints: ${mountpoints[*]}"
286 ##### end command line parsing ########
288 if [[ $source ]]; then
289 if [[ $
(ssh $source ps
--no-headers -o comm 1) == systemd
]]; then
290 status
=$
(ssh $source systemctl is-active btrbk.service
) ||
: # normally returns 3
292 inactive|failed
) : ;;
294 echo "$0: error: cron btrbk is running on source. exiting out of caution"
300 # pull_reexec stops us from getting into an infinite loop if there is some
301 # kind of weird problem
303 for m
in "${mountpoints[@]}"; do
304 if [[ $m == /a
]]; then
309 if ! $pull_reexec && [[ $source ]] && $pulla ; then
311 m rsync
-ra $source:/usr
/local
/bin
/{mount-latest-subvol
,check-subvol-stale
} /usr
/local
/bin
312 m rsync
-ra $source:/usr
/local
/lib
/err
/usr
/local
/lib
313 m scp
$source:/a
/bin
/distro-setup
/btrbk-run
$tmpf
314 if ! diff -q $tmpf ${BASH_SOURCE[0]}; then
315 e
"found different version on host $source. reexecing"
316 install -T $tmpf /usr
/local
/bin
/btrbk-run
317 m
/usr
/local
/bin
/btrbk-run
--pull-reexec "${orig_args[@]}"
323 if ! command -v btrbk
&>/dev
/null
; then
324 die
"error: no btrbk binary found"
326 # if our mountpoints are from stale snapshots,
327 # it doesn't make sense to do a backup.
328 check-subvol-stale
${mountpoints[@]} || die
"found stale mountpoints in ${mountpoints[*]}"
330 # for an initial run, btrbk requires the dir to exist.
331 mkdir
-p /mnt
/{root
,o
}/btrbk
332 local_zone
=$
(date +%z
)
334 if [[ $source ]]; then
335 if ! zone
=$
(ssh root@
$source date +%z
); then
336 die failed to
ssh to root@
$source
338 if [[ $zone != "$local_zone" ]]; then
339 die
"error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
346 min_idle_ms
=$
((1000 * 60 * 15))
347 for h
in ${targets[@]}; do
348 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
349 zone
=${remote_info[0]}
350 root_size
=${remote_info[1]}
351 percent_used
=${remote_info[2]%%%}
353 if (( ${#remote_info[@]} != 3 )); then
354 die
"error: didnt get 3 fields in test ssh to target $h. investigate"
358 # we may be booted into a bootstrap fs or something
359 min_root_kb
=$
(( 1024 * 1024 * 200 )) # 200 gb
360 if (( root_size
< min_root_kb
)); then
364 if (( percent_used
>= 98 )); then
365 die
"error: filesystem on target $h is $percent_used % full"
368 # This is a separate ssh because xprintidle can fail and thats ok.
369 if $cron && idle_ms
=$
(timeout
-s 9 6 ssh $h DISPLAY
=:0 xprintidle
); then
370 if (( idle_ms
< min_idle_ms
)); then
372 # Ignore this host. i sometimes use a non-main machine for
373 # testing or web browsing, knowing that everything will be wiped
374 # by the next backup, but I dont want it to happen as Im using
376 e
"warning: $h: active X session in the last 15 minutes, skipping for now"
381 if [[ $zone != "$local_zone" ]]; then
382 die
"error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
388 if [[ ! ${sshable[*]} ]] || { ! $cron && [[ ${sshfail[*]} ]]; }; then
389 die
"failed to ssh to hosts: ${sshfail[*]}"
391 if [[ ${sshfail[*]} ]]; then
393 e
"error: failed to ssh to ${sshfail[*]} but continuing with other hosts"
395 targets
=(${sshable[@]})
400 cat >/etc
/btrbk.conf
<<EOF
401 ssh_identity /q/root/h
402 #ssh_identity /root/.ssh/home
404 # Just a guess that local7 is a good facility to pick.
405 # It's a bit odd that the transaction log has to be logged to
406 # a file or syslog, while other output is sent to std out.
407 # The man does not mention a way for them to be together, but
408 # I dunno if setting a log level like warn might also output
410 transaction_syslog local7
415 # so we only run one at a time
416 lockfile /var/lock/btrbk.lock
418 # default format of short does not accomidate hourly preservation setting
419 timestamp_format long-iso
421 # only make a snapshot if things have changed
422 snapshot_create onchange
423 # I could make this different from target_preserve,
424 # if one disk had less space.
425 # for now, keeping them equal.
426 snapshot_preserve 18h 14d 8w 24m
427 snapshot_preserve_min 2h
429 # so, total backups = ~58
430 target_preserve 18h 14d 8w 24m
431 target_preserve_min 2h
433 # if something fails and it's not obvious, try doing
434 # btrbk -l debug -v dryrun
436 rate_limit $rate_limit
439 if $incremental_strict; then
440 cat >>/etc
/btrbk.conf
<<EOF
445 for m
in ${mountpoints[@]}; do
456 if [[ $source ]]; then
457 cat >>/etc
/btrbk.conf
<<EOF
458 volume ssh://$bbksource$vol
460 target send-receive $vol/btrbk
463 if (( ${#targets[@]} )); then
464 cat >>/etc
/btrbk.conf
<<EOF
470 # q has sensitive data i dont want to backup for so long
471 cat >>/etc
/btrbk.conf
<<EOF
472 snapshot_preserve 18h 14d
473 snapshot_preserve_min 2h
475 target_preserve 18h 14d
476 target_preserve_min 2h
480 for tg
in ${targets[@]}; do
482 if [[ $tg == *:* ]]; then
485 cat >>/etc
/btrbk.conf
<<EOF
486 target send-receive ssh://$tg$vol/btrbk
493 # # to manually backup amy,
494 # # bbk -e -s amy -m root_ubuntubionic
495 # cat >>/etc/btrbk.conf <<'EOF'
496 # volume ssh://amy/mnt/root
497 # subvolume root_ubuntubionic
498 # target send-receive /mnt/root/btrbk
502 # todo: umount first to ensure we don't have any errors
503 # todo: do some kill fuser stuff to make umount more reliable
513 m btrbk
-v -n $cmd_arg
515 elif [[ $cmd_arg == archive
]]; then
516 if [[ $source ]]; then
517 m btrbk
$verbose_arg $progress_arg $cmd_arg ssh://$source$vol $vol
519 for tg
in ${targets[@]}; do
520 m btrbk
$verbose_arg $progress_arg $cmd_arg $vol ssh://$tg$vol
525 # -q and just using the syslog option seemed nice,
526 # but it doesn't show when a send has a parent and when it doesn't.
527 m btrbk
$verbose_arg $progress_arg $cmd_arg
529 # todo: tp not valid anymore.
530 # if we have it, sync to systems which don't
531 if mountpoint
$rsync_mountpoint >/dev
/null
; then
532 for tg
in ${targets[@]}; do
535 dirs=(/p
/c
/machine_specific
/tp
)
536 for x
in /p
/c
/machine_specific
/*.hosts
; do
537 if grep -qxF $tg $x; then
541 m rsync
-aSAXPH --specials --devices --delete --relative ${dirs[@]} root@
$tg:/
547 if [[ $source ]]; then
548 m mount-latest-subvol
550 m
/a
/exe
/mount-latest-remote
${targets[@]}
553 if [[ $ret == 0 ]]; then
554 for tg
in ${targets[@]}; do
556 #ssh root@$tg /a/exe/mail-backup-clean
562 # todo: move variable data we don't care about backing up
563 # to /nocow and symlink it.
566 # background on btrbk timezones. with short/long, timestamps use local time.
567 # for long, if your local time moves backwards, by moving timezones or
568 # for an hour when daylight savings changes it, you will temporarily get
569 # a more aggressive retention policy for the overlapping period, and
570 # vice versa for the opposite timezone move. The alternative is using
571 # long-iso, which puts timezone info into the timestamp, which means
572 # that instead of shifting time, you shift the start of day/week/month
573 # which is used for retention to your new local time, which means for
574 # example, if you moved forward by 8 hours, the daily/weekly/monthly
575 # retention will be 8 hours more aggressive since midnight is at a new
576 # time, unless you fake the timzeone using the TZ env variable.
577 # However, in the short term, there will be no inconsistencies.
578 # I don't see any problem with shifting when the day starts for
579 # retention, so I'm using long-iso.
581 # note to create a long-iso timestamp: date +%Y%m%dT%H%M%S%z