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