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