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.0, released 28 Jan 2007.
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);
105 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
106 my $logPath = sprintf("$Dir/LOG.%02d%04d", $mon + 1, $year + 1900);
108 if ( !-f $logPath ) {
110 # Compress and prune old log files
112 my $lastLog = $Conf{MaxOldPerPCLogFiles} - 1;
113 foreach my $file ( $bpc->sortedPCLogFiles($client) ) {
114 if ( $lastLog <= 0 ) {
119 next if ( $file =~ /\.z$/ || !$Conf{CompressLevel} );
120 BackupPC::FileZIO->compressCopy($file,
123 $Conf{CompressLevel}, 1);
126 open(LOG, ">>", $logPath);
127 select(LOG); $| = 1; select(STDOUT);
130 # Read the request file
132 if ( !(my $ret = do "$Dir/$reqFileName") ) {
135 $err = "couldn't parse $Dir/$reqFileName: $@";
136 } elsif ( !defined($ret) ) {
137 $err = "couldn't do $Dir/$reqFileName: $!";
139 $err = "couldn't run $Dir/$reqFileName";
141 $stat{hostError} = $err;
142 exit(RestoreCleanup($client));
146 # Re-read config file, so we can include the PC-specific config
148 if ( defined(my $error = $bpc->ConfigRead($client)) ) {
149 $stat{hostError} = "Can't read PC's config file: $error";
150 exit(RestoreCleanup($client));
152 %Conf = $bpc->Conf();
155 # Make sure we eventually timeout if there is no activity from
156 # the data transport program.
158 alarm($Conf{ClientTimeout});
161 # See if the host name is aliased
163 if ( $Conf{ClientNameAlias} ne "" ) {
164 $host = $Conf{ClientNameAlias};
170 # Find its IP address
172 if ( $hostIP !~ /\d+\.\d+\.\d+\.\d+/ ) {
173 if ( !defined(gethostbyname($host)) ) {
175 # Ok, NS doesn't know about it. Maybe it is a NetBios name
178 if ( !defined($hostIP = $bpc->NetBiosHostIPFind($host)) ) {
179 $stat{hostError} = "Can't find host $host";
180 exit(RestoreCleanup($client));
188 # Check if $host is alive
190 my $delay = $bpc->CheckHostAlive($hostIP);
192 $stat{hostError} = "no ping response from $host ($hostIP)";
193 exit(RestoreCleanup($client));
194 } elsif ( $delay > $Conf{PingMaxMsec} ) {
195 $stat{hostError} = sprintf("ping too slow: %.4gmsec (max is %gmsec)\n",
196 $delay, $Conf{PingMaxMsec});
197 exit(RestoreCleanup($client));
201 # Make sure it is really the machine we expect
203 if ( (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
204 $stat{hostError} = $errMsg;
205 exit(RestoreCleanup($client));
209 # Setup file extension for compression and open RestoreLOG output file
211 if ( $Conf{CompressLevel} && !BackupPC::FileZIO->compOk ) {
212 $stat{hostError} = "Compress:Zlib not found";
213 exit(RestoreCleanup($client));
215 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
216 my $RestoreLOG = BackupPC::FileZIO->open("$Dir/RestoreLOG$fileExt", 1,
217 $Conf{CompressLevel});
218 my $tarCreateFileCnt = 0;
219 my $tarCreateByteCnt = 0;
220 my $tarCreateDirCnt = 0;
221 my $tarCreateErrCnt = 1; # assume not ok until we learn otherwise
225 $stat{xferOK} = $stat{hostAbort} = undef;
226 $stat{hostError} = $stat{lastOutputLine} = undef;
230 # Run an optional pre-restore command
232 UserCommandRun("RestorePreUserCmd");
233 if ( $? && $Conf{UserCmdCheckStatus} ) {
234 $stat{hostError} = "RestorePreUserCmd returned error status $?";
235 exit(RestoreCleanup($client));
239 if ( $Conf{XferMethod} eq "tar" ) {
241 # Use tar (eg: tar/ssh) as the transport program.
243 $xfer = BackupPC::Xfer::Tar->new($bpc);
244 } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
246 # Use rsync as the transport program.
248 if ( !defined($xfer = BackupPC::Xfer::Rsync->new($bpc)) ) {
249 my $errStr = BackupPC::Xfer::Rsync->errStr;
250 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
251 $stat{hostError} = $errStr;
252 exit(RestoreCleanup($client));
254 } elsif ( $Conf{XferMethod} eq "backuppcd" ) {
256 # Use backuppcd as the transport program.
258 if ( !defined($xfer = BackupPC::Xfer::BackupPCd->new($bpc)) ) {
259 my $errStr = BackupPC::Xfer::BackupPCd->errStr;
260 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
261 $stat{hostError} = $errStr;
262 exit(RestoreCleanup($client));
266 # Default is to use smbclient (smb) as the transport program.
268 $xfer = BackupPC::Xfer::Smb->new($bpc);
270 my $useTar = $xfer->useTar;
274 # Create a socketpair to connect BackupPC_tarCreate to the transport
275 # program (smbclient, tar, etc).
276 # WH is the write handle for writing, provided to BackupPC_tarCreate
277 # and RH is the other end of the pipe for reading provided to the
280 if ( socketpair(RH, WH, AF_UNIX, SOCK_STREAM, PF_UNSPEC) ) {
281 shutdown(RH, 1); # no writing to this socket
282 shutdown(WH, 0); # no reading from this socket
283 setsockopt(RH, SOL_SOCKET, SO_RCVBUF, 8 * 65536);
284 setsockopt(WH, SOL_SOCKET, SO_SNDBUF, 8 * 65536);
287 # Default to pipe() if socketpair() doesn't work.
294 # Run the transport program, which reads from RH and extracts the data.
296 my @Backups = $bpc->BackupInfoRead($RestoreReq{hostSrc});
302 shareName => $RestoreReq{shareDest},
305 XferLOG => $RestoreLOG,
306 XferMethod => $Conf{XferMethod},
307 logLevel => $Conf{XferLogLevel},
308 bkupSrcHost => $RestoreReq{hostSrc},
309 bkupSrcShare => $RestoreReq{shareSrc},
310 bkupSrcNum => $RestoreReq{num},
311 backups => \@Backups,
312 pathHdrSrc => $RestoreReq{pathHdrSrc},
313 pathHdrDest => $RestoreReq{pathHdrDest},
314 fileList => $RestoreReq{fileList},
315 pidHandler => \&pidHandler,
318 $xfer->args($xferArgs);
320 if ( !defined($logMsg = $xfer->start()) ) {
321 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
322 $stat{hostError} = "xfer start failed: ", $xfer->errStr;
323 exit(RestoreCleanup($client));
328 # Now do the restore by running BackupPC_tarCreate
330 # The parent must close the read handle since the transport program
336 # fork a child for BackupPC_tarCreate. TAR is a file handle
337 # on which we (the parent) read the stderr from BackupPC_tarCreate.
340 if ( defined($RestoreReq{pathHdrDest})
341 && $RestoreReq{pathHdrDest} ne $RestoreReq{pathHdrSrc} ) {
342 @tarPathOpts = ("-r", $RestoreReq{pathHdrSrc},
343 "-p", $RestoreReq{pathHdrDest}
347 "-h", $RestoreReq{hostSrc},
348 "-n", $RestoreReq{num},
349 "-s", $RestoreReq{shareSrc},
352 @{$RestoreReq{fileList}},
354 my $runMsg = "Running: "
355 . $bpc->execCmd2ShellCmd("$BinDir/BackupPC_tarCreate", @tarArgs)
357 $RestoreLOG->write(\$runMsg);
358 if ( !defined($tarPid = open(TAR, "-|")) ) {
360 # FIX: need to cleanup xfer
361 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
362 $stat{hostError} = "Can't fork to run tar";
363 exit(RestoreCleanup($client));
368 # This is the tarCreate child. Clone STDERR to STDOUT,
369 # STDOUT to WH, and then exec BackupPC_tarCreate.
373 open(STDERR, ">&STDOUT");
375 open(STDOUT, ">&WH");
377 exec("$BinDir/BackupPC_tarCreate", @tarArgs);
378 print(LOG $bpc->timeStamp, "can't exec $BinDir/BackupPC_tarCreate\n");
379 # FIX: need to cleanup xfer
383 # The parent must close the write handle since BackupPC_tarCreate
388 @xferPid = $xfer->xferPid;
390 print(LOG $bpc->timeStamp, $logMsg, "\n");
391 print("started_restore\n");
393 pidHandler(@xferPid);
396 # Parse the output of the transfer program and BackupPC_tarCreate
397 # while they run. Since we are reading from two or more children
400 my($FDread, $tarOut, $mesg);
401 vec($FDread, fileno(TAR), 1) = 1;
402 $xfer->setSelectMask(\$FDread);
406 last if ( $FDread =~ /^\0*$/ );
407 alarm($Conf{ClientTimeout});
408 select(my $rout = $FDread, undef, $ein, undef);
409 if ( vec($rout, fileno(TAR), 1) ) {
410 if ( sysread(TAR, $mesg, 8192) <= 0 ) {
411 vec($FDread, fileno(TAR), 1) = 0;
413 $tarCreateErrCnt = 1;
414 $tarCreateErr = "BackupPC_tarCreate failed";
420 while ( $tarOut =~ /(.*?)[\n\r]+(.*)/s ) {
423 $RestoreLOG->write(\"tarCreate: $_\n");
424 if ( /^Done: (\d+) files, (\d+) bytes, (\d+) dirs, (\d+) specials, (\d+) errors/ ) {
425 $tarCreateFileCnt = $1;
426 $tarCreateByteCnt = $2;
427 $tarCreateDirCnt = $3;
428 $tarCreateErrCnt = $5;
431 last if ( !$xfer->readOutput(\$FDread, $rout) );
432 while ( my $str = $xfer->logMsgGet ) {
433 print(LOG $bpc->timeStamp, "xfer: $str\n");
435 if ( $xfer->getStats->{fileCnt} == 1 ) {
437 # Make sure it is still the machine we expect. We do this while
438 # the transfer is running to avoid a potential race condition if
439 # the ip address was reassigned by dhcp just before we started
442 if ( my $errMsg = CorrectHostCheck($hostIP, $host) ) {
443 $stat{hostError} = $errMsg;
450 # otherwise the xfer module does everything for us
452 print(LOG $bpc->timeStamp, $logMsg . "\n");
453 print("started_restore\n");
454 ($tarCreateFileCnt, $tarCreateByteCnt,
455 $tarCreateErrCnt, $tarCreateErr) = $xfer->run();
460 # Merge the xfer status (need to accumulate counts)
462 my $newStat = $xfer->getStats;
463 foreach my $k ( (keys(%stat), keys(%$newStat)) ) {
464 next if ( !defined($newStat->{$k}) );
465 if ( $k =~ /Cnt$/ ) {
466 $stat{$k} += $newStat->{$k};
467 delete($newStat->{$k});
470 if ( !defined($stat{$k}) ) {
471 $stat{$k} = $newStat->{$k};
472 delete($newStat->{$k});
477 exit(RestoreCleanup($client));
479 ###########################################################################
481 ###########################################################################
485 my($hostIP, $host) = @_;
486 return if ( $hostIP eq $host && !$Conf{FixedIPNetBiosNameCheck}
487 || $Conf{NmbLookupCmd} eq "" );
488 my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($hostIP);
489 return "host $host has mismatching netbios name $netBiosHost"
490 if ( $netBiosHost ne $host );
499 # Children quit quietly on ALRM
501 exit(1) if ( $Pid != $$ && $signame eq "ALRM" );
504 # Ignore signals in children
506 return if ( $Pid != $$ );
509 # Note: needs to be tested for each kind of XferMethod
511 print(LOG $bpc->timeStamp, "cleaning up after signal $signame\n");
512 $SIG{$signame} = 'IGNORE';
513 $RestoreLOG->write(\"exiting after signal $signame\n");
515 if ( $signame eq "INT" ) {
516 $stat{hostError} = "aborted by user (signal=$signame)";
518 $stat{hostError} = "aborted by signal=$signame";
520 exit(RestoreCleanup($client));
524 # Cleanup and update the restore status
530 $stat{xferOK} = 0 if ( $stat{hostError} || $stat{hostAbort}
533 if ( !$stat{xferOK} ) {
535 # kill off the tranfer program, first nicely then forcefully
538 kill($bpc->sigName2num("INT"), @xferPid);
540 kill($bpc->sigName2num("KILL"), @xferPid);
543 # kill off the tar process, first nicely then forcefully
546 kill($bpc->sigName2num("INT"), $tarPid);
548 kill($bpc->sigName2num("KILL"), $tarPid);
556 # Do one last check to make sure it is still the machine we expect.
558 if ( $stat{xferOK} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
559 $stat{hostError} = $errMsg;
562 @Restores = $bpc->RestoreInfoRead($client);
563 for ( my $i = 0 ; $i < @Restores ; $i++ ) {
564 $lastNum = $Restores[$i]{num} if ( $lastNum < $Restores[$i]{num} );
569 # Run an optional post-restore command
571 if ( $NeedPostCmd ) {
572 UserCommandRun("RestorePostUserCmd");
573 if ( $? && $Conf{UserCmdCheckStatus} ) {
574 $stat{hostError} = "RestorePostUserCmd returned error status $?";
579 rename("$Dir/RestoreLOG$fileExt", "$Dir/RestoreLOG.$lastNum$fileExt");
580 rename("$Dir/$reqFileName", "$Dir/RestoreInfo.$lastNum");
581 my $endTime = time();
584 # If the restore failed, clean up
586 if ( !$stat{xferOK} ) {
588 # wait a short while and see if the system is still alive
590 $stat{hostError} ||= $tarCreateErr if ( $tarCreateErr ne "" );
591 $stat{hostError} = $stat{lastOutputLine} if ( $stat{hostError} eq "" );
593 if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
594 $stat{hostAbort} = 1;
596 if ( $stat{hostAbort} && $stat{hostError} eq "" ) {
597 $stat{hostError} = "lost network connection during restore";
599 $RestoreLOG->write(\"restore failed: $stat{hostError}\n")
600 if ( defined($RestoreLOG) );
603 $RestoreLOG->close() if ( defined($RestoreLOG) );
606 # Add the new restore information to the restore file
608 @Restores = $bpc->RestoreInfoRead($client);
610 $Restores[$i]{num} = $lastNum;
611 $Restores[$i]{startTime} = $startTime;
612 $Restores[$i]{endTime} = $endTime;
613 $Restores[$i]{result} = $stat{xferOK} ? "ok" : "failed";
614 $Restores[$i]{errorMsg} = $stat{hostError};
615 $Restores[$i]{nFiles} = $tarCreateFileCnt;
616 $Restores[$i]{size} = $tarCreateByteCnt;
617 $Restores[$i]{tarCreateErrs} = $tarCreateErrCnt;
618 $Restores[$i]{xferErrs} = $stat{xferErrCnt} || 0;
620 while ( @Restores > $Conf{RestoreInfoKeepCnt} ) {
621 my $num = $Restores[0]{num};
622 unlink("$Dir/RestoreLOG.$num.z");
623 unlink("$Dir/RestoreLOG.$num");
624 unlink("$Dir/RestoreInfo.$num");
627 $bpc->RestoreInfoWrite($client, @Restores);
629 if ( !$stat{xferOK} ) {
630 print(LOG $bpc->timeStamp, "restore failed ($stat{hostError})\n");
631 print("restore failed: $stat{hostError}\n");
634 $stat{xferErrCnt} ||= 0;
635 print(LOG $bpc->timeStamp, "restore $lastNum complete"
636 . " ($tarCreateFileCnt files, $tarCreateByteCnt bytes,"
637 . " $tarCreateDirCnt dirs, $stat{xferErrCnt} xferErrs)\n");
638 print("restore complete\n");
644 # The Xfer method might tell us from time to time about processes
645 # it forks. We tell BackupPC about this (for status displays) and
646 # keep track of the pids in case we cancel the backup
651 @xferPid = grep(/./, @xferPid);
652 return if ( !@xferPid && $tarPid < 0 );
654 push(@pids, $tarPid) if ( $tarPid > 0 );
655 my $str = join(",", @pids);
656 $RestoreLOG->write(\"Xfer PIDs are now $str\n") if ( defined($RestoreLOG) );
657 print("xferPids $str\n");
661 # Run an optional pre- or post-dump command
667 return if ( !defined($Conf{$cmdType}) );
673 share => $RestoreReq{shareDest},
674 XferMethod => $Conf{XferMethod},
675 sshPath => $Conf{SshPath},
677 user => $Hosts->{$client}{user},
678 moreUsers => $Hosts->{$client}{moreUsers},
679 XferLOG => $RestoreLOG,
681 xferOK => $stat{xferOK} || 0,
682 hostError => $stat{hostError},
684 bkupSrcHost => $RestoreReq{hostSrc},
685 bkupSrcShare => $RestoreReq{shareSrc},
686 bkupSrcNum => $RestoreReq{num},
687 backups => \@Backups,
688 pathHdrSrc => $RestoreReq{pathHdrSrc},
689 pathHdrDest => $RestoreReq{pathHdrDest},
690 fileList => $RestoreReq{fileList},
693 my $cmd = $bpc->cmdVarSubstitute($Conf{$cmdType}, $vars);
694 $RestoreLOG->write(\"Executing $cmdType: @$cmd\n");
696 # Run the user's command, dumping the stdout/stderr into the
697 # Xfer log file. Also supply the optional $vars and %Conf in
698 # case the command is really perl code instead of a shell
701 $bpc->cmdSystemOrEval($cmd,
703 $RestoreLOG->write(\$_[0]);