temporarily change backup targets
[distro-setup] / btrbk-run
1 #!/bin/bash
2 # Copyright (C) 2016 Ian Kelling
3
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
7
8 # http://www.apache.org/licenses/LICENSE-2.0
9
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.
15
16
17 # todo: if we cancel in the middle of a btrfs send, then run again immediately, the received subvolume doesn't get a Received UUID: field, and we won't mount it. Need to figure out a solution that will fix this.
18
19 err-bash-trace() {
20 local -i argc_index=0 frame i start=${1:-0} max_indent=8 indent
21 local source
22 local extdebug=false
23 if [[ $(shopt -p extdebug) == *-s* ]]; then
24 extdebug=true
25 fi
26 for ((frame=0; frame < ${#FUNCNAME[@]}-1; frame++)); do
27 argc=${BASH_ARGC[frame]}
28 argc_index+=$argc
29 ((frame < start)) && continue
30 if (( ${#BASH_SOURCE[@]} > 1 )); then
31 source="${BASH_SOURCE[frame+1]}:${BASH_LINENO[frame]}:"
32 fi
33 indent=$((frame-start + 1))
34 indent=$((indent < max_indent ? indent : max_indent))
35 printf "%${indent}s↳%sin \`%s" '' "$source" "${FUNCNAME[frame]}"
36 if $extdebug; then
37 for ((i=argc_index-1; i >= argc_index-argc; i--)); do
38 printf " %s" "${BASH_ARGV[i]}"
39 done
40 fi
41 echo \'
42 done
43 return 0
44 }
45 err-catch() {
46 set -E; shopt -s extdebug
47 _err-trap() {
48 err=$?
49 exec >&2
50 set +x
51 echo "${BASH_SOURCE[1]}:${BASH_LINENO[0]}: \`$BASH_COMMAND' returned $err"
52 err-bash-trace 2
53 set -e # err trap does not work within an error trap
54 "${_errcatch_cleanup[@]:-:}" # note :-: is to be compatible with set -u
55 echo "$0: exiting with code $err"
56 exit $err
57 }
58 trap _err-trap ERR
59 set -o pipefail
60 }
61 err-catch
62
63
64 [[ $EUID == 0 ]] || exec sudo -E "$BASH_SOURCE" "$@"
65
66
67 usage() {
68 cat <<'EOF'
69 btrbk-run [OPTIONS]
70 usually -t TARGET_HOST or -s SOURCE_HOST
71
72 Note, at source location, intentionally not executable, run and read
73 install-my-scripts.
74
75 EOF
76 echo "top of script file:"
77 sed -n '1,/^[# ]*end command line/{p;b};q' "$0"
78 exit $1
79 }
80
81 rsync-dirs() {
82 local host=$1
83 local path=$2
84 m rsync $dry_run_arg -ahi --relative --delete "$path" "root@$host:/"
85 }
86
87
88 pre="${0##*/}:"
89 m() { if $verbose; then printf "$pre %s\n" "$*"; fi; "$@"; }
90 die() { printf "$pre %s\n" "$*" >&2; exit 1; }
91
92 # latest $MAIL_HOST
93 if [[ -e /b/bash_unpublished/source-state ]]; then
94 source /b/bash_unpublished/source-state
95 fi
96
97 # note q is owned by root:1000
98
99 mountpoints=()
100
101 rsync_mountpoint=/q
102
103 # default options
104 conf_only=false
105 dry_run=false # mostly for testing
106 rate_limit=no
107 verbose=true; verbose_arg=-v
108 progress_arg="--progress"
109 pull_reexec=false
110
111 default_args_file=/etc/btrbk-run.conf
112 if [[ -s $default_args_file ]]; then
113 set -- $(< $default_args_file) "$@"
114 # i havent used this feature yet, so warn about it
115 echo "$0: warning: default btrbk-run options set in $default_args_file (sleeping 5 seconds):"
116 cat $default_args_file
117 sleep 5
118 fi
119
120 cron=false
121 orig_args=("$@")
122 temp=$(getopt -l cron,pull-reexec,help cl:m:npqs:t:vh "$@") || usage 1
123 eval set -- "$temp"
124 while true; do
125 case $1 in
126 --cron)
127 cron=true
128 pre=
129 shift
130 ;;
131 # only creates the config file, does not run btrbk
132 -c) conf_only=true; shift ;;
133 # bytes per second, suffix k m g
134 -l) rate_limit=$2; shift 2 ;;
135 # Comma separated mountpoints to backup. This has defaults set below.
136 -m) IFS=, mountpoints=($2); unset IFS; shift 2 ;;
137 -n) dry_run=true; dry_run_arg=-n; shift ;;
138 -p) progress_arg="--progress"; shift ;;
139 --pull-reexec) pull_reexec=true; shift ;;
140 -q) verbose=false; verbose_arg=; progress_arg=; shift ;;
141 # source host to receive a backup from
142 -s) source=$2; shift 2 ;;
143 # target hosts to send to. empty is valid for just doing local
144 # snapshot. we have default hosts we will populate.
145 -t) IFS=, targets=($2); unset IFS; shift 2 ;;
146 -v) verbose=true; verbose_arg=-v; shift ;;
147 -h|--help) usage ;;
148 --) shift; break ;;
149 *) die "Internal error!" ;;
150 esac
151 done
152
153 # only tested commands are resume and archive
154 cmd_arg=${1:-run}
155
156 case $cmd_arg in
157 run|resume|archive) : ;;
158 *) die "untested command arg" ;;
159 esac
160
161 if (( $# > 1 )); then
162 die: "only 1 nonoption arg is supported"
163 fi
164
165 if [[ -v targets && $source ]]; then
166 die "error: -t and -s are mutually exclusive"
167 fi
168
169 if $verbose; then
170 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"
171 fi
172 ### end options parsing
173
174 # TODO: i wonder if there should be an option to send to the default
175 # targets, plus any given on the command line.
176
177 # set default targets
178 if [[ ! -v targets && ! $source ]]; then
179 if [[ $HOSTNAME != "$MAIL_HOST" ]] && $cron ; then
180 echo "MAIL_HOST=$MAIL_HOST, nothing to do"
181 exit 0
182 fi
183 case $HOSTNAME in
184 kw|x2)
185 if ping -q -c1 -w1 iank.vpn.office.fsf.org &>/dev/null; then
186 home=iank.vpn.office.fsf.org
187 else
188 home=b8.nz
189 fi
190 ;;&
191 kw)
192 targets=($home x2)
193 ;;
194 x2)
195 targets=($home kw)
196 ;;
197 tp)
198 # kd disabled temporarily while its hot and i plan to work on it.
199 #targets=(frodo kd)
200 targets=(frodo)
201 # might not be connected to the vpn
202 if timeout -s 9 10 ssh kw :; then
203 targets+=(kw)
204 fi
205 ;;
206 kd)
207 targets=(frodo tp)
208 # might not be connected to the vpn
209 if timeout -s 9 10 ssh kw :; then
210 targets+=(kw)
211 fi
212 ;;
213 *)
214 die "error: no default targets for this host, use -t"
215 ;;
216 esac
217 fi
218
219 if [[ -v targets ]]; then
220 echo "targets: ${targets[*]}"
221 fi
222
223 if [[ $source ]]; then
224 echo "source: $source"
225 fi
226
227
228 if [[ $mountpoints ]]; then
229 for mp in ${mountpoints[@]}; do # default mountpoints to sync
230 if [[ -e /nocow/btrfs-stale/$mp ]]; then
231 die "error: $mp is stale, mount-latest-subvol first"
232 fi
233 done
234 else
235 # set default mountpoints
236 case $HOSTNAME in
237 # no remote backups atm. note, if we do enable this, configuration below will need some changes.
238 # frodo)
239 # prospective_mps=(/i)
240 # ;;
241 *)
242 prospective_mps=(/a /q)
243 if [[ $source ]]; then
244 source_state="$(ssh $source cat /a/bin/bash_unpublished/source-state)"
245 eval "$source_state"
246 source_host="$(ssh $source cat /etc/hostname)"
247 if [[ $source_host == "$MAIL_HOST" ]]; then
248 prospective_mps+=(/o)
249 fi
250 else
251 if [[ $HOSTNAME == "$MAIL_HOST" ]]; then
252 prospective_mps+=(/o)
253 fi
254 fi
255 ;;
256 esac
257 for mp in ${prospective_mps[@]}; do # default mountpoints to sync
258 if [[ -e /nocow/btrfs-stale/$mp ]]; then
259 echo "$pre warning: $mp stale, not adding to default mountpoints"
260 continue
261 fi
262 if awk '{print $2}' /etc/fstab | grep -xF $mp &>/dev/null; then
263 mountpoints+=($mp)
264 fi
265 done
266 fi
267
268 echo "mountpoints: ${mountpoints[*]}"
269
270 ##### end command line parsing ########
271
272 if [[ $source ]]; then
273 if [[ $(ssh $source systemctl is-active btrbk.service) != inactive ]]; then
274 echo "$0: error: cron btrbk is running on source. exiting out of caution"
275 exit 1
276 fi
277 fi
278
279 # pull_reexec stops us from getting into an infinite loop if there is some
280 # kind of weird problem
281 pulla=false
282 for m in "${mountpoints[@]}"; do
283 if [[ $m == /a ]]; then
284 pulla=true
285 break
286 fi
287 done
288 if ! $pull_reexec && [[ $source ]] && $pulla ; then
289 tmpf=$(mktemp)
290 scp $source:/a/bin/distro-setup/btrbk-run $tmpf
291 if ! diff -q $tmpf $BASH_SOURCE; then
292 echo "$pre found newer version on host $source. reexecing"
293 install -T $tmpf /usr/local/bin/btrbk-run
294 m /usr/local/bin/btrbk-run --pull-reexec "${orig_args[@]}"
295 exit
296 fi
297 fi
298
299
300
301
302
303 if ! which btrbk &>/dev/null; then
304 die "error: no btrbk binary found"
305 fi
306 # if our mountpoints are from stale snapshots,
307 # it doesn't make sense to do a backup.
308 check-subvol-stale ${mountpoints[@]} || die "found stale mountpoints in ${mountpoints[*]}"
309
310 # for an initial run, btrbk requires the dir to exist.
311 mkdir -p /mnt/root/btrbk
312 local_zone=$(date +%z)
313
314 if [[ $source ]]; then
315 if ! zone=$(ssh root@$source date +%z); then
316 die failed to ssh to root@$source
317 fi
318 if [[ $zone != $local_zone ]]; then
319 die "error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
320 fi
321
322 else
323
324 sshable=()
325 sshfail=()
326 min_idle_ms=$((1000 * 60 * 15))
327 for h in ${targets[@]}; do
328 if zone=$(ssh root@$h "mkdir -p /mnt/root/btrbk && date +%z"); then
329 if $cron && DISPLAY=:0 xprintidle; then
330 # This is a separate ssh because xprintidle can fail and thats ok.
331 # Ignore this host. i sometimes use a non-main machine for testing or web browsing, knowing that
332 # everything will be wiped by the next backup, but I dont want it to happen as Im using
333 # it from cronjob.
334 continue
335 fi
336 sshable+=($h)
337 if [[ $zone != $local_zone ]]; then
338 die "error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
339 fi
340 else
341 sshfail+=($h)
342 fi
343 done
344 if [[ ! $sshable ]] || { ! $cron && [[ $sshfail ]]; }; then
345 die "failed to ssh to hosts: ${sshfail[*]}"
346 else
347 if [[ $sshfail ]]; then
348 ret=1
349 echo "$pre error: failed to ssh to ${sshfail[*]} but continuing with other hosts"
350 fi
351 targets=(${sshable[@]})
352 fi
353 fi
354
355
356 cat >/etc/btrbk.conf <<EOF
357 ssh_identity /root/.ssh/home
358 # Just a guess that local7 is a good facility to pick.
359 # It's a bit odd that the transaction log has to be logged to
360 # a file or syslog, while other output is sent to std out.
361 # The man does not mention a way for them to be together, but
362 # I dunno if setting a log level like warn might also output
363 # transaction info.
364 transaction_syslog local7
365
366 # note, i had this because man said 20% speedup, but ran into
367 # this issue, https://github.com/digint/btrbk/issues/275
368 #stream_buffer 512m
369
370 # so we only run one at a time
371 lockfile /var/lock/btrbk.lock
372
373 # default format of short does not accomidate hourly preservation setting
374 timestamp_format long-iso
375
376 # only make a snapshot if things have changed
377 snapshot_create onchange
378 # I could make this different from target_preserve,
379 # if one disk had less space.
380 # for now, keeping them equal.
381 snapshot_preserve 36h 14d 8w 24m
382 snapshot_preserve_min 4h
383 snapshot_dir btrbk
384
385 # so, total backups = ~89
386 target_preserve 36h 14d 8w 24m
387 target_preserve_min 4h
388
389 # if something fails and it's not obvious, try doing
390 # btrbk -l debug -v dryrun
391
392 rate_limit $rate_limit
393 EOF
394
395
396
397
398
399 vol=/mnt/root
400 for m in ${mountpoints[@]}; do
401 sub=${m##*/}
402 if [[ $source ]]; then
403 cat >>/etc/btrbk.conf <<EOF
404 volume ssh://$source$vol
405 subvolume $sub
406 target send-receive $vol/btrbk
407 EOF
408 else
409 cat >>/etc/btrbk.conf <<EOF
410 volume $vol
411 subvolume $sub
412 EOF
413 for tg in ${targets[@]}; do
414 cat >>/etc/btrbk.conf <<EOF
415 target send-receive ssh://$tg$vol/btrbk
416 EOF
417 done
418 fi
419 done
420
421
422 # todo: umount first to ensure we don't have any errors
423 # todo: do some kill fuser stuff to make umount more reliable
424
425
426 if $conf_only; then
427 exit
428 fi
429
430
431
432 if $dry_run; then
433 m btrbk -v -n $cmd_arg
434 exit 0
435 elif [[ $cmd_arg == archive ]]; then
436 if [[ $source ]]; then
437 m btrbk $verbose_arg $progress_arg $cmd_arg ssh://$source$vol $vol
438 else
439 for tg in ${targets[@]}; do
440 m btrbk $verbose_arg $progress_arg $cmd_arg $vol ssh://$tg$vol
441 done
442 fi
443 exit 0
444 fi
445 # -q and just using the syslog option seemed nice,
446 # but it doesn't show when a send has a parent and when it doesn't.
447 m btrbk $verbose_arg $progress_arg $cmd_arg
448
449 # if we have it, sync to systems which don't
450 if mountpoint $rsync_mountpoint >/dev/null; then
451 for tg in ${targets[@]}; do
452 case $tg in
453 li|lk)
454 for x in /p/c/machine_specific/*.hosts; do
455 if grep -qxF $tg $x; then
456 dir=${x%.hosts}
457 rsync-dirs $tg $dir
458 fi
459 done
460 ;;
461 esac
462 done
463 fi
464
465 if [[ $source ]]; then
466 m mount-latest-subvol $verbose_arg
467 else
468 m /a/exe/mount-latest-remote ${targets[@]}
469 fi
470
471 exit $ret
472
473 # todo: move variable data we don't care about backing up
474 # to /nocow and symlink it.
475
476
477 # background on btrbk timezones. with short/long, timestamps use local time.
478 # for long, if your local time moves backwards, by moving timezones or
479 # for an hour when daylight savings changes it, you will temporarily get
480 # a more aggressive retention policy for the overlapping period, and
481 # vice versa for the opposite timezone move. The alternative is using
482 # long-iso, which puts timezone info into the timestamp, which means
483 # that instead of shifting time, you shift the start of day/week/month
484 # which is used for retention to your new local time, which means for
485 # example, if you moved forward by 8 hours, the daily/weekly/monthly
486 # retention will be 8 hours more aggressive since midnight is at a new
487 # time, unless you fake the timzeone using the TZ env variable.
488 # However, in the short term, there will be no inconsistencies.
489 # I don't see any problem with shifting when the day starts for
490 # retention, so I'm using long-iso.
491
492 # note to create a long-iso timestamp: date +%Y%m%dT%H%M%S%z