btrbk fixes
[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 set -eE -o pipefail
20 trap 'echo "$0:$LINENO:error: \"$BASH_COMMAND\" returned $?" >&2' ERR
21
22 [[ $EUID == 0 ]] || exec sudo -E "$BASH_SOURCE" "$@"
23
24
25 usage() {
26 cat <<'EOF'
27 btrbk-run [OPTIONS]
28 usually -t TARGET_HOST or -s SOURCE_HOST
29
30 Note, at source location, intentionally not executable, run and read
31 install-my-scripts.
32
33 EOF
34 echo "top of script file:"
35 sed -n '1,/^[# ]*end command line/{p;b};q' "$0"
36 exit $1
37 }
38
39 rsync-dirs() {
40 local host=$1
41 local path=$2
42 m rsync $dry_run_arg -ahi --relative --delete "$path" "root@$host:/"
43 }
44
45
46 m() { if $verbose; then printf "$pre %s\n" "$*"; fi; "$@"; }
47 die() { printf "$pre %s\n" "$*" >&2; exit 1; }
48
49 # latest $MAIL_HOST
50 if [[ -e /b/bash_unpublished/source-semi-priv ]]; then
51 source /b/bash_unpublished/source-semi-priv
52 fi
53
54 # note q is owned by root:1000
55
56 mountpoints=()
57
58 rsync_mountpoint=/q
59
60 # default options
61 conf_only=false
62 dry_run=false # mostly for testing
63 rate_limit=no
64 verbose=true; verbose_arg=-v
65 progress_arg="--progress"
66 pull_reexec=false
67
68 default_args_file=/etc/btrbk-run.conf
69 if [[ -s $default_args_file ]]; then
70 set -- $(< $default_args_file) "$@"
71 # i havent used this feature yet, so warn about it
72 echo "$0: warning: default btrbk-run options set in $default_args_file (sleeping 5 seconds):"
73 cat $default_args_file
74 sleep 5
75 fi
76
77 pre="${0##*/}:"
78 cron=false
79 orig_args=("$@")
80 temp=$(getopt -l cpull-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 # usefull commands are resume and archive
112 cmd_arg=${1:-run}
113
114 if [[ -v targets && $source ]]; then
115 die "error: -t and -s are mutually exclusive"
116 fi
117
118 if $verbose; then
119 printf "$pre options: conf_only=%s\ndry_run=%s\nrate_limit=%s\nverbose=%s\ncmd_arg=%s" "$conf_only" "$dry_run" "$rate_limit" "$verbose" "$cmd_arg"
120 fi
121 ### end options parsing
122
123
124 # set default targets
125 if [[ ! -v targets && ! $source && $HOSTNAME == "$MAIL_HOST" ]]; then
126 case $HOSTNAME in
127 kw|x2)
128 if ping -q -c1 -w1 iank.vpn.office.fsf.org &>/dev/null; then
129 home=iank.vpn.office.fsf.org
130 else
131 home=$HOME_DOMAIN
132 fi
133 ;;&
134 kw)
135 targets=($home x2)
136 ;;
137 x2)
138 targets=($home kw)
139 ;;
140 tp)
141 targets=(frodo kd)
142 # might not be connected to the vpn
143 if timeout -s 9 10 ssh kw :; then
144 targets+=(kw)
145 fi
146 ;;
147 kd)
148 targets=(frodo tp)
149 # might not be connected to the vpn
150 if timeout -s 9 10 ssh kw :; then
151 targets+=(kw)
152 fi
153 ;;
154 *)
155 die "error: no default targets for this host, use -t"
156 ;;
157 esac
158 fi
159
160 if [[ -v targets ]]; then
161 echo "targets: ${targets[*]}"
162 fi
163
164 if [[ $source ]]; then
165 echo "source: $source"
166 fi
167
168
169 if [[ $mountpoints ]]; then
170 for mp in ${mountpoints[@]}; do # default mountpoints to sync
171 if [[ -e /nocow/btrfs-stale/$mp ]]; then
172 die "error: $mp is stale, mount-latest-subvol first"
173 fi
174 done
175 else
176 # set default mountpoints
177 case $HOSTNAME in
178 # no remote backups atm. note, if we do enable this, configuration below will need some changes.
179 # frodo)
180 # prospective_mps=(/i)
181 # ;;
182 *)
183 prospective_mps=(/a /q)
184 if [[ $HOSTNAME == "$MAIL_HOST" ]]; then
185 prospective_mps+=(/o)
186 fi
187 ;;
188 esac
189 for mp in ${prospective_mps[@]}; do # default mountpoints to sync
190 if [[ -e /nocow/btrfs-stale/$mp ]]; then
191 echo "$pre warning: $mp stale, not adding to default mountpoints"
192 continue
193 fi
194 if awk '{print $2}' /etc/fstab | grep -xF $mp &>/dev/null; then
195 mountpoints+=($mp)
196 fi
197 done
198 fi
199
200 echo "mountpoints: ${mountpoints[*]}"
201
202
203
204 # pull_reexec stops us from getting into an infinite loop if there is some
205 # kind of weird problem
206 pulla=false
207 for m in "${mountpoints[@]}"; do
208 if [[ $m == /a ]]; then
209 pulla=true
210 break
211 fi
212 done
213 if ! $pull_reexec && [[ $source ]] && ! $pulla ; then
214 tmpf=$(mktemp)
215 scp $source:/a/bin/distro-setup/btrbk-run $tmpf
216 if ! diff -q $tmpf $BASH_SOURCE; then
217 echo "$pre found newer version on host $source. reexecing"
218 install -T $tmpf /usr/local/bin/btrbk-run
219 m /usr/local/bin/btrbk-run --pull-reexec "${orig_args[@]}"
220 exit
221 fi
222 fi
223
224
225 ##### end command line parsing ########
226
227
228
229 if ! which btrbk &>/dev/null; then
230 die "error: no btrbk binary found"
231 fi
232 # if our mountpoints are from stale snapshots,
233 # it doesn't make sense to do a backup.
234 check-subvol-stale ${mountpoints[@]} || die "found stale mountpoints in ${mountpoints[*]}"
235
236 # for an initial run, btrbk requires the dir to exist.
237 mkdir -p /mnt/root/btrbk
238 local_zone=$(date +%z)
239
240 if [[ $source ]]; then
241 if ! zone=$(ssh root$source date +%z); then
242 die failed to ssh to root@$source
243 fi
244 if [[ $zone != $local_zone ]]; then
245 die "error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
246 fi
247
248 else
249
250 sshable=()
251 sshfail=()
252 for h in ${targets[@]}; do
253 if zone=$(ssh root@$h "mkdir -p /mnt/root/btrbk && date +%z"); then
254 sshable+=($h)
255 else
256 sshfail+=($h)
257 fi
258 if [[ $zone != $local_zone ]]; then
259 die "error: dont confuse yourself with multiple time zones. $h has different timezone than localhost"
260 fi
261 done
262 if [[ ! $sshable ]] || { ! $cron && [[ $sshfail ]]; }; then
263 die "failed to ssh to hosts: ${sshfail[*]}"
264 else
265 if [[ $sshfail ]]; then
266 ret=1
267 echo "$pre error: failed to ssh to ${sshfail[*]} but continuing with other hosts"
268 fi
269 targets=(${sshable[@]})
270 fi
271 fi
272
273
274 cat >/etc/btrbk.conf <<EOF
275 ssh_identity /root/.ssh/home
276 # Just a guess that local7 is a good facility to pick.
277 # It's a bit odd that the transaction log has to be logged to
278 # a file or syslog, while other output is sent to std out.
279 # The man does not mention a way for them to be together, but
280 # I dunno if setting a log level like warn might also output
281 # transaction info.
282 transaction_syslog local7
283
284 # note, i had this because man said 20% speedup, but ran into
285 # this issue, https://github.com/digint/btrbk/issues/275
286 #stream_buffer 512m
287
288 # so we only run one at a time
289 lockfile /var/lock/btrbk.lock
290
291 # default format of short does not accomidate hourly preservation setting
292 timestamp_format long-iso
293
294 # only make a snapshot if things have changed
295 snapshot_create onchange
296 # I could make this different from target_preserve,
297 # if one disk had less space.
298 # for now, keeping them equal.
299 snapshot_preserve 36h 14d 8w 24m
300 snapshot_preserve_min 4h
301 snapshot_dir btrbk
302
303 # so, total backups = ~89
304 target_preserve 36h 14d 8w 24m
305 target_preserve_min 4h
306
307 # if something fails and it's not obvious, try doing
308 # btrbk -l debug -v dryrun
309
310 rate_limit $rate_limit
311 EOF
312
313
314
315
316
317 vol=/mnt/root
318 for m in ${mountpoints[@]}; do
319 sub=${m##*/}
320 if [[ $source ]]; then
321 cat >>/etc/btrbk.conf <<EOF
322 volume ssh://$source$vol
323 subvolume $sub
324 target send-receive $vol/btrbk
325 EOF
326 else
327 cat >>/etc/btrbk.conf <<EOF
328 volume $vol
329 subvolume $sub
330 EOF
331 for tg in ${targets[@]}; do
332 cat >>/etc/btrbk.conf <<EOF
333 target send-receive ssh://$tg$vol/btrbk
334 EOF
335 done
336 fi
337 done
338
339
340 # todo: umount first to ensure we don't have any errors
341 # todo: do some kill fuser stuff to make umount more reliable
342
343
344 if $conf_only; then
345 exit
346 fi
347
348
349
350 if $dry_run; then
351 m btrbk -v -n $cmd_arg
352 exit 0
353 elif [[ $cmd_arg == archive ]]; then
354 if [[ $source ]]; then
355 m btrbk $verbose_arg $progress_arg $cmd_arg ssh://$source$vol $vol
356 else
357 for tg in ${targets[@]}; do
358 m btrbk $verbose_arg $progress_arg $cmd_arg $vol ssh://$tg$vol
359 done
360 fi
361 exit 0
362 fi
363 # -q and just using the syslog option seemed nice,
364 # but it doesn't show when a send has a parent and when it doesn't.
365 m btrbk $verbose_arg $progress_arg $cmd_arg
366
367 # if we have it, sync to systems which don't
368 if mountpoint $rsync_mountpoint >/dev/null; then
369 for tg in ${targets[@]}; do
370 case $tg in
371 li|lk)
372 for x in /p/c/machine_specific/*.hosts; do
373 if grep -qxF $tg $x; then
374 dir=${x%.hosts}
375 rsync-dirs $tg $dir
376 fi
377 done
378 ;;
379 esac
380 done
381 fi
382
383 if [[ $source ]]; then
384 m mount-latest-subvol $verbose_arg
385 else
386 m /a/exe/mount-latest-remote ${targets[@]}
387 fi
388
389 exit $ret
390
391 # todo: move variable data we don't care about backing up
392 # to /nocow and symlink it.
393
394
395 # background on btrbk timezones. with short/long, timestamps use local time.
396 # for long, if your local time moves backwards, by moving timezones or
397 # for an hour when daylight savings changes it, you will temporarily get
398 # a more aggressive retention policy for the overlapping period, and
399 # vice versa for the opposite timezone move. The alternative is using
400 # long-iso, which puts timezone info into the timestamp, which means
401 # that instead of shifting time, you shift the start of day/week/month
402 # which is used for retention to your new local time, which means for
403 # example, if you moved forward by 8 hours, the daily/weekly/monthly
404 # retention will be 8 hours more aggressive since midnight is at a new
405 # time, unless you fake the timzeone using the TZ env variable.
406 # However, in the short term, there will be no inconsistencies.
407 # I don't see any problem with shifting when the day starts for
408 # retention, so I'm using long-iso.
409
410 # note to create a long-iso timestamp: date +%Y%m%dT%H%M%S%z