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 conf=@sysconfdir@/rsync-backup.conf
40 ###--------------------------------------------------------------------------
41 ### Utility functions.
46 ## Run rsync(1) in an appropriate manner. Configuration should ovrride
47 ## this or set $RSYNCOPTS if it wants to do something weirder. Arguments
48 ## to this function are passed on to rsync.
51 --archive --hard-links --numeric-ids --del \
56 --filter="dir-merge .rsync-backup" \
66 now=$(date +"%Y-%m-%d %H:%M:%S %z")
73 ## Run CMD, if this isn't a dry run.
76 t) echo >&2 " +++ $*" ;;
83 ## Copy lines from stdin to stdout, adding PREFIX.
85 while IFS= read -r line; do
86 printf "%s %s\n" "$prefix" "$line"
91 tag=$1 cmd=$2; shift 2
92 ## Run CMD, logging its output in a pleasing manner.
96 echo >&2 " *** RUN $tag"
97 echo >&2 " +++ $cmd $*"
104 "$cmd" "$@" 3>&- 4>&- 5>&- 9>&-
106 copy "|" >&4; } 2>&1 |
107 copy "*" >&4; } 4>&1 |
108 cat >&9; } 5>&1 </dev/null
112 *) log "FAIL $tag (rc = $rc)" ;;
121 ## Answer whether H is a local host.
124 "$thishost") return 0 ;;
131 ## Run CMD on the current host. If the host seems local then run the
132 ## command through a local shell; otherwise run it through ssh(1). Either
133 ## way it will be processed by a shell.
135 if localp $host; then run "@$host: $tag" sh -c "$cmd"
136 else run "@$host: $tag" ssh $userat$host "$cmd"
142 ## Like hostrun, but without the complicated logging, and targetted at a
145 if localp $h; then sh -c "$cmd"
152 ## Output (to stdout) either PATH or HOST:PATH, choosing the former if the
153 ## current host is local.
155 if localp $host; then echo $path
156 else echo $userat$host:$path
162 ## Define a hook called HOOK.
169 ## Add command CMD to the hook HOOK.
171 eval old=\$hk_$hook; new="$old $cmd"
177 ## Invoke HOOK, passing it the remaining arguments.
181 if ! $cmd "$@"; then return $?; fi
185 ###--------------------------------------------------------------------------
186 ### Database operations.
188 INDEXDB=@pkglocalstatedir@/index.db
191 host=$1 fs=$2 date=$3 vol=$4
193 if [ -f "$INDEXDB" ]; then
194 sqlite3 "$INDEXDB" <<EOF
195 INSERT INTO idx (host, fs, date, vol)
196 VALUES ('$host', '$fs', '$date', '$vol');
202 host=$1 fs=$2 date=$3
204 if [ -f "$INDEXDB" ]; then
205 sqlite3 "$INDEXDB" <<EOF
206 DELETE FROM idx WHERE
207 host = '$host' AND fs = '$fs' AND date = '$date';
212 ###--------------------------------------------------------------------------
213 ### Snapshot handling.
215 ## Snapshot protocol. Each snapshot type has a pair of functions snap_TYPE
216 ## and unsnap_TYPE. Each is given the current snapshot arguments and the
217 ## filesystem name to back up. The snap_TYPE function should create and
218 ## mount the snapshot and output an rsync(1) path to where the filesystem can
219 ## be copied; the unsnap_TYPE function should unmount and tear down the
222 ## Fake snapshot by not doing anything. Use only if you have no choice.
223 snap_live () { hostpath "$2"; }
224 unsnap_live () { :; }
226 ## Fake snapshot by remounting a live filesystem read-only. Useful if the
227 ## underlying storage isn't in LVM.
232 ## Place a marker in the filesystem so we know why it was made readonly.
233 ## (Also this serves to ensure that the filesystem was writable before.)
234 hostrun "snap-ro $mnt" "
235 echo rsync-backup >$mnt/.lock
236 mount -oremount,ro $mnt" || return $?
245 ## Check that the filesystem still has our lock marker.
246 hostrun "unsnap-ro $mnt" "
247 case \$(cat $mnt/.lock) in
249 *) echo unlocked by someone else; exit 31 ;;
251 mount -oremount,rw $mnt
252 rm $mnt/.lock" || return $?
255 ## Snapshot using LVM.
257 SNAPSIZE="-l10%ORIGIN"
258 SNAPDIR=@mntbkpdir@/snap
263 ## Make the snapshot.
264 hostrun "snap-lvm $vg/$lv" "
265 lvcreate --snapshot -n$lv.bkp $SNAPSIZE $vg/$lv
266 mkdir -p $SNAPDIR/$lv
267 mount -oro /dev/$vg/$lv.bkp $SNAPDIR/$lv" || return $?
270 hostpath $SNAPDIR/$lv
276 ## Remove the snapshot. Sometimes LVM doesn't notice that the snapshot is
277 ## no longer in open immdiately, so try several times.
278 hostrun "unsnap-lvm $vg/$lv" "
282 if lvremove -f $vg/$lv.bkp; then rc=0; break; fi
285 exit $rc" || return $?
288 ## Complicated snapshot using LVM, where the volume group and filesystem are
289 ## owned by different machines, so they need to be synchronized during the
293 lvhost=$1 vg=$2 lv=$3 fshost=$4 fsdir=$5
295 ## Engage in the rfreezefs protocol with the filesystem host. This
296 ## involves some hairy plumbing. We want to get exit statuses out of both
299 ssh $fshost rfreezefs $fsdir | {
302 ## Read the codebook from the remote end.
308 TOKEN) eval tok_$2=$3 ;;
309 READY) ready=t; break ;;
311 echo >&2 "$quis: unexpected keyword $1 (rfreezefs to $rhost)"
318 echo >&2 "$quis: unexpected eof (rfreezefs to $rhost)"
323 ## Connect to the filesystem host's TCP port and get it to freeze its
325 exec 3<>/dev/tcp/$fshost/$port
331 echo >&2 "$quis: unexpected token $tok (rfreezefs $fsdir on $fshost)"
336 ## Get the volume host to create the snapshot.
338 _hostrun >&2 3>&- $userat$lvhost \
339 "lvcreate --snapshot -n$lv.bkp $SNAPSIZE $vg/$lv"
343 ## The filesystem can thaw now.
349 _hostrun >&2 3>&- $userat$lvhost "lvremove -f $vg/$lv.bkp" || :
350 echo >&2 "$quis: unexpected token $tok (rfreezefs $fsdir on $fshost)"
359 ## Sift through the wreckage to find out what happened.
360 rc_rfreezefs=${PIPESTATUS[0]} rc_snapshot=${PIPESTATUS[1]}
362 case $rc_rfreezefs:$rc_snapshot in
366 echo >&2 "$quis: EMERGENCY failed to thaw $fsdir on $fshost!"
370 echo >&2 "$quis: failed to snapshot $vg/$lv ($fsdir on $fshost)"
375 ## Mount the snapshot on the volume host.
376 _hostrun >&2 $userat$lvhost "
377 mkdir -p $SNAPDIR/$lv
378 mount -oro /dev/$vg/$lv.bkp $SNAPDIR/$lv"
382 rhost=$1 vg=$2 lv=$3 rfs=$4
385 run "snap-rfreezefs $host:$vg/$lv $rhost:$rfs" \
386 do_rfreezefs $host $vg $lv $rhost $rfs || return $?
387 hostpath $SNAPDIR/$lv
390 unsnap_rfreezefs () {
392 ## Unshapping is the same as for plain LVM.
393 rhost=$1 vg=$2 lv=$3 rfs=$4
397 ###--------------------------------------------------------------------------
398 ### Expiry computations.
402 ## Parse an ISO8601 DATE, and set YEAR, MONTH, DAY appropriately (and
403 ## without leading zeros).
405 ## Extract the components of the date and trim leading zeros (which will
406 ## cause things to be interpreted as octal and fail).
407 year=${date%%-*} rest=${date#*-}; month=${rest%%-*} day=${rest#*-}
408 year=${year#0} month=${month#0} day=${day#0}
413 ## Convert an ISO8601 DATE to a Julian Day Number.
417 ## The actual calculation: convert a (proleptic) Gregorian calendar date
418 ## into a Julian day number. This is taken from Wikipedia's page
419 ## http://en.wikipedia.org/wiki/Julian_day#Calculation but the commentary
420 ## is mine. The epoch is 4713BC-01-01 (proleptic) Julian, or 4714BC-11-24
421 ## proleptic Gregorian.
423 ## If the MONTH is January or February then set a = 1, otherwise set a = 0.
424 a=$(( (14 - $month)/12 ))
426 ## Compute a year offset relative to 4799BC-03-01. This puts the leap day
427 ## as the very last day in a year, which is very convenient. The offset
428 ## here is sufficient to make all y values positive (within the range of
429 ## the JDN calendar), and is a multiple of 400, which is the Gregorian
431 y=$(( $year + 4800 - $a ))
433 ## Compute the offset month number in that year. These months count from
435 m=$(( $month + 12*$a - 3 ))
437 ## Now for the main event. The (153 m + 2)/5 term is a surprising but
438 ## correct trick for obtaining the number of days in the first m months of
439 ## the (shifted) year). The magic offset 32045 is what you get when you
440 ## plug the proper JDN epoch (year = -4713, month = 11, day = 24) into the
442 jdn=$(( $day + (153*$m + 2)/5 + 365*$y + $y/4 - $y/100 + $y/400 - 32045 ))
448 ## Read dates on stdin; write to stdout `EXPIRE date' for dates which
449 ## should be expired and `RETAIN date' for dates which should be retained.
451 ## Get the current date and convert it into useful forms.
452 now=$(date +%Y-%m-%d)
454 now_jdn=$(julian $now) now_year=$year now_month=$month now_day=$day
457 ## Work through each date in the input.
461 ## Convert the date into a useful form.
465 ## Work through the policy list.
466 if [ $jdn -le $now_jdn ]; then
467 while read ival age; do
469 ## Decide whether the policy entry applies to this date.
476 if [ $year -eq $now_year ] ||
477 ([ $year -eq $(( $now_year - 1 )) ] &&
478 [ $month -ge $now_month ])
482 if ([ $month -eq $now_month ] && [ $year -eq $now_year ]) ||
483 ((([ $month -eq $(( $now_month - 1 )) ] &&
484 [ $year -eq $now_year ]) ||
485 ([ $month -eq 12 ] && [ $now_month -eq 1 ] &&
486 [ $year -eq $(( $now_year - 1 )) ])) &&
487 [ $day -ge $now_day ])
491 if [ $jdn -ge $(( $now_jdn - 7 )) ]; then apply=t; fi
494 echo >&2 "$quis: unknown age symbol \`$age'"
498 case $apply in nil) continue ;; esac
500 ## Find the interval marker for this date.
506 ydn=$(julian $year-01-01)
507 wk=$(( ($jdn - $ydn)/7 + 1 ))
517 echo >&2 "$quis: unknown interval symbol \`$ival'"
522 ## See if we've alredy retained something in this interval.
525 *) keep=t kept=$kept$marker: ;;
534 t) echo RETAIN $date ;;
535 *) echo EXPIRE $date ;;
541 ###--------------------------------------------------------------------------
542 ### Actually taking backups of filesystems.
544 STOREDIR=@mntbkpdir@/store
545 METADIR=@mntbkpdir@/meta
553 _hostrun $userat$host "
557 echo \"*** $host $fs $date\"; echo
558 rsync -rx --filter='dir-merge .rsync-backup' ./ |
559 fshash -c$fshashdir/$fs.bkp -a -H$HASH -frsync
564 { echo "*** $host $fs $date"; echo
565 fshash -c$STOREDIR/fshash.cache -H$HASH new/
573 case $i in *[!-0-9]*) continue ;; esac
574 case $seen in *:"$i":*) continue ;; esac
579 while read op date; do
582 echo >&2 " --- keep $date"
585 echo >&2 " --- delete $date"
592 $verbose -n " expire $date..."
594 delete_index $host $fs $date
606 backup_precommit_hook () {
607 host=$1 fs=$2 date=$3
608 ## Compatibility: You can override this hook in the configuration file for
609 ## special effects; but it's better to use `addhook precommit'.
613 addhook precommit backup_precommit_hook
615 backup_commit_hook () {
616 host=$1 fs=$2 date=$3
617 ## Compatibility: You can override this hook in the configuration file for
618 ## special effects; but it's better to use `addhook commit'.
622 addhook commit backup_commit_hook
625 date=$1 fs=$2 fsarg=$3
626 ## Back up FS on the current host.
631 ## Run a hook beforehand.
632 set +e; runhook setup $host $fs $date; rc=$?; set -e
635 99) log "BACKUP of $host:$fs SKIPPED by hook"; return 0 ;;
636 *) log "BACKUP of $host:$fs FAILED (hook returns $?)"; return $? ;;
639 ## Report the start of this attempt.
640 log "START BACKUP of $host:$fs"
642 ## Maybe we need to retry the backup.
645 ## Create and mount the remote snapshot.
648 maybe snap_$snap $fs $fsarg
652 snapmnt=$(snap_$snap $snapargs $fs $fsarg) || return $?
655 $verbose " create snapshot"
657 ## Build the list of hardlink sources.
659 for i in $host $like; do
660 d=$STOREDIR/$i/$fs/last/
661 if [ -d $d ]; then linkdests="$linkdests --link-dest=$d"; fi
664 ## Copy files from the remote snapshot.
667 t) $verbose " running rsync" ;;
668 nil) $verbose -n " running rsync..." ;;
671 run "RSYNC of $host:$fs (snapshot on $snapmnt)" do_rsync \
677 case $dryrun in nil) $verbose " done" ;; esac
679 ## Collect a map of the snapshot for verification purposes.
682 t) $verbose " remote fshash" ;;
683 nil) $verbose -n " remote fshash..." ;;
685 run "@$host: fshash $fs" remote_fshash
688 case $dryrun in nil) $verbose " done" ;; esac
690 ## Remove the snapshot.
691 maybe unsnap_$snap $snapargs $fs $fsarg
692 $verbose " remove snapshot"
694 ## If we failed to copy, then give up.
695 case $rc_rsync:$rc_fshash in
697 0:*) return $rc_fshash ;;
698 *) return $rc_rsync ;;
701 ## Get a matching map of the files received.
702 maybe mkdir -m750 -p $STOREDIR/tmp/
703 localmap=$STOREDIR/tmp/fshash.$host.$fs.$date
705 t) $verbose " local fshash" ;;
706 nil) $verbose -n " local fshash..." ;;
708 run "local fshash $host:$fs" local_fshash || return $?
709 case $dryrun in nil) $verbose " done" ;; esac
711 ## Compare the two maps.
713 run "compare fshash maps for $host:$fs" diff -u new.fshash $localmap
721 if [ $attempt -ge $retry ]; then return $rc; fi
722 $verbose " fshash mismatch; retrying"
723 attempt=$(( $attempt + 1 ))
732 maybe rm -f $localmap
733 $verbose " fshash match"
735 ## Commit this backup.
738 runhook precommit $host $fs $date
740 mv new.fshash $date.fshash
741 insert_index $host $fs $date $VOLUME
742 runhook commit $host $fs $date
744 ln -s $date hack/last
751 ## Expire old backups.
752 case "${expire_policy+t},${default_policy+t}" in
753 ,t) expire_policy=$default_policy ;;
755 case "${expire_policy+t},$dryrun" in
756 t,nil) run "expiry for $host:$fs" expire_backups ;;
757 t,t) expire_backups ;;
763 t) log "END BACKUP of $host:$fs" ;;
764 nil) log "SUCCESSFUL BACKUP of $host:$fs" ;;
769 fs=$1 date=$2 cmd=$3; shift 3
770 ## try_backup FS DATE COMMAND ARGS ...
772 ## Run COMMAND ARGS to back up filesystem FS on the current host,
773 ## maintaining a log, and checking whether it worked. The caller has
774 ## usually worked out the DATE in order to set up the filesystem, and we
775 ## need it to name the log file properly.
777 ## Find a name for the log file. In unusual circumstances, we may have
778 ## deleted old logs from today, so just checking for an unused sequence
779 ## number is insufficient. Instead, check all of the logfiles for today,
780 ## and use a sequence number that's larger than any of them.
787 for i in "$logdir/$host/$fs.$date#"*; do
789 case "$tail" in [!1-9]* | *[!0-9]*) continue ;; esac
790 if [ -f "$i" -a $tail -ge $seq ]; then seq=$(( tail + 1 )); fi
792 log="$logdir/$host/$fs.$date#$seq"
796 ## Run the backup command.
797 case $dryrun in nil) mkdir -p $logdir/$host ;; esac
798 if ! "$cmd" "$@" 9>$log 1>&9; then
800 echo >&2 "$quis: backup of $host:$fs FAILED!"
804 ## Count up the logfiles.
806 for i in "$logdir/$host/$fs".*; do
807 if [ ! -f "$i" ]; then continue; fi
811 ## If there are too many, go through and delete some early ones.
812 if [ $dryrun = nil ] && [ $nlog -gt $MAXLOG ]; then
813 n=$(( nlog - MAXLOG ))
814 for i in "$logdir/$host/$fs".*; do
815 if [ ! -f "$i" ]; then continue; fi
818 if [ $n -eq 0 ]; then break; fi
824 ## backup FS[:ARG] ...
826 ## Back up the filesystems on the currently selected host using the
827 ## currently selected snapshot type.
829 ## Make sure that there's a store volume. We must do this here rather than
830 ## in the main body of the script, since the configuration file needs a
831 ## chance to override STOREDIR.
832 if ! [ -r $STOREDIR/.rsync-backup-store ]; then
833 echo >&2 "$quis: no backup volume mounted"
837 ## Read the volume name if we don't have one already. Again, this allows
838 ## the configuration file to provide a volume name.
839 case "${VOLUME+t}${VOLUME-nil}" in
840 nil) VOLUME=$(cat $METADIR/volume) ;;
843 ## Back up each requested file system in turn.
846 ## Parse the argument.
848 *:*) fsarg=${fs#*:} fs=${fs%%:*} ;;
851 $verbose " filesystem $fs"
853 ## Move to the store directory and set up somewhere to put this backup.
857 if [ ! -d $host ]; then
859 chown root:root $host
861 if [ ! -d $host/$fs ]; then
862 mkdir -m750 $host/$fs
863 chown root:backup $host/$fs
869 ## Find out if we've already copied this filesystem today.
870 date=$(date +%Y-%m-%d)
871 if [ $dryrun = nil ] && [ -d $date ]; then
872 $verbose " already dumped"
876 ## Do the backup of this filesystem.
877 run_backup_cmd $fs $date do_backup $date $fs $fsarg
881 ###--------------------------------------------------------------------------
882 ### Configuration functions.
887 done_first_host_p=nil
892 case $done_first_host_p in
893 nil) runhook start; done_first_host_p=t ;;
895 case "${expire_policy+t},${default_policy+t}" in
896 t,) default_policy=$expire_policy ;;
899 $verbose "host $host"
902 snaptype () { snap=$1; shift; snapargs="$*"; retry=0; }
903 rsyncargs () { rsyncargs="$*"; }
904 like () { like="$*"; }
905 retry () { retry="$*"; }
906 user () { userat="$*@"; }
909 case $clear_policy in t) unset expire_policy; clear_policy=nil ;; esac
910 expire_policy="${expire_policy+$expire_policy
914 ###--------------------------------------------------------------------------
915 ### Read the configuration and we're done.
918 echo "usage: $quis [-nv] [-c CONF]"
922 echo "$quis version $VERSION"
929 mntbkpdir = $mntbkpdir
930 fshashdir = $fshashdir
935 whine () { echo >&8 "$@"; }
937 while getopts "hVvc:n" opt; do
940 V) version; config; exit 0 ;;
947 shift $((OPTIND - 1))
948 case $# in 0) ;; *) usage >&2; exit 1 ;; esac
955 0) $verbose "All backups successful" ;;
956 *) $verbose "Backups FAILED" ;;
959 ###----- That's all, folks --------------------------------------------------