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"
86 tag=$1 cmd=$2; shift 2
87 ## Run CMD, logging its output in a pleasing manner.
91 echo >&2 " *** RUN $tag"
92 echo >&2 " +++ $cmd $*"
99 "$cmd" "$@" 3>&- 4>&- 5>&- 9>&-
101 copy "|" >&4; } 2>&1 |
102 copy "*" >&4; } 4>&1 |
103 cat >&9; } 5>&1 </dev/null
107 *) log "FAIL $tag (rc = $rc)" ;;
116 ## Answer whether H is a local host.
119 "$thishost") return 0 ;;
126 ## Run CMD on the current host. If the host seems local then run the
127 ## command through a local shell; otherwise run it through ssh(1). Either
128 ## way it will be processed by a shell.
130 if localp $host; then run "@$host: $tag" sh -c "$cmd"
131 else run "@$host: $tag" ssh $userat$host "$cmd"
137 ## Like hostrun, but without the complicated logging, and targetted at a
140 if localp $h; then sh -c "$cmd"
147 ## Output (to stdout) either PATH or HOST:PATH, choosing the former if the
148 ## current host is local.
150 if localp $host; then echo $path
151 else echo $userat$host:$path
157 ## Define a hook called HOOK.
164 ## Add command CMD to the hook HOOK.
166 eval old=\$hk_$hook; new="$old $cmd"
172 ## Invoke HOOK, passing it the remaining arguments.
176 if ! $cmd "$@"; then return $?; fi
180 remove_old_logfiles () {
182 ## Remove old logfiles with names of the form BASE.DATE#N, so that there
183 ## are at most $MAXLOG of them.
185 ## Count up the logfiles.
187 for i in "$base".*; do
188 if [ ! -f "$i" ]; then continue; fi
192 ## If there are too many, go through and delete some early ones.
193 if [ $dryrun = nil ] && [ $nlog -gt $MAXLOG ]; then
194 n=$(( nlog - MAXLOG ))
195 for i in "$base".*; do
196 if [ ! -f "$i" ]; then continue; fi
199 if [ $n -eq 0 ]; then break; fi
204 ###--------------------------------------------------------------------------
205 ### Database operations.
208 host=$1 fs=$2 date=$3 vol=$4
210 if [ -f "$INDEXDB" ]; then
211 sqlite3 "$INDEXDB" <<EOF
212 INSERT INTO idx (host, fs, date, vol)
213 VALUES ('$host', '$fs', '$date', '$vol');
219 host=$1 fs=$2 date=$3
221 if [ -f "$INDEXDB" ]; then
222 sqlite3 "$INDEXDB" <<EOF
223 DELETE FROM idx WHERE
224 host = '$host' AND fs = '$fs' AND date = '$date';
229 ###--------------------------------------------------------------------------
230 ### Snapshot handling.
232 ## Snapshot protocol. Each snapshot type has a pair of functions snap_TYPE
233 ## and unsnap_TYPE. Each is given the current snapshot arguments and the
234 ## filesystem name to back up. The snap_TYPE function should create and
235 ## mount the snapshot and output an rsync(1) path to where the filesystem can
236 ## be copied; the unsnap_TYPE function should unmount and tear down the
239 ## Fake snapshot by not doing anything. Use only if you have no choice.
240 snap_live () { hostpath "$2"; }
241 unsnap_live () { :; }
243 ## Fake snapshot by remounting a live filesystem read-only. Useful if the
244 ## underlying storage isn't in LVM.
249 ## Place a marker in the filesystem so we know why it was made readonly.
250 ## (Also this serves to ensure that the filesystem was writable before.)
251 hostrun "snap-ro $mnt" "
252 echo rsync-backup >$mnt/.lock
253 mount -oremount,ro $mnt" || return $?
262 ## Check that the filesystem still has our lock marker.
263 hostrun "unsnap-ro $mnt" "
264 case \$(cat $mnt/.lock) in
266 *) echo unlocked by someone else; exit 31 ;;
268 mount -oremount,rw $mnt
269 rm $mnt/.lock" || return $?
272 ## Snapshot using LVM.
274 SNAPSIZE="-l10%ORIGIN"
279 ## Make the snapshot.
280 hostrun "snap-lvm $vg/$lv" "
281 lvcreate --snapshot -n$lv.bkp $SNAPSIZE $vg/$lv
282 mkdir -p $SNAPDIR/$lv
283 mount -oro /dev/$vg/$lv.bkp $SNAPDIR/$lv" || return $?
286 hostpath $SNAPDIR/$lv
292 ## Remove the snapshot. Sometimes LVM doesn't notice that the snapshot is
293 ## no longer in open immdiately, so try several times.
294 hostrun "unsnap-lvm $vg/$lv" "
298 if lvremove -f $vg/$lv.bkp; then rc=0; break; fi
301 exit $rc" || return $?
304 ## Complicated snapshot using LVM, where the volume group and filesystem are
305 ## owned by different machines, so they need to be synchronized during the
309 lvhost=$1 vg=$2 lv=$3 fshost=$4 fsdir=$5
311 ## Engage in the rfreezefs protocol with the filesystem host. This
312 ## involves some hairy plumbing. We want to get exit statuses out of both
315 ssh $fshost rfreezefs $fsdir | {
318 ## Read the codebook from the remote end.
324 TOKEN) eval tok_$2=$3 ;;
325 READY) ready=t; break ;;
327 echo >&2 "$quis: unexpected keyword $1 (rfreezefs to $rhost)"
334 echo >&2 "$quis: unexpected eof (rfreezefs to $rhost)"
339 ## Connect to the filesystem host's TCP port and get it to freeze its
341 exec 3<>/dev/tcp/$fshost/$port
347 echo >&2 "$quis: unexpected token $tok (rfreezefs $fsdir on $fshost)"
352 ## Get the volume host to create the snapshot.
354 _hostrun >&2 3>&- $userat$lvhost \
355 "lvcreate --snapshot -n$lv.bkp $SNAPSIZE $vg/$lv"
359 ## The filesystem can thaw now.
365 _hostrun >&2 3>&- $userat$lvhost "lvremove -f $vg/$lv.bkp" || :
366 echo >&2 "$quis: unexpected token $tok (rfreezefs $fsdir on $fshost)"
375 ## Sift through the wreckage to find out what happened.
376 rc_rfreezefs=${PIPESTATUS[0]} rc_snapshot=${PIPESTATUS[1]}
378 case $rc_rfreezefs:$rc_snapshot in
382 echo >&2 "$quis: EMERGENCY failed to thaw $fsdir on $fshost!"
386 echo >&2 "$quis: failed to snapshot $vg/$lv ($fsdir on $fshost)"
391 ## Mount the snapshot on the volume host.
392 _hostrun >&2 $userat$lvhost "
393 mkdir -p $SNAPDIR/$lv
394 mount -oro /dev/$vg/$lv.bkp $SNAPDIR/$lv"
398 rhost=$1 vg=$2 lv=$3 rfs=$4
401 run "snap-rfreezefs $host:$vg/$lv $rhost:$rfs" \
402 do_rfreezefs $host $vg $lv $rhost $rfs || return $?
403 hostpath $SNAPDIR/$lv
406 unsnap_rfreezefs () {
408 ## Unshapping is the same as for plain LVM.
409 rhost=$1 vg=$2 lv=$3 rfs=$4
413 ###--------------------------------------------------------------------------
414 ### Expiry computations.
417 ## Read dates on stdin; write to stdout `EXPIRE date' for dates which
418 ## should be expired and `RETAIN date' for dates which should be retained.
420 ## Get the current date and convert it into useful forms.
421 now=$(date +%Y-%m-%d)
423 now_jdn=$(julian $now) now_year=$year now_month=$month now_day=$day
426 ## Work through each date in the input.
430 ## Convert the date into a useful form.
434 ## Work through the policy list.
435 if [ $jdn -le $now_jdn ]; then
436 while read ival age; do
438 ## Decide whether the policy entry applies to this date.
445 if [ $year -eq $now_year ] ||
446 ([ $year -eq $(( $now_year - 1 )) ] &&
447 [ $month -ge $now_month ])
451 if ([ $month -eq $now_month ] && [ $year -eq $now_year ]) ||
452 ((([ $month -eq $(( $now_month - 1 )) ] &&
453 [ $year -eq $now_year ]) ||
454 ([ $month -eq 12 ] && [ $now_month -eq 1 ] &&
455 [ $year -eq $(( $now_year - 1 )) ])) &&
456 [ $day -ge $now_day ])
460 if [ $jdn -ge $(( $now_jdn - 7 )) ]; then apply=t; fi
463 echo >&2 "$quis: unknown age symbol \`$age'"
467 case $apply in nil) continue ;; esac
469 ## Find the interval marker for this date.
475 ydn=$(julian $year-01-01)
476 wk=$(( ($jdn - $ydn)/7 + 1 ))
486 echo >&2 "$quis: unknown interval symbol \`$ival'"
491 ## See if we've alredy retained something in this interval.
494 *) keep=t kept=$kept$marker: ;;
503 t) echo RETAIN $date ;;
504 *) echo EXPIRE $date ;;
510 ###--------------------------------------------------------------------------
511 ### Actually taking backups of filesystems.
520 _hostrun $userat$host "
524 echo \"*** $host $fs $date\"; echo
525 rsync -rx --filter='dir-merge .rsync-backup' ./ |
526 fshash -c$fshashdir/$fs.bkp -a -H$HASH -frsync
531 { echo "*** $host $fs $date"; echo
532 fshash -c$STOREDIR/fshash.cache -H$HASH new/
540 case $i in *[!-0-9]*) continue ;; esac
541 case $seen in *:"$i":*) continue ;; esac
546 while read op date; do
549 echo >&2 " --- keep $date"
552 echo >&2 " --- delete $date"
559 $verbose -n " expire $date..."
561 delete_index $host $fs $date
573 backup_precommit_hook () {
574 host=$1 fs=$2 date=$3
575 ## Compatibility: You can override this hook in the configuration file for
576 ## special effects; but it's better to use `addhook precommit'.
580 addhook precommit backup_precommit_hook
582 backup_commit_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 commit'.
589 addhook commit backup_commit_hook
592 date=$1 fs=$2 fsarg=$3
593 ## Back up FS on the current host.
598 ## Run a hook beforehand.
599 set +e; runhook setup $host $fs $date; rc=$?; set -e
602 99) log "BACKUP of $host:$fs SKIPPED by hook"; return 0 ;;
603 *) log "BACKUP of $host:$fs FAILED (hook returns $?)"; return $? ;;
606 ## Report the start of this attempt.
607 log "START BACKUP of $host:$fs"
609 ## Maybe we need to retry the backup.
612 ## Create and mount the remote snapshot.
615 maybe snap_$snap $fs $fsarg
619 snapmnt=$(snap_$snap $snapargs $fs $fsarg) || return $?
622 $verbose " create snapshot"
624 ## Build the list of hardlink sources.
626 for i in $host $like; do
627 d=$STOREDIR/$i/$fs/last/
628 if [ -d $d ]; then linkdests="$linkdests --link-dest=$d"; fi
631 ## Copy files from the remote snapshot.
634 t) $verbose " running rsync" ;;
635 nil) $verbose -n " running rsync..." ;;
638 run "RSYNC of $host:$fs (snapshot on $snapmnt)" do_rsync \
644 case $dryrun in nil) $verbose " done" ;; esac
646 ## Collect a map of the snapshot for verification purposes.
649 t) $verbose " remote fshash" ;;
650 nil) $verbose -n " remote fshash..." ;;
652 run "@$host: fshash $fs" remote_fshash
655 case $dryrun in nil) $verbose " done" ;; esac
657 ## Remove the snapshot.
658 maybe unsnap_$snap $snapargs $fs $fsarg
659 $verbose " remove snapshot"
661 ## If we failed to copy, then give up.
662 case $rc_rsync:$rc_fshash in
664 0:*) return $rc_fshash ;;
665 *) return $rc_rsync ;;
668 ## Get a matching map of the files received.
669 maybe mkdir -m750 -p $STOREDIR/tmp/
670 localmap=$STOREDIR/tmp/fshash.$host.$fs.$date
672 t) $verbose " local fshash" ;;
673 nil) $verbose -n " local fshash..." ;;
675 run "local fshash $host:$fs" local_fshash || return $?
676 case $dryrun in nil) $verbose " done" ;; esac
678 ## Compare the two maps.
680 run "compare fshash maps for $host:$fs" diff -u new.fshash $localmap
688 if [ $attempt -ge $retry ]; then return $rc; fi
689 $verbose " fshash mismatch; retrying"
690 attempt=$(( $attempt + 1 ))
699 maybe rm -f $localmap
700 $verbose " fshash match"
702 ## Commit this backup.
705 runhook precommit $host $fs $date
707 mv new.fshash $date.fshash
708 insert_index $host $fs $date $VOLUME
709 runhook commit $host $fs $date
711 ln -s $date hack/last
718 ## Expire old backups.
719 case "${expire_policy+t},${default_policy+t}" in
720 ,t) expire_policy=$default_policy ;;
722 case "${expire_policy+t},$dryrun" in
723 t,nil) run "expiry for $host:$fs" expire_backups ;;
724 t,t) expire_backups ;;
730 t) log "END BACKUP of $host:$fs" ;;
731 nil) log "SUCCESSFUL BACKUP of $host:$fs" ;;
736 fs=$1 date=$2 cmd=$3; shift 3
737 ## try_backup FS DATE COMMAND ARGS ...
739 ## Run COMMAND ARGS to back up filesystem FS on the current host,
740 ## maintaining a log, and checking whether it worked. The caller has
741 ## usually worked out the DATE in order to set up the filesystem, and we
742 ## need it to name the log file properly.
744 ## Find a name for the log file. In unusual circumstances, we may have
745 ## deleted old logs from today, so just checking for an unused sequence
746 ## number is insufficient. Instead, check all of the logfiles for today,
747 ## and use a sequence number that's larger than any of them.
754 for i in "$logdir/$host/$fs.$date#"*; do
756 case "$tail" in [!1-9]* | *[!0-9]*) continue ;; esac
757 if [ -f "$i" -a $tail -ge $seq ]; then seq=$(( tail + 1 )); fi
759 log="$logdir/$host/$fs.$date#$seq"
763 ## Run the backup command.
764 case $dryrun in nil) mkdir -p $logdir/$host ;; esac
765 if ! "$cmd" "$@" 9>$log 1>&9; then
767 echo >&2 "$quis: backup of $host:$fs FAILED!"
771 ## Clear away any old logfiles.
772 remove_old_logfiles "$logdir/$host/$fs"
776 ## backup FS[:ARG] ...
778 ## Back up the filesystems on the currently selected host using the
779 ## currently selected snapshot type.
781 ## Make sure that there's a store volume. We must do this here rather than
782 ## in the main body of the script, since the configuration file needs a
783 ## chance to override STOREDIR.
784 if ! [ -r $STOREDIR/.rsync-backup-store ]; then
785 echo >&2 "$quis: no backup volume mounted"
789 ## Read the volume name if we don't have one already. Again, this allows
790 ## the configuration file to provide a volume name.
791 case "${VOLUME+t}${VOLUME-nil}" in
792 nil) VOLUME=$(cat $METADIR/volume) ;;
795 ## Back up each requested file system in turn.
798 ## Parse the argument.
800 *:*) fsarg=${fs#*:} fs=${fs%%:*} ;;
803 $verbose " filesystem $fs"
805 ## Move to the store directory and set up somewhere to put this backup.
809 if [ ! -d $host ]; then
811 chown root:root $host
813 if [ ! -d $host/$fs ]; then
814 mkdir -m750 $host/$fs
815 chown root:backup $host/$fs
821 ## Find out if we've already copied this filesystem today.
822 date=$(date +%Y-%m-%d)
823 if [ $dryrun = nil ] && [ -d $date ]; then
824 $verbose " already dumped"
828 ## Do the backup of this filesystem.
829 run_backup_cmd $fs $date do_backup $date $fs $fsarg
833 ###--------------------------------------------------------------------------
834 ### Configuration functions.
839 done_first_host_p=nil
844 case $done_first_host_p in
845 nil) runhook start; done_first_host_p=t ;;
847 case "${expire_policy+t},${default_policy+t}" in
848 t,) default_policy=$expire_policy ;;
851 $verbose "host $host"
854 snaptype () { snap=$1; shift; snapargs="$*"; retry=0; }
855 rsyncargs () { rsyncargs="$*"; }
856 like () { like="$*"; }
857 retry () { retry="$*"; }
858 user () { userat="$*@"; }
861 case $clear_policy in t) unset expire_policy; clear_policy=nil ;; esac
862 expire_policy="${expire_policy+$expire_policy
866 ###--------------------------------------------------------------------------
867 ### Read the configuration and we're done.
870 echo "usage: $quis [-nv] [-c CONF]"
874 echo "$quis version $VERSION"
877 whine () { echo >&8 "$@"; }
879 while getopts "hVvc:n" opt; do
882 V) version; config; exit 0 ;;
889 shift $((OPTIND - 1))
890 case $# in 0) ;; *) usage >&2; exit 1 ;; esac
897 0) $verbose "All backups successful" ;;
898 *) $verbose "Backups FAILED" ;;
901 ###----- That's all, folks --------------------------------------------------