]> git.sesse.net Git - backup.sh/blob - backup.sh
Add files that were never in RCS.
[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 # KISS. And by that I mean really simple. Only regular Unix commands, please
15 # (but GNU extensions are used and moreutils has to be installed).
16 #
17 # Because of the way we run this script from cron, informational logging goes
18 # to stderr and warnings and errors to stdout. This way, we get mail whenever
19 # stuff fails, and other output is redirected to the log file.
20
21 # The computers are backed up in parallel (but the filesystems on each
22 # computer in serial). This is implemented highly simplistic, with forking
23 # subshells. The script has no concept about threads, and stuff might go wrong,
24 # which usually requires manual cleanups.
25 #
26 # The script is halfway Norwegian and halfway English. Newer modifications are
27 # in English, we should probably stick to that.
28
29 # Known issues:
30 #
31 # o $R has no proper meaning because of the forking subshell stuff. We need a
32 #   more robust way of returning non-zero on errors, which we probably don't
33 #   right now.
34 #
35
36 # Configuration
37 LOCKFILE=/home/backup/backuprun.lockfile
38 confdir=/home/backup/conf/              # Configuration files
39 storagedir=/backup                      # Where we keep backups
40 maksantallfulle=3                       # Number of full backups
41 dagermellomfulle=30                     # Days between full backups
42 dagermellomfulleforfast=32              # Days between full backups for machines with fixed
43                                         # full-backup date (in case the fixed day gets missed)
44 DAY_OF_MONTH=`date "+%d" | sed s/^0//`  # from 1 to 31
45 DATE=`date "+%Y%m%d%H%M"`               #format: touch
46 DATEs=`date "+%Y-%m-%d %H:%M"`          #format: tar
47
48 # Exclude-pattern
49 exclude=$confdir/exclude
50 [ ! -f $exclude ] && printf "tmp\ncore\n" > $exclude
51
52 # Initially, we consider everything to be just fine.
53 R=0
54
55 # Die more or less gracefully (at least notify user)
56 die() {
57         echo `date`": Something nasty happened, and since I fork a lot:"
58         echo `date`": I CANNOT CLEAN UP THE MESS MYSELF."
59         echo `date`": You need to get rid of lost process named stuff like $0, tar and ssh."
60         exit 255
61 }
62
63 # Trap C-c and kill
64 trap die SIGINT SIGTERM
65
66 # Don't start if we're already running
67 if [ -e $LOCKFILE ]; then
68         echo `date`": $LOCKFILE exists for pid `cat $LOCKFILE`, exiting."
69         echo `date`": $LOCKFILE exists for pid `cat $LOCKFILE`, exiting." >&2
70         exit 1
71 fi;
72 touch $LOCKFILE
73 echo $$ > $LOCKFILE
74
75 #syntax of remotestat:
76 #hostname:/directory/
77 remotestatf=$confdir/remotestat
78 [ -f $remotestatf ] && remotestat=`cat $remotestatf`
79 ###
80
81 PATH=/local/bin:$PATH:/store/bin
82 export PATH
83
84 echo `date`": Backup run starting" >&2
85
86 umask 027
87
88 # The computers we want to back up
89 unixcomputers=`cat $confdir/computers.unix \
90   | grep -v "^#" \
91   | grep -v "^$" `
92
93 # Backup only one computer, from command line?
94 if [ $1 ] ; then 
95   unixcomputers=$1
96 fi
97
98 #selve backupen
99 # krever at noen variabler er satt
100 # krever at vi er i rett katalog
101 backup()
102 {
103
104  echo -n `date` >&2
105  printf " $computer: $computer:$filesystem $backuplevel backup\n" >&2
106
107  if [ "$backuplevel" = "daglig" ] || [ "$backuplevel" = "incremental" ]
108  then
109   lastd=`cat ../.date`
110   lastcmd="--newer='$lastd'"
111  else
112   lastcmd=""
113  fi
114
115  # expand the exclude-path for use with tar
116  exf=`ssh root@$computer "ls ~/.backup/exclude"`
117
118  # We try to run tar on the remote computer
119  #    z gzip it
120  #    c create archive
121  #    C change to directory first
122  #    . where to start taring (see C)
123  #    $lastcmd only files newer than this
124  #    --one-file-system don't traverse file systems
125  #    --exclude-from file to get exclusion pattern from
126  #    Pipe the stuff over ssh to ourselves, run pee to cat the contents to a
127  #    file and build a file list, respectivly.  
128  TARFILE=$DATE.tmp
129  TARCMD="ssh root@$computer \"nice -n 19 ionice -c3 tar --one-file-system -zcf - -C $filesystem . $lastcmd \
130         --exclude-from=$exf\" | pee \"cat > $TARFILE\" \"tar tzvf -\""
131  echo `date`" $computer: Running $TARCMD" >&2
132  eval $TARCMD > $DATE.idx
133
134  if [ -s $TARFILE ]; then
135   # File is >0 in size, we assume it worked.
136
137   # Move tar file in place
138   mv $TARFILE $DATE.tgz
139
140   # Update timestamp
141   echo $DATEs > ../.date && touch -t $DATE ../.date
142
143   # Make a sorted filelist as well
144   sort -k6 < $DATE.idx > $DATE.sdx
145
146   # Fix permissions
147   chmod 600 *tgz                      #only for us
148   chmod 644 *sdx *idx 2>/dev/null     #everyone can read
149
150   # Let the remote computer know that we ran a successful backup (for nagios)
151   ssh root@$computer touch $filesystem/.lastbackup
152
153  else
154   # Something wrong happened.
155   rm $TARFILE
156   echo `date`" $computer: $TARFILE empty. $backuplevel backup of $computer:$filesystem failed and deleted"
157
158   # We don't want to return 0
159   R=1
160  fi
161
162 }
163
164 for computer in $unixcomputers
165 do
166
167  # Check that the target filesystem is mounted (actually check that it's not
168  # the root filesystem)
169  rootfilesystem=`df -P /`
170  targetfilesystem=`df -P "$storagedir/$computer"`
171  if [ "$rootfilesystem" == "$targetfilesystem" ]; then
172         echo `date`" $computer: Target filesystem ($storagedir/$computer) was mounted on /. Aborting"
173         continue
174  fi
175
176  echo `date`" $computer: Backing up $computer" >&2
177
178  # Try to SSH to the computer without entering a password.
179  if ! `ssh -n -o NumberOfPasswordPrompts=0 root@$computer /bin/true`; then
180   echo `date`" $computer: Could not use passwordless SSH."
181
182   # We don't want to return 0
183   R=1
184   # Do next computer
185   continue;
186  fi
187  
188  filesystems=""
189
190  # Check dump bit in fstab
191  filesystems=`ssh -n root@$computer "cat /etc/fstab" \
192   | grep -v nfs \
193   | grep -v "^#" \
194   | grep -v "^$" \
195   | awk '{ if ( $(NF-1) != "0" ) print $2}' `
196
197  # Clean up our dir at this client
198  if ! ssh root@$computer "rm -r ~/.backup ; mkdir -m 700 ~/.backup"; then
199   echo `date`" $computer: Could not create backup staging area at $computer:~/.backup - skipping backup of $computer"
200   R=1
201   continue;
202  fi
203
204  # Try to copy $exclude to $computer
205  if ! scp $exclude root@$computer:~/.backup/exclude > /dev/null; then
206   echo `date`" $computer: Could not copy exclude.txt to $computer - skipping backup of $computer"
207   R=1
208   continue;
209  fi
210
211  # Try to copy preeexec and postexec if they exist
212  if [ -f $confdir/preexec.$computer ]; then
213    if ! scp $confdir/preexec.$computer  root@$computer:~/.backup/preexec >&2; then
214      echo `date`" $computer: Could not copy preexec.$computer to $computer:~/.backup/preexec - skipping backup of $computer"
215      R=1
216      continue
217    fi
218  fi
219  if [ -f $confdir/postexec.$computer ]; then
220    if ! scp $confdir/postexec.$computer root@$computer:~/.backup/postexec >&2; then
221      echo `date`" $computer: Could not copy postexec.$computer to $computer:~/.backup/postexec - skipping backup of $computer"
222      R=1
223      continue
224    fi
225  fi
226
227  # Try to run preexec if it exist
228  if ! ssh root@$computer "[ ! -f ~/.backup/preexec ] || /bin/bash -x ~/.backup/preexec" >&2; then
229         echo `date`" $computer: Could not run $computer:~/.backup/preexec - skipping backup of $computer"
230         R=1
231         continue
232  fi
233
234
235  for filesystem in $filesystems
236  do
237   # Remove / and $ (for Windows) for path names
238   sfilesystem=`echo $filesystem | tr '\/\$' '__'`
239
240   # Prepare storage area
241   mkdir -m 755 -p $storagedir/$computer/$sfilesystem/full 2>/dev/null
242   mkdir -m 755 -p $storagedir/$computer/$sfilesystem/daglig 2>/dev/null
243   echo $filesystem > ${storagedir}/${computer}/.${sfilesystem}.name 
244   chmod 644 ${storagedir}/${computer}/.${sfilesystem}.name
245
246   # Default backuplevel
247   backuplevel=daglig
248
249   if [ ! -f $storagedir/$computer/$sfilesystem/.date ]
250   then
251    # Take the first full backup of this filesystem on this computer
252    backuplevel=full
253    echo $DATEs > $storagedir/$computer/$sfilesystem/.date
254   fi
255
256   # Check if we want a full backup - Debug statement that causes noise in cron mail:
257   # printf " $computer $filesystem: $confdir/fastfullbackupdag.$computer.$sfilesystem\n"
258   if [ -f $confdir/fastfullbackupdag.$computer.$sfilesystem ]; then
259     fullbackup_min_for_this_machine=$dagermellomfulleforfast
260     if [ "$DAY_OF_MONTH" = "`cat $confdir/fastfullbackupdag.$computer.$sfilesystem`" ]; then
261       backuplevel=full
262     fi
263   elif [ -f $confdir/fastfullbackupdag.$computer ]; then
264     fullbackup_min_for_this_machine=$dagermellomfulleforfast
265     if [ "$DAY_OF_MONTH" = "`cat $confdir/fastfullbackupdag.$computer`" ]; then
266       backuplevel=full
267     fi
268   else
269     fullbackup_min_for_this_machine=$dagermellomfulle 
270   fi
271
272   if [ -z "`find $storagedir/$computer/$sfilesystem/full/ -name \*tgz -mtime -$fullbackup_min_for_this_machine`" ]; then
273    backuplevel=full
274   fi
275
276   # We want to be here
277   cd $storagedir/$computer/$sfilesystem/$backuplevel || die
278
279   # Perform the actual backup
280   backup
281
282   # Check if this box has a custom number of full backups
283   if [ -f $confdir/maksfulle.$computer ] ; then
284     mf=$((`cat $confdir/maksfulle.$computer`+1))
285   else
286     mf=$(($maksantallfulle+1))
287   fi
288
289   # Delete old full backups
290   for full in `ls -1t $storagedir/$computer/$sfilesystem/full/*tgz | tail -n +$mf`
291   do
292    prefix=`echo $full | sed "s/\.[^.]*$//"`
293    echo `date`": $computer:$filesystem Deleting full backup $prefix" >&2
294    rm $prefix*
295   done
296
297   # Delete incremental backups older than the oldest full backup
298   oldf=`ls -t1 $storagedir/$computer/$sfilesystem/full/*tgz | tail -1`
299   find \
300      $storagedir/$computer/$sfilesystem/daglig \
301      -type f \
302      \! -newer $oldf \
303      -printf "`date`: $computer: Deleting old incremental backup: %p\n" \
304      -exec rm {} \; >&2
305  done
306
307  # Try to run postexec if it exist
308  if ! ssh root@$computer "[ ! -f ~/.backup/postexec ] || /bin/bash -x ~/.backup/postexec" >&2; then
309         echo `date`" $computer: Could not run $computer:~/.backup/postexec"
310         R=1
311  fi
312
313 ) &
314 done
315
316 wait
317
318 # Remove lockfile
319 rm $LOCKFILE
320
321 # Did anything go wrong?
322 # (IMPORTANT NOTE: The R-business does not work as expected, since this script
323 # forks itself).
324 if [ $R != 0 ]; then
325         echo `date`": Backup run ended with errors, check logs."
326         exit 1
327 else
328         echo `date`": Backup run ended" >&2
329 fi