mostly t11 fixes
[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] [run|resume|archive]
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
80 cron=false
81 orig_args=("$@")
82 temp=$(getopt -l cron,pull-reexec,help ceil:m:npqrs:t:vh "$@") || usage 1
83 eval set -- "$temp"
84 while true; do
85 case $1 in
86 # some behaviors specific to running under cron:
87 # - skip hosts where xprintidle haven't been idle recently
88 # - if we can't ssh to 1 or more hosts, still do the rest
89 # - if we aren't MAIL_HOST and no -m or -s, just exit
90 --cron)
91 cron=true
92 pre=
93 shift
94 ;;
95 # only creates the config file, does not run btrbk
96 -c) conf_only=true; shift ;;
97 # quit early, just btrbk, no extra remounting etc.
98 -e) early=true; shift ;;
99 -i) incremental_strict=true; shift ;;
100 # bytes per second, suffix k m g
101 -l) rate_limit=$2; shift 2 ;;
102 # Comma separated mountpoints to backup. This has defaults set below.
103 -m) IFS=, mountpoints=($2); unset IFS; shift 2 ;;
104 -n) dry_run=true; dry_run_arg=-n; shift ;;
105 # show progress
106 -p) progress_arg="--progress"; shift ;;
107 # internal option for rerunning under newer SOURCE_HOST version.
108 --pull-reexec) pull_reexec=true; shift ;;
109 # quiet
110 -q) verbose=false; verbose_arg=; progress_arg=; shift ;;
111 # source host to receive a backup from
112 -s)
113 source=$2
114 bbksource=$source
115 if [[ $source == *:* ]]; then
116 bbksource="[$source]"
117 fi
118 shift 2
119 ;;
120 # target hosts to send to. empty is valid for just doing local
121 # snapshot. we have default hosts we will populate.
122 -t) IFS=, targets=($2); unset IFS; shift 2 ;;
123 # verbose.
124 -v) verbose=true; verbose_arg=-v; shift ;;
125 -h|--help) usage ;;
126 --) shift; break ;;
127 *) die "Internal error!" ;;
128 esac
129 done
130
131 cmd_arg=${1:-run}
132
133
134 std_preserve="18h 14d 8w 24m"
135 q_preserve="18h 14d"
136
137 case $cmd_arg in
138 run|resume) : ;;
139
140 # This works better than the normal archive command. We have to
141 # specify the mount points, but that is what we are used to doing and
142 # we prefer it. Another difference is that archive works recursively
143 # and we don't care about that. Sometimes we may still want to run
144 # btrbk archive, but it doesn't even use the config file, so just
145 # run it directly, eg:
146 # time s btrbk -v archive /mnt/r7/amy/boot/btrbk ssh://bo/mnt/boot2/btrbk
147 archive)
148 cmd=resume
149 std_preserve="999h 999d 999w 999m"
150 q_preserve="$std_preserve"
151 preserve_arg=-p
152 ;;
153 *) die "untested command arg" ;;
154 esac
155
156 if (( $# > 1 )); then
157 die: "only 1 nonoption arg is supported"
158 fi
159
160 if [[ -v targets && $source ]]; then
161 # note, this doesnt need to be the case, but
162 # we would need to think about it.
163 die "error: -t and -s are mutually exclusive"
164 fi
165
166 if $verbose; then
167 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"
168 fi
169 ### end options parsing
170
171 # remove path from earlier version of btrbk
172 rm -f /usr/sbin/btrbk
173 # note, this still works as intended if there is no /usr/bin/btrbk
174 if [[ /a/opt/btrbk/btrbk -nt /usr/bin/btrbk ]]; then
175 if [[ -e /b/distro-functions/src/package-manager-abstractions ]]; then
176 . /b/distro-functions/src/package-manager-abstractions
177 pi asciidoctor
178 fi
179 cd /a/opt/btrbk
180 m make install
181 fi
182
183 # TODO: i wonder if there should be an option to send to the default
184 # targets, plus any given on the command line.
185
186
187 amy=false
188 # set default targets
189 if [[ ! -v targets && ! $source ]]; then
190 if [[ $HOSTNAME != "$MAIL_HOST" ]] && $cron ; then
191 echo "MAIL_HOST=$MAIL_HOST, nothing to do"
192 mexit 0
193 else
194 amy=true
195 fi
196
197 at_work=false
198
199 targets=(frodo.b8.nz)
200 case $HOSTNAME in
201 x2|kw)
202 at_work=true
203 ;;&
204 x2|x3|sy|bo)
205 if ping -q -c1 -w1 hal.office.fsf.org \
206 && ip n show 192.168.0.26 | grep . &>/dev/null; then
207 at_work=true
208 fi
209 ;;&
210 kw|x2|x3|sy|bo)
211 if $at_work; then
212 if ping -q -c1 -w1 iank.vpn.office.fsf.org &>/dev/null; then
213 home=iank.vpn.office.fsf.org
214 else
215 home=i.b8.nz
216 fi
217 else
218 home=b8.nz
219 fi
220 ;;&
221 kw)
222 targets+=($home x2.office.fsf.org)
223 ;;
224 x2|x3|sy|bo)
225 targets+=($home)
226 if $at_work; then
227 targets+=(x2.office.fsf.org x2.b8.nz)
228 else
229 targets+=(x2wg.b8.nz)
230 fi
231 ;;
232 kd)
233 targets+=(x2wg.b8.nz x3.b8.nz)
234 if ping -q -c1 -w1 sy.b8.nz &>/dev/null; then
235 targets+=(sy.b8.nz)
236 else
237 targets+=(syw.b8.nz)
238 fi
239 ;;
240 frodo)
241 # no targets
242 targets=()
243 ;;
244 *)
245 die "error: no default targets for this host, use -t"
246 ;;
247 esac
248 fi
249
250 if [[ -v targets ]]; then
251 echo "targets: ${targets[*]}"
252 fi
253
254 if [[ $source ]]; then
255 echo "source: $source"
256 fi
257
258 if [[ ${mountpoints[0]} ]]; then
259 for mp in ${mountpoints[@]}; do
260 if [[ -e /nocow/btrfs-stale/$mp ]]; then
261 die "error: $mp is stale, mount-latest-subvol first"
262 fi
263 done
264 else
265 # set default mountpoints
266 if [[ ${targets[0]} == tp ]]; then
267 prospective_mps=(/a)
268 else
269 case $HOSTNAME in
270 frodo)
271 prospective_mps=(/i)
272 ;;
273 *)
274 prospective_mps=()
275 if [[ $source ]]; then
276 source_state="$(ssh $source cat /a/bin/bash_unpublished/source-state)"
277 eval "$source_state"
278 source_host="$(ssh $source cat /etc/hostname)"
279 if [[ $source_host == "$MAIL_HOST" ]]; then
280 prospective_mps+=(/o)
281 fi
282 else
283 if [[ $HOSTNAME == "$MAIL_HOST" ]]; then
284 # HOST2 is really the mail host if it exists
285 if [[ $HOST2 && $HOST2 != "$HOSTNAME" ]]; then
286 echo "skipping /o because HOST2 is not us"
287 else
288 prospective_mps+=(/o)
289 fi
290 fi
291 fi
292 # note: put q last just in case its specific retention options were to
293 # affect other config sections. I havent tested if that is the case.
294 prospective_mps+=(/a /ar /qr /q)
295 ;;
296 esac
297 fi
298 for mp in ${prospective_mps[@]}; do # default mountpoints to sync
299 if [[ -e /nocow/btrfs-stale/$mp ]]; then
300 e "warning: $mp stale, not adding to default mountpoints"
301 continue
302 fi
303 if awk '{print $2}' /etc/fstab | grep -xF $mp &>/dev/null; then
304 mountpoints+=($mp)
305 fi
306 done
307 fi
308
309 echo "mountpoints: ${mountpoints[*]}"
310
311 ##### end command line parsing ########
312
313 if [[ $source ]]; then
314 if [[ $(ssh $source ps --no-headers -o comm 1) == systemd ]]; then
315 status=$(ssh $source systemctl is-active btrbk.service) || : # normally returns 3
316 case $status in
317 inactive|failed) : ;;
318 *)
319 echo "$0: error: cron btrbk is running on source. exiting out of caution"
320 mexit 1
321 esac
322 fi
323 fi
324
325 # pull_reexec stops us from getting into an infinite loop if there is some
326 # kind of weird problem
327 pulla=false
328 for m in "${mountpoints[@]}"; do
329 if [[ $m == /a ]]; then
330 pulla=true
331 break
332 fi
333 done
334 if ! $pull_reexec && [[ $source ]] && $pulla ; then
335 tmpf=$(mktemp)
336 m rsync -ra $source:/usr/local/bin/{mount-latest-subvol,check-subvol-stale} /usr/local/bin
337 m rsync -ra $source:/usr/local/lib/err /usr/local/lib
338 m scp $source:/a/bin/distro-setup/btrbk-run $tmpf
339 if ! diff -q $tmpf ${BASH_SOURCE[0]}; then
340 e "found different version on host $source. reexecing"
341 install -T $tmpf /usr/local/bin/btrbk-run
342 m /usr/local/bin/btrbk-run --pull-reexec "${orig_args[@]}"
343 mexit 0
344 fi
345 fi
346
347
348 if ! command -v btrbk &>/dev/null; then
349 die "error: no btrbk binary found"
350 fi
351 # if our mountpoints are from stale snapshots,
352 # it doesn't make sense to do a backup.
353 check-subvol-stale ${mountpoints[@]} || die "found stale mountpoints in ${mountpoints[*]}"
354
355 # for an initial run, btrbk requires the dir to exist.
356 mkdir -p /mnt/{root,o}/btrbk
357 local_zone=$(date +%z)
358
359 if [[ $source ]]; then
360 if ! zone=$(ssh root@$source date +%z); then
361 if $conf_only; then
362 echo "$0: warning: failed to ssh to root@$source"
363 else
364 die failed to ssh to root@$source
365 fi
366 fi
367 if [[ $zone != "$local_zone" ]]; then
368 die "error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
369 fi
370
371 else
372
373 sshable=()
374 sshfail=()
375 min_idle_ms=$((1000 * 60 * 15))
376 for h in ${targets[@]}; do
377 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
378 zone=${remote_info[0]}
379 root_size=${remote_info[1]}
380 percent_used=${remote_info[2]%%%}
381
382 if (( ${#remote_info[@]} != 3 )); then
383 die "error: didnt get 3 fields in test ssh to target $h. investigate"
384 fi
385 elif $conf_only; then
386 # Use some typical values in this case
387 root_size=$(( 1024 * 1024 * 2000 )) #2tb
388 percent_used=10
389 zone=$(date +%z)
390 else
391 sshfail+=($h)
392 continue
393 fi
394
395 # we may be booted into a bootstrap fs or something
396 min_root_kb=$(( 1024 * 1024 * 200 )) # 200 gb
397 if (( root_size < min_root_kb )); then
398 continue
399 fi
400
401 if (( percent_used >= 98 )); then
402 die "error: filesystem on target $h is $percent_used % full"
403 fi
404
405 # This is a separate ssh because xprintidle can fail and thats ok.
406 if $cron && idle_ms=$(timeout -s 9 6 ssh $h DISPLAY=:0 xprintidle); then
407 if (( idle_ms < min_idle_ms )); then
408
409 # Ignore this host. i sometimes use a non-main machine for
410 # testing or web browsing, knowing that everything will be wiped
411 # by the next backup, but I dont want it to happen as Im using
412 # it from cronjob.
413 e "warning: $h: active X session in the last 15 minutes, skipping for now"
414 continue
415 fi
416 fi
417 sshable+=($h)
418 if [[ $zone != "$local_zone" ]]; then
419 die "error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
420 fi
421 done
422 if [[ ! ${sshable[*]} ]] || { ! $cron && [[ ${sshfail[*]} ]]; }; then
423 die "failed to ssh to hosts: ${sshfail[*]}"
424 else
425 if [[ ${sshfail[*]} ]]; then
426 ret=1
427 e "error: failed to ssh to ${sshfail[*]} but continuing with other hosts"
428 fi
429 targets=(${sshable[@]})
430 fi
431 fi
432
433
434 cat >/etc/btrbk.conf <<EOF
435 ssh_identity /q/root/h
436 #ssh_identity /root/.ssh/home
437
438 # Just a guess that local7 is a good facility to pick.
439 # It's a bit odd that the transaction log has to be logged to
440 # a file or syslog, while other output is sent to std out.
441 # The man does not mention a way for them to be together, but
442 # I dunno if setting a log level like warn might also output
443 # transaction info.
444 transaction_syslog local7
445
446 # trying this out
447 stream_compress zstd
448
449 # so we only run one at a time
450 lockfile /var/lock/btrbk.lock
451
452 # default format of short does not accomidate hourly preservation setting
453 timestamp_format long-iso
454
455 # only make a snapshot if things have changed
456 snapshot_create onchange
457 # I could make this different from target_preserve,
458 # if one disk had less space.
459 # for now, keeping them equal.
460 snapshot_preserve $std_preserve
461 snapshot_preserve_min 2h
462 snapshot_dir btrbk
463 # so, total backups = ~58
464 target_preserve $std_preserve
465 target_preserve_min 2h
466
467 # if something fails and it's not obvious, try doing
468 # btrbk -l debug -v dryrun
469
470 rate_limit $rate_limit
471 EOF
472
473 if $incremental_strict; then
474 cat >>/etc/btrbk.conf <<EOF
475 incremental strict
476 EOF
477 fi
478
479 for m in ${mountpoints[@]}; do
480 case $m in
481 /o)
482 vol=/mnt/o
483 ;;
484 *)
485 vol=/mnt/root
486 ;;
487 esac
488
489 sub=${m#/}
490 if [[ $source ]]; then
491 cat >>/etc/btrbk.conf <<EOF
492 volume ssh://$bbksource$vol
493 subvolume $sub
494 target send-receive $vol/btrbk
495 EOF
496 fi
497 if (( ${#targets[@]} )); then
498 cat >>/etc/btrbk.conf <<EOF
499 volume $vol
500 subvolume $sub
501 EOF
502 case $sub in
503 q)
504 # q has sensitive data i dont want to backup for so long
505 cat >>/etc/btrbk.conf <<EOF
506 snapshot_preserve $std_preserve
507 snapshot_preserve_min 2h
508 snapshot_dir btrbk
509 target_preserve $std_preserve
510 target_preserve_min 2h
511 EOF
512 ;;
513 esac
514 for tg in ${targets[@]}; do
515 # handle ipv6
516 if [[ $tg == *:* ]]; then
517 tg="[$tg]"
518 fi
519 cat >>/etc/btrbk.conf <<EOF
520 target send-receive ssh://$tg$vol/btrbk
521 EOF
522 done
523 fi
524 done
525
526 # if $amy; then
527 # # to manually backup amy,
528 # # bbk -e -s amy -m root_ubuntubionic
529 # cat >>/etc/btrbk.conf <<'EOF'
530 # volume ssh://amy/mnt/root
531 # subvolume root_ubuntubionic
532 # target send-receive /mnt/root/btrbk
533 # EOF
534 # fi
535
536 # todo: umount first to ensure we don't have any errors
537 # todo: do some kill fuser stuff to make umount more reliable
538
539
540 if $conf_only; then
541 mexit 0
542 fi
543
544
545
546 if $dry_run; then
547 m btrbk -v -n $cmd_arg
548 mexit 0
549 fi
550 # -q and just using the syslog option seemed nice,
551 # but it doesn't show when a send has a parent and when it doesn't.
552 m btrbk $preserve_arg $verbose_arg $progress_arg $cmd_arg
553
554 # todo: tp not valid anymore.
555 # if we have it, sync to systems which don't
556 if mountpoint $rsync_mountpoint >/dev/null; then
557 for tg in ${targets[@]}; do
558 case $tg in
559 tp)
560 dirs=(/p/c/machine_specific/tp)
561 for x in /p/c/machine_specific/*.hosts; do
562 if grep -qxF $tg $x; then
563 dirs+=(${x%.hosts})
564 fi
565 done
566 m rsync -aSAXPH --specials --devices --delete --relative ${dirs[@]} root@$tg:/
567 ;;
568 esac
569 done
570 fi
571
572 if [[ $source ]]; then
573 m mount-latest-subvol
574 else
575 m /a/exe/mount-latest-remote ${targets[@]}
576 fi
577
578 if [[ $ret == 0 ]]; then
579 for tg in ${targets[@]}; do
580 :
581 #ssh root@$tg /a/exe/mail-backup-clean
582 done
583 fi
584
585 mexit $ret
586
587 # todo: move variable data we don't care about backing up
588 # to /nocow and symlink it.
589
590
591 # background on btrbk timezones. with short/long, timestamps use local time.
592 # for long, if your local time moves backwards, by moving timezones or
593 # for an hour when daylight savings changes it, you will temporarily get
594 # a more aggressive retention policy for the overlapping period, and
595 # vice versa for the opposite timezone move. The alternative is using
596 # long-iso, which puts timezone info into the timestamp, which means
597 # that instead of shifting time, you shift the start of day/week/month
598 # which is used for retention to your new local time, which means for
599 # example, if you moved forward by 8 hours, the daily/weekly/monthly
600 # retention will be 8 hours more aggressive since midnight is at a new
601 # time, unless you fake the timzeone using the TZ env variable.
602 # However, in the short term, there will be no inconsistencies.
603 # I don't see any problem with shifting when the day starts for
604 # retention, so I'm using long-iso.
605
606 # note to create a long-iso timestamp: date +%Y%m%dT%H%M%S%z