. make maildir helper look in every subdirectory of the source directory for
[matthijs/upstream/backupninja.git] / handlers / maildir.in
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 #  Hardlinking is used to save storage space.
9
10 #  This handler expects that your maildir directory structure is
11 #  either one of the following:
12
13 #  1. /$srcdir/[a-zA-Z0-9]/$user for example: 
14 #  /var/maildir/a/anarchist
15 #  /var/maildir/a/arthur
16 #  ...
17 #  /var/maildir/Z/Zaphod
18 #  /var/maildir/Z/Zebra
19 #  
20 #  2. or the following:
21 #  /var/maildir/domain.org/user1
22 #  /var/maildir/domain.org/user2
23 #  ...
24 #  /var/maildir/anotherdomain.org/user1
25 #  /var/maildir/anotherdomain.org/user2
26 #  ...
27 #
28 #  if the configuration is setup to have keepdaily at 3, 
29 #  keepweekly is 2, and keepmonthly is 1, then each user's
30 #  maildir backup snapshot directory will contain these files:
31 #    daily.1
32 #    daily.2
33 #    daily.3
34 #    weekly.1
35 #    weekly.2
36 #    monthly.1
37 #
38 #  The basic algorithm is to rsync each maildir individually,
39 #  and to use hard links for retaining historical data.
40 #
41 #  We handle each maildir individually because it becomes very
42 #  unweldy to hardlink and rsync many hundreds of thousands
43 #  of files at once. It is much faster to take on smaller
44 #  chunks at a time. 
45 #
46 #  For the backup rotation to work, destuser must be able to run 
47 #  arbitrary bash commands on the desthost.
48 #
49 #  Any maildir which is deleted from the source will be moved to
50 #  "deleted" directory in the destination. It is up to you to 
51 #  periodically remove this directory or old maildirs in it.
52
53 ##############################################################
54
55 getconf rotate yes
56 getconf remove yes
57 getconf backup yes
58
59 getconf loadlimit 5
60 getconf speedlimit 0
61 getconf keepdaily 5
62 getconf keepweekly 3
63 getconf keepmonthly 1
64
65 getconf srcdir /var/maildir
66 getconf destdir
67 getconf desthost
68 getconf destport 22
69 getconf destuser
70 getconf destid_file /root/.ssh/id_rsa
71
72 getconf multiconnection notset
73
74 failedcount=0
75 # strip trailing /
76 destdir=${destdir%/}
77 srcdir=${srcdir%/}
78
79 [ -d $srcdir ] || fatal "source directory $srcdir doesn't exist"
80
81 [ "$multiconnection" == "notset" ] && fatal "The maildir handler uses a very different destination format. See the example .maildir for more information"
82
83 if [ $test ]; then
84    testflags="--dry-run -v"
85 fi
86
87 rsyncflags="$testflags -e 'ssh -p $destport -i $destid_file' -r -v --ignore-existing --delete --size-only --bwlimit=$speedlimit"
88 excludes="--exclude '.Trash/\*' --exclude '.Mistakes/\*' --exclude '.Spam/\*'"
89
90 ##################################################################
91 ### FUNCTIONS
92
93 function do_user() {
94         local user=$1
95         local btype=$2
96         local userdir=${3%/}
97         local source="$srcdir/$userdir/$user/"
98         local target="$destdir/$userdir/$user/$btype.1"
99         if [ ! -d $source ]; then
100           warning "maildir $source not found"
101           return
102     fi
103
104         debug "syncing"
105         ret=`$RSYNC -e "ssh -p $destport -i $destid_file" -r \
106                 --links --ignore-existing --delete --size-only --bwlimit=$speedlimit \
107                 --exclude '.Trash/*' --exclude '.Mistakes/*' --exclude '.Spam/*' \
108                 $source $destuser@$desthost:$target \
109                 2>&1`
110         ret=$?
111         # ignore 0 (success) and 24 (file vanished before it could be copied)
112         if [ $ret != 0 -a $ret != 24 ]; then
113                 warning "rsync $user failed"
114                 warning "  returned: $ret"
115                 let "failedcount = failedcount + 1"
116                 if [ $failedcount -gt 100 ]; then
117                         fatal "100 rsync errors -- something is not working right. bailing out."
118                 fi
119         fi
120         ssh -o PasswordAuthentication=no $desthost -l $destuser -i $destid_file "date +%c%n%s > $target/created"
121 }
122
123 # remove any maildirs from backup which might have been deleted
124 # and add new ones which have just been created.
125 # (actually, it just moved them to the directory "deleted")
126
127 function do_remove() {
128         local tmp1=`maketemp maildir-tmp-file`
129         local tmp2=`maketemp maildir-tmp-file`
130         
131         ssh -p $destport -i $destid_file $destuser@$desthost mkdir -p "$destdir/deleted"
132         cd "$srcdir" 
133         for userdir in `ls -d1 */`; do
134            ls -1 "$srcdir/$userdir" | sort > $tmp1
135            ssh -p $destport $destuser@$desthost ls -1 "$destdir/$userdir" | sort > $tmp2
136                 for deluser in `join -v 2 $tmp1 $tmp2`; do
137                         [ "$deluser" != "" ] || continue
138                         info "removing $destuser@$desthost:$destdir/$userdir$deluser/"
139                         ssh -p $destport $destuser@$desthost mv "$destdir/$userdir$deluser/" "$destdir/deleted"
140                         ssh -p $destport -i $destid_file $destuser@$desthost "date +%c%n%s > '$destdir/$userdir$deluser/deleted_on'"
141                 done
142         done
143         rm $tmp1
144         rm $tmp2
145 }
146
147 function do_rotate() {
148         [ "$rotate" == "yes" ] || return;
149         local user=$1
150         local userdir=${2%/}
151         local backuproot="$destdir/$userdir/$user"
152 (
153         ssh -T -o PasswordAuthentication=no $desthost -l $destuser -i $destid_file <<EOF
154 ##### BEGIN REMOTE SCRIPT #####
155         seconds_daily=86400
156         seconds_weekly=604800
157         seconds_monthly=2628000
158         keepdaily=$keepdaily
159         keepweekly=$keepweekly
160         keepmonthly=$keepmonthly
161         now=\`date +%s\`
162
163         if [ ! -d "$backuproot" ]; then
164                 echo "Debug: skipping rotate of $user. $backuproot doesn't exist."
165                 exit
166         fi
167         for rottype in daily weekly monthly; do
168                 seconds=\$((seconds_\${rottype}))
169
170                 dir="$backuproot/\$rottype"
171                 if [ ! -d \$dir.1 ]; then
172                         echo "Debug: \$dir.1 does not exist, skipping."
173                         continue 1
174                 elif [ ! -f \$dir.1/created ]; then
175                         echo "Warning: \$dir.1/created does not exist. This backup may be only partially completed. Skipping rotation."
176                         continue 1
177                 fi
178                 
179                 # Rotate the current list of backups, if we can.
180                 oldest=\`find $backuproot -maxdepth 1 -type d -name \$rottype'.*' | @SED@ 's/^.*\.//' | sort -n | tail -1\`
181                 #echo "Debug: oldest \$oldest"
182                 [ "\$oldest" == "" ] && oldest=0
183                 for (( i=\$oldest; i > 0; i-- )); do
184                         if [ -d \$dir.\$i ]; then
185                                 if [ -f \$dir.\$i/created ]; then
186                                         created=\`tail -1 \$dir.\$i/created\`
187                                 else
188                                         created=0
189                                 fi
190                                 cutoff_time=\$(( now - (seconds*(i-1)) ))
191                                 if [ ! \$created -gt \$cutoff_time ]; then
192                                         next=\$(( i + 1 ))
193                                         if [ ! -d \$dir.\$next ]; then
194                                                 echo "Debug: \$rottype.\$i --> \$rottype.\$next"
195                                                 mv \$dir.\$i \$dir.\$next
196                                                 date +%c%n%s > \$dir.\$next/rotated
197                                         else
198                                                 echo "Debug: skipping rotation of \$dir.\$i because \$dir.\$next already exists."
199                                         fi
200                                 else
201                                         echo "Debug: skipping rotation of \$dir.\$i because it was created" \$(( (now-created)/86400)) "days ago ("\$(( (now-cutoff_time)/86400))" needed)."
202                                 fi
203                         fi
204                 done
205         done
206
207         max=\$((keepdaily+1))
208         if [ \( \$keepweekly -gt 0 -a -d $backuproot/daily.\$max \) -a ! -d $backuproot/weekly.1 ]; then
209                 echo "Debug: daily.\$max --> weekly.1"
210                 mv $backuproot/daily.\$max $backuproot/weekly.1
211                 date +%c%n%s > $backuproot/weekly.1/rotated
212         fi
213
214         max=\$((keepweekly+1))
215         if [ \( \$keepmonthly -gt 0 -a -d $backuproot/weekly.\$max \) -a ! -d $backuproot/monthly.1 ]; then
216                 echo "Debug: weekly.\$max --> monthly.1"
217                 mv $backuproot/weekly.\$max $backuproot/monthly.1
218                 date +%c%n%s > $backuproot/monthly.1/rotated
219         fi
220
221         for rottype in daily weekly monthly; do
222                 max=\$((keep\${rottype}+1))
223                 dir="$backuproot/\$rottype"
224                 oldest=\`find $backuproot -maxdepth 1 -type d -name \$rottype'.*' | @SED@ 's/^.*\.//' | sort -n | tail -1\`
225                 [ "\$oldest" == "" ] && oldest=0 
226                 # if we've rotated the last backup off the stack, remove it.
227                 for (( i=\$oldest; i >= \$max; i-- )); do
228                         if [ -d \$dir.\$i ]; then
229                                 if [ -d $backuproot/rotate.tmp ]; then
230                                         echo "Debug: removing rotate.tmp"
231                                         rm -rf $backuproot/rotate.tmp
232                                 fi
233                                 echo "Debug: moving \$rottype.\$i to rotate.tmp"
234                                 mv \$dir.\$i $backuproot/rotate.tmp
235                         fi
236                 done
237         done
238 ####### END REMOTE SCRIPT #######
239 EOF
240 ) | (while read a; do passthru $a; done)
241
242 }
243
244
245 function setup_remote_dirs() {
246         local user=$1
247         local backuptype=$2
248         local userdir=${3%/}
249         local dir="$destdir/$userdir/$user/$backuptype"
250         local tmpdir="$destdir/$userdir/$user/rotate.tmp"
251 (
252         ssh -T -o PasswordAuthentication=no $desthost -l $destuser -i $destid_file <<EOF
253                 if [ ! -d $destdir ]; then
254                         echo "Fatal: Destination directory $destdir does not exist on host $desthost."
255                         exit 1
256                 elif [ -d $dir.1 ]; then
257                         if [ -f $dir.1/created ]; then
258                                 echo "Warning: $dir.1 already exists. Overwriting contents."
259                         else
260                                 echo "Warning: we seem to be resuming a partially written $dir.1"
261                         fi
262                 else
263                         if [ -d $tmpdir ]; then
264                                 mv $tmpdir $dir.1
265                                 if [ \$? == 1 ]; then
266                                         echo "Fatal: could mv $destdir/rotate.tmp $dir.1 on host $desthost"
267                                         exit 1
268                                 fi
269                         else
270                                 mkdir --parents $dir.1
271                                 if [ \$? == 1 ]; then
272                                         echo "Fatal: could not create directory $dir.1 on host $desthost"
273                                         exit 1
274                                 fi
275                         fi
276                         if [ -d $dir.2 ]; then
277                                 echo "Debug: update links $backuptype.2 --> $backuptype.1"
278                                 cp -alf $dir.2/. $dir.1
279                                 #if [ \$? == 1 ]; then
280                                 #       echo "Fatal: could not create hard links to $dir.1 on host $desthost"
281                                 #       exit 1
282                                 #fi
283                         fi
284                 fi
285                 [ -f $dir.1/created ] && rm $dir.1/created
286                 [ -f $dir.1/rotated ] && rm $dir.1/rotated
287                 exit 0
288 EOF
289 ) | (while read a; do passthru $a; done)
290
291         if [ $? == 1 ]; then exit; fi
292 }
293
294 function start_mux() {
295         if [ "$multiconnection" == "yes" ]; then
296                 debug "Starting dummy ssh connection"
297                 ssh -p $destport -i $destid_file $destuser@$desthost sleep 1d &
298         sleep 1
299         fi
300 }
301
302 function end_mux() {
303         if [ "$multiconnection" == "yes" ]; then
304                 debug "Stopping dummy ssh connection"
305                 ssh -p $destport -i $destid_file $destuser@$desthost pkill sleep
306         fi
307 }
308
309 ###
310 ##################################################################
311
312 # see if we can login
313 debug "ssh -o PasswordAuthentication=no $desthost -l $destuser -i $destid_file 'echo -n 1'"
314 if [ ! $test ]; then
315         result=`ssh -o PasswordAuthentication=no $desthost -l $destuser -i $destid_file 'echo -n 1' 2>&1`
316         if [ "$result" != "1" ]; then
317                 fatal "Can't connect to $desthost as $destuser using $destid_file."
318         fi
319 fi
320
321 end_mux
322 start_mux
323
324 ## SANITY CHECKS ##
325 status=`ssh -p $destport -i $destid_file $destuser@$desthost "[ -d \"$destdir\" ] && echo 'ok'"`
326 if [ "$status" != "ok" ]; then
327         end_mux
328         fatal "Destination directory $destdir doesn't exist!"
329     exit
330 fi
331
332 ### REMOVE OLD MAILDIRS ###
333
334 if [ "$remove" == "yes" ]; then
335         do_remove
336 fi
337
338 ### MAKE BACKUPS ###
339
340 if [ "$backup" == "yes" ]; then
341         if [ $keepdaily -gt 0 ]; then btype=daily
342         elif [ $keepweekly -gt 0 ]; then btype=weekly
343         elif [ $keepmonthly -gt 0 ]; then btype=monthly
344         else fatal "keeping no backups"; fi
345         
346         if [ "$testuser" != "" ]; then
347                 cd "$srcdir/${user:0:1}"
348                 do_rotate $testuser
349                 setup_remote_dirs $testuser $btype
350                 do_user $testuser $btype
351         else
352                 [ -d "$srcdir" ] || fatal "directory $srcdir not found."
353                 cd "$srcdir"
354                 for userdir in `ls -d1 */`; do
355                    [ -d "$srcdir/$userdir" ] || fatal "directory $srcdir/$userdir not found."
356                    cd "$srcdir/$userdir"
357                    debug $userdir
358                         for user in `ls -1`; do
359                                 [ "$user" != "" ] || continue
360                                 debug "$user $userdir"
361                                 do_rotate $user $userdir
362                                 setup_remote_dirs $user $btype $userdir
363                                 do_user $user $btype $userdir
364                         done
365                 done
366         fi
367 fi
368
369 end_mux
370