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 ( $StatusHost{reason} ne "Reason_backup_done"
290 && time - $StatusHost{startTime} > 2 * 24 * 3600 );
291 NothingToDo($needLink);
294 if ( !$opts{i} && !$opts{f} && $Conf{BlackoutGoodCnt} >= 0
295 && $StatusHost{aliveCnt} >= $Conf{BlackoutGoodCnt} ) {
296 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
297 my($currHours) = $hour + $min / 60 + $sec / 3600;
301 # Handle backward compatibility with original separate scalar
304 if ( defined($Conf{BlackoutHourBegin}) ) {
305 push(@{$Conf{BlackoutPeriods}},
307 hourBegin => $Conf{BlackoutHourBegin},
308 hourEnd => $Conf{BlackoutHourEnd},
309 weekDays => $Conf{BlackoutWeekDays},
313 foreach my $p ( @{$Conf{BlackoutPeriods}} ) {
315 # Allow blackout to span midnight (specified by BlackoutHourBegin
316 # being greater than BlackoutHourEnd)
318 next if ( ref($p->{weekDays}) ne "ARRAY"
319 || !defined($p->{hourBegin})
320 || !defined($p->{hourEnd})
322 if ( $p->{hourBegin} > $p->{hourEnd} ) {
323 $blackout = $p->{hourBegin} <= $currHours
324 || $currHours <= $p->{hourEnd};
325 if ( $currHours <= $p->{hourEnd} ) {
327 # This is after midnight, so decrement the weekday for the
328 # weekday check (eg: Monday 11pm-1am means Monday 2300 to
329 # Tuesday 0100, not Monday 2300-2400 plus Monday 0000-0100).
332 $wday += 7 if ( $wday < 0 );
335 $blackout = $p->{hourBegin} <= $currHours
336 && $currHours <= $p->{hourEnd};
338 if ( $blackout && grep($_ == $wday, @{$p->{weekDays}}) ) {
339 # print(LOG $bpc->timeStamp, "skipping because of blackout"
340 # . " (alive $StatusHost{aliveCnt} times)\n");
341 print(STDERR "Skipping $client because of blackout\n")
343 NothingToDo($needLink);
348 if ( !$opts{i} && !$opts{f} && $StatusHost{backoffTime} > time ) {
349 printf(LOG "%sskipping because of user requested delay (%.1f hours left)",
350 $bpc->timeStamp, ($StatusHost{backoffTime} - time) / 3600);
351 NothingToDo($needLink);
355 # Now see if there are any old backups we should delete
357 BackupExpire($client);
360 # Read Backup information, and find times of the most recent full and
361 # incremental backups
363 @Backups = $bpc->BackupInfoRead($client);
364 for ( my $i = 0 ; $i < @Backups ; $i++ ) {
365 $needLink = 1 if ( $Backups[$i]{nFilesNew} eq ""
366 || -f "$Dir/NewFileList.$Backups[$i]{num}" );
367 $lastBkupNum = $Backups[$i]{num};
368 if ( $Backups[$i]{type} eq "full" ) {
369 if ( $lastFull < $Backups[$i]{startTime} ) {
370 $lastFull = $Backups[$i]{startTime};
371 $lastFullBkupNum = $Backups[$i]{num};
373 } elsif ( $Backups[$i]{type} eq "incr" ) {
374 $lastIncr = $Backups[$i]{startTime}
375 if ( $lastIncr < $Backups[$i]{startTime} );
376 } elsif ( $Backups[$i]{type} eq "partial" ) {
378 $partialNum = $Backups[$i]{num};
383 # Decide whether we do nothing, or a full or incremental backup.
387 || (!$opts{i} && (time - $lastFull > $Conf{FullPeriod} * 24*3600
388 && time - $lastIncr > $Conf{IncrPeriod} * 24*3600)) ) {
390 } elsif ( $opts{i} || (time - $lastIncr > $Conf{IncrPeriod} * 24*3600
391 && time - $lastFull > $Conf{IncrPeriod} * 24*3600) ) {
394 NothingToDo($needLink);
398 # Check if $host is alive
400 my $delay = $bpc->CheckHostAlive($hostIP);
402 print(LOG $bpc->timeStamp, "no ping response\n");
403 print("no ping response\n");
404 print("link $clientURI\n") if ( $needLink );
406 } elsif ( $delay > $Conf{PingMaxMsec} ) {
407 printf(LOG "%sping too slow: %.4gmsec\n", $bpc->timeStamp, $delay);
408 printf("ping too slow: %.4gmsec (threshold is %gmsec)\n",
409 $delay, $Conf{PingMaxMsec});
410 print("link $clientURI\n") if ( $needLink );
415 # Make sure it is really the machine we expect (only for fixed addresses,
416 # since we got the DHCP address above).
418 if ( !$opts{d} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
419 print(LOG $bpc->timeStamp, "dump failed: $errMsg\n");
420 print("dump failed: $errMsg\n");
422 } elsif ( $opts{d} ) {
423 print(LOG $bpc->timeStamp, "$host is dhcp $hostIP, user is $user\n");
427 # Get a clean directory $Dir/new
429 $bpc->RmTreeDefer("$TopDir/trash", "$Dir/new") if ( -d "$Dir/new" );
432 # Setup file extension for compression and open XferLOG output file
434 $Conf{CompressLevel} = 0 if ( !BackupPC::FileZIO->compOk );
435 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
436 my $XferLOG = BackupPC::FileZIO->open("$Dir/XferLOG$fileExt", 1,
437 $Conf{CompressLevel});
438 if ( !defined($XferLOG) ) {
439 print(LOG $bpc->timeStamp, "dump failed: unable to open/create"
440 . " $Dir/XferLOG$fileExt\n");
441 print("dump failed: unable to open/create $Dir/XferLOG$fileExt\n");
446 # Ignore the partial dump in the case of an incremental.
447 # A partial is a partial full.
449 if ( $type ne "full" ) {
455 # If this is a partial, copy the old XferLOG file
458 my($compress, $fileName);
459 if ( -f "$Dir/XferLOG.$partialNum.z" ) {
460 $fileName = "$Dir/XferLOG.$partialNum.z";
462 } elsif ( -f "$Dir/XferLOG.$partialNum" ) {
463 $fileName = "$Dir/XferLOG.$partialNum";
466 if ( my $oldLOG = BackupPC::FileZIO->open($fileName, 0, $compress) ) {
468 while ( $oldLOG->read(\$data, 65536) > 0 ) {
469 $XferLOG->write(\$data);
475 $XferLOG->writeTeeStderr(1) if ( $opts{v} );
476 unlink("$Dir/NewFileList") if ( -f "$Dir/NewFileList" );
478 my $startTime = time();
482 my $sizeExistComp = 0;
485 my($logMsg, %stat, $xfer, $ShareNames, $noFilesErr);
488 if ( $Conf{XferMethod} eq "tar" ) {
489 $ShareNames = $Conf{TarShareName};
490 } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
491 $ShareNames = $Conf{RsyncShareName};
493 $ShareNames = $Conf{SmbShareName};
496 $ShareNames = [ $ShareNames ] unless ref($ShareNames) eq "ARRAY";
499 # Run an optional pre-dump command
501 UserCommandRun("DumpPreUserCmd");
505 # Now backup each of the shares
507 for my $shareName ( @$ShareNames ) {
510 $stat{xferOK} = $stat{hostAbort} = undef;
511 $stat{hostError} = $stat{lastOutputLine} = undef;
512 if ( -d "$Dir/new/$shareName" ) {
513 print(LOG $bpc->timeStamp,
514 "unexpected repeated share name $shareName skipped\n");
518 if ( $Conf{XferMethod} eq "tar" ) {
520 # Use tar (eg: tar/ssh) as the transport program.
522 $xfer = BackupPC::Xfer::Tar->new($bpc);
523 } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
525 # Use rsync as the transport program.
527 if ( !defined($xfer = BackupPC::Xfer::Rsync->new($bpc)) ) {
528 my $errStr = BackupPC::Xfer::Rsync::errStr;
529 print(LOG $bpc->timeStamp, "dump failed: $errStr\n");
530 print("dump failed: $errStr\n");
531 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
536 # Default is to use smbclient (smb) as the transport program.
538 $xfer = BackupPC::Xfer::Smb->new($bpc);
541 my $useTar = $xfer->useTar;
545 # This xfer method outputs a tar format file, so we start a
546 # BackupPC_tarExtract to extract the data.
548 # Create a socketpair to connect the Xfer method to BackupPC_tarExtract
549 # WH is the write handle for writing, provided to the transport
550 # program, and RH is the other end of the socket for reading,
551 # provided to BackupPC_tarExtract.
553 if ( socketpair(RH, WH, AF_UNIX, SOCK_STREAM, PF_UNSPEC) ) {
554 shutdown(RH, 1); # no writing to this socket
555 shutdown(WH, 0); # no reading from this socket
556 setsockopt(RH, SOL_SOCKET, SO_RCVBUF, 8 * 65536);
557 setsockopt(WH, SOL_SOCKET, SO_SNDBUF, 8 * 65536);
560 # Default to pipe() if socketpair() doesn't work.
566 # fork a child for BackupPC_tarExtract. TAR is a file handle
567 # on which we (the parent) read the stdout & stderr from
568 # BackupPC_tarExtract.
570 if ( !defined($tarPid = open(TAR, "-|")) ) {
571 print(LOG $bpc->timeStamp, "can't fork to run tar\n");
572 print("can't fork to run tar\n");
580 # This is the tar child. Close the write end of the pipe,
581 # clone STDERR to STDOUT, clone STDIN from RH, and then
582 # exec BackupPC_tarExtract.
587 open(STDERR, ">&STDOUT");
591 exec("$BinDir/BackupPC_tarExtract", $client, $shareName,
592 $Conf{CompressLevel});
593 print(LOG $bpc->timeStamp,
594 "can't exec $BinDir/BackupPC_tarExtract\n");
597 } elsif ( !defined($newFilesFH) ) {
599 # We need to create the NewFileList output file
602 open(NEW_FILES, ">", "$TopDir/pc/$client/NewFileList")
603 || die("can't open $TopDir/pc/$client/NewFileList");
604 $newFilesFH = *NEW_FILES;
609 # Run the transport program
615 shareName => $shareName,
619 newFilesFH => $newFilesFH,
622 lastFull => $lastFull,
623 lastBkupNum => $lastBkupNum,
624 lastFullBkupNum => $lastFullBkupNum,
625 backups => \@Backups,
626 compress => $Conf{CompressLevel},
627 XferMethod => $Conf{XferMethod},
628 logLevel => $Conf{XferLogLevel},
629 pidHandler => \&pidHandler,
630 partialNum => $partialNum,
633 if ( !defined($logMsg = $xfer->start()) ) {
634 print(LOG $bpc->timeStamp, "xfer start failed: ", $xfer->errStr, "\n");
635 print("dump failed: ", $xfer->errStr, "\n");
636 print("link $clientURI\n") if ( $needLink );
638 # kill off the tar process, first nicely then forcefully
641 kill($bpc->sigName2num("INT"), $tarPid);
643 kill($bpc->sigName2num("KILL"), $tarPid);
646 kill($bpc->sigName2num("INT"), @xferPid);
648 kill($bpc->sigName2num("KILL"), @xferPid);
650 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
654 @xferPid = $xfer->xferPid;
658 # The parent must close both handles on the pipe since the children
659 # are using these handles now.
664 print(LOG $bpc->timeStamp, $logMsg, "\n");
665 print("started $type dump, share=$shareName\n");
667 pidHandler(@xferPid);
671 # Parse the output of the transfer program and BackupPC_tarExtract
672 # while they run. Since we might be reading from two or more children
675 my($FDread, $tarOut, $mesg);
676 vec($FDread, fileno(TAR), 1) = 1 if ( $useTar );
677 $xfer->setSelectMask(\$FDread);
681 last if ( $FDread =~ /^\0*$/ );
682 select(my $rout = $FDread, undef, $ein, undef);
684 if ( vec($rout, fileno(TAR), 1) ) {
685 if ( sysread(TAR, $mesg, 8192) <= 0 ) {
686 vec($FDread, fileno(TAR), 1) = 0;
692 while ( $tarOut =~ /(.*?)[\n\r]+(.*)/s ) {
696 $XferLOG->write(\"$_\n");
698 $XferLOG->write(\"tarExtract: $_\n");
700 if ( /^BackupPC_tarExtact aborting \((.*)\)/ ) {
701 $stat{hostError} = $1;
703 if ( /^Done: (\d+) errors, (\d+) filesExist, (\d+) sizeExist, (\d+) sizeExistComp, (\d+) filesTotal, (\d+) sizeTotal/ ) {
707 $sizeExistComp += $4;
713 last if ( !$xfer->readOutput(\$FDread, $rout) );
714 while ( my $str = $xfer->logMsgGet ) {
715 print(LOG $bpc->timeStamp, "xfer: $str\n");
717 if ( $xfer->getStats->{fileCnt} == 1 ) {
719 # Make sure it is still the machine we expect. We do this while
720 # the transfer is running to avoid a potential race condition if
721 # the ip address was reassigned by dhcp just before we started
724 if ( my $errMsg = CorrectHostCheck($hostIP, $host) ) {
725 $stat{hostError} = $errMsg if ( $stat{hostError} eq "" );
732 # otherwise the xfer module does everything for us
734 my @results = $xfer->run();
735 $tarErrs += $results[0];
736 $nFilesExist += $results[1];
737 $sizeExist += $results[2];
738 $sizeExistComp += $results[3];
739 $nFilesTotal += $results[4];
740 $sizeTotal += $results[5];
744 # Merge the xfer status (need to accumulate counts)
746 my $newStat = $xfer->getStats;
747 if ( $newStat->{fileCnt} == 0 ) {
748 $noFilesErr ||= "No files dumped for share $shareName";
750 foreach my $k ( (keys(%stat), keys(%$newStat)) ) {
751 next if ( !defined($newStat->{$k}) );
752 if ( $k =~ /Cnt$/ ) {
753 $stat{$k} += $newStat->{$k};
754 delete($newStat->{$k});
757 if ( !defined($stat{$k}) ) {
758 $stat{$k} = $newStat->{$k};
759 delete($newStat->{$k});
763 $stat{xferOK} = 0 if ( $stat{hostError} || $stat{hostAbort} );
764 if ( !$stat{xferOK} ) {
766 # kill off the tranfer program, first nicely then forcefully
769 kill($bpc->sigName2num("INT"), @xferPid);
771 kill($bpc->sigName2num("KILL"), @xferPid);
774 # kill off the tar process, first nicely then forcefully
777 kill($bpc->sigName2num("INT"), $tarPid);
779 kill($bpc->sigName2num("KILL"), $tarPid);
782 # don't do any more shares on this host
789 # If this is a full, and any share had zero files then consider the dump bad
791 if ( $type eq "full" && $stat{hostError} eq ""
792 && length($noFilesErr) && $Conf{BackupZeroFilesIsFatal} ) {
793 $stat{hostError} = $noFilesErr;
797 $stat{xferOK} = 0 if ( $Abort );
800 # Do one last check to make sure it is still the machine we expect.
802 if ( $stat{xferOK} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
803 $stat{hostError} = $errMsg;
807 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
808 close($newFilesFH) if ( defined($newFilesFH) );
810 my $endTime = time();
813 # If the dump failed, clean up
815 if ( !$stat{xferOK} ) {
816 $stat{hostError} = $stat{lastOutputLine} if ( $stat{hostError} eq "" );
817 if ( $stat{hostError} ) {
818 print(LOG $bpc->timeStamp,
819 "Got fatal error during xfer ($stat{hostError})\n");
820 $XferLOG->write(\"Got fatal error during xfer ($stat{hostError})\n");
824 # wait a short while and see if the system is still alive
827 if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
828 $stat{hostAbort} = 1;
830 if ( $stat{hostAbort} ) {
831 $stat{hostError} = "lost network connection during backup";
833 print(LOG $bpc->timeStamp, "Backup aborted ($stat{hostError})\n");
834 $XferLOG->write(\"Backup aborted ($stat{hostError})\n");
836 $XferLOG->write(\"Backup aborted by user signal\n");
840 # Close the log file and call BackupFailCleanup, which exits.
845 my $newNum = BackupSave();
847 my $otherCount = $stat{xferErrCnt} - $stat{xferBadFileCnt}
848 - $stat{xferBadShareCnt};
849 print(LOG $bpc->timeStamp,
850 "$type backup $newNum complete, $stat{fileCnt} files,"
851 . " $stat{byteCnt} bytes,"
852 . " $stat{xferErrCnt} xferErrs ($stat{xferBadFileCnt} bad files,"
853 . " $stat{xferBadShareCnt} bad shares, $otherCount other)\n");
855 BackupExpire($client);
857 print("$type backup complete\n");
859 ###########################################################################
861 ###########################################################################
867 print("nothing to do\n");
868 print("link $clientURI\n") if ( $needLink );
877 # The first time we receive a signal we try to gracefully
878 # abort the backup. This allows us to keep a partial dump
879 # with the in-progress file deleted and attribute caches
880 # flushed to disk etc.
882 if ( !length($SigName) ) {
884 if ( $sigName eq "INT" ) {
885 $reason = "aborted by user (signal=$sigName)";
887 $reason = "aborted by signal=$sigName";
891 # Parent logs a message
893 print(LOG $bpc->timeStamp,
894 "Aborting backup up after signal $sigName\n");
899 $xfer->abort($reason);
902 # Send ALRMs to BackupPC_tarExtract if we are using it
905 kill($bpc->sigName2num("ARLM"), $tarPid);
909 # Schedule a 20 second timer in case the clean
910 # abort doesn't complete
915 # Children ignore anything other than ALRM and INT
917 if ( $sigName ne "ALRM" && $sigName ne "INT" ) {
922 # The child also tells xfer to abort
924 $xfer->abort($reason);
927 # Schedule a 15 second timer in case the clean
928 # abort doesn't complete
938 # This is a second signal: time to clean up.
940 if ( $Pid != $$ && ($sigName eq "ALRM" || $sigName eq "INT") ) {
942 # Children quit quietly on ALRM or INT
948 # Ignore other signals in children
950 return if ( $Pid != $$ );
952 $SIG{$sigName} = 'IGNORE';
953 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
954 $XferLOG->write(\"exiting after signal $sigName\n");
956 kill($bpc->sigName2num("INT"), @xferPid);
958 kill($bpc->sigName2num("KILL"), @xferPid);
961 kill($bpc->sigName2num("INT"), $tarPid);
963 kill($bpc->sigName2num("KILL"), $tarPid);
965 if ( $sigName eq "INT" ) {
966 $stat{hostError} = "aborted by user (signal=$sigName)";
968 $stat{hostError} = "received signal=$sigName";
975 if ( -f _ && $File::Find::name !~ /\/fattrib$/ ) {
979 # No need to check entire tree
981 $File::Find::prune = 1 if ( $nFilesTotal );
985 sub BackupFailCleanup
987 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
991 # We keep this backup if it is a full and we actually backed
994 if ( $type eq "full" ) {
995 if ( $nFilesTotal == 0 && $xfer->getStats->{fileCnt} == 0 ) {
997 # Xfer didn't report any files, but check in the new
998 # directory just in case.
1000 find(\&CheckForNewFiles, "$Dir/new");
1001 $keepPartial = 1 if ( $nFilesTotal );
1004 # Xfer reported some files
1010 if ( !$keepPartial ) {
1012 # No point in saving this dump; get rid of eveything.
1015 unlink("$Dir/timeStamp.level0") if ( -f "$Dir/timeStamp.level0" );
1016 unlink("$Dir/SmbLOG.bad") if ( -f "$Dir/SmbLOG.bad" );
1017 unlink("$Dir/SmbLOG.bad$fileExt") if ( -f "$Dir/SmbLOG.bad$fileExt" );
1018 unlink("$Dir/XferLOG.bad") if ( -f "$Dir/XferLOG.bad" );
1019 unlink("$Dir/XferLOG.bad$fileExt") if ( -f "$Dir/XferLOG.bad$fileExt" );
1020 unlink("$Dir/NewFileList") if ( -f "$Dir/NewFileList" );
1021 rename("$Dir/XferLOG$fileExt", "$Dir/XferLOG.bad$fileExt");
1022 $bpc->RmTreeDefer("$TopDir/trash", "$Dir/new") if ( -d "$Dir/new" );
1023 print("dump failed: $stat{hostError}\n");
1025 print("link $clientURI\n") if ( $needLink );
1029 # Ok, now we should save this as a partial dump
1032 my $newNum = BackupSave();
1033 print("dump failed: $stat{hostError}\n");
1034 print("link $clientURI\n") if ( $needLink );
1035 print(LOG $bpc->timeStamp, "Saved partial dump $newNum\n");
1040 # Decide which old backups should be expired by moving them
1046 my($Dir) = "$TopDir/pc/$client";
1047 my(@Backups) = $bpc->BackupInfoRead($client);
1048 my($cntFull, $cntIncr, $firstFull, $firstIncr, $oldestIncr, $oldestFull);
1050 if ( $Conf{FullKeepCnt} <= 0 ) {
1051 print(LOG $bpc->timeStamp,
1052 "Invalid value for \$Conf{FullKeepCnt}=$Conf{FullKeepCnt}\n");
1054 "Invalid value for \$Conf{FullKeepCnt}=$Conf{FullKeepCnt}\n")
1059 $cntFull = $cntIncr = 0;
1060 $oldestIncr = $oldestFull = 0;
1061 for ( my $i = 0 ; $i < @Backups ; $i++ ) {
1062 if ( $Backups[$i]{type} eq "full" ) {
1063 $firstFull = $i if ( $cntFull == 0 );
1066 $firstIncr = $i if ( $cntIncr == 0 );
1070 $oldestIncr = (time - $Backups[$firstIncr]{startTime}) / (24 * 3600)
1071 if ( $cntIncr > 0 );
1072 $oldestFull = (time - $Backups[$firstFull]{startTime}) / (24 * 3600)
1073 if ( $cntFull > 0 );
1074 if ( $cntIncr > $Conf{IncrKeepCnt}
1075 || ($cntIncr > $Conf{IncrKeepCntMin}
1076 && $oldestIncr > $Conf{IncrAgeMax})
1077 && (@Backups <= $firstIncr + 1
1078 || $Backups[$firstIncr]{noFill}
1079 || !$Backups[$firstIncr + 1]{noFill}) ) {
1081 # Only delete an incr backup if the Conf settings are satisfied.
1082 # We also must make sure that either this backup is the most
1083 # recent one, or it is not filled, or the next backup is filled.
1084 # (We can't deleted a filled incr if the next backup is not
1087 print(LOG $bpc->timeStamp,
1088 "removing incr backup $Backups[$firstIncr]{num}\n");
1089 BackupRemove($client, \@Backups, $firstIncr);
1094 # Delete any old full backups, according to $Conf{FullKeepCntMin}
1095 # and $Conf{FullAgeMax}.
1097 if ( $cntFull > $Conf{FullKeepCntMin}
1098 && $oldestFull > $Conf{FullAgeMax}
1099 && (@Backups <= $firstFull + 1
1100 || !$Backups[$firstFull + 1]{noFill}) ) {
1102 # Only delete a full backup if the Conf settings are satisfied.
1103 # We also must make sure that either this backup is the most
1104 # recent one, or the next backup is filled.
1105 # (We can't deleted a full backup if the next backup is not
1108 print(LOG $bpc->timeStamp,
1109 "removing old full backup $Backups[$firstFull]{num}\n");
1110 BackupRemove($client, \@Backups, $firstFull);
1115 # Do new-style full backup expiry, which includes the the case
1116 # where $Conf{FullKeepCnt} is an array.
1118 last if ( !BackupFullExpire($client, \@Backups) );
1120 $bpc->BackupInfoWrite($client, @Backups);
1124 # Handle full backup expiry, using exponential periods.
1126 sub BackupFullExpire
1128 my($client, $Backups) = @_;
1130 my $fullPeriod = $Conf{FullPeriod};
1131 my $origFullPeriod = $fullPeriod;
1132 my $fullKeepCnt = $Conf{FullKeepCnt};
1133 my $fullKeepIdx = 0;
1134 my(@delete, @fullList);
1137 # Don't delete anything if $Conf{FullPeriod} or $Conf{FullKeepCnt} are
1138 # not defined - possibly a corrupted config.pl file.
1140 return if ( !defined($Conf{FullPeriod}) || !defined($Conf{FullKeepCnt}) );
1143 # If regular backups are still disabled with $Conf{FullPeriod} < 0,
1144 # we still expire backups based on a typical FullPeriod value - weekly.
1146 $fullPeriod = 7 if ( $fullPeriod <= 0 );
1148 $fullKeepCnt = [$fullKeepCnt] if ( ref($fullKeepCnt) ne "ARRAY" );
1150 for ( my $i = 0 ; $i < @$Backups ; $i++ ) {
1151 next if ( $Backups->[$i]{type} ne "full" );
1152 push(@fullList, $i);
1154 for ( my $k = @fullList - 1 ; $k >= 0 ; $k-- ) {
1155 my $i = $fullList[$k];
1156 my $prevFull = $fullList[$k-1] if ( $k > 0 );
1158 # Don't delete any full that is followed by an unfilled backup,
1159 # since it is needed for restore.
1161 my $noDelete = $i + 1 < @$Backups ? $Backups->[$i+1]{noFill} : 0;
1164 ($fullKeepIdx >= @$fullKeepCnt
1167 && $Backups->[$i]{startTime} - $Backups->[$prevFull]{startTime}
1168 < ($fullPeriod - $origFullPeriod / 2) * 24 * 3600
1172 # Delete the full backup
1174 #printf("Deleting backup $i ($prevFull)\n");
1178 while ( $fullKeepIdx < @$fullKeepCnt
1179 && $fullCnt >= $fullKeepCnt->[$fullKeepIdx] ) {
1182 $fullPeriod = 2 * $fullPeriod;
1187 # Now actually delete the backups
1189 for ( my $i = @delete - 1 ; $i >= 0 ; $i-- ) {
1190 print(LOG $bpc->timeStamp,
1191 "removing full backup $Backups->[$delete[$i]]{num}\n");
1192 BackupRemove($client, $Backups, $delete[$i]);
1198 # Removes any partial backups
1200 sub BackupPartialRemove
1202 my($client, $Backups) = @_;
1204 for ( my $i = @$Backups - 1 ; $i >= 0 ; $i-- ) {
1205 next if ( $Backups->[$i]{type} ne "partial" );
1206 BackupRemove($client, $Backups, $i);
1212 my @Backups = $bpc->BackupInfoRead($client);
1216 # Since we got a good backup we should remove any partial dumps
1217 # (the new backup might also be a partial, but that's ok).
1219 BackupPartialRemove($client, \@Backups);
1222 # Number the new backup
1224 for ( my $i = 0 ; $i < @Backups ; $i++ ) {
1225 $num = $Backups[$i]{num} if ( $num < $Backups[$i]{num} );
1228 $bpc->RmTreeDefer("$TopDir/trash", "$Dir/$num") if ( -d "$Dir/$num" );
1229 if ( !rename("$Dir/new", "$Dir/$num") ) {
1230 print(LOG $bpc->timeStamp, "Rename $Dir/new -> $Dir/$num failed\n");
1233 $needLink = 1 if ( -f "$Dir/NewFileList" );
1236 # Add the new backup information to the backup file
1239 $Backups[$i]{num} = $num;
1240 $Backups[$i]{type} = $type;
1241 $Backups[$i]{startTime} = $startTime;
1242 $Backups[$i]{endTime} = $endTime;
1243 $Backups[$i]{size} = $sizeTotal;
1244 $Backups[$i]{nFiles} = $nFilesTotal;
1245 $Backups[$i]{xferErrs} = $stat{xferErrCnt} || 0;
1246 $Backups[$i]{xferBadFile} = $stat{xferBadFileCnt} || 0;
1247 $Backups[$i]{xferBadShare} = $stat{xferBadShareCnt} || 0;
1248 $Backups[$i]{nFilesExist} = $nFilesExist;
1249 $Backups[$i]{sizeExist} = $sizeExist;
1250 $Backups[$i]{sizeExistComp} = $sizeExistComp;
1251 $Backups[$i]{tarErrs} = $tarErrs;
1252 $Backups[$i]{compress} = $Conf{CompressLevel};
1253 $Backups[$i]{noFill} = $type eq "incr" ? 1 : 0;
1254 $Backups[$i]{level} = $type eq "incr" ? 1 : 0;
1255 $Backups[$i]{mangle} = 1; # name mangling always on for v1.04+
1256 $bpc->BackupInfoWrite($client, @Backups);
1258 unlink("$Dir/timeStamp.level0") if ( -f "$Dir/timeStamp.level0" );
1259 foreach my $ext ( qw(bad bad.z) ) {
1260 next if ( !-f "$Dir/XferLOG.$ext" );
1261 unlink("$Dir/XferLOG.$ext.old") if ( -f "$Dir/XferLOG.$ext" );
1262 rename("$Dir/XferLOG.$ext", "$Dir/XferLOG.$ext.old");
1266 # Now remove the bad files, replacing them if possible with links to
1269 foreach my $f ( $xfer->getBadFiles ) {
1271 my $shareM = $bpc->fileNameEltMangle($f->{share});
1272 my $fileM = $bpc->fileNameMangle($f->{file});
1273 unlink("$Dir/$num/$shareM/$fileM");
1274 for ( $j = $i - 1 ; $j >= 0 ; $j-- ) {
1276 if ( $Backups[$j]{mangle} ) {
1277 $file = "$shareM/$fileM";
1279 $file = "$f->{share}/$f->{file}";
1281 next if ( !-f "$Dir/$Backups[$j]{num}/$file" );
1282 if ( !link("$Dir/$Backups[$j]{num}/$file",
1283 "$Dir/$num/$shareM/$fileM") ) {
1284 my $str = \"Unable to link $num/$f->{share}/$f->{file} to"
1285 . " $Backups[$j]{num}/$f->{share}/$f->{file}\n";
1286 $XferLOG->write(\$str);
1288 my $str = "Bad file $num/$f->{share}/$f->{file} replaced"
1290 . " $Backups[$j]{num}/$f->{share}/$f->{file}\n";
1291 $XferLOG->write(\$str);
1296 my $str = "Removed bad file $num/$f->{share}/$f->{file}"
1297 . " (no older copy to link to)\n";
1298 $XferLOG->write(\$str);
1302 rename("$Dir/XferLOG$fileExt", "$Dir/XferLOG.$num$fileExt");
1303 rename("$Dir/NewFileList", "$Dir/NewFileList.$num");
1309 # Removes a specific backup
1313 my($client, $Backups, $idx) = @_;
1314 my($Dir) = "$TopDir/pc/$client";
1316 $bpc->RmTreeDefer("$TopDir/trash",
1317 "$Dir/$Backups->[$idx]{num}");
1318 unlink("$Dir/SmbLOG.$Backups->[$idx]{num}")
1319 if ( -f "$Dir/SmbLOG.$Backups->[$idx]{num}" );
1320 unlink("$Dir/SmbLOG.$Backups->[$idx]{num}.z")
1321 if ( -f "$Dir/SmbLOG.$Backups->[$idx]{num}.z" );
1322 unlink("$Dir/XferLOG.$Backups->[$idx]{num}")
1323 if ( -f "$Dir/XferLOG.$Backups->[$idx]{num}" );
1324 unlink("$Dir/XferLOG.$Backups->[$idx]{num}.z")
1325 if ( -f "$Dir/XferLOG.$Backups->[$idx]{num}.z" );
1326 splice(@{$Backups}, $idx, 1);
1329 sub CorrectHostCheck
1331 my($hostIP, $host) = @_;
1332 return if ( $hostIP eq $host && !$Conf{FixedIPNetBiosNameCheck}
1333 || $Conf{NmbLookupCmd} eq "" );
1334 my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($hostIP);
1335 return "host $host has mismatching netbios name $netBiosHost"
1336 if ( $netBiosHost ne $host );
1341 # The Xfer method might tell us from time to time about processes
1342 # it forks. We tell BackupPC about this (for status displays) and
1343 # keep track of the pids in case we cancel the backup
1348 @xferPid = grep(/./, @xferPid);
1349 return if ( !@xferPid && $tarPid < 0 );
1350 my @pids = @xferPid;
1351 push(@pids, $tarPid) if ( $tarPid > 0 );
1352 my $str = join(",", @pids);
1353 $XferLOG->write(\"Xfer PIDs are now $str\n") if ( defined($XferLOG) );
1354 print("xferPids $str\n");
1358 # Run an optional pre- or post-dump command
1364 return if ( !defined($Conf{$type}) );
1370 user => $Hosts->{$client}{user},
1371 moreUsers => $Hosts->{$client}{moreUsers},
1372 share => $ShareNames->[0],
1373 shares => $ShareNames,
1374 XferMethod => $Conf{XferMethod},
1375 sshPath => $Conf{SshPath},
1377 XferLOG => $XferLOG,
1379 xferOK => $stat{xferOK} || 0,
1380 hostError => $stat{hostError},
1383 my $cmd = $bpc->cmdVarSubstitute($Conf{$type}, $vars);
1384 $XferLOG->write(\"Executing $type: @$cmd\n");
1386 # Run the user's command, dumping the stdout/stderr into the
1387 # Xfer log file. Also supply the optional $vars and %Conf in
1388 # case the command is really perl code instead of a shell
1391 $bpc->cmdSystemOrEval($cmd,
1393 $XferLOG->write(\$_[0]);