5 ### (c) 2012 Mark Wooding
8 ###----- Licensing notice ---------------------------------------------------
10 ### This file is part of the `rsync-backup' program.
12 ### rsync-backup is free software; you can redistribute it and/or modify
13 ### it under the terms of the GNU General Public License as published by
14 ### the Free Software Foundation; either version 2 of the License, or
15 ### (at your option) any later version.
17 ### rsync-backup is distributed in the hope that it will be useful,
18 ### but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ### GNU General Public License for more details.
22 ### You should have received a copy of the GNU General Public License
23 ### along with rsync-backup; if not, write to the Free Software Foundation,
24 ### Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
28 thishost=$(hostname -s)
35 ###--------------------------------------------------------------------------
36 ### Utility functions.
41 ## Run rsync(1) in an appropriate manner. Configuration should ovrride
42 ## this or set $RSYNCOPTS if it wants to do something weirder. Arguments
43 ## to this function are passed on to rsync.
46 --archive --hard-links --numeric-ids --del \
51 --filter="dir-merge .rsync-backup" \
61 now=$(date +"%Y-%m-%d %H:%M:%S %z")
68 ## Run CMD, if this isn't a dry run.
71 t) echo >&2 " +++ $*" ;;
78 ## Copy lines from stdin to stdout, adding PREFIX.
80 while IFS= read -r line; do
81 printf "%s %s\n" "$prefix" "$line"
89 -stdin) stdinp=t; shift ;;
94 tag=$1 cmd=$2; shift 2
95 ## Run CMD, logging its output in a pleasing manner.
99 echo >&2 " *** RUN $tag"
100 echo >&2 " +++ $cmd $*"
106 case $stdinp in nil) exec </dev/null ;; esac
108 "$cmd" "$@" 3>&- 4>&- 5>&- 9>&-
110 copy "|" >&4; } 2>&1 |
111 copy "*" >&4; } 4>&1 |
116 *) log "FAIL $tag (rc = $rc)" ;;
125 ## Answer whether H is a local host.
128 "$thishost") return 0 ;;
135 ## Run CMD on the current host. If the host seems local then run the
136 ## command through a local shell; otherwise run it through ssh(1). Either
137 ## way it will be processed by a shell.
139 if localp $host; then run "@$host: $tag" sh -c "$cmd"
140 else run "@$host: $tag" ssh $userat$host "$cmd"
146 ## Like hostrun, but without the complicated logging, and targetted at a
149 if localp $h; then sh -c "$cmd"
156 ## Output (to stdout) either PATH or HOST:PATH, choosing the former if the
157 ## current host is local.
159 if localp $host; then echo $path
160 else echo $userat$host:$path
166 ## Define a hook called HOOK.
173 ## Add command CMD to the hook HOOK.
175 eval old=\$hk_$hook; new="$old $cmd"
181 ## Invoke HOOK, passing it the remaining arguments.
185 if ! $cmd "$@"; then return $?; fi
189 remove_old_logfiles () {
191 ## Remove old logfiles with names of the form BASE.DATE#N, so that there
192 ## are at most $MAXLOG of them.
194 ## Count up the logfiles.
196 for i in "$base".*; do
197 if [ ! -f "$i" ]; then continue; fi
201 ## If there are too many, go through and delete some early ones.
202 if [ $dryrun = nil ] && [ $nlog -gt $MAXLOG ]; then
203 n=$(( nlog - MAXLOG ))
204 for i in "$base".*; do
205 if [ ! -f "$i" ]; then continue; fi
208 if [ $n -eq 0 ]; then break; fi
213 ###--------------------------------------------------------------------------
214 ### Database operations.
217 host=$1 fs=$2 date=$3 vol=$4
219 if [ -f "$INDEXDB" ]; then
220 sqlite3 "$INDEXDB" <<EOF
221 INSERT INTO idx (host, fs, date, vol)
222 VALUES ('$host', '$fs', '$date', '$vol');
228 host=$1 fs=$2 date=$3
230 if [ -f "$INDEXDB" ]; then
231 sqlite3 "$INDEXDB" <<EOF
232 DELETE FROM idx WHERE
233 host = '$host' AND fs = '$fs' AND date = '$date';
238 ###--------------------------------------------------------------------------
239 ### Snapshot handling.
241 ## Snapshot protocol. Each snapshot type has a pair of functions snap_TYPE
242 ## and unsnap_TYPE. Each is given the current snapshot arguments and the
243 ## filesystem name to back up. The snap_TYPE function should create and
244 ## mount the snapshot and output an rsync(1) path to where the filesystem can
245 ## be copied; the unsnap_TYPE function should unmount and tear down the
248 ## Fake snapshot by not doing anything. Use only if you have no choice.
249 snap_live () { hostpath "$2"; }
250 unsnap_live () { :; }
252 ## Fake snapshot by remounting a live filesystem read-only. Useful if the
253 ## underlying storage isn't in LVM.
258 ## Place a marker in the filesystem so we know why it was made readonly.
259 ## (Also this serves to ensure that the filesystem was writable before.)
260 hostrun "snap-ro $mnt" "
261 echo rsync-backup >$mnt/.lock
262 mount -oremount,ro $mnt" || return $?
271 ## Check that the filesystem still has our lock marker.
272 hostrun "unsnap-ro $mnt" "
273 case \$(cat $mnt/.lock) in
275 *) echo unlocked by someone else; exit 31 ;;
277 mount -oremount,rw $mnt
278 rm $mnt/.lock" || return $?
281 ## Snapshot using LVM.
283 SNAPSIZE="-l10%ORIGIN"
288 ## Make the snapshot.
289 hostrun "snap-lvm $vg/$lv" "
290 lvcreate --snapshot -n$lv.bkp $SNAPSIZE $vg/$lv
291 mkdir -p $SNAPDIR/$lv
292 mount -oro /dev/$vg/$lv.bkp $SNAPDIR/$lv" || return $?
295 hostpath $SNAPDIR/$lv
301 ## Remove the snapshot. Sometimes LVM doesn't notice that the snapshot is
302 ## no longer in open immdiately, so try several times.
303 hostrun "unsnap-lvm $vg/$lv" "
307 if lvremove -f $vg/$lv.bkp; then rc=0; break; fi
310 exit $rc" || return $?
313 ## Complicated snapshot using LVM, where the volume group and filesystem are
314 ## owned by different machines, so they need to be synchronized during the
318 lvhost=$1 vg=$2 lv=$3 fshost=$4 fsdir=$5
320 ## Engage in the rfreezefs protocol with the filesystem host. This
321 ## involves some hairy plumbing. We want to get exit statuses out of both
324 ssh $fshost rfreezefs $fsdir | {
327 ## Read the codebook from the remote end.
333 TOKEN) eval tok_$2=$3 ;;
334 READY) ready=t; break ;;
336 echo >&2 "$quis: unexpected keyword $1 (rfreezefs to $rhost)"
343 echo >&2 "$quis: unexpected eof (rfreezefs to $rhost)"
348 ## Connect to the filesystem host's TCP port and get it to freeze its
350 exec 3<>/dev/tcp/$fshost/$port
356 echo >&2 "$quis: unexpected token $tok (rfreezefs $fsdir on $fshost)"
361 ## Get the volume host to create the snapshot.
363 _hostrun >&2 3>&- $userat$lvhost \
364 "lvcreate --snapshot -n$lv.bkp $SNAPSIZE $vg/$lv"
368 ## The filesystem can thaw now.
374 _hostrun >&2 3>&- $userat$lvhost "lvremove -f $vg/$lv.bkp" || :
375 echo >&2 "$quis: unexpected token $tok (rfreezefs $fsdir on $fshost)"
384 ## Sift through the wreckage to find out what happened.
385 rc_rfreezefs=${PIPESTATUS[0]} rc_snapshot=${PIPESTATUS[1]}
387 case $rc_rfreezefs:$rc_snapshot in
391 echo >&2 "$quis: EMERGENCY failed to thaw $fsdir on $fshost!"
395 echo >&2 "$quis: failed to snapshot $vg/$lv ($fsdir on $fshost)"
400 ## Mount the snapshot on the volume host.
401 _hostrun >&2 $userat$lvhost "
402 mkdir -p $SNAPDIR/$lv
403 mount -oro /dev/$vg/$lv.bkp $SNAPDIR/$lv"
407 rhost=$1 vg=$2 lv=$3 rfs=$4
410 run "snap-rfreezefs $host:$vg/$lv $rhost:$rfs" \
411 do_rfreezefs $host $vg $lv $rhost $rfs || return $?
412 hostpath $SNAPDIR/$lv
415 unsnap_rfreezefs () {
417 ## Unshapping is the same as for plain LVM.
418 rhost=$1 vg=$2 lv=$3 rfs=$4
422 ###--------------------------------------------------------------------------
423 ### Expiry computations.
426 ## Read dates on stdin; write to stdout `EXPIRE date' for dates which
427 ## should be expired and `RETAIN date' for dates which should be retained.
429 ## Get the current date and convert it into useful forms.
430 now=$(date +%Y-%m-%d)
432 now_jdn=$(julian $now) now_year=$year now_month=$month now_day=$day
435 ## Work through each date in the input.
439 ## Convert the date into a useful form.
443 ## Work through the policy list.
444 if [ $jdn -le $now_jdn ]; then
445 while read ival age; do
447 ## Decide whether the policy entry applies to this date.
454 if [ $year -eq $now_year ] ||
455 ([ $year -eq $(( $now_year - 1 )) ] &&
456 [ $month -ge $now_month ])
460 if ([ $month -eq $now_month ] && [ $year -eq $now_year ]) ||
461 ((([ $month -eq $(( $now_month - 1 )) ] &&
462 [ $year -eq $now_year ]) ||
463 ([ $month -eq 12 ] && [ $now_month -eq 1 ] &&
464 [ $year -eq $(( $now_year - 1 )) ])) &&
465 [ $day -ge $now_day ])
469 if [ $jdn -ge $(( $now_jdn - 7 )) ]; then apply=t; fi
472 echo >&2 "$quis: unknown age symbol \`$age'"
476 case $apply in nil) continue ;; esac
478 ## Find the interval marker for this date.
484 ydn=$(julian $year-01-01)
485 wk=$(( ($jdn - $ydn)/7 + 1 ))
495 echo >&2 "$quis: unknown interval symbol \`$ival'"
500 ## See if we've alredy retained something in this interval.
503 *) keep=t kept=$kept$marker: ;;
512 t) echo RETAIN $date ;;
513 *) echo EXPIRE $date ;;
519 ###--------------------------------------------------------------------------
520 ### Actually taking backups of filesystems.
529 _hostrun $userat$host "
533 echo \"*** $host $fs $date\"; echo
534 rsync -rx --filter='dir-merge .rsync-backup' ./ |
535 fshash -c$fshashdir/$fs.bkp -a -H$HASH -frsync
540 { echo "*** $host $fs $date"; echo
541 fshash -c$STOREDIR/fshash.cache -H$HASH new/
549 case $i in *[!-0-9]*) continue ;; esac
550 case $seen in *:"$i":*) continue ;; esac
555 while read op date; do
558 echo >&2 " --- keep $date"
561 echo >&2 " --- delete $date"
568 $verbose -n " expire $date..."
570 delete_index $host $fs $date
582 backup_precommit_hook () {
583 host=$1 fs=$2 date=$3
584 ## Compatibility: You can override this hook in the configuration file for
585 ## special effects; but it's better to use `addhook precommit'.
589 addhook precommit backup_precommit_hook
591 backup_commit_hook () {
592 host=$1 fs=$2 date=$3
593 ## Compatibility: You can override this hook in the configuration file for
594 ## special effects; but it's better to use `addhook commit'.
598 addhook commit backup_commit_hook
601 date=$1 fs=$2 fsarg=$3
602 ## Back up FS on the current host.
607 ## Run a hook beforehand.
608 set +e; runhook setup $host $fs $date; rc=$?; set -e
611 99) log "BACKUP of $host:$fs SKIPPED by hook"; return 0 ;;
612 *) log "BACKUP of $host:$fs FAILED (hook returns $?)"; return $? ;;
615 ## Report the start of this attempt.
616 log "START BACKUP of $host:$fs"
618 ## Maybe we need to retry the backup.
621 ## Create and mount the remote snapshot.
624 maybe snap_$snap $fs $fsarg
628 snapmnt=$(snap_$snap $snapargs $fs $fsarg) || return $?
631 $verbose " create snapshot"
633 ## Build the list of hardlink sources.
635 for i in $host $like; do
636 d=$STOREDIR/$i/$fs/last/
637 if [ -d $d ]; then linkdests="$linkdests --link-dest=$d"; fi
640 ## Copy files from the remote snapshot.
643 t) $verbose " running rsync" ;;
644 nil) $verbose -n " running rsync..." ;;
647 run "RSYNC of $host:$fs (snapshot on $snapmnt)" do_rsync \
653 case $dryrun in nil) $verbose " done" ;; esac
655 ## Collect a map of the snapshot for verification purposes.
658 t) $verbose " remote fshash" ;;
659 nil) $verbose -n " remote fshash..." ;;
661 run "@$host: fshash $fs" remote_fshash
664 case $dryrun in nil) $verbose " done" ;; esac
666 ## Remove the snapshot.
667 maybe unsnap_$snap $snapargs $fs $fsarg
668 $verbose " remove snapshot"
670 ## If we failed to copy, then give up.
671 case $rc_rsync:$rc_fshash in
673 0:*) return $rc_fshash ;;
674 *) return $rc_rsync ;;
677 ## Get a matching map of the files received.
678 maybe mkdir -m750 -p $STOREDIR/tmp/
679 localmap=$STOREDIR/tmp/fshash.$host.$fs.$date
681 t) $verbose " local fshash" ;;
682 nil) $verbose -n " local fshash..." ;;
684 run "local fshash $host:$fs" local_fshash || return $?
685 case $dryrun in nil) $verbose " done" ;; esac
687 ## Compare the two maps.
689 run "compare fshash maps for $host:$fs" diff -u new.fshash $localmap
697 if [ $attempt -ge $retry ]; then return $rc; fi
698 $verbose " fshash mismatch; retrying"
699 attempt=$(( $attempt + 1 ))
708 maybe rm -f $localmap
709 $verbose " fshash match"
711 ## Commit this backup.
714 runhook precommit $host $fs $date
716 mv new.fshash $date.fshash
717 insert_index $host $fs $date $VOLUME
718 runhook commit $host $fs $date
720 ln -s $date hack/last
727 ## Expire old backups.
728 case "${expire_policy+t},${default_policy+t}" in
729 ,t) expire_policy=$default_policy ;;
731 case "${expire_policy+t},$dryrun" in
732 t,nil) run "expiry for $host:$fs" expire_backups ;;
733 t,t) expire_backups ;;
739 t) log "END BACKUP of $host:$fs" ;;
740 nil) log "SUCCESSFUL BACKUP of $host:$fs" ;;
745 fs=$1 date=$2 cmd=$3; shift 3
746 ## try_backup FS DATE COMMAND ARGS ...
748 ## Run COMMAND ARGS to back up filesystem FS on the current host,
749 ## maintaining a log, and checking whether it worked. The caller has
750 ## usually worked out the DATE in order to set up the filesystem, and we
751 ## need it to name the log file properly.
753 ## Find a name for the log file. In unusual circumstances, we may have
754 ## deleted old logs from today, so just checking for an unused sequence
755 ## number is insufficient. Instead, check all of the logfiles for today,
756 ## and use a sequence number that's larger than any of them.
763 for i in "$logdir/$host/$fs.$date#"*; do
765 case "$tail" in [!1-9]* | *[!0-9]*) continue ;; esac
766 if [ -f "$i" -a $tail -ge $seq ]; then seq=$(( tail + 1 )); fi
768 log="$logdir/$host/$fs.$date#$seq"
772 ## Run the backup command.
773 case $dryrun in nil) mkdir -p $logdir/$host ;; esac
774 if ! "$cmd" "$@" 9>$log 1>&9; then
776 echo >&2 "$quis: backup of $host:$fs FAILED!"
780 ## Clear away any old logfiles.
781 remove_old_logfiles "$logdir/$host/$fs"
785 ## backup FS[:ARG] ...
787 ## Back up the filesystems on the currently selected host using the
788 ## currently selected snapshot type.
790 ## Make sure that there's a store volume. We must do this here rather than
791 ## in the main body of the script, since the configuration file needs a
792 ## chance to override STOREDIR.
793 if ! [ -r $STOREDIR/.rsync-backup-store ]; then
794 echo >&2 "$quis: no backup volume mounted"
798 ## Read the volume name if we don't have one already. Again, this allows
799 ## the configuration file to provide a volume name.
800 case "${VOLUME+t}${VOLUME-nil}" in
801 nil) VOLUME=$(cat $METADIR/volume) ;;
804 ## Back up each requested file system in turn.
807 ## Parse the argument.
809 *:*) fsarg=${fs#*:} fs=${fs%%:*} ;;
812 $verbose " filesystem $fs"
814 ## Move to the store directory and set up somewhere to put this backup.
818 if [ ! -d $host ]; then
820 chown root:root $host
822 if [ ! -d $host/$fs ]; then
823 mkdir -m750 $host/$fs
824 chown root:backup $host/$fs
830 ## Find out if we've already copied this filesystem today.
831 date=$(date +%Y-%m-%d)
832 if [ $dryrun = nil ] && [ -d $date ]; then
833 $verbose " already dumped"
837 ## Do the backup of this filesystem.
838 run_backup_cmd $fs $date do_backup $date $fs $fsarg
842 ###--------------------------------------------------------------------------
843 ### Configuration functions.
848 done_first_host_p=nil
853 case $done_first_host_p in
854 nil) runhook start; done_first_host_p=t ;;
856 case "${expire_policy+t},${default_policy+t}" in
857 t,) default_policy=$expire_policy ;;
860 $verbose "host $host"
863 snaptype () { snap=$1; shift; snapargs="$*"; retry=0; }
864 rsyncargs () { rsyncargs="$*"; }
865 like () { like="$*"; }
866 retry () { retry="$*"; }
867 user () { userat="$*@"; }
870 case $clear_policy in t) unset expire_policy; clear_policy=nil ;; esac
871 expire_policy="${expire_policy+$expire_policy
875 ###--------------------------------------------------------------------------
876 ### Read the configuration and we're done.
879 echo "usage: $quis [-nv] [-c CONF]"
883 echo "$quis version $VERSION"
886 whine () { echo >&8 "$@"; }
888 while getopts "hVvc:n" opt; do
891 V) version; config; exit 0 ;;
898 shift $((OPTIND - 1))
899 case $# in 0) ;; *) usage >&2; exit 1 ;; esac
906 0) $verbose "All backups successful" ;;
907 *) $verbose "Backups FAILED" ;;
910 ###----- That's all, folks --------------------------------------------------