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