]> git.sesse.net Git - backup.sh/blob - backup.sh
Correct logic on evaluating and running {pre,post}exec
[backup.sh] / backup.sh
1 #!/bin/sh
2
3 # Locking
4 LOCKFILE=/home/backup/backuprun.lockfile
5
6 # Initially, we consider everything to be just fine.
7 R=0
8
9 # Die gracefully (ie. remove lockfile)
10 die() {
11         echo `date`": Something nasty happened, and since I fork a lot:"
12         echo `date`": I CANNOT CLEAN UP THE MESS MYSELF."
13         echo `date`": You need to get rid of lost process named stuff like $0, tar and ssh."
14         exit 255
15 }
16
17 # Trap C-c and kill
18 trap die SIGINT SIGTERM
19
20 # Don't start if we're already running
21 if [ -e $LOCKFILE ]; then
22         echo `date`": $LOCKFILE exists, exiting."
23         exit 1
24 fi;
25 touch $LOCKFILE
26
27 #dirs
28 confdir=/home/backup/conf/           #configuration files
29 storagedir=/backup                   #mountpoint of huge disc
30 ###
31
32 #exclude-pattern
33 exclude=$confdir/exclude
34 [ ! -f $exclude ] && printf "tmp\ncore\n" > $exclude
35 ###
36
37 #syntax of remotestat:
38 #hostname:/directory/
39 remotestatf=$confdir/remotestat
40 [ -f $remotestatf ] && remotestat=`cat $remotestatf`
41 ###
42
43 PATH=/local/bin:$PATH:/store/bin
44 export PATH
45
46 #start the logfile
47 echo `date`": Backup run starting" >&2
48
49 umask 027
50
51 # The computers we want to back up
52 unixcomputers=`cat $confdir/computers.unix \
53   | grep -v "^#" \
54   | grep -v "^$" `
55
56 # Backup only one computer, from command line?
57 if [ $1 ] ; then 
58   unixcomputers=$1
59 fi;
60
61 #disse bør kunne varieres fra fs til fs?
62 maksantallfulle=3          #hvor mange fulle vi tar vare på
63 dagermellomfulle=30        #antall dager før det er på tide med ny full
64 logw=40
65 ###
66
67 #lager datovariabeler
68 DATE=`date "+%Y%m%d%H%M"`            #format: touch
69 DATEs=`date "+%Y-%m-%d %H:%M"`       #format: tar
70 ###
71
72 #selve backupen
73 # krever at noen variabler er satt
74 # krever at vi er i rett katalog
75 backup()
76 {
77
78  echo -n `date` >&2
79  printf " $computer: %-${logw}s %s\n" "$computer:$filesystem" "$backuplevel backup" >&2
80
81  if [ "$backuplevel" = "daglig" ] || [ "$backuplevel" = "incremental" ]
82  then
83   lastd=`cat ../.date`
84   lastcmd="--newer='$lastd'"
85  else
86   lastcmd=""
87  fi
88
89  #if this client has a special tar
90  #we need to find a better solution to this conf-issue
91  if [ -f $confdir/tar.$computer ] ; then
92    tar=`cat $confdir/tar.$computer`
93  else 
94    tar=tar
95  fi
96
97  #expand the exclude-path for use with tar
98  exf=`ssh root@$computer "ls ~/.backup/exclude"`
99
100  #We try to run tar on the remote computer
101  #    z gzip it
102  #    c create archive
103  #    C change to directory first
104  #    - output to stdout (we pipe to gzip, then to dd)
105  #    . where to start taring (see C)
106  #    $lastcmd only files newer than this
107  #    --exclude-from file to get exclusion pattern from
108  #    pipe to gzip, which in turn pipes over the ssh-stream
109  #    ..to dd, to output to a file. We surpress messages from dd.
110  #    And at last, redirect stderr to stdout, to get output logged.
111  TARFILE=$DATE.tmp
112  TARCMD="ssh root@$computer \"$tar --one-file-system -zcf - -C $filesystem . $lastcmd \
113         --exclude-from=$exf\" > $TARFILE"
114  echo `date`" $computer: Running $TARCMD" >&2
115
116  if eval $TARCMD; then
117   mv $TARFILE $DATE.tgz
118   #make a filelist.
119   #update the datefile if the filelist is ok.
120   tar tvfz $DATE.tgz > $DATE.idx 2>&1 &&
121     echo $DATEs > ../.date            &&
122     touch -t $DATE ../.date
123
124   #make a sortet filelist
125   grep -v ^d $DATE.idx | sort -n -r +2 > $DATE.sdx
126
127   #fix perm
128   chmod 600 *tgz                      #only for us
129   chmod 644 *sdx *idx 2>/dev/null     #everyone can read
130
131  else
132   #it did not work
133   rm $TARFILE
134   echo `date`" $computer: $TARFILE empty. $backuplevel backup of $computer:$filesystem failed and deleted"
135
136   # We don't want to return 0
137   R=1
138  fi
139
140 }
141
142 #Løper gjennom listen av unixmaskiner som vi skal ta backup av
143 for computer in $unixcomputers
144 do
145
146  echo `date`" $computer: Backing up $computer" >&2
147
148  # Try to SSH to the computer without entering a password.
149  if ! `ssh -n -o NumberOfPasswordPrompts=0 root@$computer /bin/true`; then
150   echo `date`" $computer: Could not use passwordless SSH."
151
152   # We don't want to return 0
153   R=1
154   # Do next computer
155   continue;
156  fi
157  
158  #tømmer variabelen for sikkerhets skyld
159  filesystems=""
160
161  #Sjekker nest siste felt i fstab. Om det er 0 tar vi ikke backup
162  filesystems=`ssh -n root@$computer "cat /etc/fstab" \
163   | grep -v nfs \
164   | grep -v "^#" \
165   | grep -v "^$" \
166   | awk '{ if ( $(NF-1) != "0" ) print $2}' `
167
168  #clean up our dir at this client
169  if ! ssh root@$computer "rm -r ~/.backup ; mkdir -m 700 ~/.backup"; then
170   echo `date`" $computer: Could not create backup staging area at $computer:~/.backup - skipping backup of $computer"
171   # We don't want to return 0
172   R=1
173   continue;
174  fi
175
176  #try to copy $exclude to $computer
177  if ! scp $exclude root@$computer:~/.backup/exclude > /dev/null; then
178   echo `date`" $computer: Could not copy exclude.txt to $computer - skipping backup of $computer"
179   # We don't want to return 0
180   R=1
181   continue;
182  fi
183
184  #try to copy preeexec and postexec if they exist
185 # TODO: Gah, clean this mess!
186  [ -f $confdir/preexec.$computer ] && (
187     scp $confdir/preexec.$computer  root@$computer:~/.backup/preexec >&2 ||
188      ( echo `date`" $computer: Could not copy preexec.$computer to $computer:~/.backup/preexec - skipping backup of $computer"
189        R=1
190        continue
191      )
192     )
193  [ -f $confdir/postexec.$computer ] && (
194     scp $confdir/postexec.$computer root@$computer:~/.backup/postexec >&2 ||
195      ( echo `date`" $computer: Could not copy postexec.$computer to $computer:~/.backup/postexec - skipping backup of $computer"
196        R=1
197        continue
198      )
199     )
200
201  #try to run preexec if it exist
202  if ! ssh root@$computer "[ ! -f ~/.backup/preexec ] || /bin/bash -x ~/.backup/preexec" >&2; then
203         echo `date`" $computer: Could not run $computer:~/.backup/preexec - skipping backup of $computer"
204         R=1
205         continue
206  fi
207
208
209  for filesystem in $filesystems
210  do
211   #lager en variant uten tegnet "/" eller $ (gjelder NT)
212   sfilesystem=`echo $filesystem | tr '\/\$' '__'`
213
214   #lager det som trengs av kataloger
215   mkdir -m 755 -p $storagedir/$computer/$sfilesystem/{full,daglig} 2>/dev/null
216
217   echo $filesystem > ${storagedir}/${computer}/.${sfilesystem}.name 
218   chmod 644 ${storagedir}/${computer}/.${sfilesystem}.name
219
220   #set default backuplevel
221   backuplevel=daglig
222
223   if [ ! -f $storagedir/$computer/$sfilesystem/.date ]
224   then
225    #take the first full backup of this filesystem on this computer
226    backuplevel=full
227    echo $DATEs > $storagedir/$computer/$sfilesystem/.date
228   fi
229
230   #sjekker om det er på tide med en full
231   if [ -z "`find $storagedir/$computer/$sfilesystem/full/ -name \*tgz -mtime -$dagermellomfulle`" ]; then
232    backuplevel=full
233   fi
234  
235   #gå ned i rett katalog, eller dø 
236   # TODO bør sende mail om dette skjer!
237   cd $storagedir/$computer/$sfilesystem/$backuplevel || die
238
239   #perform the actual backup
240   backup
241
242   # Sjekk om det skal være et annet antall fulle backuper av en boks
243   if [ -f $confdir/maksfulle.$computer ] ; then
244     mf=$((`cat $confdir/maksfulle.$computer`+1))
245   else
246     mf=$(($maksantallfulle+1))
247   fi
248
249   #delete complete backups
250   for full in `ls -1t $storagedir/$computer/$sfilesystem/full/*tgz | tail +$mf`
251   do
252    prefix=`echo $full | sed "s/\.[^.]*$//"`
253    echo `date`": $computer:$filesystem sletter full $prefix (for mange)" >&2
254    rm $prefix*
255   done
256
257   #delete incremental backups older than the oldest complete backup
258   oldf=`ls -t1 $storagedir/$computer/$sfilesystem/full/*tgz | tail -1`
259   find \
260      $storagedir/$computer/$sfilesystem/daglig \
261      -type f \
262      \! -newer $oldf \
263      -exec rm {} \;
264  done
265
266  #try to run postexec if it exist
267  if ! ssh root@$computer "[ ! -f ~/.backup/postexec ] || /bin/bash -x ~/.backup/postexec" >&2; then
268         echo `date`" $computer: Could not run $computer:~/.backup/postexec"
269         R=1
270  fi
271
272 )  
273 done &
274
275 wait
276
277 # Remove lockfile
278 rm $LOCKFILE
279
280 # Did anything go wrong?
281 # (IMPORTANT NOTE: The R-business does not work as expected, since this script
282 # forks itself.
283 if [ $R != 0 ]; then
284         echo `date`": Backup run ended with errors, check logs."
285         exit 1
286 else
287         echo `date`": Backup run ended" >&2
288 fi