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