Oops, adding ninjahelper to Makefile
[matthijs/upstream/backupninja.git] / handlers / maildir
1 # -*- mode: sh; sh-basic-offset: 3; indent-tabs-mode: nil; -*-
2
3 ###############################################################
4 #
5 #  This handler slowly creates a backup of each user's maildir
6 #  to a remote server. It is designed to be run with low overhead
7 #  in terms of cpu and bandwidth so it runs pretty slow.
8 #
9 #  if destdir is /backup/maildir/, then it will contain the files
10 #    daily.1
11 #    daily.2
12 #    daily.3
13 #    weekly.1
14 #    weekly.2
15 #    monthly.1
16 #  if keepdaily is 3, keepweekly is 2, and keepmonthly is 1. 
17 #
18 #  The basic algorithm is to rsync each maildir individually,
19 #  and to use hard links for retaining historical data.
20 #
21 #  We rsync each maildir individually because it becomes very
22 #  unweldy to start a single rsync of many hundreds of thousands
23 #  of files. 
24 #
25 #  For the backup rotation to work, destuser must be able to run 
26 #  arbitrary bash commands on the desthost.
27 #
28 ##############################################################
29
30 getconf rotate yes
31 getconf remove yes
32
33 getconf loadlimit 5
34 getconf speedlimit 0
35 getconf keepdaily 5
36 getconf keepweekly 3
37 getconf keepmonthly 1
38
39 getconf srcdir /var/maildir
40 getconf destdir
41 getconf desthost
42 getconf destport 22
43 getconf destuser
44
45 failedcount=0
46
47 # strip trailing /
48 destdir=${destdir%/}
49 srcdir=${srcdir%/}
50
51 # used for testing
52 #getconf letter
53 #getconf testuser elijah
54 getconf backup yes
55 #letters=e
56 letters="a b c d e f g h i j k l m n o p q r s t u v w x y z"
57
58 [ -d $srcdir ] || fatal "source directory $srcdir doesn't exist"
59
60 [ ! $test ] || testflags="--dry-run -v"
61 rsyncflags="$testflags -e 'ssh -p $destport' -r -v --ignore-existing --delete --size-only --bwlimit=$speedlimit"
62 excludes="--exclude '.Trash/\*' --exclude '.Mistakes/\*' --exclude '.Spam/\*'"
63
64 # see if we can login
65 debug "ssh -o PasswordAuthentication=no $desthost -l $destuser 'echo -n 1'"
66 if [ ! $test ]; then
67         result=`ssh -o PasswordAuthentication=no $desthost -l $destuser 'echo -n 1' 2>&1`
68         if [ "$result" != "1" ]; then
69                 fatal "Can't connect to $desthost as $destuser."
70         fi
71 fi
72
73 ##################################################################
74 ### FUNCTIONS
75
76 function do_user() {
77         local user=$1
78         local destdir=$2
79         local letter=${user:0:1}
80         local dir="$srcdir/$letter/$user"
81         [ -d $dir ] || fatal "maildir $dir not found".
82
83 #       while true; do
84 #               load=`uptime | sed 's/^.*load average: \\([^,]*\\).*$/\\1/'`
85 #               over=`expr $load \> $loadlimit`
86 #               if [ $over == 1 ]; then
87 #                       info "load $load, sleeping..."
88 #                       sleep 600
89 #               else
90 #                       break
91 #               fi
92 #       done
93         
94         cmd="$RSYNC $rsyncflags $excludes $dir $destuser@$desthost:$destdir/$letter"
95         ret=`rsync -e "ssh -p $destport" -r \
96 --links --ignore-existing --delete --size-only --bwlimit=$speedlimit \
97 --exclude '.Trash/*' --exclude '.Mistakes/*' --exclude '.Spam/*' \
98 $dir $destuser@$desthost:$destdir/$letter \
99 2>&1`
100         ret=$?
101         # ignore 0 (success) and 24 (file vanished before it could be copied)
102         if [ $ret != 0 -a $ret != 24 ]; then
103                 warning "rsync $user failed"
104                 warning "  returned: $ret"
105                 let "failedcount = failedcount + 1"
106                 if [ $failedcount -gt 100 ]; then
107                         fatal "100 rsync errors -- something is not working right. bailing out."
108                 fi
109         fi
110 }
111
112 # remove any maildirs from backup which might have been deleted
113 # and add new ones which have just been created.
114
115 function do_remove() {
116         local tmp1=`maketemp maildir-tmp-file`
117         local tmp2=`maketemp maildir-tmp-file`
118         
119         for i in a b c d e f g h i j k l m n o p q r s t u v w x y z; do
120                 ls -1 "$srcdir/$i" | sort > $tmp1
121                 ssh -p $destport $desthost ls -1 '$destdir/maildir/$i' | sort > $tmp2
122                 for deluser in `join -v 2 $tmp1 $tmp2`; do
123                         cmd="ssh -p $destport $desthost rm -vr '$destdir/maildir/$i/$deluser/'"
124                         debug $cmd
125                 done
126         done
127         rm $tmp1
128         rm $tmp2        
129 }
130
131 function do_rotate() {
132         backuproot=$destdir
133
134 (
135         debug Connecting to $desthost
136         ssh -T -o PasswordAuthentication=no $desthost -l $destuser <<EOF
137 ##### BEGIN REMOTE SCRIPT #####
138         seconds_daily=86400
139         seconds_weekly=604800
140         seconds_monthly=2628000
141         keepdaily=$keepdaily
142         keepweekly=$keepweekly
143         keepmonthly=$keepmonthly
144         now=\`date +%s\`
145
146         for rottype in daily weekly monthly; do
147                 seconds=\$((seconds_\${rottype}))
148
149                 dir="$backuproot/\$rottype"
150                 if [ ! -d \$dir.1 ]; then
151                         echo "Info: \$dir.1 does not exist. This backup is missing, so we are skipping the rotation."
152                         continue 1
153                 elif [ ! -f \$dir.1/created ]; then
154                         echo "Warning: \$dir.1/created does not exist. This backup may be only partially completed. Skipping rotation."
155                         continue 1
156                 fi
157                 
158                 # Rotate the current list of backups, if we can.
159                 oldest=\`find $backuproot -type d -maxdepth 1 -name \$rottype'.*' | sed 's/^.*\.//' | sort -n | tail -1\`
160                 echo "Debug: oldest \$oldest"
161                 [ "\$oldest" == "" ] && oldest=0
162                 for (( i=\$oldest; i > 0; i-- )); do
163                         if [ -d \$dir.\$i ]; then
164                                 if [ -f \$dir.\$i/created ]; then
165                                         created=\`tail -1 \$dir.\$i/created\`
166                                 else
167                                         created=0
168                                 fi
169                                 cutoff_time=\$(( now - (seconds*(i-1)) ))
170                                 if [ ! \$created -gt \$cutoff_time ]; then
171                                         next=\$(( i + 1 ))
172                                         if [ ! -d \$dir.\$next ]; then
173                                                 echo "Debug: mv \$dir.\$i \$dir.\$next"
174                                                 mv \$dir.\$i \$dir.\$next
175                                                 date +%c%n%s > \$dir.\$next/rotated
176                                         else
177                                                 echo "Info: skipping rotation of \$dir.\$i because \$dir.\$next already exists."
178                                         fi
179                                 else
180                                         echo "Info: skipping rotation of \$dir.\$i because it was created" \$(( (now-created)/86400)) "days ago ("\$(( (now-cutoff_time)/86400))" needed)."
181                                 fi
182                         fi
183                 done
184         done
185
186         max=\$((keepdaily+1))
187         if [ \( \$keepweekly -gt 0 -a -d $backuproot/daily.\$max \) -a ! -d $backuproot/weekly.1 ]; then
188                 echo mv $backuproot/daily.\$max $backuproot/weekly.1
189                 mv $backuproot/daily.\$max $backuproot/weekly.1
190                 date +%c%n%s > $backuproot/weekly.1/rotated
191         fi
192
193         max=\$((keepweekly+1))
194         if [ \( \$keepmonthly -gt 0 -a -d $backuproot/weekly.\$max \) -a ! -d $backuproot/monthly.1 ]; then
195                 echo mv $backuproot/weekly.\$max $backuproot/monthly.1
196                 mv $backuproot/weekly.\$max $backuproot/monthly.1
197                 date +%c%n%s > $backuproot/monthly.1/rotated
198         fi
199
200         for rottype in daily weekly monthly; do
201                 max=\$((keep\${rottype}+1))
202                 dir="$backuproot/\$rottype"
203                 oldest=\`find $backuproot -type d -maxdepth 1 -name \$rottype'.*' | sed 's/^.*\.//' | sort -n | tail -1\`
204                 [ "\$oldest" == "" ] && oldest=0 
205                 # if we've rotated the last backup off the stack, remove it.
206                 for (( i=\$oldest; i >= \$max; i-- )); do
207                         if [ -d \$dir.\$i ]; then
208                                 if [ -d $backuproot/rotate.tmp ]; then
209                                         echo "Info: removing $backuproot/rotate.tmp"
210                                         rm -rf $backuproot/rotate.tmp
211                                 fi
212                                 echo "Info: moving \$dir.\$i to $backuproot/rotate.tmp"
213                                 mv \$dir.\$i $backuproot/rotate.tmp
214                         fi
215                 done
216         done
217 ####### END REMOTE SCRIPT #######
218 EOF
219 ) | (while read a; do passthru $a; done)
220
221 }
222
223
224 function setup_remote_dirs() {
225         local backuptype=$1
226         local dir="$destdir/$backuptype"
227
228 (
229         ssh -T -o PasswordAuthentication=no $desthost -l $destuser <<EOF
230                 if [ ! -d $destdir ]; then
231                         echo "Fatal: Destination directory $destdir does not exist on host $desthost."
232                         exit 1
233                 elif [ -d $dir.1 ]; then
234                         if [ -f $dir.1/created ]; then
235                                 echo "Warning: $dir.1 already exists. Overwriting contents."
236                         else
237                                 echo "Warning: we seem to be resuming a partially written $dir.1"
238                         fi
239                 else
240                         if [ -d $destdir/rotate.tmp ]; then
241                                 mv $destdir/rotate.tmp $dir.1
242                                 if [ \$? == 1 ]; then
243                                         echo "Fatal: could mv $destdir/rotate.tmp $dir.1 on host $desthost"
244                                         exit 1
245                                 fi
246                         else
247                                 mkdir $dir.1
248                                 if [ \$? == 1 ]; then
249                                         echo "Fatal: could not create directory $dir.1 on host $desthost"
250                                         exit 1
251                                 fi
252                                 for i in a b c d e f g h i j k l m n o p q r s t u v w y x z; do
253                                         mkdir $dir.1/\$i
254                                 done
255                         fi
256                         if [ -d $destdir/$backuptype.2 ]; then
257                                 echo "Info: updating hard links to $dir.1. This may take a while."
258                                 cp -alf $destdir/$backuptype.2/. $dir.1
259                                 #if [ \$? == 1 ]; then
260                                 #       echo "Fatal: could not create hard links to $dir.1 on host $desthost"
261                                 #       exit 1
262                                 #fi
263                         fi
264                 fi
265                 [ -f $dir.1/created ] && rm $dir.1/created
266                 [ -f $dir.1/rotated ] && rm $dir.1/rotated
267                 exit 0
268 EOF
269 ) | (while read a; do passthru $a; done)
270
271         if [ $? == 1 ]; then exit; fi
272 }
273
274 ###
275 ##################################################################
276
277 ### ROTATE BACKUPS ###
278
279 if [ "$rotate" == "yes" ]; then
280         do_rotate
281 fi
282
283 ### REMOVE OLD MAILDIRS ###
284
285 if [ "$remove" == "yes" ]; then
286         debug remove
287 fi
288
289 ### MAKE BACKUPS ###
290
291 if [ "$backup" == "yes" ]; then
292         if [ $keepdaily -gt 0 ]; then btype=daily
293         elif [ $keepweekly -gt 0 ]; then btype=weekly
294         elif [ $keepmonthly -gt 0 ]; then btype=monthly
295         else fatal "keeping no backups"; fi
296
297         setup_remote_dirs $btype
298         
299         for i in $letters; do
300                 [ -d "$srcdir/$i" ] || fatal "directory $srcdir/$i not found."
301                 cd "$srcdir/$i"
302                 debug $i
303                 for user in `ls -1`; do
304                         if [ "$testuser" != "" -a "$testuser" != "$user" ]; then continue; fi
305                         do_user $user $destdir/$btype.1
306                 done
307         done
308
309         ssh -o PasswordAuthentication=no $desthost -l $destuser "date +%c%n%s > $destdir/$btype.1/created"
310 fi