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