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.0beta1, released 30 Mar 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;
49 use vars qw( %RestoreReq );
51 ###########################################################################
53 ###########################################################################
55 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
56 my $TopDir = $bpc->TopDir();
57 my $BinDir = $bpc->BinDir();
58 my %Conf = $bpc->Conf();
61 my($hostIP, $host, $client, $reqFileName, %stat);
66 print("usage: $0 <hostIP> <client> <reqFileName>\n");
69 $hostIP = $1 if ( $ARGV[0] =~ /(.+)/ );
70 $client = $1 if ( $ARGV[1] =~ /(.+)/ );
71 if ( $ARGV[2] !~ /^([\w.]+)$/ ) {
72 print("$0: bad reqFileName (arg #3): $ARGV[2]\n");
77 my $startTime = time();
79 my $Hosts = $bpc->HostInfoRead($client);
81 my $Dir = "$TopDir/pc/$client";
86 # Catch various signals
88 $SIG{INT} = \&catch_signal;
89 $SIG{ALRM} = \&catch_signal;
90 $SIG{TERM} = \&catch_signal;
92 mkpath($Dir, 0, 0777) if ( !-d $Dir );
93 if ( !-f "$Dir/LOCK" ) {
94 open(LOCK, ">", "$Dir/LOCK") && close(LOCK);
96 open(LOG, ">>", "$Dir/LOG");
97 select(LOG); $| = 1; select(STDOUT);
101 # Read the request file
103 if ( !(my $ret = do "$Dir/$reqFileName") ) {
106 $err = "couldn't parse $Dir/$reqFileName: $@";
107 } elsif ( !defined($ret) ) {
108 $err = "couldn't do $Dir/$reqFileName: $!";
110 $err = "couldn't run $Dir/$reqFileName";
112 $stat{hostError} = $err;
113 exit(RestoreCleanup($client));
117 # Re-read config file, so we can include the PC-specific config
119 if ( defined(my $error = $bpc->ConfigRead($client)) ) {
120 $stat{hostError} = "Can't read PC's config file: $error";
121 exit(RestoreCleanup($client));
123 %Conf = $bpc->Conf();
126 # Make sure we eventually timeout if there is no activity from
127 # the data transport program.
129 alarm($Conf{ClientTimeout});
132 # See if the host name is aliased
134 if ( $Conf{ClientNameAlias} ne "" ) {
135 $host = $Conf{ClientNameAlias};
141 # Find its IP address
143 if ( $hostIP !~ /\d+\.\d+\.\d+\.\d+/ ) {
144 if ( !defined(gethostbyname($host)) ) {
146 # Ok, NS doesn't know about it. Maybe it is a NetBios name
149 if ( !defined($hostIP = $bpc->NetBiosHostIPFind($host)) ) {
150 $stat{hostError} = "Can't find host $host";
151 exit(RestoreCleanup($client));
159 # Check if $host is alive
161 my $delay = $bpc->CheckHostAlive($hostIP);
163 $stat{hostError} = "no ping response from $host ($hostIP)";
164 exit(RestoreCleanup($client));
165 } elsif ( $delay > $Conf{PingMaxMsec} ) {
166 $stat{hostError} = sprintf("ping too slow: %.4gmsec (max is %gmsec)\n",
167 $delay, $Conf{PingMaxMsec});
168 exit(RestoreCleanup($client));
172 # Make sure it is really the machine we expect
174 if ( (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
175 $stat{hostError} = $errMsg;
176 exit(RestoreCleanup($client));
180 # Setup file extension for compression and open RestoreLOG output file
182 $Conf{CompressLevel} = 0 if ( !BackupPC::FileZIO->compOk );
183 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
184 my $RestoreLOG = BackupPC::FileZIO->open("$Dir/RestoreLOG$fileExt", 1,
185 $Conf{CompressLevel});
186 my $tarCreateFileCnt = 0;
187 my $tarCreateByteCnt = 0;
188 my $tarCreateErrCnt = 1; # assume not ok until we learn otherwise
192 $stat{xferOK} = $stat{hostAbort} = undef;
193 $stat{hostError} = $stat{lastOutputLine} = undef;
197 # Run an optional pre-restore command
199 UserCommandRun("RestorePreUserCmd");
202 if ( $Conf{XferMethod} eq "tar" ) {
204 # Use tar (eg: tar/ssh) as the transport program.
206 $xfer = BackupPC::Xfer::Tar->new($bpc);
207 } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
209 # Use rsync as the transport program.
211 if ( !defined($xfer = BackupPC::Xfer::Rsync->new($bpc)) ) {
212 my $errStr = BackupPC::Xfer::Rsync->errStr;
213 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
214 $stat{hostError} = $errStr;
215 exit(RestoreCleanup($client));
219 # Default is to use smbclient (smb) as the transport program.
221 $xfer = BackupPC::Xfer::Smb->new($bpc);
223 my $useTar = $xfer->useTar;
227 # Create a pipe to connect BackupPC_tarCreate to the transport program
228 # (smbclient, tar, etc).
229 # WH is the write handle for writing, provided to BackupPC_tarCreate
230 # and RH is the other end of the pipe for reading provided to the
237 # Run the transport program, which reads from RH and extracts the data.
239 my @Backups = $bpc->BackupInfoRead($RestoreReq{hostSrc});
245 shareName => $RestoreReq{shareDest},
248 XferLOG => $RestoreLOG,
249 XferMethod => $Conf{XferMethod},
250 bkupSrcHost => $RestoreReq{hostSrc},
251 bkupSrcShare => $RestoreReq{shareSrc},
252 bkupSrcNum => $RestoreReq{num},
253 backups => \@Backups,
254 pathHdrSrc => $RestoreReq{pathHdrSrc},
255 pathHdrDest => $RestoreReq{pathHdrDest},
256 fileList => $RestoreReq{fileList},
257 pidHandler => \&pidHandler,
260 $xfer->args($xferArgs);
262 if ( !defined($logMsg = $xfer->start()) ) {
263 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
264 $stat{hostError} = "xfer start failed: ", $xfer->errStr;
265 exit(RestoreCleanup($client));
270 # Now do the restore by running BackupPC_tarCreate
272 # The parent must close the read handle since the transport program
278 # fork a child for BackupPC_tarCreate. TAR is a file handle
279 # on which we (the parent) read the stderr from BackupPC_tarCreate.
282 if ( defined($RestoreReq{pathHdrDest})
283 && $RestoreReq{pathHdrDest} ne $RestoreReq{pathHdrSrc} ) {
284 @tarPathOpts = ("-r", $RestoreReq{pathHdrSrc},
285 "-p", $RestoreReq{pathHdrDest}
289 "-h", $RestoreReq{hostSrc},
290 "-n", $RestoreReq{num},
291 "-s", $RestoreReq{shareSrc},
294 @{$RestoreReq{fileList}},
296 my $logMsg = "Running: "
297 . $bpc->execCmd2ShellCmd("$BinDir/BackupPC_tarCreate", @tarArgs)
299 $RestoreLOG->write(\$logMsg);
300 if ( !defined($tarPid = open(TAR, "-|")) ) {
302 # FIX: need to cleanup xfer
303 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
304 $stat{hostError} = "Can't fork to run tar";
305 exit(RestoreCleanup($client));
309 # This is the tarCreate child. Clone STDERR to STDOUT,
310 # STDOUT to WH, and then exec BackupPC_tarCreate.
314 open(STDERR, ">&STDOUT");
316 open(STDOUT, ">&WH");
317 exec("$BinDir/BackupPC_tarCreate", @tarArgs);
318 print(LOG $bpc->timeStamp, "can't exec $BinDir/BackupPC_tarCreate\n");
319 # FIX: need to cleanup xfer
323 # The parent must close the write handle since BackupPC_tarCreate
328 @xferPid = $xfer->xferPid;
330 print(LOG $bpc->timeStamp, $logMsg, "\n");
331 print("started_restore\n");
333 pidHandler(@xferPid);
336 # Parse the output of the transfer program and BackupPC_tarCreate
337 # while they run. Since we are reading from two or more children
340 my($FDread, $tarOut, $mesg);
341 vec($FDread, fileno(TAR), 1) = 1;
342 $xfer->setSelectMask(\$FDread);
346 last if ( $FDread =~ /^\0*$/ );
347 alarm($Conf{ClientTimeout});
348 select(my $rout = $FDread, undef, $ein, undef);
349 if ( vec($rout, fileno(TAR), 1) ) {
350 if ( sysread(TAR, $mesg, 8192) <= 0 ) {
351 vec($FDread, fileno(TAR), 1) = 0;
353 $tarCreateErrCnt = 1;
354 $tarCreateErr = "BackupPC_tarCreate failed";
360 while ( $tarOut =~ /(.*?)[\n\r]+(.*)/s ) {
363 $RestoreLOG->write(\"tarCreate: $_\n");
364 if ( /^Done: (\d+) files, (\d+) bytes, (\d+) dirs, (\d+) specials, (\d+) errors/ ) {
365 $tarCreateFileCnt = $1;
366 $tarCreateByteCnt = $2;
367 $tarCreateErrCnt = $5;
370 last if ( !$xfer->readOutput(\$FDread, $rout) );
371 while ( my $str = $xfer->logMsgGet ) {
372 print(LOG $bpc->timeStamp, "xfer: $str\n");
374 if ( $xfer->getStats->{fileCnt} == 1 ) {
376 # Make sure it is still the machine we expect. We do this while
377 # the transfer is running to avoid a potential race condition if
378 # the ip address was reassigned by dhcp just before we started
381 if ( my $errMsg = CorrectHostCheck($hostIP, $host) ) {
382 $stat{hostError} = $errMsg;
389 # otherwise the xfer module does everything for us
391 print(LOG $bpc->timeStamp, "Starting restore\n");
392 print("started_restore\n");
393 ($tarCreateFileCnt, $tarCreateByteCnt,
394 $tarCreateErrCnt, $tarCreateErr) = $xfer->run();
399 # Merge the xfer status (need to accumulate counts)
401 my $newStat = $xfer->getStats;
402 foreach my $k ( (keys(%stat), keys(%$newStat)) ) {
403 next if ( !defined($newStat->{$k}) );
404 if ( $k =~ /Cnt$/ ) {
405 $stat{$k} += $newStat->{$k};
406 delete($newStat->{$k});
409 if ( !defined($stat{$k}) ) {
410 $stat{$k} = $newStat->{$k};
411 delete($newStat->{$k});
416 exit(RestoreCleanup($client));
418 ###########################################################################
420 ###########################################################################
424 my($hostIP, $host) = @_;
425 return if ( $hostIP eq $host && !$Conf{FixedIPNetBiosNameCheck}
426 || $Conf{NmbLookupCmd} eq "" );
427 my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($hostIP);
428 return "host $host has mismatching netbios name $netBiosHost"
429 if ( $netBiosHost ne $host );
438 # Note: needs to be tested for each kind of XferMethod
440 print(LOG $bpc->timeStamp, "cleaning up after signal $signame\n");
452 $stat{hostError} = "aborted by signal $signame";
456 # Cleanup and update the restore status
462 $stat{xferOK} = 0 if ( $stat{hostError} || $stat{hostAbort}
465 if ( !$stat{xferOK} ) {
467 # kill off the tranfer program, first nicely then forcefully
475 # kill off the tar process, first nicely then forcefully
488 # Do one last check to make sure it is still the machine we expect.
490 if ( $stat{xferOK} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
491 $stat{hostError} = $errMsg;
494 @Restores = $bpc->RestoreInfoRead($client);
495 for ( my $i = 0 ; $i < @Restores ; $i++ ) {
496 $lastNum = $Restores[$i]{num} if ( $lastNum < $Restores[$i]{num} );
501 # Run an optional post-restore command
503 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
505 $RestoreLOG->close() if ( defined($RestoreLOG) );
506 rename("$Dir/RestoreLOG$fileExt", "$Dir/RestoreLOG.$lastNum$fileExt");
507 rename("$Dir/$reqFileName", "$Dir/RestoreInfo.$lastNum");
508 my $endTime = time();
511 # If the restore failed, clean up
513 if ( !$stat{xferOK} ) {
515 # wait a short while and see if the system is still alive
517 $stat{hostError} ||= $tarCreateErr if ( $tarCreateErr ne "" );
518 $stat{hostError} = $stat{lastOutputLine} if ( $stat{hostError} eq "" );
520 if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
521 $stat{hostAbort} = 1;
523 if ( $stat{hostAbort} && $stat{hostError} eq "" ) {
524 $stat{hostError} = "lost network connection during restore";
529 # Add the new restore information to the restore file
531 @Restores = $bpc->RestoreInfoRead($client);
533 $Restores[$i]{num} = $lastNum;
534 $Restores[$i]{startTime} = $startTime;
535 $Restores[$i]{endTime} = $endTime;
536 $Restores[$i]{result} = $stat{xferOK} ? "ok" : "failed";
537 $Restores[$i]{errorMsg} = $stat{hostError};
538 $Restores[$i]{nFiles} = $tarCreateFileCnt;
539 $Restores[$i]{size} = $tarCreateByteCnt;
540 $Restores[$i]{tarCreateErrs} = $tarCreateErrCnt;
541 $Restores[$i]{xferErrs} = $stat{xferErrCnt} || 0;
543 while ( @Restores > $Conf{RestoreInfoKeepCnt} ) {
544 my $num = $Restores[0]{num};
545 unlink("$Dir/RestoreLOG.$num.z");
546 unlink("$Dir/RestoreLOG.$num");
547 unlink("$Dir/RestoreInfo.$num");
550 $bpc->RestoreInfoWrite($client, @Restores);
552 if ( !$stat{xferOK} ) {
553 print(LOG $bpc->timeStamp, "Restore aborted ($stat{hostError})\n");
554 print("restore failed: $stat{hostError}\n");
557 print("restore complete\n");
563 # The Xfer method might tell us from time to time about processes
564 # it forks. We tell BackupPC about this (for status displays) and
565 # keep track of the pids in case we cancel the backup
570 @xferPid = grep(/./, @xferPid);
571 return if ( !@xferPid && $tarPid < 0 );
573 push(@pids, $tarPid) if ( $tarPid > 0 );
574 my $str = join(",", @pids);
575 $XferLOG->write(\"Xfer PIDs are now $str\n") if ( defined($XferLOG) );
576 print("xferPids $str\n");
580 # Run an optional pre- or post-dump command
586 return if ( !defined($Conf{$type}) );
591 share => $RestoreReq{shareDest},
592 XferMethod => $Conf{XferMethod},
593 sshPath => $Conf{SshPath},
595 user => $Hosts->{$client}{user},
596 moreUsers => $Hosts->{$client}{moreUsers},
597 XferLOG => $RestoreLOG,
599 xferOK => $stat{xferOK},
601 bkupSrcHost => $RestoreReq{hostSrc},
602 bkupSrcShare => $RestoreReq{shareSrc},
603 bkupSrcNum => $RestoreReq{num},
604 backups => \@Backups,
605 pathHdrSrc => $RestoreReq{pathHdrSrc},
606 pathHdrDest => $RestoreReq{pathHdrDest},
607 fileList => $RestoreReq{fileList},
609 my $cmd = $bpc->cmdVarSubstitute($Conf{$type}, $vars);
610 $RestoreLOG->write(\"Executing $type: @$cmd\n");
612 # Run the user's command, dumping the stdout/stderr into the
613 # Xfer log file. Also supply the optional $vars and %Conf in
614 # case the command is really perl code instead of a shell
617 $bpc->cmdSystemOrEval($cmd,
619 $RestoreLOG->write(\$_[0]);