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();
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);
100 # Read the request file
102 if ( !(my $ret = do "$Dir/$reqFileName") ) {
105 $err = "couldn't parse $Dir/$reqFileName: $@";
106 } elsif ( !defined($ret) ) {
107 $err = "couldn't do $Dir/$reqFileName: $!";
109 $err = "couldn't run $Dir/$reqFileName";
111 $stat{hostError} = $err;
112 exit(RestoreCleanup($client));
116 # Re-read config file, so we can include the PC-specific config
118 if ( defined(my $error = $bpc->ConfigRead($client)) ) {
119 $stat{hostError} = "Can't read PC's config file: $error";
120 exit(RestoreCleanup($client));
122 %Conf = $bpc->Conf();
125 # Make sure we eventually timeout if there is no activity from
126 # the data transport program.
128 alarm($Conf{ClientTimeout});
131 # See if the host name is aliased
133 if ( $Conf{ClientNameAlias} ne "" ) {
134 $host = $Conf{ClientNameAlias};
140 # Find its IP address
142 if ( $hostIP !~ /\d+\.\d+\.\d+\.\d+/ ) {
143 if ( !defined(gethostbyname($host)) ) {
145 # Ok, NS doesn't know about it. Maybe it is a NetBios name
148 if ( !defined($hostIP = $bpc->NetBiosHostIPFind($host)) ) {
149 $stat{hostError} = "Can't find host $host";
150 exit(RestoreCleanup($client));
158 # Check if $host is alive
160 my $delay = $bpc->CheckHostAlive($hostIP);
162 $stat{hostError} = "no ping response from $host ($hostIP)";
163 exit(RestoreCleanup($client));
164 } elsif ( $delay > $Conf{PingMaxMsec} ) {
165 $stat{hostError} = sprintf("ping too slow: %.4gmsec (max is %gmsec)\n",
166 $delay, $Conf{PingMaxMsec});
167 exit(RestoreCleanup($client));
171 # Make sure it is really the machine we expect
173 if ( (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
174 $stat{hostError} = $errMsg;
175 exit(RestoreCleanup($client));
179 # Setup file extension for compression and open RestoreLOG output file
181 $Conf{CompressLevel} = 0 if ( !BackupPC::FileZIO->compOk );
182 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
183 my $RestoreLOG = BackupPC::FileZIO->open("$Dir/RestoreLOG$fileExt", 1,
184 $Conf{CompressLevel});
185 my $tarCreateFileCnt = 0;
186 my $tarCreateByteCnt = 0;
187 my $tarCreateErrCnt = 1; # assume not ok until we learn otherwise
191 $stat{xferOK} = $stat{hostAbort} = undef;
192 $stat{hostError} = $stat{lastOutputLine} = undef;
196 # Run an optional pre-restore command
198 UserCommandRun("RestorePreUserCmd");
201 if ( $Conf{XferMethod} eq "tar" ) {
203 # Use tar (eg: tar/ssh) as the transport program.
205 $xfer = BackupPC::Xfer::Tar->new($bpc);
206 } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
208 # Use rsync as the transport program.
210 if ( !defined($xfer = BackupPC::Xfer::Rsync->new($bpc)) ) {
211 my $errStr = BackupPC::Xfer::Rsync->errStr;
212 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
213 $stat{hostError} = $errStr;
214 exit(RestoreCleanup($client));
218 # Default is to use smbclient (smb) as the transport program.
220 $xfer = BackupPC::Xfer::Smb->new($bpc);
222 my $useTar = $xfer->useTar;
226 # Create a pipe to connect BackupPC_tarCreate to the transport program
227 # (smbclient, tar, etc).
228 # WH is the write handle for writing, provided to BackupPC_tarCreate
229 # and RH is the other end of the pipe for reading provided to the
236 # Run the transport program, which reads from RH and extracts the data.
238 my @Backups = $bpc->BackupInfoRead($RestoreReq{hostSrc});
244 shareName => $RestoreReq{shareDest},
247 XferLOG => $RestoreLOG,
248 XferMethod => $Conf{XferMethod},
249 bkupSrcHost => $RestoreReq{hostSrc},
250 bkupSrcShare => $RestoreReq{shareSrc},
251 bkupSrcNum => $RestoreReq{num},
252 backups => \@Backups,
253 pathHdrSrc => $RestoreReq{pathHdrSrc},
254 pathHdrDest => $RestoreReq{pathHdrDest},
255 fileList => $RestoreReq{fileList},
258 $xfer->args($xferArgs);
260 if ( !defined($logMsg = $xfer->start()) ) {
261 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
262 $stat{hostError} = "xfer start failed: ", $xfer->errStr;
263 exit(RestoreCleanup($client));
268 # Now do the restore by running BackupPC_tarCreate
270 # The parent must close the read handle since the transport program
276 # fork a child for BackupPC_tarCreate. TAR is a file handle
277 # on which we (the parent) read the stderr from BackupPC_tarCreate.
280 if ( defined($RestoreReq{pathHdrDest})
281 && $RestoreReq{pathHdrDest} ne $RestoreReq{pathHdrSrc} ) {
282 @tarPathOpts = ("-r", $RestoreReq{pathHdrSrc},
283 "-p", $RestoreReq{pathHdrDest}
287 "-h", $RestoreReq{hostSrc},
288 "-n", $RestoreReq{num},
289 "-s", $RestoreReq{shareSrc},
292 @{$RestoreReq{fileList}},
294 my $logMsg = "Running: "
295 . $bpc->execCmd2ShellCmd("$BinDir/BackupPC_tarCreate", @tarArgs)
297 $RestoreLOG->write(\$logMsg);
298 if ( !defined($tarPid = open(TAR, "-|")) ) {
300 # FIX: need to cleanup xfer
301 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
302 $stat{hostError} = "Can't fork to run tar";
303 exit(RestoreCleanup($client));
307 # This is the tarCreate child. Clone STDERR to STDOUT,
308 # STDOUT to WH, and then exec BackupPC_tarCreate.
312 open(STDERR, ">&STDOUT");
314 open(STDOUT, ">&WH");
315 exec("$BinDir/BackupPC_tarCreate", @tarArgs);
316 print(LOG $bpc->timeStamp, "can't exec $BinDir/BackupPC_tarCreate\n");
317 # FIX: need to cleanup xfer
321 # The parent must close the write handle since BackupPC_tarCreate
326 $xferPid = $xfer->xferPid;
327 print(LOG $bpc->timeStamp, $logMsg, " (tarPid=$tarPid, xferPid=$xferPid)\n");
328 print("started restore, tarPid=$tarPid, xferPid=$xferPid\n");
331 # Parse the output of the transfer program and BackupPC_tarCreate
332 # while they run. Since we are reading from two or more children
335 my($FDread, $tarOut, $mesg);
336 vec($FDread, fileno(TAR), 1) = 1;
337 $xfer->setSelectMask(\$FDread);
341 last if ( $FDread =~ /^\0*$/ );
342 alarm($Conf{ClientTimeout});
343 select(my $rout = $FDread, undef, $ein, undef);
344 if ( vec($rout, fileno(TAR), 1) ) {
345 if ( sysread(TAR, $mesg, 8192) <= 0 ) {
346 vec($FDread, fileno(TAR), 1) = 0;
348 $tarCreateErrCnt = 1;
349 $tarCreateErr = "BackupPC_tarCreate failed";
355 while ( $tarOut =~ /(.*?)[\n\r]+(.*)/s ) {
358 $RestoreLOG->write(\"tarCreate: $_\n");
359 if ( /^Done: (\d+) files, (\d+) bytes, (\d+) dirs, (\d+) specials, (\d+) errors/ ) {
360 $tarCreateFileCnt = $1;
361 $tarCreateByteCnt = $2;
362 $tarCreateErrCnt = $5;
365 last if ( !$xfer->readOutput(\$FDread, $rout) );
366 while ( my $str = $xfer->logMsgGet ) {
367 print(LOG $bpc->timeStamp, "xfer: $str\n");
369 if ( $xfer->getStats->{fileCnt} == 1 ) {
371 # Make sure it is still the machine we expect. We do this while
372 # the transfer is running to avoid a potential race condition if
373 # the ip address was reassigned by dhcp just before we started
376 if ( my $errMsg = CorrectHostCheck($hostIP, $host) ) {
377 $stat{hostError} = $errMsg;
384 # otherwise the xfer module does everything for us
386 print(LOG $bpc->timeStamp, "Starting restore (tarPid=-1, xferPid=-1)\n");
387 print("started restore, tarPid=-1, xferPid=-1\n");
388 ($tarCreateFileCnt, $tarCreateByteCnt,
389 $tarCreateErrCnt, $tarCreateErr) = $xfer->run();
394 # Merge the xfer status (need to accumulate counts)
396 my $newStat = $xfer->getStats;
397 foreach my $k ( (keys(%stat), keys(%$newStat)) ) {
398 next if ( !defined($newStat->{$k}) );
399 if ( $k =~ /Cnt$/ ) {
400 $stat{$k} += $newStat->{$k};
401 delete($newStat->{$k});
404 if ( !defined($stat{$k}) ) {
405 $stat{$k} = $newStat->{$k};
406 delete($newStat->{$k});
411 exit(RestoreCleanup($client));
413 ###########################################################################
415 ###########################################################################
419 my($hostIP, $host) = @_;
420 return if ( $hostIP eq $host && !$Conf{FixedIPNetBiosNameCheck}
421 || $Conf{NmbLookupCmd} eq "" );
422 my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($hostIP);
423 return "host $host has mismatching netbios name $netBiosHost"
424 if ( $netBiosHost ne $host );
433 # Note: needs to be tested for each kind of XferMethod
435 print(LOG $bpc->timeStamp, "cleaning up after signal $signame\n");
436 if ( $xferPid > 0 ) {
437 if ( kill(2, $xferPid) <= 0 ) {
443 if ( kill(2, $tarPid) <= 0 ) {
449 $stat{hostError} = "aborted by signal $signame";
453 # Cleanup and update the restore status
459 $stat{xferOK} = 0 if ( $stat{hostError} || $stat{hostAbort}
462 if ( !$stat{xferOK} ) {
464 # kill off the tranfer program, first nicely then forcefully
466 kill(2, $xferPid) if ( $xferPid > 0 );
468 kill(9, $xferPid) if ( $xferPid > 0 );
470 # kill off the tar process, first nicely then forcefully
472 kill(2, $tarPid) if ( $tarPid > 0 );
474 kill(9, $tarPid) if ( $tarPid > 0 );
481 # Do one last check to make sure it is still the machine we expect.
483 if ( $stat{xferOK} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
484 $stat{hostError} = $errMsg;
487 @Restores = $bpc->RestoreInfoRead($client);
488 for ( my $i = 0 ; $i < @Restores ; $i++ ) {
489 $lastNum = $Restores[$i]{num} if ( $lastNum < $Restores[$i]{num} );
494 # Run an optional post-restore command
496 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
498 $RestoreLOG->close() if ( defined($RestoreLOG) );
499 rename("$Dir/RestoreLOG$fileExt", "$Dir/RestoreLOG.$lastNum$fileExt");
500 rename("$Dir/$reqFileName", "$Dir/RestoreInfo.$lastNum");
501 my $endTime = time();
504 # If the restore failed, clean up
506 if ( !$stat{xferOK} ) {
508 # wait a short while and see if the system is still alive
510 $stat{hostError} ||= $tarCreateErr if ( $tarCreateErr ne "" );
511 $stat{hostError} = $stat{lastOutputLine} if ( $stat{hostError} eq "" );
513 if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
514 $stat{hostAbort} = 1;
516 if ( $stat{hostAbort} && $stat{hostError} eq "" ) {
517 $stat{hostError} = "lost network connection during restore";
522 # Add the new restore information to the restore file
524 @Restores = $bpc->RestoreInfoRead($client);
526 $Restores[$i]{num} = $lastNum;
527 $Restores[$i]{startTime} = $startTime;
528 $Restores[$i]{endTime} = $endTime;
529 $Restores[$i]{result} = $stat{xferOK} ? "ok" : "failed";
530 $Restores[$i]{errorMsg} = $stat{hostError};
531 $Restores[$i]{nFiles} = $tarCreateFileCnt;
532 $Restores[$i]{size} = $tarCreateByteCnt;
533 $Restores[$i]{tarCreateErrs} = $tarCreateErrCnt;
534 $Restores[$i]{xferErrs} = $stat{xferErrCnt} || 0;
536 while ( @Restores > $Conf{RestoreInfoKeepCnt} ) {
537 my $num = $Restores[0]{num};
538 unlink("$Dir/RestoreLOG.$num.z");
539 unlink("$Dir/RestoreLOG.$num");
540 unlink("$Dir/RestoreInfo.$num");
543 $bpc->RestoreInfoWrite($client, @Restores);
545 if ( !$stat{xferOK} ) {
546 print(LOG $bpc->timeStamp, "Restore aborted ($stat{hostError})\n");
547 print("restore failed: $stat{hostError}\n");
550 print("restore complete\n");
556 # Run an optional pre- or post-dump command
562 return if ( !defined($Conf{$type}) );
567 share => $RestoreReq{shareDest},
568 XferMethod => $Conf{XferMethod},
569 sshPath => $Conf{SshPath},
571 XferLOG => $RestoreLOG,
573 xferOK => $stat{xferOK},
575 bkupSrcHost => $RestoreReq{hostSrc},
576 bkupSrcShare => $RestoreReq{shareSrc},
577 bkupSrcNum => $RestoreReq{num},
578 backups => \@Backups,
579 pathHdrSrc => $RestoreReq{pathHdrSrc},
580 pathHdrDest => $RestoreReq{pathHdrDest},
581 fileList => $RestoreReq{fileList},
583 my $cmd = $bpc->cmdVarSubstitute($Conf{$type}, $vars);
584 $RestoreLOG->write(\"Executing $type: @$cmd\n");
586 # Run the user's command, dumping the stdout/stderr into the
587 # Xfer log file. Also supply the optional $vars and %Conf in
588 # case the command is really perl code instead of a shell
591 $bpc->cmdSystemOrEval($cmd,
593 $RestoreLOG->write(\$_[0]);