]> git.sesse.net Git - backup.sh/blob - backup.sh
f4ae98bb0ab7dde18f3aee1df337786472ed50ae
[backup.sh] / backup.sh
1 #!/bin/bash
2 # backup.sh
3
4 # Backup up Unix-like computers
5
6 # itk@samfundet.no
7 #
8 # This script was first checked into RCS in 2000, and has since backed up a few
9 # servers almost every day, whenever not broken.
10
11 # It's a bit peculiar, but quite effective. The following is worth keeping in
12 # mind when hacking:
13 #
14 # Because of the way we run this script from cron, informational logging goes
15 # to stderr and warnings and errors to stdout. This way, we get mail whenever
16 # stuff fails, and other output is redirected to the log file.
17
18 # The script is halfway Norwegian and halfway English. Newer modifications are
19 # in English, we should probably stick to that.
20
21 SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"  # Absolute directory the script lives in
22 confdir=$SCRIPTPATH/conf/                        # Directory configuration files
23 [ -r $confdir/env ] && . $confdir/env
24
25 # Default configuration; used unless $confdir/env has set something different.
26 storagedir=${storagedir:-/backup}                # Where we keep backups
27 exclude=${exclude:-$confdir/exclude}             # List of exclude patterns
28 maxnumfull=${maxnumfull:-3}                      # Number of full backups
29 daysbetweenfull=${daysbetweenfull:-30}           # Days between full backups
30
31 # Days between full backups for machines with fixed full-backup date
32 # (in case the fixed day gets missed).
33 daysbetweenfullforfixed=${daysbetweenfullforfixed:-32}
34
35 # End of configuration.
36
37 computer=$1                                      # The computer to backup.
38 LOCKFILE=$SCRIPTPATH/backuprun.lockfile.$computer
39 DAY_OF_MONTH=`date "+%d" | sed s/^0//`           # from 1 to 31
40 DATE=`date "+%Y%m%d%H%M"`                        # format: touch
41 DATEs=`date "+%Y-%m-%d %H:%M"`                   # format: tar
42
43 if [ -z "$computer" ]; then
44         echo "Usage: $0 COMPUTER"
45         exit 1
46 fi
47
48 [ ! -f $exclude ] && printf "tmp\ncore\n" > $exclude
49
50 # Die more or less gracefully (at least notify user)
51 die() {
52         warnmsg "Aborting."
53         rm $LOCKFILE
54         exit 1
55 }
56 diemsg() {
57         warnmsg "$@"
58         die
59 }
60 warnmsg() {
61         echo `date`": $computer: $@"
62         echo `date`": $computer: $@" >&2
63 }
64 infomsg() {
65         echo `date`": $computer: $@" >&2
66 }
67
68 # Trap C-c and kill
69 trap die SIGINT SIGTERM
70
71 # Don't start if we're already running. Don't use diemsg, as that removes the lock file!
72 if [ -e $LOCKFILE ]; then
73         warnmsg "$LOCKFILE exists for pid `cat $LOCKFILE`."
74         exit 1
75 fi;
76 touch $LOCKFILE
77 echo $$ > $LOCKFILE
78
79 infomsg "Backup run starting"
80
81 umask 027
82
83 backup()
84 {
85         infomsg "$computer:$filesystem $backuplevel backup"
86
87         localsnar="${storagedir}/${computer}/${sfilesystem}/.incremental.snar"
88         remotesnar="$remotehome/.backup/${sfilesystem}.snar"
89         if [ "$backuplevel" = "daglig" ]; then
90                 # If incremental backup, we need to copy the incremental status to $computer.
91                 # If it does not exist, whine a bit and then run date-based instead.
92                 if [ -s "$localsnar" ]; then
93                         if ! scp $localsnar $username@$computer:$remotesnar; then
94                                 diemsg "Could not copy .incremental.snar to $computer"
95                         fi
96                         lastcmd="--listed-incremental=$remotesnar --no-check-device"
97                 else
98                         infomsg "Missing incremental.snar for $filesystem, doing date-based backup instead until next full backup"
99                         remotesnar=""
100                         lastd=`cat ../.date`
101                         lastcmd="--newer='$lastd'"
102                 fi
103         else
104                 # Note: Since we rm-ed .backup previously, and we don't scp over
105                 # anything in this branch, this file will not exist, and we
106                 # will be doing a full backup (but we want the output of it).
107                 lastcmd="--listed-incremental=$remotesnar"
108         fi
109
110         # We try to run tar on the remote computer
111         #    c create archive
112         #    C change to directory first
113         #    . where to start taring (see C)
114         #    $lastcmd only files newer than this
115         #    --one-file-system don't traverse file systems
116         #    --use-compress-program compress it using gzip or pigz
117         #    --exclude-from file to get exclusion pattern from
118         #    Pipe the stuff over ssh to ourselves, run pee to cat the contents to a
119         #    file and build a file list, respectivly.  
120         TARFILE=$DATE.tmp
121         TARCMD="ssh $username@$computer \"nice -n 19 ionice -c3 tar --one-file-system --use-compress-program $compressor -cf - -C $filesystem . $lastcmd \
122                 --exclude-from=$remotehome/.backup/exclude\" | pee \"cat > $TARFILE\" \"tar tzvf -\""
123         infomsg "Running $TARCMD"
124         eval $TARCMD > $DATE.idx
125
126         if [ $? -eq 0 ] && [ -s $TARFILE ]; then
127                 # File is >0 in size and neither cat or tar tzvf failed; we assume it worked.
128  
129                 if [ "$remotesnar" ]; then
130                         if ! scp $username@$computer:$remotesnar $localsnar.tmp; then
131                                 diemsg "Could not copy .incremental.snar from $computer"
132                         fi
133                 fi
134
135                 # Move tar file in place
136                 mv $TARFILE $DATE.tgz
137                 if [ "$remotesnar" ]; then
138                         mv $localsnar.tmp $localsnar
139                 fi
140
141                 # Update timestamp
142                 echo $DATEs > ../.date && touch -t $DATE ../.date
143
144                 # Fix permissions
145                 chmod 600 *tgz                      #only for us
146                 chmod 644 *idx 2>/dev/null          #everyone can read
147
148                 # Let the remote computer know that we ran a successful backup (for nagios)
149                 ssh $username@$computer touch $filesystem/.lastbackup
150         else
151                 # Something wrong happened.
152                 rm $TARFILE
153                 diemsg "tar failed or $TARFILE empty. $backuplevel backup of $computer:$filesystem failed and deleted"
154         fi
155 }
156
157 # Non-privileged backups currently have a few limitations compared to regular ones:
158 #
159 #  - No .idx files.
160 #  - No .snar-style incremental backups, only date-based.
161 #  - No touching of .lastbackup for Nagios.
162 #  - Failed tar operations may go undetected, since we only see the error code
163 #    the last process in the pipe chain, which is gpg.
164 nonprivbackup()
165 {
166         infomsg "$computer:$filesystem $backuplevel non-privileged backup"
167
168         if [ "$backuplevel" = "daglig" ]; then
169                 lastd=`cat ../.date`
170                 lastcmd="'$lastd'"
171         else
172                 lastcmd=""
173         fi
174
175         TARFILE=$DATE.tmp
176         TARCMD="ssh $username@$computer \"sudo /usr/local/sbin/output-encrypted-backup $filesystem $lastcmd\""
177         infomsg "Running $TARCMD"
178         eval $TARCMD > $TARFILE
179
180         if [ $? -eq 0 ] && [ -s $TARFILE ]; then
181                 # File is >0 in size and the remote side did not report any fatal errors; we assume it worked.
182
183                 # Move tar file in place
184                 mv $TARFILE $DATE.tgz.gpg
185
186                 # Update timestamp
187                 echo $DATEs > ../.date && touch -t $DATE ../.date
188
189                 # Fix permissions
190                 chmod 600 *tgz.gpg                  #only for us
191         else
192                 # Something wrong happened.
193                 rm $TARFILE
194                 diemsg "tar failed or $TARFILE empty. $backuplevel backup of $computer:$filesystem failed and deleted"
195         fi
196 }
197
198 # Check that the target filesystem is mounted (actually check that it's not
199 # the root filesystem)
200 if [ ! -d "$storagedir/$computer" ]; then
201         diemsg "Target filesystem ($storagedir/$computer) does not exist."
202 fi
203 rootfilesystem=`df -P /`
204 targetfilesystem=`df -P "$storagedir/$computer"`
205 if [ "$rootfilesystem" == "$targetfilesystem" ]; then
206         diemsg "Target filesystem ($storagedir/$computer) was mounted on /."
207 fi
208  
209 # Find the user to do the backup as.
210 if [ -f $confdir/username.$computer ] ; then
211         username=`cat $confdir/username.$computer`
212 else 
213         username=root
214 fi
215
216 infomsg "Backing up $computer"
217
218 # Try to SSH to the computer without entering a password.
219 if ! ssh -n -o NumberOfPasswordPrompts=0 $username@$computer /bin/true; then
220         diemsg "Could not use passwordless SSH."
221 fi
222
223 # Find the home directory of the backup user
224 remotehome=`ssh $username@$computer "echo ~"`
225 if [ -z "$remotehome" ]; then
226         diemsg "Could not expand ~ for user $username"
227 fi
228
229 # Check if pigz is available
230 if ssh -n $username@$computer "pigz -V 2>/dev/null"; then
231         compressor=pigz
232 else
233         infomsg "pigz missing; falling back to gzip."
234         compressor=gzip
235 fi
236
237 # Check dump bit in fstab
238 filesystems=`ssh -n $username@$computer "cat /etc/fstab" \
239         | grep -v nfs \
240         | grep -v "^#" \
241         | grep -v "^$" \
242         | awk '{ if ( $(NF-1) != "0" ) print $2}' `
243
244 # Clean up our dir at this client
245 if ! ssh $username@$computer "rm -r $remotehome/.backup ; mkdir -m 700 $remotehome/.backup"; then
246         diemsg "Could not create backup staging area at $computer:$remotehome/.backup"
247 fi
248
249 # Try to copy $exclude to $computer
250 if ! scp $exclude $username@$computer:$remotehome/.backup/exclude > /dev/null; then
251         diemsg "Could not copy exclude.txt to $computer"
252 fi
253
254 # Try to copy preeexec and postexec if they exist
255 if [ -f $confdir/preexec.$computer ]; then
256         if ! scp $confdir/preexec.$computer $username@$computer:$remotehome/.backup/preexec >&2; then
257                 diemsg "Could not copy preexec.$computer to $computer:$remotehome/.backup/preexec"
258         fi
259 fi
260 if [ -f $confdir/postexec.$computer ]; then
261         if ! scp $confdir/postexec.$computer $username@$computer:$remotehome/.backup/postexec >&2; then
262                 diemsg "Could not copy postexec.$computer to $computer:$remotehome/.backup/postexec"
263         fi
264 fi
265
266 # Try to run preexec if it exists
267 if ! ssh $username@$computer "[ ! -f $remotehome/.backup/preexec ] || /bin/bash -x $remotehome/.backup/preexec" >&2; then
268         diemsg "Could not run $computer:$remotehome/.backup/preexec"
269 fi
270
271 for filesystem in $filesystems; do
272         # Remove / and $ (for Windows) for path names
273         sfilesystem=`echo $filesystem | tr '\/\$' '__'`
274
275         # Prepare storage area
276         mkdir -m 755 -p $storagedir/$computer/$sfilesystem/full 2>/dev/null
277         mkdir -m 755 -p $storagedir/$computer/$sfilesystem/daglig 2>/dev/null
278
279         # Default backuplevel
280         backuplevel=daglig
281
282         if [ ! -s $storagedir/$computer/$sfilesystem/.date ]; then
283                 # Take the first full backup of this filesystem on this computer
284                 backuplevel=full
285         fi
286
287         # Check if we want a full backup
288         if [ -f $confdir/fastfullbackupdag.$computer.$sfilesystem ]; then
289                 fullbackup_min_for_this_machine=$daysbetweenfullforfixed
290                 if [ "$DAY_OF_MONTH" = "`cat $confdir/fastfullbackupdag.$computer.$sfilesystem`" ]; then
291                         backuplevel=full
292                 fi
293         elif [ -f $confdir/fastfullbackupdag.$computer ]; then
294                 fullbackup_min_for_this_machine=$daysbetweenfullforfixed
295                 if [ "$DAY_OF_MONTH" = "`cat $confdir/fastfullbackupdag.$computer`" ]; then
296                         backuplevel=full
297                 fi
298         else
299                 fullbackup_min_for_this_machine=$daysbetweenfull 
300         fi
301
302         if [ -z "`find $storagedir/$computer/$sfilesystem/full/ -name \*tgz\* -mtime -$fullbackup_min_for_this_machine`" ]; then
303                 backuplevel=full
304         fi
305
306         # We want to be here
307         cd $storagedir/$computer/$sfilesystem/$backuplevel || diemsg "$storagedir/$computer/$sfilesystem/$backuplevel does not exist"
308
309         # Perform the actual backup
310         if [ "$username" = "root" ]; then
311                 backup
312         else
313                 nonprivbackup
314         fi
315
316         # Check if this box has a custom number of full backups
317         if [ -f $confdir/maksfulle.$computer.$sfilesystem ]; then
318                 mf=$((`cat $confdir/maksfulle.$computer`+1))
319         elif [ -f $confdir/maksfulle.$computer ] ; then
320                 mf=$((`cat $confdir/maksfulle.$computer`+1))
321         else
322                 mf=$(($maxnumfull+1))
323         fi
324
325         # Delete old full backups
326         for full in `ls -1t $storagedir/$computer/$sfilesystem/full/*tgz* | tail -n +$mf`; do
327                 prefix=`echo $full | sed "s/\.[^.]*$//"`
328                 infomsg "$computer:$filesystem Deleting full backup $prefix"
329                 rm $prefix*
330         done
331
332         # Delete incremental backups older than the oldest full backup
333         oldf=`ls -t1 $storagedir/$computer/$sfilesystem/full/*tgz* | tail -1`
334         find \
335                 $storagedir/$computer/$sfilesystem/daglig \
336                 -type f \
337                 \! -newer $oldf \
338                 -printf "`date`: $computer: Deleting old incremental backup: %p\n" \
339                 -exec rm {} \; >&2
340 done
341
342 # Try to run postexec if it exist
343 if ! ssh $username@$computer "[ ! -f $remotehome/.backup/postexec ] || /bin/bash -x $remotehome/.backup/postexec" >&2; then
344         diemsg "Could not run $computer:$remotehome/.backup/postexec"
345 fi
346
347 # Use warn so that we will get an email even on success.
348 warnmsg "Backup completed successfully."
349
350 # Remove lockfile
351 rm $LOCKFILE