fix partitionsfile example to properly use __star__ and note
[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 #  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 # used for testing
62 #getconf testuser elijah
63
64 [ -d $srcdir ] || fatal "source directory $srcdir doesn't exist"
65
66 [ "$multiconnection" == "notset" ] && fatal "The maildir handler uses a very different destination format. See the example .maildir for more information"
67
68 [ ! $test ] || testflags="--dry-run -v"
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 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                 done
122         done
123         rm $tmp1
124         rm $tmp2
125 }
126
127 function do_rotate() {
128         [ "$rotate" == "yes" ] || return;
129         local user=$1
130         local letter=${user:0:1}
131         local backuproot="$destdir/$letter/$user"
132 (
133         ssh -T -o PasswordAuthentication=no $desthost -l $destuser <<EOF
134 ##### BEGIN REMOTE SCRIPT #####
135         seconds_daily=86400
136         seconds_weekly=604800
137         seconds_monthly=2628000
138         keepdaily=$keepdaily
139         keepweekly=$keepweekly
140         keepmonthly=$keepmonthly
141         now=\`date +%s\`
142
143         if [ ! -d "$backuproot" ]; then
144                 echo "Debug: skipping rotate of $user. $backuproot doesn't exist."
145                 exit
146         fi
147         for rottype in daily weekly monthly; do
148                 seconds=\$((seconds_\${rottype}))
149
150                 dir="$backuproot/\$rottype"
151                 if [ ! -d \$dir.1 ]; then
152                         echo "Debug: \$dir.1 does not exist, skipping."
153                         continue 1
154                 elif [ ! -f \$dir.1/created ]; then
155                         echo "Warning: \$dir.1/created does not exist. This backup may be only partially completed. Skipping rotation."
156                         continue 1
157                 fi
158                 
159                 # Rotate the current list of backups, if we can.
160                 oldest=\`find $backuproot -type d -maxdepth 1 -name \$rottype'.*' | @SED@ 's/^.*\.//' | sort -n | tail -1\`
161                 #echo "Debug: oldest \$oldest"
162                 [ "\$oldest" == "" ] && oldest=0
163                 for (( i=\$oldest; i > 0; i-- )); do
164                         if [ -d \$dir.\$i ]; then
165                                 if [ -f \$dir.\$i/created ]; then
166                                         created=\`tail -1 \$dir.\$i/created\`
167                                 else
168                                         created=0
169                                 fi
170                                 cutoff_time=\$(( now - (seconds*(i-1)) ))
171                                 if [ ! \$created -gt \$cutoff_time ]; then
172                                         next=\$(( i + 1 ))
173                                         if [ ! -d \$dir.\$next ]; then
174                                                 echo "Debug: \$rottype.\$i --> \$rottype.\$next"
175                                                 mv \$dir.\$i \$dir.\$next
176                                                 date +%c%n%s > \$dir.\$next/rotated
177                                         else
178                                                 echo "Debug: skipping rotation of \$dir.\$i because \$dir.\$next already exists."
179                                         fi
180                                 else
181                                         echo "Debug: skipping rotation of \$dir.\$i because it was created" \$(( (now-created)/86400)) "days ago ("\$(( (now-cutoff_time)/86400))" needed)."
182                                 fi
183                         fi
184                 done
185         done
186
187         max=\$((keepdaily+1))
188         if [ \( \$keepweekly -gt 0 -a -d $backuproot/daily.\$max \) -a ! -d $backuproot/weekly.1 ]; then
189                 echo "Debug: daily.\$max --> weekly.1"
190                 mv $backuproot/daily.\$max $backuproot/weekly.1
191                 date +%c%n%s > $backuproot/weekly.1/rotated
192         fi
193
194         max=\$((keepweekly+1))
195         if [ \( \$keepmonthly -gt 0 -a -d $backuproot/weekly.\$max \) -a ! -d $backuproot/monthly.1 ]; then
196                 echo "Debug: weekly.\$max --> monthly.1"
197                 mv $backuproot/weekly.\$max $backuproot/monthly.1
198                 date +%c%n%s > $backuproot/monthly.1/rotated
199         fi
200
201         for rottype in daily weekly monthly; do
202                 max=\$((keep\${rottype}+1))
203                 dir="$backuproot/\$rottype"
204                 oldest=\`find $backuproot -type d -maxdepth 1 -name \$rottype'.*' | @SED@ 's/^.*\.//' | sort -n | tail -1\`
205                 [ "\$oldest" == "" ] && oldest=0 
206                 # if we've rotated the last backup off the stack, remove it.
207                 for (( i=\$oldest; i >= \$max; i-- )); do
208                         if [ -d \$dir.\$i ]; then
209                                 if [ -d $backuproot/rotate.tmp ]; then
210                                         echo "Debug: removing rotate.tmp"
211                                         rm -rf $backuproot/rotate.tmp
212                                 fi
213                                 echo "Debug: moving \$rottype.\$i to rotate.tmp"
214                                 mv \$dir.\$i $backuproot/rotate.tmp
215                         fi
216                 done
217         done
218 ####### END REMOTE SCRIPT #######
219 EOF
220 ) | (while read a; do passthru $a; done)
221
222 }
223
224
225 function setup_remote_dirs() {
226         local user=$1
227         local backuptype=$2
228         local letter=${user:0:1}
229         local dir="$destdir/$letter/$user/$backuptype"
230         local tmpdir="$destdir/$letter/$user/rotate.tmp"
231 (
232         ssh -T -o PasswordAuthentication=no $desthost -l $destuser <<EOF
233                 if [ ! -d $destdir ]; then
234                         echo "Fatal: Destination directory $destdir does not exist on host $desthost."
235                         exit 1
236                 elif [ -d $dir.1 ]; then
237                         if [ -f $dir.1/created ]; then
238                                 echo "Warning: $dir.1 already exists. Overwriting contents."
239                         else
240                                 echo "Warning: we seem to be resuming a partially written $dir.1"
241                         fi
242                 else
243                         if [ -d $tmpdir ]; then
244                                 mv $tmpdir $dir.1
245                                 if [ \$? == 1 ]; then
246                                         echo "Fatal: could mv $destdir/rotate.tmp $dir.1 on host $desthost"
247                                         exit 1
248                                 fi
249                         else
250                                 mkdir --parents $dir.1
251                                 if [ \$? == 1 ]; then
252                                         echo "Fatal: could not create directory $dir.1 on host $desthost"
253                                         exit 1
254                                 fi
255                         fi
256                         if [ -d $dir.2 ]; then
257                                 echo "Debug: update links $backuptype.2 --> $backuptype.1"
258                                 cp -alf $dir.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 function start_mux() {
275         if [ "$multiconnection" == "yes" ]; then
276                 debug "Starting dummy ssh connection"
277                 ssh -p $destport $destuser@$desthost sleep 1d &
278         sleep 1
279         fi
280 }
281
282 function end_mux() {
283         if [ "$multiconnection" == "yes" ]; then
284                 debug "Stopping dummy ssh connection"
285                 ssh -p $destport $destuser@$desthost pkill sleep
286         fi
287 }
288
289 ###
290 ##################################################################
291
292 # see if we can login
293 debug "ssh -o PasswordAuthentication=no $desthost -l $destuser 'echo -n 1'"
294 if [ ! $test ]; then
295         result=`ssh -o PasswordAuthentication=no $desthost -l $destuser 'echo -n 1' 2>&1`
296         if [ "$result" != "1" ]; then
297                 fatal "Can't connect to $desthost as $destuser."
298         fi
299 fi
300
301 end_mux
302 start_mux
303
304 ## SANITY CHECKS ##
305 status=`ssh -p $destport $destuser@$desthost "[ -d \"$destdir\" ] && echo 'ok'"`
306 if [ "$status" != "ok" ]; then
307         end_mux
308         fatal "Destination directory $destdir doesn't exist!"
309     exit
310 fi
311
312 ### REMOVE OLD MAILDIRS ###
313
314 if [ "$remove" == "yes" ]; then
315         do_remove
316 fi
317
318 ### MAKE BACKUPS ###
319
320 if [ "$backup" == "yes" ]; then
321         if [ $keepdaily -gt 0 ]; then btype=daily
322         elif [ $keepweekly -gt 0 ]; then btype=weekly
323         elif [ $keepmonthly -gt 0 ]; then btype=monthly
324         else fatal "keeping no backups"; fi
325         
326         if [ "$testuser" != "" ]; then
327                 cd "$srcdir/${user:0:1}"
328                 do_rotate $testuser
329                 setup_remote_dirs $testuser $btype
330                 do_user $testuser $btype
331         else
332                 for i in $letters; do
333                         [ -d "$srcdir/$i" ] || fatal "directory $srcdir/$i not found."
334                         cd "$srcdir/$i"
335                         debug $i
336                         for user in `ls -1`; do
337                                 [ "$user" != "" ] || continue
338                                 info $user
339                                 do_rotate $user
340                                 setup_remote_dirs $user $btype
341                                 do_user $user $btype
342                         done
343                 done
344         fi
345 fi
346
347 end_mux
348