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