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.0beta2, released 23 May 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);
281 if ( $Conf{FullPeriod} == -1 && !$opts{f} && !$opts{i}
282 || $Conf{FullPeriod} == -2 ) {
283 print(STDERR "Exiting because backups are disabled with"
284 . " \$Conf{FullPeriod} = $Conf{FullPeriod}\n") if ( $opts{v} );
286 # Tell BackupPC to ignore old failed backups on hosts that
287 # have backups disabled.
289 print("backups disabled\n")
290 if ( defined($StatusHost{errorTime})
291 && $StatusHost{reason} ne "Reason_backup_done"
292 && time - $StatusHost{errorTime} > 4 * 24 * 3600 );
293 NothingToDo($needLink);
296 if ( !$opts{i} && !$opts{f} && $Conf{BlackoutGoodCnt} >= 0
297 && $StatusHost{aliveCnt} >= $Conf{BlackoutGoodCnt} ) {
298 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
299 my($currHours) = $hour + $min / 60 + $sec / 3600;
303 # Handle backward compatibility with original separate scalar
306 if ( defined($Conf{BlackoutHourBegin}) ) {
307 push(@{$Conf{BlackoutPeriods}},
309 hourBegin => $Conf{BlackoutHourBegin},
310 hourEnd => $Conf{BlackoutHourEnd},
311 weekDays => $Conf{BlackoutWeekDays},
315 foreach my $p ( @{$Conf{BlackoutPeriods}} ) {
317 # Allow blackout to span midnight (specified by BlackoutHourBegin
318 # being greater than BlackoutHourEnd)
320 next if ( ref($p->{weekDays}) ne "ARRAY"
321 || !defined($p->{hourBegin})
322 || !defined($p->{hourEnd})
324 if ( $p->{hourBegin} > $p->{hourEnd} ) {
325 $blackout = $p->{hourBegin} <= $currHours
326 || $currHours <= $p->{hourEnd};
327 if ( $currHours <= $p->{hourEnd} ) {
329 # This is after midnight, so decrement the weekday for the
330 # weekday check (eg: Monday 11pm-1am means Monday 2300 to
331 # Tuesday 0100, not Monday 2300-2400 plus Monday 0000-0100).
334 $wday += 7 if ( $wday < 0 );
337 $blackout = $p->{hourBegin} <= $currHours
338 && $currHours <= $p->{hourEnd};
340 if ( $blackout && grep($_ == $wday, @{$p->{weekDays}}) ) {
341 # print(LOG $bpc->timeStamp, "skipping because of blackout"
342 # . " (alive $StatusHost{aliveCnt} times)\n");
343 print(STDERR "Skipping $client because of blackout\n")
345 NothingToDo($needLink);
350 if ( !$opts{i} && !$opts{f} && $StatusHost{backoffTime} > time ) {
351 printf(LOG "%sskipping because of user requested delay (%.1f hours left)",
352 $bpc->timeStamp, ($StatusHost{backoffTime} - time) / 3600);
353 NothingToDo($needLink);
357 # Now see if there are any old backups we should delete
359 BackupExpire($client);
362 # Read Backup information, and find times of the most recent full and
363 # incremental backups
365 @Backups = $bpc->BackupInfoRead($client);
366 for ( my $i = 0 ; $i < @Backups ; $i++ ) {
367 $needLink = 1 if ( $Backups[$i]{nFilesNew} eq ""
368 || -f "$Dir/NewFileList.$Backups[$i]{num}" );
369 $lastBkupNum = $Backups[$i]{num};
370 if ( $Backups[$i]{type} eq "full" ) {
371 if ( $lastFull < $Backups[$i]{startTime} ) {
372 $lastFull = $Backups[$i]{startTime};
373 $lastFullBkupNum = $Backups[$i]{num};
375 } elsif ( $Backups[$i]{type} eq "incr" ) {
376 $lastIncr = $Backups[$i]{startTime}
377 if ( $lastIncr < $Backups[$i]{startTime} );
378 } elsif ( $Backups[$i]{type} eq "partial" ) {
380 $lastPartial = $Backups[$i]{startTime};
381 $partialNum = $Backups[$i]{num};
386 # Decide whether we do nothing, or a full or incremental backup.
390 || (!$opts{i} && (time - $lastFull > $Conf{FullPeriod} * 24*3600
391 && time - $lastIncr > $Conf{IncrPeriod} * 24*3600)) ) {
393 } elsif ( $opts{i} || (time - $lastIncr > $Conf{IncrPeriod} * 24*3600
394 && time - $lastFull > $Conf{IncrPeriod} * 24*3600) ) {
397 NothingToDo($needLink);
401 # Check if $host is alive
403 my $delay = $bpc->CheckHostAlive($hostIP);
405 print(LOG $bpc->timeStamp, "no ping response\n");
406 print("no ping response\n");
407 print("link $clientURI\n") if ( $needLink );
409 } elsif ( $delay > $Conf{PingMaxMsec} ) {
410 printf(LOG "%sping too slow: %.4gmsec\n", $bpc->timeStamp, $delay);
411 printf("ping too slow: %.4gmsec (threshold is %gmsec)\n",
412 $delay, $Conf{PingMaxMsec});
413 print("link $clientURI\n") if ( $needLink );
418 # Make sure it is really the machine we expect (only for fixed addresses,
419 # since we got the DHCP address above).
421 if ( !$opts{d} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
422 print(LOG $bpc->timeStamp, "dump failed: $errMsg\n");
423 print("dump failed: $errMsg\n");
425 } elsif ( $opts{d} ) {
426 print(LOG $bpc->timeStamp, "$host is dhcp $hostIP, user is $user\n");
430 # Get a clean directory $Dir/new
432 $bpc->RmTreeDefer("$TopDir/trash", "$Dir/new") if ( -d "$Dir/new" );
435 # Setup file extension for compression and open XferLOG output file
437 $Conf{CompressLevel} = 0 if ( !BackupPC::FileZIO->compOk );
438 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
439 my $XferLOG = BackupPC::FileZIO->open("$Dir/XferLOG$fileExt", 1,
440 $Conf{CompressLevel});
441 if ( !defined($XferLOG) ) {
442 print(LOG $bpc->timeStamp, "dump failed: unable to open/create"
443 . " $Dir/XferLOG$fileExt\n");
444 print("dump failed: unable to open/create $Dir/XferLOG$fileExt\n");
449 # Ignore the partial dump in the case of an incremental
450 # or when the partial is too old. A partial is a partial full.
452 if ( $type ne "full" || time - $lastPartial > $Conf{PartialAgeMax} * 24*3600 ) {
458 # If this is a partial, copy the old XferLOG file
461 my($compress, $fileName);
462 if ( -f "$Dir/XferLOG.$partialNum.z" ) {
463 $fileName = "$Dir/XferLOG.$partialNum.z";
465 } elsif ( -f "$Dir/XferLOG.$partialNum" ) {
466 $fileName = "$Dir/XferLOG.$partialNum";
469 if ( my $oldLOG = BackupPC::FileZIO->open($fileName, 0, $compress) ) {
471 while ( $oldLOG->read(\$data, 65536) > 0 ) {
472 $XferLOG->write(\$data);
478 $XferLOG->writeTeeStderr(1) if ( $opts{v} );
479 unlink("$Dir/NewFileList") if ( -f "$Dir/NewFileList" );
481 my $startTime = time();
485 my $sizeExistComp = 0;
488 my($logMsg, %stat, $xfer, $ShareNames, $noFilesErr);
491 if ( $Conf{XferMethod} eq "tar" ) {
492 $ShareNames = $Conf{TarShareName};
493 } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
494 $ShareNames = $Conf{RsyncShareName};
496 $ShareNames = $Conf{SmbShareName};
499 $ShareNames = [ $ShareNames ] unless ref($ShareNames) eq "ARRAY";
502 # Run an optional pre-dump command
504 UserCommandRun("DumpPreUserCmd");
508 # Now backup each of the shares
510 for my $shareName ( @$ShareNames ) {
513 $stat{xferOK} = $stat{hostAbort} = undef;
514 $stat{hostError} = $stat{lastOutputLine} = undef;
515 if ( -d "$Dir/new/$shareName" ) {
516 print(LOG $bpc->timeStamp,
517 "unexpected repeated share name $shareName skipped\n");
521 if ( $Conf{XferMethod} eq "tar" ) {
523 # Use tar (eg: tar/ssh) as the transport program.
525 $xfer = BackupPC::Xfer::Tar->new($bpc);
526 } elsif ( $Conf{XferMethod} eq "rsync" || $Conf{XferMethod} eq "rsyncd" ) {
528 # Use rsync as the transport program.
530 if ( !defined($xfer = BackupPC::Xfer::Rsync->new($bpc)) ) {
531 my $errStr = BackupPC::Xfer::Rsync::errStr;
532 print(LOG $bpc->timeStamp, "dump failed: $errStr\n");
533 print("dump failed: $errStr\n");
534 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
539 # Default is to use smbclient (smb) as the transport program.
541 $xfer = BackupPC::Xfer::Smb->new($bpc);
544 my $useTar = $xfer->useTar;
548 # This xfer method outputs a tar format file, so we start a
549 # BackupPC_tarExtract to extract the data.
551 # Create a socketpair to connect the Xfer method to BackupPC_tarExtract
552 # WH is the write handle for writing, provided to the transport
553 # program, and RH is the other end of the socket for reading,
554 # provided to BackupPC_tarExtract.
556 if ( socketpair(RH, WH, AF_UNIX, SOCK_STREAM, PF_UNSPEC) ) {
557 shutdown(RH, 1); # no writing to this socket
558 shutdown(WH, 0); # no reading from this socket
559 setsockopt(RH, SOL_SOCKET, SO_RCVBUF, 8 * 65536);
560 setsockopt(WH, SOL_SOCKET, SO_SNDBUF, 8 * 65536);
563 # Default to pipe() if socketpair() doesn't work.
569 # fork a child for BackupPC_tarExtract. TAR is a file handle
570 # on which we (the parent) read the stdout & stderr from
571 # BackupPC_tarExtract.
573 if ( !defined($tarPid = open(TAR, "-|")) ) {
574 print(LOG $bpc->timeStamp, "can't fork to run tar\n");
575 print("can't fork to run tar\n");
583 # This is the tar child. Close the write end of the pipe,
584 # clone STDERR to STDOUT, clone STDIN from RH, and then
585 # exec BackupPC_tarExtract.
590 open(STDERR, ">&STDOUT");
594 exec("$BinDir/BackupPC_tarExtract", $client, $shareName,
595 $Conf{CompressLevel});
596 print(LOG $bpc->timeStamp,
597 "can't exec $BinDir/BackupPC_tarExtract\n");
600 } elsif ( !defined($newFilesFH) ) {
602 # We need to create the NewFileList output file
605 open(NEW_FILES, ">", "$TopDir/pc/$client/NewFileList")
606 || die("can't open $TopDir/pc/$client/NewFileList");
607 $newFilesFH = *NEW_FILES;
612 # Run the transport program
618 shareName => $shareName,
622 newFilesFH => $newFilesFH,
625 lastFull => $lastFull,
626 lastBkupNum => $lastBkupNum,
627 lastFullBkupNum => $lastFullBkupNum,
628 backups => \@Backups,
629 compress => $Conf{CompressLevel},
630 XferMethod => $Conf{XferMethod},
631 logLevel => $Conf{XferLogLevel},
632 pidHandler => \&pidHandler,
633 partialNum => $partialNum,
636 if ( !defined($logMsg = $xfer->start()) ) {
637 print(LOG $bpc->timeStamp, "xfer start failed: ", $xfer->errStr, "\n");
638 print("dump failed: ", $xfer->errStr, "\n");
639 print("link $clientURI\n") if ( $needLink );
641 # kill off the tar process, first nicely then forcefully
644 kill($bpc->sigName2num("INT"), $tarPid);
646 kill($bpc->sigName2num("KILL"), $tarPid);
649 kill($bpc->sigName2num("INT"), @xferPid);
651 kill($bpc->sigName2num("KILL"), @xferPid);
653 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
657 @xferPid = $xfer->xferPid;
661 # The parent must close both handles on the pipe since the children
662 # are using these handles now.
667 print(LOG $bpc->timeStamp, $logMsg, "\n");
668 print("started $type dump, share=$shareName\n");
670 pidHandler(@xferPid);
674 # Parse the output of the transfer program and BackupPC_tarExtract
675 # while they run. Since we might be reading from two or more children
678 my($FDread, $tarOut, $mesg);
679 vec($FDread, fileno(TAR), 1) = 1 if ( $useTar );
680 $xfer->setSelectMask(\$FDread);
684 last if ( $FDread =~ /^\0*$/ );
685 select(my $rout = $FDread, undef, $ein, undef);
687 if ( vec($rout, fileno(TAR), 1) ) {
688 if ( sysread(TAR, $mesg, 8192) <= 0 ) {
689 vec($FDread, fileno(TAR), 1) = 0;
695 while ( $tarOut =~ /(.*?)[\n\r]+(.*)/s ) {
699 $XferLOG->write(\"$_\n");
701 $XferLOG->write(\"tarExtract: $_\n");
703 if ( /^BackupPC_tarExtact aborting \((.*)\)/ ) {
704 $stat{hostError} = $1;
706 if ( /^Done: (\d+) errors, (\d+) filesExist, (\d+) sizeExist, (\d+) sizeExistComp, (\d+) filesTotal, (\d+) sizeTotal/ ) {
710 $sizeExistComp += $4;
716 last if ( !$xfer->readOutput(\$FDread, $rout) );
717 while ( my $str = $xfer->logMsgGet ) {
718 print(LOG $bpc->timeStamp, "xfer: $str\n");
720 if ( $xfer->getStats->{fileCnt} == 1 ) {
722 # Make sure it is still the machine we expect. We do this while
723 # the transfer is running to avoid a potential race condition if
724 # the ip address was reassigned by dhcp just before we started
727 if ( my $errMsg = CorrectHostCheck($hostIP, $host) ) {
728 $stat{hostError} = $errMsg if ( $stat{hostError} eq "" );
735 # otherwise the xfer module does everything for us
737 my @results = $xfer->run();
738 $tarErrs += $results[0];
739 $nFilesExist += $results[1];
740 $sizeExist += $results[2];
741 $sizeExistComp += $results[3];
742 $nFilesTotal += $results[4];
743 $sizeTotal += $results[5];
747 # Merge the xfer status (need to accumulate counts)
749 my $newStat = $xfer->getStats;
750 if ( $newStat->{fileCnt} == 0 ) {
751 $noFilesErr ||= "No files dumped for share $shareName";
753 foreach my $k ( (keys(%stat), keys(%$newStat)) ) {
754 next if ( !defined($newStat->{$k}) );
755 if ( $k =~ /Cnt$/ ) {
756 $stat{$k} += $newStat->{$k};
757 delete($newStat->{$k});
760 if ( !defined($stat{$k}) ) {
761 $stat{$k} = $newStat->{$k};
762 delete($newStat->{$k});
766 $stat{xferOK} = 0 if ( $stat{hostError} || $stat{hostAbort} );
767 if ( !$stat{xferOK} ) {
769 # kill off the tranfer program, first nicely then forcefully
772 kill($bpc->sigName2num("INT"), @xferPid);
774 kill($bpc->sigName2num("KILL"), @xferPid);
777 # kill off the tar process, first nicely then forcefully
780 kill($bpc->sigName2num("INT"), $tarPid);
782 kill($bpc->sigName2num("KILL"), $tarPid);
785 # don't do any more shares on this host
792 # If this is a full, and any share had zero files then consider the dump bad
794 if ( $type eq "full" && $stat{hostError} eq ""
795 && length($noFilesErr) && $Conf{BackupZeroFilesIsFatal} ) {
796 $stat{hostError} = $noFilesErr;
800 $stat{xferOK} = 0 if ( $Abort );
803 # Do one last check to make sure it is still the machine we expect.
805 if ( $stat{xferOK} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
806 $stat{hostError} = $errMsg;
810 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
811 close($newFilesFH) if ( defined($newFilesFH) );
813 my $endTime = time();
816 # If the dump failed, clean up
818 if ( !$stat{xferOK} ) {
819 $stat{hostError} = $stat{lastOutputLine} if ( $stat{hostError} eq "" );
820 if ( $stat{hostError} ) {
821 print(LOG $bpc->timeStamp,
822 "Got fatal error during xfer ($stat{hostError})\n");
823 $XferLOG->write(\"Got fatal error during xfer ($stat{hostError})\n");
827 # wait a short while and see if the system is still alive
830 if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
831 $stat{hostAbort} = 1;
833 if ( $stat{hostAbort} ) {
834 $stat{hostError} = "lost network connection during backup";
836 print(LOG $bpc->timeStamp, "Backup aborted ($stat{hostError})\n");
837 $XferLOG->write(\"Backup aborted ($stat{hostError})\n");
839 $XferLOG->write(\"Backup aborted by user signal\n");
843 # Close the log file and call BackupFailCleanup, which exits.
848 my $newNum = BackupSave();
850 my $otherCount = $stat{xferErrCnt} - $stat{xferBadFileCnt}
851 - $stat{xferBadShareCnt};
852 print(LOG $bpc->timeStamp,
853 "$type backup $newNum complete, $stat{fileCnt} files,"
854 . " $stat{byteCnt} bytes,"
855 . " $stat{xferErrCnt} xferErrs ($stat{xferBadFileCnt} bad files,"
856 . " $stat{xferBadShareCnt} bad shares, $otherCount other)\n");
858 BackupExpire($client);
860 print("$type backup complete\n");
862 ###########################################################################
864 ###########################################################################
870 print("nothing to do\n");
871 print("link $clientURI\n") if ( $needLink );
880 # The first time we receive a signal we try to gracefully
881 # abort the backup. This allows us to keep a partial dump
882 # with the in-progress file deleted and attribute caches
883 # flushed to disk etc.
885 if ( !length($SigName) ) {
887 if ( $sigName eq "INT" ) {
888 $reason = "aborted by user (signal=$sigName)";
890 $reason = "aborted by signal=$sigName";
894 # Parent logs a message
896 print(LOG $bpc->timeStamp,
897 "Aborting backup up after signal $sigName\n");
902 $xfer->abort($reason);
905 # Send ALRMs to BackupPC_tarExtract if we are using it
908 kill($bpc->sigName2num("ARLM"), $tarPid);
912 # Schedule a 20 second timer in case the clean
913 # abort doesn't complete
918 # Children ignore anything other than ALRM and INT
920 if ( $sigName ne "ALRM" && $sigName ne "INT" ) {
925 # The child also tells xfer to abort
927 $xfer->abort($reason);
930 # Schedule a 15 second timer in case the clean
931 # abort doesn't complete
941 # This is a second signal: time to clean up.
943 if ( $Pid != $$ && ($sigName eq "ALRM" || $sigName eq "INT") ) {
945 # Children quit quietly on ALRM or INT
951 # Ignore other signals in children
953 return if ( $Pid != $$ );
955 $SIG{$sigName} = 'IGNORE';
956 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
957 $XferLOG->write(\"exiting after signal $sigName\n");
959 kill($bpc->sigName2num("INT"), @xferPid);
961 kill($bpc->sigName2num("KILL"), @xferPid);
964 kill($bpc->sigName2num("INT"), $tarPid);
966 kill($bpc->sigName2num("KILL"), $tarPid);
968 if ( $sigName eq "INT" ) {
969 $stat{hostError} = "aborted by user (signal=$sigName)";
971 $stat{hostError} = "received signal=$sigName";
978 if ( -f _ && $File::Find::name !~ /\/fattrib$/ ) {
982 # No need to check entire tree
984 $File::Find::prune = 1 if ( $nFilesTotal );
988 sub BackupFailCleanup
990 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
994 # We keep this backup if it is a full and we actually backed
997 if ( $type eq "full" ) {
998 if ( $nFilesTotal == 0 && $xfer->getStats->{fileCnt} == 0 ) {
1000 # Xfer didn't report any files, but check in the new
1001 # directory just in case.
1003 find(\&CheckForNewFiles, "$Dir/new");
1004 $keepPartial = 1 if ( $nFilesTotal );
1007 # Xfer reported some files
1014 # Don't keep partials if they are disabled
1016 $keepPartial = 0 if ( $Conf{PartialAgeMax} < 0 );
1018 if ( !$keepPartial ) {
1020 # No point in saving this dump; get rid of eveything.
1023 unlink("$Dir/timeStamp.level0") if ( -f "$Dir/timeStamp.level0" );
1024 unlink("$Dir/SmbLOG.bad") if ( -f "$Dir/SmbLOG.bad" );
1025 unlink("$Dir/SmbLOG.bad$fileExt") if ( -f "$Dir/SmbLOG.bad$fileExt" );
1026 unlink("$Dir/XferLOG.bad") if ( -f "$Dir/XferLOG.bad" );
1027 unlink("$Dir/XferLOG.bad$fileExt") if ( -f "$Dir/XferLOG.bad$fileExt" );
1028 unlink("$Dir/NewFileList") if ( -f "$Dir/NewFileList" );
1029 rename("$Dir/XferLOG$fileExt", "$Dir/XferLOG.bad$fileExt");
1030 $bpc->RmTreeDefer("$TopDir/trash", "$Dir/new") if ( -d "$Dir/new" );
1031 print("dump failed: $stat{hostError}\n");
1033 print("link $clientURI\n") if ( $needLink );
1037 # Ok, now we should save this as a partial dump
1040 my $newNum = BackupSave();
1041 print("dump failed: $stat{hostError}\n");
1042 print("link $clientURI\n") if ( $needLink );
1043 print(LOG $bpc->timeStamp, "Saved partial dump $newNum\n");
1048 # Decide which old backups should be expired by moving them
1054 my($Dir) = "$TopDir/pc/$client";
1055 my(@Backups) = $bpc->BackupInfoRead($client);
1056 my($cntFull, $cntIncr, $firstFull, $firstIncr, $oldestIncr, $oldestFull);
1058 if ( $Conf{FullKeepCnt} <= 0 ) {
1059 print(LOG $bpc->timeStamp,
1060 "Invalid value for \$Conf{FullKeepCnt}=$Conf{FullKeepCnt}\n");
1062 "Invalid value for \$Conf{FullKeepCnt}=$Conf{FullKeepCnt}\n")
1067 $cntFull = $cntIncr = 0;
1068 $oldestIncr = $oldestFull = 0;
1069 for ( my $i = 0 ; $i < @Backups ; $i++ ) {
1070 if ( $Backups[$i]{type} eq "full" ) {
1071 $firstFull = $i if ( $cntFull == 0 );
1074 $firstIncr = $i if ( $cntIncr == 0 );
1078 $oldestIncr = (time - $Backups[$firstIncr]{startTime}) / (24 * 3600)
1079 if ( $cntIncr > 0 );
1080 $oldestFull = (time - $Backups[$firstFull]{startTime}) / (24 * 3600)
1081 if ( $cntFull > 0 );
1082 if ( $cntIncr > $Conf{IncrKeepCnt}
1083 || ($cntIncr > $Conf{IncrKeepCntMin}
1084 && $oldestIncr > $Conf{IncrAgeMax})
1085 && (@Backups <= $firstIncr + 1
1086 || $Backups[$firstIncr]{noFill}
1087 || !$Backups[$firstIncr + 1]{noFill}) ) {
1089 # Only delete an incr backup if the Conf settings are satisfied.
1090 # We also must make sure that either this backup is the most
1091 # recent one, or it is not filled, or the next backup is filled.
1092 # (We can't deleted a filled incr if the next backup is not
1095 print(LOG $bpc->timeStamp,
1096 "removing incr backup $Backups[$firstIncr]{num}\n");
1097 BackupRemove($client, \@Backups, $firstIncr);
1102 # Delete any old full backups, according to $Conf{FullKeepCntMin}
1103 # and $Conf{FullAgeMax}.
1105 # First make sure that $Conf{FullAgeMax} is at least bigger
1106 # than $Conf{FullPeriod} * $Conf{FullKeepCnt}, including
1107 # the exponential array case.
1109 my $fullKeepCnt = $Conf{FullKeepCnt};
1110 $fullKeepCnt = [$fullKeepCnt] if ( ref($fullKeepCnt) ne "ARRAY" );
1112 my $fullPeriod = int(0.5 + $Conf{FullPeriod});
1113 for ( my $i = 0 ; $i < @$fullKeepCnt ; $i++ ) {
1114 $oldestFull += $fullKeepCnt->[$i] * $fullPeriod;
1117 $oldestFull += $fullPeriod; # add some buffer
1119 if ( $cntFull > $Conf{FullKeepCntMin}
1120 && $oldestFull > $Conf{FullAgeMax}
1121 && $oldestFull > $oldestFull
1122 && $Conf{FullKeepCntMin} > 0
1123 && $Conf{FullAgeMax} > 0
1124 && (@Backups <= $firstFull + 1
1125 || !$Backups[$firstFull + 1]{noFill}) ) {
1127 # Only delete a full backup if the Conf settings are satisfied.
1128 # We also must make sure that either this backup is the most
1129 # recent one, or the next backup is filled.
1130 # (We can't deleted a full backup if the next backup is not
1133 print(LOG $bpc->timeStamp,
1134 "removing old full backup $Backups[$firstFull]{num}\n");
1135 BackupRemove($client, \@Backups, $firstFull);
1140 # Do new-style full backup expiry, which includes the the case
1141 # where $Conf{FullKeepCnt} is an array.
1143 last if ( !BackupFullExpire($client, \@Backups) );
1145 $bpc->BackupInfoWrite($client, @Backups);
1149 # Handle full backup expiry, using exponential periods.
1151 sub BackupFullExpire
1153 my($client, $Backups) = @_;
1155 my $fullPeriod = $Conf{FullPeriod};
1156 my $origFullPeriod = $fullPeriod;
1157 my $fullKeepCnt = $Conf{FullKeepCnt};
1158 my $fullKeepIdx = 0;
1159 my(@delete, @fullList);
1162 # Don't delete anything if $Conf{FullPeriod} or $Conf{FullKeepCnt} are
1163 # not defined - possibly a corrupted config.pl file.
1165 return if ( !defined($Conf{FullPeriod}) || !defined($Conf{FullKeepCnt}) );
1168 # If regular backups are still disabled with $Conf{FullPeriod} < 0,
1169 # we still expire backups based on a typical FullPeriod value - weekly.
1171 $fullPeriod = 7 if ( $fullPeriod <= 0 );
1173 $fullKeepCnt = [$fullKeepCnt] if ( ref($fullKeepCnt) ne "ARRAY" );
1175 for ( my $i = 0 ; $i < @$Backups ; $i++ ) {
1176 next if ( $Backups->[$i]{type} ne "full" );
1177 push(@fullList, $i);
1179 for ( my $k = @fullList - 1 ; $k >= 0 ; $k-- ) {
1180 my $i = $fullList[$k];
1181 my $prevFull = $fullList[$k-1] if ( $k > 0 );
1183 # Don't delete any full that is followed by an unfilled backup,
1184 # since it is needed for restore.
1186 my $noDelete = $i + 1 < @$Backups ? $Backups->[$i+1]{noFill} : 0;
1189 ($fullKeepIdx >= @$fullKeepCnt
1192 && $Backups->[$i]{startTime} - $Backups->[$prevFull]{startTime}
1193 < ($fullPeriod - $origFullPeriod / 2) * 24 * 3600
1197 # Delete the full backup
1199 #printf("Deleting backup $i ($prevFull)\n");
1203 while ( $fullKeepIdx < @$fullKeepCnt
1204 && $fullCnt >= $fullKeepCnt->[$fullKeepIdx] ) {
1207 $fullPeriod = 2 * $fullPeriod;
1212 # Now actually delete the backups
1214 for ( my $i = @delete - 1 ; $i >= 0 ; $i-- ) {
1215 print(LOG $bpc->timeStamp,
1216 "removing full backup $Backups->[$delete[$i]]{num}\n");
1217 BackupRemove($client, $Backups, $delete[$i]);
1223 # Removes any partial backups
1225 sub BackupPartialRemove
1227 my($client, $Backups) = @_;
1229 for ( my $i = @$Backups - 1 ; $i >= 0 ; $i-- ) {
1230 next if ( $Backups->[$i]{type} ne "partial" );
1231 BackupRemove($client, $Backups, $i);
1237 my @Backups = $bpc->BackupInfoRead($client);
1241 # Since we got a good backup we should remove any partial dumps
1242 # (the new backup might also be a partial, but that's ok).
1244 BackupPartialRemove($client, \@Backups);
1247 # Number the new backup
1249 for ( my $i = 0 ; $i < @Backups ; $i++ ) {
1250 $num = $Backups[$i]{num} if ( $num < $Backups[$i]{num} );
1253 $bpc->RmTreeDefer("$TopDir/trash", "$Dir/$num") if ( -d "$Dir/$num" );
1254 if ( !rename("$Dir/new", "$Dir/$num") ) {
1255 print(LOG $bpc->timeStamp, "Rename $Dir/new -> $Dir/$num failed\n");
1258 $needLink = 1 if ( -f "$Dir/NewFileList" );
1261 # Add the new backup information to the backup file
1264 $Backups[$i]{num} = $num;
1265 $Backups[$i]{type} = $type;
1266 $Backups[$i]{startTime} = $startTime;
1267 $Backups[$i]{endTime} = $endTime;
1268 $Backups[$i]{size} = $sizeTotal;
1269 $Backups[$i]{nFiles} = $nFilesTotal;
1270 $Backups[$i]{xferErrs} = $stat{xferErrCnt} || 0;
1271 $Backups[$i]{xferBadFile} = $stat{xferBadFileCnt} || 0;
1272 $Backups[$i]{xferBadShare} = $stat{xferBadShareCnt} || 0;
1273 $Backups[$i]{nFilesExist} = $nFilesExist;
1274 $Backups[$i]{sizeExist} = $sizeExist;
1275 $Backups[$i]{sizeExistComp} = $sizeExistComp;
1276 $Backups[$i]{tarErrs} = $tarErrs;
1277 $Backups[$i]{compress} = $Conf{CompressLevel};
1278 $Backups[$i]{noFill} = $type eq "incr" ? 1 : 0;
1279 $Backups[$i]{level} = $type eq "incr" ? 1 : 0;
1280 $Backups[$i]{mangle} = 1; # name mangling always on for v1.04+
1281 $bpc->BackupInfoWrite($client, @Backups);
1283 unlink("$Dir/timeStamp.level0") if ( -f "$Dir/timeStamp.level0" );
1284 foreach my $ext ( qw(bad bad.z) ) {
1285 next if ( !-f "$Dir/XferLOG.$ext" );
1286 unlink("$Dir/XferLOG.$ext.old") if ( -f "$Dir/XferLOG.$ext" );
1287 rename("$Dir/XferLOG.$ext", "$Dir/XferLOG.$ext.old");
1291 # Now remove the bad files, replacing them if possible with links to
1294 foreach my $f ( $xfer->getBadFiles ) {
1296 my $shareM = $bpc->fileNameEltMangle($f->{share});
1297 my $fileM = $bpc->fileNameMangle($f->{file});
1298 unlink("$Dir/$num/$shareM/$fileM");
1299 for ( $j = $i - 1 ; $j >= 0 ; $j-- ) {
1301 if ( $Backups[$j]{mangle} ) {
1302 $file = "$shareM/$fileM";
1304 $file = "$f->{share}/$f->{file}";
1306 next if ( !-f "$Dir/$Backups[$j]{num}/$file" );
1307 if ( !link("$Dir/$Backups[$j]{num}/$file",
1308 "$Dir/$num/$shareM/$fileM") ) {
1309 my $str = \"Unable to link $num/$f->{share}/$f->{file} to"
1310 . " $Backups[$j]{num}/$f->{share}/$f->{file}\n";
1311 $XferLOG->write(\$str);
1313 my $str = "Bad file $num/$f->{share}/$f->{file} replaced"
1315 . " $Backups[$j]{num}/$f->{share}/$f->{file}\n";
1316 $XferLOG->write(\$str);
1321 my $str = "Removed bad file $num/$f->{share}/$f->{file}"
1322 . " (no older copy to link to)\n";
1323 $XferLOG->write(\$str);
1327 rename("$Dir/XferLOG$fileExt", "$Dir/XferLOG.$num$fileExt");
1328 rename("$Dir/NewFileList", "$Dir/NewFileList.$num");
1334 # Removes a specific backup
1338 my($client, $Backups, $idx) = @_;
1339 my($Dir) = "$TopDir/pc/$client";
1341 $bpc->RmTreeDefer("$TopDir/trash",
1342 "$Dir/$Backups->[$idx]{num}");
1343 unlink("$Dir/SmbLOG.$Backups->[$idx]{num}")
1344 if ( -f "$Dir/SmbLOG.$Backups->[$idx]{num}" );
1345 unlink("$Dir/SmbLOG.$Backups->[$idx]{num}.z")
1346 if ( -f "$Dir/SmbLOG.$Backups->[$idx]{num}.z" );
1347 unlink("$Dir/XferLOG.$Backups->[$idx]{num}")
1348 if ( -f "$Dir/XferLOG.$Backups->[$idx]{num}" );
1349 unlink("$Dir/XferLOG.$Backups->[$idx]{num}.z")
1350 if ( -f "$Dir/XferLOG.$Backups->[$idx]{num}.z" );
1351 splice(@{$Backups}, $idx, 1);
1354 sub CorrectHostCheck
1356 my($hostIP, $host) = @_;
1357 return if ( $hostIP eq $host && !$Conf{FixedIPNetBiosNameCheck}
1358 || $Conf{NmbLookupCmd} eq "" );
1359 my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($hostIP);
1360 return "host $host has mismatching netbios name $netBiosHost"
1361 if ( $netBiosHost ne $host );
1366 # The Xfer method might tell us from time to time about processes
1367 # it forks. We tell BackupPC about this (for status displays) and
1368 # keep track of the pids in case we cancel the backup
1373 @xferPid = grep(/./, @xferPid);
1374 return if ( !@xferPid && $tarPid < 0 );
1375 my @pids = @xferPid;
1376 push(@pids, $tarPid) if ( $tarPid > 0 );
1377 my $str = join(",", @pids);
1378 $XferLOG->write(\"Xfer PIDs are now $str\n") if ( defined($XferLOG) );
1379 print("xferPids $str\n");
1383 # Run an optional pre- or post-dump command
1389 return if ( !defined($Conf{$type}) );
1395 user => $Hosts->{$client}{user},
1396 moreUsers => $Hosts->{$client}{moreUsers},
1397 share => $ShareNames->[0],
1398 shares => $ShareNames,
1399 XferMethod => $Conf{XferMethod},
1400 sshPath => $Conf{SshPath},
1402 XferLOG => $XferLOG,
1404 xferOK => $stat{xferOK} || 0,
1405 hostError => $stat{hostError},
1408 my $cmd = $bpc->cmdVarSubstitute($Conf{$type}, $vars);
1409 $XferLOG->write(\"Executing $type: @$cmd\n");
1411 # Run the user's command, dumping the stdout/stderr into the
1412 # Xfer log file. Also supply the optional $vars and %Conf in
1413 # case the command is really perl code instead of a shell
1416 $bpc->cmdSystemOrEval($cmd,
1418 $XferLOG->write(\$_[0]);