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