* On the phase 2 retry pass with rsync, verify the cached checksums
[BackupPC.git] / lib / BackupPC / Xfer / Rsync.pm
1 #============================================================= -*-perl-*-
2 #
3 # BackupPC::Xfer::Rsync package
4 #
5 # DESCRIPTION
6 #
7 #   This library defines a BackupPC::Xfer::Rsync class for managing
8 #   the rsync-based transport of backup data from the client.
9 #
10 # AUTHOR
11 #   Craig Barratt  <cbarratt@users.sourceforge.net>
12 #
13 # COPYRIGHT
14 #   Copyright (C) 2002-2003  Craig Barratt
15 #
16 #   This program is free software; you can redistribute it and/or modify
17 #   it under the terms of the GNU General Public License as published by
18 #   the Free Software Foundation; either version 2 of the License, or
19 #   (at your option) any later version.
20 #
21 #   This program is distributed in the hope that it will be useful,
22 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
23 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 #   GNU General Public License for more details.
25 #
26 #   You should have received a copy of the GNU General Public License
27 #   along with this program; if not, write to the Free Software
28 #   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
29 #
30 #========================================================================
31 #
32 # Version 2.1.0beta2, released 9 May 2004.
33 #
34 # See http://backuppc.sourceforge.net.
35 #
36 #========================================================================
37
38 package BackupPC::Xfer::Rsync;
39
40 use strict;
41 use BackupPC::View;
42 use BackupPC::Xfer::RsyncFileIO;
43
44 use vars qw( $RsyncLibOK $RsyncLibErr );
45
46 BEGIN {
47     eval "use File::RsyncP;";
48     if ( $@ ) {
49         #
50         # Rsync module doesn't exist.
51         #
52         $RsyncLibOK = 0;
53         $RsyncLibErr = "File::RsyncP module doesn't exist";
54     } else {
55         #
56         # Note: also update configure.pl when this version number is changed!
57         #
58         if ( $File::RsyncP::VERSION < 0.51 ) {
59             $RsyncLibOK = 0;
60             $RsyncLibErr = "File::RsyncP module version too old: need 0.50";
61         } else {
62             $RsyncLibOK = 1;
63         }
64     }
65 };
66
67 sub new
68 {
69     my($class, $bpc, $args) = @_;
70
71     return if ( !$RsyncLibOK );
72     $args ||= {};
73     my $t = bless {
74         bpc       => $bpc,
75         conf      => { $bpc->Conf },
76         host      => "",
77         hostIP    => "",
78         shareName => "",
79         badFiles  => [],
80
81         #
82         # Various stats
83         #
84         byteCnt         => 0,
85         fileCnt         => 0,
86         xferErrCnt      => 0,
87         xferBadShareCnt => 0,
88         xferBadFileCnt  => 0,
89         xferOK          => 0,
90
91         #
92         # User's args
93         #
94         %$args,
95     }, $class;
96
97     return $t;
98 }
99
100 sub args
101 {
102     my($t, $args) = @_;
103
104     foreach my $arg ( keys(%$args) ) {
105         $t->{$arg} = $args->{$arg};
106     }
107 }
108
109 sub useTar
110 {
111     return 0;
112 }
113
114 sub start
115 {
116     my($t) = @_;
117     my $bpc = $t->{bpc};
118     my $conf = $t->{conf};
119     my(@fileList, $rsyncClientCmd, $rsyncArgs, $logMsg,
120        $incrDate, $argList, $fioArgs);
121
122     #
123     # We add a slash to the share name we pass to rsync
124     #
125     ($t->{shareNameSlash} = "$t->{shareName}/") =~ s{//+$}{/};
126
127     if ( $t->{type} eq "restore" ) {
128         $rsyncClientCmd = $conf->{RsyncClientRestoreCmd};
129         $rsyncArgs = $conf->{RsyncRestoreArgs};
130         my $remoteDir = "$t->{shareName}/$t->{pathHdrDest}";
131         $remoteDir    =~ s{//+}{/}g;
132         $argList = ['--server', @$rsyncArgs, '.', $remoteDir];
133         $fioArgs = {
134             client   => $t->{bkupSrcHost},
135             share    => $t->{bkupSrcShare},
136             viewNum  => $t->{bkupSrcNum},
137             fileList => $t->{fileList},
138         };
139         $logMsg = "restore started below directory $t->{shareName}"
140                 . " to host $t->{host}";
141     } else {
142         #
143         # Turn $conf->{BackupFilesOnly} and $conf->{BackupFilesExclude}
144         # into a hash of arrays of files.
145         #
146         $conf->{RsyncShareName} = [ $conf->{RsyncShareName} ]
147                         unless ref($conf->{RsyncShareName}) eq "ARRAY";
148         foreach my $param qw(BackupFilesOnly BackupFilesExclude) {
149             next if ( !defined($conf->{$param}) );
150             if ( ref($conf->{$param}) eq "ARRAY" ) {
151                 $conf->{$param} = {
152                         $conf->{RsyncShareName}[0] => $conf->{$param}
153                 };
154             } elsif ( ref($conf->{$param}) eq "HASH" ) {
155                 # do nothing
156             } else {
157                 $conf->{$param} = {
158                         $conf->{RsyncShareName}[0] => [ $conf->{$param} ]
159                 };
160             }
161         }
162         if ( defined($conf->{BackupFilesOnly}{$t->{shareName}}) ) {
163             my(@inc, @exc, %incDone, %excDone);
164             foreach my $file ( @{$conf->{BackupFilesOnly}{$t->{shareName}}} ) {
165                 #
166                 # If the user wants to just include /home/craig, then
167                 # we need to do create include/exclude pairs at
168                 # each level:
169                 #     --include /home --exclude /*
170                 #     --include /home/craig --exclude /home/*
171                 #
172                 # It's more complex if the user wants to include multiple
173                 # deep paths.  For example, if they want /home/craig and
174                 # /var/log, then we need this mouthfull:
175                 #     --include /home --include /var --exclude /*
176                 #     --include /home/craig --exclude /home/*
177                 #     --include /var/log --exclude /var/*
178                 #
179                 # To make this easier we do all the includes first and all
180                 # of the excludes at the end (hopefully they commute).
181                 #
182                 $file =~ s{/$}{};
183                 $file = "/$file";
184                 $file =~ s{//+}{/}g;
185                 if ( $file eq "/" ) {
186                     #
187                     # This is a special case: if the user specifies
188                     # "/" then just include it and don't exclude "/*".
189                     #
190                     push(@inc, $file) if ( !$incDone{$file} );
191                     next;
192                 }
193                 my $f = "";
194                 while ( $file =~ m{^/([^/]*)(.*)} ) {
195                     my $elt = $1;
196                     $file = $2;
197                     if ( $file eq "/" ) {
198                         #
199                         # preserve a tailing slash
200                         #
201                         $file = "";
202                         $elt = "$elt/";
203                     }
204                     push(@exc, "$f/*") if ( !$excDone{"$f/*"} );
205                     $excDone{"$f/*"} = 1;
206                     $f = "$f/$elt";
207                     push(@inc, $f) if ( !$incDone{$f} );
208                     $incDone{$f} = 1;
209                 }
210             }
211             foreach my $file ( @inc ) {
212                 push(@fileList, "--include=$file");
213             }
214             foreach my $file ( @exc ) {
215                 push(@fileList, "--exclude=$file");
216             }
217         }
218         if ( defined($conf->{BackupFilesExclude}{$t->{shareName}}) ) {
219             foreach my $file ( @{$conf->{BackupFilesExclude}{$t->{shareName}}} )
220             {
221                 #
222                 # just append additional exclude lists onto the end
223                 #
224                 push(@fileList, "--exclude=$file");
225             }
226         }
227         if ( $t->{type} eq "full" ) {
228             if ( $t->{partialNum} ) {
229                 $logMsg = "full backup started for directory $t->{shareName};"
230                         . " updating partial $t->{partialNum}";
231             } else {
232                 $logMsg = "full backup started for directory $t->{shareName}";
233             }
234         } else {
235             $incrDate = $bpc->timeStamp($t->{lastFull} - 3600, 1);
236             $logMsg = "incr backup started back to $incrDate for directory"
237                     . " $t->{shareName}";
238         }
239         
240         #
241         # A full dump is implemented with --ignore-times: this causes all
242         # files to be checksummed, even if the attributes are the same.
243         # That way all the file contents are checked, but you get all
244         # the efficiencies of rsync: only files deltas need to be
245         # transferred, even though it is a full dump.
246         #
247         $rsyncArgs = $conf->{RsyncArgs};
248         $rsyncArgs = [@$rsyncArgs, @fileList] if ( @fileList );
249         $rsyncArgs = [@$rsyncArgs, "--ignore-times"]
250                                     if ( $t->{type} eq "full" );
251         $rsyncClientCmd = $conf->{RsyncClientCmd};
252         $argList = ['--server', '--sender', @$rsyncArgs,
253                               '.', $t->{shareNameSlash}];
254         $fioArgs = {
255             client     => $t->{client},
256             share      => $t->{shareName},
257             viewNum    => $t->{lastFullBkupNum},
258             partialNum => $t->{partialNum},
259         };
260     }
261
262     #
263     # Merge variables into $rsyncClientCmd
264     #
265     my $args = {
266         host      => $t->{host},
267         hostIP    => $t->{hostIP},
268         client    => $t->{client},
269         shareName => $t->{shareName},
270         shareNameSlash => $t->{shareNameSlash},
271         rsyncPath => $conf->{RsyncClientPath},
272         sshPath   => $conf->{SshPath},
273         argList   => $argList,
274     };
275     $rsyncClientCmd = $bpc->cmdVarSubstitute($rsyncClientCmd, $args);
276
277     #
278     # Create the Rsync object, and tell it to use our own File::RsyncP::FileIO
279     # module, which handles all the special BackupPC file storage
280     # (compression, mangling, hardlinks, special files, attributes etc).
281     #
282     $t->{rsyncClientCmd} = $rsyncClientCmd;
283     $t->{rs} = File::RsyncP->new({
284         logLevel     => $t->{logLevel} || $conf->{RsyncLogLevel},
285         rsyncCmd     => sub {
286                             $bpc->verbose(0);
287                             $bpc->cmdExecOrEval($rsyncClientCmd, $args);
288                         },
289         rsyncCmdType => "full",
290         rsyncArgs    => $rsyncArgs,
291         timeout      => $conf->{ClientTimeout},
292         doPartial    => defined($t->{partialNum}) ? 1 : undef,
293         logHandler   =>
294                 sub {
295                     my($str) = @_;
296                     $str .= "\n";
297                     $t->{XferLOG}->write(\$str);
298                     if ( $str =~ /^Remote\[1\]: read errors mapping "(.*)"/ ) {
299                         #
300                         # Files with read errors (eg: region locked files
301                         # on WinXX) are filled with 0 by rsync.  Remember
302                         # them and delete them later.
303                         #
304                         my $badFile = $1;
305                         $badFile =~ s/^\/+//;
306                         push(@{$t->{badFiles}}, {
307                                 share => $t->{shareName},
308                                 file  => $badFile
309                             });
310                     }
311                 },
312         pidHandler   => sub {
313                             $t->{pidHandler}(@_);
314                         },
315         fio          => BackupPC::Xfer::RsyncFileIO->new({
316                             xfer       => $t,
317                             bpc        => $t->{bpc},
318                             conf       => $t->{conf},
319                             backups    => $t->{backups},
320                             logLevel   => $t->{logLevel}
321                                               || $conf->{RsyncLogLevel},
322                             logHandler => sub {
323                                               my($str) = @_;
324                                               $str .= "\n";
325                                               $t->{XferLOG}->write(\$str);
326                                           },
327                             cacheCheckProb => $conf->{RsyncCsumCacheVerifyProb},
328                             %$fioArgs,
329                       }),
330     });
331
332     delete($t->{_errStr});
333
334     return $logMsg;
335 }
336
337 sub run
338 {
339     my($t) = @_;
340     my $rs = $t->{rs};
341     my $conf = $t->{conf};
342     my($remoteSend, $remoteDir, $remoteDirDaemon);
343
344     alarm($conf->{ClientTimeout});
345     if ( $t->{type} eq "restore" ) {
346         $remoteSend       = 0;
347         ($remoteDir       = "$t->{shareName}/$t->{pathHdrDest}") =~ s{//+}{/}g;
348         ($remoteDirDaemon = "$t->{shareName}/$t->{pathHdrDest}") =~ s{//+}{/}g;
349         $remoteDirDaemon  = $t->{shareNameSlash}
350                                 if ( $t->{pathHdrDest} eq ""
351                                               || $t->{pathHdrDest} eq "/" );
352     } else {
353         $remoteSend      = 1;
354         $remoteDir       = $t->{shareNameSlash};
355         $remoteDirDaemon = ".";
356     }
357     if ( $t->{XferMethod} eq "rsync" ) {
358         #
359         # Run rsync command
360         #
361         my $str = "Running: "
362                 . $t->{bpc}->execCmd2ShellCmd(@{$t->{rsyncClientCmd}})
363                 . "\n";
364         $t->{XferLOG}->write(\$str);
365         $rs->remoteStart($remoteSend, $remoteDir);
366     } else {
367         #
368         # Connect to the rsync server
369         #
370         if ( defined(my $err = $rs->serverConnect($t->{hostIP},
371                                              $conf->{RsyncdClientPort})) ) {
372             $t->{hostError} = $err;
373             my $str = "Error connecting to rsync daemon at $t->{hostIP}"
374                     . ":$conf->{RsyncdClientPort}: $err\n";
375             $t->{XferLOG}->write(\$str);
376             return;
377         }
378         #
379         # Pass module name, and follow it with a slash if it already
380         # contains a slash; otherwise just keep the plain module name.
381         #
382         my $module = $t->{shareName};
383         $module = $t->{shareNameSlash} if ( $module =~ /\// );
384         if ( defined(my $err = $rs->serverService($module,
385                                              $conf->{RsyncdUserName},
386                                              $conf->{RsyncdPasswd},
387                                              $conf->{RsyncdAuthRequired})) ) {
388             my $str = "Error connecting to module $module at $t->{hostIP}"
389                     . ":$conf->{RsyncdClientPort}: $err\n";
390             $t->{XferLOG}->write(\$str);
391             $t->{hostError} = $err;
392             return;
393         }
394         $rs->serverStart($remoteSend, $remoteDirDaemon);
395     }
396     my $error = $rs->go($t->{shareNameSlash});
397     $rs->serverClose();
398
399     #
400     # TODO: generate sensible stats
401     # 
402     # $rs->{stats}{totalWritten}
403     # $rs->{stats}{totalSize}
404     #
405     my $stats = $rs->statsFinal;
406     if ( !defined($error) && defined($stats) ) {
407         $t->{xferOK} = 1;
408     } else {
409         $t->{xferOK} = 0;
410     }
411     $t->{xferErrCnt} = $stats->{remoteErrCnt}
412                      + $stats->{childStats}{errorCnt}
413                      + $stats->{parentStats}{errorCnt};
414     $t->{byteCnt}    = $stats->{childStats}{TotalFileSize}
415                      + $stats->{parentStats}{TotalFileSize};
416     $t->{fileCnt}    = $stats->{childStats}{TotalFileCnt}
417                      + $stats->{parentStats}{TotalFileCnt};
418     my $str = "Done: $t->{fileCnt} files, $t->{byteCnt} bytes\n";
419     $t->{XferLOG}->write(\$str);
420     #
421     # TODO: get error count, and call fio to get stats...
422     #
423     $t->{hostError} = $error if ( defined($error) );
424
425     if ( $t->{type} eq "restore" ) {
426         return (
427             $t->{fileCnt},
428             $t->{byteCnt},
429             0,
430             0
431         );
432     } else {
433         return (
434             0,
435             $stats->{childStats}{ExistFileCnt}
436                 + $stats->{parentStats}{ExistFileCnt},
437             $stats->{childStats}{ExistFileSize}
438                 + $stats->{parentStats}{ExistFileSize},
439             $stats->{childStats}{ExistFileCompSize}
440                 + $stats->{parentStats}{ExistFileCompSize},
441             $stats->{childStats}{TotalFileCnt}
442                 + $stats->{parentStats}{TotalFileCnt},
443             $stats->{childStats}{TotalFileSize}
444                 + $stats->{parentStats}{TotalFileSize},
445         );
446     }
447 }
448
449 sub abort
450 {
451     my($t, $reason) = @_;
452     my $rs = $t->{rs};
453
454     $rs->abort($reason);
455     return 1;
456 }
457
458 sub setSelectMask
459 {
460     my($t, $FDreadRef) = @_;
461 }
462
463 sub errStr
464 {
465     my($t) = @_;
466
467     return $RsyncLibErr if ( !defined($t) || ref($t) ne "HASH" );
468     return $t->{_errStr};
469 }
470
471 sub xferPid
472 {
473     my($t) = @_;
474
475     return ();
476 }
477
478 sub logMsg
479 {
480     my($t, $msg) = @_;
481
482     push(@{$t->{_logMsg}}, $msg);
483 }
484
485 sub logMsgGet
486 {
487     my($t) = @_;
488
489     return shift(@{$t->{_logMsg}});
490 }
491
492 #
493 # Returns a hash ref giving various status information about
494 # the transfer.
495 #
496 sub getStats
497 {
498     my($t) = @_;
499
500     return { map { $_ => $t->{$_} }
501             qw(byteCnt fileCnt xferErrCnt xferBadShareCnt xferBadFileCnt
502                xferOK hostAbort hostError lastOutputLine)
503     };
504 }
505
506 sub getBadFiles
507 {
508     my($t) = @_;
509
510     return @{$t->{badFiles}};
511 }
512
513 1;