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