2 #============================================================= -*-perl-*-
4 # BackupPC_restore: Restore files to a client.
8 # Usage: BackupPC_restore <hostIP> <host> <reqFileName>
11 # Craig Barratt <cbarratt@users.sourceforge.net>
14 # Copyright (C) 2001 Craig Barratt
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.
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.
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
30 #========================================================================
32 # Version 1.6.0_CVS, released 10 Dec 2002.
34 # See http://backuppc.sourceforge.net.
36 #========================================================================
39 use lib "/usr/local/BackupPC/lib";
41 use BackupPC::FileZIO;
42 use BackupPC::Xfer::Smb;
43 use BackupPC::Xfer::Tar;
44 use BackupPC::Xfer::Rsync;
49 use vars qw( %RestoreReq );
51 ###########################################################################
53 ###########################################################################
55 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
56 my $TopDir = $bpc->TopDir();
57 my $BinDir = $bpc->BinDir();
58 my %Conf = $bpc->Conf();
61 my($hostIP, $host, $reqFileName);
66 print("usage: $0 <hostIP> <host> <reqFileName>\n");
69 $hostIP = $1 if ( $ARGV[0] =~ /(.+)/ );
70 $host = $1 if ( $ARGV[1] =~ /(.+)/ );
71 if ( $ARGV[2] !~ /^([\w.]+)$/ ) {
72 print("$0: bad reqFileName (arg #3): $ARGV[2]\n");
77 my $Hosts = $bpc->HostInfoRead();
80 # Re-read config file, so we can include the PC-specific config
82 if ( defined(my $error = $bpc->ConfigRead($host)) ) {
83 print("Can't read PC's config file: $error\n");
88 my $Dir = "$TopDir/pc/$host";
93 # Catch various signals
95 $SIG{INT} = \&catch_signal;
96 $SIG{ALRM} = \&catch_signal;
97 $SIG{TERM} = \&catch_signal;
100 # Read the request file
102 if ( !(my $ret = do "$Dir/$reqFileName") ) {
103 die "couldn't parse $Dir/$reqFileName: $@" if $@;
104 die "couldn't do $Dir/$reqFileName: $!" unless defined $ret;
105 die "couldn't run $Dir/$reqFileName";
109 # Make sure we eventually timeout if there is no activity from
110 # the data transport program.
112 alarm($Conf{ClientTimeout});
114 mkpath($Dir, 0, 0777) if ( !-d $Dir );
115 if ( !-f "$Dir/LOCK" ) {
116 open(LOCK, ">$Dir/LOCK") && close(LOCK);
118 open(LOG, ">>$Dir/LOG");
119 select(LOG); $| = 1; select(STDOUT);
122 # Check if $host is alive
124 my $delay = $bpc->CheckHostAlive($hostIP);
126 print(LOG $bpc->timeStamp, "no ping response\n");
127 print("no ping response\n");
129 } elsif ( $delay > $Conf{PingMaxMsec} ) {
130 printf(LOG "%sping too slow: %.4gmsec\n", $bpc->timeStamp, $delay);
131 printf("ping too slow: %.4gmsec (threshold is %gmsec)\n",
132 $delay, $Conf{PingMaxMsec});
137 # Make sure it is really the machine we expect
139 if ( (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
140 print(LOG $bpc->timeStamp, "restore failed: $errMsg\n");
141 print("restore failed: $errMsg\n");
146 # Setup file extension for compression and open RestoreLOG output file
148 $Conf{CompressLevel} = 0 if ( !BackupPC::FileZIO->compOk );
149 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
150 my $RestoreLOG = BackupPC::FileZIO->open("$Dir/RestoreLOG$fileExt", 1,
151 $Conf{CompressLevel});
152 my $startTime = time();
154 my $tarCreateFileCnt = 0;
155 my $tarCreateByteCnt = 0;
156 my $tarCreateErrCnt = 1; # assume not ok until we learn otherwise
158 my($logMsg, %stat, $xfer);
160 $stat{xferOK} = $stat{hostAbort} = undef;
161 $stat{hostError} = $stat{lastOutputLine} = undef;
165 # Run an optional pre-restore command
167 UserCommandRun("RestorePreUserCmd");
170 if ( $Conf{XferMethod} eq "tar" ) {
172 # Use tar (eg: tar/ssh) as the transport program.
174 $xfer = BackupPC::Xfer::Tar->new($bpc);
175 } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
177 # Use rsync as the transport program.
179 if ( !defined($xfer = BackupPC::Xfer::Rsync->new($bpc)) ) {
180 my $errStr = BackupPC::Xfer::Rsync->errStr;
181 print(LOG $bpc->timeStamp, "restore failed: $errStr\n");
182 print("restore failed: $errStr\n");
183 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
188 # Default is to use smbclient (smb) as the transport program.
190 $xfer = BackupPC::Xfer::Smb->new($bpc);
192 my $useTar = $xfer->useTar;
196 # Create a pipe to connect BackupPC_tarCreate to the transport program
197 # (smbclient, tar, etc).
198 # WH is the write handle for writing, provided to BackupPC_tarCreate
199 # and RH is the other end of the pipe for reading provided to the
206 # Run the transport program, which reads from RH and extracts the data.
208 my @Backups = $bpc->BackupInfoRead($RestoreReq{hostSrc});
213 shareName => $RestoreReq{shareDest},
216 XferLOG => $RestoreLOG,
217 XferMethod => $Conf{XferMethod},
218 bkupSrcHost => $RestoreReq{hostSrc},
219 bkupSrcShare => $RestoreReq{shareSrc},
220 bkupSrcNum => $RestoreReq{num},
221 backups => \@Backups,
222 pathHdrSrc => $RestoreReq{pathHdrSrc},
223 pathHdrDest => $RestoreReq{pathHdrDest},
224 fileList => $RestoreReq{fileList},
227 $xfer->args($xferArgs);
229 if ( !defined($logMsg = $xfer->start()) ) {
230 print(LOG $bpc->timeStamp, "xfer start failed: ", $xfer->errStr, "\n");
231 print($xfer->errStr, "\n");
232 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
238 # Now do the restore by running BackupPC_tarCreate
240 # The parent must close the read handle since the transport program
246 # fork a child for BackupPC_tarCreate. TAR is a file handle
247 # on which we (the parent) read the stderr from BackupPC_tarCreate.
250 if ( defined($RestoreReq{pathHdrDest})
251 && $RestoreReq{pathHdrDest} ne $RestoreReq{pathHdrSrc} ) {
252 @tarPathOpts = ("-r", $RestoreReq{pathHdrSrc},
253 "-p", $RestoreReq{pathHdrDest}
257 "-h", $RestoreReq{hostSrc},
258 "-n", $RestoreReq{num},
259 "-s", $RestoreReq{shareSrc},
262 @{$RestoreReq{fileList}},
264 my $logMsg = "Running: $BinDir/BackupPC_tarCreate "
265 . join(" ", @tarArgs) . "\n";
266 $RestoreLOG->write(\$logMsg);
267 if ( !defined($tarPid = open(TAR, "-|")) ) {
268 print(LOG $bpc->timeStamp, "can't fork to run tar\n");
269 print("can't fork to run tar\n");
271 # FIX: need to cleanup xfer
272 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
277 # This is the tarCreate child. Clone STDERR to STDOUT,
278 # STDOUT to WH, and then exec BackupPC_tarCreate.
282 open(STDERR, ">&STDOUT");
284 open(STDOUT, ">&WH");
285 exec("$BinDir/BackupPC_tarCreate", @tarArgs);
286 print(LOG $bpc->timeStamp, "can't exec $BinDir/BackupPC_tarCreate\n");
287 # FIX: need to cleanup xfer
291 # The parent must close the write handle since BackupPC_tarCreate
296 $xferPid = $xfer->xferPid;
297 print(LOG $bpc->timeStamp, $logMsg, " (tarPid=$tarPid, xferPid=$xferPid)\n");
298 print("started restore, tarPid=$tarPid, xferPid=$xferPid\n");
301 # Parse the output of the transfer program and BackupPC_tarCreate
302 # while they run. Since we are reading from two or more children
305 my($FDread, $tarOut, $mesg);
306 vec($FDread, fileno(TAR), 1) = 1;
307 $xfer->setSelectMask(\$FDread);
311 last if ( $FDread =~ /^\0*$/ );
312 alarm($Conf{ClientTimeout});
313 select(my $rout = $FDread, undef, $ein, undef);
314 if ( vec($rout, fileno(TAR), 1) ) {
315 if ( sysread(TAR, $mesg, 8192) <= 0 ) {
316 vec($FDread, fileno(TAR), 1) = 0;
318 $tarCreateErrCnt = 1;
319 $tarCreateErr = "BackupPC_tarCreate failed";
325 while ( $tarOut =~ /(.*?)[\n\r]+(.*)/s ) {
328 $RestoreLOG->write(\"tarCreate: $_\n");
329 if ( /^Done: (\d+) files, (\d+) bytes, (\d+) dirs, (\d+) specials, (\d+) errors/ ) {
330 $tarCreateFileCnt = $1;
331 $tarCreateByteCnt = $2;
332 $tarCreateErrCnt = $5;
335 last if ( !$xfer->readOutput(\$FDread, $rout) );
336 while ( my $str = $xfer->logMsgGet ) {
337 print(LOG $bpc->timeStamp, "xfer: $str\n");
339 if ( $xfer->getStats->{fileCnt} == 1 ) {
341 # Make sure it is still the machine we expect. We do this while
342 # the transfer is running to avoid a potential race condition if
343 # the ip address was reassigned by dhcp just before we started
346 if ( my $errMsg = CorrectHostCheck($hostIP, $host) ) {
347 $stat{hostError} = $errMsg;
354 # otherwise the xfer module does everything for us
356 print(LOG $bpc->timeStamp, "Starting restore (tarPid=-1, xferPid=-1)\n");
357 print("started restore, tarPid=-1, xferPid=-1\n");
358 ($tarCreateFileCnt, $tarCreateByteCnt,
359 $tarCreateErrCnt, $tarCreateErr) = $xfer->run();
364 # Merge the xfer status (need to accumulate counts)
366 my $newStat = $xfer->getStats;
367 foreach my $k ( (keys(%stat), keys(%$newStat)) ) {
368 next if ( !defined($newStat->{$k}) );
369 if ( $k =~ /Cnt$/ ) {
370 $stat{$k} += $newStat->{$k};
371 delete($newStat->{$k});
374 if ( !defined($stat{$k}) ) {
375 $stat{$k} = $newStat->{$k};
376 delete($newStat->{$k});
381 $stat{xferOK} = 0 if ( $stat{hostError} || $stat{hostAbort} || $tarCreateErr );
383 if ( !$stat{xferOK} ) {
385 # kill off the tranfer program, first nicely then forcefully
387 kill(2, $xferPid) if ( $xferPid > 0 );
389 kill(9, $xferPid) if ( $xferPid > 0 );
391 # kill off the tar process, first nicely then forcefully
393 kill(2, $tarPid) if ( $tarPid > 0 );
395 kill(9, $tarPid) if ( $tarPid > 0 );
402 # Do one last check to make sure it is still the machine we expect.
404 if ( $stat{xferOK} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
405 $stat{hostError} = $errMsg;
408 @Restores = $bpc->RestoreInfoRead($host);
409 for ( my $i = 0 ; $i < @Restores ; $i++ ) {
410 $lastNum = $Restores[$i]{num} if ( $lastNum < $Restores[$i]{num} );
415 # Run an optional post-restore command
417 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
419 $RestoreLOG->close();
420 rename("$Dir/RestoreLOG$fileExt", "$Dir/RestoreLOG.$lastNum$fileExt");
421 rename("$Dir/$reqFileName", "$Dir/RestoreInfo.$lastNum");
422 my $endTime = time();
425 # If the restore failed, clean up
427 if ( !$stat{xferOK} ) {
429 # wait a short while and see if the system is still alive
431 $stat{hostError} ||= $tarCreateErr if ( $tarCreateErr ne "" );
432 $stat{hostError} = $stat{lastOutputLine} if ( $stat{hostError} eq "" );
433 if ( $stat{hostError} ) {
434 print(LOG $bpc->timeStamp,
435 "Got fatal error during xfer ($stat{hostError})\n");
438 if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
439 $stat{hostAbort} = 1;
441 if ( $stat{hostAbort} ) {
442 $stat{hostError} = "lost network connection during restore";
447 # Add the new restore information to the restore file
449 @Restores = $bpc->RestoreInfoRead($host);
451 $Restores[$i]{num} = $lastNum;
452 $Restores[$i]{startTime} = $startTime;
453 $Restores[$i]{endTime} = $endTime;
454 $Restores[$i]{result} = $stat{xferOK} ? "ok" : "failed";
455 $Restores[$i]{errorMsg} = $stat{hostError};
456 $Restores[$i]{nFiles} = $tarCreateFileCnt;
457 $Restores[$i]{size} = $tarCreateByteCnt;
458 $Restores[$i]{tarCreateErrs} = $tarCreateErrCnt;
459 $Restores[$i]{xferErrs} = $stat{xferErrCnt} || 0;
461 while ( @Restores > $Conf{RestoreInfoKeepCnt} ) {
462 my $num = $Restores[0]{num};
463 unlink("$Dir/RestoreLOG.$num.z");
464 unlink("$Dir/RestoreLOG.$num");
465 unlink("$Dir/RestoreInfo.$num");
468 $bpc->RestoreInfoWrite($host, @Restores);
470 if ( !$stat{xferOK} ) {
471 print(LOG $bpc->timeStamp, "Restore aborted ($stat{hostError})\n");
472 print("restore failed: $stat{hostError}\n");
474 print("restore complete\n");
477 ###########################################################################
479 ###########################################################################
483 my($hostIP, $host) = @_;
484 return if ( $hostIP eq $host && !$Conf{FixedIPNetBiosNameCheck} );
485 my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($hostIP);
486 return "host $host has mismatching netbios name $netBiosHost"
487 if ( $netBiosHost ne $host );
496 # Note: needs to be tested for each kind of XferMethod
498 print(LOG $bpc->timeStamp, "cleaning up after signal $signame\n");
499 if ( $xferPid > 0 ) {
500 if ( kill(2, $xferPid) <= 0 ) {
506 if ( kill(2, $tarPid) <= 0 ) {
512 $stat{hostError} = "aborted by signal $signame";
516 # Run an optional pre- or post-dump command
522 return if ( !defined($Conf{$type}) );
527 share => $RestoreReq{shareDest},
528 XferMethod => $Conf{XferMethod},
530 XferLOG => $RestoreLOG,
532 xferOK => $stat{xferOK},
534 bkupSrcHost => $RestoreReq{hostSrc},
535 bkupSrcShare => $RestoreReq{shareSrc},
536 bkupSrcNum => $RestoreReq{num},
537 backups => \@Backups,
538 pathHdrSrc => $RestoreReq{pathHdrSrc},
539 pathHdrDest => $RestoreReq{pathHdrDest},
540 fileList => $RestoreReq{fileList},
542 my $cmd = $bpc->cmdVarSubstitute($Conf{$type}, $vars);
543 $RestoreLOG->write(\"Executing $type: @$cmd\n");
545 # Run the user's command, dumping the stdout/stderr into the
546 # Xfer log file. Also supply the optional $vars and %Conf in
547 # case the command is really perl code instead of a shell
550 $bpc->cmdSystemOrEval($cmd,
552 $RestoreLOG->write(\$_[0]);