2 #============================================================= -*-perl-*-
4 # BackupPC_restore: Restore files to a client.
8 # Usage: BackupPC_restore <hostIP> <client> <reqFileName>
11 # Craig Barratt <cbarratt@users.sourceforge.net>
14 # Copyright (C) 2001-2009 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 3.2.0, released 31 Jul 2010.
34 # See http://backuppc.sourceforge.net.
36 #========================================================================
40 use lib "/usr/local/BackupPC/lib";
42 use BackupPC::FileZIO;
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, $client, $reqFileName, %stat);
66 print("usage: $0 <hostIP> <client> <reqFileName>\n");
69 $hostIP = $1 if ( $ARGV[0] =~ /(.+)/ );
70 $client = $1 if ( $ARGV[1] =~ /(.+)/ );
71 if ( $ARGV[2] !~ /^([\w.]+)$/ ) {
72 print("$0: bad reqFileName (arg #3): $ARGV[2]\n");
77 my $startTime = time();
79 my $Hosts = $bpc->HostInfoRead($client);
81 my $Dir = "$TopDir/pc/$client";
86 # Catch various signals
88 $SIG{INT} = \&catch_signal;
89 $SIG{ALRM} = \&catch_signal;
90 $SIG{TERM} = \&catch_signal;
91 $SIG{PIPE} = \&catch_signal;
92 $SIG{STOP} = \&catch_signal;
93 $SIG{TSTP} = \&catch_signal;
94 $SIG{TTIN} = \&catch_signal;
97 mkpath($Dir, 0, 0777) if ( !-d $Dir );
98 if ( !-f "$Dir/LOCK" ) {
99 open(LOCK, ">", "$Dir/LOCK") && close(LOCK);
102 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
103 my $logPath = sprintf("$Dir/LOG.%02d%04d", $mon + 1, $year + 1900);
105 if ( !-f $logPath ) {
107 # Compress and prune old log files
109 my $lastLog = $Conf{MaxOldPerPCLogFiles} - 1;
110 foreach my $file ( $bpc->sortedPCLogFiles($client) ) {
111 if ( $lastLog <= 0 ) {
116 next if ( $file =~ /\.z$/ || !$Conf{CompressLevel} );
117 BackupPC::FileZIO->compressCopy($file,
120 $Conf{CompressLevel}, 1);
123 open(LOG, ">>", $logPath);
124 select(LOG); $| = 1; select(STDOUT);
127 # Read the request file
129 if ( !(my $ret = do "$Dir/$reqFileName") ) {
132 $err = "couldn't parse $Dir/$reqFileName: $@";
133 } elsif ( !defined($ret) ) {
134 $err = "couldn't do $Dir/$reqFileName: $!";
136 $err = "couldn't run $Dir/$reqFileName";
138 $stat{hostError} = $err;
139 exit(RestoreCleanup($client));
143 # Re-read config file, so we can include the PC-specific config
145 if ( defined(my $error = $bpc->ConfigRead($client)) ) {
146 $stat{hostError} = "Can't read PC's config file: $error";
147 exit(RestoreCleanup($client));
149 %Conf = $bpc->Conf();
152 # Make sure we eventually timeout if there is no activity from
153 # the data transport program.
155 alarm($Conf{ClientTimeout});
158 # See if the host name is aliased
160 if ( $Conf{ClientNameAlias} ne "" ) {
161 $host = $Conf{ClientNameAlias};
167 # Find its IP address
169 if ( $hostIP !~ /\d+\.\d+\.\d+\.\d+/ ) {
170 if ( !defined(gethostbyname($host)) ) {
172 # Ok, NS doesn't know about it. Maybe it is a NetBios name
175 if ( !defined($hostIP = $bpc->NetBiosHostIPFind($host)) ) {
176 $stat{hostError} = "Can't find host $host";
177 exit(RestoreCleanup($client));
185 # Check if $host is alive
187 my $delay = $bpc->CheckHostAlive($hostIP);
189 $stat{hostError} = "no ping response from $host ($hostIP)";
190 exit(RestoreCleanup($client));
191 } elsif ( $delay > $Conf{PingMaxMsec} ) {
192 $stat{hostError} = sprintf("ping too slow: %.4gmsec (max is %gmsec)\n",
193 $delay, $Conf{PingMaxMsec});
194 exit(RestoreCleanup($client));
198 # Make sure it is really the machine we expect
200 if ( (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
201 $stat{hostError} = $errMsg;
202 exit(RestoreCleanup($client));
206 # Setup file extension for compression and open RestoreLOG output file
208 if ( $Conf{CompressLevel} && !BackupPC::FileZIO->compOk ) {
209 $stat{hostError} = "Compress:Zlib not found";
210 exit(RestoreCleanup($client));
212 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
213 my $RestoreLOG = BackupPC::FileZIO->open("$Dir/RestoreLOG$fileExt", 1,
214 $Conf{CompressLevel});
215 my $tarCreateFileCnt = 0;
216 my $tarCreateByteCnt = 0;
217 my $tarCreateDirCnt = 0;
218 my $tarCreateErrCnt = 1; # assume not ok until we learn otherwise
222 $stat{xferOK} = $stat{hostAbort} = undef;
223 $stat{hostError} = $stat{lastOutputLine} = undef;
227 # Run an optional pre-restore command
229 UserCommandRun("RestorePreUserCmd");
230 if ( $? && $Conf{UserCmdCheckStatus} ) {
231 $stat{hostError} = "RestorePreUserCmd returned error status $?";
232 exit(RestoreCleanup($client));
236 $xfer = BackupPC::Xfer::create($Conf{XferMethod}, $bpc);
237 if ( !defined($xfer) ) {
238 my $errStr = BackupPC::Xfer::errStr();
239 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
240 $stat{hostError} = $errStr;
241 exit(RestoreCleanup($client));
244 my $useTar = $xfer->useTar;
248 # Create a socketpair to connect BackupPC_tarCreate to the transport
249 # program (smbclient, tar, etc).
250 # WH is the write handle for writing, provided to BackupPC_tarCreate
251 # and RH is the other end of the pipe for reading provided to the
254 if ( socketpair(RH, WH, AF_UNIX, SOCK_STREAM, PF_UNSPEC) ) {
255 shutdown(RH, 1); # no writing to this socket
256 shutdown(WH, 0); # no reading from this socket
257 setsockopt(RH, SOL_SOCKET, SO_RCVBUF, 8 * 65536);
258 setsockopt(WH, SOL_SOCKET, SO_SNDBUF, 8 * 65536);
261 # Default to pipe() if socketpair() doesn't work.
268 # Run the transport program, which reads from RH and extracts the data.
270 my @Backups = $bpc->BackupInfoRead($RestoreReq{hostSrc});
276 shareName => $RestoreReq{shareDest},
279 XferLOG => $RestoreLOG,
280 XferMethod => $Conf{XferMethod},
281 logLevel => $Conf{XferLogLevel},
282 bkupSrcHost => $RestoreReq{hostSrc},
283 bkupSrcShare => $RestoreReq{shareSrc},
284 bkupSrcNum => $RestoreReq{num},
285 backups => \@Backups,
286 pathHdrSrc => $RestoreReq{pathHdrSrc},
287 pathHdrDest => $RestoreReq{pathHdrDest},
288 fileList => $RestoreReq{fileList},
289 pidHandler => \&pidHandler,
292 $xfer->args($xferArgs);
294 if ( !defined($logMsg = $xfer->start()) ) {
295 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
296 $stat{hostError} = "xfer start failed: ", $xfer->errStr;
297 exit(RestoreCleanup($client));
302 # Now do the restore by running BackupPC_tarCreate
304 # The parent must close the read handle since the transport program
310 # fork a child for BackupPC_tarCreate. TAR is a file handle
311 # on which we (the parent) read the stderr from BackupPC_tarCreate.
314 if ( defined($RestoreReq{pathHdrDest})
315 && $RestoreReq{pathHdrDest} ne $RestoreReq{pathHdrSrc} ) {
316 @tarPathOpts = ("-r", $RestoreReq{pathHdrSrc},
317 "-p", $RestoreReq{pathHdrDest}
321 "-h", $RestoreReq{hostSrc},
322 "-n", $RestoreReq{num},
323 "-s", $RestoreReq{shareSrc},
326 @{$RestoreReq{fileList}},
328 my $runMsg = "Running: "
329 . $bpc->execCmd2ShellCmd("$BinDir/BackupPC_tarCreate", @tarArgs)
331 $RestoreLOG->write(\$runMsg);
332 if ( !defined($tarPid = open(TAR, "-|")) ) {
334 # FIX: need to cleanup xfer
335 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
336 $stat{hostError} = "Can't fork to run tar";
337 exit(RestoreCleanup($client));
342 # This is the tarCreate child. Clone STDERR to STDOUT,
343 # STDOUT to WH, and then exec BackupPC_tarCreate.
347 open(STDERR, ">&STDOUT");
349 open(STDOUT, ">&WH");
351 exec("$BinDir/BackupPC_tarCreate", @tarArgs);
352 print(LOG $bpc->timeStamp, "can't exec $BinDir/BackupPC_tarCreate\n");
353 # FIX: need to cleanup xfer
357 # The parent must close the write handle since BackupPC_tarCreate
362 @xferPid = $xfer->xferPid;
364 print(LOG $bpc->timeStamp, $logMsg, "\n");
365 print("started_restore\n");
367 pidHandler(@xferPid);
370 # Parse the output of the transfer program and BackupPC_tarCreate
371 # while they run. Since we are reading from two or more children
374 my($FDread, $tarOut, $mesg);
375 vec($FDread, fileno(TAR), 1) = 1;
376 $xfer->setSelectMask(\$FDread);
380 last if ( $FDread =~ /^\0*$/ );
381 alarm($Conf{ClientTimeout});
382 select(my $rout = $FDread, undef, $ein, undef);
383 if ( vec($rout, fileno(TAR), 1) ) {
384 if ( sysread(TAR, $mesg, 8192) <= 0 ) {
385 vec($FDread, fileno(TAR), 1) = 0;
387 $tarCreateErrCnt = 1;
388 $tarCreateErr = "BackupPC_tarCreate failed";
394 while ( $tarOut =~ /(.*?)[\n\r]+(.*)/s ) {
397 $RestoreLOG->write(\"tarCreate: $_\n");
398 if ( /^Done: (\d+) files, (\d+) bytes, (\d+) dirs, (\d+) specials, (\d+) errors/ ) {
399 $tarCreateFileCnt = $1;
400 $tarCreateByteCnt = $2;
401 $tarCreateDirCnt = $3;
402 $tarCreateErrCnt = $5;
405 last if ( !$xfer->readOutput(\$FDread, $rout) );
406 while ( my $str = $xfer->logMsgGet ) {
407 print(LOG $bpc->timeStamp, "xfer: $str\n");
409 if ( $xfer->getStats->{fileCnt} == 1 ) {
411 # Make sure it is still the machine we expect. We do this while
412 # the transfer is running to avoid a potential race condition if
413 # the ip address was reassigned by dhcp just before we started
416 if ( my $errMsg = CorrectHostCheck($hostIP, $host) ) {
417 $stat{hostError} = $errMsg;
424 # otherwise the xfer module does everything for us
426 print(LOG $bpc->timeStamp, $logMsg . "\n");
427 print("started_restore\n");
428 ($tarCreateFileCnt, $tarCreateByteCnt,
429 $tarCreateErrCnt, $tarCreateErr) = $xfer->run();
434 # Merge the xfer status (need to accumulate counts)
436 my $newStat = $xfer->getStats;
437 foreach my $k ( (keys(%stat), keys(%$newStat)) ) {
438 next if ( !defined($newStat->{$k}) );
439 if ( $k =~ /Cnt$/ ) {
440 $stat{$k} += $newStat->{$k};
441 delete($newStat->{$k});
444 if ( !defined($stat{$k}) ) {
445 $stat{$k} = $newStat->{$k};
446 delete($newStat->{$k});
451 exit(RestoreCleanup($client));
453 ###########################################################################
455 ###########################################################################
459 my($hostIP, $host) = @_;
460 return if ( $hostIP eq $host && !$Conf{FixedIPNetBiosNameCheck}
461 || $Conf{NmbLookupCmd} eq "" );
462 my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($hostIP);
463 return "host $host has mismatching netbios name $netBiosHost"
464 if ( lc($netBiosHost) ne lc(substr($host, 0, 15)) );
473 # Children quit quietly on ALRM
475 exit(1) if ( $Pid != $$ && $signame eq "ALRM" );
478 # Ignore signals in children
480 return if ( $Pid != $$ );
483 # Note: needs to be tested for each kind of XferMethod
485 print(LOG $bpc->timeStamp, "cleaning up after signal $signame\n");
486 $SIG{$signame} = 'IGNORE';
487 $RestoreLOG->write(\"exiting after signal $signame\n");
489 if ( $signame eq "INT" ) {
490 $stat{hostError} = "aborted by user (signal=$signame)";
492 $stat{hostError} = "aborted by signal=$signame";
494 exit(RestoreCleanup($client));
498 # Cleanup and update the restore status
504 $stat{xferOK} = 0 if ( $stat{hostError} || $stat{hostAbort}
507 if ( !$stat{xferOK} ) {
509 # kill off the tranfer program, first nicely then forcefully
512 kill($bpc->sigName2num("INT"), @xferPid);
514 kill($bpc->sigName2num("KILL"), @xferPid);
517 # kill off the tar process, first nicely then forcefully
520 kill($bpc->sigName2num("INT"), $tarPid);
522 kill($bpc->sigName2num("KILL"), $tarPid);
530 # Do one last check to make sure it is still the machine we expect.
532 if ( $stat{xferOK} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
533 $stat{hostError} = $errMsg;
536 @Restores = $bpc->RestoreInfoRead($client);
537 for ( my $i = 0 ; $i < @Restores ; $i++ ) {
538 $lastNum = $Restores[$i]{num} if ( $lastNum < $Restores[$i]{num} );
543 # Run an optional post-restore command
545 if ( $NeedPostCmd ) {
546 UserCommandRun("RestorePostUserCmd");
547 if ( $? && $Conf{UserCmdCheckStatus} ) {
548 $stat{hostError} = "RestorePostUserCmd returned error status $?";
553 rename("$Dir/RestoreLOG$fileExt", "$Dir/RestoreLOG.$lastNum$fileExt");
554 rename("$Dir/$reqFileName", "$Dir/RestoreInfo.$lastNum");
555 my $endTime = time();
558 # If the restore failed, clean up
560 if ( !$stat{xferOK} ) {
562 # wait a short while and see if the system is still alive
564 $stat{hostError} ||= $tarCreateErr if ( $tarCreateErr ne "" );
565 $stat{hostError} = $stat{lastOutputLine} if ( $stat{hostError} eq "" );
567 if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
568 $stat{hostAbort} = 1;
570 if ( $stat{hostAbort} && $stat{hostError} eq "" ) {
571 $stat{hostError} = "lost network connection during restore";
573 $RestoreLOG->write(\"restore failed: $stat{hostError}\n")
574 if ( defined($RestoreLOG) );
577 $RestoreLOG->close() if ( defined($RestoreLOG) );
580 # Add the new restore information to the restore file
582 @Restores = $bpc->RestoreInfoRead($client);
584 $Restores[$i]{num} = $lastNum;
585 $Restores[$i]{startTime} = $startTime;
586 $Restores[$i]{endTime} = $endTime;
587 $Restores[$i]{result} = $stat{xferOK} ? "ok" : "failed";
588 $Restores[$i]{errorMsg} = $stat{hostError};
589 $Restores[$i]{nFiles} = $tarCreateFileCnt;
590 $Restores[$i]{size} = $tarCreateByteCnt;
591 $Restores[$i]{tarCreateErrs} = $tarCreateErrCnt;
592 $Restores[$i]{xferErrs} = $stat{xferErrCnt} || 0;
594 while ( @Restores > $Conf{RestoreInfoKeepCnt} ) {
595 my $num = $Restores[0]{num};
596 unlink("$Dir/RestoreLOG.$num.z");
597 unlink("$Dir/RestoreLOG.$num");
598 unlink("$Dir/RestoreInfo.$num");
601 $bpc->RestoreInfoWrite($client, @Restores);
603 if ( !$stat{xferOK} ) {
604 print(LOG $bpc->timeStamp, "restore failed ($stat{hostError})\n");
605 print("restore failed: $stat{hostError}\n");
608 $stat{xferErrCnt} ||= 0;
609 print(LOG $bpc->timeStamp, "restore $lastNum complete"
610 . " ($tarCreateFileCnt files, $tarCreateByteCnt bytes,"
611 . " $tarCreateDirCnt dirs, $stat{xferErrCnt} xferErrs)\n");
612 print("restore complete\n");
618 # The Xfer method might tell us from time to time about processes
619 # it forks. We tell BackupPC about this (for status displays) and
620 # keep track of the pids in case we cancel the backup
625 @xferPid = grep(/./, @xferPid);
626 return if ( !@xferPid && $tarPid < 0 );
628 push(@pids, $tarPid) if ( $tarPid > 0 );
629 my $str = join(",", @pids);
630 $RestoreLOG->write(\"Xfer PIDs are now $str\n") if ( defined($RestoreLOG) );
631 print("xferPids $str\n");
635 # Run an optional pre- or post-dump command
641 return if ( !defined($Conf{$cmdType}) );
647 share => $RestoreReq{shareDest},
648 XferMethod => $Conf{XferMethod},
649 sshPath => $Conf{SshPath},
651 user => $Hosts->{$client}{user},
652 moreUsers => $Hosts->{$client}{moreUsers},
653 XferLOG => $RestoreLOG,
655 xferOK => $stat{xferOK} || 0,
656 hostError => $stat{hostError},
658 bkupSrcHost => $RestoreReq{hostSrc},
659 bkupSrcShare => $RestoreReq{shareSrc},
660 bkupSrcNum => $RestoreReq{num},
661 backups => \@Backups,
662 pathHdrSrc => $RestoreReq{pathHdrSrc},
663 pathHdrDest => $RestoreReq{pathHdrDest},
664 fileList => $RestoreReq{fileList},
667 my $cmd = $bpc->cmdVarSubstitute($Conf{$cmdType}, $vars);
668 $RestoreLOG->write(\"Executing $cmdType: @$cmd\n");
670 # Run the user's command, dumping the stdout/stderr into the
671 # Xfer log file. Also supply the optional $vars and %Conf in
672 # case the command is really perl code instead of a shell
675 $bpc->cmdSystemOrEval($cmd,
677 $RestoreLOG->write(\$_[0]);