2 #============================================================= -*-perl-*-
4 # BackupPC_dump: Dump a single client.
8 # Usage: BackupPC_dump [-i] [-f] [-d] [-e] [-v] <client>
12 # -i Do an incremental dump, overriding any scheduling (but a full
13 # dump will be done if no dumps have yet succeeded)
15 # -f Do a full dump, overriding any scheduling.
17 # -d Host is a DHCP pool address, and the client argument
18 # just an IP address. We lookup the NetBios name from
21 # -e Just do an dump expiry check for the client. Don't do anything
22 # else. This is used periodically by BackupPC to make sure that
23 # dhcp hosts have correctly expired old backups. Without this,
24 # dhcp hosts that are no longer on the network will not expire
27 # -v verbose. for manual usage: prints failure reasons in more detail.
29 # BackupPC_dump is run periodically by BackupPC to backup $client.
30 # The file $TopDir/pc/$client/backups is read to decide whether a
31 # full or incremental backup needs to be run. If no backup is
32 # scheduled, or a ping to $client fails, then BackupPC_dump quits.
34 # The backup is done using the selected XferMethod (smb, tar, rsync etc),
35 # extracting the dump into $TopDir/pc/$client/new. The xfer output is
36 # put into $TopDir/pc/$client/XferLOG.
38 # If the dump succeeds (based on parsing the output of the XferMethod):
39 # - $TopDir/pc/$client/new is renamed to $TopDir/pc/$client/nnn, where
40 # nnn is the next sequential dump number.
41 # - $TopDir/pc/$client/XferLOG is renamed to $TopDir/pc/$client/XferLOG.nnn.
42 # - $TopDir/pc/$client/backups is updated.
45 # - $TopDir/pc/$client/new is moved to $TopDir/trash for later removal.
46 # - $TopDir/pc/$client/XferLOG is renamed to $TopDir/pc/$client/XferLOG.bad
49 # BackupPC_dump communicates to BackupPC via printing to STDOUT.
52 # Craig Barratt <cbarratt@users.sourceforge.net>
55 # Copyright (C) 2001-2003 Craig Barratt
57 # This program is free software; you can redistribute it and/or modify
58 # it under the terms of the GNU General Public License as published by
59 # the Free Software Foundation; either version 2 of the License, or
60 # (at your option) any later version.
62 # This program is distributed in the hope that it will be useful,
63 # but WITHOUT ANY WARRANTY; without even the implied warranty of
64 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
65 # GNU General Public License for more details.
67 # You should have received a copy of the GNU General Public License
68 # along with this program; if not, write to the Free Software
69 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
71 #========================================================================
73 # Version 2.1.0, released 20 Jun 2004.
75 # See http://backuppc.sourceforge.net.
77 #========================================================================
81 use lib "/usr/local/BackupPC/lib";
83 use BackupPC::FileZIO;
84 use BackupPC::Storage;
85 use BackupPC::Xfer::Smb;
86 use BackupPC::Xfer::Tar;
87 use BackupPC::Xfer::Rsync;
93 ###########################################################################
95 ###########################################################################
97 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
98 my $TopDir = $bpc->TopDir();
99 my $BinDir = $bpc->BinDir();
100 my %Conf = $bpc->Conf();
109 if ( !getopts("defiv", \%opts) || @ARGV != 1 ) {
110 print("usage: $0 [-d] [-e] [-f] [-i] [-v] <client>\n");
113 if ( $ARGV[0] !~ /^([\w\.\s-]+)$/ ) {
114 print("$0: bad client name '$ARGV[0]'\n");
117 my $client = $1; # BackupPC's client name (might not be real host name)
118 my $hostIP; # this is the IP address
119 my $host; # this is the real host name
121 my($clientURI, $user);
123 $bpc->verbose(1) if ( $opts{v} );
127 # The client name $client is simply a DHCP address. We need to check
128 # if there is any machine at this address, and if so, get the actual
129 # host name via NetBios using nmblookup.
132 if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
133 print(STDERR "Exiting because CheckHostAlive($hostIP) failed\n")
137 if ( $Conf{NmbLookupCmd} eq "" ) {
138 print(STDERR "Exiting because \$Conf{NmbLookupCmd} is empty\n")
142 ($client, $user) = $bpc->NetBiosInfoGet($hostIP);
143 if ( $client !~ /^([\w\.\s-]+)$/ ) {
144 print(STDERR "Exiting because NetBiosInfoGet($hostIP) returned"
145 . " '$client', an invalid host name\n") if ( $opts{v} );
148 $Hosts = $bpc->HostInfoRead($client);
151 $Hosts = $bpc->HostInfoRead($client);
153 if ( !defined($Hosts->{$client}) ) {
154 print(STDERR "Exiting because host $client does not exist in the"
155 . " hosts file\n") if ( $opts{v} );
159 my $Dir = "$TopDir/pc/$client";
164 # Re-read config file, so we can include the PC-specific config
166 $clientURI = $bpc->uriEsc($client);
167 if ( defined(my $error = $bpc->ConfigRead($client)) ) {
168 print("dump failed: Can't read PC's config file: $error\n");
171 %Conf = $bpc->Conf();
174 # Catch various signals
176 $SIG{INT} = \&catch_signal;
177 $SIG{ALRM} = \&catch_signal;
178 $SIG{TERM} = \&catch_signal;
179 $SIG{PIPE} = \&catch_signal;
180 $SIG{STOP} = \&catch_signal;
181 $SIG{TSTP} = \&catch_signal;
182 $SIG{TTIN} = \&catch_signal;
186 # Make sure we eventually timeout if there is no activity from
187 # the data transport program.
189 alarm($Conf{ClientTimeout});
191 mkpath($Dir, 0, 0777) if ( !-d $Dir );
192 if ( !-f "$Dir/LOCK" ) {
193 open(LOCK, ">", "$Dir/LOCK") && close(LOCK);
195 open(LOG, ">>", "$Dir/LOG");
196 select(LOG); $| = 1; select(STDOUT);
199 # For the -e option we just expire backups and quit
202 BackupExpire($client);
207 # For archive hosts we don't bother any further
209 if ($Conf{XferMethod} eq "archive" ) {
210 print(STDERR "Exiting because the XferMethod is set to archive\n")
217 # In the non-DHCP case, make sure the host can be looked up
218 # via NS, or otherwise find the IP address via NetBios.
220 if ( $Conf{ClientNameAlias} ne "" ) {
221 $host = $Conf{ClientNameAlias};
225 if ( !defined(gethostbyname($host)) ) {
227 # Ok, NS doesn't know about it. Maybe it is a NetBios name
230 print(STDERR "Name server doesn't know about $host; trying NetBios\n")
232 if ( !defined($hostIP = $bpc->NetBiosHostIPFind($host)) ) {
233 print(LOG $bpc->timeStamp, "Can't find host $host via netbios\n");
234 print("host not found\n");
242 ###########################################################################
243 # Figure out what to do and do it
244 ###########################################################################
247 # See if we should skip this host during a certain range
250 my $err = $bpc->ServerConnect($Conf{ServerHost}, $Conf{ServerPort});
252 print("Can't connect to server ($err)\n");
253 print(LOG $bpc->timeStamp, "Can't connect to server ($err)\n");
256 my $reply = $bpc->ServerMesg("status host($clientURI)");
257 $reply = $1 if ( $reply =~ /(.*)/s );
260 $bpc->ServerDisconnect();
263 # For DHCP tell BackupPC which host this is
266 if ( $StatusHost{activeJob} ) {
267 # oops, something is already running for this host
268 print(STDERR "Exiting because backup is already running for $client\n")
272 print("DHCP $hostIP $clientURI\n");
275 my($needLink, @Backups, $type, $lastBkupNum, $lastFullBkupNum);
282 if ( $Conf{FullPeriod} == -1 && !$opts{f} && !$opts{i}
283 || $Conf{FullPeriod} == -2 ) {
284 print(STDERR "Exiting because backups are disabled with"
285 . " \$Conf{FullPeriod} = $Conf{FullPeriod}\n") if ( $opts{v} );
287 # Tell BackupPC to ignore old failed backups on hosts that
288 # have backups disabled.
290 print("backups disabled\n")
291 if ( defined($StatusHost{errorTime})
292 && $StatusHost{reason} ne "Reason_backup_done"
293 && time - $StatusHost{errorTime} > 4 * 24 * 3600 );
294 NothingToDo($needLink);
297 if ( !$opts{i} && !$opts{f} && $Conf{BlackoutGoodCnt} >= 0
298 && $StatusHost{aliveCnt} >= $Conf{BlackoutGoodCnt} ) {
299 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
300 my($currHours) = $hour + $min / 60 + $sec / 3600;
304 # Handle backward compatibility with original separate scalar
307 if ( defined($Conf{BlackoutHourBegin}) ) {
308 push(@{$Conf{BlackoutPeriods}},
310 hourBegin => $Conf{BlackoutHourBegin},
311 hourEnd => $Conf{BlackoutHourEnd},
312 weekDays => $Conf{BlackoutWeekDays},
316 foreach my $p ( @{$Conf{BlackoutPeriods}} ) {
318 # Allow blackout to span midnight (specified by BlackoutHourBegin
319 # being greater than BlackoutHourEnd)
321 next if ( ref($p->{weekDays}) ne "ARRAY"
322 || !defined($p->{hourBegin})
323 || !defined($p->{hourEnd})
325 if ( $p->{hourBegin} > $p->{hourEnd} ) {
326 $blackout = $p->{hourBegin} <= $currHours
327 || $currHours <= $p->{hourEnd};
328 if ( $currHours <= $p->{hourEnd} ) {
330 # This is after midnight, so decrement the weekday for the
331 # weekday check (eg: Monday 11pm-1am means Monday 2300 to
332 # Tuesday 0100, not Monday 2300-2400 plus Monday 0000-0100).
335 $wday += 7 if ( $wday < 0 );
338 $blackout = $p->{hourBegin} <= $currHours
339 && $currHours <= $p->{hourEnd};
341 if ( $blackout && grep($_ == $wday, @{$p->{weekDays}}) ) {
342 # print(LOG $bpc->timeStamp, "skipping because of blackout"
343 # . " (alive $StatusHost{aliveCnt} times)\n");
344 print(STDERR "Skipping $client because of blackout\n")
346 NothingToDo($needLink);
351 if ( !$opts{i} && !$opts{f} && $StatusHost{backoffTime} > time ) {
352 printf(LOG "%sskipping because of user requested delay (%.1f hours left)\n",
353 $bpc->timeStamp, ($StatusHost{backoffTime} - time) / 3600);
354 NothingToDo($needLink);
358 # Now see if there are any old backups we should delete
360 BackupExpire($client);
363 # Read Backup information, and find times of the most recent full and
364 # incremental backups
366 @Backups = $bpc->BackupInfoRead($client);
367 for ( my $i = 0 ; $i < @Backups ; $i++ ) {
368 $needLink = 1 if ( $Backups[$i]{nFilesNew} eq ""
369 || -f "$Dir/NewFileList.$Backups[$i]{num}" );
370 $lastBkupNum = $Backups[$i]{num};
371 if ( $Backups[$i]{type} eq "full" ) {
372 if ( $lastFull < $Backups[$i]{startTime} ) {
373 $lastFull = $Backups[$i]{startTime};
374 $lastFullBkupNum = $Backups[$i]{num};
376 } elsif ( $Backups[$i]{type} eq "incr" ) {
377 $lastIncr = $Backups[$i]{startTime}
378 if ( $lastIncr < $Backups[$i]{startTime} );
379 } elsif ( $Backups[$i]{type} eq "partial" ) {
381 $lastPartial = $Backups[$i]{startTime};
382 $partialNum = $Backups[$i]{num};
387 # Decide whether we do nothing, or a full or incremental backup.
391 || (!$opts{i} && (time - $lastFull > $Conf{FullPeriod} * 24*3600
392 && time - $lastIncr > $Conf{IncrPeriod} * 24*3600)) ) {
394 } elsif ( $opts{i} || (time - $lastIncr > $Conf{IncrPeriod} * 24*3600
395 && time - $lastFull > $Conf{IncrPeriod} * 24*3600) ) {
398 NothingToDo($needLink);
402 # Check if $host is alive
404 my $delay = $bpc->CheckHostAlive($hostIP);
406 print(LOG $bpc->timeStamp, "no ping response\n");
407 print("no ping response\n");
408 print("link $clientURI\n") if ( $needLink );
410 } elsif ( $delay > $Conf{PingMaxMsec} ) {
411 printf(LOG "%sping too slow: %.4gmsec\n", $bpc->timeStamp, $delay);
412 printf("ping too slow: %.4gmsec (threshold is %gmsec)\n",
413 $delay, $Conf{PingMaxMsec});
414 print("link $clientURI\n") if ( $needLink );
419 # Make sure it is really the machine we expect (only for fixed addresses,
420 # since we got the DHCP address above).
422 if ( !$opts{d} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
423 print(LOG $bpc->timeStamp, "dump failed: $errMsg\n");
424 print("dump failed: $errMsg\n");
426 } elsif ( $opts{d} ) {
427 print(LOG $bpc->timeStamp, "$host is dhcp $hostIP, user is $user\n");
431 # Get a clean directory $Dir/new
433 $bpc->RmTreeDefer("$TopDir/trash", "$Dir/new") if ( -d "$Dir/new" );
436 # Setup file extension for compression and open XferLOG output file
438 if ( $Conf{CompressLevel} && !BackupPC::FileZIO->compOk ) {
439 print(LOG $bpc->timeStamp, "dump failed: can't find Compress::Zlib\n");
440 print("dump failed: can't find Compress::Zlib\n");
443 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
444 my $XferLOG = BackupPC::FileZIO->open("$Dir/XferLOG$fileExt", 1,
445 $Conf{CompressLevel});
446 if ( !defined($XferLOG) ) {
447 print(LOG $bpc->timeStamp, "dump failed: unable to open/create"
448 . " $Dir/XferLOG$fileExt\n");
449 print("dump failed: unable to open/create $Dir/XferLOG$fileExt\n");
454 # Ignore the partial dump in the case of an incremental
455 # or when the partial is too old. A partial is a partial full.
457 if ( $type ne "full" || time - $lastPartial > $Conf{PartialAgeMax} * 24*3600 ) {
463 # If this is a partial, copy the old XferLOG file
466 my($compress, $fileName);
467 if ( -f "$Dir/XferLOG.$partialNum.z" ) {
468 $fileName = "$Dir/XferLOG.$partialNum.z";
470 } elsif ( -f "$Dir/XferLOG.$partialNum" ) {
471 $fileName = "$Dir/XferLOG.$partialNum";
474 if ( my $oldLOG = BackupPC::FileZIO->open($fileName, 0, $compress) ) {
476 while ( $oldLOG->read(\$data, 65536) > 0 ) {
477 $XferLOG->write(\$data);
483 $XferLOG->writeTeeStderr(1) if ( $opts{v} );
484 unlink("$Dir/NewFileList") if ( -f "$Dir/NewFileList" );
486 my $startTime = time();
490 my $sizeExistComp = 0;
493 my($logMsg, %stat, $xfer, $ShareNames, $noFilesErr);
496 if ( $Conf{XferMethod} eq "tar" ) {
497 $ShareNames = $Conf{TarShareName};
498 } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
499 $ShareNames = $Conf{RsyncShareName};
501 $ShareNames = $Conf{SmbShareName};
504 $ShareNames = [ $ShareNames ] unless ref($ShareNames) eq "ARRAY";
507 # Run an optional pre-dump command
509 UserCommandRun("DumpPreUserCmd");
513 # Now backup each of the shares
515 for my $shareName ( @$ShareNames ) {
518 $stat{xferOK} = $stat{hostAbort} = undef;
519 $stat{hostError} = $stat{lastOutputLine} = undef;
520 if ( -d "$Dir/new/$shareName" ) {
521 print(LOG $bpc->timeStamp,
522 "unexpected repeated share name $shareName skipped\n");
526 UserCommandRun("DumpPreShareCmd", $shareName);
528 if ( $Conf{XferMethod} eq "tar" ) {
530 # Use tar (eg: tar/ssh) as the transport program.
532 $xfer = BackupPC::Xfer::Tar->new($bpc);
533 } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
535 # Use rsync as the transport program.
537 if ( !defined($xfer = BackupPC::Xfer::Rsync->new($bpc)) ) {
538 my $errStr = BackupPC::Xfer::Rsync::errStr;
539 print(LOG $bpc->timeStamp, "dump failed: $errStr\n");
540 print("dump failed: $errStr\n");
541 UserCommandRun("DumpPostShareCmd", $shareName) if ( $NeedPostCmd );
542 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
547 # Default is to use smbclient (smb) as the transport program.
549 $xfer = BackupPC::Xfer::Smb->new($bpc);
552 my $useTar = $xfer->useTar;
556 # This xfer method outputs a tar format file, so we start a
557 # BackupPC_tarExtract to extract the data.
559 # Create a socketpair to connect the Xfer method to BackupPC_tarExtract
560 # WH is the write handle for writing, provided to the transport
561 # program, and RH is the other end of the socket for reading,
562 # provided to BackupPC_tarExtract.
564 if ( socketpair(RH, WH, AF_UNIX, SOCK_STREAM, PF_UNSPEC) ) {
565 shutdown(RH, 1); # no writing to this socket
566 shutdown(WH, 0); # no reading from this socket
567 setsockopt(RH, SOL_SOCKET, SO_RCVBUF, 8 * 65536);
568 setsockopt(WH, SOL_SOCKET, SO_SNDBUF, 8 * 65536);
571 # Default to pipe() if socketpair() doesn't work.
577 # fork a child for BackupPC_tarExtract. TAR is a file handle
578 # on which we (the parent) read the stdout & stderr from
579 # BackupPC_tarExtract.
581 if ( !defined($tarPid = open(TAR, "-|")) ) {
582 print(LOG $bpc->timeStamp, "can't fork to run tar\n");
583 print("can't fork to run tar\n");
591 # This is the tar child. Close the write end of the pipe,
592 # clone STDERR to STDOUT, clone STDIN from RH, and then
593 # exec BackupPC_tarExtract.
598 open(STDERR, ">&STDOUT");
602 exec("$BinDir/BackupPC_tarExtract", $client, $shareName,
603 $Conf{CompressLevel});
604 print(LOG $bpc->timeStamp,
605 "can't exec $BinDir/BackupPC_tarExtract\n");
608 } elsif ( !defined($newFilesFH) ) {
610 # We need to create the NewFileList output file
613 open(NEW_FILES, ">", "$TopDir/pc/$client/NewFileList")
614 || die("can't open $TopDir/pc/$client/NewFileList");
615 $newFilesFH = *NEW_FILES;
620 # Run the transport program
626 shareName => $shareName,
630 newFilesFH => $newFilesFH,
633 lastFull => $lastFull,
634 lastBkupNum => $lastBkupNum,
635 lastFullBkupNum => $lastFullBkupNum,
636 backups => \@Backups,
637 compress => $Conf{CompressLevel},
638 XferMethod => $Conf{XferMethod},
639 logLevel => $Conf{XferLogLevel},
640 pidHandler => \&pidHandler,
641 partialNum => $partialNum,
644 if ( !defined($logMsg = $xfer->start()) ) {
645 print(LOG $bpc->timeStamp, "xfer start failed: ", $xfer->errStr, "\n");
646 print("dump failed: ", $xfer->errStr, "\n");
647 print("link $clientURI\n") if ( $needLink );
649 # kill off the tar process, first nicely then forcefully
652 kill($bpc->sigName2num("INT"), $tarPid);
654 kill($bpc->sigName2num("KILL"), $tarPid);
657 kill($bpc->sigName2num("INT"), @xferPid);
659 kill($bpc->sigName2num("KILL"), @xferPid);
661 UserCommandRun("DumpPostShareCmd", $shareName) if ( $NeedPostCmd );
662 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
666 @xferPid = $xfer->xferPid;
670 # The parent must close both handles on the pipe since the children
671 # are using these handles now.
676 print(LOG $bpc->timeStamp, $logMsg, "\n");
677 print("started $type dump, share=$shareName\n");
679 pidHandler(@xferPid);
683 # Parse the output of the transfer program and BackupPC_tarExtract
684 # while they run. Since we might be reading from two or more children
687 my($FDread, $tarOut, $mesg);
688 vec($FDread, fileno(TAR), 1) = 1 if ( $useTar );
689 $xfer->setSelectMask(\$FDread);
693 last if ( $FDread =~ /^\0*$/ );
694 select(my $rout = $FDread, undef, $ein, undef);
696 if ( vec($rout, fileno(TAR), 1) ) {
697 if ( sysread(TAR, $mesg, 8192) <= 0 ) {
698 vec($FDread, fileno(TAR), 1) = 0;
704 while ( $tarOut =~ /(.*?)[\n\r]+(.*)/s ) {
708 $XferLOG->write(\"$_\n");
710 $XferLOG->write(\"tarExtract: $_\n");
712 if ( /^BackupPC_tarExtact aborting \((.*)\)/ ) {
713 $stat{hostError} = $1;
715 if ( /^Done: (\d+) errors, (\d+) filesExist, (\d+) sizeExist, (\d+) sizeExistComp, (\d+) filesTotal, (\d+) sizeTotal/ ) {
719 $sizeExistComp += $4;
725 last if ( !$xfer->readOutput(\$FDread, $rout) );
726 while ( my $str = $xfer->logMsgGet ) {
727 print(LOG $bpc->timeStamp, "xfer: $str\n");
729 if ( $xfer->getStats->{fileCnt} == 1 ) {
731 # Make sure it is still the machine we expect. We do this while
732 # the transfer is running to avoid a potential race condition if
733 # the ip address was reassigned by dhcp just before we started
736 if ( my $errMsg = CorrectHostCheck($hostIP, $host) ) {
737 $stat{hostError} = $errMsg if ( $stat{hostError} eq "" );
744 # otherwise the xfer module does everything for us
746 my @results = $xfer->run();
747 $tarErrs += $results[0];
748 $nFilesExist += $results[1];
749 $sizeExist += $results[2];
750 $sizeExistComp += $results[3];
751 $nFilesTotal += $results[4];
752 $sizeTotal += $results[5];
756 # Merge the xfer status (need to accumulate counts)
758 my $newStat = $xfer->getStats;
759 if ( $newStat->{fileCnt} == 0 ) {
760 $noFilesErr ||= "No files dumped for share $shareName";
762 foreach my $k ( (keys(%stat), keys(%$newStat)) ) {
763 next if ( !defined($newStat->{$k}) );
764 if ( $k =~ /Cnt$/ ) {
765 $stat{$k} += $newStat->{$k};
766 delete($newStat->{$k});
769 if ( !defined($stat{$k}) ) {
770 $stat{$k} = $newStat->{$k};
771 delete($newStat->{$k});
776 UserCommandRun("DumpPostShareCmd", $shareName) if ( $NeedPostCmd );
778 $stat{xferOK} = 0 if ( $stat{hostError} || $stat{hostAbort} );
779 if ( !$stat{xferOK} ) {
781 # kill off the tranfer program, first nicely then forcefully
784 kill($bpc->sigName2num("INT"), @xferPid);
786 kill($bpc->sigName2num("KILL"), @xferPid);
789 # kill off the tar process, first nicely then forcefully
792 kill($bpc->sigName2num("INT"), $tarPid);
794 kill($bpc->sigName2num("KILL"), $tarPid);
797 # don't do any more shares on this host
804 # If this is a full, and any share had zero files then consider the dump bad
806 if ( $type eq "full" && $stat{hostError} eq ""
807 && length($noFilesErr) && $Conf{BackupZeroFilesIsFatal} ) {
808 $stat{hostError} = $noFilesErr;
812 $stat{xferOK} = 0 if ( $Abort );
815 # Do one last check to make sure it is still the machine we expect.
817 if ( $stat{xferOK} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
818 $stat{hostError} = $errMsg;
822 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
823 close($newFilesFH) if ( defined($newFilesFH) );
825 my $endTime = time();
828 # If the dump failed, clean up
830 if ( !$stat{xferOK} ) {
831 $stat{hostError} = $stat{lastOutputLine} if ( $stat{hostError} eq "" );
832 if ( $stat{hostError} ) {
833 print(LOG $bpc->timeStamp,
834 "Got fatal error during xfer ($stat{hostError})\n");
835 $XferLOG->write(\"Got fatal error during xfer ($stat{hostError})\n");
839 # wait a short while and see if the system is still alive
842 if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
843 $stat{hostAbort} = 1;
845 if ( $stat{hostAbort} ) {
846 $stat{hostError} = "lost network connection during backup";
848 print(LOG $bpc->timeStamp, "Backup aborted ($stat{hostError})\n");
849 $XferLOG->write(\"Backup aborted ($stat{hostError})\n");
851 $XferLOG->write(\"Backup aborted by user signal\n");
855 # Close the log file and call BackupFailCleanup, which exits.
860 my $newNum = BackupSave();
862 my $otherCount = $stat{xferErrCnt} - $stat{xferBadFileCnt}
863 - $stat{xferBadShareCnt};
864 print(LOG $bpc->timeStamp,
865 "$type backup $newNum complete, $stat{fileCnt} files,"
866 . " $stat{byteCnt} bytes,"
867 . " $stat{xferErrCnt} xferErrs ($stat{xferBadFileCnt} bad files,"
868 . " $stat{xferBadShareCnt} bad shares, $otherCount other)\n");
870 BackupExpire($client);
872 print("$type backup complete\n");
874 ###########################################################################
876 ###########################################################################
882 print("nothing to do\n");
883 print("link $clientURI\n") if ( $needLink );
892 # The first time we receive a signal we try to gracefully
893 # abort the backup. This allows us to keep a partial dump
894 # with the in-progress file deleted and attribute caches
895 # flushed to disk etc.
897 if ( !length($SigName) ) {
899 if ( $sigName eq "INT" ) {
900 $reason = "aborted by user (signal=$sigName)";
902 $reason = "aborted by signal=$sigName";
906 # Parent logs a message
908 print(LOG $bpc->timeStamp,
909 "Aborting backup up after signal $sigName\n");
914 $xfer->abort($reason);
917 # Send ALRMs to BackupPC_tarExtract if we are using it
920 kill($bpc->sigName2num("ARLM"), $tarPid);
924 # Schedule a 20 second timer in case the clean
925 # abort doesn't complete
930 # Children ignore anything other than ALRM and INT
932 if ( $sigName ne "ALRM" && $sigName ne "INT" ) {
937 # The child also tells xfer to abort
939 $xfer->abort($reason);
942 # Schedule a 15 second timer in case the clean
943 # abort doesn't complete
953 # This is a second signal: time to clean up.
955 if ( $Pid != $$ && ($sigName eq "ALRM" || $sigName eq "INT") ) {
957 # Children quit quietly on ALRM or INT
963 # Ignore other signals in children
965 return if ( $Pid != $$ );
967 $SIG{$sigName} = 'IGNORE';
968 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
969 $XferLOG->write(\"exiting after signal $sigName\n");
971 kill($bpc->sigName2num("INT"), @xferPid);
973 kill($bpc->sigName2num("KILL"), @xferPid);
976 kill($bpc->sigName2num("INT"), $tarPid);
978 kill($bpc->sigName2num("KILL"), $tarPid);
980 if ( $sigName eq "INT" ) {
981 $stat{hostError} = "aborted by user (signal=$sigName)";
983 $stat{hostError} = "received signal=$sigName";
990 if ( -f _ && $File::Find::name !~ /\/fattrib$/ ) {
994 # No need to check entire tree
996 $File::Find::prune = 1 if ( $nFilesTotal );
1000 sub BackupFailCleanup
1002 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
1003 my $keepPartial = 0;
1006 # We keep this backup if it is a full and we actually backed
1009 if ( $type eq "full" ) {
1010 if ( $nFilesTotal == 0 && $xfer->getStats->{fileCnt} == 0 ) {
1012 # Xfer didn't report any files, but check in the new
1013 # directory just in case.
1015 find(\&CheckForNewFiles, "$Dir/new");
1016 $keepPartial = 1 if ( $nFilesTotal );
1019 # Xfer reported some files
1026 # Don't keep partials if they are disabled
1028 $keepPartial = 0 if ( $Conf{PartialAgeMax} < 0 );
1030 if ( !$keepPartial ) {
1032 # No point in saving this dump; get rid of eveything.
1035 unlink("$Dir/timeStamp.level0") if ( -f "$Dir/timeStamp.level0" );
1036 unlink("$Dir/SmbLOG.bad") if ( -f "$Dir/SmbLOG.bad" );
1037 unlink("$Dir/SmbLOG.bad$fileExt") if ( -f "$Dir/SmbLOG.bad$fileExt" );
1038 unlink("$Dir/XferLOG.bad") if ( -f "$Dir/XferLOG.bad" );
1039 unlink("$Dir/XferLOG.bad$fileExt") if ( -f "$Dir/XferLOG.bad$fileExt" );
1040 unlink("$Dir/NewFileList") if ( -f "$Dir/NewFileList" );
1041 rename("$Dir/XferLOG$fileExt", "$Dir/XferLOG.bad$fileExt");
1042 $bpc->RmTreeDefer("$TopDir/trash", "$Dir/new") if ( -d "$Dir/new" );
1043 print("dump failed: $stat{hostError}\n");
1045 print("link $clientURI\n") if ( $needLink );
1049 # Ok, now we should save this as a partial dump
1052 my $newNum = BackupSave();
1053 print("dump failed: $stat{hostError}\n");
1054 print("link $clientURI\n") if ( $needLink );
1055 print(LOG $bpc->timeStamp, "Saved partial dump $newNum\n");
1060 # Decide which old backups should be expired by moving them
1066 my($Dir) = "$TopDir/pc/$client";
1067 my(@Backups) = $bpc->BackupInfoRead($client);
1068 my($cntFull, $cntIncr, $firstFull, $firstIncr, $oldestIncr,
1069 $oldestFull, $changes);
1071 if ( $Conf{FullKeepCnt} <= 0 ) {
1072 print(LOG $bpc->timeStamp,
1073 "Invalid value for \$Conf{FullKeepCnt}=$Conf{FullKeepCnt}\n");
1075 "Invalid value for \$Conf{FullKeepCnt}=$Conf{FullKeepCnt}\n")
1080 $cntFull = $cntIncr = 0;
1081 $oldestIncr = $oldestFull = 0;
1082 for ( my $i = 0 ; $i < @Backups ; $i++ ) {
1083 if ( $Backups[$i]{type} eq "full" ) {
1084 $firstFull = $i if ( $cntFull == 0 );
1087 $firstIncr = $i if ( $cntIncr == 0 );
1091 $oldestIncr = (time - $Backups[$firstIncr]{startTime}) / (24 * 3600)
1092 if ( $cntIncr > 0 );
1093 $oldestFull = (time - $Backups[$firstFull]{startTime}) / (24 * 3600)
1094 if ( $cntFull > 0 );
1095 if ( $cntIncr > $Conf{IncrKeepCnt}
1096 || ($cntIncr > $Conf{IncrKeepCntMin}
1097 && $oldestIncr > $Conf{IncrAgeMax})
1098 && (@Backups <= $firstIncr + 1
1099 || $Backups[$firstIncr]{noFill}
1100 || !$Backups[$firstIncr + 1]{noFill}) ) {
1102 # Only delete an incr backup if the Conf settings are satisfied.
1103 # We also must make sure that either this backup is the most
1104 # recent one, or it is not filled, or the next backup is filled.
1105 # (We can't deleted a filled incr if the next backup is not
1108 print(LOG $bpc->timeStamp,
1109 "removing incr backup $Backups[$firstIncr]{num}\n");
1110 BackupRemove($client, \@Backups, $firstIncr);
1116 # Delete any old full backups, according to $Conf{FullKeepCntMin}
1117 # and $Conf{FullAgeMax}.
1119 # First make sure that $Conf{FullAgeMax} is at least bigger
1120 # than $Conf{FullPeriod} * $Conf{FullKeepCnt}, including
1121 # the exponential array case.
1123 my $fullKeepCnt = $Conf{FullKeepCnt};
1124 $fullKeepCnt = [$fullKeepCnt] if ( ref($fullKeepCnt) ne "ARRAY" );
1126 my $fullPeriod = int(0.5 + $Conf{FullPeriod});
1127 $fullPeriod = 7 if ( $fullPeriod <= 0 );
1128 for ( my $i = 0 ; $i < @$fullKeepCnt ; $i++ ) {
1129 $fullAgeMax += $fullKeepCnt->[$i] * $fullPeriod;
1132 $fullAgeMax += $fullPeriod; # add some buffer
1134 if ( $cntFull > $Conf{FullKeepCntMin}
1135 && $oldestFull > $Conf{FullAgeMax}
1136 && $oldestFull > $fullAgeMax
1137 && $Conf{FullKeepCntMin} > 0
1138 && $Conf{FullAgeMax} > 0
1139 && (@Backups <= $firstFull + 1
1140 || !$Backups[$firstFull + 1]{noFill}) ) {
1142 # Only delete a full backup if the Conf settings are satisfied.
1143 # We also must make sure that either this backup is the most
1144 # recent one, or the next backup is filled.
1145 # (We can't deleted a full backup if the next backup is not
1148 print(LOG $bpc->timeStamp,
1149 "removing old full backup $Backups[$firstFull]{num}\n");
1150 BackupRemove($client, \@Backups, $firstFull);
1156 # Do new-style full backup expiry, which includes the the case
1157 # where $Conf{FullKeepCnt} is an array.
1159 last if ( !BackupFullExpire($client, \@Backups) );
1161 $bpc->BackupInfoWrite($client, @Backups) if ( $changes );
1165 # Handle full backup expiry, using exponential periods.
1167 sub BackupFullExpire
1169 my($client, $Backups) = @_;
1171 my $fullPeriod = $Conf{FullPeriod};
1172 my $origFullPeriod = $fullPeriod;
1173 my $fullKeepCnt = $Conf{FullKeepCnt};
1174 my $fullKeepIdx = 0;
1175 my(@delete, @fullList);
1178 # Don't delete anything if $Conf{FullPeriod} or $Conf{FullKeepCnt} are
1179 # not defined - possibly a corrupted config.pl file.
1181 return if ( !defined($Conf{FullPeriod}) || !defined($Conf{FullKeepCnt}) );
1184 # If regular backups are still disabled with $Conf{FullPeriod} < 0,
1185 # we still expire backups based on a typical FullPeriod value - weekly.
1187 $fullPeriod = 7 if ( $fullPeriod <= 0 );
1189 $fullKeepCnt = [$fullKeepCnt] if ( ref($fullKeepCnt) ne "ARRAY" );
1191 for ( my $i = 0 ; $i < @$Backups ; $i++ ) {
1192 next if ( $Backups->[$i]{type} ne "full" );
1193 push(@fullList, $i);
1195 for ( my $k = @fullList - 1 ; $k >= 0 ; $k-- ) {
1196 my $i = $fullList[$k];
1197 my $prevFull = $fullList[$k-1] if ( $k > 0 );
1199 # Don't delete any full that is followed by an unfilled backup,
1200 # since it is needed for restore.
1202 my $noDelete = $i + 1 < @$Backups ? $Backups->[$i+1]{noFill} : 0;
1205 ($fullKeepIdx >= @$fullKeepCnt
1208 && $Backups->[$i]{startTime} - $Backups->[$prevFull]{startTime}
1209 < ($fullPeriod - $origFullPeriod / 2) * 24 * 3600
1213 # Delete the full backup
1215 #print("Deleting backup $i ($prevFull)\n");
1216 unshift(@delete, $i);
1219 while ( $fullKeepIdx < @$fullKeepCnt
1220 && $fullCnt >= $fullKeepCnt->[$fullKeepIdx] ) {
1223 $fullPeriod = 2 * $fullPeriod;
1228 # Now actually delete the backups
1230 for ( my $i = @delete - 1 ; $i >= 0 ; $i-- ) {
1231 print(LOG $bpc->timeStamp,
1232 "removing full backup $Backups->[$delete[$i]]{num}\n");
1233 BackupRemove($client, $Backups, $delete[$i]);
1239 # Removes any partial backups
1241 sub BackupPartialRemove
1243 my($client, $Backups) = @_;
1245 for ( my $i = @$Backups - 1 ; $i >= 0 ; $i-- ) {
1246 next if ( $Backups->[$i]{type} ne "partial" );
1247 BackupRemove($client, $Backups, $i);
1253 my @Backups = $bpc->BackupInfoRead($client);
1258 # Since we got a good backup we should remove any partial dumps
1259 # (the new backup might also be a partial, but that's ok).
1261 BackupPartialRemove($client, \@Backups);
1264 # Number the new backup
1266 for ( my $i = 0 ; $i < @Backups ; $i++ ) {
1267 $num = $Backups[$i]{num} if ( $num < $Backups[$i]{num} );
1270 $bpc->RmTreeDefer("$TopDir/trash", "$Dir/$num") if ( -d "$Dir/$num" );
1271 if ( !rename("$Dir/new", "$Dir/$num") ) {
1272 print(LOG $bpc->timeStamp, "Rename $Dir/new -> $Dir/$num failed\n");
1275 $needLink = 1 if ( -f "$Dir/NewFileList" );
1278 # Add the new backup information to the backup file
1281 $Backups[$i]{num} = $num;
1282 $Backups[$i]{type} = $type;
1283 $Backups[$i]{startTime} = $startTime;
1284 $Backups[$i]{endTime} = $endTime;
1285 $Backups[$i]{size} = $sizeTotal;
1286 $Backups[$i]{nFiles} = $nFilesTotal;
1287 $Backups[$i]{xferErrs} = $stat{xferErrCnt} || 0;
1288 $Backups[$i]{xferBadFile} = $stat{xferBadFileCnt} || 0;
1289 $Backups[$i]{xferBadShare} = $stat{xferBadShareCnt} || 0;
1290 $Backups[$i]{nFilesExist} = $nFilesExist;
1291 $Backups[$i]{sizeExist} = $sizeExist;
1292 $Backups[$i]{sizeExistComp} = $sizeExistComp;
1293 $Backups[$i]{tarErrs} = $tarErrs;
1294 $Backups[$i]{compress} = $Conf{CompressLevel};
1295 $Backups[$i]{noFill} = $type eq "incr" ? 1 : 0;
1296 $Backups[$i]{level} = $type eq "incr" ? 1 : 0;
1297 $Backups[$i]{mangle} = 1; # name mangling always on for v1.04+
1298 $Backups[$i]{xferMethod} = $Conf{XferMethod};
1299 $Backups[$i]{charset} = $Conf{ClientCharset};
1301 # Save the main backups file
1303 $bpc->BackupInfoWrite($client, @Backups);
1305 # Save just this backup's info in case the main backups file
1308 BackupPC::Storage->backupInfoWrite($Dir, $Backups[$i]{num},
1311 unlink("$Dir/timeStamp.level0") if ( -f "$Dir/timeStamp.level0" );
1312 foreach my $ext ( qw(bad bad.z) ) {
1313 next if ( !-f "$Dir/XferLOG.$ext" );
1314 unlink("$Dir/XferLOG.$ext.old") if ( -f "$Dir/XferLOG.$ext" );
1315 rename("$Dir/XferLOG.$ext", "$Dir/XferLOG.$ext.old");
1319 # Now remove the bad files, replacing them if possible with links to
1322 foreach my $f ( $xfer->getBadFiles ) {
1324 my $shareM = $bpc->fileNameEltMangle($f->{share});
1325 my $fileM = $bpc->fileNameMangle($f->{file});
1326 unlink("$Dir/$num/$shareM/$fileM");
1327 for ( $j = $i - 1 ; $j >= 0 ; $j-- ) {
1329 if ( $Backups[$j]{mangle} ) {
1330 $file = "$shareM/$fileM";
1332 $file = "$f->{share}/$f->{file}";
1334 next if ( !-f "$Dir/$Backups[$j]{num}/$file" );
1336 my($exists, $digest, $origSize, $outSize, $errs)
1337 = BackupPC::PoolWrite::LinkOrCopy(
1339 "$Dir/$Backups[$j]{num}/$file",
1340 $Backups[$j]{compress},
1341 "$Dir/$num/$shareM/$fileM",
1342 $Conf{CompressLevel});
1345 # the hard link failed, most likely because the target
1346 # file has too many links. We have copied the file
1347 # instead, so add this to the new file list.
1349 if ( !defined($newFilesFH) ) {
1350 my $str = "Appending to NewFileList for $shareM/$fileM\n";
1351 $XferLOG->write(\$str);
1352 open($newFilesFH, ">>", "$TopDir/pc/$client/NewFileList")
1353 || die("can't open $TopDir/pc/$client/NewFileList");
1354 binmode($newFilesFH);
1356 if ( -f "$Dir/$num/$shareM/$fileM" ) {
1357 print($newFilesFH "$digest $origSize $shareM/$fileM\n");
1359 my $str = "Unable to link/copy $num/$f->{share}/$f->{file}"
1360 . " to $Backups[$j]{num}/$f->{share}/$f->{file}\n";
1361 $XferLOG->write(\$str);
1364 my $str = "Bad file $num/$f->{share}/$f->{file} replaced"
1366 . " $Backups[$j]{num}/$f->{share}/$f->{file}\n";
1367 $XferLOG->write(\$str);
1372 my $str = "Removed bad file $num/$f->{share}/$f->{file}"
1373 . " (no older copy to link to)\n";
1374 $XferLOG->write(\$str);
1377 close($newFilesFH) if ( defined($newFilesFH) );
1379 rename("$Dir/XferLOG$fileExt", "$Dir/XferLOG.$num$fileExt");
1380 rename("$Dir/NewFileList", "$Dir/NewFileList.$num");
1386 # Removes a specific backup
1390 my($client, $Backups, $idx) = @_;
1391 my($Dir) = "$TopDir/pc/$client";
1393 if ( $Backups->[$idx]{num} eq "" ) {
1394 print("BackupRemove: ignoring empty backup number for idx $idx\n");
1398 $bpc->RmTreeDefer("$TopDir/trash",
1399 "$Dir/$Backups->[$idx]{num}");
1400 unlink("$Dir/SmbLOG.$Backups->[$idx]{num}")
1401 if ( -f "$Dir/SmbLOG.$Backups->[$idx]{num}" );
1402 unlink("$Dir/SmbLOG.$Backups->[$idx]{num}.z")
1403 if ( -f "$Dir/SmbLOG.$Backups->[$idx]{num}.z" );
1404 unlink("$Dir/XferLOG.$Backups->[$idx]{num}")
1405 if ( -f "$Dir/XferLOG.$Backups->[$idx]{num}" );
1406 unlink("$Dir/XferLOG.$Backups->[$idx]{num}.z")
1407 if ( -f "$Dir/XferLOG.$Backups->[$idx]{num}.z" );
1408 splice(@{$Backups}, $idx, 1);
1411 sub CorrectHostCheck
1413 my($hostIP, $host) = @_;
1414 return if ( $hostIP eq $host && !$Conf{FixedIPNetBiosNameCheck}
1415 || $Conf{NmbLookupCmd} eq "" );
1416 my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($hostIP);
1417 return "host $host has mismatching netbios name $netBiosHost"
1418 if ( $netBiosHost ne $host );
1423 # The Xfer method might tell us from time to time about processes
1424 # it forks. We tell BackupPC about this (for status displays) and
1425 # keep track of the pids in case we cancel the backup
1430 @xferPid = grep(/./, @xferPid);
1431 return if ( !@xferPid && $tarPid < 0 );
1432 my @pids = @xferPid;
1433 push(@pids, $tarPid) if ( $tarPid > 0 );
1434 my $str = join(",", @pids);
1435 $XferLOG->write(\"Xfer PIDs are now $str\n") if ( defined($XferLOG) );
1436 print("xferPids $str\n");
1440 # Run an optional pre- or post-dump command
1444 my($cmdType, $sharename) = @_;
1446 return if ( !defined($Conf{$cmdType}) );
1452 user => $Hosts->{$client}{user},
1453 moreUsers => $Hosts->{$client}{moreUsers},
1454 share => $ShareNames->[0],
1455 shares => $ShareNames,
1456 XferMethod => $Conf{XferMethod},
1457 sshPath => $Conf{SshPath},
1459 XferLOG => $XferLOG,
1461 xferOK => $stat{xferOK} || 0,
1462 hostError => $stat{hostError},
1464 cmdType => $cmdType,
1467 if ($cmdType eq 'DumpPreShareCmd' || $cmdType eq 'DumpPostShareCmd') {
1468 $vars->{share} = $sharename;
1471 my $cmd = $bpc->cmdVarSubstitute($Conf{$cmdType}, $vars);
1472 $XferLOG->write(\"Executing $cmdType: @$cmd\n");
1474 # Run the user's command, dumping the stdout/stderr into the
1475 # Xfer log file. Also supply the optional $vars and %Conf in
1476 # case the command is really perl code instead of a shell
1479 $bpc->cmdSystemOrEval($cmd,
1481 $XferLOG->write(\$_[0]);