338ca568acc45cc50a3fc350c04878aaeff1040f
[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.0beta1, released 9 Apr 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.50 ) {
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                             %$fioArgs,
328                       }),
329     });
330
331     delete($t->{_errStr});
332
333     return $logMsg;
334 }
335
336 sub run
337 {
338     my($t) = @_;
339     my $rs = $t->{rs};
340     my $conf = $t->{conf};
341     my($remoteSend, $remoteDir, $remoteDirDaemon);
342
343     alarm($conf->{ClientTimeout});
344     if ( $t->{type} eq "restore" ) {
345         $remoteSend       = 0;
346         ($remoteDir       = "$t->{shareName}/$t->{pathHdrDest}") =~ s{//+}{/}g;
347         ($remoteDirDaemon = "$t->{shareName}/$t->{pathHdrDest}") =~ s{//+}{/}g;
348         $remoteDirDaemon  = $t->{shareNameSlash}
349                                 if ( $t->{pathHdrDest} eq ""
350                                               || $t->{pathHdrDest} eq "/" );
351     } else {
352         $remoteSend      = 1;
353         $remoteDir       = $t->{shareNameSlash};
354         $remoteDirDaemon = ".";
355     }
356     if ( $t->{XferMethod} eq "rsync" ) {
357         #
358         # Run rsync command
359         #
360         my $str = "Running: "
361                 . $t->{bpc}->execCmd2ShellCmd(@{$t->{rsyncClientCmd}})
362                 . "\n";
363         $t->{XferLOG}->write(\$str);
364         $rs->remoteStart($remoteSend, $remoteDir);
365     } else {
366         #
367         # Connect to the rsync server
368         #
369         if ( defined(my $err = $rs->serverConnect($t->{hostIP},
370                                              $conf->{RsyncdClientPort})) ) {
371             $t->{hostError} = $err;
372             my $str = "Error connecting to rsync daemon at $t->{hostIP}"
373                     . ":$conf->{RsyncdClientPort}: $err\n";
374             $t->{XferLOG}->write(\$str);
375             return;
376         }
377         #
378         # Pass module name, and follow it with a slash if it already
379         # contains a slash; otherwise just keep the plain module name.
380         #
381         my $module = $t->{shareName};
382         $module = $t->{shareNameSlash} if ( $module =~ /\// );
383         if ( defined(my $err = $rs->serverService($module,
384                                              $conf->{RsyncdUserName},
385                                              $conf->{RsyncdPasswd},
386                                              $conf->{RsyncdAuthRequired})) ) {
387             my $str = "Error connecting to module $module at $t->{hostIP}"
388                     . ":$conf->{RsyncdClientPort}: $err\n";
389             $t->{XferLOG}->write(\$str);
390             $t->{hostError} = $err;
391             return;
392         }
393         $rs->serverStart($remoteSend, $remoteDirDaemon);
394     }
395     my $error = $rs->go($t->{shareNameSlash});
396     $rs->serverClose();
397
398     #
399     # TODO: generate sensible stats
400     # 
401     # $rs->{stats}{totalWritten}
402     # $rs->{stats}{totalSize}
403     #
404     my $stats = $rs->statsFinal;
405     if ( !defined($error) && defined($stats) ) {
406         $t->{xferOK} = 1;
407     } else {
408         $t->{xferOK} = 0;
409     }
410     $t->{xferErrCnt} = $stats->{remoteErrCnt}
411                      + $stats->{childStats}{errorCnt}
412                      + $stats->{parentStats}{errorCnt};
413     $t->{byteCnt}    = $stats->{childStats}{TotalFileSize}
414                      + $stats->{parentStats}{TotalFileSize};
415     $t->{fileCnt}    = $stats->{childStats}{TotalFileCnt}
416                      + $stats->{parentStats}{TotalFileCnt};
417     my $str = "Done: $t->{fileCnt} files, $t->{byteCnt} bytes\n";
418     $t->{XferLOG}->write(\$str);
419     #
420     # TODO: get error count, and call fio to get stats...
421     #
422     $t->{hostError} = $error if ( defined($error) );
423
424     if ( $t->{type} eq "restore" ) {
425         return (
426             $t->{fileCnt},
427             $t->{byteCnt},
428             0,
429             0
430         );
431     } else {
432         return (
433             0,
434             $stats->{childStats}{ExistFileCnt}
435                 + $stats->{parentStats}{ExistFileCnt},
436             $stats->{childStats}{ExistFileSize}
437                 + $stats->{parentStats}{ExistFileSize},
438             $stats->{childStats}{ExistFileCompSize}
439                 + $stats->{parentStats}{ExistFileCompSize},
440             $stats->{childStats}{TotalFileCnt}
441                 + $stats->{parentStats}{TotalFileCnt},
442             $stats->{childStats}{TotalFileSize}
443                 + $stats->{parentStats}{TotalFileSize},
444         );
445     }
446 }
447
448 sub abort
449 {
450     my($t, $reason) = @_;
451     my $rs = $t->{rs};
452
453     $rs->abort($reason);
454     return 1;
455 }
456
457 sub setSelectMask
458 {
459     my($t, $FDreadRef) = @_;
460 }
461
462 sub errStr
463 {
464     my($t) = @_;
465
466     return $RsyncLibErr if ( !defined($t) || ref($t) ne "HASH" );
467     return $t->{_errStr};
468 }
469
470 sub xferPid
471 {
472     my($t) = @_;
473
474     return ();
475 }
476
477 sub logMsg
478 {
479     my($t, $msg) = @_;
480
481     push(@{$t->{_logMsg}}, $msg);
482 }
483
484 sub logMsgGet
485 {
486     my($t) = @_;
487
488     return shift(@{$t->{_logMsg}});
489 }
490
491 #
492 # Returns a hash ref giving various status information about
493 # the transfer.
494 #
495 sub getStats
496 {
497     my($t) = @_;
498
499     return { map { $_ => $t->{$_} }
500             qw(byteCnt fileCnt xferErrCnt xferBadShareCnt xferBadFileCnt
501                xferOK hostAbort hostError lastOutputLine)
502     };
503 }
504
505 sub getBadFiles
506 {
507     my($t) = @_;
508
509     return @{$t->{badFiles}};
510 }
511
512 1;