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-2003 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.0.0beta0, released 11 Jul 2006.
34 # See http://backuppc.sourceforge.net.
36 #========================================================================
40 use lib "/usr/local/BackupPC/lib";
42 use BackupPC::FileZIO;
43 use BackupPC::Xfer::Smb;
44 use BackupPC::Xfer::Tar;
45 use BackupPC::Xfer::Rsync;
46 use BackupPC::Xfer::BackupPCd;
52 use vars qw( %RestoreReq );
54 ###########################################################################
56 ###########################################################################
58 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
59 my $TopDir = $bpc->TopDir();
60 my $BinDir = $bpc->BinDir();
61 my %Conf = $bpc->Conf();
64 my($hostIP, $host, $client, $reqFileName, %stat);
69 print("usage: $0 <hostIP> <client> <reqFileName>\n");
72 $hostIP = $1 if ( $ARGV[0] =~ /(.+)/ );
73 $client = $1 if ( $ARGV[1] =~ /(.+)/ );
74 if ( $ARGV[2] !~ /^([\w.]+)$/ ) {
75 print("$0: bad reqFileName (arg #3): $ARGV[2]\n");
80 my $startTime = time();
82 my $Hosts = $bpc->HostInfoRead($client);
84 my $Dir = "$TopDir/pc/$client";
89 # Catch various signals
91 $SIG{INT} = \&catch_signal;
92 $SIG{ALRM} = \&catch_signal;
93 $SIG{TERM} = \&catch_signal;
94 $SIG{PIPE} = \&catch_signal;
95 $SIG{STOP} = \&catch_signal;
96 $SIG{TSTP} = \&catch_signal;
97 $SIG{TTIN} = \&catch_signal;
100 mkpath($Dir, 0, 0777) if ( !-d $Dir );
101 if ( !-f "$Dir/LOCK" ) {
102 open(LOCK, ">", "$Dir/LOCK") && close(LOCK);
104 open(LOG, ">>", "$Dir/LOG");
105 select(LOG); $| = 1; select(STDOUT);
109 # Read the request file
111 if ( !(my $ret = do "$Dir/$reqFileName") ) {
114 $err = "couldn't parse $Dir/$reqFileName: $@";
115 } elsif ( !defined($ret) ) {
116 $err = "couldn't do $Dir/$reqFileName: $!";
118 $err = "couldn't run $Dir/$reqFileName";
120 $stat{hostError} = $err;
121 exit(RestoreCleanup($client));
125 # Re-read config file, so we can include the PC-specific config
127 if ( defined(my $error = $bpc->ConfigRead($client)) ) {
128 $stat{hostError} = "Can't read PC's config file: $error";
129 exit(RestoreCleanup($client));
131 %Conf = $bpc->Conf();
134 # Make sure we eventually timeout if there is no activity from
135 # the data transport program.
137 alarm($Conf{ClientTimeout});
140 # See if the host name is aliased
142 if ( $Conf{ClientNameAlias} ne "" ) {
143 $host = $Conf{ClientNameAlias};
149 # Find its IP address
151 if ( $hostIP !~ /\d+\.\d+\.\d+\.\d+/ ) {
152 if ( !defined(gethostbyname($host)) ) {
154 # Ok, NS doesn't know about it. Maybe it is a NetBios name
157 if ( !defined($hostIP = $bpc->NetBiosHostIPFind($host)) ) {
158 $stat{hostError} = "Can't find host $host";
159 exit(RestoreCleanup($client));
167 # Check if $host is alive
169 my $delay = $bpc->CheckHostAlive($hostIP);
171 $stat{hostError} = "no ping response from $host ($hostIP)";
172 exit(RestoreCleanup($client));
173 } elsif ( $delay > $Conf{PingMaxMsec} ) {
174 $stat{hostError} = sprintf("ping too slow: %.4gmsec (max is %gmsec)\n",
175 $delay, $Conf{PingMaxMsec});
176 exit(RestoreCleanup($client));
180 # Make sure it is really the machine we expect
182 if ( (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
183 $stat{hostError} = $errMsg;
184 exit(RestoreCleanup($client));
188 # Setup file extension for compression and open RestoreLOG output file
190 if ( $Conf{CompressLevel} && !BackupPC::FileZIO->compOk ) {
191 $stat{hostError} = "Compress:Zlib not found";
192 exit(RestoreCleanup($client));
194 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
195 my $RestoreLOG = BackupPC::FileZIO->open("$Dir/RestoreLOG$fileExt", 1,
196 $Conf{CompressLevel});
197 my $tarCreateFileCnt = 0;
198 my $tarCreateByteCnt = 0;
199 my $tarCreateErrCnt = 1; # assume not ok until we learn otherwise
203 $stat{xferOK} = $stat{hostAbort} = undef;
204 $stat{hostError} = $stat{lastOutputLine} = undef;
208 # Run an optional pre-restore command
210 UserCommandRun("RestorePreUserCmd");
211 if ( $? && $Conf{UserCmdCheckStatus} ) {
212 $stat{hostError} = "RestorePreUserCmd returned error status $?";
213 exit(RestoreCleanup($client));
217 if ( $Conf{XferMethod} eq "tar" ) {
219 # Use tar (eg: tar/ssh) as the transport program.
221 $xfer = BackupPC::Xfer::Tar->new($bpc);
222 } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
224 # Use rsync as the transport program.
226 if ( !defined($xfer = BackupPC::Xfer::Rsync->new($bpc)) ) {
227 my $errStr = BackupPC::Xfer::Rsync->errStr;
228 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
229 $stat{hostError} = $errStr;
230 exit(RestoreCleanup($client));
232 } elsif ( $Conf{XferMethod} eq "backuppcd" ) {
234 # Use backuppcd as the transport program.
236 if ( !defined($xfer = BackupPC::Xfer::BackupPCd->new($bpc)) ) {
237 my $errStr = BackupPC::Xfer::BackupPCd->errStr;
238 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
239 $stat{hostError} = $errStr;
240 exit(RestoreCleanup($client));
244 # Default is to use smbclient (smb) as the transport program.
246 $xfer = BackupPC::Xfer::Smb->new($bpc);
248 my $useTar = $xfer->useTar;
252 # Create a socketpair to connect BackupPC_tarCreate to the transport
253 # program (smbclient, tar, etc).
254 # WH is the write handle for writing, provided to BackupPC_tarCreate
255 # and RH is the other end of the pipe for reading provided to the
258 if ( socketpair(RH, WH, AF_UNIX, SOCK_STREAM, PF_UNSPEC) ) {
259 shutdown(RH, 1); # no writing to this socket
260 shutdown(WH, 0); # no reading from this socket
261 setsockopt(RH, SOL_SOCKET, SO_RCVBUF, 8 * 65536);
262 setsockopt(WH, SOL_SOCKET, SO_SNDBUF, 8 * 65536);
265 # Default to pipe() if socketpair() doesn't work.
272 # Run the transport program, which reads from RH and extracts the data.
274 my @Backups = $bpc->BackupInfoRead($RestoreReq{hostSrc});
280 shareName => $RestoreReq{shareDest},
283 XferLOG => $RestoreLOG,
284 XferMethod => $Conf{XferMethod},
285 logLevel => $Conf{XferLogLevel},
286 bkupSrcHost => $RestoreReq{hostSrc},
287 bkupSrcShare => $RestoreReq{shareSrc},
288 bkupSrcNum => $RestoreReq{num},
289 backups => \@Backups,
290 pathHdrSrc => $RestoreReq{pathHdrSrc},
291 pathHdrDest => $RestoreReq{pathHdrDest},
292 fileList => $RestoreReq{fileList},
293 pidHandler => \&pidHandler,
296 $xfer->args($xferArgs);
298 if ( !defined($logMsg = $xfer->start()) ) {
299 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
300 $stat{hostError} = "xfer start failed: ", $xfer->errStr;
301 exit(RestoreCleanup($client));
306 # Now do the restore by running BackupPC_tarCreate
308 # The parent must close the read handle since the transport program
314 # fork a child for BackupPC_tarCreate. TAR is a file handle
315 # on which we (the parent) read the stderr from BackupPC_tarCreate.
318 if ( defined($RestoreReq{pathHdrDest})
319 && $RestoreReq{pathHdrDest} ne $RestoreReq{pathHdrSrc} ) {
320 @tarPathOpts = ("-r", $RestoreReq{pathHdrSrc},
321 "-p", $RestoreReq{pathHdrDest}
325 "-h", $RestoreReq{hostSrc},
326 "-n", $RestoreReq{num},
327 "-s", $RestoreReq{shareSrc},
330 @{$RestoreReq{fileList}},
332 my $logMsg = "Running: "
333 . $bpc->execCmd2ShellCmd("$BinDir/BackupPC_tarCreate", @tarArgs)
335 $RestoreLOG->write(\$logMsg);
336 if ( !defined($tarPid = open(TAR, "-|")) ) {
338 # FIX: need to cleanup xfer
339 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
340 $stat{hostError} = "Can't fork to run tar";
341 exit(RestoreCleanup($client));
346 # This is the tarCreate child. Clone STDERR to STDOUT,
347 # STDOUT to WH, and then exec BackupPC_tarCreate.
351 open(STDERR, ">&STDOUT");
353 open(STDOUT, ">&WH");
355 exec("$BinDir/BackupPC_tarCreate", @tarArgs);
356 print(LOG $bpc->timeStamp, "can't exec $BinDir/BackupPC_tarCreate\n");
357 # FIX: need to cleanup xfer
361 # The parent must close the write handle since BackupPC_tarCreate
366 @xferPid = $xfer->xferPid;
368 print(LOG $bpc->timeStamp, $logMsg, "\n");
369 print("started_restore\n");
371 pidHandler(@xferPid);
374 # Parse the output of the transfer program and BackupPC_tarCreate
375 # while they run. Since we are reading from two or more children
378 my($FDread, $tarOut, $mesg);
379 vec($FDread, fileno(TAR), 1) = 1;
380 $xfer->setSelectMask(\$FDread);
384 last if ( $FDread =~ /^\0*$/ );
385 alarm($Conf{ClientTimeout});
386 select(my $rout = $FDread, undef, $ein, undef);
387 if ( vec($rout, fileno(TAR), 1) ) {
388 if ( sysread(TAR, $mesg, 8192) <= 0 ) {
389 vec($FDread, fileno(TAR), 1) = 0;
391 $tarCreateErrCnt = 1;
392 $tarCreateErr = "BackupPC_tarCreate failed";
398 while ( $tarOut =~ /(.*?)[\n\r]+(.*)/s ) {
401 $RestoreLOG->write(\"tarCreate: $_\n");
402 if ( /^Done: (\d+) files, (\d+) bytes, (\d+) dirs, (\d+) specials, (\d+) errors/ ) {
403 $tarCreateFileCnt = $1;
404 $tarCreateByteCnt = $2;
405 $tarCreateErrCnt = $5;
408 last if ( !$xfer->readOutput(\$FDread, $rout) );
409 while ( my $str = $xfer->logMsgGet ) {
410 print(LOG $bpc->timeStamp, "xfer: $str\n");
412 if ( $xfer->getStats->{fileCnt} == 1 ) {
414 # Make sure it is still the machine we expect. We do this while
415 # the transfer is running to avoid a potential race condition if
416 # the ip address was reassigned by dhcp just before we started
419 if ( my $errMsg = CorrectHostCheck($hostIP, $host) ) {
420 $stat{hostError} = $errMsg;
427 # otherwise the xfer module does everything for us
429 print(LOG $bpc->timeStamp, "Starting restore\n");
430 print("started_restore\n");
431 ($tarCreateFileCnt, $tarCreateByteCnt,
432 $tarCreateErrCnt, $tarCreateErr) = $xfer->run();
437 # Merge the xfer status (need to accumulate counts)
439 my $newStat = $xfer->getStats;
440 foreach my $k ( (keys(%stat), keys(%$newStat)) ) {
441 next if ( !defined($newStat->{$k}) );
442 if ( $k =~ /Cnt$/ ) {
443 $stat{$k} += $newStat->{$k};
444 delete($newStat->{$k});
447 if ( !defined($stat{$k}) ) {
448 $stat{$k} = $newStat->{$k};
449 delete($newStat->{$k});
454 exit(RestoreCleanup($client));
456 ###########################################################################
458 ###########################################################################
462 my($hostIP, $host) = @_;
463 return if ( $hostIP eq $host && !$Conf{FixedIPNetBiosNameCheck}
464 || $Conf{NmbLookupCmd} eq "" );
465 my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($hostIP);
466 return "host $host has mismatching netbios name $netBiosHost"
467 if ( $netBiosHost ne $host );
476 # Children quit quietly on ALRM
478 exit(1) if ( $Pid != $$ && $signame eq "ALRM" );
481 # Ignore signals in children
483 return if ( $Pid != $$ );
486 # Note: needs to be tested for each kind of XferMethod
488 print(LOG $bpc->timeStamp, "cleaning up after signal $signame\n");
489 $SIG{$signame} = 'IGNORE';
490 $RestoreLOG->write(\"exiting after signal $signame\n");
492 if ( $signame eq "INT" ) {
493 $stat{hostError} = "aborted by user (signal=$signame)";
495 $stat{hostError} = "aborted by signal=$signame";
497 exit(RestoreCleanup($client));
501 # Cleanup and update the restore status
507 $stat{xferOK} = 0 if ( $stat{hostError} || $stat{hostAbort}
510 if ( !$stat{xferOK} ) {
512 # kill off the tranfer program, first nicely then forcefully
515 kill($bpc->sigName2num("INT"), @xferPid);
517 kill($bpc->sigName2num("KILL"), @xferPid);
520 # kill off the tar process, first nicely then forcefully
523 kill($bpc->sigName2num("INT"), $tarPid);
525 kill($bpc->sigName2num("KILL"), $tarPid);
533 # Do one last check to make sure it is still the machine we expect.
535 if ( $stat{xferOK} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
536 $stat{hostError} = $errMsg;
539 @Restores = $bpc->RestoreInfoRead($client);
540 for ( my $i = 0 ; $i < @Restores ; $i++ ) {
541 $lastNum = $Restores[$i]{num} if ( $lastNum < $Restores[$i]{num} );
546 # Run an optional post-restore command
548 if ( $NeedPostCmd ) {
549 UserCommandRun("RestorePostUserCmd");
550 if ( $? && $Conf{UserCmdCheckStatus} ) {
551 $stat{hostError} = "RestorePostUserCmd returned error status $?";
556 rename("$Dir/RestoreLOG$fileExt", "$Dir/RestoreLOG.$lastNum$fileExt");
557 rename("$Dir/$reqFileName", "$Dir/RestoreInfo.$lastNum");
558 my $endTime = time();
561 # If the restore failed, clean up
563 if ( !$stat{xferOK} ) {
565 # wait a short while and see if the system is still alive
567 $stat{hostError} ||= $tarCreateErr if ( $tarCreateErr ne "" );
568 $stat{hostError} = $stat{lastOutputLine} if ( $stat{hostError} eq "" );
570 if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
571 $stat{hostAbort} = 1;
573 if ( $stat{hostAbort} && $stat{hostError} eq "" ) {
574 $stat{hostError} = "lost network connection during restore";
576 $RestoreLOG->write(\"Restore failed: $stat{hostError}\n")
577 if ( defined($RestoreLOG) );
580 $RestoreLOG->close() if ( defined($RestoreLOG) );
583 # Add the new restore information to the restore file
585 @Restores = $bpc->RestoreInfoRead($client);
587 $Restores[$i]{num} = $lastNum;
588 $Restores[$i]{startTime} = $startTime;
589 $Restores[$i]{endTime} = $endTime;
590 $Restores[$i]{result} = $stat{xferOK} ? "ok" : "failed";
591 $Restores[$i]{errorMsg} = $stat{hostError};
592 $Restores[$i]{nFiles} = $tarCreateFileCnt;
593 $Restores[$i]{size} = $tarCreateByteCnt;
594 $Restores[$i]{tarCreateErrs} = $tarCreateErrCnt;
595 $Restores[$i]{xferErrs} = $stat{xferErrCnt} || 0;
597 while ( @Restores > $Conf{RestoreInfoKeepCnt} ) {
598 my $num = $Restores[0]{num};
599 unlink("$Dir/RestoreLOG.$num.z");
600 unlink("$Dir/RestoreLOG.$num");
601 unlink("$Dir/RestoreInfo.$num");
604 $bpc->RestoreInfoWrite($client, @Restores);
606 if ( !$stat{xferOK} ) {
607 print(LOG $bpc->timeStamp, "Restore failed ($stat{hostError})\n");
608 print("restore failed: $stat{hostError}\n");
611 print("restore complete\n");
617 # The Xfer method might tell us from time to time about processes
618 # it forks. We tell BackupPC about this (for status displays) and
619 # keep track of the pids in case we cancel the backup
624 @xferPid = grep(/./, @xferPid);
625 return if ( !@xferPid && $tarPid < 0 );
627 push(@pids, $tarPid) if ( $tarPid > 0 );
628 my $str = join(",", @pids);
629 $RestoreLOG->write(\"Xfer PIDs are now $str\n") if ( defined($RestoreLOG) );
630 print("xferPids $str\n");
634 # Run an optional pre- or post-dump command
640 return if ( !defined($Conf{$cmdType}) );
646 share => $RestoreReq{shareDest},
647 XferMethod => $Conf{XferMethod},
648 sshPath => $Conf{SshPath},
650 user => $Hosts->{$client}{user},
651 moreUsers => $Hosts->{$client}{moreUsers},
652 XferLOG => $RestoreLOG,
654 xferOK => $stat{xferOK} || 0,
655 hostError => $stat{hostError},
657 bkupSrcHost => $RestoreReq{hostSrc},
658 bkupSrcShare => $RestoreReq{shareSrc},
659 bkupSrcNum => $RestoreReq{num},
660 backups => \@Backups,
661 pathHdrSrc => $RestoreReq{pathHdrSrc},
662 pathHdrDest => $RestoreReq{pathHdrDest},
663 fileList => $RestoreReq{fileList},
666 my $cmd = $bpc->cmdVarSubstitute($Conf{$cmdType}, $vars);
667 $RestoreLOG->write(\"Executing $cmdType: @$cmd\n");
669 # Run the user's command, dumping the stdout/stderr into the
670 # Xfer log file. Also supply the optional $vars and %Conf in
671 # case the command is really perl code instead of a shell
674 $bpc->cmdSystemOrEval($cmd,
676 $RestoreLOG->write(\$_[0]);