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.0alpha, released 23 Jan 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");
213 if ( $Conf{XferMethod} eq "tar" ) {
215 # Use tar (eg: tar/ssh) as the transport program.
217 $xfer = BackupPC::Xfer::Tar->new($bpc);
218 } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
220 # Use rsync as the transport program.
222 if ( !defined($xfer = BackupPC::Xfer::Rsync->new($bpc)) ) {
223 my $errStr = BackupPC::Xfer::Rsync->errStr;
224 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
225 $stat{hostError} = $errStr;
226 exit(RestoreCleanup($client));
228 } elsif ( $Conf{XferMethod} eq "backuppcd" ) {
230 # Use backuppcd as the transport program.
232 if ( !defined($xfer = BackupPC::Xfer::BackupPCd->new($bpc)) ) {
233 my $errStr = BackupPC::Xfer::BackupPCd->errStr;
234 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
235 $stat{hostError} = $errStr;
236 exit(RestoreCleanup($client));
240 # Default is to use smbclient (smb) as the transport program.
242 $xfer = BackupPC::Xfer::Smb->new($bpc);
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 $logMsg = "Running: "
329 . $bpc->execCmd2ShellCmd("$BinDir/BackupPC_tarCreate", @tarArgs)
331 $RestoreLOG->write(\$logMsg);
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 $tarCreateErrCnt = $5;
404 last if ( !$xfer->readOutput(\$FDread, $rout) );
405 while ( my $str = $xfer->logMsgGet ) {
406 print(LOG $bpc->timeStamp, "xfer: $str\n");
408 if ( $xfer->getStats->{fileCnt} == 1 ) {
410 # Make sure it is still the machine we expect. We do this while
411 # the transfer is running to avoid a potential race condition if
412 # the ip address was reassigned by dhcp just before we started
415 if ( my $errMsg = CorrectHostCheck($hostIP, $host) ) {
416 $stat{hostError} = $errMsg;
423 # otherwise the xfer module does everything for us
425 print(LOG $bpc->timeStamp, "Starting restore\n");
426 print("started_restore\n");
427 ($tarCreateFileCnt, $tarCreateByteCnt,
428 $tarCreateErrCnt, $tarCreateErr) = $xfer->run();
433 # Merge the xfer status (need to accumulate counts)
435 my $newStat = $xfer->getStats;
436 foreach my $k ( (keys(%stat), keys(%$newStat)) ) {
437 next if ( !defined($newStat->{$k}) );
438 if ( $k =~ /Cnt$/ ) {
439 $stat{$k} += $newStat->{$k};
440 delete($newStat->{$k});
443 if ( !defined($stat{$k}) ) {
444 $stat{$k} = $newStat->{$k};
445 delete($newStat->{$k});
450 exit(RestoreCleanup($client));
452 ###########################################################################
454 ###########################################################################
458 my($hostIP, $host) = @_;
459 return if ( $hostIP eq $host && !$Conf{FixedIPNetBiosNameCheck}
460 || $Conf{NmbLookupCmd} eq "" );
461 my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($hostIP);
462 return "host $host has mismatching netbios name $netBiosHost"
463 if ( $netBiosHost ne $host );
472 # Children quit quietly on ALRM
474 exit(1) if ( $Pid != $$ && $signame eq "ALRM" );
477 # Ignore signals in children
479 return if ( $Pid != $$ );
482 # Note: needs to be tested for each kind of XferMethod
484 print(LOG $bpc->timeStamp, "cleaning up after signal $signame\n");
485 $SIG{$signame} = 'IGNORE';
486 $RestoreLOG->write(\"exiting after signal $signame\n");
488 if ( $signame eq "INT" ) {
489 $stat{hostError} = "aborted by user (signal=$signame)";
491 $stat{hostError} = "aborted by signal=$signame";
493 exit(RestoreCleanup($client));
497 # Cleanup and update the restore status
503 $stat{xferOK} = 0 if ( $stat{hostError} || $stat{hostAbort}
506 if ( !$stat{xferOK} ) {
508 # kill off the tranfer program, first nicely then forcefully
511 kill($bpc->sigName2num("INT"), @xferPid);
513 kill($bpc->sigName2num("KILL"), @xferPid);
516 # kill off the tar process, first nicely then forcefully
519 kill($bpc->sigName2num("INT"), $tarPid);
521 kill($bpc->sigName2num("KILL"), $tarPid);
529 # Do one last check to make sure it is still the machine we expect.
531 if ( $stat{xferOK} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
532 $stat{hostError} = $errMsg;
535 @Restores = $bpc->RestoreInfoRead($client);
536 for ( my $i = 0 ; $i < @Restores ; $i++ ) {
537 $lastNum = $Restores[$i]{num} if ( $lastNum < $Restores[$i]{num} );
542 # Run an optional post-restore command
544 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
546 rename("$Dir/RestoreLOG$fileExt", "$Dir/RestoreLOG.$lastNum$fileExt");
547 rename("$Dir/$reqFileName", "$Dir/RestoreInfo.$lastNum");
548 my $endTime = time();
551 # If the restore failed, clean up
553 if ( !$stat{xferOK} ) {
555 # wait a short while and see if the system is still alive
557 $stat{hostError} ||= $tarCreateErr if ( $tarCreateErr ne "" );
558 $stat{hostError} = $stat{lastOutputLine} if ( $stat{hostError} eq "" );
560 if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
561 $stat{hostAbort} = 1;
563 if ( $stat{hostAbort} && $stat{hostError} eq "" ) {
564 $stat{hostError} = "lost network connection during restore";
566 $RestoreLOG->write(\"Restore failed: $stat{hostError}\n")
567 if ( defined($RestoreLOG) );
570 $RestoreLOG->close() if ( defined($RestoreLOG) );
573 # Add the new restore information to the restore file
575 @Restores = $bpc->RestoreInfoRead($client);
577 $Restores[$i]{num} = $lastNum;
578 $Restores[$i]{startTime} = $startTime;
579 $Restores[$i]{endTime} = $endTime;
580 $Restores[$i]{result} = $stat{xferOK} ? "ok" : "failed";
581 $Restores[$i]{errorMsg} = $stat{hostError};
582 $Restores[$i]{nFiles} = $tarCreateFileCnt;
583 $Restores[$i]{size} = $tarCreateByteCnt;
584 $Restores[$i]{tarCreateErrs} = $tarCreateErrCnt;
585 $Restores[$i]{xferErrs} = $stat{xferErrCnt} || 0;
587 while ( @Restores > $Conf{RestoreInfoKeepCnt} ) {
588 my $num = $Restores[0]{num};
589 unlink("$Dir/RestoreLOG.$num.z");
590 unlink("$Dir/RestoreLOG.$num");
591 unlink("$Dir/RestoreInfo.$num");
594 $bpc->RestoreInfoWrite($client, @Restores);
596 if ( !$stat{xferOK} ) {
597 print(LOG $bpc->timeStamp, "Restore failed ($stat{hostError})\n");
598 print("restore failed: $stat{hostError}\n");
601 print("restore complete\n");
607 # The Xfer method might tell us from time to time about processes
608 # it forks. We tell BackupPC about this (for status displays) and
609 # keep track of the pids in case we cancel the backup
614 @xferPid = grep(/./, @xferPid);
615 return if ( !@xferPid && $tarPid < 0 );
617 push(@pids, $tarPid) if ( $tarPid > 0 );
618 my $str = join(",", @pids);
619 $RestoreLOG->write(\"Xfer PIDs are now $str\n") if ( defined($RestoreLOG) );
620 print("xferPids $str\n");
624 # Run an optional pre- or post-dump command
630 return if ( !defined($Conf{$cmdType}) );
636 share => $RestoreReq{shareDest},
637 XferMethod => $Conf{XferMethod},
638 sshPath => $Conf{SshPath},
640 user => $Hosts->{$client}{user},
641 moreUsers => $Hosts->{$client}{moreUsers},
642 XferLOG => $RestoreLOG,
644 xferOK => $stat{xferOK} || 0,
645 hostError => $stat{hostError},
647 bkupSrcHost => $RestoreReq{hostSrc},
648 bkupSrcShare => $RestoreReq{shareSrc},
649 bkupSrcNum => $RestoreReq{num},
650 backups => \@Backups,
651 pathHdrSrc => $RestoreReq{pathHdrSrc},
652 pathHdrDest => $RestoreReq{pathHdrDest},
653 fileList => $RestoreReq{fileList},
656 my $cmd = $bpc->cmdVarSubstitute($Conf{$cmdType}, $vars);
657 $RestoreLOG->write(\"Executing $cmdType: @$cmd\n");
659 # Run the user's command, dumping the stdout/stderr into the
660 # Xfer log file. Also supply the optional $vars and %Conf in
661 # case the command is really perl code instead of a shell
664 $bpc->cmdSystemOrEval($cmd,
666 $RestoreLOG->write(\$_[0]);