- added $Conf{ClientNameAlias}, which allows the host name to be
[BackupPC.git] / bin / BackupPC_restore
1 #!/bin/perl -T
2 #============================================================= -*-perl-*-
3 #
4 # BackupPC_restore: Restore files to a client.
5 #
6 # DESCRIPTION
7 #
8 #   Usage: BackupPC_restore <hostIP> <client> <reqFileName>
9 #
10 # AUTHOR
11 #   Craig Barratt  <cbarratt@users.sourceforge.net>
12 #
13 # COPYRIGHT
14 #   Copyright (C) 2001  Craig Barratt
15 #
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.
20 #
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.
25 #
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
29 #
30 #========================================================================
31 #
32 # Version 2.0.0_CVS, released 18 Jan 2003.
33 #
34 # See http://backuppc.sourceforge.net.
35 #
36 #========================================================================
37
38 use strict;
39 use lib "/usr/local/BackupPC/lib";
40 use BackupPC::Lib;
41 use BackupPC::FileZIO;
42 use BackupPC::Xfer::Smb;
43 use BackupPC::Xfer::Tar;
44 use BackupPC::Xfer::Rsync;
45
46 use File::Path;
47 use Getopt::Std;
48
49 use vars qw( %RestoreReq );
50
51 ###########################################################################
52 # Initialize
53 ###########################################################################
54
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();
59 my $NeedPostCmd;
60
61 my($hostIP, $host, $client, $reqFileName, %stat);
62
63 $bpc->ChildInit();
64
65 if ( @ARGV != 3 ) {
66     print("usage: $0 <hostIP> <client> <reqFileName>\n");
67     exit(1);
68 }
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");
73     exit(1);
74 }
75 $reqFileName = $1;
76
77 my $startTime = time();
78
79 my $Hosts = $bpc->HostInfoRead();
80
81 my $Dir     = "$TopDir/pc/$client";
82 my $xferPid = -1;
83 my $tarPid  = -1;
84
85 #
86 # Catch various signals
87 #
88 $SIG{INT}  = \&catch_signal;
89 $SIG{ALRM} = \&catch_signal;
90 $SIG{TERM} = \&catch_signal;
91
92 mkpath($Dir, 0, 0777) if ( !-d $Dir );
93 if ( !-f "$Dir/LOCK" ) {
94     open(LOCK, ">", "$Dir/LOCK") && close(LOCK);
95 }
96 open(LOG, ">>", "$Dir/LOG");
97 select(LOG); $| = 1; select(STDOUT);
98
99 #
100 # Read the request file
101 #
102 if ( !(my $ret = do "$Dir/$reqFileName") ) {
103     my $err;
104     if ( $@ ) {
105         $err = "couldn't parse $Dir/$reqFileName: $@";
106     } elsif ( !defined($ret) ) {
107         $err = "couldn't do $Dir/$reqFileName: $!";
108     } else {
109         $err = "couldn't run $Dir/$reqFileName";
110     }
111     $stat{hostError} = $err;
112     exit(RestoreCleanup($client));
113 }
114
115 #
116 # Re-read config file, so we can include the PC-specific config
117 #
118 if ( defined(my $error = $bpc->ConfigRead($client)) ) {
119     $stat{hostError} = "Can't read PC's config file: $error";
120     exit(RestoreCleanup($client));
121 }
122 %Conf = $bpc->Conf();
123
124 #
125 # Make sure we eventually timeout if there is no activity from
126 # the data transport program.
127 #
128 alarm($Conf{ClientTimeout});
129
130 #
131 # See if the host name is aliased
132 #
133 if ( $Conf{ClientNameAlias} ne "" ) {
134     $host = $Conf{ClientNameAlias};
135 } else {
136     $host = $client;
137 }
138
139 #
140 # Find its IP address
141 #
142 if ( $hostIP !~ /\d+\.\d+\.\d+\.\d+/ ) {
143     if ( !defined(gethostbyname($host)) ) {
144         #
145         # Ok, NS doesn't know about it.  Maybe it is a NetBios name
146         # instead.
147         #
148         if ( !defined($hostIP = $bpc->NetBiosHostIPFind($host)) ) {
149             $stat{hostError} = "Can't find host $host";
150             exit(RestoreCleanup($client));
151         }
152     } else {
153         $hostIP = $host;
154     }
155 }
156
157 #
158 # Check if $host is alive
159 #
160 my $delay = $bpc->CheckHostAlive($hostIP);
161 if ( $delay < 0 ) {
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));
168 }
169
170 #
171 # Make sure it is really the machine we expect
172 #
173 if ( (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
174     $stat{hostError} = $errMsg;
175     exit(RestoreCleanup($client));
176 }
177
178 #
179 # Setup file extension for compression and open RestoreLOG output file
180 #
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
188 my $tarCreateErr;
189 my($logMsg, $xfer);
190
191 $stat{xferOK} = $stat{hostAbort} = undef;
192 $stat{hostError} = $stat{lastOutputLine} = undef;
193 local(*RH, *WH);
194
195 #
196 # Run an optional pre-restore command
197 #
198 UserCommandRun("RestorePreUserCmd");
199 $NeedPostCmd = 1;
200
201 if ( $Conf{XferMethod} eq "tar" ) {
202     #
203     # Use tar (eg: tar/ssh) as the transport program.
204     #
205     $xfer = BackupPC::Xfer::Tar->new($bpc);
206 } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
207     #
208     # Use rsync as the transport program.
209     #
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));
215     }
216 } else {
217     #
218     # Default is to use smbclient (smb) as the transport program.
219     #
220     $xfer = BackupPC::Xfer::Smb->new($bpc);
221 }
222 my $useTar = $xfer->useTar;
223
224 if ( $useTar ) {
225     #
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
230     # transport program.
231     #
232     pipe(RH, WH);
233 }
234
235 #
236 # Run the transport program, which reads from RH and extracts the data.
237 #
238 my @Backups = $bpc->BackupInfoRead($RestoreReq{hostSrc});
239 my $xferArgs = {
240     client       => $client,
241     host         => $host,
242     hostIP       => $hostIP,
243     type         => "restore",
244     shareName    => $RestoreReq{shareDest},
245     pipeRH       => *RH,
246     pipeWH       => *WH,
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},
256 };
257
258 $xfer->args($xferArgs);
259
260 if ( !defined($logMsg = $xfer->start()) ) {
261     UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
262     $stat{hostError} = "xfer start failed: ", $xfer->errStr;
263     exit(RestoreCleanup($client));
264 }
265
266 if ( $useTar ) {
267     #
268     # Now do the restore by running BackupPC_tarCreate
269     #
270     # The parent must close the read handle since the transport program
271     # is using it.
272     #
273     close(RH);
274
275     #
276     # fork a child for BackupPC_tarCreate.  TAR is a file handle
277     # on which we (the parent) read the stderr from BackupPC_tarCreate.
278     #
279     my @tarPathOpts;
280     if ( defined($RestoreReq{pathHdrDest})
281                 && $RestoreReq{pathHdrDest} ne $RestoreReq{pathHdrSrc} ) {
282         @tarPathOpts = ("-r", $RestoreReq{pathHdrSrc},
283                         "-p", $RestoreReq{pathHdrDest}
284                 );
285     }
286     my @tarArgs = (
287              "-h", $RestoreReq{hostSrc},
288              "-n", $RestoreReq{num},
289              "-s", $RestoreReq{shareSrc},
290              "-t",
291              @tarPathOpts,
292              @{$RestoreReq{fileList}},
293     );
294     my $logMsg = "Running: "
295                . $bpc->execCmd2ShellCmd("$BinDir/BackupPC_tarCreate", @tarArgs)
296                . "\n";
297     $RestoreLOG->write(\$logMsg);
298     if ( !defined($tarPid = open(TAR, "-|")) ) {
299         close(WH);
300         # FIX: need to cleanup xfer
301         UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
302         $stat{hostError} = "Can't fork to run tar";
303         exit(RestoreCleanup($client));
304     }
305     if ( !$tarPid ) {
306         #
307         # This is the tarCreate child.  Clone STDERR to STDOUT,
308         # STDOUT to WH, and then exec BackupPC_tarCreate.
309         #
310         setpgrp 0,0;
311         close(STDERR);
312         open(STDERR, ">&STDOUT");
313         close(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
318         exit(0);
319     }
320     #
321     # The parent must close the write handle since BackupPC_tarCreate
322     # is using it.
323     #
324     close(WH);
325
326     $xferPid = $xfer->xferPid;
327     print(LOG $bpc->timeStamp, $logMsg, " (tarPid=$tarPid, xferPid=$xferPid)\n");
328     print("started restore, tarPid=$tarPid, xferPid=$xferPid\n");
329
330     #
331     # Parse the output of the transfer program and BackupPC_tarCreate
332     # while they run.  Since we are reading from two or more children
333     # we use a select.
334     #
335     my($FDread, $tarOut, $mesg);
336     vec($FDread, fileno(TAR), 1) = 1;
337     $xfer->setSelectMask(\$FDread);
338
339     SCAN: while ( 1 ) {
340         my $ein = $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;
347                 if ( !close(TAR) ) {
348                     $tarCreateErrCnt  = 1;
349                     $tarCreateErr = "BackupPC_tarCreate failed";
350                 }
351             } else {
352                 $tarOut .= $mesg;
353             }
354         }
355         while ( $tarOut =~ /(.*?)[\n\r]+(.*)/s ) {
356             $_ = $1;
357             $tarOut = $2;
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;
363             }
364         }
365         last if ( !$xfer->readOutput(\$FDread, $rout) );
366         while ( my $str = $xfer->logMsgGet ) {
367             print(LOG $bpc->timeStamp, "xfer: $str\n");
368         }
369         if ( $xfer->getStats->{fileCnt} == 1 ) {
370             #
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
374             # the transfer.
375             #
376             if ( my $errMsg = CorrectHostCheck($hostIP, $host) ) {
377                 $stat{hostError} = $errMsg;
378                 last SCAN;
379             }
380         }
381     }
382 } else {
383     #
384     # otherwise the xfer module does everything for us
385     #
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();
390 }
391 alarm(0);
392
393 #
394 # Merge the xfer status (need to accumulate counts)
395 #
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});
402         next;
403     }
404     if ( !defined($stat{$k}) ) {
405         $stat{$k} = $newStat->{$k};
406         delete($newStat->{$k});
407         next;
408     }
409 }
410
411 exit(RestoreCleanup($client));
412
413 ###########################################################################
414 # Subroutines
415 ###########################################################################
416
417 sub CorrectHostCheck
418 {
419     my($hostIP, $host) = @_;
420     return if ( $hostIP eq $host && !$Conf{FixedIPNetBiosNameCheck} );
421     my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($hostIP);
422     return "host $host has mismatching netbios name $netBiosHost"
423             if ( $netBiosHost ne $host );
424     return;
425 }
426
427 sub catch_signal
428 {
429     my $signame = shift;
430
431     #
432     # Note: needs to be tested for each kind of XferMethod
433     #
434     print(LOG $bpc->timeStamp, "cleaning up after signal $signame\n");
435     if ( $xferPid > 0 ) {
436         if ( kill(2, $xferPid) <= 0 ) {
437             sleep(1);
438             kill(9, $xferPid);
439         }
440     }
441     if ( $tarPid > 0 ) {
442         if ( kill(2, $tarPid) <= 0 ) {
443             sleep(1);
444             kill(9, $tarPid);
445         }
446     }
447     $stat{xferOK} = 0;
448     $stat{hostError} = "aborted by signal $signame";
449 }
450
451 #
452 # Cleanup and update the restore status
453 #
454 sub RestoreCleanup
455 {
456     my($client) = @_;
457
458     $stat{xferOK} = 0 if ( $stat{hostError} || $stat{hostAbort}
459                         || $tarCreateErr );
460
461     if ( !$stat{xferOK} ) {
462         #
463         # kill off the tranfer program, first nicely then forcefully
464         #
465         kill(2, $xferPid) if ( $xferPid > 0 );
466         sleep(1);
467         kill(9, $xferPid) if ( $xferPid > 0 );
468         #
469         # kill off the tar process, first nicely then forcefully
470         #
471         kill(2, $tarPid) if ( $tarPid > 0 );
472         sleep(1);
473         kill(9, $tarPid) if ( $tarPid > 0 );
474     }
475
476     my $lastNum  = -1;
477     my @Restores;
478
479     #
480     # Do one last check to make sure it is still the machine we expect.
481     #
482     if ( $stat{xferOK} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
483         $stat{hostError} = $errMsg;
484         $stat{xferOK} = 0;
485     }
486     @Restores = $bpc->RestoreInfoRead($client);
487     for ( my $i = 0 ; $i < @Restores ; $i++ ) {
488         $lastNum = $Restores[$i]{num} if ( $lastNum < $Restores[$i]{num} );
489     }
490     $lastNum++;
491
492     #
493     # Run an optional post-restore command
494     #
495     UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
496
497     $RestoreLOG->close() if ( defined($RestoreLOG) );
498     rename("$Dir/RestoreLOG$fileExt", "$Dir/RestoreLOG.$lastNum$fileExt");
499     rename("$Dir/$reqFileName", "$Dir/RestoreInfo.$lastNum");
500     my $endTime = time();
501
502     #
503     # If the restore failed, clean up
504     #
505     if ( !$stat{xferOK} ) {
506         #
507         # wait a short while and see if the system is still alive
508         #
509         $stat{hostError} ||= $tarCreateErr if ( $tarCreateErr ne "" );
510         $stat{hostError} = $stat{lastOutputLine} if ( $stat{hostError} eq "" );
511         sleep(2);
512         if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
513             $stat{hostAbort} = 1;
514         }
515         if ( $stat{hostAbort} && $stat{hostError} eq "" ) {
516             $stat{hostError} = "lost network connection during restore";
517         }
518     }
519
520     #
521     # Add the new restore information to the restore file
522     #
523     @Restores = $bpc->RestoreInfoRead($client);
524     my $i = @Restores;
525     $Restores[$i]{num}           = $lastNum;
526     $Restores[$i]{startTime}     = $startTime;
527     $Restores[$i]{endTime}       = $endTime;
528     $Restores[$i]{result}        = $stat{xferOK} ? "ok" : "failed";
529     $Restores[$i]{errorMsg}      = $stat{hostError};
530     $Restores[$i]{nFiles}        = $tarCreateFileCnt;
531     $Restores[$i]{size}          = $tarCreateByteCnt;
532     $Restores[$i]{tarCreateErrs} = $tarCreateErrCnt;
533     $Restores[$i]{xferErrs}      = $stat{xferErrCnt} || 0;
534
535     while ( @Restores > $Conf{RestoreInfoKeepCnt} ) {
536         my $num = $Restores[0]{num};
537         unlink("$Dir/RestoreLOG.$num.z");
538         unlink("$Dir/RestoreLOG.$num");
539         unlink("$Dir/RestoreInfo.$num");
540         shift(@Restores);
541     }
542     $bpc->RestoreInfoWrite($client, @Restores);
543
544     if ( !$stat{xferOK} ) {
545         print(LOG $bpc->timeStamp, "Restore aborted ($stat{hostError})\n");
546         print("restore failed: $stat{hostError}\n");
547         return 1;
548     } else {
549         print("restore complete\n");
550         return;
551     }
552 }
553
554 #
555 # Run an optional pre- or post-dump command
556 #
557 sub UserCommandRun
558 {
559     my($type) = @_;
560
561     return if ( !defined($Conf{$type}) );
562     my $vars = {
563         xfer         => $xfer,
564         host         => $host,
565         hostIP       => $hostIP,
566         share        => $RestoreReq{shareDest},
567         XferMethod   => $Conf{XferMethod},
568         LOG          => *LOG,
569         XferLOG      => $RestoreLOG,
570         stat         => \%stat,
571         xferOK       => $stat{xferOK},
572         type         => $type,
573         bkupSrcHost  => $RestoreReq{hostSrc},
574         bkupSrcShare => $RestoreReq{shareSrc},
575         bkupSrcNum   => $RestoreReq{num},
576         backups      => \@Backups,
577         pathHdrSrc   => $RestoreReq{pathHdrSrc},
578         pathHdrDest  => $RestoreReq{pathHdrDest},
579         fileList     => $RestoreReq{fileList},
580     };
581     my $cmd = $bpc->cmdVarSubstitute($Conf{$type}, $vars);
582     $RestoreLOG->write(\"Executing $type: @$cmd\n");
583     #
584     # Run the user's command, dumping the stdout/stderr into the
585     # Xfer log file.  Also supply the optional $vars and %Conf in
586     # case the command is really perl code instead of a shell
587     # command.
588     #
589     $bpc->cmdSystemOrEval($cmd,
590             sub {
591                 $RestoreLOG->write(\$_[0]);
592             },
593             $vars, \%Conf);
594 }