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 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.0.0beta3, released 1 Jun 2003.
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;
50 use vars qw( %RestoreReq );
52 ###########################################################################
54 ###########################################################################
56 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
57 my $TopDir = $bpc->TopDir();
58 my $BinDir = $bpc->BinDir();
59 my %Conf = $bpc->Conf();
62 my($hostIP, $host, $client, $reqFileName, %stat);
67 print("usage: $0 <hostIP> <client> <reqFileName>\n");
70 $hostIP = $1 if ( $ARGV[0] =~ /(.+)/ );
71 $client = $1 if ( $ARGV[1] =~ /(.+)/ );
72 if ( $ARGV[2] !~ /^([\w.]+)$/ ) {
73 print("$0: bad reqFileName (arg #3): $ARGV[2]\n");
78 my $startTime = time();
80 my $Hosts = $bpc->HostInfoRead($client);
82 my $Dir = "$TopDir/pc/$client";
87 # Catch various signals
89 $SIG{INT} = \&catch_signal;
90 $SIG{ALRM} = \&catch_signal;
91 $SIG{TERM} = \&catch_signal;
92 $SIG{PIPE} = \&catch_signal;
93 $SIG{STOP} = \&catch_signal;
94 $SIG{TSTP} = \&catch_signal;
95 $SIG{TTIN} = \&catch_signal;
98 mkpath($Dir, 0, 0777) if ( !-d $Dir );
99 if ( !-f "$Dir/LOCK" ) {
100 open(LOCK, ">", "$Dir/LOCK") && close(LOCK);
102 open(LOG, ">>", "$Dir/LOG");
103 select(LOG); $| = 1; select(STDOUT);
107 # Read the request file
109 if ( !(my $ret = do "$Dir/$reqFileName") ) {
112 $err = "couldn't parse $Dir/$reqFileName: $@";
113 } elsif ( !defined($ret) ) {
114 $err = "couldn't do $Dir/$reqFileName: $!";
116 $err = "couldn't run $Dir/$reqFileName";
118 $stat{hostError} = $err;
119 exit(RestoreCleanup($client));
123 # Re-read config file, so we can include the PC-specific config
125 if ( defined(my $error = $bpc->ConfigRead($client)) ) {
126 $stat{hostError} = "Can't read PC's config file: $error";
127 exit(RestoreCleanup($client));
129 %Conf = $bpc->Conf();
132 # Make sure we eventually timeout if there is no activity from
133 # the data transport program.
135 alarm($Conf{ClientTimeout});
138 # See if the host name is aliased
140 if ( $Conf{ClientNameAlias} ne "" ) {
141 $host = $Conf{ClientNameAlias};
147 # Find its IP address
149 if ( $hostIP !~ /\d+\.\d+\.\d+\.\d+/ ) {
150 if ( !defined(gethostbyname($host)) ) {
152 # Ok, NS doesn't know about it. Maybe it is a NetBios name
155 if ( !defined($hostIP = $bpc->NetBiosHostIPFind($host)) ) {
156 $stat{hostError} = "Can't find host $host";
157 exit(RestoreCleanup($client));
165 # Check if $host is alive
167 my $delay = $bpc->CheckHostAlive($hostIP);
169 $stat{hostError} = "no ping response from $host ($hostIP)";
170 exit(RestoreCleanup($client));
171 } elsif ( $delay > $Conf{PingMaxMsec} ) {
172 $stat{hostError} = sprintf("ping too slow: %.4gmsec (max is %gmsec)\n",
173 $delay, $Conf{PingMaxMsec});
174 exit(RestoreCleanup($client));
178 # Make sure it is really the machine we expect
180 if ( (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
181 $stat{hostError} = $errMsg;
182 exit(RestoreCleanup($client));
186 # Setup file extension for compression and open RestoreLOG output file
188 $Conf{CompressLevel} = 0 if ( !BackupPC::FileZIO->compOk );
189 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
190 my $RestoreLOG = BackupPC::FileZIO->open("$Dir/RestoreLOG$fileExt", 1,
191 $Conf{CompressLevel});
192 my $tarCreateFileCnt = 0;
193 my $tarCreateByteCnt = 0;
194 my $tarCreateErrCnt = 1; # assume not ok until we learn otherwise
198 $stat{xferOK} = $stat{hostAbort} = undef;
199 $stat{hostError} = $stat{lastOutputLine} = undef;
203 # Run an optional pre-restore command
205 UserCommandRun("RestorePreUserCmd");
208 if ( $Conf{XferMethod} eq "tar" ) {
210 # Use tar (eg: tar/ssh) as the transport program.
212 $xfer = BackupPC::Xfer::Tar->new($bpc);
213 } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
215 # Use rsync as the transport program.
217 if ( !defined($xfer = BackupPC::Xfer::Rsync->new($bpc)) ) {
218 my $errStr = BackupPC::Xfer::Rsync->errStr;
219 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
220 $stat{hostError} = $errStr;
221 exit(RestoreCleanup($client));
225 # Default is to use smbclient (smb) as the transport program.
227 $xfer = BackupPC::Xfer::Smb->new($bpc);
229 my $useTar = $xfer->useTar;
233 # Create a socketpair to connect BackupPC_tarCreate to the transport
234 # program (smbclient, tar, etc).
235 # WH is the write handle for writing, provided to BackupPC_tarCreate
236 # and RH is the other end of the pipe for reading provided to the
239 if ( socketpair(RH, WH, AF_UNIX, SOCK_STREAM, PF_UNSPEC) ) {
240 shutdown(RH, 1); # no writing to this socket
241 shutdown(WH, 0); # no reading from this socket
242 setsockopt(RH, SOL_SOCKET, SO_RCVBUF, 8 * 65536);
243 setsockopt(WH, SOL_SOCKET, SO_SNDBUF, 8 * 65536);
246 # Default to pipe() if socketpair() doesn't work.
253 # Run the transport program, which reads from RH and extracts the data.
255 my @Backups = $bpc->BackupInfoRead($RestoreReq{hostSrc});
261 shareName => $RestoreReq{shareDest},
264 XferLOG => $RestoreLOG,
265 XferMethod => $Conf{XferMethod},
266 bkupSrcHost => $RestoreReq{hostSrc},
267 bkupSrcShare => $RestoreReq{shareSrc},
268 bkupSrcNum => $RestoreReq{num},
269 backups => \@Backups,
270 pathHdrSrc => $RestoreReq{pathHdrSrc},
271 pathHdrDest => $RestoreReq{pathHdrDest},
272 fileList => $RestoreReq{fileList},
273 pidHandler => \&pidHandler,
276 $xfer->args($xferArgs);
278 if ( !defined($logMsg = $xfer->start()) ) {
279 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
280 $stat{hostError} = "xfer start failed: ", $xfer->errStr;
281 exit(RestoreCleanup($client));
286 # Now do the restore by running BackupPC_tarCreate
288 # The parent must close the read handle since the transport program
294 # fork a child for BackupPC_tarCreate. TAR is a file handle
295 # on which we (the parent) read the stderr from BackupPC_tarCreate.
298 if ( defined($RestoreReq{pathHdrDest})
299 && $RestoreReq{pathHdrDest} ne $RestoreReq{pathHdrSrc} ) {
300 @tarPathOpts = ("-r", $RestoreReq{pathHdrSrc},
301 "-p", $RestoreReq{pathHdrDest}
305 "-h", $RestoreReq{hostSrc},
306 "-n", $RestoreReq{num},
307 "-s", $RestoreReq{shareSrc},
310 @{$RestoreReq{fileList}},
312 my $logMsg = "Running: "
313 . $bpc->execCmd2ShellCmd("$BinDir/BackupPC_tarCreate", @tarArgs)
315 $RestoreLOG->write(\$logMsg);
316 if ( !defined($tarPid = open(TAR, "-|")) ) {
318 # FIX: need to cleanup xfer
319 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
320 $stat{hostError} = "Can't fork to run tar";
321 exit(RestoreCleanup($client));
325 # This is the tarCreate child. Clone STDERR to STDOUT,
326 # STDOUT to WH, and then exec BackupPC_tarCreate.
330 open(STDERR, ">&STDOUT");
332 open(STDOUT, ">&WH");
333 exec("$BinDir/BackupPC_tarCreate", @tarArgs);
334 print(LOG $bpc->timeStamp, "can't exec $BinDir/BackupPC_tarCreate\n");
335 # FIX: need to cleanup xfer
339 # The parent must close the write handle since BackupPC_tarCreate
344 @xferPid = $xfer->xferPid;
346 print(LOG $bpc->timeStamp, $logMsg, "\n");
347 print("started_restore\n");
349 pidHandler(@xferPid);
352 # Parse the output of the transfer program and BackupPC_tarCreate
353 # while they run. Since we are reading from two or more children
356 my($FDread, $tarOut, $mesg);
357 vec($FDread, fileno(TAR), 1) = 1;
358 $xfer->setSelectMask(\$FDread);
362 last if ( $FDread =~ /^\0*$/ );
363 alarm($Conf{ClientTimeout});
364 select(my $rout = $FDread, undef, $ein, undef);
365 if ( vec($rout, fileno(TAR), 1) ) {
366 if ( sysread(TAR, $mesg, 8192) <= 0 ) {
367 vec($FDread, fileno(TAR), 1) = 0;
369 $tarCreateErrCnt = 1;
370 $tarCreateErr = "BackupPC_tarCreate failed";
376 while ( $tarOut =~ /(.*?)[\n\r]+(.*)/s ) {
379 $RestoreLOG->write(\"tarCreate: $_\n");
380 if ( /^Done: (\d+) files, (\d+) bytes, (\d+) dirs, (\d+) specials, (\d+) errors/ ) {
381 $tarCreateFileCnt = $1;
382 $tarCreateByteCnt = $2;
383 $tarCreateErrCnt = $5;
386 last if ( !$xfer->readOutput(\$FDread, $rout) );
387 while ( my $str = $xfer->logMsgGet ) {
388 print(LOG $bpc->timeStamp, "xfer: $str\n");
390 if ( $xfer->getStats->{fileCnt} == 1 ) {
392 # Make sure it is still the machine we expect. We do this while
393 # the transfer is running to avoid a potential race condition if
394 # the ip address was reassigned by dhcp just before we started
397 if ( my $errMsg = CorrectHostCheck($hostIP, $host) ) {
398 $stat{hostError} = $errMsg;
405 # otherwise the xfer module does everything for us
407 print(LOG $bpc->timeStamp, "Starting restore\n");
408 print("started_restore\n");
409 ($tarCreateFileCnt, $tarCreateByteCnt,
410 $tarCreateErrCnt, $tarCreateErr) = $xfer->run();
415 # Merge the xfer status (need to accumulate counts)
417 my $newStat = $xfer->getStats;
418 foreach my $k ( (keys(%stat), keys(%$newStat)) ) {
419 next if ( !defined($newStat->{$k}) );
420 if ( $k =~ /Cnt$/ ) {
421 $stat{$k} += $newStat->{$k};
422 delete($newStat->{$k});
425 if ( !defined($stat{$k}) ) {
426 $stat{$k} = $newStat->{$k};
427 delete($newStat->{$k});
432 exit(RestoreCleanup($client));
434 ###########################################################################
436 ###########################################################################
440 my($hostIP, $host) = @_;
441 return if ( $hostIP eq $host && !$Conf{FixedIPNetBiosNameCheck}
442 || $Conf{NmbLookupCmd} eq "" );
443 my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($hostIP);
444 return "host $host has mismatching netbios name $netBiosHost"
445 if ( $netBiosHost ne $host );
454 # Children quit quietly on ALRM
456 exit(1) if ( $Pid != $$ && $signame eq "ALRM" );
459 # Ignore signals in children
461 return if ( $Pid != $$ );
464 # Note: needs to be tested for each kind of XferMethod
466 print(LOG $bpc->timeStamp, "cleaning up after signal $signame\n");
467 $SIG{$signame} = 'IGNORE';
468 $RestoreLOG->write(\"exiting after signal $signame\n");
470 if ( $signame eq "INT" ) {
471 $stat{hostError} = "aborted by user (signal=$signame)";
473 $stat{hostError} = "aborted by signal=$signame";
475 exit(RestoreCleanup($client));
479 # Cleanup and update the restore status
485 $stat{xferOK} = 0 if ( $stat{hostError} || $stat{hostAbort}
488 if ( !$stat{xferOK} ) {
490 # kill off the tranfer program, first nicely then forcefully
498 # kill off the tar process, first nicely then forcefully
511 # Do one last check to make sure it is still the machine we expect.
513 if ( $stat{xferOK} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
514 $stat{hostError} = $errMsg;
517 @Restores = $bpc->RestoreInfoRead($client);
518 for ( my $i = 0 ; $i < @Restores ; $i++ ) {
519 $lastNum = $Restores[$i]{num} if ( $lastNum < $Restores[$i]{num} );
524 # Run an optional post-restore command
526 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
528 rename("$Dir/RestoreLOG$fileExt", "$Dir/RestoreLOG.$lastNum$fileExt");
529 rename("$Dir/$reqFileName", "$Dir/RestoreInfo.$lastNum");
530 my $endTime = time();
533 # If the restore failed, clean up
535 if ( !$stat{xferOK} ) {
537 # wait a short while and see if the system is still alive
539 $stat{hostError} ||= $tarCreateErr if ( $tarCreateErr ne "" );
540 $stat{hostError} = $stat{lastOutputLine} if ( $stat{hostError} eq "" );
542 if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
543 $stat{hostAbort} = 1;
545 if ( $stat{hostAbort} && $stat{hostError} eq "" ) {
546 $stat{hostError} = "lost network connection during restore";
548 $RestoreLOG->write(\"Restore failed: $stat{hostError}\n")
549 if ( defined($RestoreLOG) );
552 $RestoreLOG->close() if ( defined($RestoreLOG) );
555 # Add the new restore information to the restore file
557 @Restores = $bpc->RestoreInfoRead($client);
559 $Restores[$i]{num} = $lastNum;
560 $Restores[$i]{startTime} = $startTime;
561 $Restores[$i]{endTime} = $endTime;
562 $Restores[$i]{result} = $stat{xferOK} ? "ok" : "failed";
563 $Restores[$i]{errorMsg} = $stat{hostError};
564 $Restores[$i]{nFiles} = $tarCreateFileCnt;
565 $Restores[$i]{size} = $tarCreateByteCnt;
566 $Restores[$i]{tarCreateErrs} = $tarCreateErrCnt;
567 $Restores[$i]{xferErrs} = $stat{xferErrCnt} || 0;
569 while ( @Restores > $Conf{RestoreInfoKeepCnt} ) {
570 my $num = $Restores[0]{num};
571 unlink("$Dir/RestoreLOG.$num.z");
572 unlink("$Dir/RestoreLOG.$num");
573 unlink("$Dir/RestoreInfo.$num");
576 $bpc->RestoreInfoWrite($client, @Restores);
578 if ( !$stat{xferOK} ) {
579 print(LOG $bpc->timeStamp, "Restore failed ($stat{hostError})\n");
580 print("restore failed: $stat{hostError}\n");
583 print("restore complete\n");
589 # The Xfer method might tell us from time to time about processes
590 # it forks. We tell BackupPC about this (for status displays) and
591 # keep track of the pids in case we cancel the backup
596 @xferPid = grep(/./, @xferPid);
597 return if ( !@xferPid && $tarPid < 0 );
599 push(@pids, $tarPid) if ( $tarPid > 0 );
600 my $str = join(",", @pids);
601 $RestoreLOG->write(\"Xfer PIDs are now $str\n") if ( defined($RestoreLOG) );
602 print("xferPids $str\n");
606 # Run an optional pre- or post-dump command
612 return if ( !defined($Conf{$type}) );
617 share => $RestoreReq{shareDest},
618 XferMethod => $Conf{XferMethod},
619 sshPath => $Conf{SshPath},
621 user => $Hosts->{$client}{user},
622 moreUsers => $Hosts->{$client}{moreUsers},
623 XferLOG => $RestoreLOG,
625 xferOK => $stat{xferOK},
627 bkupSrcHost => $RestoreReq{hostSrc},
628 bkupSrcShare => $RestoreReq{shareSrc},
629 bkupSrcNum => $RestoreReq{num},
630 backups => \@Backups,
631 pathHdrSrc => $RestoreReq{pathHdrSrc},
632 pathHdrDest => $RestoreReq{pathHdrDest},
633 fileList => $RestoreReq{fileList},
635 my $cmd = $bpc->cmdVarSubstitute($Conf{$type}, $vars);
636 $RestoreLOG->write(\"Executing $type: @$cmd\n");
638 # Run the user's command, dumping the stdout/stderr into the
639 # Xfer log file. Also supply the optional $vars and %Conf in
640 # case the command is really perl code instead of a shell
643 $bpc->cmdSystemOrEval($cmd,
645 $RestoreLOG->write(\$_[0]);