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