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 ###--------------------------------------------------------------------------
181 ### Database operations.
184 host=$1 fs=$2 date=$3 vol=$4
186 if [ -f "$INDEXDB" ]; then
187 sqlite3 "$INDEXDB" <<EOF
188 INSERT INTO idx (host, fs, date, vol)
189 VALUES ('$host', '$fs', '$date', '$vol');
195 host=$1 fs=$2 date=$3
197 if [ -f "$INDEXDB" ]; then
198 sqlite3 "$INDEXDB" <<EOF
199 DELETE FROM idx WHERE
200 host = '$host' AND fs = '$fs' AND date = '$date';
205 ###--------------------------------------------------------------------------
206 ### Snapshot handling.
208 ## Snapshot protocol. Each snapshot type has a pair of functions snap_TYPE
209 ## and unsnap_TYPE. Each is given the current snapshot arguments and the
210 ## filesystem name to back up. The snap_TYPE function should create and
211 ## mount the snapshot and output an rsync(1) path to where the filesystem can
212 ## be copied; the unsnap_TYPE function should unmount and tear down the
215 ## Fake snapshot by not doing anything. Use only if you have no choice.
216 snap_live () { hostpath "$2"; }
217 unsnap_live () { :; }
219 ## Fake snapshot by remounting a live filesystem read-only. Useful if the
220 ## underlying storage isn't in LVM.
225 ## Place a marker in the filesystem so we know why it was made readonly.
226 ## (Also this serves to ensure that the filesystem was writable before.)
227 hostrun "snap-ro $mnt" "
228 echo rsync-backup >$mnt/.lock
229 mount -oremount,ro $mnt" || return $?
238 ## Check that the filesystem still has our lock marker.
239 hostrun "unsnap-ro $mnt" "
240 case \$(cat $mnt/.lock) in
242 *) echo unlocked by someone else; exit 31 ;;
244 mount -oremount,rw $mnt
245 rm $mnt/.lock" || return $?
248 ## Snapshot using LVM.
250 SNAPSIZE="-l10%ORIGIN"
255 ## Make the snapshot.
256 hostrun "snap-lvm $vg/$lv" "
257 lvcreate --snapshot -n$lv.bkp $SNAPSIZE $vg/$lv
258 mkdir -p $SNAPDIR/$lv
259 mount -oro /dev/$vg/$lv.bkp $SNAPDIR/$lv" || return $?
262 hostpath $SNAPDIR/$lv
268 ## Remove the snapshot. Sometimes LVM doesn't notice that the snapshot is
269 ## no longer in open immdiately, so try several times.
270 hostrun "unsnap-lvm $vg/$lv" "
274 if lvremove -f $vg/$lv.bkp; then rc=0; break; fi
277 exit $rc" || return $?
280 ## Complicated snapshot using LVM, where the volume group and filesystem are
281 ## owned by different machines, so they need to be synchronized during the
285 lvhost=$1 vg=$2 lv=$3 fshost=$4 fsdir=$5
287 ## Engage in the rfreezefs protocol with the filesystem host. This
288 ## involves some hairy plumbing. We want to get exit statuses out of both
291 ssh $fshost rfreezefs $fsdir | {
294 ## Read the codebook from the remote end.
300 TOKEN) eval tok_$2=$3 ;;
301 READY) ready=t; break ;;
303 echo >&2 "$quis: unexpected keyword $1 (rfreezefs to $rhost)"
310 echo >&2 "$quis: unexpected eof (rfreezefs to $rhost)"
315 ## Connect to the filesystem host's TCP port and get it to freeze its
317 exec 3<>/dev/tcp/$fshost/$port
323 echo >&2 "$quis: unexpected token $tok (rfreezefs $fsdir on $fshost)"
328 ## Get the volume host to create the snapshot.
330 _hostrun >&2 3>&- $userat$lvhost \
331 "lvcreate --snapshot -n$lv.bkp $SNAPSIZE $vg/$lv"
335 ## The filesystem can thaw now.
341 _hostrun >&2 3>&- $userat$lvhost "lvremove -f $vg/$lv.bkp" || :
342 echo >&2 "$quis: unexpected token $tok (rfreezefs $fsdir on $fshost)"
351 ## Sift through the wreckage to find out what happened.
352 rc_rfreezefs=${PIPESTATUS[0]} rc_snapshot=${PIPESTATUS[1]}
354 case $rc_rfreezefs:$rc_snapshot in
358 echo >&2 "$quis: EMERGENCY failed to thaw $fsdir on $fshost!"
362 echo >&2 "$quis: failed to snapshot $vg/$lv ($fsdir on $fshost)"
367 ## Mount the snapshot on the volume host.
368 _hostrun >&2 $userat$lvhost "
369 mkdir -p $SNAPDIR/$lv
370 mount -oro /dev/$vg/$lv.bkp $SNAPDIR/$lv"
374 rhost=$1 vg=$2 lv=$3 rfs=$4
377 run "snap-rfreezefs $host:$vg/$lv $rhost:$rfs" \
378 do_rfreezefs $host $vg $lv $rhost $rfs || return $?
379 hostpath $SNAPDIR/$lv
382 unsnap_rfreezefs () {
384 ## Unshapping is the same as for plain LVM.
385 rhost=$1 vg=$2 lv=$3 rfs=$4
389 ###--------------------------------------------------------------------------
390 ### Expiry computations.
393 ## Read dates on stdin; write to stdout `EXPIRE date' for dates which
394 ## should be expired and `RETAIN date' for dates which should be retained.
396 ## Get the current date and convert it into useful forms.
397 now=$(date +%Y-%m-%d)
399 now_jdn=$(julian $now) now_year=$year now_month=$month now_day=$day
402 ## Work through each date in the input.
406 ## Convert the date into a useful form.
410 ## Work through the policy list.
411 if [ $jdn -le $now_jdn ]; then
412 while read ival age; do
414 ## Decide whether the policy entry applies to this date.
421 if [ $year -eq $now_year ] ||
422 ([ $year -eq $(( $now_year - 1 )) ] &&
423 [ $month -ge $now_month ])
427 if ([ $month -eq $now_month ] && [ $year -eq $now_year ]) ||
428 ((([ $month -eq $(( $now_month - 1 )) ] &&
429 [ $year -eq $now_year ]) ||
430 ([ $month -eq 12 ] && [ $now_month -eq 1 ] &&
431 [ $year -eq $(( $now_year - 1 )) ])) &&
432 [ $day -ge $now_day ])
436 if [ $jdn -ge $(( $now_jdn - 7 )) ]; then apply=t; fi
439 echo >&2 "$quis: unknown age symbol \`$age'"
443 case $apply in nil) continue ;; esac
445 ## Find the interval marker for this date.
451 ydn=$(julian $year-01-01)
452 wk=$(( ($jdn - $ydn)/7 + 1 ))
462 echo >&2 "$quis: unknown interval symbol \`$ival'"
467 ## See if we've alredy retained something in this interval.
470 *) keep=t kept=$kept$marker: ;;
479 t) echo RETAIN $date ;;
480 *) echo EXPIRE $date ;;
486 ###--------------------------------------------------------------------------
487 ### Actually taking backups of filesystems.
496 _hostrun $userat$host "
500 echo \"*** $host $fs $date\"; echo
501 rsync -rx --filter='dir-merge .rsync-backup' ./ |
502 fshash -c$fshashdir/$fs.bkp -a -H$HASH -frsync
507 { echo "*** $host $fs $date"; echo
508 fshash -c$STOREDIR/fshash.cache -H$HASH new/
516 case $i in *[!-0-9]*) continue ;; esac
517 case $seen in *:"$i":*) continue ;; esac
522 while read op date; do
525 echo >&2 " --- keep $date"
528 echo >&2 " --- delete $date"
535 $verbose -n " expire $date..."
537 delete_index $host $fs $date
549 backup_precommit_hook () {
550 host=$1 fs=$2 date=$3
551 ## Compatibility: You can override this hook in the configuration file for
552 ## special effects; but it's better to use `addhook precommit'.
556 addhook precommit backup_precommit_hook
558 backup_commit_hook () {
559 host=$1 fs=$2 date=$3
560 ## Compatibility: You can override this hook in the configuration file for
561 ## special effects; but it's better to use `addhook commit'.
565 addhook commit backup_commit_hook
568 date=$1 fs=$2 fsarg=$3
569 ## Back up FS on the current host.
574 ## Run a hook beforehand.
575 set +e; runhook setup $host $fs $date; rc=$?; set -e
578 99) log "BACKUP of $host:$fs SKIPPED by hook"; return 0 ;;
579 *) log "BACKUP of $host:$fs FAILED (hook returns $?)"; return $? ;;
582 ## Report the start of this attempt.
583 log "START BACKUP of $host:$fs"
585 ## Maybe we need to retry the backup.
588 ## Create and mount the remote snapshot.
591 maybe snap_$snap $fs $fsarg
595 snapmnt=$(snap_$snap $snapargs $fs $fsarg) || return $?
598 $verbose " create snapshot"
600 ## Build the list of hardlink sources.
602 for i in $host $like; do
603 d=$STOREDIR/$i/$fs/last/
604 if [ -d $d ]; then linkdests="$linkdests --link-dest=$d"; fi
607 ## Copy files from the remote snapshot.
610 t) $verbose " running rsync" ;;
611 nil) $verbose -n " running rsync..." ;;
614 run "RSYNC of $host:$fs (snapshot on $snapmnt)" do_rsync \
620 case $dryrun in nil) $verbose " done" ;; esac
622 ## Collect a map of the snapshot for verification purposes.
625 t) $verbose " remote fshash" ;;
626 nil) $verbose -n " remote fshash..." ;;
628 run "@$host: fshash $fs" remote_fshash
631 case $dryrun in nil) $verbose " done" ;; esac
633 ## Remove the snapshot.
634 maybe unsnap_$snap $snapargs $fs $fsarg
635 $verbose " remove snapshot"
637 ## If we failed to copy, then give up.
638 case $rc_rsync:$rc_fshash in
640 0:*) return $rc_fshash ;;
641 *) return $rc_rsync ;;
644 ## Get a matching map of the files received.
645 maybe mkdir -m750 -p $STOREDIR/tmp/
646 localmap=$STOREDIR/tmp/fshash.$host.$fs.$date
648 t) $verbose " local fshash" ;;
649 nil) $verbose -n " local fshash..." ;;
651 run "local fshash $host:$fs" local_fshash || return $?
652 case $dryrun in nil) $verbose " done" ;; esac
654 ## Compare the two maps.
656 run "compare fshash maps for $host:$fs" diff -u new.fshash $localmap
664 if [ $attempt -ge $retry ]; then return $rc; fi
665 $verbose " fshash mismatch; retrying"
666 attempt=$(( $attempt + 1 ))
675 maybe rm -f $localmap
676 $verbose " fshash match"
678 ## Commit this backup.
681 runhook precommit $host $fs $date
683 mv new.fshash $date.fshash
684 insert_index $host $fs $date $VOLUME
685 runhook commit $host $fs $date
687 ln -s $date hack/last
694 ## Expire old backups.
695 case "${expire_policy+t},${default_policy+t}" in
696 ,t) expire_policy=$default_policy ;;
698 case "${expire_policy+t},$dryrun" in
699 t,nil) run "expiry for $host:$fs" expire_backups ;;
700 t,t) expire_backups ;;
706 t) log "END BACKUP of $host:$fs" ;;
707 nil) log "SUCCESSFUL BACKUP of $host:$fs" ;;
712 fs=$1 date=$2 cmd=$3; shift 3
713 ## try_backup FS DATE COMMAND ARGS ...
715 ## Run COMMAND ARGS to back up filesystem FS on the current host,
716 ## maintaining a log, and checking whether it worked. The caller has
717 ## usually worked out the DATE in order to set up the filesystem, and we
718 ## need it to name the log file properly.
720 ## Find a name for the log file. In unusual circumstances, we may have
721 ## deleted old logs from today, so just checking for an unused sequence
722 ## number is insufficient. Instead, check all of the logfiles for today,
723 ## and use a sequence number that's larger than any of them.
730 for i in "$logdir/$host/$fs.$date#"*; do
732 case "$tail" in [!1-9]* | *[!0-9]*) continue ;; esac
733 if [ -f "$i" -a $tail -ge $seq ]; then seq=$(( tail + 1 )); fi
735 log="$logdir/$host/$fs.$date#$seq"
739 ## Run the backup command.
740 case $dryrun in nil) mkdir -p $logdir/$host ;; esac
741 if ! "$cmd" "$@" 9>$log 1>&9; then
743 echo >&2 "$quis: backup of $host:$fs FAILED!"
747 ## Count up the logfiles.
749 for i in "$logdir/$host/$fs".*; do
750 if [ ! -f "$i" ]; then continue; fi
754 ## If there are too many, go through and delete some early ones.
755 if [ $dryrun = nil ] && [ $nlog -gt $MAXLOG ]; then
756 n=$(( nlog - MAXLOG ))
757 for i in "$logdir/$host/$fs".*; do
758 if [ ! -f "$i" ]; then continue; fi
761 if [ $n -eq 0 ]; then break; fi
767 ## backup FS[:ARG] ...
769 ## Back up the filesystems on the currently selected host using the
770 ## currently selected snapshot type.
772 ## Make sure that there's a store volume. We must do this here rather than
773 ## in the main body of the script, since the configuration file needs a
774 ## chance to override STOREDIR.
775 if ! [ -r $STOREDIR/.rsync-backup-store ]; then
776 echo >&2 "$quis: no backup volume mounted"
780 ## Read the volume name if we don't have one already. Again, this allows
781 ## the configuration file to provide a volume name.
782 case "${VOLUME+t}${VOLUME-nil}" in
783 nil) VOLUME=$(cat $METADIR/volume) ;;
786 ## Back up each requested file system in turn.
789 ## Parse the argument.
791 *:*) fsarg=${fs#*:} fs=${fs%%:*} ;;
794 $verbose " filesystem $fs"
796 ## Move to the store directory and set up somewhere to put this backup.
800 if [ ! -d $host ]; then
802 chown root:root $host
804 if [ ! -d $host/$fs ]; then
805 mkdir -m750 $host/$fs
806 chown root:backup $host/$fs
812 ## Find out if we've already copied this filesystem today.
813 date=$(date +%Y-%m-%d)
814 if [ $dryrun = nil ] && [ -d $date ]; then
815 $verbose " already dumped"
819 ## Do the backup of this filesystem.
820 run_backup_cmd $fs $date do_backup $date $fs $fsarg
824 ###--------------------------------------------------------------------------
825 ### Configuration functions.
830 done_first_host_p=nil
835 case $done_first_host_p in
836 nil) runhook start; done_first_host_p=t ;;
838 case "${expire_policy+t},${default_policy+t}" in
839 t,) default_policy=$expire_policy ;;
842 $verbose "host $host"
845 snaptype () { snap=$1; shift; snapargs="$*"; retry=0; }
846 rsyncargs () { rsyncargs="$*"; }
847 like () { like="$*"; }
848 retry () { retry="$*"; }
849 user () { userat="$*@"; }
852 case $clear_policy in t) unset expire_policy; clear_policy=nil ;; esac
853 expire_policy="${expire_policy+$expire_policy
857 ###--------------------------------------------------------------------------
858 ### Read the configuration and we're done.
861 echo "usage: $quis [-nv] [-c CONF]"
865 echo "$quis version $VERSION"
868 whine () { echo >&8 "$@"; }
870 while getopts "hVvc:n" opt; do
873 V) version; config; exit 0 ;;
880 shift $((OPTIND - 1))
881 case $# in 0) ;; *) usage >&2; exit 1 ;; esac
888 0) $verbose "All backups successful" ;;
889 *) $verbose "Backups FAILED" ;;
892 ###----- That's all, folks --------------------------------------------------