9612cab634757a5c99339b927048032d10446dbe
[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.0, released 20 Jun 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, and $conf->{RsyncShareName}
145         # to an array
146         #
147         $bpc->backupFileConfFix($conf, "RsyncShareName");
148
149         if ( defined($conf->{BackupFilesOnly}{$t->{shareName}}) ) {
150             my(@inc, @exc, %incDone, %excDone);
151             foreach my $file ( @{$conf->{BackupFilesOnly}{$t->{shareName}}} ) {
152                 #
153                 # If the user wants to just include /home/craig, then
154                 # we need to do create include/exclude pairs at
155                 # each level:
156                 #     --include /home --exclude /*
157                 #     --include /home/craig --exclude /home/*
158                 #
159                 # It's more complex if the user wants to include multiple
160                 # deep paths.  For example, if they want /home/craig and
161                 # /var/log, then we need this mouthfull:
162                 #     --include /home --include /var --exclude /*
163                 #     --include /home/craig --exclude /home/*
164                 #     --include /var/log --exclude /var/*
165                 #
166                 # To make this easier we do all the includes first and all
167                 # of the excludes at the end (hopefully they commute).
168                 #
169                 $file =~ s{/$}{};
170                 $file = "/$file";
171                 $file =~ s{//+}{/}g;
172                 if ( $file eq "/" ) {
173                     #
174                     # This is a special case: if the user specifies
175                     # "/" then just include it and don't exclude "/*".
176                     #
177                     push(@inc, $file) if ( !$incDone{$file} );
178                     next;
179                 }
180                 my $f = "";
181                 while ( $file =~ m{^/([^/]*)(.*)} ) {
182                     my $elt = $1;
183                     $file = $2;
184                     if ( $file eq "/" ) {
185                         #
186                         # preserve a tailing slash
187                         #
188                         $file = "";
189                         $elt = "$elt/";
190                     }
191                     push(@exc, "$f/*") if ( !$excDone{"$f/*"} );
192                     $excDone{"$f/*"} = 1;
193                     $f = "$f/$elt";
194                     push(@inc, $f) if ( !$incDone{$f} );
195                     $incDone{$f} = 1;
196                 }
197             }
198             foreach my $file ( @inc ) {
199                 push(@fileList, "--include=$file");
200             }
201             foreach my $file ( @exc ) {
202                 push(@fileList, "--exclude=$file");
203             }
204         }
205         if ( defined($conf->{BackupFilesExclude}{$t->{shareName}}) ) {
206             foreach my $file ( @{$conf->{BackupFilesExclude}{$t->{shareName}}} )
207             {
208                 #
209                 # just append additional exclude lists onto the end
210                 #
211                 push(@fileList, "--exclude=$file");
212             }
213         }
214         if ( $t->{type} eq "full" ) {
215             if ( $t->{partialNum} ) {
216                 $logMsg = "full backup started for directory $t->{shareName};"
217                         . " updating partial $t->{partialNum}";
218             } else {
219                 $logMsg = "full backup started for directory $t->{shareName}";
220             }
221         } else {
222             $incrDate = $bpc->timeStamp($t->{lastFull} - 3600, 1);
223             $logMsg = "incr backup started back to $incrDate for directory"
224                     . " $t->{shareName}";
225         }
226         
227         #
228         # A full dump is implemented with --ignore-times: this causes all
229         # files to be checksummed, even if the attributes are the same.
230         # That way all the file contents are checked, but you get all
231         # the efficiencies of rsync: only files deltas need to be
232         # transferred, even though it is a full dump.
233         #
234         $rsyncArgs = $conf->{RsyncArgs};
235         $rsyncArgs = [@$rsyncArgs, @fileList] if ( @fileList );
236         $rsyncArgs = [@$rsyncArgs, "--ignore-times"]
237                                     if ( $t->{type} eq "full" );
238         $rsyncClientCmd = $conf->{RsyncClientCmd};
239         $argList = ['--server', '--sender', @$rsyncArgs,
240                               '.', $t->{shareNameSlash}];
241         $fioArgs = {
242             client     => $t->{client},
243             share      => $t->{shareName},
244             viewNum    => $t->{lastFullBkupNum},
245             partialNum => $t->{partialNum},
246         };
247     }
248
249     #
250     # Merge variables into $rsyncClientCmd
251     #
252     my $args = {
253         host      => $t->{host},
254         hostIP    => $t->{hostIP},
255         client    => $t->{client},
256         shareName => $t->{shareName},
257         shareNameSlash => $t->{shareNameSlash},
258         rsyncPath => $conf->{RsyncClientPath},
259         sshPath   => $conf->{SshPath},
260         argList   => $argList,
261     };
262     $rsyncClientCmd = $bpc->cmdVarSubstitute($rsyncClientCmd, $args);
263
264     #
265     # Create the Rsync object, and tell it to use our own File::RsyncP::FileIO
266     # module, which handles all the special BackupPC file storage
267     # (compression, mangling, hardlinks, special files, attributes etc).
268     #
269     $t->{rsyncClientCmd} = $rsyncClientCmd;
270     $t->{rs} = File::RsyncP->new({
271         logLevel     => $t->{logLevel} || $conf->{RsyncLogLevel},
272         rsyncCmd     => sub {
273                             $bpc->verbose(0);
274                             $bpc->cmdExecOrEval($rsyncClientCmd, $args);
275                         },
276         rsyncCmdType => "full",
277         rsyncArgs    => $rsyncArgs,
278         timeout      => $conf->{ClientTimeout},
279         doPartial    => defined($t->{partialNum}) ? 1 : undef,
280         logHandler   =>
281                 sub {
282                     my($str) = @_;
283                     $str .= "\n";
284                     $t->{XferLOG}->write(\$str);
285                     if ( $str =~ /^Remote\[1\]: read errors mapping "(.*)"/ ) {
286                         #
287                         # Files with read errors (eg: region locked files
288                         # on WinXX) are filled with 0 by rsync.  Remember
289                         # them and delete them later.
290                         #
291                         my $badFile = $1;
292                         $badFile =~ s/^\/+//;
293                         push(@{$t->{badFiles}}, {
294                                 share => $t->{shareName},
295                                 file  => $badFile
296                             });
297                     }
298                 },
299         pidHandler   => sub {
300                             $t->{pidHandler}(@_);
301                         },
302         fio          => BackupPC::Xfer::RsyncFileIO->new({
303                             xfer       => $t,
304                             bpc        => $t->{bpc},
305                             conf       => $t->{conf},
306                             backups    => $t->{backups},
307                             logLevel   => $t->{logLevel}
308                                               || $conf->{RsyncLogLevel},
309                             logHandler => sub {
310                                               my($str) = @_;
311                                               $str .= "\n";
312                                               $t->{XferLOG}->write(\$str);
313                                           },
314                             cacheCheckProb => $conf->{RsyncCsumCacheVerifyProb},
315                             %$fioArgs,
316                       }),
317     });
318
319     delete($t->{_errStr});
320
321     return $logMsg;
322 }
323
324 sub run
325 {
326     my($t) = @_;
327     my $rs = $t->{rs};
328     my $conf = $t->{conf};
329     my($remoteSend, $remoteDir, $remoteDirDaemon);
330
331     alarm($conf->{ClientTimeout});
332     if ( $t->{type} eq "restore" ) {
333         $remoteSend       = 0;
334         ($remoteDir       = "$t->{shareName}/$t->{pathHdrDest}") =~ s{//+}{/}g;
335         ($remoteDirDaemon = "$t->{shareName}/$t->{pathHdrDest}") =~ s{//+}{/}g;
336         $remoteDirDaemon  = $t->{shareNameSlash}
337                                 if ( $t->{pathHdrDest} eq ""
338                                               || $t->{pathHdrDest} eq "/" );
339     } else {
340         $remoteSend      = 1;
341         $remoteDir       = $t->{shareNameSlash};
342         $remoteDirDaemon = ".";
343     }
344     if ( $t->{XferMethod} eq "rsync" ) {
345         #
346         # Run rsync command
347         #
348         my $str = "Running: "
349                 . $t->{bpc}->execCmd2ShellCmd(@{$t->{rsyncClientCmd}})
350                 . "\n";
351         $t->{XferLOG}->write(\$str);
352         $rs->remoteStart($remoteSend, $remoteDir);
353     } else {
354         #
355         # Connect to the rsync server
356         #
357         if ( defined(my $err = $rs->serverConnect($t->{hostIP},
358                                              $conf->{RsyncdClientPort})) ) {
359             $t->{hostError} = $err;
360             my $str = "Error connecting to rsync daemon at $t->{hostIP}"
361                     . ":$conf->{RsyncdClientPort}: $err\n";
362             $t->{XferLOG}->write(\$str);
363             return;
364         }
365         #
366         # Pass module name, and follow it with a slash if it already
367         # contains a slash; otherwise just keep the plain module name.
368         #
369         my $module = $t->{shareName};
370         $module = $t->{shareNameSlash} if ( $module =~ /\// );
371         if ( defined(my $err = $rs->serverService($module,
372                                              $conf->{RsyncdUserName},
373                                              $conf->{RsyncdPasswd},
374                                              $conf->{RsyncdAuthRequired})) ) {
375             my $str = "Error connecting to module $module at $t->{hostIP}"
376                     . ":$conf->{RsyncdClientPort}: $err\n";
377             $t->{XferLOG}->write(\$str);
378             $t->{hostError} = $err;
379             return;
380         }
381         $rs->serverStart($remoteSend, $remoteDirDaemon);
382     }
383     my $error = $rs->go($t->{shareNameSlash});
384     $rs->serverClose();
385
386     #
387     # TODO: generate sensible stats
388     # 
389     # $rs->{stats}{totalWritten}
390     # $rs->{stats}{totalSize}
391     #
392     my $stats = $rs->statsFinal;
393     if ( !defined($error) && defined($stats) ) {
394         $t->{xferOK} = 1;
395     } else {
396         $t->{xferOK} = 0;
397     }
398     $t->{xferErrCnt} = $stats->{remoteErrCnt}
399                      + $stats->{childStats}{errorCnt}
400                      + $stats->{parentStats}{errorCnt};
401     $t->{byteCnt}    = $stats->{childStats}{TotalFileSize}
402                      + $stats->{parentStats}{TotalFileSize};
403     $t->{fileCnt}    = $stats->{childStats}{TotalFileCnt}
404                      + $stats->{parentStats}{TotalFileCnt};
405     my $str = "Done: $t->{fileCnt} files, $t->{byteCnt} bytes\n";
406     $t->{XferLOG}->write(\$str);
407     #
408     # TODO: get error count, and call fio to get stats...
409     #
410     $t->{hostError} = $error if ( defined($error) );
411
412     if ( $t->{type} eq "restore" ) {
413         return (
414             $t->{fileCnt},
415             $t->{byteCnt},
416             0,
417             0
418         );
419     } else {
420         return (
421             0,
422             $stats->{childStats}{ExistFileCnt}
423                 + $stats->{parentStats}{ExistFileCnt},
424             $stats->{childStats}{ExistFileSize}
425                 + $stats->{parentStats}{ExistFileSize},
426             $stats->{childStats}{ExistFileCompSize}
427                 + $stats->{parentStats}{ExistFileCompSize},
428             $stats->{childStats}{TotalFileCnt}
429                 + $stats->{parentStats}{TotalFileCnt},
430             $stats->{childStats}{TotalFileSize}
431                 + $stats->{parentStats}{TotalFileSize},
432         );
433     }
434 }
435
436 sub abort
437 {
438     my($t, $reason) = @_;
439     my $rs = $t->{rs};
440
441     $rs->abort($reason);
442     return 1;
443 }
444
445 sub setSelectMask
446 {
447     my($t, $FDreadRef) = @_;
448 }
449
450 sub errStr
451 {
452     my($t) = @_;
453
454     return $RsyncLibErr if ( !defined($t) || ref($t) ne "HASH" );
455     return $t->{_errStr};
456 }
457
458 sub xferPid
459 {
460     my($t) = @_;
461
462     return ();
463 }
464
465 sub logMsg
466 {
467     my($t, $msg) = @_;
468
469     push(@{$t->{_logMsg}}, $msg);
470 }
471
472 sub logMsgGet
473 {
474     my($t) = @_;
475
476     return shift(@{$t->{_logMsg}});
477 }
478
479 #
480 # Returns a hash ref giving various status information about
481 # the transfer.
482 #
483 sub getStats
484 {
485     my($t) = @_;
486
487     return { map { $_ => $t->{$_} }
488             qw(byteCnt fileCnt xferErrCnt xferBadShareCnt xferBadFileCnt
489                xferOK hostAbort hostError lastOutputLine)
490     };
491 }
492
493 sub getBadFiles
494 {
495     my($t) = @_;
496
497     return @{$t->{badFiles}};
498 }
499
500 1;