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 2.1.0_CVS, released 8 Feb 2004.
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;
51 use vars qw( %RestoreReq );
53 ###########################################################################
55 ###########################################################################
57 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
58 my $TopDir = $bpc->TopDir();
59 my $BinDir = $bpc->BinDir();
60 my %Conf = $bpc->Conf();
63 my($hostIP, $host, $client, $reqFileName, %stat);
68 print("usage: $0 <hostIP> <client> <reqFileName>\n");
71 $hostIP = $1 if ( $ARGV[0] =~ /(.+)/ );
72 $client = $1 if ( $ARGV[1] =~ /(.+)/ );
73 if ( $ARGV[2] !~ /^([\w.]+)$/ ) {
74 print("$0: bad reqFileName (arg #3): $ARGV[2]\n");
79 my $startTime = time();
81 my $Hosts = $bpc->HostInfoRead($client);
83 my $Dir = "$TopDir/pc/$client";
88 # Catch various signals
90 $SIG{INT} = \&catch_signal;
91 $SIG{ALRM} = \&catch_signal;
92 $SIG{TERM} = \&catch_signal;
93 $SIG{PIPE} = \&catch_signal;
94 $SIG{STOP} = \&catch_signal;
95 $SIG{TSTP} = \&catch_signal;
96 $SIG{TTIN} = \&catch_signal;
99 mkpath($Dir, 0, 0777) if ( !-d $Dir );
100 if ( !-f "$Dir/LOCK" ) {
101 open(LOCK, ">", "$Dir/LOCK") && close(LOCK);
103 open(LOG, ">>", "$Dir/LOG");
104 select(LOG); $| = 1; select(STDOUT);
108 # Read the request file
110 if ( !(my $ret = do "$Dir/$reqFileName") ) {
113 $err = "couldn't parse $Dir/$reqFileName: $@";
114 } elsif ( !defined($ret) ) {
115 $err = "couldn't do $Dir/$reqFileName: $!";
117 $err = "couldn't run $Dir/$reqFileName";
119 $stat{hostError} = $err;
120 exit(RestoreCleanup($client));
124 # Re-read config file, so we can include the PC-specific config
126 if ( defined(my $error = $bpc->ConfigRead($client)) ) {
127 $stat{hostError} = "Can't read PC's config file: $error";
128 exit(RestoreCleanup($client));
130 %Conf = $bpc->Conf();
133 # Make sure we eventually timeout if there is no activity from
134 # the data transport program.
136 alarm($Conf{ClientTimeout});
139 # See if the host name is aliased
141 if ( $Conf{ClientNameAlias} ne "" ) {
142 $host = $Conf{ClientNameAlias};
148 # Find its IP address
150 if ( $hostIP !~ /\d+\.\d+\.\d+\.\d+/ ) {
151 if ( !defined(gethostbyname($host)) ) {
153 # Ok, NS doesn't know about it. Maybe it is a NetBios name
156 if ( !defined($hostIP = $bpc->NetBiosHostIPFind($host)) ) {
157 $stat{hostError} = "Can't find host $host";
158 exit(RestoreCleanup($client));
166 # Check if $host is alive
168 my $delay = $bpc->CheckHostAlive($hostIP);
170 $stat{hostError} = "no ping response from $host ($hostIP)";
171 exit(RestoreCleanup($client));
172 } elsif ( $delay > $Conf{PingMaxMsec} ) {
173 $stat{hostError} = sprintf("ping too slow: %.4gmsec (max is %gmsec)\n",
174 $delay, $Conf{PingMaxMsec});
175 exit(RestoreCleanup($client));
179 # Make sure it is really the machine we expect
181 if ( (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
182 $stat{hostError} = $errMsg;
183 exit(RestoreCleanup($client));
187 # Setup file extension for compression and open RestoreLOG output file
189 $Conf{CompressLevel} = 0 if ( !BackupPC::FileZIO->compOk );
190 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
191 my $RestoreLOG = BackupPC::FileZIO->open("$Dir/RestoreLOG$fileExt", 1,
192 $Conf{CompressLevel});
193 my $tarCreateFileCnt = 0;
194 my $tarCreateByteCnt = 0;
195 my $tarCreateErrCnt = 1; # assume not ok until we learn otherwise
199 $stat{xferOK} = $stat{hostAbort} = undef;
200 $stat{hostError} = $stat{lastOutputLine} = undef;
204 # Run an optional pre-restore command
206 UserCommandRun("RestorePreUserCmd");
209 if ( $Conf{XferMethod} eq "tar" ) {
211 # Use tar (eg: tar/ssh) as the transport program.
213 $xfer = BackupPC::Xfer::Tar->new($bpc);
214 } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
216 # Use rsync as the transport program.
218 if ( !defined($xfer = BackupPC::Xfer::Rsync->new($bpc)) ) {
219 my $errStr = BackupPC::Xfer::Rsync->errStr;
220 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
221 $stat{hostError} = $errStr;
222 exit(RestoreCleanup($client));
226 # Default is to use smbclient (smb) as the transport program.
228 $xfer = BackupPC::Xfer::Smb->new($bpc);
230 my $useTar = $xfer->useTar;
234 # Create a socketpair to connect BackupPC_tarCreate to the transport
235 # program (smbclient, tar, etc).
236 # WH is the write handle for writing, provided to BackupPC_tarCreate
237 # and RH is the other end of the pipe for reading provided to the
240 if ( socketpair(RH, WH, AF_UNIX, SOCK_STREAM, PF_UNSPEC) ) {
241 shutdown(RH, 1); # no writing to this socket
242 shutdown(WH, 0); # no reading from this socket
243 setsockopt(RH, SOL_SOCKET, SO_RCVBUF, 8 * 65536);
244 setsockopt(WH, SOL_SOCKET, SO_SNDBUF, 8 * 65536);
247 # Default to pipe() if socketpair() doesn't work.
254 # Run the transport program, which reads from RH and extracts the data.
256 my @Backups = $bpc->BackupInfoRead($RestoreReq{hostSrc});
262 shareName => $RestoreReq{shareDest},
265 XferLOG => $RestoreLOG,
266 XferMethod => $Conf{XferMethod},
267 bkupSrcHost => $RestoreReq{hostSrc},
268 bkupSrcShare => $RestoreReq{shareSrc},
269 bkupSrcNum => $RestoreReq{num},
270 backups => \@Backups,
271 pathHdrSrc => $RestoreReq{pathHdrSrc},
272 pathHdrDest => $RestoreReq{pathHdrDest},
273 fileList => $RestoreReq{fileList},
274 pidHandler => \&pidHandler,
277 $xfer->args($xferArgs);
279 if ( !defined($logMsg = $xfer->start()) ) {
280 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
281 $stat{hostError} = "xfer start failed: ", $xfer->errStr;
282 exit(RestoreCleanup($client));
287 # Now do the restore by running BackupPC_tarCreate
289 # The parent must close the read handle since the transport program
295 # fork a child for BackupPC_tarCreate. TAR is a file handle
296 # on which we (the parent) read the stderr from BackupPC_tarCreate.
299 if ( defined($RestoreReq{pathHdrDest})
300 && $RestoreReq{pathHdrDest} ne $RestoreReq{pathHdrSrc} ) {
301 @tarPathOpts = ("-r", $RestoreReq{pathHdrSrc},
302 "-p", $RestoreReq{pathHdrDest}
306 "-h", $RestoreReq{hostSrc},
307 "-n", $RestoreReq{num},
308 "-s", $RestoreReq{shareSrc},
311 @{$RestoreReq{fileList}},
313 my $logMsg = "Running: "
314 . $bpc->execCmd2ShellCmd("$BinDir/BackupPC_tarCreate", @tarArgs)
316 $RestoreLOG->write(\$logMsg);
317 if ( !defined($tarPid = open(TAR, "-|")) ) {
319 # FIX: need to cleanup xfer
320 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
321 $stat{hostError} = "Can't fork to run tar";
322 exit(RestoreCleanup($client));
327 # This is the tarCreate child. Clone STDERR to STDOUT,
328 # STDOUT to WH, and then exec BackupPC_tarCreate.
332 open(STDERR, ">&STDOUT");
334 open(STDOUT, ">&WH");
336 exec("$BinDir/BackupPC_tarCreate", @tarArgs);
337 print(LOG $bpc->timeStamp, "can't exec $BinDir/BackupPC_tarCreate\n");
338 # FIX: need to cleanup xfer
342 # The parent must close the write handle since BackupPC_tarCreate
347 @xferPid = $xfer->xferPid;
349 print(LOG $bpc->timeStamp, $logMsg, "\n");
350 print("started_restore\n");
352 pidHandler(@xferPid);
355 # Parse the output of the transfer program and BackupPC_tarCreate
356 # while they run. Since we are reading from two or more children
359 my($FDread, $tarOut, $mesg);
360 vec($FDread, fileno(TAR), 1) = 1;
361 $xfer->setSelectMask(\$FDread);
365 last if ( $FDread =~ /^\0*$/ );
366 alarm($Conf{ClientTimeout});
367 select(my $rout = $FDread, undef, $ein, undef);
368 if ( vec($rout, fileno(TAR), 1) ) {
369 if ( sysread(TAR, $mesg, 8192) <= 0 ) {
370 vec($FDread, fileno(TAR), 1) = 0;
372 $tarCreateErrCnt = 1;
373 $tarCreateErr = "BackupPC_tarCreate failed";
379 while ( $tarOut =~ /(.*?)[\n\r]+(.*)/s ) {
382 $RestoreLOG->write(\"tarCreate: $_\n");
383 if ( /^Done: (\d+) files, (\d+) bytes, (\d+) dirs, (\d+) specials, (\d+) errors/ ) {
384 $tarCreateFileCnt = $1;
385 $tarCreateByteCnt = $2;
386 $tarCreateErrCnt = $5;
389 last if ( !$xfer->readOutput(\$FDread, $rout) );
390 while ( my $str = $xfer->logMsgGet ) {
391 print(LOG $bpc->timeStamp, "xfer: $str\n");
393 if ( $xfer->getStats->{fileCnt} == 1 ) {
395 # Make sure it is still the machine we expect. We do this while
396 # the transfer is running to avoid a potential race condition if
397 # the ip address was reassigned by dhcp just before we started
400 if ( my $errMsg = CorrectHostCheck($hostIP, $host) ) {
401 $stat{hostError} = $errMsg;
408 # otherwise the xfer module does everything for us
410 print(LOG $bpc->timeStamp, "Starting restore\n");
411 print("started_restore\n");
412 ($tarCreateFileCnt, $tarCreateByteCnt,
413 $tarCreateErrCnt, $tarCreateErr) = $xfer->run();
418 # Merge the xfer status (need to accumulate counts)
420 my $newStat = $xfer->getStats;
421 foreach my $k ( (keys(%stat), keys(%$newStat)) ) {
422 next if ( !defined($newStat->{$k}) );
423 if ( $k =~ /Cnt$/ ) {
424 $stat{$k} += $newStat->{$k};
425 delete($newStat->{$k});
428 if ( !defined($stat{$k}) ) {
429 $stat{$k} = $newStat->{$k};
430 delete($newStat->{$k});
435 exit(RestoreCleanup($client));
437 ###########################################################################
439 ###########################################################################
443 my($hostIP, $host) = @_;
444 return if ( $hostIP eq $host && !$Conf{FixedIPNetBiosNameCheck}
445 || $Conf{NmbLookupCmd} eq "" );
446 my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($hostIP);
447 return "host $host has mismatching netbios name $netBiosHost"
448 if ( $netBiosHost ne $host );
457 # Children quit quietly on ALRM
459 exit(1) if ( $Pid != $$ && $signame eq "ALRM" );
462 # Ignore signals in children
464 return if ( $Pid != $$ );
467 # Note: needs to be tested for each kind of XferMethod
469 print(LOG $bpc->timeStamp, "cleaning up after signal $signame\n");
470 $SIG{$signame} = 'IGNORE';
471 $RestoreLOG->write(\"exiting after signal $signame\n");
473 if ( $signame eq "INT" ) {
474 $stat{hostError} = "aborted by user (signal=$signame)";
476 $stat{hostError} = "aborted by signal=$signame";
478 exit(RestoreCleanup($client));
482 # Cleanup and update the restore status
488 $stat{xferOK} = 0 if ( $stat{hostError} || $stat{hostAbort}
491 if ( !$stat{xferOK} ) {
493 # kill off the tranfer program, first nicely then forcefully
501 # kill off the tar process, first nicely then forcefully
514 # Do one last check to make sure it is still the machine we expect.
516 if ( $stat{xferOK} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
517 $stat{hostError} = $errMsg;
520 @Restores = $bpc->RestoreInfoRead($client);
521 for ( my $i = 0 ; $i < @Restores ; $i++ ) {
522 $lastNum = $Restores[$i]{num} if ( $lastNum < $Restores[$i]{num} );
527 # Run an optional post-restore command
529 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
531 rename("$Dir/RestoreLOG$fileExt", "$Dir/RestoreLOG.$lastNum$fileExt");
532 rename("$Dir/$reqFileName", "$Dir/RestoreInfo.$lastNum");
533 my $endTime = time();
536 # If the restore failed, clean up
538 if ( !$stat{xferOK} ) {
540 # wait a short while and see if the system is still alive
542 $stat{hostError} ||= $tarCreateErr if ( $tarCreateErr ne "" );
543 $stat{hostError} = $stat{lastOutputLine} if ( $stat{hostError} eq "" );
545 if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
546 $stat{hostAbort} = 1;
548 if ( $stat{hostAbort} && $stat{hostError} eq "" ) {
549 $stat{hostError} = "lost network connection during restore";
551 $RestoreLOG->write(\"Restore failed: $stat{hostError}\n")
552 if ( defined($RestoreLOG) );
555 $RestoreLOG->close() if ( defined($RestoreLOG) );
558 # Add the new restore information to the restore file
560 @Restores = $bpc->RestoreInfoRead($client);
562 $Restores[$i]{num} = $lastNum;
563 $Restores[$i]{startTime} = $startTime;
564 $Restores[$i]{endTime} = $endTime;
565 $Restores[$i]{result} = $stat{xferOK} ? "ok" : "failed";
566 $Restores[$i]{errorMsg} = $stat{hostError};
567 $Restores[$i]{nFiles} = $tarCreateFileCnt;
568 $Restores[$i]{size} = $tarCreateByteCnt;
569 $Restores[$i]{tarCreateErrs} = $tarCreateErrCnt;
570 $Restores[$i]{xferErrs} = $stat{xferErrCnt} || 0;
572 while ( @Restores > $Conf{RestoreInfoKeepCnt} ) {
573 my $num = $Restores[0]{num};
574 unlink("$Dir/RestoreLOG.$num.z");
575 unlink("$Dir/RestoreLOG.$num");
576 unlink("$Dir/RestoreInfo.$num");
579 $bpc->RestoreInfoWrite($client, @Restores);
581 if ( !$stat{xferOK} ) {
582 print(LOG $bpc->timeStamp, "Restore failed ($stat{hostError})\n");
583 print("restore failed: $stat{hostError}\n");
586 print("restore complete\n");
592 # The Xfer method might tell us from time to time about processes
593 # it forks. We tell BackupPC about this (for status displays) and
594 # keep track of the pids in case we cancel the backup
599 @xferPid = grep(/./, @xferPid);
600 return if ( !@xferPid && $tarPid < 0 );
602 push(@pids, $tarPid) if ( $tarPid > 0 );
603 my $str = join(",", @pids);
604 $RestoreLOG->write(\"Xfer PIDs are now $str\n") if ( defined($RestoreLOG) );
605 print("xferPids $str\n");
609 # Run an optional pre- or post-dump command
615 return if ( !defined($Conf{$type}) );
621 share => $RestoreReq{shareDest},
622 XferMethod => $Conf{XferMethod},
623 sshPath => $Conf{SshPath},
625 user => $Hosts->{$client}{user},
626 moreUsers => $Hosts->{$client}{moreUsers},
627 XferLOG => $RestoreLOG,
629 xferOK => $stat{xferOK} || 0,
630 hostError => $stat{hostError},
632 bkupSrcHost => $RestoreReq{hostSrc},
633 bkupSrcShare => $RestoreReq{shareSrc},
634 bkupSrcNum => $RestoreReq{num},
635 backups => \@Backups,
636 pathHdrSrc => $RestoreReq{pathHdrSrc},
637 pathHdrDest => $RestoreReq{pathHdrDest},
638 fileList => $RestoreReq{fileList},
640 my $cmd = $bpc->cmdVarSubstitute($Conf{$type}, $vars);
641 $RestoreLOG->write(\"Executing $type: @$cmd\n");
643 # Run the user's command, dumping the stdout/stderr into the
644 # Xfer log file. Also supply the optional $vars and %Conf in
645 # case the command is really perl code instead of a shell
648 $bpc->cmdSystemOrEval($cmd,
650 $RestoreLOG->write(\$_[0]);