e96bb52cdc9294faf7e5fae96b5a1e254013cff4
[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
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
20 # fix this.
21
22
23 [[ $EUID == 0 ]] || exec sudo -E "${BASH_SOURCE[0]}" "$@"
24
25 source /usr/local/lib/err
26
27 usage() {
28 cat <<'EOF'
29 btrbk-run [OPTIONS]
30 usually -t TARGET_HOST or -s SOURCE_HOST
31
32 Note, at source location, intentionally not executable, run and read
33 install-my-scripts.
34
35 EOF
36 echo "top of script file:"
37 sed -n '1,/^[# ]*end command line/{p;b};q' "$0"
38 exit $1
39 }
40
41
42
43 pre="${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; }
48
49 # latest $MAIL_HOST
50 if [[ -e /b/bash_unpublished/source-state ]]; then
51 source /b/bash_unpublished/source-state
52 fi
53
54 # note q is owned by root:1000
55
56 mountpoints=()
57
58 rsync_mountpoint=/q
59
60 ret=0
61 # default options
62 conf_only=false
63 dry_run=false # mostly for testing
64 rate_limit=no
65 verbose=true; verbose_arg=-v
66 progress_arg="--progress"
67 incremental_strict=false
68 pull_reexec=false
69
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
76 sleep 5
77 fi
78
79 early=false # quit early, just btrbk, no extra remounting etc.
80 cron=false
81 orig_args=("$@")
82 temp=$(getopt -l cron,pull-reexec,help ceil:m:npqs:t:vh "$@") || usage 1
83 eval set -- "$temp"
84 while true; do
85 case $1 in
86 --cron)
87 cron=true
88 pre=
89 shift
90 ;;
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 -q) verbose=false; verbose_arg=; progress_arg=; shift ;;
103 # source host to receive a backup from
104 -s)
105 source=$2
106 bbksource=$source
107 if [[ $source == *:* ]]; then
108 bbksource="[$source]"
109 fi
110 shift 2
111 ;;
112 # target hosts to send to. empty is valid for just doing local
113 # snapshot. we have default hosts we will populate.
114 -t) IFS=, targets=($2); unset IFS; shift 2 ;;
115 -v) verbose=true; verbose_arg=-v; shift ;;
116 -h|--help) usage ;;
117 --) shift; break ;;
118 *) die "Internal error!" ;;
119 esac
120 done
121
122 # only tested commands are resume and archive
123 cmd_arg=${1:-run}
124
125 case $cmd_arg in
126 run|resume|archive) : ;;
127 *) die "untested command arg" ;;
128 esac
129
130 if (( $# > 1 )); then
131 die: "only 1 nonoption arg is supported"
132 fi
133
134 if [[ -v targets && $source ]]; then
135 # note, this doesnt need to be the case, but
136 # we would need to think about it.
137 die "error: -t and -s are mutually exclusive"
138 fi
139
140 if $verbose; then
141 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"
142 fi
143 ### end options parsing
144
145 # remove path from earlier version of btrbk
146 rm -f /usr/sbin/btrbk
147 # note, this still works as intended if there is no /usr/bin/btrbk
148 if [[ /a/opt/btrbk/btrbk -nt /usr/bin/btrbk ]]; then
149 if [[ -e /b/distro-functions/src/package-manager-abstractions ]]; then
150 . /b/distro-functions/src/package-manager-abstractions
151 pi asciidoctor
152 fi
153 cd /a/opt/btrbk
154 m make install
155 fi
156
157 # TODO: i wonder if there should be an option to send to the default
158 # targets, plus any given on the command line.
159
160
161 amy=false
162 # set default targets
163 if [[ ! -v targets && ! $source ]]; then
164 if [[ $HOSTNAME != "$MAIL_HOST" ]] && $cron ; then
165 echo "MAIL_HOST=$MAIL_HOST, nothing to do"
166 mexit 0
167 else
168 amy=true
169 fi
170
171 at_work=false
172
173 targets=(frodo.b8.nz)
174 case $HOSTNAME in
175 kw)
176 at_work=true
177 ;;&
178 x2|x3|sy)
179 if ping -q -c1 -w1 hal.office.fsf.org \
180 && ip n show 192.168.0.26 | grep . &>/dev/null; then
181 at_work=true
182 fi
183 ;;&
184 kw|x2|x3|sy)
185 if $at_work; then
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=i.b8.nz
190 fi
191 else
192 home=b8.nz
193 fi
194 ;;&
195 kw)
196 targets+=($home x3)
197 ;;
198 x2|x3|sy)
199 targets+=($home)
200 if $at_work; then
201 targets+=(kw.office.fsf.org)
202 else
203 targets+=(kw.b8.nz)
204 fi
205 ;;
206 kd)
207 targets+=(x2.b8.nz sy.b8.nz kw.b8.nz)
208 ;;
209 frodo)
210 # no targets
211 targets=()
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 if [[ ${mountpoints[0]} ]]; then
228 for mp in ${mountpoints[@]}; do
229 if [[ -e /nocow/btrfs-stale/$mp ]]; then
230 die "error: $mp is stale, mount-latest-subvol first"
231 fi
232 done
233 else
234 # set default mountpoints
235 if [[ ${targets[0]} == tp ]]; then
236 prospective_mps=(/a)
237 else
238 case $HOSTNAME in
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 # HOST2 is really the mail host if it exists
254 if [[ $HOST2 && $HOST2 != "$HOSTNAME" ]]; then
255 echo "skipping /o because HOST2 is not us"
256 else
257 prospective_mps+=(/o)
258 fi
259 fi
260 fi
261 ;;
262 esac
263 fi
264 for mp in ${prospective_mps[@]}; do # default mountpoints to sync
265 if [[ -e /nocow/btrfs-stale/$mp ]]; then
266 e "warning: $mp stale, not adding to default mountpoints"
267 continue
268 fi
269 if awk '{print $2}' /etc/fstab | grep -xF $mp &>/dev/null; then
270 mountpoints+=($mp)
271 fi
272 done
273 fi
274
275 echo "mountpoints: ${mountpoints[*]}"
276
277 ##### end command line parsing ########
278
279 if [[ $source ]]; then
280 if [[ $(ssh $source ps --no-headers -o comm 1) == systemd ]]; then
281 status=$(ssh $source systemctl is-active btrbk.service) || : # normally returns 3
282 case $status in
283 inactive|failed) : ;;
284 *)
285 echo "$0: error: cron btrbk is running on source. exiting out of caution"
286 mexit 1
287 esac
288 fi
289 fi
290
291 # pull_reexec stops us from getting into an infinite loop if there is some
292 # kind of weird problem
293 pulla=false
294 for m in "${mountpoints[@]}"; do
295 if [[ $m == /a ]]; then
296 pulla=true
297 break
298 fi
299 done
300 if ! $pull_reexec && [[ $source ]] && $pulla ; then
301 tmpf=$(mktemp)
302 m rsync -ra $source:/usr/local/bin/{mount-latest-subvol,check-subvol-stale} /usr/local/bin
303 m rsync -ra $source:/usr/local/lib/err /usr/local/lib
304 m scp $source:/a/bin/distro-setup/btrbk-run $tmpf
305 if ! diff -q $tmpf ${BASH_SOURCE[0]}; then
306 e "found different version on host $source. reexecing"
307 install -T $tmpf /usr/local/bin/btrbk-run
308 m /usr/local/bin/btrbk-run --pull-reexec "${orig_args[@]}"
309 mexit 0
310 fi
311 fi
312
313
314 if ! which btrbk &>/dev/null; then
315 die "error: no btrbk binary found"
316 fi
317 # if our mountpoints are from stale snapshots,
318 # it doesn't make sense to do a backup.
319 check-subvol-stale ${mountpoints[@]} || die "found stale mountpoints in ${mountpoints[*]}"
320
321 # for an initial run, btrbk requires the dir to exist.
322 mkdir -p /mnt/root/btrbk
323 local_zone=$(date +%z)
324
325 if [[ $source ]]; then
326 if ! zone=$(ssh root@$source date +%z); then
327 die failed to ssh to root@$source
328 fi
329 if [[ $zone != "$local_zone" ]]; then
330 die "error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
331 fi
332
333 else
334
335 sshable=()
336 sshfail=()
337 min_idle_ms=$((1000 * 60 * 15))
338 for h in ${targets[@]}; do
339 if remote_info=( $(timeout -s 9 6 ssh root@$h "mkdir -p /mnt/root/btrbk && date +%z && df --output=size,pcent / | tail -n1") ); then
340 zone=${remote_info[0]}
341 root_size=${remote_info[1]}
342 percent_used=${remote_info[2]%%%}
343
344 if (( ${#remote_info[@]} != 3 )); then
345 die "error: didnt get 3 fields in test ssh to target $h. investigate"
346 fi
347
348
349 # we may be booted into a bootstrap fs or something
350 min_root_kb=$(( 1024 * 1024 * 200 )) # 200 gb
351 if (( root_size < min_root_kb )); then
352 continue
353 fi
354
355 if (( percent_used >= 98 )); then
356 die "error: filesystem on target $h is $percent_used % full"
357 fi
358
359 # This is a separate ssh because xprintidle can fail and thats ok.
360 if $cron && idle_ms=$(timeout -s 9 6 ssh $h DISPLAY=:0 xprintidle); then
361 if (( idle_ms < min_idle_ms )); then
362
363 # Ignore this host. i sometimes use a non-main machine for
364 # testing or web browsing, knowing that everything will be wiped
365 # by the next backup, but I dont want it to happen as Im using
366 # it from cronjob.
367 e "warning: $h: active X session in the last 15 minutes, skipping for now"
368 continue
369 fi
370 fi
371 sshable+=($h)
372 if [[ $zone != "$local_zone" ]]; then
373 die "error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
374 fi
375 else
376 sshfail+=($h)
377 fi
378 done
379 if [[ ! ${sshable[*]} ]] || { ! $cron && [[ ${sshfail[*]} ]]; }; then
380 die "failed to ssh to hosts: ${sshfail[*]}"
381 else
382 if [[ ${sshfail[*]} ]]; then
383 ret=1
384 e "error: failed to ssh to ${sshfail[*]} but continuing with other hosts"
385 fi
386 targets=(${sshable[@]})
387 fi
388 fi
389
390
391 cat >/etc/btrbk.conf <<EOF
392 ssh_identity /q/root/h
393 #ssh_identity /root/.ssh/home
394
395 # Just a guess that local7 is a good facility to pick.
396 # It's a bit odd that the transaction log has to be logged to
397 # a file or syslog, while other output is sent to std out.
398 # The man does not mention a way for them to be together, but
399 # I dunno if setting a log level like warn might also output
400 # transaction info.
401 transaction_syslog local7
402
403 # trying this out
404 stream_compress zstd
405
406 # so we only run one at a time
407 lockfile /var/lock/btrbk.lock
408
409 # default format of short does not accomidate hourly preservation setting
410 timestamp_format long-iso
411
412 # only make a snapshot if things have changed
413 snapshot_create onchange
414 # I could make this different from target_preserve,
415 # if one disk had less space.
416 # for now, keeping them equal.
417 snapshot_preserve 18h 14d 8w 24m
418 snapshot_preserve_min 2h
419 snapshot_dir btrbk
420
421 # so, total backups = ~58
422 target_preserve 18h 14d 8w 24m
423 target_preserve_min 2h
424
425 # if something fails and it's not obvious, try doing
426 # btrbk -l debug -v dryrun
427
428 rate_limit $rate_limit
429 EOF
430
431 if $incremental_strict; then
432 cat >>/etc/btrbk.conf <<EOF
433 incremental strict
434 EOF
435 fi
436
437 vol=/mnt/root
438 for m in ${mountpoints[@]}; do
439 sub=${m#/}
440 if [[ $source ]]; then
441 cat >>/etc/btrbk.conf <<EOF
442 volume ssh://$bbksource$vol
443 subvolume $sub
444 target send-receive $vol/btrbk
445 EOF
446 fi
447 if (( ${#targets[@]} )); then
448 cat >>/etc/btrbk.conf <<EOF
449 volume $vol
450 subvolume $sub
451 EOF
452 for tg in ${targets[@]}; do
453 # handle ipv6
454 if [[ $tg == *:* ]]; then
455 tg="[$tg]"
456 fi
457 cat >>/etc/btrbk.conf <<EOF
458 target send-receive ssh://$tg$vol/btrbk
459 EOF
460 done
461 fi
462 done
463
464 # if $amy; then
465 # # to manually backup amy,
466 # # bbk -e -s amy -m root_ubuntubionic
467 # cat >>/etc/btrbk.conf <<'EOF'
468 # volume ssh://amy/mnt/root
469 # subvolume root_ubuntubionic
470 # target send-receive /mnt/root/btrbk
471 # EOF
472 # fi
473
474 # todo: umount first to ensure we don't have any errors
475 # todo: do some kill fuser stuff to make umount more reliable
476
477
478 if $conf_only; then
479 mexit 0
480 fi
481
482
483
484 if $dry_run; then
485 m btrbk -v -n $cmd_arg
486 mexit 0
487 elif [[ $cmd_arg == archive ]]; then
488 if [[ $source ]]; then
489 m btrbk $verbose_arg $progress_arg $cmd_arg ssh://$source$vol $vol
490 else
491 for tg in ${targets[@]}; do
492 m btrbk $verbose_arg $progress_arg $cmd_arg $vol ssh://$tg$vol
493 done
494 fi
495 mexit 0
496 fi
497 # -q and just using the syslog option seemed nice,
498 # but it doesn't show when a send has a parent and when it doesn't.
499 m btrbk $verbose_arg $progress_arg $cmd_arg
500
501 # todo: tp not valid anymore.
502 # if we have it, sync to systems which don't
503 if mountpoint $rsync_mountpoint >/dev/null; then
504 for tg in ${targets[@]}; do
505 case $tg in
506 tp)
507 dirs=(/p/c/machine_specific/tp)
508 for x in /p/c/machine_specific/*.hosts; do
509 if grep -qxF $tg $x; then
510 dirs+=(${x%.hosts})
511 fi
512 done
513 m rsync -aSAXPH --specials --devices --delete --relative ${dirs[@]} root@$tg:/
514 ;;
515 esac
516 done
517 fi
518
519 if [[ $source ]]; then
520 m mount-latest-subvol
521 else
522 m /a/exe/mount-latest-remote ${targets[@]}
523 fi
524
525 if [[ $ret == 0 ]]; then
526 for tg in ${targets[@]}; do
527 :
528 #ssh root@$tg /a/exe/mail-backup-clean
529 done
530 fi
531
532 mexit $ret
533
534 # todo: move variable data we don't care about backing up
535 # to /nocow and symlink it.
536
537
538 # background on btrbk timezones. with short/long, timestamps use local time.
539 # for long, if your local time moves backwards, by moving timezones or
540 # for an hour when daylight savings changes it, you will temporarily get
541 # a more aggressive retention policy for the overlapping period, and
542 # vice versa for the opposite timezone move. The alternative is using
543 # long-iso, which puts timezone info into the timestamp, which means
544 # that instead of shifting time, you shift the start of day/week/month
545 # which is used for retention to your new local time, which means for
546 # example, if you moved forward by 8 hours, the daily/weekly/monthly
547 # retention will be 8 hours more aggressive since midnight is at a new
548 # time, unless you fake the timzeone using the TZ env variable.
549 # However, in the short term, there will be no inconsistencies.
550 # I don't see any problem with shifting when the day starts for
551 # retention, so I'm using long-iso.
552
553 # note to create a long-iso timestamp: date +%Y%m%dT%H%M%S%z