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