* Completed support for rsync and rsyncd, including restore.
[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> <host> <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 1.6.0_CVS, released 10 Dec 2002.
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, $reqFileName);
62
63 $bpc->ChildInit();
64
65 if ( @ARGV != 3 ) {
66     print("usage: $0 <hostIP> <host> <reqFileName>\n");
67     exit(1);
68 }
69 $hostIP = $1 if ( $ARGV[0] =~ /(.+)/ );
70 $host   = $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 $Hosts = $bpc->HostInfoRead();
78
79 #
80 # Re-read config file, so we can include the PC-specific config
81 #
82 if ( defined(my $error = $bpc->ConfigRead($host)) ) {
83     print("Can't read PC's config file: $error\n");
84     exit(1);
85 }
86 %Conf = $bpc->Conf();
87
88 my $Dir     = "$TopDir/pc/$host";
89 my $xferPid = -1;
90 my $tarPid  = -1;
91
92 #
93 # Catch various signals
94 #
95 $SIG{INT}  = \&catch_signal;
96 $SIG{ALRM} = \&catch_signal;
97 $SIG{TERM} = \&catch_signal;
98
99 #
100 # Read the request file
101 #
102 if ( !(my $ret = do "$Dir/$reqFileName") ) {
103    die "couldn't parse $Dir/$reqFileName: $@" if $@;
104    die "couldn't do $Dir/$reqFileName: $!"    unless defined $ret;
105    die "couldn't run $Dir/$reqFileName";
106 }
107
108 #
109 # Make sure we eventually timeout if there is no activity from
110 # the data transport program.
111 #
112 alarm($Conf{ClientTimeout});
113
114 mkpath($Dir, 0, 0777) if ( !-d $Dir );
115 if ( !-f "$Dir/LOCK" ) {
116     open(LOCK, ">$Dir/LOCK") && close(LOCK);
117 }
118 open(LOG, ">>$Dir/LOG");
119 select(LOG); $| = 1; select(STDOUT);
120
121 #
122 # Check if $host is alive
123 #
124 my $delay = $bpc->CheckHostAlive($hostIP);
125 if ( $delay < 0 ) {
126     print(LOG $bpc->timeStamp, "no ping response\n");
127     print("no ping response\n");
128     exit(1);
129 } elsif ( $delay > $Conf{PingMaxMsec} ) {
130     printf(LOG "%sping too slow: %.4gmsec\n", $bpc->timeStamp, $delay);
131     printf("ping too slow: %.4gmsec (threshold is %gmsec)\n",
132                     $delay, $Conf{PingMaxMsec});
133     exit(1);
134 }
135
136 #
137 # Make sure it is really the machine we expect
138 #
139 if ( (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
140     print(LOG $bpc->timeStamp, "restore failed: $errMsg\n");
141     print("restore failed: $errMsg\n");
142     exit(1);
143 }
144
145 #
146 # Setup file extension for compression and open RestoreLOG output file
147 #
148 $Conf{CompressLevel} = 0 if ( !BackupPC::FileZIO->compOk );
149 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
150 my $RestoreLOG = BackupPC::FileZIO->open("$Dir/RestoreLOG$fileExt", 1,
151                                      $Conf{CompressLevel});
152 my $startTime = time();
153
154 my $tarCreateFileCnt = 0;
155 my $tarCreateByteCnt = 0;
156 my $tarCreateErrCnt  = 1;       # assume not ok until we learn otherwise
157 my $tarCreateErr;
158 my($logMsg, %stat, $xfer);
159
160 $stat{xferOK} = $stat{hostAbort} = undef;
161 $stat{hostError} = $stat{lastOutputLine} = undef;
162 local(*RH, *WH);
163
164 #
165 # Run an optional pre-restore command
166 #
167 UserCommandRun("RestorePreUserCmd");
168 $NeedPostCmd = 1;
169
170 if ( $Conf{XferMethod} eq "tar" ) {
171     #
172     # Use tar (eg: tar/ssh) as the transport program.
173     #
174     $xfer = BackupPC::Xfer::Tar->new($bpc);
175 } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
176     #
177     # Use rsync as the transport program.
178     #
179     if ( !defined($xfer = BackupPC::Xfer::Rsync->new($bpc)) ) {
180         my $errStr = BackupPC::Xfer::Rsync->errStr;
181         print(LOG $bpc->timeStamp, "restore failed: $errStr\n");
182         print("restore failed: $errStr\n");
183         UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
184         exit(1);
185     }
186 } else {
187     #
188     # Default is to use smbclient (smb) as the transport program.
189     #
190     $xfer = BackupPC::Xfer::Smb->new($bpc);
191 }
192 my $useTar = $xfer->useTar;
193
194 if ( $useTar ) {
195     #
196     # Create a pipe to connect BackupPC_tarCreate to the transport program
197     # (smbclient, tar, etc).
198     # WH is the write handle for writing, provided to BackupPC_tarCreate
199     # and RH is the other end of the pipe for reading provided to the
200     # transport program.
201     #
202     pipe(RH, WH);
203 }
204
205 #
206 # Run the transport program, which reads from RH and extracts the data.
207 #
208 my @Backups = $bpc->BackupInfoRead($RestoreReq{hostSrc});
209 my $xferArgs = {
210     host         => $host,
211     hostIP       => $hostIP,
212     type         => "restore",
213     shareName    => $RestoreReq{shareDest},
214     pipeRH       => *RH,
215     pipeWH       => *WH,
216     XferLOG      => $RestoreLOG,
217     XferMethod   => $Conf{XferMethod},
218     bkupSrcHost  => $RestoreReq{hostSrc},
219     bkupSrcShare => $RestoreReq{shareSrc},
220     bkupSrcNum   => $RestoreReq{num},
221     backups      => \@Backups,
222     pathHdrSrc   => $RestoreReq{pathHdrSrc},
223     pathHdrDest  => $RestoreReq{pathHdrDest},
224     fileList     => $RestoreReq{fileList},
225 };
226
227 $xfer->args($xferArgs);
228
229 if ( !defined($logMsg = $xfer->start()) ) {
230     print(LOG $bpc->timeStamp, "xfer start failed: ", $xfer->errStr, "\n");
231     print($xfer->errStr, "\n");
232     UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
233     exit(1);
234 }
235
236 if ( $useTar ) {
237     #
238     # Now do the restore by running BackupPC_tarCreate
239     #
240     # The parent must close the read handle since the transport program
241     # is using it.
242     #
243     close(RH);
244
245     #
246     # fork a child for BackupPC_tarCreate.  TAR is a file handle
247     # on which we (the parent) read the stderr from BackupPC_tarCreate.
248     #
249     my @tarPathOpts;
250     if ( defined($RestoreReq{pathHdrDest})
251                 && $RestoreReq{pathHdrDest} ne $RestoreReq{pathHdrSrc} ) {
252         @tarPathOpts = ("-r", $RestoreReq{pathHdrSrc},
253                         "-p", $RestoreReq{pathHdrDest}
254                 );
255     }
256     my @tarArgs = (
257              "-h", $RestoreReq{hostSrc},
258              "-n", $RestoreReq{num},
259              "-s", $RestoreReq{shareSrc},
260              "-t",
261              @tarPathOpts,
262              @{$RestoreReq{fileList}},
263     );
264     my $logMsg = "Running: $BinDir/BackupPC_tarCreate "
265                       . join(" ", @tarArgs) . "\n";
266     $RestoreLOG->write(\$logMsg);
267     if ( !defined($tarPid = open(TAR, "-|")) ) {
268         print(LOG $bpc->timeStamp, "can't fork to run tar\n");
269         print("can't fork to run tar\n");
270         close(WH);
271         # FIX: need to cleanup xfer
272         UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
273         exit(0);
274     }
275     if ( !$tarPid ) {
276         #
277         # This is the tarCreate child.  Clone STDERR to STDOUT,
278         # STDOUT to WH, and then exec BackupPC_tarCreate.
279         #
280         setpgrp 0,0;
281         close(STDERR);
282         open(STDERR, ">&STDOUT");
283         close(STDOUT);
284         open(STDOUT, ">&WH");
285         exec("$BinDir/BackupPC_tarCreate", @tarArgs);
286         print(LOG $bpc->timeStamp, "can't exec $BinDir/BackupPC_tarCreate\n");
287         # FIX: need to cleanup xfer
288         exit(0);
289     }
290     #
291     # The parent must close the write handle since BackupPC_tarCreate
292     # is using it.
293     #
294     close(WH);
295
296     $xferPid = $xfer->xferPid;
297     print(LOG $bpc->timeStamp, $logMsg, " (tarPid=$tarPid, xferPid=$xferPid)\n");
298     print("started restore, tarPid=$tarPid, xferPid=$xferPid\n");
299
300     #
301     # Parse the output of the transfer program and BackupPC_tarCreate
302     # while they run.  Since we are reading from two or more children
303     # we use a select.
304     #
305     my($FDread, $tarOut, $mesg);
306     vec($FDread, fileno(TAR), 1) = 1;
307     $xfer->setSelectMask(\$FDread);
308
309     SCAN: while ( 1 ) {
310         my $ein = $FDread;
311         last if ( $FDread =~ /^\0*$/ );
312         alarm($Conf{ClientTimeout});
313         select(my $rout = $FDread, undef, $ein, undef);
314         if ( vec($rout, fileno(TAR), 1) ) {
315             if ( sysread(TAR, $mesg, 8192) <= 0 ) {
316                 vec($FDread, fileno(TAR), 1) = 0;
317                 if ( !close(TAR) ) {
318                     $tarCreateErrCnt  = 1;
319                     $tarCreateErr = "BackupPC_tarCreate failed";
320                 }
321             } else {
322                 $tarOut .= $mesg;
323             }
324         }
325         while ( $tarOut =~ /(.*?)[\n\r]+(.*)/s ) {
326             $_ = $1;
327             $tarOut = $2;
328             $RestoreLOG->write(\"tarCreate: $_\n");
329             if ( /^Done: (\d+) files, (\d+) bytes, (\d+) dirs, (\d+) specials, (\d+) errors/ ) {
330                 $tarCreateFileCnt = $1;
331                 $tarCreateByteCnt = $2;
332                 $tarCreateErrCnt  = $5;
333             }
334         }
335         last if ( !$xfer->readOutput(\$FDread, $rout) );
336         while ( my $str = $xfer->logMsgGet ) {
337             print(LOG $bpc->timeStamp, "xfer: $str\n");
338         }
339         if ( $xfer->getStats->{fileCnt} == 1 ) {
340             #
341             # Make sure it is still the machine we expect.  We do this while
342             # the transfer is running to avoid a potential race condition if
343             # the ip address was reassigned by dhcp just before we started
344             # the transfer.
345             #
346             if ( my $errMsg = CorrectHostCheck($hostIP, $host) ) {
347                 $stat{hostError} = $errMsg;
348                 last SCAN;
349             }
350         }
351     }
352 } else {
353     #
354     # otherwise the xfer module does everything for us
355     #
356     print(LOG $bpc->timeStamp, "Starting restore (tarPid=-1, xferPid=-1)\n");
357     print("started restore, tarPid=-1, xferPid=-1\n");
358     ($tarCreateFileCnt, $tarCreateByteCnt,
359         $tarCreateErrCnt, $tarCreateErr) = $xfer->run();
360 }
361 alarm(0);
362
363 #
364 # Merge the xfer status (need to accumulate counts)
365 #
366 my $newStat = $xfer->getStats;
367 foreach my $k ( (keys(%stat), keys(%$newStat)) ) {
368     next if ( !defined($newStat->{$k}) );
369     if ( $k =~ /Cnt$/ ) {
370         $stat{$k} += $newStat->{$k};
371         delete($newStat->{$k});
372         next;
373     }
374     if ( !defined($stat{$k}) ) {
375         $stat{$k} = $newStat->{$k};
376         delete($newStat->{$k});
377         next;
378     }
379 }
380
381 $stat{xferOK} = 0 if ( $stat{hostError} || $stat{hostAbort} || $tarCreateErr );
382
383 if ( !$stat{xferOK} ) {
384     #
385     # kill off the tranfer program, first nicely then forcefully
386     #
387     kill(2, $xferPid) if ( $xferPid > 0 );
388     sleep(1);
389     kill(9, $xferPid) if ( $xferPid > 0 );
390     #
391     # kill off the tar process, first nicely then forcefully
392     #
393     kill(2, $tarPid) if ( $tarPid > 0 );
394     sleep(1);
395     kill(9, $tarPid) if ( $tarPid > 0 );
396 }
397
398 my $lastNum  = -1;
399 my @Restores;
400
401 #
402 # Do one last check to make sure it is still the machine we expect.
403 #
404 if ( $stat{xferOK} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
405     $stat{hostError} = $errMsg;
406     $stat{xferOK} = 0;
407 }
408 @Restores = $bpc->RestoreInfoRead($host);
409 for ( my $i = 0 ; $i < @Restores ; $i++ ) {
410     $lastNum = $Restores[$i]{num} if ( $lastNum < $Restores[$i]{num} );
411 }
412 $lastNum++;
413
414 #
415 # Run an optional post-restore command
416 #
417 UserCommandRun("RestorePostUserCmd") if ( $NeedPostCmd );
418
419 $RestoreLOG->close();
420 rename("$Dir/RestoreLOG$fileExt", "$Dir/RestoreLOG.$lastNum$fileExt");
421 rename("$Dir/$reqFileName", "$Dir/RestoreInfo.$lastNum");
422 my $endTime = time();
423
424 #
425 # If the restore failed, clean up
426 #
427 if ( !$stat{xferOK} ) {
428     #
429     # wait a short while and see if the system is still alive
430     #
431     $stat{hostError} ||= $tarCreateErr if ( $tarCreateErr ne "" );
432     $stat{hostError} = $stat{lastOutputLine} if ( $stat{hostError} eq "" );
433     if ( $stat{hostError} ) {
434         print(LOG $bpc->timeStamp,
435                   "Got fatal error during xfer ($stat{hostError})\n");
436     }
437     sleep(2);
438     if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
439         $stat{hostAbort} = 1;
440     }
441     if ( $stat{hostAbort} ) {
442         $stat{hostError} = "lost network connection during restore";
443     }
444 }
445
446 #
447 # Add the new restore information to the restore file
448 #
449 @Restores = $bpc->RestoreInfoRead($host);
450 my $i = @Restores;
451 $Restores[$i]{num}           = $lastNum;
452 $Restores[$i]{startTime}     = $startTime;
453 $Restores[$i]{endTime}       = $endTime;
454 $Restores[$i]{result}        = $stat{xferOK} ? "ok" : "failed";
455 $Restores[$i]{errorMsg}      = $stat{hostError};
456 $Restores[$i]{nFiles}        = $tarCreateFileCnt;
457 $Restores[$i]{size}          = $tarCreateByteCnt;
458 $Restores[$i]{tarCreateErrs} = $tarCreateErrCnt;
459 $Restores[$i]{xferErrs}      = $stat{xferErrCnt} || 0;
460
461 while ( @Restores > $Conf{RestoreInfoKeepCnt} ) {
462     my $num = $Restores[0]{num};
463     unlink("$Dir/RestoreLOG.$num.z");
464     unlink("$Dir/RestoreLOG.$num");
465     unlink("$Dir/RestoreInfo.$num");
466     shift(@Restores);
467 }
468 $bpc->RestoreInfoWrite($host, @Restores);
469
470 if ( !$stat{xferOK} ) {
471     print(LOG $bpc->timeStamp, "Restore aborted ($stat{hostError})\n");
472     print("restore failed: $stat{hostError}\n");
473 } else {
474     print("restore complete\n");
475 }
476
477 ###########################################################################
478 # Subroutines
479 ###########################################################################
480
481 sub CorrectHostCheck
482 {
483     my($hostIP, $host) = @_;
484     return if ( $hostIP eq $host && !$Conf{FixedIPNetBiosNameCheck} );
485     my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($hostIP);
486     return "host $host has mismatching netbios name $netBiosHost"
487             if ( $netBiosHost ne $host );
488     return;
489 }
490
491 sub catch_signal
492 {
493     my $signame = shift;
494
495     #
496     # Note: needs to be tested for each kind of XferMethod
497     #
498     print(LOG $bpc->timeStamp, "cleaning up after signal $signame\n");
499     if ( $xferPid > 0 ) {
500         if ( kill(2, $xferPid) <= 0 ) {
501             sleep(1);
502             kill(9, $xferPid);
503         }
504     }
505     if ( $tarPid > 0 ) {
506         if ( kill(2, $tarPid) <= 0 ) {
507             sleep(1);
508             kill(9, $tarPid);
509         }
510     }
511     $stat{xferOK} = 0;
512     $stat{hostError} = "aborted by signal $signame";
513 }
514
515 #
516 # Run an optional pre- or post-dump command
517 #
518 sub UserCommandRun
519 {
520     my($type) = @_;
521
522     return if ( !defined($Conf{$type}) );
523     my $vars = {
524         xfer         => $xfer,
525         host         => $host,
526         hostIP       => $hostIP,
527         share        => $RestoreReq{shareDest},
528         XferMethod   => $Conf{XferMethod},
529         LOG          => *LOG,
530         XferLOG      => $RestoreLOG,
531         stat         => \%stat,
532         xferOK       => $stat{xferOK},
533         type         => $type,
534         bkupSrcHost  => $RestoreReq{hostSrc},
535         bkupSrcShare => $RestoreReq{shareSrc},
536         bkupSrcNum   => $RestoreReq{num},
537         backups      => \@Backups,
538         pathHdrSrc   => $RestoreReq{pathHdrSrc},
539         pathHdrDest  => $RestoreReq{pathHdrDest},
540         fileList     => $RestoreReq{fileList},
541     };
542     my $cmd = $bpc->cmdVarSubstitute($Conf{$type}, $vars);
543     $RestoreLOG->write(\"Executing $type: @$cmd\n");
544     #
545     # Run the user's command, dumping the stdout/stderr into the
546     # Xfer log file.  Also supply the optional $vars and %Conf in
547     # case the command is really perl code instead of a shell
548     # command.
549     #
550     $bpc->cmdSystemOrEval($cmd,
551             sub {
552                 $RestoreLOG->write(\$_[0]);
553             },
554             $vars, \%Conf);
555 }