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.0_CVS, released 3 Feb 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},
259 $xfer->args($xferArgs);
261 if ( !defined($logMsg = $xfer->start()) ) {
262 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
263 $stat{hostError} = "xfer start failed: ", $xfer->errStr;
264 exit(RestoreCleanup($client));
269 # Now do the restore by running BackupPC_tarCreate
271 # The parent must close the read handle since the transport program
277 # fork a child for BackupPC_tarCreate. TAR is a file handle
278 # on which we (the parent) read the stderr from BackupPC_tarCreate.
281 if ( defined($RestoreReq{pathHdrDest})
282 && $RestoreReq{pathHdrDest} ne $RestoreReq{pathHdrSrc} ) {
283 @tarPathOpts = ("-r", $RestoreReq{pathHdrSrc},
284 "-p", $RestoreReq{pathHdrDest}
288 "-h", $RestoreReq{hostSrc},
289 "-n", $RestoreReq{num},
290 "-s", $RestoreReq{shareSrc},
293 @{$RestoreReq{fileList}},
295 my $logMsg = "Running: "
296 . $bpc->execCmd2ShellCmd("$BinDir/BackupPC_tarCreate", @tarArgs)
298 $RestoreLOG->write(\$logMsg);
299 if ( !defined($tarPid = open(TAR, "-|")) ) {
301 # FIX: need to cleanup xfer
302 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
303 $stat{hostError} = "Can't fork to run tar";
304 exit(RestoreCleanup($client));
308 # This is the tarCreate child. Clone STDERR to STDOUT,
309 # STDOUT to WH, and then exec BackupPC_tarCreate.
313 open(STDERR, ">&STDOUT");
315 open(STDOUT, ">&WH");
316 exec("$BinDir/BackupPC_tarCreate", @tarArgs);
317 print(LOG $bpc->timeStamp, "can't exec $BinDir/BackupPC_tarCreate\n");
318 # FIX: need to cleanup xfer
322 # The parent must close the write handle since BackupPC_tarCreate
327 $xferPid = $xfer->xferPid;
328 print(LOG $bpc->timeStamp, $logMsg, " (tarPid=$tarPid, xferPid=$xferPid)\n");
329 print("started restore, tarPid=$tarPid, xferPid=$xferPid\n");
332 # Parse the output of the transfer program and BackupPC_tarCreate
333 # while they run. Since we are reading from two or more children
336 my($FDread, $tarOut, $mesg);
337 vec($FDread, fileno(TAR), 1) = 1;
338 $xfer->setSelectMask(\$FDread);
342 last if ( $FDread =~ /^\0*$/ );
343 alarm($Conf{ClientTimeout});
344 select(my $rout = $FDread, undef, $ein, undef);
345 if ( vec($rout, fileno(TAR), 1) ) {
346 if ( sysread(TAR, $mesg, 8192) <= 0 ) {
347 vec($FDread, fileno(TAR), 1) = 0;
349 $tarCreateErrCnt = 1;
350 $tarCreateErr = "BackupPC_tarCreate failed";
356 while ( $tarOut =~ /(.*?)[\n\r]+(.*)/s ) {
359 $RestoreLOG->write(\"tarCreate: $_\n");
360 if ( /^Done: (\d+) files, (\d+) bytes, (\d+) dirs, (\d+) specials, (\d+) errors/ ) {
361 $tarCreateFileCnt = $1;
362 $tarCreateByteCnt = $2;
363 $tarCreateErrCnt = $5;
366 last if ( !$xfer->readOutput(\$FDread, $rout) );
367 while ( my $str = $xfer->logMsgGet ) {
368 print(LOG $bpc->timeStamp, "xfer: $str\n");
370 if ( $xfer->getStats->{fileCnt} == 1 ) {
372 # Make sure it is still the machine we expect. We do this while
373 # the transfer is running to avoid a potential race condition if
374 # the ip address was reassigned by dhcp just before we started
377 if ( my $errMsg = CorrectHostCheck($hostIP, $host) ) {
378 $stat{hostError} = $errMsg;
385 # otherwise the xfer module does everything for us
387 print(LOG $bpc->timeStamp, "Starting restore (tarPid=-1, xferPid=-1)\n");
388 print("started restore, tarPid=-1, xferPid=-1\n");
389 ($tarCreateFileCnt, $tarCreateByteCnt,
390 $tarCreateErrCnt, $tarCreateErr) = $xfer->run();
395 # Merge the xfer status (need to accumulate counts)
397 my $newStat = $xfer->getStats;
398 foreach my $k ( (keys(%stat), keys(%$newStat)) ) {
399 next if ( !defined($newStat->{$k}) );
400 if ( $k =~ /Cnt$/ ) {
401 $stat{$k} += $newStat->{$k};
402 delete($newStat->{$k});
405 if ( !defined($stat{$k}) ) {
406 $stat{$k} = $newStat->{$k};
407 delete($newStat->{$k});
412 exit(RestoreCleanup($client));
414 ###########################################################################
416 ###########################################################################
420 my($hostIP, $host) = @_;
421 return if ( $hostIP eq $host && !$Conf{FixedIPNetBiosNameCheck}
422 || $Conf{NmbLookupCmd} eq "" );
423 my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($hostIP);
424 return "host $host has mismatching netbios name $netBiosHost"
425 if ( $netBiosHost ne $host );
434 # Note: needs to be tested for each kind of XferMethod
436 print(LOG $bpc->timeStamp, "cleaning up after signal $signame\n");
437 if ( $xferPid > 0 ) {
438 if ( kill(2, $xferPid) <= 0 ) {
444 if ( kill(2, $tarPid) <= 0 ) {
450 $stat{hostError} = "aborted by signal $signame";
454 # Cleanup and update the restore status
460 $stat{xferOK} = 0 if ( $stat{hostError} || $stat{hostAbort}
463 if ( !$stat{xferOK} ) {
465 # kill off the tranfer program, first nicely then forcefully
467 kill(2, $xferPid) if ( $xferPid > 0 );
469 kill(9, $xferPid) if ( $xferPid > 0 );
471 # kill off the tar process, first nicely then forcefully
473 kill(2, $tarPid) if ( $tarPid > 0 );
475 kill(9, $tarPid) if ( $tarPid > 0 );
482 # Do one last check to make sure it is still the machine we expect.
484 if ( $stat{xferOK} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
485 $stat{hostError} = $errMsg;
488 @Restores = $bpc->RestoreInfoRead($client);
489 for ( my $i = 0 ; $i < @Restores ; $i++ ) {
490 $lastNum = $Restores[$i]{num} if ( $lastNum < $Restores[$i]{num} );
495 # Run an optional post-restore command
497 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
499 $RestoreLOG->close() if ( defined($RestoreLOG) );
500 rename("$Dir/RestoreLOG$fileExt", "$Dir/RestoreLOG.$lastNum$fileExt");
501 rename("$Dir/$reqFileName", "$Dir/RestoreInfo.$lastNum");
502 my $endTime = time();
505 # If the restore failed, clean up
507 if ( !$stat{xferOK} ) {
509 # wait a short while and see if the system is still alive
511 $stat{hostError} ||= $tarCreateErr if ( $tarCreateErr ne "" );
512 $stat{hostError} = $stat{lastOutputLine} if ( $stat{hostError} eq "" );
514 if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
515 $stat{hostAbort} = 1;
517 if ( $stat{hostAbort} && $stat{hostError} eq "" ) {
518 $stat{hostError} = "lost network connection during restore";
523 # Add the new restore information to the restore file
525 @Restores = $bpc->RestoreInfoRead($client);
527 $Restores[$i]{num} = $lastNum;
528 $Restores[$i]{startTime} = $startTime;
529 $Restores[$i]{endTime} = $endTime;
530 $Restores[$i]{result} = $stat{xferOK} ? "ok" : "failed";
531 $Restores[$i]{errorMsg} = $stat{hostError};
532 $Restores[$i]{nFiles} = $tarCreateFileCnt;
533 $Restores[$i]{size} = $tarCreateByteCnt;
534 $Restores[$i]{tarCreateErrs} = $tarCreateErrCnt;
535 $Restores[$i]{xferErrs} = $stat{xferErrCnt} || 0;
537 while ( @Restores > $Conf{RestoreInfoKeepCnt} ) {
538 my $num = $Restores[0]{num};
539 unlink("$Dir/RestoreLOG.$num.z");
540 unlink("$Dir/RestoreLOG.$num");
541 unlink("$Dir/RestoreInfo.$num");
544 $bpc->RestoreInfoWrite($client, @Restores);
546 if ( !$stat{xferOK} ) {
547 print(LOG $bpc->timeStamp, "Restore aborted ($stat{hostError})\n");
548 print("restore failed: $stat{hostError}\n");
551 print("restore complete\n");
557 # Run an optional pre- or post-dump command
563 return if ( !defined($Conf{$type}) );
568 share => $RestoreReq{shareDest},
569 XferMethod => $Conf{XferMethod},
570 sshPath => $Conf{SshPath},
572 user => $Hosts->{$client}{user},
573 moreUsers => $Hosts->{$client}{moreUsers},
574 XferLOG => $RestoreLOG,
576 xferOK => $stat{xferOK},
578 bkupSrcHost => $RestoreReq{hostSrc},
579 bkupSrcShare => $RestoreReq{shareSrc},
580 bkupSrcNum => $RestoreReq{num},
581 backups => \@Backups,
582 pathHdrSrc => $RestoreReq{pathHdrSrc},
583 pathHdrDest => $RestoreReq{pathHdrDest},
584 fileList => $RestoreReq{fileList},
586 my $cmd = $bpc->cmdVarSubstitute($Conf{$type}, $vars);
587 $RestoreLOG->write(\"Executing $type: @$cmd\n");
589 # Run the user's command, dumping the stdout/stderr into the
590 # Xfer log file. Also supply the optional $vars and %Conf in
591 # case the command is really perl code instead of a shell
594 $bpc->cmdSystemOrEval($cmd,
596 $RestoreLOG->write(\$_[0]);