ed60c873e63140d08b95d7f4eeeeaa052f574814
[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  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.0.0beta1, released 30 Mar 2003.
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.30 ) {
56             $RsyncLibOK = 0;
57             $RsyncLibErr = "File::RsyncP module version too old: need 0.30";
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 = "/$file";
180                 $file =~ s{//+}{/}g;
181                 my $f = "";
182                 while ( $file =~ m{^/([^/]*)(.*)} ) {
183                     my $elt = $1;
184                     $file = $2;
185                     if ( $file eq "/" ) {
186                         #
187                         # preserve a tailing slash
188                         #
189                         $file = "";
190                         $elt = "$elt/";
191                     }
192                     push(@exc, "$f/*") if ( !$excDone{"$f/*"} );
193                     $excDone{"$f/*"} = 1;
194                     $f = "$f/$elt";
195                     push(@inc, $f) if ( !$incDone{$f} );
196                     $incDone{$f} = 1;
197                 }
198             }
199             foreach my $file ( @inc ) {
200                 push(@fileList, "--include=$file");
201             }
202             foreach my $file ( @exc ) {
203                 push(@fileList, "--exclude=$file");
204             }
205         }
206         if ( defined($conf->{BackupFilesExclude}{$t->{shareName}}) ) {
207             foreach my $file ( @{$conf->{BackupFilesExclude}{$t->{shareName}}} )
208             {
209                 #
210                 # just append additional exclude lists onto the end
211                 #
212                 push(@fileList, "--exclude=$file");
213             }
214         }
215         if ( $t->{type} eq "full" ) {
216             $logMsg = "full backup started for directory $t->{shareName}";
217         } else {
218             $incrDate = $bpc->timeStampISO($t->{lastFull} - 3600, 1);
219             $logMsg = "incr backup started back to $incrDate for directory"
220                     . " $t->{shareName}";
221         }
222         
223         #
224         # A full dump is implemented with --ignore-times: this causes all
225         # files to be checksummed, even if the attributes are the same.
226         # That way all the file contents are checked, but you get all
227         # the efficiencies of rsync: only files deltas need to be
228         # transferred, even though it is a full dump.
229         #
230         $rsyncArgs = $conf->{RsyncArgs};
231         $rsyncArgs = [@$rsyncArgs, @fileList] if ( @fileList );
232         $rsyncArgs = [@$rsyncArgs, "--ignore-times"]
233                                     if ( $t->{type} eq "full" );
234         $rsyncClientCmd = $conf->{RsyncClientCmd};
235         $argList = ['--server', '--sender', @$rsyncArgs,
236                               '.', $t->{shareNameSlash}];
237         $fioArgs = {
238             client  => $t->{client},
239             share   => $t->{shareName},
240             viewNum => $t->{lastFullBkupNum},
241         };
242     }
243
244     #
245     # Merge variables into $rsyncClientCmd
246     #
247     my $args = {
248         host      => $t->{host},
249         hostIP    => $t->{hostIP},
250         client    => $t->{client},
251         shareName => $t->{shareName},
252         shareNameSlash => $t->{shareNameSlash},
253         rsyncPath => $conf->{RsyncClientPath},
254         sshPath   => $conf->{SshPath},
255         argList   => $argList,
256     };
257     $rsyncClientCmd = $bpc->cmdVarSubstitute($rsyncClientCmd, $args);
258
259     #
260     # Create the Rsync object, and tell it to use our own File::RsyncP::FileIO
261     # module, which handles all the special BackupPC file storage
262     # (compression, mangling, hardlinks, special files, attributes etc).
263     #
264     $t->{rsyncClientCmd} = $rsyncClientCmd;
265     $t->{rs} = File::RsyncP->new({
266         logLevel     => $conf->{RsyncLogLevel},
267         rsyncCmd     => sub {
268                             $bpc->verbose(0);
269                             $bpc->cmdExecOrEval($rsyncClientCmd, $args);
270                         },
271         rsyncCmdType => "full",
272         rsyncArgs    => $rsyncArgs,
273         timeout      => $conf->{ClientTimeout},
274         logHandler   => sub {
275                             my($str) = @_;
276                             $str .= "\n";
277                             $t->{XferLOG}->write(\$str);
278                         },
279         pidHandler   => sub {
280                             $t->{pidHandler}(@_);
281                         },
282         fio          => BackupPC::Xfer::RsyncFileIO->new({
283                             xfer       => $t,
284                             bpc        => $t->{bpc},
285                             conf       => $t->{conf},
286                             backups    => $t->{backups},
287                             logLevel   => $conf->{RsyncLogLevel},
288                             logHandler => sub {
289                                               my($str) = @_;
290                                               $str .= "\n";
291                                               $t->{XferLOG}->write(\$str);
292                                           },
293                             %$fioArgs,
294                       }),
295     });
296
297     delete($t->{_errStr});
298
299     return $logMsg;
300 }
301
302 sub run
303 {
304     my($t) = @_;
305     my $rs = $t->{rs};
306     my $conf = $t->{conf};
307     my($remoteSend, $remoteDir, $remoteDirDaemon);
308
309     alarm($conf->{ClientTimeout});
310     if ( $t->{type} eq "restore" ) {
311         $remoteSend       = 0;
312         ($remoteDir       = "$t->{shareName}/$t->{pathHdrDest}") =~ s{//+}{/}g;
313         ($remoteDirDaemon = "$t->{shareName}/$t->{pathHdrDest}") =~ s{//+}{/}g;
314         $remoteDirDaemon  = $t->{shareNameSlash}
315                                 if ( $t->{pathHdrDest} eq ""
316                                               || $t->{pathHdrDest} eq "/" );
317     } else {
318         $remoteSend      = 1;
319         $remoteDir       = $t->{shareNameSlash};
320         $remoteDirDaemon = ".";
321     }
322     if ( $t->{XferMethod} eq "rsync" ) {
323         #
324         # Run rsync command
325         #
326         my $str = "Running: "
327                 . $t->{bpc}->execCmd2ShellCmd(@{$t->{rsyncClientCmd}})
328                 . "\n";
329         $t->{XferLOG}->write(\$str);
330         $rs->remoteStart($remoteSend, $remoteDir);
331     } else {
332         #
333         # Connect to the rsync server
334         #
335         if ( defined(my $err = $rs->serverConnect($t->{hostIP},
336                                              $conf->{RsyncdClientPort})) ) {
337             $t->{hostError} = $err;
338             my $str = "Error connecting to rsync daemon at $t->{hostIP}"
339                     . ":$conf->{RsyncdClientPort}: $err\n";
340             $t->{XferLOG}->write(\$str);
341             return;
342         }
343         #
344         # Pass module name, and follow it with a slash if it already
345         # contains a slash; otherwise just keep the plain module name.
346         #
347         my $module = $t->{shareName};
348         $module = $t->{shareNameSlash} if ( $module =~ /\// );
349         if ( defined(my $err = $rs->serverService($module,
350                                              $conf->{RsyncdUserName},
351                                              $conf->{RsyncdPasswd},
352                                              $conf->{RsyncdAuthRequired})) ) {
353             my $str = "Error connecting to module $module at $t->{hostIP}"
354                     . ":$conf->{RsyncdClientPort}: $err\n";
355             $t->{XferLOG}->write(\$str);
356             $t->{hostError} = $err;
357             return;
358         }
359         $rs->serverStart($remoteSend, $remoteDirDaemon);
360     }
361     my $error = $rs->go($t->{shareNameSlash});
362     $rs->serverClose();
363
364     #
365     # TODO: generate sensible stats
366     # 
367     # $rs->{stats}{totalWritten}
368     # $rs->{stats}{totalSize}
369     #
370     my $stats = $rs->statsFinal;
371     if ( !defined($error) && defined($stats) ) {
372         $t->{xferOK} = 1;
373     } else {
374         $t->{xferOK} = 0;
375     }
376     $t->{xferErrCnt} = $stats->{remoteErrCnt}
377                      + $stats->{childStats}{errorCnt}
378                      + $stats->{parentStats}{errorCnt};
379     $t->{byteCnt}    = $stats->{childStats}{TotalFileSize}
380                      + $stats->{parentStats}{TotalFileSize};
381     $t->{fileCnt}    = $stats->{childStats}{TotalFileCnt}
382                      + $stats->{parentStats}{TotalFileCnt};
383     my $str = "Done: $t->{fileCnt} files, $t->{byteCnt} bytes\n";
384     $t->{XferLOG}->write(\$str);
385     #
386     # TODO: get error count, and call fio to get stats...
387     #
388     $t->{hostError} = $error if ( defined($error) );
389
390     if ( $t->{type} eq "restore" ) {
391         return (
392             $t->{fileCnt},
393             $t->{byteCnt},
394             0,
395             0
396         );
397     } else {
398         return (
399             0,
400             $stats->{childStats}{ExistFileCnt}
401                 + $stats->{parentStats}{ExistFileCnt},
402             $stats->{childStats}{ExistFileSize}
403                 + $stats->{parentStats}{ExistFileSize},
404             $stats->{childStats}{ExistFileCompSize}
405                 + $stats->{parentStats}{ExistFileCompSize},
406             $stats->{childStats}{TotalFileCnt}
407                 + $stats->{parentStats}{TotalFileCnt},
408             $stats->{childStats}{TotalFileSize}
409                 + $stats->{parentStats}{TotalFileSize},
410         );
411     }
412 }
413
414 sub setSelectMask
415 {
416     my($t, $FDreadRef) = @_;
417 }
418
419 sub errStr
420 {
421     my($t) = @_;
422
423     return $RsyncLibErr if ( !defined($t) || ref($t) ne "HASH" );
424     return $t->{_errStr};
425 }
426
427 sub xferPid
428 {
429     my($t) = @_;
430
431     return ();
432 }
433
434 sub logMsg
435 {
436     my($t, $msg) = @_;
437
438     push(@{$t->{_logMsg}}, $msg);
439 }
440
441 sub logMsgGet
442 {
443     my($t) = @_;
444
445     return shift(@{$t->{_logMsg}});
446 }
447
448 #
449 # Returns a hash ref giving various status information about
450 # the transfer.
451 #
452 sub getStats
453 {
454     my($t) = @_;
455
456     return { map { $_ => $t->{$_} }
457             qw(byteCnt fileCnt xferErrCnt xferBadShareCnt xferBadFileCnt
458                xferOK hostAbort hostError lastOutputLine)
459     };
460 }
461
462 sub getBadFiles
463 {
464     my($t) = @_;
465
466     return @{$t->{badFiles}};
467 }
468
469 1;