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