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.0beta0, released 20 Mar 2004.
75 # See http://backuppc.sourceforge.net.
77 #========================================================================
81 use lib "/usr/local/BackupPC/lib";
83 use BackupPC::FileZIO;
84 use BackupPC::Xfer::Smb;
85 use BackupPC::Xfer::Tar;
86 use BackupPC::Xfer::Rsync;
92 ###########################################################################
94 ###########################################################################
96 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
97 my $TopDir = $bpc->TopDir();
98 my $BinDir = $bpc->BinDir();
99 my %Conf = $bpc->Conf();
108 if ( !getopts("defiv", \%opts) || @ARGV != 1 ) {
109 print("usage: $0 [-d] [-e] [-f] [-i] [-v] <client>\n");
112 if ( $ARGV[0] !~ /^([\w\.\s-]+)$/ ) {
113 print("$0: bad client name '$ARGV[0]'\n");
116 my $client = $1; # BackupPC's client name (might not be real host name)
117 my $hostIP; # this is the IP address
118 my $host; # this is the real host name
120 my($clientURI, $user);
122 $bpc->verbose(1) if ( $opts{v} );
126 # The client name $client is simply a DHCP address. We need to check
127 # if there is any machine at this address, and if so, get the actual
128 # host name via NetBios using nmblookup.
131 if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
132 print(STDERR "Exiting because CheckHostAlive($hostIP) failed\n")
136 if ( $Conf{NmbLookupCmd} eq "" ) {
137 print(STDERR "Exiting because \$Conf{NmbLookupCmd} is empty\n")
141 ($client, $user) = $bpc->NetBiosInfoGet($hostIP);
142 if ( $client !~ /^([\w\.\s-]+)$/ ) {
143 print(STDERR "Exiting because NetBiosInfoGet($hostIP) returned"
144 . " '$client', an invalid host name\n") if ( $opts{v} );
147 $Hosts = $bpc->HostInfoRead($client);
150 $Hosts = $bpc->HostInfoRead($client);
152 if ( !defined($Hosts->{$client}) ) {
153 print(STDERR "Exiting because host $client does not exist in the"
154 . " hosts file\n") if ( $opts{v} );
158 my $Dir = "$TopDir/pc/$client";
163 # Re-read config file, so we can include the PC-specific config
165 $clientURI = $bpc->uriEsc($client);
166 if ( defined(my $error = $bpc->ConfigRead($client)) ) {
167 print("dump failed: Can't read PC's config file: $error\n");
170 %Conf = $bpc->Conf();
173 # Catch various signals
175 $SIG{INT} = \&catch_signal;
176 $SIG{ALRM} = \&catch_signal;
177 $SIG{TERM} = \&catch_signal;
178 $SIG{PIPE} = \&catch_signal;
179 $SIG{STOP} = \&catch_signal;
180 $SIG{TSTP} = \&catch_signal;
181 $SIG{TTIN} = \&catch_signal;
185 # Make sure we eventually timeout if there is no activity from
186 # the data transport program.
188 alarm($Conf{ClientTimeout});
190 mkpath($Dir, 0, 0777) if ( !-d $Dir );
191 if ( !-f "$Dir/LOCK" ) {
192 open(LOCK, ">", "$Dir/LOCK") && close(LOCK);
194 open(LOG, ">>", "$Dir/LOG");
195 select(LOG); $| = 1; select(STDOUT);
198 # For the -e option we just expire backups and quit
201 BackupExpire($client);
206 # For archive hosts we don't bother any further
208 if ($Conf{XferMethod} eq "archive" ) {
209 print(STDERR "Exiting because the XferMethod is set to archive\n")
216 # In the non-DHCP case, make sure the host can be looked up
217 # via NS, or otherwise find the IP address via NetBios.
219 if ( $Conf{ClientNameAlias} ne "" ) {
220 $host = $Conf{ClientNameAlias};
224 if ( !defined(gethostbyname($host)) ) {
226 # Ok, NS doesn't know about it. Maybe it is a NetBios name
229 print(STDERR "Name server doesn't know about $host; trying NetBios\n")
231 if ( !defined($hostIP = $bpc->NetBiosHostIPFind($host)) ) {
232 print(LOG $bpc->timeStamp, "Can't find host $host via netbios\n");
233 print("host not found\n");
241 ###########################################################################
242 # Figure out what to do and do it
243 ###########################################################################
246 # See if we should skip this host during a certain range
249 my $err = $bpc->ServerConnect($Conf{ServerHost}, $Conf{ServerPort});
251 print("Can't connect to server ($err)\n");
252 print(LOG $bpc->timeStamp, "Can't connect to server ($err)\n");
255 my $reply = $bpc->ServerMesg("status host($clientURI)");
256 $reply = $1 if ( $reply =~ /(.*)/s );
259 $bpc->ServerDisconnect();
262 # For DHCP tell BackupPC which host this is
265 if ( $StatusHost{activeJob} ) {
266 # oops, something is already running for this host
267 print(STDERR "Exiting because backup is already running for $client\n")
271 print("DHCP $hostIP $clientURI\n");
274 my($needLink, @Backups, $type, $lastBkupNum, $lastFullBkupNum);
280 if ( $Conf{FullPeriod} == -1 && !$opts{f} && !$opts{i}
281 || $Conf{FullPeriod} == -2 ) {
282 print(STDERR "Exiting because backups are disabled with"
283 . " \$Conf{FullPeriod} = $Conf{FullPeriod}\n") if ( $opts{v} );
285 # Tell BackupPC to ignore old failed backups on hosts that
286 # have backups disabled.
288 print("backups disabled\n")
289 if ( defined($StatusHost{errorTime})
290 && $StatusHost{reason} ne "Reason_backup_done"
291 && time - $StatusHost{errorTime} > 4 * 24 * 3600 );
292 NothingToDo($needLink);
295 if ( !$opts{i} && !$opts{f} && $Conf{BlackoutGoodCnt} >= 0
296 && $StatusHost{aliveCnt} >= $Conf{BlackoutGoodCnt} ) {
297 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
298 my($currHours) = $hour + $min / 60 + $sec / 3600;
302 # Handle backward compatibility with original separate scalar
305 if ( defined($Conf{BlackoutHourBegin}) ) {
306 push(@{$Conf{BlackoutPeriods}},
308 hourBegin => $Conf{BlackoutHourBegin},
309 hourEnd => $Conf{BlackoutHourEnd},
310 weekDays => $Conf{BlackoutWeekDays},
314 foreach my $p ( @{$Conf{BlackoutPeriods}} ) {
316 # Allow blackout to span midnight (specified by BlackoutHourBegin
317 # being greater than BlackoutHourEnd)
319 next if ( ref($p->{weekDays}) ne "ARRAY"
320 || !defined($p->{hourBegin})
321 || !defined($p->{hourEnd})
323 if ( $p->{hourBegin} > $p->{hourEnd} ) {
324 $blackout = $p->{hourBegin} <= $currHours
325 || $currHours <= $p->{hourEnd};
326 if ( $currHours <= $p->{hourEnd} ) {
328 # This is after midnight, so decrement the weekday for the
329 # weekday check (eg: Monday 11pm-1am means Monday 2300 to
330 # Tuesday 0100, not Monday 2300-2400 plus Monday 0000-0100).
333 $wday += 7 if ( $wday < 0 );
336 $blackout = $p->{hourBegin} <= $currHours
337 && $currHours <= $p->{hourEnd};
339 if ( $blackout && grep($_ == $wday, @{$p->{weekDays}}) ) {
340 # print(LOG $bpc->timeStamp, "skipping because of blackout"
341 # . " (alive $StatusHost{aliveCnt} times)\n");
342 print(STDERR "Skipping $client because of blackout\n")
344 NothingToDo($needLink);
349 if ( !$opts{i} && !$opts{f} && $StatusHost{backoffTime} > time ) {
350 printf(LOG "%sskipping because of user requested delay (%.1f hours left)",
351 $bpc->timeStamp, ($StatusHost{backoffTime} - time) / 3600);
352 NothingToDo($needLink);
356 # Now see if there are any old backups we should delete
358 BackupExpire($client);
361 # Read Backup information, and find times of the most recent full and
362 # incremental backups
364 @Backups = $bpc->BackupInfoRead($client);
365 for ( my $i = 0 ; $i < @Backups ; $i++ ) {
366 $needLink = 1 if ( $Backups[$i]{nFilesNew} eq ""
367 || -f "$Dir/NewFileList.$Backups[$i]{num}" );
368 $lastBkupNum = $Backups[$i]{num};
369 if ( $Backups[$i]{type} eq "full" ) {
370 if ( $lastFull < $Backups[$i]{startTime} ) {
371 $lastFull = $Backups[$i]{startTime};
372 $lastFullBkupNum = $Backups[$i]{num};
374 } elsif ( $Backups[$i]{type} eq "incr" ) {
375 $lastIncr = $Backups[$i]{startTime}
376 if ( $lastIncr < $Backups[$i]{startTime} );
377 } elsif ( $Backups[$i]{type} eq "partial" ) {
379 $partialNum = $Backups[$i]{num};
384 # Decide whether we do nothing, or a full or incremental backup.
388 || (!$opts{i} && (time - $lastFull > $Conf{FullPeriod} * 24*3600
389 && time - $lastIncr > $Conf{IncrPeriod} * 24*3600)) ) {
391 } elsif ( $opts{i} || (time - $lastIncr > $Conf{IncrPeriod} * 24*3600
392 && time - $lastFull > $Conf{IncrPeriod} * 24*3600) ) {
395 NothingToDo($needLink);
399 # Check if $host is alive
401 my $delay = $bpc->CheckHostAlive($hostIP);
403 print(LOG $bpc->timeStamp, "no ping response\n");
404 print("no ping response\n");
405 print("link $clientURI\n") if ( $needLink );
407 } elsif ( $delay > $Conf{PingMaxMsec} ) {
408 printf(LOG "%sping too slow: %.4gmsec\n", $bpc->timeStamp, $delay);
409 printf("ping too slow: %.4gmsec (threshold is %gmsec)\n",
410 $delay, $Conf{PingMaxMsec});
411 print("link $clientURI\n") if ( $needLink );
416 # Make sure it is really the machine we expect (only for fixed addresses,
417 # since we got the DHCP address above).
419 if ( !$opts{d} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
420 print(LOG $bpc->timeStamp, "dump failed: $errMsg\n");
421 print("dump failed: $errMsg\n");
423 } elsif ( $opts{d} ) {
424 print(LOG $bpc->timeStamp, "$host is dhcp $hostIP, user is $user\n");
428 # Get a clean directory $Dir/new
430 $bpc->RmTreeDefer("$TopDir/trash", "$Dir/new") if ( -d "$Dir/new" );
433 # Setup file extension for compression and open XferLOG output file
435 $Conf{CompressLevel} = 0 if ( !BackupPC::FileZIO->compOk );
436 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
437 my $XferLOG = BackupPC::FileZIO->open("$Dir/XferLOG$fileExt", 1,
438 $Conf{CompressLevel});
439 if ( !defined($XferLOG) ) {
440 print(LOG $bpc->timeStamp, "dump failed: unable to open/create"
441 . " $Dir/XferLOG$fileExt\n");
442 print("dump failed: unable to open/create $Dir/XferLOG$fileExt\n");
447 # Ignore the partial dump in the case of an incremental.
448 # A partial is a partial full.
450 if ( $type ne "full" ) {
456 # If this is a partial, copy the old XferLOG file
459 my($compress, $fileName);
460 if ( -f "$Dir/XferLOG.$partialNum.z" ) {
461 $fileName = "$Dir/XferLOG.$partialNum.z";
463 } elsif ( -f "$Dir/XferLOG.$partialNum" ) {
464 $fileName = "$Dir/XferLOG.$partialNum";
467 if ( my $oldLOG = BackupPC::FileZIO->open($fileName, 0, $compress) ) {
469 while ( $oldLOG->read(\$data, 65536) > 0 ) {
470 $XferLOG->write(\$data);
476 $XferLOG->writeTeeStderr(1) if ( $opts{v} );
477 unlink("$Dir/NewFileList") if ( -f "$Dir/NewFileList" );
479 my $startTime = time();
483 my $sizeExistComp = 0;
486 my($logMsg, %stat, $xfer, $ShareNames, $noFilesErr);
489 if ( $Conf{XferMethod} eq "tar" ) {
490 $ShareNames = $Conf{TarShareName};
491 } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
492 $ShareNames = $Conf{RsyncShareName};
494 $ShareNames = $Conf{SmbShareName};
497 $ShareNames = [ $ShareNames ] unless ref($ShareNames) eq "ARRAY";
500 # Run an optional pre-dump command
502 UserCommandRun("DumpPreUserCmd");
506 # Now backup each of the shares
508 for my $shareName ( @$ShareNames ) {
511 $stat{xferOK} = $stat{hostAbort} = undef;
512 $stat{hostError} = $stat{lastOutputLine} = undef;
513 if ( -d "$Dir/new/$shareName" ) {
514 print(LOG $bpc->timeStamp,
515 "unexpected repeated share name $shareName skipped\n");
519 if ( $Conf{XferMethod} eq "tar" ) {
521 # Use tar (eg: tar/ssh) as the transport program.
523 $xfer = BackupPC::Xfer::Tar->new($bpc);
524 } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
526 # Use rsync as the transport program.
528 if ( !defined($xfer = BackupPC::Xfer::Rsync->new($bpc)) ) {
529 my $errStr = BackupPC::Xfer::Rsync::errStr;
530 print(LOG $bpc->timeStamp, "dump failed: $errStr\n");
531 print("dump failed: $errStr\n");
532 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
537 # Default is to use smbclient (smb) as the transport program.
539 $xfer = BackupPC::Xfer::Smb->new($bpc);
542 my $useTar = $xfer->useTar;
546 # This xfer method outputs a tar format file, so we start a
547 # BackupPC_tarExtract to extract the data.
549 # Create a socketpair to connect the Xfer method to BackupPC_tarExtract
550 # WH is the write handle for writing, provided to the transport
551 # program, and RH is the other end of the socket for reading,
552 # provided to BackupPC_tarExtract.
554 if ( socketpair(RH, WH, AF_UNIX, SOCK_STREAM, PF_UNSPEC) ) {
555 shutdown(RH, 1); # no writing to this socket
556 shutdown(WH, 0); # no reading from this socket
557 setsockopt(RH, SOL_SOCKET, SO_RCVBUF, 8 * 65536);
558 setsockopt(WH, SOL_SOCKET, SO_SNDBUF, 8 * 65536);
561 # Default to pipe() if socketpair() doesn't work.
567 # fork a child for BackupPC_tarExtract. TAR is a file handle
568 # on which we (the parent) read the stdout & stderr from
569 # BackupPC_tarExtract.
571 if ( !defined($tarPid = open(TAR, "-|")) ) {
572 print(LOG $bpc->timeStamp, "can't fork to run tar\n");
573 print("can't fork to run tar\n");
581 # This is the tar child. Close the write end of the pipe,
582 # clone STDERR to STDOUT, clone STDIN from RH, and then
583 # exec BackupPC_tarExtract.
588 open(STDERR, ">&STDOUT");
592 exec("$BinDir/BackupPC_tarExtract", $client, $shareName,
593 $Conf{CompressLevel});
594 print(LOG $bpc->timeStamp,
595 "can't exec $BinDir/BackupPC_tarExtract\n");
598 } elsif ( !defined($newFilesFH) ) {
600 # We need to create the NewFileList output file
603 open(NEW_FILES, ">", "$TopDir/pc/$client/NewFileList")
604 || die("can't open $TopDir/pc/$client/NewFileList");
605 $newFilesFH = *NEW_FILES;
610 # Run the transport program
616 shareName => $shareName,
620 newFilesFH => $newFilesFH,
623 lastFull => $lastFull,
624 lastBkupNum => $lastBkupNum,
625 lastFullBkupNum => $lastFullBkupNum,
626 backups => \@Backups,
627 compress => $Conf{CompressLevel},
628 XferMethod => $Conf{XferMethod},
629 logLevel => $Conf{XferLogLevel},
630 pidHandler => \&pidHandler,
631 partialNum => $partialNum,
634 if ( !defined($logMsg = $xfer->start()) ) {
635 print(LOG $bpc->timeStamp, "xfer start failed: ", $xfer->errStr, "\n");
636 print("dump failed: ", $xfer->errStr, "\n");
637 print("link $clientURI\n") if ( $needLink );
639 # kill off the tar process, first nicely then forcefully
642 kill($bpc->sigName2num("INT"), $tarPid);
644 kill($bpc->sigName2num("KILL"), $tarPid);
647 kill($bpc->sigName2num("INT"), @xferPid);
649 kill($bpc->sigName2num("KILL"), @xferPid);
651 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
655 @xferPid = $xfer->xferPid;
659 # The parent must close both handles on the pipe since the children
660 # are using these handles now.
665 print(LOG $bpc->timeStamp, $logMsg, "\n");
666 print("started $type dump, share=$shareName\n");
668 pidHandler(@xferPid);
672 # Parse the output of the transfer program and BackupPC_tarExtract
673 # while they run. Since we might be reading from two or more children
676 my($FDread, $tarOut, $mesg);
677 vec($FDread, fileno(TAR), 1) = 1 if ( $useTar );
678 $xfer->setSelectMask(\$FDread);
682 last if ( $FDread =~ /^\0*$/ );
683 select(my $rout = $FDread, undef, $ein, undef);
685 if ( vec($rout, fileno(TAR), 1) ) {
686 if ( sysread(TAR, $mesg, 8192) <= 0 ) {
687 vec($FDread, fileno(TAR), 1) = 0;
693 while ( $tarOut =~ /(.*?)[\n\r]+(.*)/s ) {
697 $XferLOG->write(\"$_\n");
699 $XferLOG->write(\"tarExtract: $_\n");
701 if ( /^BackupPC_tarExtact aborting \((.*)\)/ ) {
702 $stat{hostError} = $1;
704 if ( /^Done: (\d+) errors, (\d+) filesExist, (\d+) sizeExist, (\d+) sizeExistComp, (\d+) filesTotal, (\d+) sizeTotal/ ) {
708 $sizeExistComp += $4;
714 last if ( !$xfer->readOutput(\$FDread, $rout) );
715 while ( my $str = $xfer->logMsgGet ) {
716 print(LOG $bpc->timeStamp, "xfer: $str\n");
718 if ( $xfer->getStats->{fileCnt} == 1 ) {
720 # Make sure it is still the machine we expect. We do this while
721 # the transfer is running to avoid a potential race condition if
722 # the ip address was reassigned by dhcp just before we started
725 if ( my $errMsg = CorrectHostCheck($hostIP, $host) ) {
726 $stat{hostError} = $errMsg if ( $stat{hostError} eq "" );
733 # otherwise the xfer module does everything for us
735 my @results = $xfer->run();
736 $tarErrs += $results[0];
737 $nFilesExist += $results[1];
738 $sizeExist += $results[2];
739 $sizeExistComp += $results[3];
740 $nFilesTotal += $results[4];
741 $sizeTotal += $results[5];
745 # Merge the xfer status (need to accumulate counts)
747 my $newStat = $xfer->getStats;
748 if ( $newStat->{fileCnt} == 0 ) {
749 $noFilesErr ||= "No files dumped for share $shareName";
751 foreach my $k ( (keys(%stat), keys(%$newStat)) ) {
752 next if ( !defined($newStat->{$k}) );
753 if ( $k =~ /Cnt$/ ) {
754 $stat{$k} += $newStat->{$k};
755 delete($newStat->{$k});
758 if ( !defined($stat{$k}) ) {
759 $stat{$k} = $newStat->{$k};
760 delete($newStat->{$k});
764 $stat{xferOK} = 0 if ( $stat{hostError} || $stat{hostAbort} );
765 if ( !$stat{xferOK} ) {
767 # kill off the tranfer program, first nicely then forcefully
770 kill($bpc->sigName2num("INT"), @xferPid);
772 kill($bpc->sigName2num("KILL"), @xferPid);
775 # kill off the tar process, first nicely then forcefully
778 kill($bpc->sigName2num("INT"), $tarPid);
780 kill($bpc->sigName2num("KILL"), $tarPid);
783 # don't do any more shares on this host
790 # If this is a full, and any share had zero files then consider the dump bad
792 if ( $type eq "full" && $stat{hostError} eq ""
793 && length($noFilesErr) && $Conf{BackupZeroFilesIsFatal} ) {
794 $stat{hostError} = $noFilesErr;
798 $stat{xferOK} = 0 if ( $Abort );
801 # Do one last check to make sure it is still the machine we expect.
803 if ( $stat{xferOK} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
804 $stat{hostError} = $errMsg;
808 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
809 close($newFilesFH) if ( defined($newFilesFH) );
811 my $endTime = time();
814 # If the dump failed, clean up
816 if ( !$stat{xferOK} ) {
817 $stat{hostError} = $stat{lastOutputLine} if ( $stat{hostError} eq "" );
818 if ( $stat{hostError} ) {
819 print(LOG $bpc->timeStamp,
820 "Got fatal error during xfer ($stat{hostError})\n");
821 $XferLOG->write(\"Got fatal error during xfer ($stat{hostError})\n");
825 # wait a short while and see if the system is still alive
828 if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
829 $stat{hostAbort} = 1;
831 if ( $stat{hostAbort} ) {
832 $stat{hostError} = "lost network connection during backup";
834 print(LOG $bpc->timeStamp, "Backup aborted ($stat{hostError})\n");
835 $XferLOG->write(\"Backup aborted ($stat{hostError})\n");
837 $XferLOG->write(\"Backup aborted by user signal\n");
841 # Close the log file and call BackupFailCleanup, which exits.
846 my $newNum = BackupSave();
848 my $otherCount = $stat{xferErrCnt} - $stat{xferBadFileCnt}
849 - $stat{xferBadShareCnt};
850 print(LOG $bpc->timeStamp,
851 "$type backup $newNum complete, $stat{fileCnt} files,"
852 . " $stat{byteCnt} bytes,"
853 . " $stat{xferErrCnt} xferErrs ($stat{xferBadFileCnt} bad files,"
854 . " $stat{xferBadShareCnt} bad shares, $otherCount other)\n");
856 BackupExpire($client);
858 print("$type backup complete\n");
860 ###########################################################################
862 ###########################################################################
868 print("nothing to do\n");
869 print("link $clientURI\n") if ( $needLink );
878 # The first time we receive a signal we try to gracefully
879 # abort the backup. This allows us to keep a partial dump
880 # with the in-progress file deleted and attribute caches
881 # flushed to disk etc.
883 if ( !length($SigName) ) {
885 if ( $sigName eq "INT" ) {
886 $reason = "aborted by user (signal=$sigName)";
888 $reason = "aborted by signal=$sigName";
892 # Parent logs a message
894 print(LOG $bpc->timeStamp,
895 "Aborting backup up after signal $sigName\n");
900 $xfer->abort($reason);
903 # Send ALRMs to BackupPC_tarExtract if we are using it
906 kill($bpc->sigName2num("ARLM"), $tarPid);
910 # Schedule a 20 second timer in case the clean
911 # abort doesn't complete
916 # Children ignore anything other than ALRM and INT
918 if ( $sigName ne "ALRM" && $sigName ne "INT" ) {
923 # The child also tells xfer to abort
925 $xfer->abort($reason);
928 # Schedule a 15 second timer in case the clean
929 # abort doesn't complete
939 # This is a second signal: time to clean up.
941 if ( $Pid != $$ && ($sigName eq "ALRM" || $sigName eq "INT") ) {
943 # Children quit quietly on ALRM or INT
949 # Ignore other signals in children
951 return if ( $Pid != $$ );
953 $SIG{$sigName} = 'IGNORE';
954 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
955 $XferLOG->write(\"exiting after signal $sigName\n");
957 kill($bpc->sigName2num("INT"), @xferPid);
959 kill($bpc->sigName2num("KILL"), @xferPid);
962 kill($bpc->sigName2num("INT"), $tarPid);
964 kill($bpc->sigName2num("KILL"), $tarPid);
966 if ( $sigName eq "INT" ) {
967 $stat{hostError} = "aborted by user (signal=$sigName)";
969 $stat{hostError} = "received signal=$sigName";
976 if ( -f _ && $File::Find::name !~ /\/fattrib$/ ) {
980 # No need to check entire tree
982 $File::Find::prune = 1 if ( $nFilesTotal );
986 sub BackupFailCleanup
988 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
992 # We keep this backup if it is a full and we actually backed
995 if ( $type eq "full" ) {
996 if ( $nFilesTotal == 0 && $xfer->getStats->{fileCnt} == 0 ) {
998 # Xfer didn't report any files, but check in the new
999 # directory just in case.
1001 find(\&CheckForNewFiles, "$Dir/new");
1002 $keepPartial = 1 if ( $nFilesTotal );
1005 # Xfer reported some files
1011 if ( !$keepPartial ) {
1013 # No point in saving this dump; get rid of eveything.
1016 unlink("$Dir/timeStamp.level0") if ( -f "$Dir/timeStamp.level0" );
1017 unlink("$Dir/SmbLOG.bad") if ( -f "$Dir/SmbLOG.bad" );
1018 unlink("$Dir/SmbLOG.bad$fileExt") if ( -f "$Dir/SmbLOG.bad$fileExt" );
1019 unlink("$Dir/XferLOG.bad") if ( -f "$Dir/XferLOG.bad" );
1020 unlink("$Dir/XferLOG.bad$fileExt") if ( -f "$Dir/XferLOG.bad$fileExt" );
1021 unlink("$Dir/NewFileList") if ( -f "$Dir/NewFileList" );
1022 rename("$Dir/XferLOG$fileExt", "$Dir/XferLOG.bad$fileExt");
1023 $bpc->RmTreeDefer("$TopDir/trash", "$Dir/new") if ( -d "$Dir/new" );
1024 print("dump failed: $stat{hostError}\n");
1026 print("link $clientURI\n") if ( $needLink );
1030 # Ok, now we should save this as a partial dump
1033 my $newNum = BackupSave();
1034 print("dump failed: $stat{hostError}\n");
1035 print("link $clientURI\n") if ( $needLink );
1036 print(LOG $bpc->timeStamp, "Saved partial dump $newNum\n");
1041 # Decide which old backups should be expired by moving them
1047 my($Dir) = "$TopDir/pc/$client";
1048 my(@Backups) = $bpc->BackupInfoRead($client);
1049 my($cntFull, $cntIncr, $firstFull, $firstIncr, $oldestIncr, $oldestFull);
1051 if ( $Conf{FullKeepCnt} <= 0 ) {
1052 print(LOG $bpc->timeStamp,
1053 "Invalid value for \$Conf{FullKeepCnt}=$Conf{FullKeepCnt}\n");
1055 "Invalid value for \$Conf{FullKeepCnt}=$Conf{FullKeepCnt}\n")
1060 $cntFull = $cntIncr = 0;
1061 $oldestIncr = $oldestFull = 0;
1062 for ( my $i = 0 ; $i < @Backups ; $i++ ) {
1063 if ( $Backups[$i]{type} eq "full" ) {
1064 $firstFull = $i if ( $cntFull == 0 );
1067 $firstIncr = $i if ( $cntIncr == 0 );
1071 $oldestIncr = (time - $Backups[$firstIncr]{startTime}) / (24 * 3600)
1072 if ( $cntIncr > 0 );
1073 $oldestFull = (time - $Backups[$firstFull]{startTime}) / (24 * 3600)
1074 if ( $cntFull > 0 );
1075 if ( $cntIncr > $Conf{IncrKeepCnt}
1076 || ($cntIncr > $Conf{IncrKeepCntMin}
1077 && $oldestIncr > $Conf{IncrAgeMax})
1078 && (@Backups <= $firstIncr + 1
1079 || $Backups[$firstIncr]{noFill}
1080 || !$Backups[$firstIncr + 1]{noFill}) ) {
1082 # Only delete an incr backup if the Conf settings are satisfied.
1083 # We also must make sure that either this backup is the most
1084 # recent one, or it is not filled, or the next backup is filled.
1085 # (We can't deleted a filled incr if the next backup is not
1088 print(LOG $bpc->timeStamp,
1089 "removing incr backup $Backups[$firstIncr]{num}\n");
1090 BackupRemove($client, \@Backups, $firstIncr);
1095 # Delete any old full backups, according to $Conf{FullKeepCntMin}
1096 # and $Conf{FullAgeMax}.
1098 if ( $cntFull > $Conf{FullKeepCntMin}
1099 && $oldestFull > $Conf{FullAgeMax}
1100 && (@Backups <= $firstFull + 1
1101 || !$Backups[$firstFull + 1]{noFill}) ) {
1103 # Only delete a full backup if the Conf settings are satisfied.
1104 # We also must make sure that either this backup is the most
1105 # recent one, or the next backup is filled.
1106 # (We can't deleted a full backup if the next backup is not
1109 print(LOG $bpc->timeStamp,
1110 "removing old full backup $Backups[$firstFull]{num}\n");
1111 BackupRemove($client, \@Backups, $firstFull);
1116 # Do new-style full backup expiry, which includes the the case
1117 # where $Conf{FullKeepCnt} is an array.
1119 last if ( !BackupFullExpire($client, \@Backups) );
1121 $bpc->BackupInfoWrite($client, @Backups);
1125 # Handle full backup expiry, using exponential periods.
1127 sub BackupFullExpire
1129 my($client, $Backups) = @_;
1131 my $fullPeriod = $Conf{FullPeriod};
1132 my $origFullPeriod = $fullPeriod;
1133 my $fullKeepCnt = $Conf{FullKeepCnt};
1134 my $fullKeepIdx = 0;
1135 my(@delete, @fullList);
1138 # Don't delete anything if $Conf{FullPeriod} or $Conf{FullKeepCnt} are
1139 # not defined - possibly a corrupted config.pl file.
1141 return if ( !defined($Conf{FullPeriod}) || !defined($Conf{FullKeepCnt}) );
1144 # If regular backups are still disabled with $Conf{FullPeriod} < 0,
1145 # we still expire backups based on a typical FullPeriod value - weekly.
1147 $fullPeriod = 7 if ( $fullPeriod <= 0 );
1149 $fullKeepCnt = [$fullKeepCnt] if ( ref($fullKeepCnt) ne "ARRAY" );
1151 for ( my $i = 0 ; $i < @$Backups ; $i++ ) {
1152 next if ( $Backups->[$i]{type} ne "full" );
1153 push(@fullList, $i);
1155 for ( my $k = @fullList - 1 ; $k >= 0 ; $k-- ) {
1156 my $i = $fullList[$k];
1157 my $prevFull = $fullList[$k-1] if ( $k > 0 );
1159 # Don't delete any full that is followed by an unfilled backup,
1160 # since it is needed for restore.
1162 my $noDelete = $i + 1 < @$Backups ? $Backups->[$i+1]{noFill} : 0;
1165 ($fullKeepIdx >= @$fullKeepCnt
1168 && $Backups->[$i]{startTime} - $Backups->[$prevFull]{startTime}
1169 < ($fullPeriod - $origFullPeriod / 2) * 24 * 3600
1173 # Delete the full backup
1175 #printf("Deleting backup $i ($prevFull)\n");
1179 while ( $fullKeepIdx < @$fullKeepCnt
1180 && $fullCnt >= $fullKeepCnt->[$fullKeepIdx] ) {
1183 $fullPeriod = 2 * $fullPeriod;
1188 # Now actually delete the backups
1190 for ( my $i = @delete - 1 ; $i >= 0 ; $i-- ) {
1191 print(LOG $bpc->timeStamp,
1192 "removing full backup $Backups->[$delete[$i]]{num}\n");
1193 BackupRemove($client, $Backups, $delete[$i]);
1199 # Removes any partial backups
1201 sub BackupPartialRemove
1203 my($client, $Backups) = @_;
1205 for ( my $i = @$Backups - 1 ; $i >= 0 ; $i-- ) {
1206 next if ( $Backups->[$i]{type} ne "partial" );
1207 BackupRemove($client, $Backups, $i);
1213 my @Backups = $bpc->BackupInfoRead($client);
1217 # Since we got a good backup we should remove any partial dumps
1218 # (the new backup might also be a partial, but that's ok).
1220 BackupPartialRemove($client, \@Backups);
1223 # Number the new backup
1225 for ( my $i = 0 ; $i < @Backups ; $i++ ) {
1226 $num = $Backups[$i]{num} if ( $num < $Backups[$i]{num} );
1229 $bpc->RmTreeDefer("$TopDir/trash", "$Dir/$num") if ( -d "$Dir/$num" );
1230 if ( !rename("$Dir/new", "$Dir/$num") ) {
1231 print(LOG $bpc->timeStamp, "Rename $Dir/new -> $Dir/$num failed\n");
1234 $needLink = 1 if ( -f "$Dir/NewFileList" );
1237 # Add the new backup information to the backup file
1240 $Backups[$i]{num} = $num;
1241 $Backups[$i]{type} = $type;
1242 $Backups[$i]{startTime} = $startTime;
1243 $Backups[$i]{endTime} = $endTime;
1244 $Backups[$i]{size} = $sizeTotal;
1245 $Backups[$i]{nFiles} = $nFilesTotal;
1246 $Backups[$i]{xferErrs} = $stat{xferErrCnt} || 0;
1247 $Backups[$i]{xferBadFile} = $stat{xferBadFileCnt} || 0;
1248 $Backups[$i]{xferBadShare} = $stat{xferBadShareCnt} || 0;
1249 $Backups[$i]{nFilesExist} = $nFilesExist;
1250 $Backups[$i]{sizeExist} = $sizeExist;
1251 $Backups[$i]{sizeExistComp} = $sizeExistComp;
1252 $Backups[$i]{tarErrs} = $tarErrs;
1253 $Backups[$i]{compress} = $Conf{CompressLevel};
1254 $Backups[$i]{noFill} = $type eq "incr" ? 1 : 0;
1255 $Backups[$i]{level} = $type eq "incr" ? 1 : 0;
1256 $Backups[$i]{mangle} = 1; # name mangling always on for v1.04+
1257 $bpc->BackupInfoWrite($client, @Backups);
1259 unlink("$Dir/timeStamp.level0") if ( -f "$Dir/timeStamp.level0" );
1260 foreach my $ext ( qw(bad bad.z) ) {
1261 next if ( !-f "$Dir/XferLOG.$ext" );
1262 unlink("$Dir/XferLOG.$ext.old") if ( -f "$Dir/XferLOG.$ext" );
1263 rename("$Dir/XferLOG.$ext", "$Dir/XferLOG.$ext.old");
1267 # Now remove the bad files, replacing them if possible with links to
1270 foreach my $f ( $xfer->getBadFiles ) {
1272 my $shareM = $bpc->fileNameEltMangle($f->{share});
1273 my $fileM = $bpc->fileNameMangle($f->{file});
1274 unlink("$Dir/$num/$shareM/$fileM");
1275 for ( $j = $i - 1 ; $j >= 0 ; $j-- ) {
1277 if ( $Backups[$j]{mangle} ) {
1278 $file = "$shareM/$fileM";
1280 $file = "$f->{share}/$f->{file}";
1282 next if ( !-f "$Dir/$Backups[$j]{num}/$file" );
1283 if ( !link("$Dir/$Backups[$j]{num}/$file",
1284 "$Dir/$num/$shareM/$fileM") ) {
1285 my $str = \"Unable to link $num/$f->{share}/$f->{file} to"
1286 . " $Backups[$j]{num}/$f->{share}/$f->{file}\n";
1287 $XferLOG->write(\$str);
1289 my $str = "Bad file $num/$f->{share}/$f->{file} replaced"
1291 . " $Backups[$j]{num}/$f->{share}/$f->{file}\n";
1292 $XferLOG->write(\$str);
1297 my $str = "Removed bad file $num/$f->{share}/$f->{file}"
1298 . " (no older copy to link to)\n";
1299 $XferLOG->write(\$str);
1303 rename("$Dir/XferLOG$fileExt", "$Dir/XferLOG.$num$fileExt");
1304 rename("$Dir/NewFileList", "$Dir/NewFileList.$num");
1310 # Removes a specific backup
1314 my($client, $Backups, $idx) = @_;
1315 my($Dir) = "$TopDir/pc/$client";
1317 $bpc->RmTreeDefer("$TopDir/trash",
1318 "$Dir/$Backups->[$idx]{num}");
1319 unlink("$Dir/SmbLOG.$Backups->[$idx]{num}")
1320 if ( -f "$Dir/SmbLOG.$Backups->[$idx]{num}" );
1321 unlink("$Dir/SmbLOG.$Backups->[$idx]{num}.z")
1322 if ( -f "$Dir/SmbLOG.$Backups->[$idx]{num}.z" );
1323 unlink("$Dir/XferLOG.$Backups->[$idx]{num}")
1324 if ( -f "$Dir/XferLOG.$Backups->[$idx]{num}" );
1325 unlink("$Dir/XferLOG.$Backups->[$idx]{num}.z")
1326 if ( -f "$Dir/XferLOG.$Backups->[$idx]{num}.z" );
1327 splice(@{$Backups}, $idx, 1);
1330 sub CorrectHostCheck
1332 my($hostIP, $host) = @_;
1333 return if ( $hostIP eq $host && !$Conf{FixedIPNetBiosNameCheck}
1334 || $Conf{NmbLookupCmd} eq "" );
1335 my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($hostIP);
1336 return "host $host has mismatching netbios name $netBiosHost"
1337 if ( $netBiosHost ne $host );
1342 # The Xfer method might tell us from time to time about processes
1343 # it forks. We tell BackupPC about this (for status displays) and
1344 # keep track of the pids in case we cancel the backup
1349 @xferPid = grep(/./, @xferPid);
1350 return if ( !@xferPid && $tarPid < 0 );
1351 my @pids = @xferPid;
1352 push(@pids, $tarPid) if ( $tarPid > 0 );
1353 my $str = join(",", @pids);
1354 $XferLOG->write(\"Xfer PIDs are now $str\n") if ( defined($XferLOG) );
1355 print("xferPids $str\n");
1359 # Run an optional pre- or post-dump command
1365 return if ( !defined($Conf{$type}) );
1371 user => $Hosts->{$client}{user},
1372 moreUsers => $Hosts->{$client}{moreUsers},
1373 share => $ShareNames->[0],
1374 shares => $ShareNames,
1375 XferMethod => $Conf{XferMethod},
1376 sshPath => $Conf{SshPath},
1378 XferLOG => $XferLOG,
1380 xferOK => $stat{xferOK} || 0,
1381 hostError => $stat{hostError},
1384 my $cmd = $bpc->cmdVarSubstitute($Conf{$type}, $vars);
1385 $XferLOG->write(\"Executing $type: @$cmd\n");
1387 # Run the user's command, dumping the stdout/stderr into the
1388 # Xfer log file. Also supply the optional $vars and %Conf in
1389 # case the command is really perl code instead of a shell
1392 $bpc->cmdSystemOrEval($cmd,
1394 $XferLOG->write(\$_[0]);