2 #============================================================= -*-perl-*-
4 # BackupPC: Main program for PC backups.
8 # BackupPC reads the configuration and status information from
9 # $ConfDir/conf. It then runs and manages all the backup activity.
11 # As specified by $Conf{WakeupSchedule}, BackupPC wakes up periodically
12 # to queue backups on all the PCs. This is a four step process:
13 # 1) For each host and DHCP address backup requests are queued on the
14 # background command queue.
15 # 2) For each PC, BackupPC_dump is forked. Several of these may
16 # be run in parallel, based on the configuration.
17 # 3) For each complete, good, backup, BackupPC_link is forked.
18 # Only one of these tasks runs at a time.
19 # 4) In the background BackupPC_trashClean is run to remove any expired
20 # backups. Once each night, BackupPC_nightly is run to complete some
21 # additional administrative tasks (pool cleaning etc).
23 # BackupPC also listens for connections on a unix domain socket and
24 # the tcp port $Conf{ServerPort}, which are used by various
25 # sub-programs and the CGI script BackupPC_Admin for status reporting
26 # and user-initiated backup or backup cancel requests.
29 # Craig Barratt <cbarratt@users.sourceforge.net>
32 # Copyright (C) 2001-2003 Craig Barratt
34 # This program is free software; you can redistribute it and/or modify
35 # it under the terms of the GNU General Public License as published by
36 # the Free Software Foundation; either version 2 of the License, or
37 # (at your option) any later version.
39 # This program is distributed in the hope that it will be useful,
40 # but WITHOUT ANY WARRANTY; without even the implied warranty of
41 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
42 # GNU General Public License for more details.
44 # You should have received a copy of the GNU General Public License
45 # along with this program; if not, write to the Free Software
46 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
48 #========================================================================
50 # Version 3.0.0beta2, released 18 Nov 2006.
52 # See http://backuppc.sourceforge.net.
54 #========================================================================
58 use vars qw(%Status %Info $Hosts);
59 use lib "/usr/local/BackupPC/lib";
61 use BackupPC::FileZIO;
71 ###########################################################################
72 # Handle command line options
73 ###########################################################################
75 if ( !getopts("d", \%opts) || @ARGV != 0 ) {
76 print("usage: $0 [-d]\n");
80 ###########################################################################
81 # Initialize major data structures and variables
82 ###########################################################################
85 # Get an instance of BackupPC::Lib and get some shortcuts.
87 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
88 my $TopDir = $bpc->TopDir();
89 my $BinDir = $bpc->BinDir();
90 my $LogDir = $bpc->LogDir();
91 my %Conf = $bpc->Conf();
94 # Verify we are running as the correct user
96 if ( $Conf{BackupPCUserVerify}
97 && $> != (my $uid = (getpwnam($Conf{BackupPCUser}))[2]) ) {
98 die "Wrong user: my userid is $>, instead of $uid ($Conf{BackupPCUser})\n";
102 # %Status maintain status information about each host.
103 # It is a hash of hashes, whose first index is the host.
108 # %Info is a hash giving general information about BackupPC status.
115 if ( -f "$LogDir/status.pl" && !(my $ret = do "$LogDir/status.pl") ) {
117 print STDERR "couldn't parse $LogDir/status.pl: $@";
118 } elsif ( !defined($ret) ) {
119 print STDERR "couldn't do $LogDir/status.pl: $!";
121 print STDERR "couldn't run $LogDir/status.pl";
126 # %Jobs maintains information about currently running jobs.
127 # It is a hash of hashes, whose first index is the host.
132 # There are three command queues:
133 # - @UserQueue is a queue of user initiated backup requests.
134 # - @BgQueue is a queue of automatically scheduled backup requests.
135 # - @CmdQueue is a queue of administrative jobs, including tasks
136 # like BackupPC_link, BackupPC_trashClean, and BackupPC_nightly
137 # Each queue is an array of hashes. Each hash stores information
138 # about the command request.
145 # To quickly lookup if a given host is on a given queue, we keep
146 # a hash of flags for each queue type.
148 my(%CmdQueueOn, %UserQueueOn, %BgQueueOn);
151 # One or more clients can connect to the server to get status information
152 # or request/cancel backups etc. The %Clients hash maintains information
153 # about each of these socket connections. The hash key is an incrementing
154 # number stored in $ClientConnCnt. Each entry is a hash that contains
155 # various information about the client connection.
161 # Read file descriptor mask used by select(). Every file descriptor
162 # on which we expect to read (or accept) has the corresponding bit
168 # Unix seconds when we next wakeup. A value of zero forces the scheduler
169 # to compute the next wakeup time.
174 # Name of signal saved by catch_signal
181 my($RunNightlyWhenIdle, $FirstWakeup, $CmdJob, $ServerInetPort);
182 my($BackupPCNightlyJobs, $BackupPCNightlyLock);
185 # Complete the rest of the initialization
189 ###########################################################################
191 ###########################################################################
195 # Check if we can/should run BackupPC_nightly
197 Main_TryToRun_nightly();
200 # Check if we can run a new command from @CmdQueue.
202 Main_TryToRun_CmdQueue();
205 # Check if we can run a new command from @UserQueue or @BgQueue.
207 Main_TryToRun_Bg_or_User_Queue();
210 # Do a select() to wait for the next interesting thing to happen
211 # (timeout, signal, someone sends a message, child dies etc).
213 my $fdRead = Main_Select();
216 # Process a signal if we received one.
219 Main_Process_Signal();
224 # Check if a timeout has occurred.
226 Main_Check_Timeout();
229 # Check for, and process, any messages (output) from our jobs
231 Main_Check_Job_Messages($fdRead);
234 # Check for, and process, any output from our clients. Also checks
235 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
237 Main_Check_Client_Messages($fdRead);
240 ############################################################################
243 # Main initialization routine. Called once at statup.
244 ############################################################################
247 umask($Conf{UmaskMode});
250 # Check for another running process, check that PASSWD is set and
251 # verify executables are configured correctly.
253 if ( $Info{pid} ne "" && kill(0, $Info{pid}) ) {
254 print(STDERR $bpc->timeStamp,
255 "Another BackupPC is running (pid $Info{pid}); quitting...\n");
258 foreach my $progName ( qw(SmbClientPath NmbLookupPath PingPath DfPath
259 SendmailPath SshPath) ) {
260 next if ( $Conf{$progName} eq "" || -x $Conf{$progName} );
261 print(STDERR $bpc->timeStamp,
262 "\$Conf{$progName} = '$Conf{$progName}' is not a"
263 . " valid executable program\n");
269 # daemonize by forking; more robust method per:
270 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=301057
273 defined($pid = fork) or die("Can't fork: $!");
274 exit if( $pid ); # parent exits
277 defined($pid = fork) or die("Can't fork: $!");
278 exit if $pid; # parent exits
280 chdir ("/") or die("Cannot chdir to /: $!\n");
282 open(STDIN , ">/dev/null") or die("Cannot open /dev/null as stdin\n");
283 # STDOUT and STDERR are handled in LogFileOpen() right below,
284 # otherwise we would have to reopen them too.
288 # Open the LOG file and redirect STDOUT, STDERR etc
293 # Read the hosts file (force a read).
295 exit(1) if ( !HostsUpdate(1) );
298 # Clean up %ENV for taint checking
300 delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
301 $ENV{PATH} = $Conf{MyPath};
304 # Initialize server sockets
309 # Catch various signals
311 foreach my $sig ( qw(INT BUS SEGV PIPE TERM ALRM HUP) ) {
312 $SIG{$sig} = \&catch_signal;
316 # Report that we started, and update %Info.
318 print(LOG $bpc->timeStamp, "BackupPC started, pid $$\n");
319 $Info{ConfigModTime} = $bpc->ConfigMTime();
321 $Info{startTime} = time;
322 $Info{ConfigLTime} = time;
323 $Info{Version} = $bpc->{Version};
326 # Update the status left over form the last time BackupPC ran.
327 # Requeue any pending links.
329 foreach my $host ( sort(keys(%$Hosts)) ) {
330 if ( $Status{$host}{state} eq "Status_backup_in_progress" ) {
332 # should we restart it? skip it for now.
334 $Status{$host}{state} = "Status_idle";
335 } elsif ( $Status{$host}{state} eq "Status_link_pending"
336 || $Status{$host}{state} eq "Status_link_running" ) {
339 $Status{$host}{state} = "Status_idle";
341 $Status{$host}{activeJob} = 0;
343 foreach my $host ( sort(keys(%Status)) ) {
344 next if ( defined($Hosts->{$host}) );
345 delete($Status{$host});
349 # Write out our initial status and save our PID
352 unlink("$LogDir/BackupPC.pid");
353 if ( open(PID, ">", "$LogDir/BackupPC.pid") ) {
356 chmod(0444, "$LogDir/BackupPC.pid");
360 # For unknown reasons there is a very infrequent error about not
361 # being able to coerce GLOBs inside the XS Data::Dumper. I've
362 # only seen this on a particular platform and perl version.
363 # For now the workaround appears to be use the perl version of
366 $Data::Dumper::Useqq = 1;
369 ############################################################################
370 # Main_TryToRun_nightly()
372 # Checks to see if we can/should run BackupPC_nightly or
373 # BackupPC_trashClean. If so we push the appropriate command onto
375 ############################################################################
376 sub Main_TryToRun_nightly
379 # Check if we should run BackupPC_nightly or BackupPC_trashClean.
380 # BackupPC_nightly is run when the current job queue is empty.
381 # BackupPC_trashClean is run in the background always.
383 my $trashCleanRunning = defined($Jobs{$bpc->trashJob}) ? 1 : 0;
384 if ( !$trashCleanRunning && !$CmdQueueOn{$bpc->trashJob} ) {
386 # This should only happen once at startup, but just in case this
387 # code will re-start BackupPC_trashClean if it quits
390 host => $bpc->trashJob,
393 cmd => ["$BinDir/BackupPC_trashClean"],
395 $CmdQueueOn{$bpc->trashJob} = 1;
397 if ( $RunNightlyWhenIdle == 1 ) {
400 # Queue multiple nightly jobs based on the configuration
402 $Conf{MaxBackupPCNightlyJobs} = 1
403 if ( $Conf{MaxBackupPCNightlyJobs} <= 0 );
404 $Conf{BackupPCNightlyPeriod} = 1
405 if ( $Conf{BackupPCNightlyPeriod} <= 0 );
407 # Decide what subset of the 16 top-level directories 0..9a..f
408 # we run BackupPC_nightly on, based on $Conf{BackupPCNightlyPeriod}.
409 # If $Conf{BackupPCNightlyPeriod} == 1 then we run 0..15 every
410 # time. If $Conf{BackupPCNightlyPeriod} == 2 then we run
411 # 0..7 one night and 89a-f the next night. And so on.
413 # $Info{NightlyPhase} counts which night, from 0 to
414 # $Conf{BackupPCNightlyPeriod} - 1.
416 my $start = int($Info{NightlyPhase} * 16
417 / $Conf{BackupPCNightlyPeriod});
418 my $end = int(($Info{NightlyPhase} + 1) * 16
419 / $Conf{BackupPCNightlyPeriod});
420 $end = $start + 1 if ( $end <= $start );
421 $Info{NightlyPhase}++;
422 $Info{NightlyPhase} = 0 if ( $end >= 16 );
425 # Zero out the data we expect to get from BackupPC_nightly.
427 for my $p ( qw(pool cpool) ) {
428 for ( my $i = $start ; $i < $end ; $i++ ) {
429 $Info{pool}{$p}[$i]{FileCnt} = 0;
430 $Info{pool}{$p}[$i]{DirCnt} = 0;
431 $Info{pool}{$p}[$i]{Kb} = 0;
432 $Info{pool}{$p}[$i]{Kb2} = 0;
433 $Info{pool}{$p}[$i]{KbRm} = 0;
434 $Info{pool}{$p}[$i]{FileCntRm} = 0;
435 $Info{pool}{$p}[$i]{FileCntRep} = 0;
436 $Info{pool}{$p}[$i]{FileRepMax} = 0;
437 $Info{pool}{$p}[$i]{FileCntRename} = 0;
438 $Info{pool}{$p}[$i]{FileLinkMax} = 0;
439 $Info{pool}{$p}[$i]{Time} = 0;
442 print(LOG $bpc->timeStamp,
443 sprintf("Running %d BackupPC_nightly jobs from %d..%d"
444 . " (out of 0..15)\n",
445 $Conf{MaxBackupPCNightlyJobs}, $start, $end - 1));
448 # Now queue the $Conf{MaxBackupPCNightlyJobs} jobs.
449 # The granularity on start and end is now 0..255.
454 for ( my $i = 0 ; $i < $Conf{MaxBackupPCNightlyJobs} ; $i++ ) {
456 # The first nightly job gets the -m option (does email, log aging).
457 # All jobs get the start and end options from 0..255 telling
458 # them which parts of the pool to traverse.
460 my $cmd = ["$BinDir/BackupPC_nightly"];
461 push(@$cmd, "-m") if ( $i == 0 );
463 $start = $start0 + int(($end - $start0)
464 * ($i + 1) / $Conf{MaxBackupPCNightlyJobs});
465 push(@$cmd, $start - 1);
467 my $job = $bpc->adminJob($i);
474 $CmdQueueOn{$job} = 1;
476 $RunNightlyWhenIdle = 2;
480 ############################################################################
481 # Main_TryToRun_CmdQueue()
483 # Decide if we can run a new command from the @CmdQueue.
484 # We only run one of these at a time. The @CmdQueue is
485 # used to run BackupPC_link (for the corresponding host),
486 # BackupPC_trashClean, and BackupPC_nightly using a fake
487 # host name of $bpc->adminJob.
488 ############################################################################
489 sub Main_TryToRun_CmdQueue
493 while ( $CmdJob eq "" && @CmdQueue > 0 && $RunNightlyWhenIdle != 1
494 || @CmdQueue > 0 && $RunNightlyWhenIdle == 2
495 && $bpc->isAdminJob($CmdQueue[0]->{host})
498 $req = pop(@CmdQueue);
500 $host = $req->{host};
501 if ( defined($Jobs{$host}) ) {
502 print(LOG $bpc->timeStamp,
503 "Botch on admin job for $host: already in use!!\n");
505 # This could happen during normal opertion: a user could
506 # request a backup while a BackupPC_link is queued from
507 # a previous backup. But it is unlikely. Just put this
508 # request back on the end of the queue.
510 unshift(@CmdQueue, $req);
513 $CmdQueueOn{$host} = 0;
514 my $cmd = $req->{cmd};
515 my $pid = open(FH, "-|");
516 if ( !defined($pid) ) {
517 print(LOG $bpc->timeStamp,
518 "can't fork for $host, request by $req->{user}\n");
525 print(LOG $bpc->timeStamp, "can't exec @$cmd for $host\n");
528 $Jobs{$host}{pid} = $pid;
529 $Jobs{$host}{fh} = *FH;
530 $Jobs{$host}{fn} = fileno(FH);
531 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
532 $Jobs{$host}{startTime} = time;
533 $Jobs{$host}{reqTime} = $req->{reqTime};
534 $cmd = $bpc->execCmd2ShellCmd(@$cmd);
535 $Jobs{$host}{cmd} = $cmd;
536 $Jobs{$host}{user} = $req->{user};
537 $Jobs{$host}{type} = $Status{$host}{type};
538 $Status{$host}{state} = "Status_link_running";
539 $Status{$host}{activeJob} = 1;
540 $Status{$host}{endTime} = time;
541 $CmdJob = $host if ( $host ne $bpc->trashJob );
542 $cmd =~ s/$BinDir\///g;
543 print(LOG $bpc->timeStamp, "Running $cmd (pid=$pid)\n");
544 if ( $cmd =~ /^BackupPC_nightly\s/ ) {
545 $BackupPCNightlyJobs++;
546 $BackupPCNightlyLock++;
551 ############################################################################
552 # Main_TryToRun_Bg_or_User_Queue()
554 # Decide if we can run any new backup requests from @BgQueue
555 # or @UserQueue. Several of these can be run at the same time
556 # based on %Conf settings. Jobs from @UserQueue take priority,
557 # and at total of $Conf{MaxBackups} + $Conf{MaxUserBackups}
558 # simultaneous jobs can run from @UserQueue. After @UserQueue
559 # is exhausted, up to $Conf{MaxBackups} simultaneous jobs can
561 ############################################################################
562 sub Main_TryToRun_Bg_or_User_Queue
565 my(@deferUserQueue, @deferBgQueue);
568 if ( time - $Info{DUlastValueTime} >= 600 ) {
570 # Update our notion of disk usage no more than
571 # once every 10 minutes
573 $du = $bpc->CheckFileSystemUsage($TopDir);
574 $Info{DUlastValue} = $du;
575 $Info{DUlastValueTime} = time;
578 # if we recently checked it then just use the old value
580 $du = $Info{DUlastValue};
582 if ( $Info{DUDailyMaxReset} ) {
583 $Info{DUDailyMaxStartTime} = time;
584 $Info{DUDailyMaxReset} = 0;
585 $Info{DUDailyMax} = 0;
587 if ( $du > $Info{DUDailyMax} ) {
588 $Info{DUDailyMax} = $du;
589 $Info{DUDailyMaxTime} = time;
591 if ( $du > $Conf{DfMaxUsagePct} ) {
592 my @bgQueue = @BgQueue;
596 # When the disk is too full, only run backups that will
597 # do expires, not regular backups
600 foreach $req ( @bgQueue ) {
601 if ( $req->{dumpExpire} ) {
602 unshift(@BgQueue, $req);
604 $BgQueueOn{$req->{host}} = 0;
609 print(LOG $bpc->timeStamp,
610 "Disk too full ($du%); skipped $nSkip hosts\n");
611 $Info{DUDailySkipHostCnt} += $nSkip;
616 # Run background jobs anytime. Previously they were locked out
617 # when BackupPC_nightly was running or pending with this
618 # condition on the while loop:
620 # while ( $RunNightlyWhenIdle == 0 )
624 my(@args, $progName, $type);
625 my $nJobs = keys(%Jobs);
627 # CmdJob and trashClean don't count towards MaxBackups / MaxUserBackups
629 if ( $CmdJob ne "" ) {
630 if ( $BackupPCNightlyJobs ) {
631 $nJobs -= $BackupPCNightlyJobs;
636 $nJobs-- if ( defined($Jobs{$bpc->trashJob} ) );
637 if ( $nJobs < $Conf{MaxBackups} + $Conf{MaxUserBackups}
638 && @UserQueue > 0 ) {
639 $req = pop(@UserQueue);
640 if ( defined($Jobs{$req->{host}}) ) {
641 push(@deferUserQueue, $req);
644 push(@args, $req->{doFull} ? "-f" : "-i")
645 if (( !$req->{restore} ) && ( !$req->{archive} ));
646 $UserQueueOn{$req->{host}} = 0;
647 } elsif ( $nJobs < $Conf{MaxBackups}
648 && (@CmdQueue + $nJobs)
649 <= $Conf{MaxBackups} + $Conf{MaxPendingCmds}
651 $req = pop(@BgQueue);
652 if ( defined($Jobs{$req->{host}}) ) {
654 # Job is currently running for this host; save it for later
656 unshift(@deferBgQueue, $req);
659 $BgQueueOn{$req->{host}} = 0;
662 # Restore the deferred jobs
664 @BgQueue = (@BgQueue, @deferBgQueue);
665 @UserQueue = (@UserQueue, @deferUserQueue);
668 $host = $req->{host};
669 my $user = $req->{user};
670 if ( $req->{restore} ) {
671 $progName = "BackupPC_restore";
673 push(@args, $req->{hostIP}, $req->{host}, $req->{reqFileName});
674 } elsif ( $req->{archive} ) {
675 $progName = "BackupPC_archive";
677 push(@args, $req->{user}, $req->{host}, $req->{reqFileName});
679 $progName = "BackupPC_dump";
681 push(@args, "-d") if ( $req->{dhcp} );
682 push(@args, "-e") if ( $req->{dumpExpire} );
685 my $pid = open(FH, "-|");
686 if ( !defined($pid) ) {
687 print(LOG $bpc->timeStamp,
688 "can't fork to run $progName for $host, request by $user\n");
694 exec("$BinDir/$progName", @args);
695 print(LOG $bpc->timeStamp, "can't exec $progName for $host\n");
698 $Jobs{$host}{pid} = $pid;
699 $Jobs{$host}{fh} = *FH;
700 $Jobs{$host}{fn} = fileno(FH);
701 $Jobs{$host}{dhcp} = $req->{dhcp};
702 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
703 $Jobs{$host}{startTime} = time;
704 $Jobs{$host}{reqTime} = $req->{reqTime};
705 $Jobs{$host}{userReq} = $req->{userReq};
706 $Jobs{$host}{cmd} = $bpc->execCmd2ShellCmd($progName, @args);
707 $Jobs{$host}{user} = $user;
708 $Jobs{$host}{type} = $type;
709 $Status{$host}{userReq} = $req->{userReq}
710 if ( defined($Hosts->{$host}) );
711 if ( !$req->{dhcp} ) {
712 $Status{$host}{state} = "Status_".$type."_starting";
713 $Status{$host}{activeJob} = 1;
714 $Status{$host}{startTime} = time;
715 $Status{$host}{endTime} = "";
720 ############################################################################
723 # If necessary, figure out when to next wakeup based on $Conf{WakeupSchedule},
724 # and then do a select() to wait for the next thing to happen
725 # (timeout, signal, someone sends a message, child dies etc).
726 ############################################################################
729 if ( $NextWakeup <= 0 ) {
731 # Figure out when to next wakeup based on $Conf{WakeupSchedule}.
733 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
735 my($currHours) = $hour + $min / 60 + $sec / 3600;
736 if ( $bpc->ConfigMTime() != $Info{ConfigModTime} ) {
737 ServerReload("Re-read config file because mtime changed");
740 foreach my $t ( @{$Conf{WakeupSchedule} || [0..23]} ) {
741 next if ( $t < 0 || $t > 24 );
742 my $tomorrow = $t + 24;
744 || ($tomorrow - $currHours > 0
745 && $delta > $tomorrow - $currHours) ) {
746 $delta = $tomorrow - $currHours;
747 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
750 || ($t - $currHours > 0 && $delta > $t - $currHours) ) {
751 $delta = $t - $currHours;
752 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
755 $NextWakeup = time + $delta * 3600;
756 $Info{nextWakeup} = $NextWakeup;
757 print(LOG $bpc->timeStamp, "Next wakeup is ",
758 $bpc->timeStamp($NextWakeup, 1), "\n");
761 # Call select(), waiting until either a signal, a timeout,
762 # any output from our jobs, or any messages from clients
764 # select() is where we (hopefully) spend most of our time blocked...
766 my $timeout = $NextWakeup - time;
767 $timeout = 1 if ( $timeout <= 0 );
769 select(my $rout = $FDread, undef, $ein, $timeout);
774 ############################################################################
775 # Main_Process_Signal()
778 ############################################################################
779 sub Main_Process_Signal
784 if ( $SigName eq "HUP" ) {
785 ServerReload("Re-read config file because of a SIG_HUP");
786 } elsif ( $SigName ) {
787 ServerShutdown("Got signal $SigName... cleaning up");
792 ############################################################################
793 # Main_Check_Timeout()
795 # Check if a timeout has occured, and if so, queue all the PCs for backups.
796 # Also does log file aging on the first timeout after midnight.
797 ############################################################################
798 sub Main_Check_Timeout
803 return if ( time < $NextWakeup || $NextWakeup <= 0 );
805 if ( $FirstWakeup ) {
807 # This is the first wakeup after midnight. Do log file aging
808 # and various house keeping.
811 printf(LOG "%s24hr disk usage: %d%% max, %d%% recent,"
812 . " %d skipped hosts\n",
813 $bpc->timeStamp, $Info{DUDailyMax}, $Info{DUlastValue},
814 $Info{DUDailySkipHostCnt});
815 $Info{DUDailyMaxReset} = 1;
816 $Info{DUDailyMaxPrev} = $Info{DUDailyMax};
817 $Info{DUDailySkipHostCntPrev} = $Info{DUDailySkipHostCnt};
818 $Info{DUDailySkipHostCnt} = 0;
819 my $lastLog = $Conf{MaxOldLogFiles} - 1;
820 if ( -f "$LogDir/LOG.$lastLog" ) {
821 print(LOG $bpc->timeStamp,
822 "Removing $LogDir/LOG.$lastLog\n");
823 unlink("$LogDir/LOG.$lastLog");
825 if ( -f "$LogDir/LOG.$lastLog.z" ) {
826 print(LOG $bpc->timeStamp,
827 "Removing $LogDir/LOG.$lastLog.z\n");
828 unlink("$LogDir/LOG.$lastLog.z");
830 print(LOG $bpc->timeStamp, "Aging LOG files, LOG -> LOG.0 -> "
831 . "LOG.1 -> ... -> LOG.$lastLog\n");
832 close(STDERR); # dup of LOG
833 close(STDOUT); # dup of LOG
835 for ( my $i = $lastLog - 1 ; $i >= 0 ; $i-- ) {
837 rename("$LogDir/LOG.$i", "$LogDir/LOG.$j")
838 if ( -f "$LogDir/LOG.$i" );
839 rename("$LogDir/LOG.$i.z", "$LogDir/LOG.$j.z")
840 if ( -f "$LogDir/LOG.$i.z" );
843 # Compress the log file LOG -> LOG.0.z (if enabled).
844 # Otherwise, just rename LOG -> LOG.0.
846 BackupPC::FileZIO->compressCopy("$LogDir/LOG",
849 $Conf{CompressLevel}, 1);
852 # Remember to run the nightly script when the next CmdQueue
855 $RunNightlyWhenIdle = 1;
858 # Write out the current status and then queue all the PCs
862 %BgQueueOn = () if ( @BgQueue == 0 );
863 %UserQueueOn = () if ( @UserQueue == 0 );
864 %CmdQueueOn = () if ( @CmdQueue == 0 );
868 ############################################################################
869 # Main_Check_Job_Messages($fdRead)
871 # Check if select() says we have bytes waiting from any of our jobs.
872 # Handle each of the messages when complete (newline terminated).
873 ############################################################################
874 sub Main_Check_Job_Messages
877 foreach my $host ( keys(%Jobs) ) {
878 next if ( !vec($fdRead, $Jobs{$host}{fn}, 1) );
881 # do a last check to make sure there is something to read so
882 # we are absolutely sure we won't block.
884 vec(my $readMask, $Jobs{$host}{fn}, 1) = 1;
885 if ( !select($readMask, undef, undef, 0.0) ) {
886 print(LOG $bpc->timeStamp, "Botch in Main_Check_Job_Messages:"
887 . " nothing to read from $host. Debug dump:\n");
888 my($dump) = Data::Dumper->new(
889 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
890 [qw(*Clients, *Jobs *FDread, *fdRead)]);
892 print(LOG $dump->Dump);
895 my $nbytes = sysread($Jobs{$host}{fh}, $mesg, 1024);
896 $Jobs{$host}{mesg} .= $mesg if ( $nbytes > 0 );
898 # Process any complete lines of output from this jobs.
899 # Any output to STDOUT or STDERR from the children is processed here.
901 while ( $Jobs{$host}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
903 $Jobs{$host}{mesg} = $2;
904 if ( $Jobs{$host}{dhcp} ) {
905 if ( $mesg =~ /^DHCP (\S+) (\S+)/ ) {
906 my $newHost = $bpc->uriUnesc($2);
907 if ( defined($Jobs{$newHost}) ) {
908 print(LOG $bpc->timeStamp,
909 "Backup on $newHost is already running\n");
910 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
914 $Jobs{$host}{dhcpHostIP} = $host;
915 $Status{$newHost}{dhcpHostIP} = $host;
916 $Jobs{$newHost} = $Jobs{$host};
917 delete($Jobs{$host});
919 $Status{$host}{state} = "Status_backup_starting";
920 $Status{$host}{activeJob} = 1;
921 $Status{$host}{startTime} = $Jobs{$host}{startTime};
922 $Status{$host}{endTime} = "";
923 $Jobs{$host}{dhcp} = 0;
925 print(LOG $bpc->timeStamp, "dhcp $host: $mesg\n");
927 } elsif ( $mesg =~ /^started (.*) dump, share=(.*)/ ) {
928 $Jobs{$host}{type} = $1;
929 $Jobs{$host}{shareName} = $2;
930 print(LOG $bpc->timeStamp,
931 "Started $1 backup on $host (pid=$Jobs{$host}{pid}",
932 $Jobs{$host}{dhcpHostIP}
933 ? ", dhcp=$Jobs{$host}{dhcpHostIP}" : "",
934 ", share=$Jobs{$host}{shareName})\n");
935 $Status{$host}{state} = "Status_backup_in_progress";
936 $Status{$host}{reason} = "";
937 $Status{$host}{type} = $1;
938 $Status{$host}{startTime} = time;
939 $Status{$host}{deadCnt} = 0;
940 $Status{$host}{aliveCnt}++;
941 $Status{$host}{dhcpCheckCnt}--
942 if ( $Status{$host}{dhcpCheckCnt} > 0 );
943 } elsif ( $mesg =~ /^xferPids (.*)/ ) {
944 $Jobs{$host}{xferPid} = $1;
945 } elsif ( $mesg =~ /^started_restore/ ) {
946 $Jobs{$host}{type} = "restore";
947 print(LOG $bpc->timeStamp,
948 "Started restore on $host"
949 . " (pid=$Jobs{$host}{pid})\n");
950 $Status{$host}{state} = "Status_restore_in_progress";
951 $Status{$host}{reason} = "";
952 $Status{$host}{type} = "restore";
953 $Status{$host}{startTime} = time;
954 $Status{$host}{deadCnt} = 0;
955 $Status{$host}{aliveCnt}++;
956 } elsif ( $mesg =~ /^started_archive/ ) {
957 $Jobs{$host}{type} = "archive";
958 print(LOG $bpc->timeStamp,
959 "Started archive on $host"
960 . " (pid=$Jobs{$host}{pid})\n");
961 $Status{$host}{state} = "Status_archive_in_progress";
962 $Status{$host}{reason} = "";
963 $Status{$host}{type} = "archive";
964 $Status{$host}{startTime} = time;
965 $Status{$host}{deadCnt} = 0;
966 $Status{$host}{aliveCnt}++;
967 } elsif ( $mesg =~ /^(full|incr) backup complete/ ) {
968 print(LOG $bpc->timeStamp, "Finished $1 backup on $host\n");
969 $Status{$host}{reason} = "Reason_backup_done";
970 delete($Status{$host}{error});
971 delete($Status{$host}{errorTime});
972 $Status{$host}{endTime} = time;
973 $Status{$host}{lastGoodBackupTime} = time;
974 } elsif ( $mesg =~ /^backups disabled/ ) {
975 print(LOG $bpc->timeStamp,
976 "Ignoring old backup error on $host\n");
977 $Status{$host}{reason} = "Reason_backup_done";
978 delete($Status{$host}{error});
979 delete($Status{$host}{errorTime});
980 $Status{$host}{endTime} = time;
981 } elsif ( $mesg =~ /^restore complete/ ) {
982 print(LOG $bpc->timeStamp, "Finished restore on $host\n");
983 $Status{$host}{reason} = "Reason_restore_done";
984 delete($Status{$host}{error});
985 delete($Status{$host}{errorTime});
986 $Status{$host}{endTime} = time;
987 } elsif ( $mesg =~ /^archive complete/ ) {
988 print(LOG $bpc->timeStamp, "Finished archive on $host\n");
989 $Status{$host}{reason} = "Reason_archive_done";
990 delete($Status{$host}{error});
991 delete($Status{$host}{errorTime});
992 $Status{$host}{endTime} = time;
993 } elsif ( $mesg =~ /^nothing to do/ ) {
994 if ( $Status{$host}{reason} ne "Reason_backup_failed"
995 && $Status{$host}{reason} ne "Reason_restore_failed" ) {
996 $Status{$host}{state} = "Status_idle";
997 $Status{$host}{reason} = "Reason_nothing_to_do";
998 $Status{$host}{startTime} = time;
1000 $Status{$host}{dhcpCheckCnt}--
1001 if ( $Status{$host}{dhcpCheckCnt} > 0 );
1002 } elsif ( $mesg =~ /^no ping response/
1003 || $mesg =~ /^ping too slow/
1004 || $mesg =~ /^host not found/ ) {
1005 $Status{$host}{state} = "Status_idle";
1006 if ( $Status{$host}{userReq}
1007 || $Status{$host}{reason} ne "Reason_backup_failed"
1008 || $Status{$host}{error} =~ /^aborted by user/ ) {
1009 $Status{$host}{reason} = "Reason_no_ping";
1010 $Status{$host}{error} = $mesg;
1011 $Status{$host}{startTime} = time;
1013 $Status{$host}{deadCnt}++;
1014 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1015 $Status{$host}{aliveCnt} = 0;
1017 } elsif ( $mesg =~ /^dump failed: (.*)/ ) {
1018 $Status{$host}{state} = "Status_idle";
1019 $Status{$host}{error} = $1;
1020 $Status{$host}{errorTime} = time;
1021 $Status{$host}{endTime} = time;
1022 if ( $Status{$host}{reason}
1023 eq "Reason_backup_canceled_by_user" ) {
1024 print(LOG $bpc->timeStamp,
1025 "Backup canceled on $host ($1)\n");
1027 $Status{$host}{reason} = "Reason_backup_failed";
1028 print(LOG $bpc->timeStamp,
1029 "Backup failed on $host ($1)\n");
1031 } elsif ( $mesg =~ /^restore failed: (.*)/ ) {
1032 $Status{$host}{state} = "Status_idle";
1033 $Status{$host}{error} = $1;
1034 $Status{$host}{errorTime} = time;
1035 $Status{$host}{endTime} = time;
1036 if ( $Status{$host}{reason}
1037 eq "Reason_restore_canceled_by_user" ) {
1038 print(LOG $bpc->timeStamp,
1039 "Restore canceled on $host ($1)\n");
1041 $Status{$host}{reason} = "Reason_restore_failed";
1042 print(LOG $bpc->timeStamp,
1043 "Restore failed on $host ($1)\n");
1045 } elsif ( $mesg =~ /^archive failed: (.*)/ ) {
1046 $Status{$host}{state} = "Status_idle";
1047 $Status{$host}{error} = $1;
1048 $Status{$host}{errorTime} = time;
1049 $Status{$host}{endTime} = time;
1050 if ( $Status{$host}{reason}
1051 eq "Reason_archive_canceled_by_user" ) {
1052 print(LOG $bpc->timeStamp,
1053 "Archive canceled on $host ($1)\n");
1055 $Status{$host}{reason} = "Reason_archive_failed";
1056 print(LOG $bpc->timeStamp,
1057 "Archive failed on $host ($1)\n");
1059 } elsif ( $mesg =~ /^log\s+(.*)/ ) {
1060 print(LOG $bpc->timeStamp, "$1\n");
1061 } elsif ( $mesg =~ /^BackupPC_stats (\d+) = (.*)/ ) {
1062 my $chunk = int($1 / 16);
1063 my @f = split(/,/, $2);
1064 $Info{pool}{$f[0]}[$chunk]{FileCnt} += $f[1];
1065 $Info{pool}{$f[0]}[$chunk]{DirCnt} += $f[2];
1066 $Info{pool}{$f[0]}[$chunk]{Kb} += $f[3];
1067 $Info{pool}{$f[0]}[$chunk]{Kb2} += $f[4];
1068 $Info{pool}{$f[0]}[$chunk]{KbRm} += $f[5];
1069 $Info{pool}{$f[0]}[$chunk]{FileCntRm} += $f[6];
1070 $Info{pool}{$f[0]}[$chunk]{FileCntRep} += $f[7];
1071 $Info{pool}{$f[0]}[$chunk]{FileRepMax} = $f[8]
1072 if ( $Info{pool}{$f[0]}[$chunk]{FileRepMax} < $f[8] );
1073 $Info{pool}{$f[0]}[$chunk]{FileCntRename} += $f[9];
1074 $Info{pool}{$f[0]}[$chunk]{FileLinkMax} = $f[10]
1075 if ( $Info{pool}{$f[0]}[$chunk]{FileLinkMax} < $f[10] );
1076 $Info{pool}{$f[0]}[$chunk]{FileLinkTotal} += $f[11];
1077 $Info{pool}{$f[0]}[$chunk]{Time} = time;
1078 } elsif ( $mesg =~ /^BackupPC_nightly lock_off/ ) {
1079 $BackupPCNightlyLock--;
1080 if ( $BackupPCNightlyLock == 0 ) {
1082 # This means the last BackupPC_nightly is done with
1083 # the pool clean, so it's ok to start running regular
1084 # backups again. But starting in 3.0 regular jobs
1085 # are decoupled from BackupPC_nightly.
1087 $RunNightlyWhenIdle = 0;
1089 } elsif ( $mesg =~ /^processState\s+(.+)/ ) {
1090 $Jobs{$host}{processState} = $1;
1091 } elsif ( $mesg =~ /^link\s+(.+)/ ) {
1093 $Status{$h}{needLink} = 1;
1095 print(LOG $bpc->timeStamp, "$host: $mesg\n");
1099 # shut down the client connection if we read EOF
1101 if ( $nbytes <= 0 ) {
1102 close($Jobs{$host}{fh});
1103 vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1104 if ( $CmdJob eq $host || $bpc->isAdminJob($host) ) {
1105 my $cmd = $Jobs{$host}{cmd};
1106 $cmd =~ s/$BinDir\///g;
1107 print(LOG $bpc->timeStamp, "Finished $host ($cmd)\n");
1108 $Status{$host}{state} = "Status_idle";
1109 $Status{$host}{endTime} = time;
1110 if ( $cmd =~ /^BackupPC_nightly\s/ ) {
1111 $BackupPCNightlyJobs--;
1112 #print(LOG $bpc->timeStamp, "BackupPC_nightly done; now"
1113 # . " have $BackupPCNightlyJobs running\n");
1114 if ( $BackupPCNightlyJobs <= 0 ) {
1116 # Last BackupPC_nightly has finished
1118 $BackupPCNightlyJobs = 0;
1119 $RunNightlyWhenIdle = 0;
1122 # Combine the 16 per-directory results
1124 for my $p ( qw(pool cpool) ) {
1125 $Info{"${p}FileCnt"} = 0;
1126 $Info{"${p}DirCnt"} = 0;
1127 $Info{"${p}Kb"} = 0;
1128 $Info{"${p}Kb2"} = 0;
1129 $Info{"${p}KbRm"} = 0;
1130 $Info{"${p}FileCntRm"} = 0;
1131 $Info{"${p}FileCntRep"} = 0;
1132 $Info{"${p}FileRepMax"} = 0;
1133 $Info{"${p}FileCntRename"} = 0;
1134 $Info{"${p}FileLinkMax"} = 0;
1135 $Info{"${p}Time"} = 0;
1136 for ( my $i = 0 ; $i < 16 ; $i++ ) {
1137 $Info{"${p}FileCnt"}
1138 += $Info{pool}{$p}[$i]{FileCnt};
1140 += $Info{pool}{$p}[$i]{DirCnt};
1142 += $Info{pool}{$p}[$i]{Kb};
1144 += $Info{pool}{$p}[$i]{Kb2};
1146 += $Info{pool}{$p}[$i]{KbRm};
1147 $Info{"${p}FileCntRm"}
1148 += $Info{pool}{$p}[$i]{FileCntRm};
1149 $Info{"${p}FileCntRep"}
1150 += $Info{pool}{$p}[$i]{FileCntRep};
1151 $Info{"${p}FileRepMax"}
1152 = $Info{pool}{$p}[$i]{FileRepMax}
1153 if ( $Info{"${p}FileRepMax"} <
1154 $Info{pool}{$p}[$i]{FileRepMax} );
1155 $Info{"${p}FileCntRename"}
1156 += $Info{pool}{$p}[$i]{FileCntRename};
1157 $Info{"${p}FileLinkMax"}
1158 = $Info{pool}{$p}[$i]{FileLinkMax}
1159 if ( $Info{"${p}FileLinkMax"} <
1160 $Info{pool}{$p}[$i]{FileLinkMax} );
1161 $Info{"${p}Time"} = $Info{pool}{$p}[$i]{Time}
1162 if ( $Info{"${p}Time"} <
1163 $Info{pool}{$p}[$i]{Time} );
1165 printf(LOG "%s%s nightly clean removed %d files of"
1167 $bpc->timeStamp, ucfirst($p),
1168 $Info{"${p}FileCntRm"},
1169 $Info{"${p}KbRm"} / (1000 * 1024));
1170 printf(LOG "%s%s is %.2fGB, %d files (%d repeated, "
1171 . "%d max chain, %d max links), %d directories\n",
1172 $bpc->timeStamp, ucfirst($p),
1173 $Info{"${p}Kb"} / (1000 * 1024),
1174 $Info{"${p}FileCnt"}, $Info{"${p}FileCntRep"},
1175 $Info{"${p}FileRepMax"},
1176 $Info{"${p}FileLinkMax"}, $Info{"${p}DirCnt"});
1184 # Queue BackupPC_link to complete the backup
1185 # processing for this host.
1187 if ( defined($Status{$host})
1188 && ($Status{$host}{reason} eq "Reason_backup_done"
1189 || $Status{$host}{needLink}) ) {
1191 } elsif ( defined($Status{$host}) ) {
1192 $Status{$host}{state} = "Status_idle";
1195 delete($Jobs{$host});
1196 $Status{$host}{activeJob} = 0 if ( defined($Status{$host}) );
1200 # When we are idle (empty Jobs, CmdQueue, BgQueue, UserQueue) we
1201 # do a pass over %Status updating the deadCnt and aliveCnt for
1202 # DHCP hosts. The reason we need to do this later is we can't
1203 # be sure whether a DHCP host is alive or dead until we have passed
1204 # over all the DHCP pool.
1206 return if ( @CmdQueue || @BgQueue || @UserQueue || keys(%Jobs) > 1 );
1207 foreach my $host ( keys(%Status) ) {
1208 next if ( $Status{$host}{dhcpCheckCnt} <= 0 );
1209 $Status{$host}{deadCnt} += $Status{$host}{dhcpCheckCnt};
1210 $Status{$host}{dhcpCheckCnt} = 0;
1211 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1212 $Status{$host}{aliveCnt} = 0;
1217 ############################################################################
1218 # Main_Check_Client_Messages($fdRead)
1220 # Check for, and process, any output from our clients. Also checks
1221 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
1222 ############################################################################
1223 sub Main_Check_Client_Messages
1226 foreach my $client ( keys(%Clients) ) {
1227 next if ( !vec($fdRead, $Clients{$client}{fn}, 1) );
1230 # do a last check to make sure there is something to read so
1231 # we are absolutely sure we won't block.
1233 vec(my $readMask, $Clients{$client}{fn}, 1) = 1;
1234 if ( !select($readMask, undef, undef, 0.0) ) {
1235 print(LOG $bpc->timeStamp, "Botch in Main_Check_Client_Messages:"
1236 . " nothing to read from $client. Debug dump:\n");
1237 my($dump) = Data::Dumper->new(
1238 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
1239 [qw(*Clients, *Jobs *FDread, *fdRead)]);
1241 print(LOG $dump->Dump);
1244 my $nbytes = sysread($Clients{$client}{fh}, $mesg, 1024);
1245 $Clients{$client}{mesg} .= $mesg if ( $nbytes > 0 );
1247 # Process any complete lines received from this client.
1249 while ( $Clients{$client}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
1252 $Clients{$client}{mesg} = $2;
1254 # Authenticate the message by checking the MD5 digest
1256 my $md5 = Digest::MD5->new;
1257 if ( $cmd !~ /^(.{22}) (.*)/
1258 || ($md5->add($Clients{$client}{seed}
1259 . $Clients{$client}{mesgCnt}
1260 . $Conf{ServerMesgSecret} . $2),
1261 $md5->b64digest ne $1) ) {
1262 print(LOG $bpc->timeStamp, "Corrupted message '$cmd' from"
1263 . " client '$Clients{$client}{clientName}':"
1264 . " shutting down client connection\n");
1268 $Clients{$client}{mesgCnt}++;
1270 if ( $cmd =~ /^stop (\S+)\s+(\S+)\s+(\S*)/ ) {
1274 $host = $bpc->uriUnesc($host);
1275 if ( $CmdJob ne $host && defined($Status{$host})
1276 && defined($Jobs{$host}) ) {
1277 print(LOG $bpc->timeStamp,
1278 "Stopping current $Jobs{$host}{type} of $host,"
1279 . " request by $user (backoff=$backoff)\n");
1280 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1282 # Don't close the pipe now; wait until the child
1283 # really exits later. Otherwise close() will
1284 # block until the child has exited.
1286 ##vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1287 ##close($Jobs{$host}{fh});
1288 ##delete($Jobs{$host});
1290 $Status{$host}{state} = "Status_idle";
1291 if ( $Jobs{$host}{type} eq "restore" ) {
1292 $Status{$host}{reason}
1293 = "Reason_restore_canceled_by_user";
1294 } elsif ( $Jobs{$host}{type} eq "archive" ) {
1295 $Status{$host}{reason}
1296 = "Reason_archive_canceled_by_user";
1298 $Status{$host}{reason}
1299 = "Reason_backup_canceled_by_user";
1301 $Status{$host}{activeJob} = 0;
1302 $Status{$host}{startTime} = time;
1303 $reply = "ok: $Jobs{$host}{type} of $host canceled";
1304 } elsif ( $BgQueueOn{$host} || $UserQueueOn{$host} ) {
1305 print(LOG $bpc->timeStamp,
1306 "Stopping pending backup of $host,"
1307 . " request by $user (backoff=$backoff)\n");
1308 @BgQueue = grep($_->{host} ne $host, @BgQueue);
1309 @UserQueue = grep($_->{host} ne $host, @UserQueue);
1310 $BgQueueOn{$host} = $UserQueueOn{$host} = 0;
1311 $reply = "ok: pending backup of $host canceled";
1313 print(LOG $bpc->timeStamp,
1314 "Nothing to do for stop backup of $host,"
1315 . " request by $user (backoff=$backoff)\n");
1316 $reply = "ok: no backup was pending or running";
1318 if ( defined($Status{$host}) && $backoff ne "" ) {
1319 if ( $backoff > 0 ) {
1320 $Status{$host}{backoffTime} = time + $backoff * 3600;
1322 delete($Status{$host}{backoffTime});
1325 } elsif ( $cmd =~ /^backup all$/ ) {
1327 } elsif ( $cmd =~ /^BackupPC_nightly run$/ ) {
1328 $RunNightlyWhenIdle = 1;
1329 } elsif ( $cmd =~ /^backup (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1334 $host = $bpc->uriUnesc($host);
1335 $hostIP = $bpc->uriUnesc($hostIP);
1336 if ( !defined($Status{$host}) ) {
1337 print(LOG $bpc->timeStamp,
1338 "User $user requested backup of unknown host"
1340 $reply = "error: unknown host $host";
1342 print(LOG $bpc->timeStamp,
1343 "User $user requested backup of $host"
1345 if ( $BgQueueOn{$hostIP} ) {
1346 @BgQueue = grep($_->{host} ne $hostIP, @BgQueue);
1347 $BgQueueOn{$hostIP} = 0;
1349 if ( $UserQueueOn{$hostIP} ) {
1350 @UserQueue = grep($_->{host} ne $hostIP, @UserQueue);
1351 $UserQueueOn{$hostIP} = 0;
1353 unshift(@UserQueue, {
1359 dhcp => $hostIP eq $host ? 0 : 1,
1361 $UserQueueOn{$hostIP} = 1;
1362 $reply = "ok: requested backup of $host";
1364 } elsif ( $cmd =~ /^archive (\S+)\s+(\S+)\s+(\S+)/ ) {
1366 my $archivehost = $2;
1367 my $reqFileName = $3;
1368 $host = $bpc->uriUnesc($archivehost);
1369 if ( !defined($Status{$host}) ) {
1370 print(LOG $bpc->timeStamp,
1371 "User $user requested archive of unknown archive host"
1373 $reply = "archive error: unknown archive host $host";
1375 print(LOG $bpc->timeStamp,
1376 "User $user requested archive on $host"
1378 if ( defined($Jobs{$host}) ) {
1379 $reply = "Archive currently running on $host, please try later";
1381 unshift(@UserQueue, {
1384 reqFileName => $reqFileName,
1390 $UserQueueOn{$host} = 1;
1391 $reply = "ok: requested archive on $host";
1394 } elsif ( $cmd =~ /^restore (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1398 my $reqFileName = $4;
1399 $host = $bpc->uriUnesc($host);
1400 $hostIP = $bpc->uriUnesc($hostIP);
1401 if ( !defined($Status{$host}) ) {
1402 print(LOG $bpc->timeStamp,
1403 "User $user requested restore to unknown host"
1405 $reply = "restore error: unknown host $host";
1407 print(LOG $bpc->timeStamp,
1408 "User $user requested restore to $host"
1410 unshift(@UserQueue, {
1413 reqFileName => $reqFileName,
1419 $UserQueueOn{$host} = 1;
1420 if ( defined($Jobs{$host}) ) {
1421 $reply = "ok: requested restore of $host, but a"
1422 . " job is currently running,"
1423 . " so this request will start later";
1425 $reply = "ok: requested restore of $host";
1428 } elsif ( $cmd =~ /^status\s*(.*)/ ) {
1430 my($dump, @values, @names);
1431 foreach my $type ( split(/\s+/, $args) ) {
1432 if ( $type =~ /^queues/ ) {
1433 push(@values, \@BgQueue, \@UserQueue, \@CmdQueue);
1434 push(@names, qw(*BgQueue *UserQueue *CmdQueue));
1435 } elsif ( $type =~ /^jobs/ ) {
1436 push(@values, \%Jobs);
1437 push(@names, qw(*Jobs));
1438 } elsif ( $type =~ /^queueLen/ ) {
1440 BgQueue => scalar(@BgQueue),
1441 UserQueue => scalar(@UserQueue),
1442 CmdQueue => scalar(@CmdQueue),
1444 push(@names, qw(*QueueLen));
1445 } elsif ( $type =~ /^info/ ) {
1446 push(@values, \%Info);
1447 push(@names, qw(*Info));
1448 } elsif ( $type =~ /^hosts/ ) {
1449 push(@values, \%Status);
1450 push(@names, qw(*Status));
1451 } elsif ( $type =~ /^host\((.*)\)/ ) {
1452 my $h = $bpc->uriUnesc($1);
1453 if ( defined($Status{$h}) ) {
1456 BgQueueOn => $BgQueueOn{$h},
1457 UserQueueOn => $UserQueueOn{$h},
1458 CmdQueueOn => $CmdQueueOn{$h},
1460 push(@names, qw(*StatusHost));
1462 print(LOG $bpc->timeStamp,
1463 "Unknown host $h for status request\n");
1466 print(LOG $bpc->timeStamp,
1467 "Unknown status request $type\n");
1470 $dump = Data::Dumper->new(\@values, \@names);
1472 $reply = $dump->Dump;
1473 } elsif ( $cmd =~ /^link\s+(.+)/ ) {
1475 $host = $bpc->uriUnesc($host);
1477 } elsif ( $cmd =~ /^log\s+(.*)/ ) {
1478 print(LOG $bpc->timeStamp, "$1\n");
1479 } elsif ( $cmd =~ /^server\s+(\w+)/ ) {
1481 if ( $type eq 'reload' ) {
1482 ServerReload("Reloading config/host files via CGI request");
1483 } elsif ( $type eq 'shutdown' ) {
1484 $reply = "Shutting down...\n";
1485 syswrite($Clients{$client}{fh}, $reply, length($reply));
1486 ServerShutdown("Server shutting down...");
1488 } elsif ( $cmd =~ /^quit/ || $cmd =~ /^exit/ ) {
1492 print(LOG $bpc->timeStamp, "Unknown command $cmd\n");
1493 $reply = "error: bad command $cmd";
1496 # send a reply to the client, at a minimum "ok\n".
1498 $reply = "ok" if ( $reply eq "" );
1500 syswrite($Clients{$client}{fh}, $reply, length($reply));
1503 # Detect possible denial-of-service attack from sending a huge line
1504 # (ie: never terminated). 32K seems to be plenty big enough as
1507 if ( length($Clients{$client}{mesg}) > 32 * 1024 ) {
1508 print(LOG $bpc->timeStamp, "Line too long from client"
1509 . " '$Clients{$client}{clientName}':"
1510 . " shutting down client connection\n");
1514 # Shut down the client connection if we read EOF
1516 if ( $nbytes <= 0 ) {
1517 close($Clients{$client}{fh});
1518 vec($FDread, $Clients{$client}{fn}, 1) = 0;
1519 delete($Clients{$client});
1523 # Accept any new connections on each of our listen sockets
1525 if ( vec($fdRead, fileno(SERVER_UNIX), 1) ) {
1527 my $paddr = accept(CLIENT, SERVER_UNIX);
1529 $Clients{$ClientConnCnt}{clientName} = "unix socket";
1530 $Clients{$ClientConnCnt}{mesg} = "";
1531 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1532 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1533 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1535 # Generate and send unique seed for MD5 digests to avoid
1536 # replay attacks. See BackupPC::Lib::ServerMesg().
1538 my $seed = time . ",$ClientConnCnt,$$,0\n";
1539 $Clients{$ClientConnCnt}{seed} = $seed;
1540 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1541 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1543 if ( $ServerInetPort > 0 && vec($fdRead, fileno(SERVER_INET), 1) ) {
1545 my $paddr = accept(CLIENT, SERVER_INET);
1546 my($port,$iaddr) = sockaddr_in($paddr);
1547 my $name = gethostbyaddr($iaddr, AF_INET);
1549 $Clients{$ClientConnCnt}{mesg} = "";
1550 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1551 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1552 $Clients{$ClientConnCnt}{clientName} = "$name:$port";
1553 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1555 # Generate and send unique seed for MD5 digests to avoid
1556 # replay attacks. See BackupPC::Lib::ServerMesg().
1558 my $seed = time . ",$ClientConnCnt,$$,$port\n";
1559 $Clients{$ClientConnCnt}{seed} = $seed;
1560 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1561 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1565 ###########################################################################
1566 # Miscellaneous subroutines
1567 ###########################################################################
1570 # Write the current status to $LogDir/status.pl
1574 my($dump) = Data::Dumper->new(
1575 [ \%Info, \%Status],
1576 [qw(*Info *Status)]);
1578 if ( open(STATUS, ">", "$LogDir/status.pl") ) {
1579 print(STATUS $dump->Dump);
1585 # Compare function for host sort. Hosts with errors go first,
1586 # sorted with the oldest errors first. The remaining hosts
1587 # are sorted so that those with the oldest backups go first.
1592 # Hosts with errors go before hosts without errors
1594 return -1 if ( $Status{$a}{error} ne "" && $Status{$b}{error} eq "" );
1597 # Hosts with no errors go after hosts with errors
1600 return 1 if ( $Status{$a}{error} eq "" && $Status{$b}{error} ne "" );
1603 # hosts with the older last good backups sort earlier
1605 my $r = $Status{$a}{lastGoodBackupTime} <=> $Status{$b}{lastGoodBackupTime};
1606 return $r if ( $r );
1609 # Finally, just sort based on host name
1615 # Queue all the hosts for backup. This means queuing all the fixed
1616 # ip hosts and all the dhcp address ranges. We also additionally
1617 # queue the dhcp hosts with a -e flag to check for expired dumps.
1622 foreach my $host ( sort(HostSortCompare keys(%$Hosts)) ) {
1623 delete($Status{$host}{backoffTime})
1624 if ( defined($Status{$host}{backoffTime})
1625 && $Status{$host}{backoffTime} < time );
1626 next if ( defined($Jobs{$host})
1627 || $BgQueueOn{$host}
1628 || $UserQueueOn{$host}
1629 || $CmdQueueOn{$host} );
1630 if ( $Hosts->{$host}{dhcp} ) {
1631 $Status{$host}{dhcpCheckCnt}++;
1632 if ( $RunNightlyWhenIdle ) {
1634 # Once per night queue a check for DHCP hosts that just
1635 # checks for expired dumps. We need to do this to handle
1636 # the case when a DHCP host has not been on the network for
1637 # a long time, and some of the old dumps need to be expired.
1638 # Normally expiry checks are done by BackupPC_dump only
1639 # after the DHCP hosts has been detected on the network.
1642 {host => $host, user => "BackupPC", reqTime => time,
1643 dhcp => 0, dumpExpire => 1});
1644 $BgQueueOn{$host} = 1;
1648 # this is a fixed ip host: queue it
1650 if ( $Info{DUlastValue} > $Conf{DfMaxUsagePct} ) {
1652 # Since we are out of disk space, instead of queuing
1653 # a regular job, queue an expire check instead. That
1654 # way if the admin reduces the number of backups to
1655 # keep then we will actually delete them. Otherwise
1656 # BackupPC_dump will never run since we have exceeded
1661 {host => $host, user => "BackupPC", reqTime => time,
1662 dhcp => $Hosts->{$host}{dhcp}, dumpExpire => 1});
1665 # Queue regular background backup
1668 {host => $host, user => "BackupPC", reqTime => time,
1669 dhcp => $Hosts->{$host}{dhcp}});
1671 $BgQueueOn{$host} = 1;
1675 print(LOG $bpc->timeStamp,
1676 "Disk too full ($Info{DUlastValue}%); skipped $nSkip hosts\n");
1677 $Info{DUDailySkipHostCnt} += $nSkip;
1679 foreach my $dhcp ( @{$Conf{DHCPAddressRanges}} ) {
1680 for ( my $i = $dhcp->{first} ; $i <= $dhcp->{last} ; $i++ ) {
1681 my $ipAddr = "$dhcp->{ipAddrBase}.$i";
1682 next if ( defined($Jobs{$ipAddr})
1683 || $BgQueueOn{$ipAddr}
1684 || $UserQueueOn{$ipAddr}
1685 || $CmdQueueOn{$ipAddr} );
1687 # this is a potential dhcp ip address (we don't know the
1688 # host name yet): queue it
1691 {host => $ipAddr, user => "BackupPC", reqTime => time,
1693 $BgQueueOn{$ipAddr} = 1;
1699 # Queue a BackupPC_link for the given host
1705 return if ( $CmdQueueOn{$host} );
1706 $Status{$host}{state} = "Status_link_pending";
1707 $Status{$host}{needLink} = 0;
1708 unshift(@CmdQueue, {
1712 cmd => ["$BinDir/BackupPC_link", $host],
1714 $CmdQueueOn{$host} = 1;
1718 # Read the hosts file, and update Status if any hosts have been
1719 # added or deleted. We also track the mtime so the only need to
1720 # update the hosts file on changes.
1722 # This function is called at startup, SIGHUP, and on each wakeup.
1723 # It returns 1 on success and undef on failure.
1730 # Nothing to do if we already have the current hosts file
1732 return 1 if ( !$force && defined($Hosts)
1733 && $Info{HostsModTime} == $bpc->HostsMTime() );
1734 if ( !defined($newHosts = $bpc->HostInfoRead()) ) {
1735 print(LOG $bpc->timeStamp, "Can't read hosts file!\n");
1738 print(LOG $bpc->timeStamp, "Reading hosts file\n");
1740 $Info{HostsModTime} = $bpc->HostsMTime();
1742 # Now update %Status in case any hosts have been added or deleted
1744 foreach my $host ( sort(keys(%$Hosts)) ) {
1745 next if ( defined($Status{$host}) );
1746 $Status{$host}{state} = "Status_idle";
1747 print(LOG $bpc->timeStamp, "Added host $host to backup list\n");
1749 foreach my $host ( sort(keys(%Status)) ) {
1750 next if ( $host eq $bpc->trashJob
1751 || $bpc->isAdminJob($host)
1752 || defined($Hosts->{$host})
1753 || defined($Jobs{$host})
1754 || $BgQueueOn{$host}
1755 || $UserQueueOn{$host}
1756 || $CmdQueueOn{$host} );
1757 print(LOG $bpc->timeStamp, "Deleted host $host from backup list\n");
1758 delete($Status{$host});
1764 # Remember the signal name for later processing
1770 foreach my $host ( keys(%Jobs) ) {
1771 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1774 # In case we are inside the exit handler, reopen the log file
1778 print(LOG "Fatal error: unhandled signal $SigName\n");
1779 unlink("$LogDir/BackupPC.pid");
1780 confess("Got new signal $SigName... quitting\n");
1787 # Open the log file and point STDOUT and STDERR there too
1791 mkpath($LogDir, 0, 0777) if ( !-d $LogDir );
1792 open(LOG, ">>$LogDir/LOG")
1793 || die("Can't create LOG file $LogDir/LOG");
1796 open(STDOUT, ">&LOG");
1797 open(STDERR, ">&LOG");
1798 select(LOG); $| = 1;
1799 select(STDERR); $| = 1;
1800 select(STDOUT); $| = 1;
1804 # Initialize the unix-domain and internet-domain sockets that
1805 # we listen to for client connections (from the CGI script and
1806 # some of the BackupPC sub-programs).
1808 sub ServerSocketInit
1810 if ( !defined(fileno(SERVER_UNIX)) ) {
1812 # one-time only: initialize unix-domain socket
1814 if ( !socket(SERVER_UNIX, PF_UNIX, SOCK_STREAM, 0) ) {
1815 print(LOG $bpc->timeStamp, "unix socket() failed: $!\n");
1818 my $sockFile = "$LogDir/BackupPC.sock";
1820 if ( !bind(SERVER_UNIX, sockaddr_un($sockFile)) ) {
1821 print(LOG $bpc->timeStamp, "unix bind() failed: $!\n");
1824 if ( !listen(SERVER_UNIX, SOMAXCONN) ) {
1825 print(LOG $bpc->timeStamp, "unix listen() failed: $!\n");
1828 vec($FDread, fileno(SERVER_UNIX), 1) = 1;
1830 return if ( $ServerInetPort == $Conf{ServerPort} );
1831 if ( $ServerInetPort > 0 ) {
1832 vec($FDread, fileno(SERVER_INET), 1) = 0;
1834 $ServerInetPort = -1;
1836 if ( $Conf{ServerPort} > 0 ) {
1838 # Setup a socket to listen on $Conf{ServerPort}
1840 my $proto = getprotobyname('tcp');
1841 if ( !socket(SERVER_INET, PF_INET, SOCK_STREAM, $proto) ) {
1842 print(LOG $bpc->timeStamp, "inet socket() failed: $!\n");
1845 if ( !setsockopt(SERVER_INET, SOL_SOCKET, SO_REUSEADDR, pack("l",1)) ) {
1846 print(LOG $bpc->timeStamp, "setsockopt() failed: $!\n");
1849 if ( !bind(SERVER_INET, sockaddr_in($Conf{ServerPort}, INADDR_ANY)) ) {
1850 print(LOG $bpc->timeStamp, "inet bind() failed: $!\n");
1853 if ( !listen(SERVER_INET, SOMAXCONN) ) {
1854 print(LOG $bpc->timeStamp, "inet listen() failed: $!\n");
1857 vec($FDread, fileno(SERVER_INET), 1) = 1;
1858 $ServerInetPort = $Conf{ServerPort};
1863 # Reload the server. Used by Main_Process_Signal when $SigName eq "HUP"
1864 # or when the command "server reload" is received.
1869 $mesg = $bpc->ConfigRead() || $mesg;
1870 print(LOG $bpc->timeStamp, "$mesg\n");
1871 $Info{ConfigModTime} = $bpc->ConfigMTime();
1872 %Conf = $bpc->Conf();
1873 umask($Conf{UmaskMode});
1877 $Info{ConfigLTime} = time;
1881 # Gracefully shutdown the server. Used by Main_Process_Signal when
1882 # $SigName ne "" && $SigName ne "HUP" or when the command
1883 # "server shutdown" is received.
1888 print(LOG $bpc->timeStamp, "$mesg\n");
1889 if ( keys(%Jobs) ) {
1890 foreach my $host ( keys(%Jobs) ) {
1891 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1894 foreach my $host ( keys(%Jobs) ) {
1895 kill($bpc->sigName2num("KILL"), $Jobs{$host}{pid});
1901 unlink("$LogDir/BackupPC.pid");