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