- Significant documentation changes for 2.0.0beta0
[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 3 Feb 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($client);
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 #
101 # Read the request file
102 #
103 if ( !(my $ret = do "$Dir/$reqFileName") ) {
104     my $err;
105     if ( $@ ) {
106         $err = "couldn't parse $Dir/$reqFileName: $@";
107     } elsif ( !defined($ret) ) {
108         $err = "couldn't do $Dir/$reqFileName: $!";
109     } else {
110         $err = "couldn't run $Dir/$reqFileName";
111     }
112     $stat{hostError} = $err;
113     exit(RestoreCleanup($client));
114 }
115
116 #
117 # Re-read config file, so we can include the PC-specific config
118 #
119 if ( defined(my $error = $bpc->ConfigRead($client)) ) {
120     $stat{hostError} = "Can't read PC's config file: $error";
121     exit(RestoreCleanup($client));
122 }
123 %Conf = $bpc->Conf();
124
125 #
126 # Make sure we eventually timeout if there is no activity from
127 # the data transport program.
128 #
129 alarm($Conf{ClientTimeout});
130
131 #
132 # See if the host name is aliased
133 #
134 if ( $Conf{ClientNameAlias} ne "" ) {
135     $host = $Conf{ClientNameAlias};
136 } else {
137     $host = $client;
138 }
139
140 #
141 # Find its IP address
142 #
143 if ( $hostIP !~ /\d+\.\d+\.\d+\.\d+/ ) {
144     if ( !defined(gethostbyname($host)) ) {
145         #
146         # Ok, NS doesn't know about it.  Maybe it is a NetBios name
147         # instead.
148         #
149         if ( !defined($hostIP = $bpc->NetBiosHostIPFind($host)) ) {
150             $stat{hostError} = "Can't find host $host";
151             exit(RestoreCleanup($client));
152         }
153     } else {
154         $hostIP = $host;
155     }
156 }
157
158 #
159 # Check if $host is alive
160 #
161 my $delay = $bpc->CheckHostAlive($hostIP);
162 if ( $delay < 0 ) {
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));
169 }
170
171 #
172 # Make sure it is really the machine we expect
173 #
174 if ( (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
175     $stat{hostError} = $errMsg;
176     exit(RestoreCleanup($client));
177 }
178
179 #
180 # Setup file extension for compression and open RestoreLOG output file
181 #
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
189 my $tarCreateErr;
190 my($logMsg, $xfer);
191
192 $stat{xferOK} = $stat{hostAbort} = undef;
193 $stat{hostError} = $stat{lastOutputLine} = undef;
194 local(*RH, *WH);
195
196 #
197 # Run an optional pre-restore command
198 #
199 UserCommandRun("RestorePreUserCmd");
200 $NeedPostCmd = 1;
201
202 if ( $Conf{XferMethod} eq "tar" ) {
203     #
204     # Use tar (eg: tar/ssh) as the transport program.
205     #
206     $xfer = BackupPC::Xfer::Tar->new($bpc);
207 } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
208     #
209     # Use rsync as the transport program.
210     #
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));
216     }
217 } else {
218     #
219     # Default is to use smbclient (smb) as the transport program.
220     #
221     $xfer = BackupPC::Xfer::Smb->new($bpc);
222 }
223 my $useTar = $xfer->useTar;
224
225 if ( $useTar ) {
226     #
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
231     # transport program.
232     #
233     pipe(RH, WH);
234 }
235
236 #
237 # Run the transport program, which reads from RH and extracts the data.
238 #
239 my @Backups = $bpc->BackupInfoRead($RestoreReq{hostSrc});
240 my $xferArgs = {
241     client       => $client,
242     host         => $host,
243     hostIP       => $hostIP,
244     type         => "restore",
245     shareName    => $RestoreReq{shareDest},
246     pipeRH       => *RH,
247     pipeWH       => *WH,
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 };
258
259 $xfer->args($xferArgs);
260
261 if ( !defined($logMsg = $xfer->start()) ) {
262     UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
263     $stat{hostError} = "xfer start failed: ", $xfer->errStr;
264     exit(RestoreCleanup($client));
265 }
266
267 if ( $useTar ) {
268     #
269     # Now do the restore by running BackupPC_tarCreate
270     #
271     # The parent must close the read handle since the transport program
272     # is using it.
273     #
274     close(RH);
275
276     #
277     # fork a child for BackupPC_tarCreate.  TAR is a file handle
278     # on which we (the parent) read the stderr from BackupPC_tarCreate.
279     #
280     my @tarPathOpts;
281     if ( defined($RestoreReq{pathHdrDest})
282                 && $RestoreReq{pathHdrDest} ne $RestoreReq{pathHdrSrc} ) {
283         @tarPathOpts = ("-r", $RestoreReq{pathHdrSrc},
284                         "-p", $RestoreReq{pathHdrDest}
285                 );
286     }
287     my @tarArgs = (
288              "-h", $RestoreReq{hostSrc},
289              "-n", $RestoreReq{num},
290              "-s", $RestoreReq{shareSrc},
291              "-t",
292              @tarPathOpts,
293              @{$RestoreReq{fileList}},
294     );
295     my $logMsg = "Running: "
296                . $bpc->execCmd2ShellCmd("$BinDir/BackupPC_tarCreate", @tarArgs)
297                . "\n";
298     $RestoreLOG->write(\$logMsg);
299     if ( !defined($tarPid = open(TAR, "-|")) ) {
300         close(WH);
301         # FIX: need to cleanup xfer
302         UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
303         $stat{hostError} = "Can't fork to run tar";
304         exit(RestoreCleanup($client));
305     }
306     if ( !$tarPid ) {
307         #
308         # This is the tarCreate child.  Clone STDERR to STDOUT,
309         # STDOUT to WH, and then exec BackupPC_tarCreate.
310         #
311         setpgrp 0,0;
312         close(STDERR);
313         open(STDERR, ">&STDOUT");
314         close(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
319         exit(0);
320     }
321     #
322     # The parent must close the write handle since BackupPC_tarCreate
323     # is using it.
324     #
325     close(WH);
326
327     $xferPid = $xfer->xferPid;
328     print(LOG $bpc->timeStamp, $logMsg, " (tarPid=$tarPid, xferPid=$xferPid)\n");
329     print("started restore, tarPid=$tarPid, xferPid=$xferPid\n");
330
331     #
332     # Parse the output of the transfer program and BackupPC_tarCreate
333     # while they run.  Since we are reading from two or more children
334     # we use a select.
335     #
336     my($FDread, $tarOut, $mesg);
337     vec($FDread, fileno(TAR), 1) = 1;
338     $xfer->setSelectMask(\$FDread);
339
340     SCAN: while ( 1 ) {
341         my $ein = $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;
348                 if ( !close(TAR) ) {
349                     $tarCreateErrCnt  = 1;
350                     $tarCreateErr = "BackupPC_tarCreate failed";
351                 }
352             } else {
353                 $tarOut .= $mesg;
354             }
355         }
356         while ( $tarOut =~ /(.*?)[\n\r]+(.*)/s ) {
357             $_ = $1;
358             $tarOut = $2;
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;
364             }
365         }
366         last if ( !$xfer->readOutput(\$FDread, $rout) );
367         while ( my $str = $xfer->logMsgGet ) {
368             print(LOG $bpc->timeStamp, "xfer: $str\n");
369         }
370         if ( $xfer->getStats->{fileCnt} == 1 ) {
371             #
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
375             # the transfer.
376             #
377             if ( my $errMsg = CorrectHostCheck($hostIP, $host) ) {
378                 $stat{hostError} = $errMsg;
379                 last SCAN;
380             }
381         }
382     }
383 } else {
384     #
385     # otherwise the xfer module does everything for us
386     #
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();
391 }
392 alarm(0);
393
394 #
395 # Merge the xfer status (need to accumulate counts)
396 #
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});
403         next;
404     }
405     if ( !defined($stat{$k}) ) {
406         $stat{$k} = $newStat->{$k};
407         delete($newStat->{$k});
408         next;
409     }
410 }
411
412 exit(RestoreCleanup($client));
413
414 ###########################################################################
415 # Subroutines
416 ###########################################################################
417
418 sub CorrectHostCheck
419 {
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 );
426     return;
427 }
428
429 sub catch_signal
430 {
431     my $signame = shift;
432
433     #
434     # Note: needs to be tested for each kind of XferMethod
435     #
436     print(LOG $bpc->timeStamp, "cleaning up after signal $signame\n");
437     if ( $xferPid > 0 ) {
438         if ( kill(2, $xferPid) <= 0 ) {
439             sleep(1);
440             kill(9, $xferPid);
441         }
442     }
443     if ( $tarPid > 0 ) {
444         if ( kill(2, $tarPid) <= 0 ) {
445             sleep(1);
446             kill(9, $tarPid);
447         }
448     }
449     $stat{xferOK} = 0;
450     $stat{hostError} = "aborted by signal $signame";
451 }
452
453 #
454 # Cleanup and update the restore status
455 #
456 sub RestoreCleanup
457 {
458     my($client) = @_;
459
460     $stat{xferOK} = 0 if ( $stat{hostError} || $stat{hostAbort}
461                         || $tarCreateErr );
462
463     if ( !$stat{xferOK} ) {
464         #
465         # kill off the tranfer program, first nicely then forcefully
466         #
467         kill(2, $xferPid) if ( $xferPid > 0 );
468         sleep(1);
469         kill(9, $xferPid) if ( $xferPid > 0 );
470         #
471         # kill off the tar process, first nicely then forcefully
472         #
473         kill(2, $tarPid) if ( $tarPid > 0 );
474         sleep(1);
475         kill(9, $tarPid) if ( $tarPid > 0 );
476     }
477
478     my $lastNum  = -1;
479     my @Restores;
480
481     #
482     # Do one last check to make sure it is still the machine we expect.
483     #
484     if ( $stat{xferOK} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
485         $stat{hostError} = $errMsg;
486         $stat{xferOK} = 0;
487     }
488     @Restores = $bpc->RestoreInfoRead($client);
489     for ( my $i = 0 ; $i < @Restores ; $i++ ) {
490         $lastNum = $Restores[$i]{num} if ( $lastNum < $Restores[$i]{num} );
491     }
492     $lastNum++;
493
494     #
495     # Run an optional post-restore command
496     #
497     UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
498
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();
503
504     #
505     # If the restore failed, clean up
506     #
507     if ( !$stat{xferOK} ) {
508         #
509         # wait a short while and see if the system is still alive
510         #
511         $stat{hostError} ||= $tarCreateErr if ( $tarCreateErr ne "" );
512         $stat{hostError} = $stat{lastOutputLine} if ( $stat{hostError} eq "" );
513         sleep(2);
514         if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
515             $stat{hostAbort} = 1;
516         }
517         if ( $stat{hostAbort} && $stat{hostError} eq "" ) {
518             $stat{hostError} = "lost network connection during restore";
519         }
520     }
521
522     #
523     # Add the new restore information to the restore file
524     #
525     @Restores = $bpc->RestoreInfoRead($client);
526     my $i = @Restores;
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;
536
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");
542         shift(@Restores);
543     }
544     $bpc->RestoreInfoWrite($client, @Restores);
545
546     if ( !$stat{xferOK} ) {
547         print(LOG $bpc->timeStamp, "Restore aborted ($stat{hostError})\n");
548         print("restore failed: $stat{hostError}\n");
549         return 1;
550     } else {
551         print("restore complete\n");
552         return;
553     }
554 }
555
556 #
557 # Run an optional pre- or post-dump command
558 #
559 sub UserCommandRun
560 {
561     my($type) = @_;
562
563     return if ( !defined($Conf{$type}) );
564     my $vars = {
565         xfer         => $xfer,
566         host         => $host,
567         hostIP       => $hostIP,
568         share        => $RestoreReq{shareDest},
569         XferMethod   => $Conf{XferMethod},
570         sshPath      => $Conf{SshPath},
571         LOG          => *LOG,
572         user         => $Hosts->{$client}{user},
573         moreUsers    => $Hosts->{$client}{moreUsers},
574         XferLOG      => $RestoreLOG,
575         stat         => \%stat,
576         xferOK       => $stat{xferOK},
577         type         => $type,
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},
585     };
586     my $cmd = $bpc->cmdVarSubstitute($Conf{$type}, $vars);
587     $RestoreLOG->write(\"Executing $type: @$cmd\n");
588     #
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
592     # command.
593     #
594     $bpc->cmdSystemOrEval($cmd,
595             sub {
596                 $RestoreLOG->write(\$_[0]);
597             },
598             $vars, \%Conf);
599 }