3.1.0 changes:
[BackupPC.git] / lib / BackupPC / Xfer / Tar.pm
1 #============================================================= -*-perl-*-
2 #
3 # BackupPC::Xfer::Tar package
4 #
5 # DESCRIPTION
6 #
7 #   This library defines a BackupPC::Xfer::Tar class for managing
8 #   the tar-based transport of backup data from the client.
9 #
10 # AUTHOR
11 #   Craig Barratt  <cbarratt@users.sourceforge.net>
12 #
13 # COPYRIGHT
14 #   Copyright (C) 2001-2007  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 3.1.0, released 25 Nov 2007.
33 #
34 # See http://backuppc.sourceforge.net.
35 #
36 #========================================================================
37
38 package BackupPC::Xfer::Tar;
39
40 use strict;
41 use Encode qw/from_to encode/;
42
43 sub new
44 {
45     my($class, $bpc, $args) = @_;
46
47     $args ||= {};
48     my $t = bless {
49         bpc       => $bpc,
50         conf      => { $bpc->Conf },
51         host      => "",
52         hostIP    => "",
53         shareName => "",
54         pipeRH    => undef,
55         pipeWH    => undef,
56         badFiles  => [],
57         %$args,
58     }, $class;
59
60     return $t;
61 }
62
63 sub args
64 {
65     my($t, $args) = @_;
66
67     foreach my $arg ( keys(%$args) ) {
68         $t->{$arg} = $args->{$arg};
69     }
70 }
71
72 sub useTar
73 {
74     return 1;
75 }
76
77 sub start
78 {
79     my($t) = @_;
80     my $bpc = $t->{bpc};
81     my $conf = $t->{conf};
82     my(@fileList, $tarClientCmd, $logMsg, $incrDate);
83     local(*TAR);
84
85     if ( $t->{type} eq "restore" ) {
86         $tarClientCmd = $conf->{TarClientRestoreCmd};
87         $logMsg = "restore started below directory $t->{shareName}";
88         #
89         # restores are considered to work unless we see they fail
90         # (opposite to backups...)
91         #
92         $t->{xferOK} = 1;
93     } else {
94         #
95         # Turn $conf->{BackupFilesOnly} and $conf->{BackupFilesExclude}
96         # into a hash of arrays of files, and $conf->{TarShareName}
97         # to an array
98         #
99         $bpc->backupFileConfFix($conf, "TarShareName");
100
101         if ( defined($conf->{BackupFilesExclude}{$t->{shareName}}) ) {
102             foreach my $file ( @{$conf->{BackupFilesExclude}{$t->{shareName}}} )
103             {
104                 $file = "./$2" if ( $file =~ m{^(\./+|/+)(.*)}s );
105                 $file = encode($conf->{ClientCharset}, $file)
106                             if ( $conf->{ClientCharset} ne "" );
107                 push(@fileList, "--exclude=$file");
108             }
109         }
110         if ( defined($conf->{BackupFilesOnly}{$t->{shareName}}) ) {
111             foreach my $file ( @{$conf->{BackupFilesOnly}{$t->{shareName}}} ) {
112                 $file = $2 if ( $file =~ m{^(\./+|/+)(.*)}s );
113                 $file = "./$file";
114                 $file = encode($conf->{ClientCharset}, $file)
115                             if ( $conf->{ClientCharset} ne "" );
116                 push(@fileList, $file);
117             }
118         } else {
119             push(@fileList, ".");
120         }
121         if ( ref($conf->{TarClientCmd}) eq "ARRAY" ) {
122             $tarClientCmd = $conf->{TarClientCmd};
123         } else {
124             $tarClientCmd = [split(/ +/, $conf->{TarClientCmd})];
125         }
126         my $args;
127         if ( $t->{type} eq "full" ) {
128             $args = $conf->{TarFullArgs};
129             $logMsg = "full backup started for directory $t->{shareName}";
130         } else {
131             $incrDate = $bpc->timeStamp($t->{incrBaseTime} - 3600, 1);
132             $args = $conf->{TarIncrArgs};
133             $logMsg = "incr backup started back to $incrDate"
134                     . " (backup #$t->{incrBaseBkupNum}) for directory"
135                     . " $t->{shareName}";
136         }
137         push(@$tarClientCmd, split(/ +/, $args));
138     }
139     #
140     # Merge variables into @tarClientCmd
141     #
142     my $args = {
143         host      => $t->{host},
144         hostIP    => $t->{hostIP},
145         client    => $t->{client},
146         incrDate  => $incrDate,
147         shareName => $t->{shareName},
148         fileList  => \@fileList,
149         tarPath   => $conf->{TarClientPath},
150         sshPath   => $conf->{SshPath},
151     };
152     from_to($args->{shareName}, "utf8", $conf->{ClientCharset})
153                             if ( $conf->{ClientCharset} ne "" );
154     $tarClientCmd = $bpc->cmdVarSubstitute($tarClientCmd, $args);
155     if ( !defined($t->{xferPid} = open(TAR, "-|")) ) {
156         $t->{_errStr} = "Can't fork to run tar";
157         return;
158     }
159     $t->{pipeTar} = *TAR;
160     if ( !$t->{xferPid} ) {
161         #
162         # This is the tar child.
163         #
164         setpgrp 0,0;
165         if ( $t->{type} eq "restore" ) {
166             #
167             # For restores, close the write end of the pipe,
168             # clone STDIN to RH
169             #
170             close($t->{pipeWH});
171             close(STDERR);
172             open(STDERR, ">&STDOUT");
173             close(STDIN);
174             open(STDIN, "<&$t->{pipeRH}");
175         } else {
176             #
177             # For backups, close the read end of the pipe,
178             # clone STDOUT to WH, and STDERR to STDOUT
179             #
180             close($t->{pipeRH});
181             close(STDERR);
182             open(STDERR, ">&STDOUT");
183             open(STDOUT, ">&$t->{pipeWH}");
184         }
185         #
186         # Run the tar command
187         #
188         alarm(0);
189         $bpc->cmdExecOrEval($tarClientCmd, $args);
190         # should not be reached, but just in case...
191         $t->{_errStr} = "Can't exec @$tarClientCmd";
192         return;
193     }
194     my $str = "Running: " . $bpc->execCmd2ShellCmd(@$tarClientCmd) . "\n";
195     from_to($str, $conf->{ClientCharset}, "utf8")
196                             if ( $conf->{ClientCharset} ne "" );
197     $t->{XferLOG}->write(\"Running: @$tarClientCmd\n");
198     alarm($conf->{ClientTimeout});
199     $t->{_errStr} = undef;
200     return $logMsg;
201 }
202
203 sub readOutput
204 {
205     my($t, $FDreadRef, $rout) = @_;
206     my $conf = $t->{conf};
207
208     if ( vec($rout, fileno($t->{pipeTar}), 1) ) {
209         my $mesg;
210         if ( sysread($t->{pipeTar}, $mesg, 8192) <= 0 ) {
211             vec($$FDreadRef, fileno($t->{pipeTar}), 1) = 0;
212             if ( !close($t->{pipeTar}) && $? != 256 ) {
213                 #
214                 # Tar 1.16 uses exit status 1 (256) when some files
215                 # changed during archive creation.  We allow this
216                 # as a benign error and consider the archive ok
217                 #
218                 $t->{tarOut} .= "Tar exited with error $? ($!) status\n";
219                 $t->{xferOK} = 0 if ( !$t->{tarBadExitOk} );
220             }
221         } else {
222             $t->{tarOut} .= $mesg;
223         }
224     }
225     my $logFileThres = $t->{type} eq "restore" ? 1 : 2;
226     while ( $t->{tarOut} =~ /(.*?)[\n\r]+(.*)/s ) {
227         $_ = $1;
228         $t->{tarOut} = $2;
229         from_to($_, $conf->{ClientCharset}, "utf8")
230                             if ( $conf->{ClientCharset} ne "" );
231         #
232         # refresh our inactivity alarm
233         #
234         alarm($conf->{ClientTimeout}) if ( !$t->{abort} );
235         $t->{lastOutputLine} = $_ if ( !/^$/ );
236         if ( /^Total bytes (written|read): / ) {
237             $t->{XferLOG}->write(\"$_\n") if ( $t->{logLevel} >= 1 );
238             $t->{xferOK} = 1;
239         } elsif ( /^\./ ) {
240             $t->{XferLOG}->write(\"$_\n") if ( $t->{logLevel} >= $logFileThres );
241             $t->{fileCnt}++;
242         } else {
243             #
244             # Ignore annoying log message on incremental for tar 1.15.x
245             #
246             if ( !/: file is unchanged; not dumped$/ && !/: socket ignored$/ ) {
247                 $t->{XferLOG}->write(\"$_\n") if ( $t->{logLevel} >= 0 );
248                 $t->{xferErrCnt}++;
249             }
250             #
251             # If tar encounters a minor error, it will exit with a non-zero
252             # status.  We still consider that ok.  Remember if tar prints
253             # this message indicating a non-fatal error.
254             #
255             $t->{tarBadExitOk} = 1
256                     if ( $t->{xferOK} && /Error exit delayed from previous / );
257             #
258             # Also remember files that had read errors
259             #
260             if ( /: \.\/(.*): Read error at byte / ) {
261                 my $badFile = $1;
262                 push(@{$t->{badFiles}}, {
263                         share => $t->{shareName},
264                         file  => $badFile
265                     });
266             }
267
268         }
269     }
270     return 1;
271 }
272
273 sub abort
274 {
275     my($t, $reason) = @_;
276     my @xferPid = $t->xferPid;
277
278     $t->{abort} = 1;
279     $t->{abortReason} = $reason;
280     if ( @xferPid ) {
281         kill($t->{bpc}->sigName2num("INT"), @xferPid);
282     }
283 }
284
285 sub setSelectMask
286 {
287     my($t, $FDreadRef) = @_;
288
289     vec($$FDreadRef, fileno($t->{pipeTar}), 1) = 1;
290 }
291
292 sub errStr
293 {
294     my($t) = @_;
295
296     return $t->{_errStr};
297 }
298
299 sub xferPid
300 {
301     my($t) = @_;
302
303     return ($t->{xferPid});
304 }
305
306 sub logMsg
307 {
308     my($t, $msg) = @_;
309
310     push(@{$t->{_logMsg}}, $msg);
311 }
312
313 sub logMsgGet
314 {
315     my($t) = @_;
316
317     return shift(@{$t->{_logMsg}});
318 }
319
320 #
321 # Returns a hash ref giving various status information about
322 # the transfer.
323 #
324 sub getStats
325 {
326     my($t) = @_;
327
328     return { map { $_ => $t->{$_} }
329             qw(byteCnt fileCnt xferErrCnt xferBadShareCnt xferBadFileCnt
330                xferOK hostAbort hostError lastOutputLine)
331     };
332 }
333
334 sub getBadFiles
335 {
336     my($t) = @_;
337
338     return @{$t->{badFiles}};
339 }
340
341 1;