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_CVS, released 8 Feb 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;
91 ###########################################################################
93 ###########################################################################
95 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
96 my $TopDir = $bpc->TopDir();
97 my $BinDir = $bpc->BinDir();
98 my %Conf = $bpc->Conf();
105 if ( !getopts("defiv", \%opts) || @ARGV != 1 ) {
106 print("usage: $0 [-d] [-e] [-f] [-i] [-v] <client>\n");
109 if ( $ARGV[0] !~ /^([\w\.\s-]+)$/ ) {
110 print("$0: bad client name '$ARGV[0]'\n");
113 my $client = $1; # BackupPC's client name (might not be real host name)
114 my $hostIP; # this is the IP address
115 my $host; # this is the real host name
117 my($clientURI, $user);
119 $bpc->verbose(1) if ( $opts{v} );
123 # The client name $client is simply a DHCP address. We need to check
124 # if there is any machine at this address, and if so, get the actual
125 # host name via NetBios using nmblookup.
128 if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
129 print(STDERR "Exiting because CheckHostAlive($hostIP) failed\n")
133 if ( $Conf{NmbLookupCmd} eq "" ) {
134 print(STDERR "Exiting because \$Conf{NmbLookupCmd} is empty\n")
138 ($client, $user) = $bpc->NetBiosInfoGet($hostIP);
139 if ( $client !~ /^([\w\.\s-]+)$/ ) {
140 print(STDERR "Exiting because NetBiosInfoGet($hostIP) returned"
141 . " '$client', an invalid host name\n") if ( $opts{v} );
144 $Hosts = $bpc->HostInfoRead($client);
147 $Hosts = $bpc->HostInfoRead($client);
149 if ( !defined($Hosts->{$client}) ) {
150 print(STDERR "Exiting because host $client does not exist in the"
151 . " hosts file\n") if ( $opts{v} );
155 my $Dir = "$TopDir/pc/$client";
160 # Re-read config file, so we can include the PC-specific config
162 $clientURI = $bpc->uriEsc($client);
163 if ( defined(my $error = $bpc->ConfigRead($client)) ) {
164 print("dump failed: Can't read PC's config file: $error\n");
167 %Conf = $bpc->Conf();
170 # Catch various signals
172 $SIG{INT} = \&catch_signal;
173 $SIG{ALRM} = \&catch_signal;
174 $SIG{TERM} = \&catch_signal;
175 $SIG{PIPE} = \&catch_signal;
176 $SIG{STOP} = \&catch_signal;
177 $SIG{TSTP} = \&catch_signal;
178 $SIG{TTIN} = \&catch_signal;
182 # Make sure we eventually timeout if there is no activity from
183 # the data transport program.
185 alarm($Conf{ClientTimeout});
187 mkpath($Dir, 0, 0777) if ( !-d $Dir );
188 if ( !-f "$Dir/LOCK" ) {
189 open(LOCK, ">", "$Dir/LOCK") && close(LOCK);
191 open(LOG, ">>", "$Dir/LOG");
192 select(LOG); $| = 1; select(STDOUT);
195 # For the -e option we just expire backups and quit
198 BackupExpire($client);
203 # For archive hosts we don't bother any further
205 if ($Conf{XferMethod} eq "archive" ) {
211 # In the non-DHCP case, make sure the host can be looked up
212 # via NS, or otherwise find the IP address via NetBios.
214 if ( $Conf{ClientNameAlias} ne "" ) {
215 $host = $Conf{ClientNameAlias};
219 if ( !defined(gethostbyname($host)) ) {
221 # Ok, NS doesn't know about it. Maybe it is a NetBios name
224 print(STDERR "Name server doesn't know about $host; trying NetBios\n")
226 if ( !defined($hostIP = $bpc->NetBiosHostIPFind($host)) ) {
227 print(LOG $bpc->timeStamp, "Can't find host $host via netbios\n");
228 print("host not found\n");
236 ###########################################################################
237 # Figure out what to do and do it
238 ###########################################################################
241 # See if we should skip this host during a certain range
244 my $err = $bpc->ServerConnect($Conf{ServerHost}, $Conf{ServerPort});
246 print("Can't connect to server ($err)\n");
247 print(LOG $bpc->timeStamp, "Can't connect to server ($err)\n");
250 my $reply = $bpc->ServerMesg("status host($clientURI)");
251 $reply = $1 if ( $reply =~ /(.*)/s );
254 $bpc->ServerDisconnect();
257 # For DHCP tell BackupPC which host this is
260 if ( $StatusHost{activeJob} ) {
261 # oops, something is already running for this host
262 print(STDERR "Exiting because backup is already running for $client\n")
266 print("DHCP $hostIP $clientURI\n");
269 my($needLink, @Backups, $type, $lastBkupNum, $lastFullBkupNum);
275 if ( $Conf{FullPeriod} == -1 && !$opts{f} && !$opts{i}
276 || $Conf{FullPeriod} == -2 ) {
277 NothingToDo($needLink);
280 if ( !$opts{i} && !$opts{f} && $Conf{BlackoutGoodCnt} >= 0
281 && $StatusHost{aliveCnt} >= $Conf{BlackoutGoodCnt} ) {
282 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
283 my($currHours) = $hour + $min / 60 + $sec / 3600;
286 # Allow blackout to span midnight (specified by BlackoutHourBegin
287 # being greater than BlackoutHourEnd)
289 if ( $Conf{BlackoutHourBegin} > $Conf{BlackoutHourEnd} ) {
290 $blackout = $Conf{BlackoutHourBegin} <= $currHours
291 || $currHours <= $Conf{BlackoutHourEnd};
292 if ( $currHours <= $Conf{BlackoutHourEnd} ) {
294 # This is after midnight, so decrement the weekday for the
295 # weekday check (eg: Monday 11pm-1am means Monday 2300 to
296 # Tuesday 0100, not Monday 2300-2400 plus Monday 0000-0100).
299 $wday += 7 if ( $wday < 0 );
302 $blackout = $Conf{BlackoutHourBegin} <= $currHours
303 && $currHours <= $Conf{BlackoutHourEnd};
305 if ( $blackout && grep($_ == $wday, @{$Conf{BlackoutWeekDays}}) ) {
306 # print(LOG $bpc->timeStamp, "skipping because of blackout"
307 # . " (alive $StatusHost{aliveCnt} times)\n");
308 print(STDERR "Skipping $client because of blackout\n")
310 NothingToDo($needLink);
314 if ( !$opts{i} && !$opts{f} && $StatusHost{backoffTime} > time ) {
315 printf(LOG "%sskipping because of user requested delay (%.1f hours left)",
316 $bpc->timeStamp, ($StatusHost{backoffTime} - time) / 3600);
317 NothingToDo($needLink);
321 # Now see if there are any old backups we should delete
323 BackupExpire($client);
326 # Read Backup information, and find times of the most recent full and
327 # incremental backups
329 @Backups = $bpc->BackupInfoRead($client);
330 for ( my $i = 0 ; $i < @Backups ; $i++ ) {
331 $needLink = 1 if ( $Backups[$i]{nFilesNew} eq ""
332 || -f "$Dir/NewFileList.$Backups[$i]{num}" );
333 $lastBkupNum = $Backups[$i]{num};
334 if ( $Backups[$i]{type} eq "full" ) {
335 if ( $lastFull < $Backups[$i]{startTime} ) {
336 $lastFull = $Backups[$i]{startTime};
337 $lastFullBkupNum = $Backups[$i]{num};
339 } elsif ( $Backups[$i]{type} eq "incr" ) {
340 $lastIncr = $Backups[$i]{startTime}
341 if ( $lastIncr < $Backups[$i]{startTime} );
342 } elsif ( $Backups[$i]{type} eq "partial" ) {
344 $partialNum = $Backups[$i]{num};
349 # Decide whether we do nothing, or a full or incremental backup.
353 || (!$opts{i} && (time - $lastFull > $Conf{FullPeriod} * 24*3600
354 && time - $lastIncr > $Conf{IncrPeriod} * 24*3600)) ) {
356 } elsif ( $opts{i} || (time - $lastIncr > $Conf{IncrPeriod} * 24*3600
357 && time - $lastFull > $Conf{IncrPeriod} * 24*3600) ) {
360 NothingToDo($needLink);
364 # Check if $host is alive
366 my $delay = $bpc->CheckHostAlive($hostIP);
368 print(LOG $bpc->timeStamp, "no ping response\n");
369 print("no ping response\n");
370 print("link $clientURI\n") if ( $needLink );
372 } elsif ( $delay > $Conf{PingMaxMsec} ) {
373 printf(LOG "%sping too slow: %.4gmsec\n", $bpc->timeStamp, $delay);
374 printf("ping too slow: %.4gmsec (threshold is %gmsec)\n",
375 $delay, $Conf{PingMaxMsec});
376 print("link $clientURI\n") if ( $needLink );
381 # Make sure it is really the machine we expect (only for fixed addresses,
382 # since we got the DHCP address above).
384 if ( !$opts{d} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
385 print(LOG $bpc->timeStamp, "dump failed: $errMsg\n");
386 print("dump failed: $errMsg\n");
388 } elsif ( $opts{d} ) {
389 print(LOG $bpc->timeStamp, "$host is dhcp $hostIP, user is $user\n");
393 # Get a clean directory $Dir/new
395 $bpc->RmTreeDefer("$TopDir/trash", "$Dir/new") if ( -d "$Dir/new" );
398 # Setup file extension for compression and open XferLOG output file
400 $Conf{CompressLevel} = 0 if ( !BackupPC::FileZIO->compOk );
401 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
402 my $XferLOG = BackupPC::FileZIO->open("$Dir/XferLOG$fileExt", 1,
403 $Conf{CompressLevel});
404 if ( !defined($XferLOG) ) {
405 print(LOG $bpc->timeStamp, "dump failed: unable to open/create"
406 . " $Dir/XferLOG$fileExt\n");
407 print("dump failed: unable to open/create $Dir/XferLOG$fileExt\n");
410 $XferLOG->writeTeeStderr(1) if ( $opts{v} );
411 unlink("$Dir/NewFileList");
412 my $startTime = time();
417 my $sizeExistComp = 0;
420 my($logMsg, %stat, $xfer, $ShareNames, $noFilesErr);
423 if ( $Conf{XferMethod} eq "tar" ) {
424 $ShareNames = $Conf{TarShareName};
425 } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
426 $ShareNames = $Conf{RsyncShareName};
428 $ShareNames = $Conf{SmbShareName};
431 $ShareNames = [ $ShareNames ] unless ref($ShareNames) eq "ARRAY";
434 # Run an optional pre-dump command
436 UserCommandRun("DumpPreUserCmd");
440 # Now backup each of the shares
442 for my $shareName ( @$ShareNames ) {
445 $stat{xferOK} = $stat{hostAbort} = undef;
446 $stat{hostError} = $stat{lastOutputLine} = undef;
447 if ( -d "$Dir/new/$shareName" ) {
448 print(LOG $bpc->timeStamp,
449 "unexpected repeated share name $shareName skipped\n");
453 if ( $Conf{XferMethod} eq "tar" ) {
455 # Use tar (eg: tar/ssh) as the transport program.
457 $xfer = BackupPC::Xfer::Tar->new($bpc);
458 } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
460 # Use rsync as the transport program.
462 if ( !defined($xfer = BackupPC::Xfer::Rsync->new($bpc)) ) {
463 my $errStr = BackupPC::Xfer::Rsync::errStr;
464 print(LOG $bpc->timeStamp, "dump failed: $errStr\n");
465 print("dump failed: $errStr\n");
466 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
471 # Default is to use smbclient (smb) as the transport program.
473 $xfer = BackupPC::Xfer::Smb->new($bpc);
476 my $useTar = $xfer->useTar;
480 # This xfer method outputs a tar format file, so we start a
481 # BackupPC_tarExtract to extract the data.
483 # Create a socketpair to connect the Xfer method to BackupPC_tarExtract
484 # WH is the write handle for writing, provided to the transport
485 # program, and RH is the other end of the socket for reading,
486 # provided to BackupPC_tarExtract.
488 if ( socketpair(RH, WH, AF_UNIX, SOCK_STREAM, PF_UNSPEC) ) {
489 shutdown(RH, 1); # no writing to this socket
490 shutdown(WH, 0); # no reading from this socket
491 setsockopt(RH, SOL_SOCKET, SO_RCVBUF, 8 * 65536);
492 setsockopt(WH, SOL_SOCKET, SO_SNDBUF, 8 * 65536);
495 # Default to pipe() if socketpair() doesn't work.
501 # fork a child for BackupPC_tarExtract. TAR is a file handle
502 # on which we (the parent) read the stdout & stderr from
503 # BackupPC_tarExtract.
505 if ( !defined($tarPid = open(TAR, "-|")) ) {
506 print(LOG $bpc->timeStamp, "can't fork to run tar\n");
507 print("can't fork to run tar\n");
515 # This is the tar child. Close the write end of the pipe,
516 # clone STDERR to STDOUT, clone STDIN from RH, and then
517 # exec BackupPC_tarExtract.
522 open(STDERR, ">&STDOUT");
526 exec("$BinDir/BackupPC_tarExtract", $client, $shareName,
527 $Conf{CompressLevel});
528 print(LOG $bpc->timeStamp,
529 "can't exec $BinDir/BackupPC_tarExtract\n");
532 } elsif ( !defined($newFilesFH) ) {
534 # We need to create the NewFileList output file
537 open(NEW_FILES, ">", "$TopDir/pc/$client/NewFileList")
538 || die("can't open $TopDir/pc/$client/NewFileList");
539 $newFilesFH = *NEW_FILES;
544 # Run the transport program
550 shareName => $shareName,
554 newFilesFH => $newFilesFH,
557 lastFull => $lastFull,
558 lastBkupNum => $lastBkupNum,
559 lastFullBkupNum => $lastFullBkupNum,
560 backups => \@Backups,
561 compress => $Conf{CompressLevel},
562 XferMethod => $Conf{XferMethod},
563 pidHandler => \&pidHandler,
564 partialNum => $partialNum,
567 if ( !defined($logMsg = $xfer->start()) ) {
568 print(LOG $bpc->timeStamp, "xfer start failed: ", $xfer->errStr, "\n");
569 print("dump failed: ", $xfer->errStr, "\n");
570 print("link $clientURI\n") if ( $needLink );
572 # kill off the tar process, first nicely then forcefully
584 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
588 @xferPid = $xfer->xferPid;
592 # The parent must close both handles on the pipe since the children
593 # are using these handles now.
598 print(LOG $bpc->timeStamp, $logMsg, "\n");
599 print("started $type dump, share=$shareName\n");
601 pidHandler(@xferPid);
605 # Parse the output of the transfer program and BackupPC_tarExtract
606 # while they run. Since we might be reading from two or more children
609 my($FDread, $tarOut, $mesg);
610 vec($FDread, fileno(TAR), 1) = 1 if ( $useTar );
611 $xfer->setSelectMask(\$FDread);
615 last if ( $FDread =~ /^\0*$/ );
616 select(my $rout = $FDread, undef, $ein, undef);
618 if ( vec($rout, fileno(TAR), 1) ) {
619 if ( sysread(TAR, $mesg, 8192) <= 0 ) {
620 vec($FDread, fileno(TAR), 1) = 0;
626 while ( $tarOut =~ /(.*?)[\n\r]+(.*)/s ) {
629 $XferLOG->write(\"tarExtract: $_\n");
630 if ( /^Done: (\d+) errors, (\d+) filesExist, (\d+) sizeExist, (\d+) sizeExistComp, (\d+) filesTotal, (\d+) sizeTotal/ ) {
634 $sizeExistComp += $4;
640 last if ( !$xfer->readOutput(\$FDread, $rout) );
641 while ( my $str = $xfer->logMsgGet ) {
642 print(LOG $bpc->timeStamp, "xfer: $str\n");
644 if ( $xfer->getStats->{fileCnt} == 1 ) {
646 # Make sure it is still the machine we expect. We do this while
647 # the transfer is running to avoid a potential race condition if
648 # the ip address was reassigned by dhcp just before we started
651 if ( my $errMsg = CorrectHostCheck($hostIP, $host) ) {
652 $stat{hostError} = $errMsg if ( $stat{hostError} eq "" );
659 # otherwise the xfer module does everything for us
661 my @results = $xfer->run();
662 $tarErrs += $results[0];
663 $nFilesExist += $results[1];
664 $sizeExist += $results[2];
665 $sizeExistComp += $results[3];
666 $nFilesTotal += $results[4];
667 $sizeTotal += $results[5];
671 # Merge the xfer status (need to accumulate counts)
673 my $newStat = $xfer->getStats;
674 if ( $newStat->{fileCnt} == 0 ) {
675 $noFilesErr ||= "No files dumped for share $shareName";
677 foreach my $k ( (keys(%stat), keys(%$newStat)) ) {
678 next if ( !defined($newStat->{$k}) );
679 if ( $k =~ /Cnt$/ ) {
680 $stat{$k} += $newStat->{$k};
681 delete($newStat->{$k});
684 if ( !defined($stat{$k}) ) {
685 $stat{$k} = $newStat->{$k};
686 delete($newStat->{$k});
690 $stat{xferOK} = 0 if ( $stat{hostError} || $stat{hostAbort} );
691 if ( !$stat{xferOK} ) {
693 # kill off the tranfer program, first nicely then forcefully
701 # kill off the tar process, first nicely then forcefully
709 # don't do any more shares on this host
716 # If this is a full, and any share had zero files then consider the dump bad
718 if ( $type eq "full" && $stat{hostError} eq ""
719 && length($noFilesErr) && $Conf{BackupZeroFilesIsFatal} ) {
720 $stat{hostError} = $noFilesErr;
725 # Do one last check to make sure it is still the machine we expect.
727 if ( $stat{xferOK} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
728 $stat{hostError} = $errMsg;
732 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
734 close($newFilesFH) if ( defined($newFilesFH) );
736 my $endTime = time();
739 # If the dump failed, clean up
741 if ( !$stat{xferOK} ) {
743 # wait a short while and see if the system is still alive
745 $stat{hostError} = $stat{lastOutputLine} if ( $stat{hostError} eq "" );
746 if ( $stat{hostError} ) {
747 print(LOG $bpc->timeStamp,
748 "Got fatal error during xfer ($stat{hostError})\n");
751 if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
752 $stat{hostAbort} = 1;
754 if ( $stat{hostAbort} ) {
755 $stat{hostError} = "lost network connection during backup";
757 print(LOG $bpc->timeStamp, "Dump aborted ($stat{hostError})\n");
765 my $newNum = BackupSave();
767 my $otherCount = $stat{xferErrCnt} - $stat{xferBadFileCnt}
768 - $stat{xferBadShareCnt};
769 print(LOG $bpc->timeStamp,
770 "$type backup $newNum complete, $stat{fileCnt} files,"
771 . " $stat{byteCnt} bytes,"
772 . " $stat{xferErrCnt} xferErrs ($stat{xferBadFileCnt} bad files,"
773 . " $stat{xferBadShareCnt} bad shares, $otherCount other)\n");
775 BackupExpire($client);
777 print("$type backup complete\n");
779 ###########################################################################
781 ###########################################################################
787 print("nothing to do\n");
788 print("link $clientURI\n") if ( $needLink );
797 # Children quit quietly on ALRM
799 exit(1) if ( $Pid != $$ && $signame eq "ALRM" );
802 # Ignore other signals in children
804 return if ( $Pid != $$ );
806 print(LOG $bpc->timeStamp, "cleaning up after signal $signame\n");
807 $SIG{$signame} = 'IGNORE';
808 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
809 $XferLOG->write(\"exiting after signal $signame\n");
821 if ( $signame eq "INT" ) {
822 $stat{hostError} = "aborted by user (signal=$signame)";
824 $stat{hostError} = "received signal=$signame";
829 sub BackupFailCleanup
831 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
834 || ($nFilesTotal == 0 && $xfer->getStats->{fileCnt} == 0) ) {
836 # No point in saving this dump; get rid of eveything.
838 unlink("$Dir/timeStamp.level0");
839 unlink("$Dir/SmbLOG.bad");
840 unlink("$Dir/SmbLOG.bad$fileExt");
841 unlink("$Dir/XferLOG.bad");
842 unlink("$Dir/XferLOG.bad$fileExt");
843 unlink("$Dir/NewFileList");
844 rename("$Dir/XferLOG$fileExt", "$Dir/XferLOG.bad$fileExt");
845 $bpc->RmTreeDefer("$TopDir/trash", "$Dir/new") if ( -d "$Dir/new" );
846 print("dump failed: $stat{hostError}\n");
847 print("link $clientURI\n") if ( $needLink );
851 # Ok, now we should save this as a partial dump
854 my $newNum = BackupSave();
855 print("dump failed: $stat{hostError}\n");
856 print("link $clientURI\n") if ( $needLink );
857 print(LOG $bpc->timeStamp, "Saved partial dump $newNum\n");
862 # Decide which old backups should be expired by moving them
868 my($Dir) = "$TopDir/pc/$client";
869 my(@Backups) = $bpc->BackupInfoRead($client);
870 my($cntFull, $cntIncr, $firstFull, $firstIncr, $oldestIncr, $oldestFull);
873 $cntFull = $cntIncr = 0;
874 $oldestIncr = $oldestFull = 0;
875 for ( my $i = 0 ; $i < @Backups ; $i++ ) {
876 if ( $Backups[$i]{type} eq "full" ) {
877 $firstFull = $i if ( $cntFull == 0 );
880 $firstIncr = $i if ( $cntIncr == 0 );
884 $oldestIncr = (time - $Backups[$firstIncr]{startTime}) / (24 * 3600)
886 $oldestFull = (time - $Backups[$firstFull]{startTime}) / (24 * 3600)
888 if ( $cntIncr > $Conf{IncrKeepCnt}
889 || ($cntIncr > $Conf{IncrKeepCntMin}
890 && $oldestIncr > $Conf{IncrAgeMax})
891 && (@Backups <= $firstIncr + 1
892 || $Backups[$firstIncr]{noFill}
893 || !$Backups[$firstIncr + 1]{noFill}) ) {
895 # Only delete an incr backup if the Conf settings are satisfied.
896 # We also must make sure that either this backup is the most
897 # recent one, or it is not filled, or the next backup is filled.
898 # (We can't deleted a filled incr if the next backup is not
901 print(LOG $bpc->timeStamp,
902 "removing incr backup $Backups[$firstIncr]{num}\n");
903 BackupRemove($client, \@Backups, $firstIncr);
904 } elsif ( ($cntFull > $Conf{FullKeepCnt}
905 || ($cntFull > $Conf{FullKeepCntMin}
906 && $oldestFull > $Conf{FullAgeMax}))
907 && (@Backups <= $firstFull + 1
908 || !$Backups[$firstFull + 1]{noFill}) ) {
910 # Only delete a full backup if the Conf settings are satisfied.
911 # We also must make sure that either this backup is the most
912 # recent one, or the next backup is filled.
913 # (We can't deleted a full backup if the next backup is not
916 print(LOG $bpc->timeStamp,
917 "removing full backup $Backups[$firstFull]{num}\n");
918 BackupRemove($client, \@Backups, $firstFull);
923 $bpc->BackupInfoWrite($client, @Backups);
927 # Removes any partial backups
929 sub BackupPartialRemove
931 my($client, $Backups) = @_;
933 for ( my $i = @$Backups - 1 ; $i >= 0 ; $i-- ) {
934 next if ( $Backups->[$i]{type} ne "partial" );
935 BackupRemove($client, $Backups, $i);
941 my @Backups = $bpc->BackupInfoRead($client);
945 # Since we got a good backup we should remove any partial dumps
946 # (the new backup might also be a partial, but that's ok).
948 BackupPartialRemove($client, \@Backups);
951 # Number the new backup
953 for ( my $i = 0 ; $i < @Backups ; $i++ ) {
954 $num = $Backups[$i]{num} if ( $num < $Backups[$i]{num} );
957 $bpc->RmTreeDefer("$TopDir/trash", "$Dir/$num")
958 if ( -d "$Dir/$num" );
959 if ( !rename("$Dir/new", "$Dir/$num") ) {
960 print(LOG $bpc->timeStamp,
961 "Rename $Dir/new -> $Dir/$num failed\n");
964 rename("$Dir/XferLOG$fileExt", "$Dir/XferLOG.$num$fileExt");
965 rename("$Dir/NewFileList", "$Dir/NewFileList.$num");
968 # Add the new backup information to the backup file
971 $Backups[$i]{num} = $num;
972 $Backups[$i]{type} = $type;
973 $Backups[$i]{startTime} = $startTime;
974 $Backups[$i]{endTime} = $endTime;
975 $Backups[$i]{size} = $sizeTotal;
976 $Backups[$i]{nFiles} = $nFilesTotal;
977 $Backups[$i]{xferErrs} = $stat{xferErrCnt} || 0;
978 $Backups[$i]{xferBadFile} = $stat{xferBadFileCnt} || 0;
979 $Backups[$i]{xferBadShare} = $stat{xferBadShareCnt} || 0;
980 $Backups[$i]{nFilesExist} = $nFilesExist;
981 $Backups[$i]{sizeExist} = $sizeExist;
982 $Backups[$i]{sizeExistComp} = $sizeExistComp;
983 $Backups[$i]{tarErrs} = $tarErrs;
984 $Backups[$i]{compress} = $Conf{CompressLevel};
985 $Backups[$i]{noFill} = $type eq "incr" ? 1 : 0;
986 $Backups[$i]{level} = $type eq "incr" ? 1 : 0;
987 $Backups[$i]{mangle} = 1; # name mangling always on for v1.04+
988 $bpc->BackupInfoWrite($client, @Backups);
990 unlink("$Dir/timeStamp.level0");
993 # Now remove the bad files, replacing them if possible with links to
996 foreach my $f ( $xfer->getBadFiles ) {
998 my $shareM = $bpc->fileNameEltMangle($f->{share});
999 my $fileM = $bpc->fileNameMangle($f->{file});
1000 unlink("$Dir/$num/$shareM/$fileM");
1001 for ( $j = $i - 1 ; $j >= 0 ; $j-- ) {
1003 if ( $Backups[$j]{mangle} ) {
1004 $file = "$shareM/$fileM";
1006 $file = "$f->{share}/$f->{file}";
1008 next if ( !-f "$Dir/$Backups[$j]{num}/$file" );
1009 if ( !link("$Dir/$Backups[$j]{num}/$file",
1010 "$Dir/$num/$shareM/$fileM") ) {
1011 print(LOG $bpc->timeStamp,
1012 "Unable to link $num/$shareM/$fileM to"
1013 . " $Backups[$j]{num}/$file\n");
1015 print(LOG $bpc->timeStamp,
1016 "Bad file $num/$shareM/$fileM replaced by link to"
1017 . " $Backups[$j]{num}/$file\n");
1022 print(LOG $bpc->timeStamp,
1023 "Removed bad file $num/$shareM/$fileM (no older"
1024 . " copy to link to)\n");
1031 # Removes a specific backup
1035 my($client, $Backups, $idx) = @_;
1036 my($Dir) = "$TopDir/pc/$client";
1038 $bpc->RmTreeDefer("$TopDir/trash",
1039 "$Dir/$Backups->[$idx]{num}");
1040 unlink("$Dir/SmbLOG.$Backups->[$idx]{num}")
1041 if ( -f "$Dir/SmbLOG.$Backups->[$idx]{num}" );
1042 unlink("$Dir/SmbLOG.$Backups->[$idx]{num}.z")
1043 if ( -f "$Dir/SmbLOG.$Backups->[$idx]{num}.z" );
1044 unlink("$Dir/XferLOG.$Backups->[$idx]{num}")
1045 if ( -f "$Dir/XferLOG.$Backups->[$idx]{num}" );
1046 unlink("$Dir/XferLOG.$Backups->[$idx]{num}.z")
1047 if ( -f "$Dir/XferLOG.$Backups->[$idx]{num}.z" );
1048 splice(@{$Backups}, $idx, 1);
1051 sub CorrectHostCheck
1053 my($hostIP, $host) = @_;
1054 return if ( $hostIP eq $host && !$Conf{FixedIPNetBiosNameCheck}
1055 || $Conf{NmbLookupCmd} eq "" );
1056 my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($hostIP);
1057 return "host $host has mismatching netbios name $netBiosHost"
1058 if ( $netBiosHost ne $host );
1063 # The Xfer method might tell us from time to time about processes
1064 # it forks. We tell BackupPC about this (for status displays) and
1065 # keep track of the pids in case we cancel the backup
1070 @xferPid = grep(/./, @xferPid);
1071 return if ( !@xferPid && $tarPid < 0 );
1072 my @pids = @xferPid;
1073 push(@pids, $tarPid) if ( $tarPid > 0 );
1074 my $str = join(",", @pids);
1075 $XferLOG->write(\"Xfer PIDs are now $str\n") if ( defined($XferLOG) );
1076 print("xferPids $str\n");
1080 # Run an optional pre- or post-dump command
1086 return if ( !defined($Conf{$type}) );
1092 user => $Hosts->{$client}{user},
1093 moreUsers => $Hosts->{$client}{moreUsers},
1094 share => $ShareNames->[0],
1095 shares => $ShareNames,
1096 XferMethod => $Conf{XferMethod},
1097 sshPath => $Conf{SshPath},
1099 XferLOG => $XferLOG,
1101 xferOK => $stat{xferOK} || 0,
1102 hostError => $stat{hostError},
1105 my $cmd = $bpc->cmdVarSubstitute($Conf{$type}, $vars);
1106 $XferLOG->write(\"Executing $type: @$cmd\n");
1108 # Run the user's command, dumping the stdout/stderr into the
1109 # Xfer log file. Also supply the optional $vars and %Conf in
1110 # case the command is really perl code instead of a shell
1113 $bpc->cmdSystemOrEval($cmd,
1115 $XferLOG->write(\$_[0]);