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