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,
35 # backuppcd etc), extracting the dump into $TopDir/pc/$client/new.
36 # The xfer output is 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-2007 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 3.2.0beta0, released 17 Jan 2009.
75 # See http://backuppc.sourceforge.net.
77 #========================================================================
81 use lib "/usr/local/BackupPC/lib";
83 use BackupPC::FileZIO;
84 use BackupPC::Storage;
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";
161 my $completionPercent;
164 # Re-read config file, so we can include the PC-specific config
166 $clientURI = $bpc->uriEsc($client);
167 if ( defined(my $error = $bpc->ConfigRead($client)) ) {
168 print("dump failed: Can't read PC's config file: $error\n");
171 %Conf = $bpc->Conf();
174 # Catch various signals
176 $SIG{INT} = \&catch_signal;
177 $SIG{ALRM} = \&catch_signal;
178 $SIG{TERM} = \&catch_signal;
179 $SIG{PIPE} = \&catch_signal;
180 $SIG{STOP} = \&catch_signal;
181 $SIG{TSTP} = \&catch_signal;
182 $SIG{TTIN} = \&catch_signal;
186 # Make sure we eventually timeout if there is no activity from
187 # the data transport program.
189 alarm($Conf{ClientTimeout});
191 mkpath($Dir, 0, 0777) if ( !-d $Dir );
192 if ( !-f "$Dir/LOCK" ) {
193 open(LOCK, ">", "$Dir/LOCK") && close(LOCK);
196 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
197 my $logPath = sprintf("$Dir/LOG.%02d%04d", $mon + 1, $year + 1900);
199 if ( !-f $logPath ) {
201 # Compress and prune old log files
203 my $lastLog = $Conf{MaxOldPerPCLogFiles} - 1;
204 foreach my $file ( $bpc->sortedPCLogFiles($client) ) {
205 if ( $lastLog <= 0 ) {
210 next if ( $file =~ /\.z$/ || !$Conf{CompressLevel} );
211 BackupPC::FileZIO->compressCopy($file,
214 $Conf{CompressLevel}, 1);
218 open(LOG, ">>", $logPath);
219 select(LOG); $| = 1; select(STDOUT);
222 # For the -e option we just expire backups and quit
225 BackupExpire($client);
230 # For archive hosts we don't bother any further
232 if ($Conf{XferMethod} eq "archive" ) {
233 print(STDERR "Exiting because the XferMethod is set to archive\n")
238 ###########################################################################
239 # Figure out what to do and do it
240 ###########################################################################
243 # See if we should skip this host during a certain range
246 my $err = $bpc->ServerConnect($Conf{ServerHost}, $Conf{ServerPort});
248 print("Can't connect to server ($err)\n");
249 print(LOG $bpc->timeStamp, "Can't connect to server ($err)\n");
252 my $reply = $bpc->ServerMesg("status host($clientURI)");
253 $reply = $1 if ( $reply =~ /(.*)/s );
256 $bpc->ServerDisconnect();
259 # For DHCP tell BackupPC which host this is
262 if ( $StatusHost{activeJob} ) {
263 # oops, something is already running for this host
264 print(STDERR "Exiting because backup is already running for $client\n")
268 print("DHCP $hostIP $clientURI\n");
271 my($needLink, @Backups, $type);
272 my($incrBaseTime, $incrBaseBkupNum, $incrBaseLevel, $incrLevel);
273 my $lastFullTime = 0;
274 my $lastIncrTime = 0;
282 # Maintain backward compatibility with $Conf{FullPeriod} == -1 or -2
283 # meaning disable backups
285 $Conf{BackupsDisable} = -$Conf{FullPeriod}
286 if ( !$Conf{BackupsDisable} && $Conf{FullPeriod} < 0 );
288 if ( $Conf{BackupsDisable} == 1 && !$opts{f} && !$opts{i}
289 || $Conf{BackupsDisable} == 2 ) {
290 print(STDERR "Exiting because backups are disabled with"
291 . " \$Conf{BackupsDisable} = $Conf{BackupsDisable}\n") if ( $opts{v} );
293 # Tell BackupPC to ignore old failed backups on hosts that
294 # have backups disabled.
296 print("backups disabled\n")
297 if ( defined($StatusHost{errorTime})
298 && $StatusHost{reason} ne "Reason_backup_done"
299 && time - $StatusHost{errorTime} > 4 * 24 * 3600 );
300 NothingToDo($needLink);
303 if ( !$opts{i} && !$opts{f} && $Conf{BlackoutGoodCnt} >= 0
304 && $StatusHost{aliveCnt} >= $Conf{BlackoutGoodCnt} ) {
305 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
306 my($currHours) = $hour + $min / 60 + $sec / 3600;
309 foreach my $p ( @{$Conf{BlackoutPeriods}} ) {
311 # Allow blackout to span midnight (specified by hourBegin
312 # being greater than hourEnd)
314 next if ( ref($p->{weekDays}) ne "ARRAY"
315 || !defined($p->{hourBegin})
316 || !defined($p->{hourEnd})
318 if ( $p->{hourBegin} > $p->{hourEnd} ) {
319 $blackout = $p->{hourBegin} <= $currHours
320 || $currHours <= $p->{hourEnd};
321 if ( $currHours <= $p->{hourEnd} ) {
323 # This is after midnight, so decrement the weekday for the
324 # weekday check (eg: Monday 11pm-1am means Monday 2300 to
325 # Tuesday 0100, not Monday 2300-2400 plus Monday 0000-0100).
328 $wday += 7 if ( $wday < 0 );
331 $blackout = $p->{hourBegin} <= $currHours
332 && $currHours <= $p->{hourEnd};
334 if ( $blackout && grep($_ == $wday, @{$p->{weekDays}}) ) {
335 # print(LOG $bpc->timeStamp, "skipping because of blackout"
336 # . " (alive $StatusHost{aliveCnt} times)\n");
337 print(STDERR "Skipping $client because of blackout\n")
339 NothingToDo($needLink);
344 if ( !$opts{i} && !$opts{f} && $StatusHost{backoffTime} > time ) {
345 printf(LOG "%sskipping because of user requested delay (%.1f hours left)\n",
346 $bpc->timeStamp, ($StatusHost{backoffTime} - time) / 3600);
347 NothingToDo($needLink);
351 # Now see if there are any old backups we should delete
353 BackupExpire($client);
355 my(@lastIdxByLevel, $incrCntSinceFull);
358 # Read Backup information, and find times of the most recent full and
359 # incremental backups. Also figure out which backup we will use
360 # as a starting point for an incremental.
362 @Backups = $bpc->BackupInfoRead($client);
363 for ( my $i = 0 ; $i < @Backups ; $i++ ) {
364 $needLink = 1 if ( $Backups[$i]{nFilesNew} eq ""
365 || -f "$Dir/NewFileList.$Backups[$i]{num}" );
366 if ( $Backups[$i]{type} eq "full" ) {
367 $incrCntSinceFull = 0;
368 $lastBkupNum = $Backups[$i]{num};
369 $lastIdxByLevel[0] = $i;
370 if ( $lastFullTime < $Backups[$i]{startTime} ) {
371 $lastFullTime = $Backups[$i]{startTime};
373 } elsif ( $Backups[$i]{type} eq "incr" ) {
375 $lastBkupNum = $Backups[$i]{num};
376 $lastIdxByLevel[$Backups[$i]{level}] = $i;
377 $lastIncrTime = $Backups[$i]{startTime}
378 if ( $lastIncrTime < $Backups[$i]{startTime} );
379 } elsif ( $Backups[$i]{type} eq "partial" ) {
381 $lastPartial = $Backups[$i]{startTime};
382 $partialNum = $Backups[$i]{num};
383 $partialFileCnt = $Backups[$i]{nFiles};
388 # Decide whether we do nothing, or a full or incremental backup.
390 if ( $lastFullTime == 0
392 || (!$opts{i} && (time - $lastFullTime > $Conf{FullPeriod} * 24*3600
393 && time - $lastIncrTime > $Conf{IncrPeriod} * 24*3600)) ) {
396 $incrBaseBkupNum = $lastBkupNum;
397 } elsif ( $opts{i} || (time - $lastIncrTime > $Conf{IncrPeriod} * 24*3600
398 && time - $lastFullTime > $Conf{IncrPeriod} * 24*3600) ) {
401 # For an incremental backup, figure out which level we should
402 # do and the index of the reference backup, which is the most
403 # recent backup at any lower level.
405 @{$Conf{IncrLevels}} = [$Conf{IncrLevels}]
406 unless ref($Conf{IncrLevels}) eq "ARRAY";
407 @{$Conf{IncrLevels}} = [1] if ( !@{$Conf{IncrLevels}} );
408 $incrCntSinceFull = $incrCntSinceFull % @{$Conf{IncrLevels}};
409 $incrLevel = $Conf{IncrLevels}[$incrCntSinceFull];
410 for ( my $i = 0 ; $i < $incrLevel ; $i++ ) {
411 my $idx = $lastIdxByLevel[$i];
412 next if ( !defined($idx) );
413 if ( !defined($incrBaseTime)
414 || $Backups[$idx]{startTime} > $incrBaseTime ) {
415 $incrBaseBkupNum = $Backups[$idx]{num};
416 $incrBaseLevel = $Backups[$idx]{level};
417 $incrBaseTime = $Backups[$idx]{startTime};
421 # Can't find any earlier lower-level backup! Shouldn't
422 # happen - just do full instead
424 if ( !defined($incrBaseBkupNum) || $incrLevel < 1 ) {
426 $incrBaseBkupNum = $lastBkupNum;
429 NothingToDo($needLink);
433 # Create top-level directories if they don't exist
437 "$Conf{TopDir}/pool",
438 "$Conf{TopDir}/cpool",
440 "$Conf{TopDir}/trash",
443 mkpath($dir, 0, 0750);
445 print("Failed to create $dir\n");
446 printf(LOG "%sFailed to create directory %s\n", $bpc->timeStamp, $dir);
447 print("link $clientURI\n") if ( $needLink );
450 printf(LOG "%sCreated directory %s\n", $bpc->timeStamp, $dir);
454 if ( !$bpc->HardlinkTest($Dir, "$TopDir/cpool") ) {
455 print(LOG $bpc->timeStamp, "Can't create a test hardlink between a file"
456 . " in $Dir and $TopDir/cpool. Either these are different"
457 . " file systems, or this file system doesn't support hardlinks,"
458 . " or these directories don't exist, or there is a permissions"
459 . " problem, or the file system is out of inodes or full. Use"
460 . " df, df -i, and ls -ld to check each of these possibilities."
462 print("test hardlink between $Dir and $TopDir/cpool failed\n");
463 print("link $clientURI\n") if ( $needLink );
469 # In the non-DHCP case, make sure the host can be looked up
470 # via NS, or otherwise find the IP address via NetBios.
472 if ( $Conf{ClientNameAlias} ne "" ) {
473 $host = $Conf{ClientNameAlias};
477 if ( !defined(gethostbyname($host)) ) {
479 # Ok, NS doesn't know about it. Maybe it is a NetBios name
482 print(STDERR "Name server doesn't know about $host; trying NetBios\n")
484 if ( !defined($hostIP = $bpc->NetBiosHostIPFind($host)) ) {
485 print(LOG $bpc->timeStamp, "Can't find host $host via netbios\n");
486 print("host not found\n");
495 # Check if $host is alive
497 my $delay = $bpc->CheckHostAlive($hostIP);
499 print(LOG $bpc->timeStamp, "no ping response\n");
500 print("no ping response\n");
501 print("link $clientURI\n") if ( $needLink );
503 } elsif ( $delay > $Conf{PingMaxMsec} ) {
504 printf(LOG "%sping too slow: %.4gmsec\n", $bpc->timeStamp, $delay);
505 printf("ping too slow: %.4gmsec (threshold is %gmsec)\n",
506 $delay, $Conf{PingMaxMsec});
507 print("link $clientURI\n") if ( $needLink );
512 # Make sure it is really the machine we expect (only for fixed addresses,
513 # since we got the DHCP address above).
515 if ( !$opts{d} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
516 print(LOG $bpc->timeStamp, "dump failed: $errMsg\n");
517 print("dump failed: $errMsg\n");
519 } elsif ( $opts{d} ) {
520 print(LOG $bpc->timeStamp, "$host is dhcp $hostIP, user is $user\n");
524 # Get a clean directory $Dir/new
526 $bpc->RmTreeDefer("$TopDir/trash", "$Dir/new") if ( -d "$Dir/new" );
529 # Setup file extension for compression and open XferLOG output file
531 if ( $Conf{CompressLevel} && !BackupPC::FileZIO->compOk ) {
532 print(LOG $bpc->timeStamp, "dump failed: can't find Compress::Zlib\n");
533 print("dump failed: can't find Compress::Zlib\n");
536 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
537 my $XferLOG = BackupPC::FileZIO->open("$Dir/XferLOG$fileExt", 1,
538 $Conf{CompressLevel});
539 if ( !defined($XferLOG) ) {
540 print(LOG $bpc->timeStamp, "dump failed: unable to open/create"
541 . " $Dir/XferLOG$fileExt\n");
542 print("dump failed: unable to open/create $Dir/XferLOG$fileExt\n");
547 # Ignore the partial dump in the case of an incremental
548 # or when the partial is too old. A partial is a partial full.
550 if ( $type ne "full" || time - $lastPartial > $Conf{PartialAgeMax} * 24*3600 ) {
556 # If this is a partial, copy the old XferLOG file
559 my($compress, $fileName);
560 if ( -f "$Dir/XferLOG.$partialNum.z" ) {
561 $fileName = "$Dir/XferLOG.$partialNum.z";
563 } elsif ( -f "$Dir/XferLOG.$partialNum" ) {
564 $fileName = "$Dir/XferLOG.$partialNum";
567 if ( my $oldLOG = BackupPC::FileZIO->open($fileName, 0, $compress) ) {
569 while ( $oldLOG->read(\$data, 65536) > 0 ) {
570 $XferLOG->write(\$data);
576 $XferLOG->writeTeeStderr(1) if ( $opts{v} );
577 unlink("$Dir/NewFileList") if ( -f "$Dir/NewFileList" );
579 my $startTime = time();
583 my $sizeExistComp = 0;
586 my($logMsg, %stat, $xfer, $ShareNames, $noFilesErr);
589 $ShareNames = BackupPC::Xfer::getShareNames(\%Conf);
592 # Run an optional pre-dump command
594 UserCommandRun("DumpPreUserCmd");
595 if ( $? && $Conf{UserCmdCheckStatus} ) {
596 print(LOG $bpc->timeStamp,
597 "DumpPreUserCmd returned error status $?... exiting\n");
598 $XferLOG->write(\"DumpPreUserCmd returned error status $?... exiting\n");
599 $stat{hostError} = "DumpPreUserCmd returned error status $?";
605 # Now backup each of the shares
607 for my $shareName ( @$ShareNames ) {
611 # Convert $shareName to utf8 octets
613 $shareName = encode("utf8", $shareName);
614 $stat{xferOK} = $stat{hostAbort} = undef;
615 $stat{hostError} = $stat{lastOutputLine} = undef;
616 if ( -d "$Dir/new/$shareName" ) {
617 print(LOG $bpc->timeStamp,
618 "unexpected repeated share name $shareName skipped\n");
622 UserCommandRun("DumpPreShareCmd", $shareName);
623 if ( $? && $Conf{UserCmdCheckStatus} ) {
624 print(LOG $bpc->timeStamp,
625 "DumpPreShareCmd returned error status $?... exiting\n");
626 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
627 $XferLOG->write(\"DumpPreShareCmd returned error status $?... exiting\n");
628 $stat{hostError} = "DumpPreShareCmd returned error status $?";
632 $xfer = BackupPC::Xfer::create($Conf{XferMethod}, $bpc);
633 if ( !defined($xfer) ) {
634 my $errStr = BackupPC::Xfer::errStr();
635 print(LOG $bpc->timeStamp, "dump failed: $errStr\n");
636 UserCommandRun("DumpPostShareCmd", $shareName) if ( $NeedPostCmd );
637 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
638 $XferLOG->write(\"BackupPC::Xfer::create failed: $errStr\n");
639 $stat{hostError} = $errStr;
643 my $useTar = $xfer->useTar;
647 # This xfer method outputs a tar format file, so we start a
648 # BackupPC_tarExtract to extract the data.
650 # Create a socketpair to connect the Xfer method to BackupPC_tarExtract
651 # WH is the write handle for writing, provided to the transport
652 # program, and RH is the other end of the socket for reading,
653 # provided to BackupPC_tarExtract.
655 if ( socketpair(RH, WH, AF_UNIX, SOCK_STREAM, PF_UNSPEC) ) {
656 shutdown(RH, 1); # no writing to this socket
657 shutdown(WH, 0); # no reading from this socket
658 setsockopt(RH, SOL_SOCKET, SO_RCVBUF, 8 * 65536);
659 setsockopt(WH, SOL_SOCKET, SO_SNDBUF, 8 * 65536);
662 # Default to pipe() if socketpair() doesn't work.
668 # fork a child for BackupPC_tarExtract. TAR is a file handle
669 # on which we (the parent) read the stdout & stderr from
670 # BackupPC_tarExtract.
672 if ( !defined($tarPid = open(TAR, "-|")) ) {
673 print(LOG $bpc->timeStamp, "can't fork to run tar\n");
674 print("can't fork to run tar\n");
682 # This is the tar child. Close the write end of the pipe,
683 # clone STDERR to STDOUT, clone STDIN from RH, and then
684 # exec BackupPC_tarExtract.
689 open(STDERR, ">&STDOUT");
693 exec("$BinDir/BackupPC_tarExtract", $client, $shareName,
694 $Conf{CompressLevel});
695 print(LOG $bpc->timeStamp,
696 "can't exec $BinDir/BackupPC_tarExtract\n");
699 } elsif ( !defined($newFilesFH) ) {
701 # We need to create the NewFileList output file
704 open(NEW_FILES, ">", "$TopDir/pc/$client/NewFileList")
705 || die("can't open $TopDir/pc/$client/NewFileList");
706 $newFilesFH = *NEW_FILES;
711 # Run the transport program
717 shareName => $shareName,
721 newFilesFH => $newFilesFH,
724 incrBaseTime => $incrBaseTime,
725 incrBaseBkupNum => $incrBaseBkupNum,
726 backups => \@Backups,
727 compress => $Conf{CompressLevel},
728 XferMethod => $Conf{XferMethod},
729 logLevel => $Conf{XferLogLevel},
730 partialNum => $partialNum,
731 pidHandler => \&pidHandler,
732 completionPercent => \&completionPercent,
735 if ( !defined($logMsg = $xfer->start()) ) {
736 my $errStr = "xfer start failed: " . $xfer->errStr . "\n";
737 print(LOG $bpc->timeStamp, $errStr);
739 # kill off the tar process, first nicely then forcefully
742 kill($bpc->sigName2num("INT"), $tarPid);
744 kill($bpc->sigName2num("KILL"), $tarPid);
747 kill($bpc->sigName2num("INT"), @xferPid);
749 kill($bpc->sigName2num("KILL"), @xferPid);
751 UserCommandRun("DumpPostShareCmd", $shareName) if ( $NeedPostCmd );
752 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
753 $XferLOG->write(\"xfer start failed: $errStr\n");
754 $stat{hostError} = $errStr;
758 @xferPid = $xfer->xferPid;
762 # The parent must close both handles on the pipe since the children
763 # are using these handles now.
768 print(LOG $bpc->timeStamp, $logMsg, "\n");
769 $XferLOG->write(\"$logMsg\n");
770 print("started $type dump, share=$shareName\n");
772 pidHandler(@xferPid);
776 # Parse the output of the transfer program and BackupPC_tarExtract
777 # while they run. Since we might be reading from two or more children
780 my($FDread, $tarOut, $mesg);
781 vec($FDread, fileno(TAR), 1) = 1;
782 $xfer->setSelectMask(\$FDread);
786 last if ( $FDread =~ /^\0*$/ );
787 select(my $rout = $FDread, undef, $ein, undef);
788 if ( vec($rout, fileno(TAR), 1) ) {
789 if ( sysread(TAR, $mesg, 8192) <= 0 ) {
790 vec($FDread, fileno(TAR), 1) = 0;
796 while ( $tarOut =~ /(.*?)[\n\r]+(.*)/s ) {
800 $XferLOG->write(\"$_\n");
802 $XferLOG->write(\"tarExtract: $_\n");
804 if ( /^BackupPC_tarExtact aborting \((.*)\)/ ) {
805 $stat{hostError} = $1;
807 if ( /^Done: (\d+) errors, (\d+) filesExist, (\d+) sizeExist, (\d+) sizeExistComp, (\d+) filesTotal, (\d+) sizeTotal/ ) {
811 $sizeExistComp += $4;
816 last if ( !$xfer->readOutput(\$FDread, $rout) );
817 while ( my $str = $xfer->logMsgGet ) {
818 print(LOG $bpc->timeStamp, "xfer: $str\n");
820 if ( $xfer->getStats->{fileCnt} == 1 ) {
822 # Make sure it is still the machine we expect. We do this while
823 # the transfer is running to avoid a potential race condition if
824 # the ip address was reassigned by dhcp just before we started
827 if ( my $errMsg = CorrectHostCheck($hostIP, $host) ) {
828 $stat{hostError} = $errMsg if ( $stat{hostError} eq "" );
835 # otherwise the xfer module does everything for us
837 my @results = $xfer->run();
838 $tarErrs += $results[0];
839 $nFilesExist += $results[1];
840 $sizeExist += $results[2];
841 $sizeExistComp += $results[3];
842 $nFilesTotal += $results[4];
843 $sizeTotal += $results[5];
847 # Merge the xfer status (need to accumulate counts)
849 my $newStat = $xfer->getStats;
850 if ( $newStat->{fileCnt} == 0 ) {
851 $noFilesErr ||= "No files dumped for share $shareName";
853 foreach my $k ( (keys(%stat), keys(%$newStat)) ) {
854 next if ( !defined($newStat->{$k}) );
855 if ( $k =~ /Cnt$/ ) {
856 $stat{$k} += $newStat->{$k};
857 delete($newStat->{$k});
860 if ( !defined($stat{$k}) ) {
861 $stat{$k} = $newStat->{$k};
862 delete($newStat->{$k});
867 if ( $NeedPostCmd ) {
868 UserCommandRun("DumpPostShareCmd", $shareName);
869 if ( $? && $Conf{UserCmdCheckStatus} ) {
870 print(LOG $bpc->timeStamp,
871 "DumpPostShareCmd returned error status $?... exiting\n");
872 $stat{hostError} = "DumpPostShareCmd returned error status $?";
876 $stat{xferOK} = 0 if ( $stat{hostError} || $stat{hostAbort} );
877 if ( !$stat{xferOK} ) {
879 # kill off the transfer program, first nicely then forcefully
882 kill($bpc->sigName2num("INT"), @xferPid);
884 kill($bpc->sigName2num("KILL"), @xferPid);
887 # kill off the tar process, first nicely then forcefully
890 kill($bpc->sigName2num("INT"), $tarPid);
892 kill($bpc->sigName2num("KILL"), $tarPid);
895 # don't do any more shares on this host
902 # If this is a full, and any share had zero files then consider the dump bad
904 if ( $type eq "full" && $stat{hostError} eq ""
905 && length($noFilesErr) && $Conf{BackupZeroFilesIsFatal} ) {
906 $stat{hostError} = $noFilesErr;
910 $stat{xferOK} = 0 if ( $Abort );
913 # If there is no "new" directory then the backup is bad
915 if ( $stat{xferOK} && !-d "$Dir/new" ) {
916 $stat{hostError} = "No backup directory $Dir/new"
917 if ( $stat{hostError} eq "" );
922 # Do one last check to make sure it is still the machine we expect.
924 if ( $stat{xferOK} && (my $errMsg = CorrectHostCheck($hostIP, $host)) ) {
925 $stat{hostError} = $errMsg;
929 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
930 if ( $? && $Conf{UserCmdCheckStatus} ) {
931 print(LOG $bpc->timeStamp,
932 "DumpPostUserCmd returned error status $?... exiting\n");
933 $stat{hostError} = "DumpPostUserCmd returned error status $?";
936 close($newFilesFH) if ( defined($newFilesFH) );
938 my $endTime = time();
941 # If the dump failed, clean up
943 if ( !$stat{xferOK} ) {
944 $stat{hostError} = $stat{lastOutputLine} if ( $stat{hostError} eq "" );
945 if ( $stat{hostError} ) {
946 print(LOG $bpc->timeStamp,
947 "Got fatal error during xfer ($stat{hostError})\n");
948 $XferLOG->write(\"Got fatal error during xfer ($stat{hostError})\n");
952 # wait a short while and see if the system is still alive
955 if ( $bpc->CheckHostAlive($hostIP) < 0 ) {
956 $stat{hostAbort} = 1;
958 if ( $stat{hostAbort} ) {
959 $stat{hostError} = "lost network connection during backup";
961 print(LOG $bpc->timeStamp, "Backup aborted ($stat{hostError})\n");
962 $XferLOG->write(\"Backup aborted ($stat{hostError})\n");
964 $XferLOG->write(\"Backup aborted by user signal\n");
968 # Close the log file and call BackupFailCleanup, which exits.
973 my $newNum = BackupSave();
975 my $otherCount = $stat{xferErrCnt} - $stat{xferBadFileCnt}
976 - $stat{xferBadShareCnt};
977 $stat{fileCnt} ||= 0;
978 $stat{byteCnt} ||= 0;
979 $stat{xferErrCnt} ||= 0;
980 $stat{xferBadFileCnt} ||= 0;
981 $stat{xferBadShareCnt} ||= 0;
982 print(LOG $bpc->timeStamp,
983 "$type backup $newNum complete, $stat{fileCnt} files,"
984 . " $stat{byteCnt} bytes,"
985 . " $stat{xferErrCnt} xferErrs ($stat{xferBadFileCnt} bad files,"
986 . " $stat{xferBadShareCnt} bad shares, $otherCount other)\n");
988 BackupExpire($client);
990 print("$type backup complete\n");
992 ###########################################################################
994 ###########################################################################
1000 print("nothing to do\n");
1001 print("link $clientURI\n") if ( $needLink );
1007 my $sigName = shift;
1010 # The first time we receive a signal we try to gracefully
1011 # abort the backup. This allows us to keep a partial dump
1012 # with the in-progress file deleted and attribute caches
1013 # flushed to disk etc.
1015 if ( !length($SigName) ) {
1017 if ( $sigName eq "INT" ) {
1018 $reason = "aborted by user (signal=$sigName)";
1020 $reason = "aborted by signal=$sigName";
1024 # Parent logs a message
1026 print(LOG $bpc->timeStamp,
1027 "Aborting backup up after signal $sigName\n");
1030 # Tell xfer to abort, but only if we actually started one
1032 $xfer->abort($reason) if ( defined($xfer) );
1035 # Send ALRMs to BackupPC_tarExtract if we are using it
1037 if ( $tarPid > 0 ) {
1038 kill($bpc->sigName2num("ARLM"), $tarPid);
1042 # Schedule a 20 second timer in case the clean
1043 # abort doesn't complete
1048 # Children ignore anything other than ALRM and INT
1050 if ( $sigName ne "ALRM" && $sigName ne "INT" ) {
1055 # The child also tells xfer to abort
1057 $xfer->abort($reason);
1060 # Schedule a 15 second timer in case the clean
1061 # abort doesn't complete
1065 $SigName = $sigName;
1071 # This is a second signal: time to clean up.
1073 if ( $Pid != $$ && ($sigName eq "ALRM" || $sigName eq "INT") ) {
1075 # Children quit quietly on ALRM or INT
1081 # Ignore other signals in children
1083 return if ( $Pid != $$ );
1085 $SIG{$sigName} = 'IGNORE';
1086 UserCommandRun("DumpPostUserCmd") if ( $NeedPostCmd );
1087 $XferLOG->write(\"exiting after signal $sigName\n");
1089 kill($bpc->sigName2num("INT"), @xferPid);
1091 kill($bpc->sigName2num("KILL"), @xferPid);
1093 if ( $tarPid > 0 ) {
1094 kill($bpc->sigName2num("INT"), $tarPid);
1096 kill($bpc->sigName2num("KILL"), $tarPid);
1098 if ( $sigName eq "INT" ) {
1099 $stat{hostError} = "aborted by user (signal=$sigName)";
1101 $stat{hostError} = "received signal=$sigName";
1103 BackupFailCleanup();
1106 sub CheckForNewFiles
1108 if ( -f _ && $File::Find::name !~ /\/fattrib$/ ) {
1112 # No need to check entire tree
1114 $File::Find::prune = 1 if ( $nFilesTotal );
1118 sub BackupFailCleanup
1120 my $fileExt = $Conf{CompressLevel} > 0 ? ".z" : "";
1121 my $keepPartial = 0;
1124 # We keep this backup if it is a full and we actually backed
1125 # up some files. If the prior backup was a partial too, we
1126 # only keep this backup if it has more files than the previous
1129 if ( $type eq "full" ) {
1130 if ( $nFilesTotal == 0 && $xfer->getStats->{fileCnt} == 0 ) {
1132 # Xfer didn't report any files, but check in the new
1133 # directory just in case.
1135 find(\&CheckForNewFiles, "$Dir/new");
1138 if ( $nFilesTotal > $partialFileCnt
1139 || $xfer->getStats->{fileCnt} > $partialFileCnt ) {
1141 # If the last backup wasn't a partial then
1142 # $partialFileCnt is undefined, so the above
1143 # test is simply $nFilesTotal > 0
1146 if ( $partialFileCnt ) {
1147 $str = "Saving this as a partial backup\n";
1149 $str = sprintf("Saving this as a partial backup, replacing the"
1150 . " prior one (got %d and %d files versus %d)\n",
1151 $nFilesTotal, $xfer->getStats->{fileCnt}, $partialFileCnt);
1154 $str = sprintf("Not saving this as a partial backup since it has fewer"
1155 . " files than the prior one (got %d and %d files versus %d)\n",
1156 $nFilesTotal, $xfer->getStats->{fileCnt}, $partialFileCnt);
1158 $XferLOG->write(\$str);
1162 # Don't keep partials if they are disabled
1164 $keepPartial = 0 if ( $Conf{PartialAgeMax} < 0 );
1166 if ( !$keepPartial ) {
1168 # No point in saving this dump; get rid of eveything.
1171 unlink("$Dir/timeStamp.level0") if ( -f "$Dir/timeStamp.level0" );
1172 unlink("$Dir/SmbLOG.bad") if ( -f "$Dir/SmbLOG.bad" );
1173 unlink("$Dir/SmbLOG.bad$fileExt") if ( -f "$Dir/SmbLOG.bad$fileExt" );
1174 unlink("$Dir/XferLOG.bad") if ( -f "$Dir/XferLOG.bad" );
1175 unlink("$Dir/XferLOG.bad$fileExt") if ( -f "$Dir/XferLOG.bad$fileExt" );
1176 unlink("$Dir/NewFileList") if ( -f "$Dir/NewFileList" );
1177 rename("$Dir/XferLOG$fileExt", "$Dir/XferLOG.bad$fileExt");
1178 $bpc->RmTreeDefer("$TopDir/trash", "$Dir/new") if ( -d "$Dir/new" );
1179 print("dump failed: $stat{hostError}\n");
1181 print("link $clientURI\n") if ( $needLink );
1185 # Ok, now we should save this as a partial dump
1188 my $newNum = BackupSave();
1189 print("dump failed: $stat{hostError}\n");
1190 print("link $clientURI\n") if ( $needLink );
1191 print(LOG $bpc->timeStamp, "Saved partial dump $newNum\n");
1196 # Decide which old backups should be expired by moving them
1202 my($Dir) = "$TopDir/pc/$client";
1203 my(@Backups) = $bpc->BackupInfoRead($client);
1204 my($cntFull, $cntIncr, $firstFull, $firstIncr, $oldestIncr,
1205 $oldestFull, $changes);
1207 if ( $Conf{FullKeepCnt} <= 0 ) {
1208 print(LOG $bpc->timeStamp,
1209 "Invalid value for \$Conf{FullKeepCnt}=$Conf{FullKeepCnt}\n");
1211 "Invalid value for \$Conf{FullKeepCnt}=$Conf{FullKeepCnt}\n")
1216 $cntFull = $cntIncr = 0;
1217 $oldestIncr = $oldestFull = 0;
1218 for ( my $i = 0 ; $i < @Backups ; $i++ ) {
1219 if ( $Backups[$i]{type} eq "full" ) {
1220 $firstFull = $i if ( $cntFull == 0 );
1222 } elsif ( $Backups[$i]{type} eq "incr" ) {
1223 $firstIncr = $i if ( $cntIncr == 0 );
1227 $oldestIncr = (time - $Backups[$firstIncr]{startTime}) / (24 * 3600)
1228 if ( $cntIncr > 0 );
1229 $oldestFull = (time - $Backups[$firstFull]{startTime}) / (24 * 3600)
1230 if ( $cntFull > 0 );
1233 # With multi-level incrementals, several of the following
1234 # incrementals might depend upon this one, so we have to
1235 # delete all of the them. Figure out if that is possible
1236 # by counting the number of consecutive incrementals that
1237 # are unfilled and have a level higher than this one.
1240 my $earliestIncr = $oldestIncr;
1242 for ( my $i = $firstIncr + 1 ; $i < @Backups ; $i++ ) {
1243 last if ( $Backups[$i]{level} <= $Backups[$firstIncr]{level}
1244 || !$Backups[$i]{noFill} );
1246 $earliestIncr = (time - $Backups[$i]{startTime}) / (24 * 3600);
1249 if ( $cntIncr >= $Conf{IncrKeepCnt} + $cntIncrDel
1250 || ($cntIncr >= $Conf{IncrKeepCntMin} + $cntIncrDel
1251 && $earliestIncr > $Conf{IncrAgeMax}) ) {
1253 # Only delete an incr backup if the Conf settings are satisfied
1254 # for all $cntIncrDel incrementals. Since BackupRemove() does
1255 # a splice() we need to do the deletes in the reverse order.
1257 for ( my $i = $firstIncr + $cntIncrDel - 1 ;
1258 $i >= $firstIncr ; $i-- ) {
1259 print(LOG $bpc->timeStamp,
1260 "removing incr backup $Backups[$i]{num}\n");
1261 BackupRemove($client, \@Backups, $i);
1268 # Delete any old full backups, according to $Conf{FullKeepCntMin}
1269 # and $Conf{FullAgeMax}.
1271 # First make sure that $Conf{FullAgeMax} is at least bigger
1272 # than $Conf{FullPeriod} * $Conf{FullKeepCnt}, including
1273 # the exponential array case.
1275 my $fullKeepCnt = $Conf{FullKeepCnt};
1276 $fullKeepCnt = [$fullKeepCnt] if ( ref($fullKeepCnt) ne "ARRAY" );
1278 my $fullPeriod = int(0.5 + $Conf{FullPeriod});
1279 $fullPeriod = 7 if ( $fullPeriod <= 0 );
1280 for ( my $i = 0 ; $i < @$fullKeepCnt ; $i++ ) {
1281 $fullAgeMax += $fullKeepCnt->[$i] * $fullPeriod;
1284 $fullAgeMax += $fullPeriod; # add some buffer
1286 if ( $cntFull > $Conf{FullKeepCntMin}
1287 && $oldestFull > $Conf{FullAgeMax}
1288 && $oldestFull > $fullAgeMax
1289 && $Conf{FullKeepCntMin} > 0
1290 && $Conf{FullAgeMax} > 0
1291 && (@Backups <= $firstFull + 1
1292 || !$Backups[$firstFull + 1]{noFill}) ) {
1294 # Only delete a full backup if the Conf settings are satisfied.
1295 # We also must make sure that either this backup is the most
1296 # recent one, or the next backup is filled.
1297 # (We can't deleted a full backup if the next backup is not
1300 print(LOG $bpc->timeStamp,
1301 "removing old full backup $Backups[$firstFull]{num}\n");
1302 BackupRemove($client, \@Backups, $firstFull);
1308 # Do new-style full backup expiry, which includes the the case
1309 # where $Conf{FullKeepCnt} is an array.
1311 last if ( !BackupFullExpire($client, \@Backups) );
1314 $bpc->BackupInfoWrite($client, @Backups) if ( $changes );
1318 # Handle full backup expiry, using exponential periods.
1320 sub BackupFullExpire
1322 my($client, $Backups) = @_;
1324 my $fullPeriod = $Conf{FullPeriod};
1325 my $origFullPeriod = $fullPeriod;
1326 my $fullKeepCnt = $Conf{FullKeepCnt};
1327 my $fullKeepIdx = 0;
1328 my(@delete, @fullList);
1331 # Don't delete anything if $Conf{FullPeriod} or $Conf{FullKeepCnt} are
1332 # not defined - possibly a corrupted config.pl file.
1334 return if ( !defined($Conf{FullPeriod}) || !defined($Conf{FullKeepCnt}) );
1337 # If regular backups are still disabled with $Conf{FullPeriod} < 0,
1338 # we still expire backups based on a typical FullPeriod value - weekly.
1340 $fullPeriod = 7 if ( $fullPeriod <= 0 );
1342 $fullKeepCnt = [$fullKeepCnt] if ( ref($fullKeepCnt) ne "ARRAY" );
1344 for ( my $i = 0 ; $i < @$Backups ; $i++ ) {
1345 next if ( $Backups->[$i]{type} ne "full" );
1346 push(@fullList, $i);
1348 for ( my $k = @fullList - 1 ; $k >= 0 ; $k-- ) {
1349 my $i = $fullList[$k];
1350 my $prevFull = $fullList[$k-1] if ( $k > 0 );
1352 # Don't delete any full that is followed by an unfilled backup,
1353 # since it is needed for restore.
1355 my $noDelete = $i + 1 < @$Backups ? $Backups->[$i+1]{noFill} : 0;
1358 ($fullKeepIdx >= @$fullKeepCnt
1361 && $Backups->[$i]{startTime} - $Backups->[$prevFull]{startTime}
1362 < ($fullPeriod - $origFullPeriod / 2) * 24 * 3600
1366 # Delete the full backup
1368 #print("Deleting backup $i ($prevFull)\n");
1369 unshift(@delete, $i);
1372 while ( $fullKeepIdx < @$fullKeepCnt
1373 && $fullCnt >= $fullKeepCnt->[$fullKeepIdx] ) {
1376 $fullPeriod = 2 * $fullPeriod;
1381 # Now actually delete the backups
1383 for ( my $i = @delete - 1 ; $i >= 0 ; $i-- ) {
1384 print(LOG $bpc->timeStamp,
1385 "removing full backup $Backups->[$delete[$i]]{num}\n");
1386 BackupRemove($client, $Backups, $delete[$i]);
1392 # Removes any partial backups
1394 sub BackupPartialRemove
1396 my($client, $Backups) = @_;
1398 for ( my $i = @$Backups - 1 ; $i >= 0 ; $i-- ) {
1399 next if ( $Backups->[$i]{type} ne "partial" );
1400 BackupRemove($client, $Backups, $i);
1406 my @Backups = $bpc->BackupInfoRead($client);
1411 # Since we got a good backup we should remove any partial dumps
1412 # (the new backup might also be a partial, but that's ok).
1414 BackupPartialRemove($client, \@Backups);
1415 $needLink = 1 if ( -f "$Dir/NewFileList" );
1418 # Number the new backup
1420 for ( my $i = 0 ; $i < @Backups ; $i++ ) {
1421 $num = $Backups[$i]{num} if ( $num < $Backups[$i]{num} );
1424 $bpc->RmTreeDefer("$TopDir/trash", "$Dir/$num") if ( -d "$Dir/$num" );
1425 if ( !rename("$Dir/new", "$Dir/$num") ) {
1426 print(LOG $bpc->timeStamp, "Rename $Dir/new -> $Dir/$num failed\n");
1432 # Add the new backup information to the backup file
1435 $Backups[$i]{num} = $num;
1436 $Backups[$i]{type} = $type;
1437 $Backups[$i]{startTime} = $startTime;
1438 $Backups[$i]{endTime} = $endTime;
1439 $Backups[$i]{size} = $sizeTotal;
1440 $Backups[$i]{nFiles} = $nFilesTotal;
1441 $Backups[$i]{xferErrs} = $stat{xferErrCnt} || 0;
1442 $Backups[$i]{xferBadFile} = $stat{xferBadFileCnt} || 0;
1443 $Backups[$i]{xferBadShare} = $stat{xferBadShareCnt} || 0;
1444 $Backups[$i]{nFilesExist} = $nFilesExist;
1445 $Backups[$i]{sizeExist} = $sizeExist;
1446 $Backups[$i]{sizeExistComp} = $sizeExistComp;
1447 $Backups[$i]{tarErrs} = $tarErrs;
1448 $Backups[$i]{compress} = $Conf{CompressLevel};
1449 $Backups[$i]{noFill} = $type eq "incr" ? 1 : 0;
1450 $Backups[$i]{level} = $incrLevel;
1451 $Backups[$i]{mangle} = 1; # name mangling always on for v1.04+
1452 $Backups[$i]{xferMethod} = $Conf{XferMethod};
1453 $Backups[$i]{charset} = $Conf{ClientCharset};
1454 $Backups[$i]{version} = $bpc->Version();
1456 # Save the main backups file
1458 $bpc->BackupInfoWrite($client, @Backups);
1460 # Save just this backup's info in case the main backups file
1463 BackupPC::Storage->backupInfoWrite($Dir, $Backups[$i]{num},
1466 unlink("$Dir/timeStamp.level0") if ( -f "$Dir/timeStamp.level0" );
1467 foreach my $ext ( qw(bad bad.z) ) {
1468 next if ( !-f "$Dir/XferLOG.$ext" );
1469 unlink("$Dir/XferLOG.$ext.old") if ( -f "$Dir/XferLOG.$ext" );
1470 rename("$Dir/XferLOG.$ext", "$Dir/XferLOG.$ext.old");
1474 # Now remove the bad files, replacing them if possible with links to
1477 foreach my $f ( $xfer->getBadFiles ) {
1479 my $shareM = $bpc->fileNameEltMangle($f->{share});
1480 my $fileM = $bpc->fileNameMangle($f->{file});
1481 unlink("$Dir/$num/$shareM/$fileM");
1482 for ( $j = $i - 1 ; $j >= 0 ; $j-- ) {
1484 if ( $Backups[$j]{mangle} ) {
1485 $file = "$shareM/$fileM";
1487 $file = "$f->{share}/$f->{file}";
1489 next if ( !-f "$Dir/$Backups[$j]{num}/$file" );
1491 my($exists, $digest, $origSize, $outSize, $errs)
1492 = BackupPC::PoolWrite::LinkOrCopy(
1494 "$Dir/$Backups[$j]{num}/$file",
1495 $Backups[$j]{compress},
1496 "$Dir/$num/$shareM/$fileM",
1497 $Conf{CompressLevel});
1500 # the hard link failed, most likely because the target
1501 # file has too many links. We have copied the file
1502 # instead, so add this to the new file list.
1504 if ( !defined($newFilesFH) ) {
1505 my $str = "Appending to NewFileList for $shareM/$fileM\n";
1506 $XferLOG->write(\$str);
1507 open($newFilesFH, ">>", "$TopDir/pc/$client/NewFileList")
1508 || die("can't open $TopDir/pc/$client/NewFileList");
1509 binmode($newFilesFH);
1511 if ( -f "$Dir/$num/$shareM/$fileM" ) {
1512 print($newFilesFH "$digest $origSize $shareM/$fileM\n");
1514 my $str = "Unable to link/copy $num/$f->{share}/$f->{file}"
1515 . " to $Backups[$j]{num}/$f->{share}/$f->{file}\n";
1516 $XferLOG->write(\$str);
1519 my $str = "Bad file $num/$f->{share}/$f->{file} replaced"
1521 . " $Backups[$j]{num}/$f->{share}/$f->{file}\n";
1522 $XferLOG->write(\$str);
1527 my $str = "Removed bad file $num/$f->{share}/$f->{file}"
1528 . " (no older copy to link to)\n";
1529 $XferLOG->write(\$str);
1532 close($newFilesFH) if ( defined($newFilesFH) );
1534 rename("$Dir/XferLOG$fileExt", "$Dir/XferLOG.$num$fileExt");
1535 rename("$Dir/NewFileList", "$Dir/NewFileList.$num");
1541 # Removes a specific backup
1545 my($client, $Backups, $idx) = @_;
1546 my($Dir) = "$TopDir/pc/$client";
1548 if ( $Backups->[$idx]{num} eq "" ) {
1549 print("BackupRemove: ignoring empty backup number for idx $idx\n");
1553 $bpc->RmTreeDefer("$TopDir/trash",
1554 "$Dir/$Backups->[$idx]{num}");
1555 unlink("$Dir/SmbLOG.$Backups->[$idx]{num}")
1556 if ( -f "$Dir/SmbLOG.$Backups->[$idx]{num}" );
1557 unlink("$Dir/SmbLOG.$Backups->[$idx]{num}.z")
1558 if ( -f "$Dir/SmbLOG.$Backups->[$idx]{num}.z" );
1559 unlink("$Dir/XferLOG.$Backups->[$idx]{num}")
1560 if ( -f "$Dir/XferLOG.$Backups->[$idx]{num}" );
1561 unlink("$Dir/XferLOG.$Backups->[$idx]{num}.z")
1562 if ( -f "$Dir/XferLOG.$Backups->[$idx]{num}.z" );
1563 splice(@{$Backups}, $idx, 1);
1566 sub CorrectHostCheck
1568 my($hostIP, $host) = @_;
1569 return if ( $hostIP eq $host && !$Conf{FixedIPNetBiosNameCheck}
1570 || $Conf{NmbLookupCmd} eq "" );
1571 my($netBiosHost, $netBiosUser) = $bpc->NetBiosInfoGet($hostIP);
1572 return "host $host has mismatching netbios name $netBiosHost"
1573 if ( lc($netBiosHost) ne lc(substr($host, 0, 15)) );
1578 # The Xfer method might tell us from time to time about processes
1579 # it forks. We tell BackupPC about this (for status displays) and
1580 # keep track of the pids in case we cancel the backup
1585 @xferPid = grep(/./, @xferPid);
1586 return if ( !@xferPid && $tarPid < 0 );
1587 my @pids = @xferPid;
1588 push(@pids, $tarPid) if ( $tarPid > 0 );
1589 my $str = join(",", @pids);
1590 $XferLOG->write(\"Xfer PIDs are now $str\n") if ( defined($XferLOG) );
1591 print("xferPids $str\n");
1595 # The Xfer method might tell us from time to time about progress
1596 # in the backup or restore
1598 sub completionPercent
1602 $percent = 100 if ( $percent > 100 );
1603 $percent = 0 if ( $percent < 0 );
1604 if ( !defined($completionPercent)
1605 || int($completionPercent + 0.5) != int($percent) ) {
1606 printf("completionPercent %.0f\n", $percent);
1608 $completionPercent = $percent;
1612 # Run an optional pre- or post-dump command
1616 my($cmdType, $sharename) = @_;
1618 return if ( !defined($Conf{$cmdType}) );
1624 user => $Hosts->{$client}{user},
1625 moreUsers => $Hosts->{$client}{moreUsers},
1626 share => $ShareNames->[0],
1627 shares => $ShareNames,
1628 XferMethod => $Conf{XferMethod},
1629 sshPath => $Conf{SshPath},
1631 XferLOG => $XferLOG,
1633 xferOK => $stat{xferOK} || 0,
1634 hostError => $stat{hostError},
1636 cmdType => $cmdType,
1639 if ($cmdType eq 'DumpPreShareCmd' || $cmdType eq 'DumpPostShareCmd') {
1640 $vars->{share} = $sharename;
1643 my $cmd = $bpc->cmdVarSubstitute($Conf{$cmdType}, $vars);
1644 $XferLOG->write(\"Executing $cmdType: @$cmd\n");
1646 # Run the user's command, dumping the stdout/stderr into the
1647 # Xfer log file. Also supply the optional $vars and %Conf in
1648 # case the command is really perl code instead of a shell
1651 $bpc->cmdSystemOrEval($cmd,
1653 $XferLOG->write(\$_[0]);
1654 print(LOG $bpc->timeStamp, "Output from $cmdType: ", $_[0]);