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