#!/bin/bash
+# backup.sh
+#
+# Backup up Unix-like computers
+#
+# itk@samfundet.no
+#
+# This script was first checked into RCS in 2000, and has since backed up a few
+# servers almost every day, whenever not broken.
+#
+# It's a bit peculiar, but quite effective. The following is worth keeping in
+# mind when hacking:
+#
+# Because of the way we run this script from cron, informational logging goes
+# to stderr and warnings and errors to stdout. This way, we get mail whenever
+# stuff fails, and other output is redirected to the log file.
+#
+# The script is halfway Norwegian and halfway English. Newer modifications are
+# in English, we should probably stick to that.
+
+SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )" # Absolute directory the script lives in
+confdir=$SCRIPTPATH/conf/ # Directory configuration files
+[ -r $confdir/env ] && . $confdir/env
+
+# Default configuration; used unless $confdir/env has set something different.
+storagedir=${storagedir:-/backup} # Where we keep backups
+exclude=${exclude:-$confdir/exclude} # List of exclude patterns
+maxnumfull=${maxnumfull:-3} # Number of full backups
+daysbetweenfull=${daysbetweenfull:-30} # Days between full backups
+
+# Days between full backups for machines with fixed full-backup date
+# (in case the fixed day gets missed).
+daysbetweenfullforfixed=${daysbetweenfullforfixed:-32}
+
+# End of configuration.
+
+computer=$1 # The computer to backup.
+LOCKFILE=$SCRIPTPATH/backuprun.lockfile.$computer
+DAY_OF_MONTH=`date "+%d" | sed s/^0//` # from 1 to 31
+DATE=`date "+%Y%m%d%H%M"` # format: touch
+DATEs=`date "+%Y-%m-%d %H:%M"` # format: tar
+
+if [ -z "$computer" ]; then
+ echo "Usage: $0 COMPUTER"
+ exit 1
+fi
-#dirs
-confdir=/home/backup/conf/ #configuration files
-storagedir=/backup #mountpoint of huge disc
-###
-
-#exclude-pattern
-exclude=$confdir/exclude
[ ! -f $exclude ] && printf "tmp\ncore\n" > $exclude
-###
-
-#syntax of remotestat:
-#hostname:/directory/
-remotestatf=$confdir/remotestat
-[ -f $remotestatf ] && remotestat=`cat $remotestatf`
-###
-PATH=/local/bin:$PATH:/store/bin
-export PATH
-
-#start the logfile
-date
-echo
-echo "Exclude pattern:"
-cat $exclude
-echo
-echo
+# Die more or less gracefully (at least notify user)
+die() {
+ warnmsg "Aborting."
+ rm $LOCKFILE
+ exit 1
+}
+diemsg() {
+ warnmsg "$@"
+ die
+}
+warnmsg() {
+ echo `date`": $computer: $@"
+ echo `date`": $computer: $@" >&2
+}
+infomsg() {
+ echo `date`": $computer: $@" >&2
+}
-umask 027
+# Trap C-c and kill
+trap die SIGINT SIGTERM
-# The computers we want to back up
-unixcomputers=`cat $confdir/computers.unix`
-###
+# Don't start if we're already running. Don't use diemsg, as that removes the lock file!
+if [ -e $LOCKFILE ]; then
+ warnmsg "$LOCKFILE exists for pid `cat $LOCKFILE`."
+ exit 1
+fi;
+touch $LOCKFILE
+echo $$ > $LOCKFILE
-#disse bør kunne varieres fra fs til fs?
-maksantallfulle=2 #hvor mange fulle vi tar vare på
-dagermellomfulle=30 #antall dager før det er på tide med ny full
-logw=40
-###
+infomsg "Backup run starting"
-#lager datovariabeler
-DATE=`date "+%Y%m%d%H%M"` #format: touch
-DATEs=`date "+%Y-%m-%d %H:%M"` #format: tar
-###
+umask 027
-#selve backupen
-# krever at noen variabler er satt
-# krever at vi er i rett katalog
backup()
{
+ infomsg "$computer:$filesystem $backuplevel backup"
+
+ localsnar="${storagedir}/${computer}/${sfilesystem}/.incremental.snar"
+ remotesnar="$remotehome/.backup/${sfilesystem}.snar"
+ if [ "$backuplevel" = "daglig" ]; then
+ # If incremental backup, we need to copy the incremental status to $computer.
+ # If it does not exist, whine a bit and then run date-based instead.
+ if [ -s "$localsnar" ]; then
+ if ! scp $localsnar $username@$computer:$remotesnar; then
+ diemsg "Could not copy .incremental.snar to $computer"
+ fi
+ lastcmd="--listed-incremental=$remotesnar --no-check-device"
+ else
+ infomsg "Missing incremental.snar for $filesystem, doing date-based backup instead until next full backup"
+ remotesnar=""
+ lastd=`cat ../.date`
+ lastcmd="--newer='$lastd'"
+ fi
+ else
+ # Note: Since we rm-ed .backup previously, and we don't scp over
+ # anything in this branch, this file will not exist, and we
+ # will be doing a full backup (but we want the output of it).
+ lastcmd="--listed-incremental=$remotesnar"
+ fi
+
+ # We try to run tar on the remote computer
+ # c create archive
+ # C change to directory first
+ # . where to start taring (see C)
+ # $lastcmd only files newer than this
+ # --one-file-system don't traverse file systems
+ # --use-compress-program compress it using gzip or pigz
+ # --exclude-from file to get exclusion pattern from
+ # Pipe the stuff over ssh to ourselves, run pee to cat the contents to a
+ # file and build a file list, respectivly.
+ TARFILE=$DATE.tmp
+ TARCMD="ssh $username@$computer \"nice -n 19 ionice -c3 tar --one-file-system --use-compress-program $compressor -cf - -C $filesystem . $lastcmd \
+ --exclude-from=$remotehome/.backup/exclude\" | pee \"cat > $TARFILE\" \"tar tzvf -\""
+ infomsg "Running $TARCMD"
+ eval $TARCMD > $DATE.idx
+
+ if [ $? -eq 0 ] && [ -s $TARFILE ]; then
+ # File is >0 in size and neither cat or tar tzvf failed; we assume it worked.
+
+ if [ "$remotesnar" ]; then
+ if ! scp $username@$computer:$remotesnar $localsnar.tmp; then
+ diemsg "Could not copy .incremental.snar from $computer"
+ fi
+ fi
+
+ # Move tar file in place
+ mv $TARFILE $DATE.tgz
+ if [ "$remotesnar" ]; then
+ mv $localsnar.tmp $localsnar
+ fi
+
+ # Update timestamp
+ echo $DATEs > ../.date && touch -t $DATE ../.date
+
+ # Fix permissions
+ chmod 600 *tgz #only for us
+ chmod 644 *idx 2>/dev/null #everyone can read
+
+ # Let the remote computer know that we ran a successful backup (for nagios)
+ ssh $username@$computer touch $filesystem/.lastbackup
+ else
+ # Something wrong happened.
+ rm $TARFILE
+ diemsg "tar failed or $TARFILE empty. $backuplevel backup of $computer:$filesystem failed and deleted"
+ fi
+}
- printf "%-${logw}s %s\n" "$computer:$filesystem" "$backuplevel backup"
-
- if [ "$backuplevel" = "daglig" ] || [ "$backuplevel" = "incremental" ]
- then
- forrige=`cat ../.date`
- forrigecmd="--newer=\"$forrige\""
- else
- forrigecmd=""
- fi
-
- #We try to run tar on the remote computer
- if `ssh $computer ". /tmp/.backup/env ;\
- cd $filesystem ;\
- tar cfl - . $forrigecmd \
- --exclude-from=/tmp/.backup/exclude \
- | gzip" \
- | dd of=$DATE.tmp 2>/dev/null`
- then
- #perhaps it did work
- mv $DATE.tmp $DATE.tgz
- #make a filelist.
- #update the datefile if the filelist is ok.
- tar tvfz $DATE.tgz > $DATE.idx 2>&1 &&
- echo $DATEs > ../.date &&
- touch -t $DATE ../.date
-
- #make a sortet filelist
- grep -v ^d $DATE.idx | sort -n -r +2 > $DATE.sdx
-
- #fix perm
- chmod 600 *tgz #only for us
- chmod 644 *sdx *idx 2>/dev/null #everyone can read
-
- else
- #it did not work
- rm $DATE.tmp 2>/dev/null
- echo "$backuplevel backup of $computer:$filesystem failed and deleted"
- fi
-
+# Non-privileged backups currently have a few limitations compared to regular ones:
+#
+# - No .idx files.
+# - No .snar-style incremental backups, only date-based.
+# - No touching of .lastbackup for Nagios.
+# - Failed tar operations may go undetected, since we only see the error code
+# the last process in the pipe chain, which is gpg.
+nonprivbackup()
+{
+ infomsg "$computer:$filesystem $backuplevel non-privileged backup"
+
+ if [ "$backuplevel" = "daglig" ]; then
+ lastd=`cat ../.date`
+ lastcmd="'$lastd'"
+ else
+ lastcmd=""
+ fi
+
+ TARFILE=$DATE.tmp
+ TARCMD="ssh $username@$computer \"sudo /usr/local/sbin/output-encrypted-backup $filesystem $lastcmd\""
+ infomsg "Running $TARCMD"
+ eval $TARCMD > $TARFILE
+
+ if [ $? -eq 0 ] && [ -s $TARFILE ]; then
+ # File is >0 in size and the remote side did not report any fatal errors; we assume it worked.
+
+ # Move tar file in place
+ mv $TARFILE $DATE.tgz.gpg
+
+ # Update timestamp
+ echo $DATEs > ../.date && touch -t $DATE ../.date
+
+ # Fix permissions
+ chmod 600 *tgz.gpg #only for us
+ else
+ # Something wrong happened.
+ rm $TARFILE
+ diemsg "tar failed or $TARFILE empty. $backuplevel backup of $computer:$filesystem failed and deleted"
+ fi
}
-#Løper gjennom listen av unixmaskiner som vi skal ta backup av
-for computer in $unixcomputers
-do
-
- #tømmer variabelen for sikkerhets skyld
- filesystems=""
-
- #Sjekker nest siste felt i fstab. Om det er 0 tar vi ikke backup
- filesystems=`ssh -n $computer ". /tmp/.backup/env ; cat /etc/fstab" \
- | grep -v nfs \
- | grep -v ^# \
- | awk '{ if ( $(NF-1) != "0" ) print $2}' `
-
- #clean up our dir at this client
- ssh $computer "rm -rf /tmp/.backup ; mkdir -m 700 /tmp/.backup"
-
- #try to copy $exclude to $computer
- scp $exclude $computer:/tmp/.backup/exclude ||
- echo "could not copy exclude.txt to $computer :("
-
- #create env if it does not exist
- if [ ! -f $confdir/env.$computer ]
- touch $confdir/env.$computer
-
- #copy env to client
- scp $confdir/env.$computer $computer:/tmp/.backup/env
-
- #try to copy preeexec and postexec if they exist
- [ -f $confdir/preexec.$computer ] &&
- scp $confdir/preexec.$computer $computer:/tmp/.backup/preexec
- [ -f $confdir/postexec.$computer ] &&
- scp $confdir/postexec.$computer $computer:/tmp/.backup/postexec
-
- #try to run preexec if it exist
- ssh $computer ". /tmp/.backup/env ; [ -f /tmp/.backup/preexec ] && /bin/bash -x /tmp/.backup/preexec"
-
- for filesystem in $filesystems
- do
- #lager en variant uten tegnet "/" eller $ (gjelder NT)
- sfilesystem=`echo $filesystem | tr '\/\$' '__'`
-
- #lager det som trengs av kataloger
- mkdir -m 755 -p $storagedir/$computer/$sfilesystem/{full,daglig} 2>/dev/null
-
- #
- echo $filesystem > ${storagedir}/${computer}/.${sfilesystem}.name
- chmod 644 ${storagedir}/${computer}/.${sfilesystem}.name
-
- #set default backuplevel
- backuplevel=daglig
-
- if [ ! -f $storagedir/$computer/$sfilesystem/.date ]
- then
- #take the first full backup of this filesystem on this computer
- backuplevel=full
- echo $DATEs > $storagedir/$computer/$sfilesystem/.date
- fi
-
- #sjekker om det er på tide med en full
- if
- [ -z `find $storagedir/$computer/$sfilesystem/full/ -name \*tgz -mtime -$dagermellomfulle` ]
- then
- backuplevel=full
- fi
+# Check that the target filesystem is mounted (actually check that it's not
+# the root filesystem)
+if [ ! -d "$storagedir/$computer" ]; then
+ diemsg "Target filesystem ($storagedir/$computer) does not exist."
+fi
+rootfilesystem=`df -P /`
+targetfilesystem=`df -P "$storagedir/$computer"`
+if [ "$rootfilesystem" == "$targetfilesystem" ]; then
+ diemsg "Target filesystem ($storagedir/$computer) was mounted on /."
+fi
- #gå ned i rett katalog
- cd $storagedir/$computer/$sfilesystem/$backuplevel
-
- #perform the actual backup
- backup
-
- #delete complete backups
- mf=$(($maksantallfulle+1))
- for full in `ls -1t $storagedir/$computer/$sfilesystem/full/*tgz | tail +$mf`
- do
- prefix=`echo $full|cut -d . -f 1`
- echo "$computer:$filesystem sletter full $prefix (for mange)"
- rm $prefix*
- done
-
- #delete incremental backups older than the oldest complete backup
- oldf=`ls -t1 $storagedir/$computer/$sfilesystem/full/*tgz | tail -1`
- find \
- $storagedir/$computer/$sfilesystem/daglig \
- -type f \
- \! -newer $oldf \
- -exec rm {} \;
- #denne funker bare med gnu find
- #-printf "$computer:$filesystem sletter daglig %f (for gammel)\n" \
-
- done
-
- #try to run postexec if it exist
- ssh $computer ". /tmp/.backup/env ; [ -f /tmp/.backup/postexec ] && /bin/bash -x /tmp/.backup/postexec"
-
+# Find the user to do the backup as.
+if [ -f $confdir/username.$computer ] ; then
+ username=`cat $confdir/username.$computer`
+else
+ username=root
+fi
+
+infomsg "Backing up $computer"
+
+# Try to SSH to the computer without entering a password.
+if ! ssh -n -o NumberOfPasswordPrompts=0 $username@$computer /bin/true; then
+ diemsg "Could not use passwordless SSH."
+fi
+
+# Find the home directory of the backup user
+remotehome=`ssh $username@$computer "echo ~"`
+if [ -z "$remotehome" ]; then
+ diemsg "Could not expand ~ for user $username"
+fi
+
+# Check if pigz is available
+if ssh -n $username@$computer "pigz -V 2>/dev/null"; then
+ compressor=pigz
+else
+ infomsg "pigz missing; falling back to gzip."
+ compressor=gzip
+fi
+
+# Check dump bit in fstab
+filesystems=`ssh -n $username@$computer "cat /etc/fstab" \
+ | grep -v nfs \
+ | grep -v "^#" \
+ | grep -v "^$" \
+ | awk '{ if ( $(NF-1) != "0" ) print $2}' `
+
+# Clean up our dir at this client
+if ! ssh $username@$computer "rm -r $remotehome/.backup ; mkdir -m 700 $remotehome/.backup"; then
+ diemsg "Could not create backup staging area at $computer:$remotehome/.backup"
+fi
+
+# Try to copy $exclude to $computer
+if ! scp $exclude $username@$computer:$remotehome/.backup/exclude > /dev/null; then
+ diemsg "Could not copy exclude.txt to $computer"
+fi
+
+# Try to copy preeexec and postexec if they exist
+if [ -f $confdir/preexec.$computer ]; then
+ if ! scp $confdir/preexec.$computer $username@$computer:$remotehome/.backup/preexec >&2; then
+ diemsg "Could not copy preexec.$computer to $computer:$remotehome/.backup/preexec"
+ fi
+fi
+if [ -f $confdir/postexec.$computer ]; then
+ if ! scp $confdir/postexec.$computer $username@$computer:$remotehome/.backup/postexec >&2; then
+ diemsg "Could not copy postexec.$computer to $computer:$remotehome/.backup/postexec"
+ fi
+fi
+
+# Try to run preexec if it exists
+if ! ssh $username@$computer "[ ! -f $remotehome/.backup/preexec ] || /bin/bash -x $remotehome/.backup/preexec" >&2; then
+ diemsg "Could not run $computer:$remotehome/.backup/preexec"
+fi
+
+for filesystem in $filesystems; do
+ # Remove / and $ (for Windows) for path names
+ sfilesystem=`echo $filesystem | tr '\/\$' '__'`
+
+ # Prepare storage area
+ mkdir -m 755 -p $storagedir/$computer/$sfilesystem/full 2>/dev/null
+ mkdir -m 755 -p $storagedir/$computer/$sfilesystem/daglig 2>/dev/null
+
+ # Default backuplevel
+ backuplevel=daglig
+
+ if [ ! -s $storagedir/$computer/$sfilesystem/.date ]; then
+ # Take the first full backup of this filesystem on this computer
+ backuplevel=full
+ fi
+
+ # Check if we want a full backup
+ if [ -f $confdir/fastfullbackupdag.$computer.$sfilesystem ]; then
+ fullbackup_min_for_this_machine=$daysbetweenfullforfixed
+ if [ "$DAY_OF_MONTH" = "`cat $confdir/fastfullbackupdag.$computer.$sfilesystem`" ]; then
+ backuplevel=full
+ fi
+ elif [ -f $confdir/fastfullbackupdag.$computer ]; then
+ fullbackup_min_for_this_machine=$daysbetweenfullforfixed
+ if [ "$DAY_OF_MONTH" = "`cat $confdir/fastfullbackupdag.$computer`" ]; then
+ backuplevel=full
+ fi
+ else
+ fullbackup_min_for_this_machine=$daysbetweenfull
+ fi
+
+ if [ -z "`find $storagedir/$computer/$sfilesystem/full/ -name \*tgz\* -mtime -$fullbackup_min_for_this_machine`" ]; then
+ backuplevel=full
+ fi
+
+ # We want to be here
+ cd $storagedir/$computer/$sfilesystem/$backuplevel || diemsg "$storagedir/$computer/$sfilesystem/$backuplevel does not exist"
+
+ # Perform the actual backup
+ if [ "$username" = "root" ]; then
+ backup
+ else
+ nonprivbackup
+ fi
+
+ # Check if this box has a custom number of full backups
+ if [ -f $confdir/maksfulle.$computer.$sfilesystem ]; then
+ mf=$((`cat $confdir/maksfulle.$computer`+1))
+ elif [ -f $confdir/maksfulle.$computer ] ; then
+ mf=$((`cat $confdir/maksfulle.$computer`+1))
+ else
+ mf=$(($maxnumfull+1))
+ fi
+
+ # Delete old full backups
+ for full in `ls -1t $storagedir/$computer/$sfilesystem/full/*tgz* | tail -n +$mf`; do
+ prefix=`echo $full | sed "s/\.[^.]*$//"`
+ infomsg "$computer:$filesystem Deleting full backup $prefix"
+ rm $prefix*
+ done
+
+ # Delete incremental backups older than the oldest full backup
+ oldf=`ls -t1 $storagedir/$computer/$sfilesystem/full/*tgz* | tail -1`
+ find \
+ $storagedir/$computer/$sfilesystem/daglig \
+ -type f \
+ \! -newer $oldf \
+ -printf "`date`: $computer: Deleting old incremental backup: %p\n" \
+ -exec rm {} \; >&2
done
-#create report
-/home/backup/report.sh $storagedir > /tmp/report.txt
-[ ! -z $remotestat ] && scp /tmp/report.txt $remotestat
-###
+# Try to run postexec if it exist
+if ! ssh $username@$computer "[ ! -f $remotehome/.backup/postexec ] || /bin/bash -x $remotehome/.backup/postexec" >&2; then
+ diemsg "Could not run $computer:$remotehome/.backup/postexec"
+fi
+
+# Use warn so that we will get an email even on success.
+warnmsg "Backup completed successfully."
-date
+# Remove lockfile
+rm $LOCKFILE