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