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