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