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