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