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