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