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.0, released 28 Jan 2007.
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;
72 ###########################################################################
73 # Handle command line options
74 ###########################################################################
76 if ( !getopts("d", \%opts) || @ARGV != 0 ) {
77 print("usage: $0 [-d]\n");
81 ###########################################################################
82 # Initialize major data structures and variables
83 ###########################################################################
86 # Get an instance of BackupPC::Lib and get some shortcuts.
88 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
89 my $TopDir = $bpc->TopDir();
90 my $BinDir = $bpc->BinDir();
91 my $LogDir = $bpc->LogDir();
92 my %Conf = $bpc->Conf();
95 # Verify we are running as the correct user
97 if ( $Conf{BackupPCUserVerify}
98 && $> != (my $uid = (getpwnam($Conf{BackupPCUser}))[2]) ) {
99 die "Wrong user: my userid is $>, instead of $uid ($Conf{BackupPCUser})\n";
103 # %Status maintain status information about each host.
104 # It is a hash of hashes, whose first index is the host.
109 # %Info is a hash giving general information about BackupPC status.
116 if ( -f "$LogDir/status.pl" && !(my $ret = do "$LogDir/status.pl") ) {
118 print STDERR "couldn't parse $LogDir/status.pl: $@";
119 } elsif ( !defined($ret) ) {
120 print STDERR "couldn't do $LogDir/status.pl: $!";
122 print STDERR "couldn't run $LogDir/status.pl";
127 # %Jobs maintains information about currently running jobs.
128 # It is a hash of hashes, whose first index is the host.
133 # There are three command queues:
134 # - @UserQueue is a queue of user initiated backup requests.
135 # - @BgQueue is a queue of automatically scheduled backup requests.
136 # - @CmdQueue is a queue of administrative jobs, including tasks
137 # like BackupPC_link, BackupPC_trashClean, and BackupPC_nightly
138 # Each queue is an array of hashes. Each hash stores information
139 # about the command request.
146 # To quickly lookup if a given host is on a given queue, we keep
147 # a hash of flags for each queue type.
149 my(%CmdQueueOn, %UserQueueOn, %BgQueueOn);
152 # One or more clients can connect to the server to get status information
153 # or request/cancel backups etc. The %Clients hash maintains information
154 # about each of these socket connections. The hash key is an incrementing
155 # number stored in $ClientConnCnt. Each entry is a hash that contains
156 # various information about the client connection.
162 # Read file descriptor mask used by select(). Every file descriptor
163 # on which we expect to read (or accept) has the corresponding bit
169 # Unix seconds when we next wakeup. A value of zero forces the scheduler
170 # to compute the next wakeup time.
175 # Name of signal saved by catch_signal
182 my($RunNightlyWhenIdle, $FirstWakeup, $CmdJob, $ServerInetPort);
183 my($BackupPCNightlyJobs, $BackupPCNightlyLock);
186 # Complete the rest of the initialization
190 ###########################################################################
192 ###########################################################################
196 # Check if we can/should run BackupPC_nightly
198 Main_TryToRun_nightly();
201 # Check if we can run a new command from @CmdQueue.
203 Main_TryToRun_CmdQueue();
206 # Check if we can run a new command from @UserQueue or @BgQueue.
208 Main_TryToRun_Bg_or_User_Queue();
211 # Do a select() to wait for the next interesting thing to happen
212 # (timeout, signal, someone sends a message, child dies etc).
214 my $fdRead = Main_Select();
217 # Process a signal if we received one.
220 Main_Process_Signal();
225 # Check if a timeout has occurred.
227 Main_Check_Timeout();
230 # Check for, and process, any messages (output) from our jobs
232 Main_Check_Job_Messages($fdRead);
235 # Check for, and process, any output from our clients. Also checks
236 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
238 Main_Check_Client_Messages($fdRead);
241 ############################################################################
244 # Main initialization routine. Called once at statup.
245 ############################################################################
248 umask($Conf{UmaskMode});
251 # Check for another running process, check that PASSWD is set and
252 # verify executables are configured correctly.
254 if ( $Info{pid} ne "" && kill(0, $Info{pid}) ) {
255 print(STDERR $bpc->timeStamp,
256 "Another BackupPC is running (pid $Info{pid}); quitting...\n");
259 foreach my $progName ( qw(SmbClientPath NmbLookupPath PingPath DfPath
260 SendmailPath SshPath) ) {
261 next if ( $Conf{$progName} eq "" || -x $Conf{$progName} );
262 print(STDERR $bpc->timeStamp,
263 "\$Conf{$progName} = '$Conf{$progName}' is not a"
264 . " valid executable program\n");
270 # daemonize by forking; more robust method per:
271 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=301057
274 defined($pid = fork) or die("Can't fork: $!");
275 exit if( $pid ); # parent exits
278 defined($pid = fork) or die("Can't fork: $!");
279 exit if $pid; # parent exits
281 chdir ("/") or die("Cannot chdir to /: $!\n");
283 open(STDIN , ">/dev/null") or die("Cannot open /dev/null as stdin\n");
284 # STDOUT and STDERR are handled in LogFileOpen() right below,
285 # otherwise we would have to reopen them too.
289 # Open the LOG file and redirect STDOUT, STDERR etc
294 # Read the hosts file (force a read).
296 exit(1) if ( !HostsUpdate(1) );
299 # Clean up %ENV for taint checking
301 delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
302 $ENV{PATH} = $Conf{MyPath};
305 # Initialize server sockets
310 # Catch various signals
312 foreach my $sig ( qw(INT BUS SEGV PIPE TERM ALRM HUP) ) {
313 $SIG{$sig} = \&catch_signal;
317 # Report that we started, and update %Info.
319 print(LOG $bpc->timeStamp, "BackupPC started, pid $$\n");
320 $Info{ConfigModTime} = $bpc->ConfigMTime();
322 $Info{startTime} = time;
323 $Info{ConfigLTime} = time;
324 $Info{Version} = $bpc->{Version};
327 # Update the status left over form the last time BackupPC ran.
328 # Requeue any pending links.
330 foreach my $host ( sort(keys(%$Hosts)) ) {
331 if ( $Status{$host}{state} eq "Status_backup_in_progress" ) {
333 # should we restart it? skip it for now.
335 $Status{$host}{state} = "Status_idle";
336 } elsif ( $Status{$host}{state} eq "Status_link_pending"
337 || $Status{$host}{state} eq "Status_link_running" ) {
340 $Status{$host}{state} = "Status_idle";
342 $Status{$host}{activeJob} = 0;
344 foreach my $host ( sort(keys(%Status)) ) {
345 next if ( defined($Hosts->{$host}) );
346 delete($Status{$host});
350 # Write out our initial status and save our PID
353 unlink("$LogDir/BackupPC.pid");
354 if ( open(PID, ">", "$LogDir/BackupPC.pid") ) {
357 chmod(0444, "$LogDir/BackupPC.pid");
361 # For unknown reasons there is a very infrequent error about not
362 # being able to coerce GLOBs inside the XS Data::Dumper. I've
363 # only seen this on a particular platform and perl version.
364 # For now the workaround appears to be use the perl version of
367 $Data::Dumper::Useqq = 1;
370 ############################################################################
371 # Main_TryToRun_nightly()
373 # Checks to see if we can/should run BackupPC_nightly or
374 # BackupPC_trashClean. If so we push the appropriate command onto
376 ############################################################################
377 sub Main_TryToRun_nightly
380 # Check if we should run BackupPC_nightly or BackupPC_trashClean.
381 # BackupPC_nightly is run when the current job queue is empty.
382 # BackupPC_trashClean is run in the background always.
384 my $trashCleanRunning = defined($Jobs{$bpc->trashJob}) ? 1 : 0;
385 if ( !$trashCleanRunning && !$CmdQueueOn{$bpc->trashJob} ) {
387 # This should only happen once at startup, but just in case this
388 # code will re-start BackupPC_trashClean if it quits
391 host => $bpc->trashJob,
394 cmd => ["$BinDir/BackupPC_trashClean"],
396 $CmdQueueOn{$bpc->trashJob} = 1;
398 if ( $RunNightlyWhenIdle == 1 ) {
401 # Queue multiple nightly jobs based on the configuration
403 $Conf{MaxBackupPCNightlyJobs} = 1
404 if ( $Conf{MaxBackupPCNightlyJobs} <= 0 );
405 $Conf{BackupPCNightlyPeriod} = 1
406 if ( $Conf{BackupPCNightlyPeriod} <= 0 );
408 # Decide what subset of the 16 top-level directories 0..9a..f
409 # we run BackupPC_nightly on, based on $Conf{BackupPCNightlyPeriod}.
410 # If $Conf{BackupPCNightlyPeriod} == 1 then we run 0..15 every
411 # time. If $Conf{BackupPCNightlyPeriod} == 2 then we run
412 # 0..7 one night and 89a-f the next night. And so on.
414 # $Info{NightlyPhase} counts which night, from 0 to
415 # $Conf{BackupPCNightlyPeriod} - 1.
417 my $start = int($Info{NightlyPhase} * 16
418 / $Conf{BackupPCNightlyPeriod});
419 my $end = int(($Info{NightlyPhase} + 1) * 16
420 / $Conf{BackupPCNightlyPeriod});
421 $end = $start + 1 if ( $end <= $start );
422 $Info{NightlyPhase}++;
423 $Info{NightlyPhase} = 0 if ( $end >= 16 );
426 # Zero out the data we expect to get from BackupPC_nightly.
428 for my $p ( qw(pool cpool) ) {
429 for ( my $i = $start ; $i < $end ; $i++ ) {
430 $Info{pool}{$p}[$i]{FileCnt} = 0;
431 $Info{pool}{$p}[$i]{DirCnt} = 0;
432 $Info{pool}{$p}[$i]{Kb} = 0;
433 $Info{pool}{$p}[$i]{Kb2} = 0;
434 $Info{pool}{$p}[$i]{KbRm} = 0;
435 $Info{pool}{$p}[$i]{FileCntRm} = 0;
436 $Info{pool}{$p}[$i]{FileCntRep} = 0;
437 $Info{pool}{$p}[$i]{FileRepMax} = 0;
438 $Info{pool}{$p}[$i]{FileCntRename} = 0;
439 $Info{pool}{$p}[$i]{FileLinkMax} = 0;
440 $Info{pool}{$p}[$i]{Time} = 0;
443 print(LOG $bpc->timeStamp,
444 sprintf("Running %d BackupPC_nightly jobs from %d..%d"
445 . " (out of 0..15)\n",
446 $Conf{MaxBackupPCNightlyJobs}, $start, $end - 1));
449 # Now queue the $Conf{MaxBackupPCNightlyJobs} jobs.
450 # The granularity on start and end is now 0..255.
455 for ( my $i = 0 ; $i < $Conf{MaxBackupPCNightlyJobs} ; $i++ ) {
457 # The first nightly job gets the -m option (does email, log aging).
458 # All jobs get the start and end options from 0..255 telling
459 # them which parts of the pool to traverse.
461 my $cmd = ["$BinDir/BackupPC_nightly"];
462 push(@$cmd, "-m") if ( $i == 0 );
464 $start = $start0 + int(($end - $start0)
465 * ($i + 1) / $Conf{MaxBackupPCNightlyJobs});
466 push(@$cmd, $start - 1);
468 my $job = $bpc->adminJob($i);
475 $CmdQueueOn{$job} = 1;
477 $RunNightlyWhenIdle = 2;
481 ############################################################################
482 # Main_TryToRun_CmdQueue()
484 # Decide if we can run a new command from the @CmdQueue.
485 # We only run one of these at a time. The @CmdQueue is
486 # used to run BackupPC_link (for the corresponding host),
487 # BackupPC_trashClean, and BackupPC_nightly using a fake
488 # host name of $bpc->adminJob.
489 ############################################################################
490 sub Main_TryToRun_CmdQueue
494 while ( $CmdJob eq "" && @CmdQueue > 0 && $RunNightlyWhenIdle != 1
495 || @CmdQueue > 0 && $RunNightlyWhenIdle == 2
496 && $bpc->isAdminJob($CmdQueue[0]->{host})
499 $req = pop(@CmdQueue);
501 $host = $req->{host};
502 if ( defined($Jobs{$host}) ) {
503 print(LOG $bpc->timeStamp,
504 "Botch on admin job for $host: already in use!!\n");
506 # This could happen during normal opertion: a user could
507 # request a backup while a BackupPC_link is queued from
508 # a previous backup. But it is unlikely. Just put this
509 # request back on the end of the queue.
511 unshift(@CmdQueue, $req);
514 $CmdQueueOn{$host} = 0;
515 my $cmd = $req->{cmd};
516 my $pid = open(FH, "-|");
517 if ( !defined($pid) ) {
518 print(LOG $bpc->timeStamp,
519 "can't fork for $host, request by $req->{user}\n");
526 print(LOG $bpc->timeStamp, "can't exec @$cmd for $host\n");
529 $Jobs{$host}{pid} = $pid;
530 $Jobs{$host}{fh} = *FH;
531 $Jobs{$host}{fn} = fileno(FH);
532 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
533 $Jobs{$host}{startTime} = time;
534 $Jobs{$host}{reqTime} = $req->{reqTime};
535 $cmd = $bpc->execCmd2ShellCmd(@$cmd);
536 $Jobs{$host}{cmd} = $cmd;
537 $Jobs{$host}{user} = $req->{user};
538 $Jobs{$host}{type} = $Status{$host}{type};
539 $Status{$host}{state} = "Status_link_running";
540 $Status{$host}{activeJob} = 1;
541 $Status{$host}{endTime} = time;
542 $CmdJob = $host if ( $host ne $bpc->trashJob );
543 $cmd =~ s/$BinDir\///g;
544 print(LOG $bpc->timeStamp, "Running $cmd (pid=$pid)\n");
545 if ( $cmd =~ /^BackupPC_nightly\s/ ) {
546 $BackupPCNightlyJobs++;
547 $BackupPCNightlyLock++;
552 ############################################################################
553 # Main_TryToRun_Bg_or_User_Queue()
555 # Decide if we can run any new backup requests from @BgQueue
556 # or @UserQueue. Several of these can be run at the same time
557 # based on %Conf settings. Jobs from @UserQueue take priority,
558 # and at total of $Conf{MaxBackups} + $Conf{MaxUserBackups}
559 # simultaneous jobs can run from @UserQueue. After @UserQueue
560 # is exhausted, up to $Conf{MaxBackups} simultaneous jobs can
562 ############################################################################
563 sub Main_TryToRun_Bg_or_User_Queue
566 my(@deferUserQueue, @deferBgQueue);
569 if ( time - $Info{DUlastValueTime} >= 600 ) {
571 # Update our notion of disk usage no more than
572 # once every 10 minutes
574 $du = $bpc->CheckFileSystemUsage($TopDir);
575 $Info{DUlastValue} = $du;
576 $Info{DUlastValueTime} = time;
579 # if we recently checked it then just use the old value
581 $du = $Info{DUlastValue};
583 if ( $Info{DUDailyMaxReset} ) {
584 $Info{DUDailyMaxStartTime} = time;
585 $Info{DUDailyMaxReset} = 0;
586 $Info{DUDailyMax} = 0;
588 if ( $du > $Info{DUDailyMax} ) {
589 $Info{DUDailyMax} = $du;
590 $Info{DUDailyMaxTime} = time;
592 if ( $du > $Conf{DfMaxUsagePct} ) {
593 my @bgQueue = @BgQueue;
597 # When the disk is too full, only run backups that will
598 # do expires, not regular backups
601 foreach $req ( @bgQueue ) {
602 if ( $req->{dumpExpire} ) {
603 unshift(@BgQueue, $req);
605 $BgQueueOn{$req->{host}} = 0;
610 print(LOG $bpc->timeStamp,
611 "Disk too full ($du%); skipped $nSkip hosts\n");
612 $Info{DUDailySkipHostCnt} += $nSkip;
617 # Run background jobs anytime. Previously they were locked out
618 # when BackupPC_nightly was running or pending with this
619 # condition on the while loop:
621 # while ( $RunNightlyWhenIdle == 0 )
625 my(@args, $progName, $type);
626 my $nJobs = keys(%Jobs);
628 # CmdJob and trashClean don't count towards MaxBackups / MaxUserBackups
630 if ( $CmdJob ne "" ) {
631 if ( $BackupPCNightlyJobs ) {
632 $nJobs -= $BackupPCNightlyJobs;
637 $nJobs-- if ( defined($Jobs{$bpc->trashJob} ) );
638 if ( $nJobs < $Conf{MaxBackups} + $Conf{MaxUserBackups}
639 && @UserQueue > 0 ) {
640 $req = pop(@UserQueue);
641 if ( defined($Jobs{$req->{host}}) ) {
642 push(@deferUserQueue, $req);
645 push(@args, $req->{doFull} ? "-f" : "-i")
646 if (( !$req->{restore} ) && ( !$req->{archive} ));
647 $UserQueueOn{$req->{host}} = 0;
648 } elsif ( $nJobs < $Conf{MaxBackups}
649 && (@CmdQueue + $nJobs)
650 <= $Conf{MaxBackups} + $Conf{MaxPendingCmds}
652 $req = pop(@BgQueue);
653 if ( defined($Jobs{$req->{host}}) ) {
655 # Job is currently running for this host; save it for later
657 unshift(@deferBgQueue, $req);
660 $BgQueueOn{$req->{host}} = 0;
663 # Restore the deferred jobs
665 @BgQueue = (@BgQueue, @deferBgQueue);
666 @UserQueue = (@UserQueue, @deferUserQueue);
669 $host = $req->{host};
670 my $user = $req->{user};
671 if ( $req->{restore} ) {
672 $progName = "BackupPC_restore";
674 push(@args, $req->{hostIP}, $req->{host}, $req->{reqFileName});
675 } elsif ( $req->{archive} ) {
676 $progName = "BackupPC_archive";
678 push(@args, $req->{user}, $req->{host}, $req->{reqFileName});
680 $progName = "BackupPC_dump";
682 push(@args, "-d") if ( $req->{dhcp} );
683 push(@args, "-e") if ( $req->{dumpExpire} );
686 my $pid = open(FH, "-|");
687 if ( !defined($pid) ) {
688 print(LOG $bpc->timeStamp,
689 "can't fork to run $progName for $host, request by $user\n");
695 exec("$BinDir/$progName", @args);
696 print(LOG $bpc->timeStamp, "can't exec $progName for $host\n");
699 $Jobs{$host}{pid} = $pid;
700 $Jobs{$host}{fh} = *FH;
701 $Jobs{$host}{fn} = fileno(FH);
702 $Jobs{$host}{dhcp} = $req->{dhcp};
703 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
704 $Jobs{$host}{startTime} = time;
705 $Jobs{$host}{reqTime} = $req->{reqTime};
706 $Jobs{$host}{userReq} = $req->{userReq};
707 $Jobs{$host}{cmd} = $bpc->execCmd2ShellCmd($progName, @args);
708 $Jobs{$host}{user} = $user;
709 $Jobs{$host}{type} = $type;
710 $Status{$host}{userReq} = $req->{userReq}
711 if ( defined($Hosts->{$host}) );
712 if ( !$req->{dhcp} ) {
713 $Status{$host}{state} = "Status_".$type."_starting";
714 $Status{$host}{activeJob} = 1;
715 $Status{$host}{startTime} = time;
716 $Status{$host}{endTime} = "";
721 ############################################################################
724 # If necessary, figure out when to next wakeup based on $Conf{WakeupSchedule},
725 # and then do a select() to wait for the next thing to happen
726 # (timeout, signal, someone sends a message, child dies etc).
727 ############################################################################
730 if ( $NextWakeup <= 0 ) {
732 # Figure out when to next wakeup based on $Conf{WakeupSchedule}.
734 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
736 my($currHours) = $hour + $min / 60 + $sec / 3600;
737 if ( $bpc->ConfigMTime() != $Info{ConfigModTime} ) {
738 ServerReload("Re-read config file because mtime changed");
741 foreach my $t ( @{$Conf{WakeupSchedule} || [0..23]} ) {
742 next if ( $t < 0 || $t > 24 );
743 my $tomorrow = $t + 24;
745 || ($tomorrow - $currHours > 0
746 && $delta > $tomorrow - $currHours) ) {
747 $delta = $tomorrow - $currHours;
748 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
751 || ($t - $currHours > 0 && $delta > $t - $currHours) ) {
752 $delta = $t - $currHours;
753 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
756 $NextWakeup = time + $delta * 3600;
757 $Info{nextWakeup} = $NextWakeup;
758 print(LOG $bpc->timeStamp, "Next wakeup is ",
759 $bpc->timeStamp($NextWakeup, 1), "\n");
762 # Call select(), waiting until either a signal, a timeout,
763 # any output from our jobs, or any messages from clients
765 # select() is where we (hopefully) spend most of our time blocked...
767 my $timeout = $NextWakeup - time;
768 $timeout = 1 if ( $timeout <= 0 );
770 select(my $rout = $FDread, undef, $ein, $timeout);
775 ############################################################################
776 # Main_Process_Signal()
779 ############################################################################
780 sub Main_Process_Signal
785 if ( $SigName eq "HUP" ) {
786 ServerReload("Re-read config file because of a SIG_HUP");
787 } elsif ( $SigName ) {
788 ServerShutdown("Got signal $SigName... cleaning up");
793 ############################################################################
794 # Main_Check_Timeout()
796 # Check if a timeout has occured, and if so, queue all the PCs for backups.
797 # Also does log file aging on the first timeout after midnight.
798 ############################################################################
799 sub Main_Check_Timeout
804 return if ( time < $NextWakeup || $NextWakeup <= 0 );
806 if ( $FirstWakeup ) {
808 # This is the first wakeup after midnight. Do log file aging
809 # and various house keeping.
812 printf(LOG "%s24hr disk usage: %d%% max, %d%% recent,"
813 . " %d skipped hosts\n",
814 $bpc->timeStamp, $Info{DUDailyMax}, $Info{DUlastValue},
815 $Info{DUDailySkipHostCnt});
816 $Info{DUDailyMaxReset} = 1;
817 $Info{DUDailyMaxPrev} = $Info{DUDailyMax};
818 $Info{DUDailySkipHostCntPrev} = $Info{DUDailySkipHostCnt};
819 $Info{DUDailySkipHostCnt} = 0;
820 my $lastLog = $Conf{MaxOldLogFiles} - 1;
821 if ( -f "$LogDir/LOG.$lastLog" ) {
822 print(LOG $bpc->timeStamp,
823 "Removing $LogDir/LOG.$lastLog\n");
824 unlink("$LogDir/LOG.$lastLog");
826 if ( -f "$LogDir/LOG.$lastLog.z" ) {
827 print(LOG $bpc->timeStamp,
828 "Removing $LogDir/LOG.$lastLog.z\n");
829 unlink("$LogDir/LOG.$lastLog.z");
831 print(LOG $bpc->timeStamp, "Aging LOG files, LOG -> LOG.0 -> "
832 . "LOG.1 -> ... -> LOG.$lastLog\n");
833 close(STDERR); # dup of LOG
834 close(STDOUT); # dup of LOG
836 for ( my $i = $lastLog - 1 ; $i >= 0 ; $i-- ) {
838 rename("$LogDir/LOG.$i", "$LogDir/LOG.$j")
839 if ( -f "$LogDir/LOG.$i" );
840 rename("$LogDir/LOG.$i.z", "$LogDir/LOG.$j.z")
841 if ( -f "$LogDir/LOG.$i.z" );
844 # Compress the log file LOG -> LOG.0.z (if enabled).
845 # Otherwise, just rename LOG -> LOG.0.
847 BackupPC::FileZIO->compressCopy("$LogDir/LOG",
850 $Conf{CompressLevel}, 1);
853 # Remember to run the nightly script when the next CmdQueue
856 $RunNightlyWhenIdle = 1;
859 # Write out the current status and then queue all the PCs
863 %BgQueueOn = () if ( @BgQueue == 0 );
864 %UserQueueOn = () if ( @UserQueue == 0 );
865 %CmdQueueOn = () if ( @CmdQueue == 0 );
869 ############################################################################
870 # Main_Check_Job_Messages($fdRead)
872 # Check if select() says we have bytes waiting from any of our jobs.
873 # Handle each of the messages when complete (newline terminated).
874 ############################################################################
875 sub Main_Check_Job_Messages
878 foreach my $host ( keys(%Jobs) ) {
879 next if ( !vec($fdRead, $Jobs{$host}{fn}, 1) );
882 # do a last check to make sure there is something to read so
883 # we are absolutely sure we won't block.
885 vec(my $readMask, $Jobs{$host}{fn}, 1) = 1;
886 if ( !select($readMask, undef, undef, 0.0) ) {
887 print(LOG $bpc->timeStamp, "Botch in Main_Check_Job_Messages:"
888 . " nothing to read from $host. Debug dump:\n");
889 my($dump) = Data::Dumper->new(
890 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
891 [qw(*Clients, *Jobs *FDread, *fdRead)]);
893 print(LOG $dump->Dump);
896 my $nbytes = sysread($Jobs{$host}{fh}, $mesg, 1024);
897 $Jobs{$host}{mesg} .= $mesg if ( $nbytes > 0 );
899 # Process any complete lines of output from this jobs.
900 # Any output to STDOUT or STDERR from the children is processed here.
902 while ( $Jobs{$host}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
904 $Jobs{$host}{mesg} = $2;
905 if ( $Jobs{$host}{dhcp} ) {
906 if ( $mesg =~ /^DHCP (\S+) (\S+)/ ) {
907 my $newHost = $bpc->uriUnesc($2);
908 if ( defined($Jobs{$newHost}) ) {
909 print(LOG $bpc->timeStamp,
910 "Backup on $newHost is already running\n");
911 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
915 $Jobs{$host}{dhcpHostIP} = $host;
916 $Status{$newHost}{dhcpHostIP} = $host;
917 $Jobs{$newHost} = $Jobs{$host};
918 delete($Jobs{$host});
920 $Status{$host}{state} = "Status_backup_starting";
921 $Status{$host}{activeJob} = 1;
922 $Status{$host}{startTime} = $Jobs{$host}{startTime};
923 $Status{$host}{endTime} = "";
924 $Jobs{$host}{dhcp} = 0;
926 print(LOG $bpc->timeStamp, "dhcp $host: $mesg\n");
928 } elsif ( $mesg =~ /^started (.*) dump, share=(.*)/ ) {
929 $Jobs{$host}{type} = $1;
930 $Jobs{$host}{shareName} = $2;
931 print(LOG $bpc->timeStamp,
932 "Started $1 backup on $host (pid=$Jobs{$host}{pid}",
933 $Jobs{$host}{dhcpHostIP}
934 ? ", dhcp=$Jobs{$host}{dhcpHostIP}" : "",
935 ", share=$Jobs{$host}{shareName})\n");
936 $Status{$host}{state} = "Status_backup_in_progress";
937 $Status{$host}{reason} = "";
938 $Status{$host}{type} = $1;
939 $Status{$host}{startTime} = time;
940 $Status{$host}{deadCnt} = 0;
941 $Status{$host}{aliveCnt}++;
942 $Status{$host}{dhcpCheckCnt}--
943 if ( $Status{$host}{dhcpCheckCnt} > 0 );
944 } elsif ( $mesg =~ /^xferPids (.*)/ ) {
945 $Jobs{$host}{xferPid} = $1;
946 } elsif ( $mesg =~ /^started_restore/ ) {
947 $Jobs{$host}{type} = "restore";
948 print(LOG $bpc->timeStamp,
949 "Started restore on $host"
950 . " (pid=$Jobs{$host}{pid})\n");
951 $Status{$host}{state} = "Status_restore_in_progress";
952 $Status{$host}{reason} = "";
953 $Status{$host}{type} = "restore";
954 $Status{$host}{startTime} = time;
955 $Status{$host}{deadCnt} = 0;
956 $Status{$host}{aliveCnt}++;
957 } elsif ( $mesg =~ /^started_archive/ ) {
958 $Jobs{$host}{type} = "archive";
959 print(LOG $bpc->timeStamp,
960 "Started archive on $host"
961 . " (pid=$Jobs{$host}{pid})\n");
962 $Status{$host}{state} = "Status_archive_in_progress";
963 $Status{$host}{reason} = "";
964 $Status{$host}{type} = "archive";
965 $Status{$host}{startTime} = time;
966 $Status{$host}{deadCnt} = 0;
967 $Status{$host}{aliveCnt}++;
968 } elsif ( $mesg =~ /^(full|incr) backup complete/ ) {
969 print(LOG $bpc->timeStamp, "Finished $1 backup on $host\n");
970 $Status{$host}{reason} = "Reason_backup_done";
971 delete($Status{$host}{error});
972 delete($Status{$host}{errorTime});
973 $Status{$host}{endTime} = time;
974 $Status{$host}{lastGoodBackupTime} = time;
975 } elsif ( $mesg =~ /^backups disabled/ ) {
976 print(LOG $bpc->timeStamp,
977 "Ignoring old backup error on $host\n");
978 $Status{$host}{reason} = "Reason_backup_done";
979 delete($Status{$host}{error});
980 delete($Status{$host}{errorTime});
981 $Status{$host}{endTime} = time;
982 } elsif ( $mesg =~ /^restore complete/ ) {
983 print(LOG $bpc->timeStamp, "Finished restore on $host\n");
984 $Status{$host}{reason} = "Reason_restore_done";
985 delete($Status{$host}{error});
986 delete($Status{$host}{errorTime});
987 $Status{$host}{endTime} = time;
988 } elsif ( $mesg =~ /^archive complete/ ) {
989 print(LOG $bpc->timeStamp, "Finished archive on $host\n");
990 $Status{$host}{reason} = "Reason_archive_done";
991 delete($Status{$host}{error});
992 delete($Status{$host}{errorTime});
993 $Status{$host}{endTime} = time;
994 } elsif ( $mesg =~ /^nothing to do/ ) {
995 if ( $Status{$host}{reason} ne "Reason_backup_failed"
996 && $Status{$host}{reason} ne "Reason_restore_failed" ) {
997 $Status{$host}{state} = "Status_idle";
998 $Status{$host}{reason} = "Reason_nothing_to_do";
999 $Status{$host}{startTime} = time;
1001 $Status{$host}{dhcpCheckCnt}--
1002 if ( $Status{$host}{dhcpCheckCnt} > 0 );
1003 } elsif ( $mesg =~ /^no ping response/
1004 || $mesg =~ /^ping too slow/
1005 || $mesg =~ /^host not found/ ) {
1006 $Status{$host}{state} = "Status_idle";
1007 if ( $Status{$host}{userReq}
1008 || $Status{$host}{reason} ne "Reason_backup_failed"
1009 || $Status{$host}{error} =~ /^aborted by user/ ) {
1010 $Status{$host}{reason} = "Reason_no_ping";
1011 $Status{$host}{error} = $mesg;
1012 $Status{$host}{startTime} = time;
1014 $Status{$host}{deadCnt}++;
1015 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1016 $Status{$host}{aliveCnt} = 0;
1018 } elsif ( $mesg =~ /^dump failed: (.*)/ ) {
1019 $Status{$host}{state} = "Status_idle";
1020 $Status{$host}{error} = $1;
1021 $Status{$host}{errorTime} = time;
1022 $Status{$host}{endTime} = time;
1023 if ( $Status{$host}{reason}
1024 eq "Reason_backup_canceled_by_user" ) {
1025 print(LOG $bpc->timeStamp,
1026 "Backup canceled on $host ($1)\n");
1028 $Status{$host}{reason} = "Reason_backup_failed";
1029 print(LOG $bpc->timeStamp,
1030 "Backup failed on $host ($1)\n");
1032 } elsif ( $mesg =~ /^restore failed: (.*)/ ) {
1033 $Status{$host}{state} = "Status_idle";
1034 $Status{$host}{error} = $1;
1035 $Status{$host}{errorTime} = time;
1036 $Status{$host}{endTime} = time;
1037 if ( $Status{$host}{reason}
1038 eq "Reason_restore_canceled_by_user" ) {
1039 print(LOG $bpc->timeStamp,
1040 "Restore canceled on $host ($1)\n");
1042 $Status{$host}{reason} = "Reason_restore_failed";
1043 print(LOG $bpc->timeStamp,
1044 "Restore failed on $host ($1)\n");
1046 } elsif ( $mesg =~ /^archive failed: (.*)/ ) {
1047 $Status{$host}{state} = "Status_idle";
1048 $Status{$host}{error} = $1;
1049 $Status{$host}{errorTime} = time;
1050 $Status{$host}{endTime} = time;
1051 if ( $Status{$host}{reason}
1052 eq "Reason_archive_canceled_by_user" ) {
1053 print(LOG $bpc->timeStamp,
1054 "Archive canceled on $host ($1)\n");
1056 $Status{$host}{reason} = "Reason_archive_failed";
1057 print(LOG $bpc->timeStamp,
1058 "Archive failed on $host ($1)\n");
1060 } elsif ( $mesg =~ /^log\s+(.*)/ ) {
1061 print(LOG $bpc->timeStamp, "$1\n");
1062 } elsif ( $mesg =~ /^BackupPC_stats (\d+) = (.*)/ ) {
1063 my $chunk = int($1 / 16);
1064 my @f = split(/,/, $2);
1065 $Info{pool}{$f[0]}[$chunk]{FileCnt} += $f[1];
1066 $Info{pool}{$f[0]}[$chunk]{DirCnt} += $f[2];
1067 $Info{pool}{$f[0]}[$chunk]{Kb} += $f[3];
1068 $Info{pool}{$f[0]}[$chunk]{Kb2} += $f[4];
1069 $Info{pool}{$f[0]}[$chunk]{KbRm} += $f[5];
1070 $Info{pool}{$f[0]}[$chunk]{FileCntRm} += $f[6];
1071 $Info{pool}{$f[0]}[$chunk]{FileCntRep} += $f[7];
1072 $Info{pool}{$f[0]}[$chunk]{FileRepMax} = $f[8]
1073 if ( $Info{pool}{$f[0]}[$chunk]{FileRepMax} < $f[8] );
1074 $Info{pool}{$f[0]}[$chunk]{FileCntRename} += $f[9];
1075 $Info{pool}{$f[0]}[$chunk]{FileLinkMax} = $f[10]
1076 if ( $Info{pool}{$f[0]}[$chunk]{FileLinkMax} < $f[10] );
1077 $Info{pool}{$f[0]}[$chunk]{FileLinkTotal} += $f[11];
1078 $Info{pool}{$f[0]}[$chunk]{Time} = time;
1079 } elsif ( $mesg =~ /^BackupPC_nightly lock_off/ ) {
1080 $BackupPCNightlyLock--;
1081 if ( $BackupPCNightlyLock == 0 ) {
1083 # This means the last BackupPC_nightly is done with
1084 # the pool clean, so it's ok to start running regular
1085 # backups again. But starting in 3.0 regular jobs
1086 # are decoupled from BackupPC_nightly.
1088 $RunNightlyWhenIdle = 0;
1090 } elsif ( $mesg =~ /^processState\s+(.+)/ ) {
1091 $Jobs{$host}{processState} = $1;
1092 } elsif ( $mesg =~ /^link\s+(.+)/ ) {
1094 $Status{$h}{needLink} = 1;
1096 print(LOG $bpc->timeStamp, "$host: $mesg\n");
1100 # shut down the client connection if we read EOF
1102 if ( $nbytes <= 0 ) {
1103 close($Jobs{$host}{fh});
1104 vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1105 if ( $CmdJob eq $host || $bpc->isAdminJob($host) ) {
1106 my $cmd = $Jobs{$host}{cmd};
1107 $cmd =~ s/$BinDir\///g;
1108 print(LOG $bpc->timeStamp, "Finished $host ($cmd)\n");
1109 $Status{$host}{state} = "Status_idle";
1110 $Status{$host}{endTime} = time;
1111 if ( $cmd =~ /^BackupPC_nightly\s/ ) {
1112 $BackupPCNightlyJobs--;
1113 #print(LOG $bpc->timeStamp, "BackupPC_nightly done; now"
1114 # . " have $BackupPCNightlyJobs running\n");
1115 if ( $BackupPCNightlyJobs <= 0 ) {
1117 # Last BackupPC_nightly has finished
1119 $BackupPCNightlyJobs = 0;
1120 $RunNightlyWhenIdle = 0;
1123 # Combine the 16 per-directory results
1125 for my $p ( qw(pool cpool) ) {
1126 $Info{"${p}FileCnt"} = 0;
1127 $Info{"${p}DirCnt"} = 0;
1128 $Info{"${p}Kb"} = 0;
1129 $Info{"${p}Kb2"} = 0;
1130 $Info{"${p}KbRm"} = 0;
1131 $Info{"${p}FileCntRm"} = 0;
1132 $Info{"${p}FileCntRep"} = 0;
1133 $Info{"${p}FileRepMax"} = 0;
1134 $Info{"${p}FileCntRename"} = 0;
1135 $Info{"${p}FileLinkMax"} = 0;
1136 $Info{"${p}Time"} = 0;
1137 for ( my $i = 0 ; $i < 16 ; $i++ ) {
1138 $Info{"${p}FileCnt"}
1139 += $Info{pool}{$p}[$i]{FileCnt};
1141 += $Info{pool}{$p}[$i]{DirCnt};
1143 += $Info{pool}{$p}[$i]{Kb};
1145 += $Info{pool}{$p}[$i]{Kb2};
1147 += $Info{pool}{$p}[$i]{KbRm};
1148 $Info{"${p}FileCntRm"}
1149 += $Info{pool}{$p}[$i]{FileCntRm};
1150 $Info{"${p}FileCntRep"}
1151 += $Info{pool}{$p}[$i]{FileCntRep};
1152 $Info{"${p}FileRepMax"}
1153 = $Info{pool}{$p}[$i]{FileRepMax}
1154 if ( $Info{"${p}FileRepMax"} <
1155 $Info{pool}{$p}[$i]{FileRepMax} );
1156 $Info{"${p}FileCntRename"}
1157 += $Info{pool}{$p}[$i]{FileCntRename};
1158 $Info{"${p}FileLinkMax"}
1159 = $Info{pool}{$p}[$i]{FileLinkMax}
1160 if ( $Info{"${p}FileLinkMax"} <
1161 $Info{pool}{$p}[$i]{FileLinkMax} );
1162 $Info{"${p}Time"} = $Info{pool}{$p}[$i]{Time}
1163 if ( $Info{"${p}Time"} <
1164 $Info{pool}{$p}[$i]{Time} );
1166 printf(LOG "%s%s nightly clean removed %d files of"
1168 $bpc->timeStamp, ucfirst($p),
1169 $Info{"${p}FileCntRm"},
1170 $Info{"${p}KbRm"} / (1000 * 1024));
1171 printf(LOG "%s%s is %.2fGB, %d files (%d repeated, "
1172 . "%d max chain, %d max links), %d directories\n",
1173 $bpc->timeStamp, ucfirst($p),
1174 $Info{"${p}Kb"} / (1000 * 1024),
1175 $Info{"${p}FileCnt"}, $Info{"${p}FileCntRep"},
1176 $Info{"${p}FileRepMax"},
1177 $Info{"${p}FileLinkMax"}, $Info{"${p}DirCnt"});
1185 # Queue BackupPC_link to complete the backup
1186 # processing for this host.
1188 if ( defined($Status{$host})
1189 && ($Status{$host}{reason} eq "Reason_backup_done"
1190 || $Status{$host}{needLink}) ) {
1192 } elsif ( defined($Status{$host}) ) {
1193 $Status{$host}{state} = "Status_idle";
1196 delete($Jobs{$host});
1197 $Status{$host}{activeJob} = 0 if ( defined($Status{$host}) );
1201 # When we are idle (empty Jobs, CmdQueue, BgQueue, UserQueue) we
1202 # do a pass over %Status updating the deadCnt and aliveCnt for
1203 # DHCP hosts. The reason we need to do this later is we can't
1204 # be sure whether a DHCP host is alive or dead until we have passed
1205 # over all the DHCP pool.
1207 return if ( @CmdQueue || @BgQueue || @UserQueue || keys(%Jobs) > 1 );
1208 foreach my $host ( keys(%Status) ) {
1209 next if ( $Status{$host}{dhcpCheckCnt} <= 0 );
1210 $Status{$host}{deadCnt} += $Status{$host}{dhcpCheckCnt};
1211 $Status{$host}{dhcpCheckCnt} = 0;
1212 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1213 $Status{$host}{aliveCnt} = 0;
1218 ############################################################################
1219 # Main_Check_Client_Messages($fdRead)
1221 # Check for, and process, any output from our clients. Also checks
1222 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
1223 ############################################################################
1224 sub Main_Check_Client_Messages
1227 foreach my $client ( keys(%Clients) ) {
1228 next if ( !vec($fdRead, $Clients{$client}{fn}, 1) );
1231 # do a last check to make sure there is something to read so
1232 # we are absolutely sure we won't block.
1234 vec(my $readMask, $Clients{$client}{fn}, 1) = 1;
1235 if ( !select($readMask, undef, undef, 0.0) ) {
1236 print(LOG $bpc->timeStamp, "Botch in Main_Check_Client_Messages:"
1237 . " nothing to read from $client. Debug dump:\n");
1238 my($dump) = Data::Dumper->new(
1239 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
1240 [qw(*Clients, *Jobs *FDread, *fdRead)]);
1242 print(LOG $dump->Dump);
1245 my $nbytes = sysread($Clients{$client}{fh}, $mesg, 1024);
1246 $Clients{$client}{mesg} .= $mesg if ( $nbytes > 0 );
1248 # Process any complete lines received from this client.
1250 while ( $Clients{$client}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
1253 $Clients{$client}{mesg} = $2;
1255 # Authenticate the message by checking the MD5 digest
1257 my $md5 = Digest::MD5->new;
1258 if ( $cmd !~ /^(.{22}) (.*)/
1259 || ($md5->add($Clients{$client}{seed}
1260 . $Clients{$client}{mesgCnt}
1261 . $Conf{ServerMesgSecret} . $2),
1262 $md5->b64digest ne $1) ) {
1263 print(LOG $bpc->timeStamp, "Corrupted message '$cmd' from"
1264 . " client '$Clients{$client}{clientName}':"
1265 . " shutting down client connection\n");
1269 $Clients{$client}{mesgCnt}++;
1270 $cmd = decode_utf8($2);
1271 if ( $cmd =~ /^stop (\S+)\s+(\S+)\s+(\S*)/ ) {
1275 $host = $bpc->uriUnesc($host);
1276 if ( $CmdJob ne $host && defined($Status{$host})
1277 && defined($Jobs{$host}) ) {
1278 print(LOG $bpc->timeStamp,
1279 "Stopping current $Jobs{$host}{type} of $host,"
1280 . " request by $user (backoff=$backoff)\n");
1281 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1283 # Don't close the pipe now; wait until the child
1284 # really exits later. Otherwise close() will
1285 # block until the child has exited.
1287 ##vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1288 ##close($Jobs{$host}{fh});
1289 ##delete($Jobs{$host});
1291 $Status{$host}{state} = "Status_idle";
1292 if ( $Jobs{$host}{type} eq "restore" ) {
1293 $Status{$host}{reason}
1294 = "Reason_restore_canceled_by_user";
1295 } elsif ( $Jobs{$host}{type} eq "archive" ) {
1296 $Status{$host}{reason}
1297 = "Reason_archive_canceled_by_user";
1299 $Status{$host}{reason}
1300 = "Reason_backup_canceled_by_user";
1302 $Status{$host}{activeJob} = 0;
1303 $Status{$host}{startTime} = time;
1304 $reply = "ok: $Jobs{$host}{type} of $host canceled";
1305 } elsif ( $BgQueueOn{$host} || $UserQueueOn{$host} ) {
1306 print(LOG $bpc->timeStamp,
1307 "Stopping pending backup of $host,"
1308 . " request by $user (backoff=$backoff)\n");
1309 @BgQueue = grep($_->{host} ne $host, @BgQueue);
1310 @UserQueue = grep($_->{host} ne $host, @UserQueue);
1311 $BgQueueOn{$host} = $UserQueueOn{$host} = 0;
1312 $reply = "ok: pending backup of $host canceled";
1314 print(LOG $bpc->timeStamp,
1315 "Nothing to do for stop backup of $host,"
1316 . " request by $user (backoff=$backoff)\n");
1317 $reply = "ok: no backup was pending or running";
1319 if ( defined($Status{$host}) && $backoff ne "" ) {
1320 if ( $backoff > 0 ) {
1321 $Status{$host}{backoffTime} = time + $backoff * 3600;
1323 delete($Status{$host}{backoffTime});
1326 } elsif ( $cmd =~ /^backup all$/ ) {
1328 } elsif ( $cmd =~ /^BackupPC_nightly run$/ ) {
1329 $RunNightlyWhenIdle = 1;
1330 } elsif ( $cmd =~ /^backup (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1335 $host = $bpc->uriUnesc($host);
1336 $hostIP = $bpc->uriUnesc($hostIP);
1337 if ( !defined($Status{$host}) ) {
1338 print(LOG $bpc->timeStamp,
1339 "User $user requested backup of unknown host"
1341 $reply = "error: unknown host $host";
1343 print(LOG $bpc->timeStamp,
1344 "User $user requested backup of $host"
1346 if ( $BgQueueOn{$hostIP} ) {
1347 @BgQueue = grep($_->{host} ne $hostIP, @BgQueue);
1348 $BgQueueOn{$hostIP} = 0;
1350 if ( $UserQueueOn{$hostIP} ) {
1351 @UserQueue = grep($_->{host} ne $hostIP, @UserQueue);
1352 $UserQueueOn{$hostIP} = 0;
1354 unshift(@UserQueue, {
1360 dhcp => $hostIP eq $host ? 0 : 1,
1362 $UserQueueOn{$hostIP} = 1;
1363 $reply = "ok: requested backup of $host";
1365 } elsif ( $cmd =~ /^archive (\S+)\s+(\S+)\s+(\S+)/ ) {
1367 my $archivehost = $2;
1368 my $reqFileName = $3;
1369 $host = $bpc->uriUnesc($archivehost);
1370 if ( !defined($Status{$host}) ) {
1371 print(LOG $bpc->timeStamp,
1372 "User $user requested archive of unknown archive host"
1374 $reply = "archive error: unknown archive host $host";
1376 print(LOG $bpc->timeStamp,
1377 "User $user requested archive on $host"
1379 if ( defined($Jobs{$host}) ) {
1380 $reply = "Archive currently running on $host, please try later";
1382 unshift(@UserQueue, {
1385 reqFileName => $reqFileName,
1391 $UserQueueOn{$host} = 1;
1392 $reply = "ok: requested archive on $host";
1395 } elsif ( $cmd =~ /^restore (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1399 my $reqFileName = $4;
1400 $host = $bpc->uriUnesc($host);
1401 $hostIP = $bpc->uriUnesc($hostIP);
1402 if ( !defined($Status{$host}) ) {
1403 print(LOG $bpc->timeStamp,
1404 "User $user requested restore to unknown host"
1406 $reply = "restore error: unknown host $host";
1408 print(LOG $bpc->timeStamp,
1409 "User $user requested restore to $host"
1411 unshift(@UserQueue, {
1414 reqFileName => $reqFileName,
1420 $UserQueueOn{$host} = 1;
1421 if ( defined($Jobs{$host}) ) {
1422 $reply = "ok: requested restore of $host, but a"
1423 . " job is currently running,"
1424 . " so this request will start later";
1426 $reply = "ok: requested restore of $host";
1429 } elsif ( $cmd =~ /^status\s*(.*)/ ) {
1431 my($dump, @values, @names);
1432 foreach my $type ( split(/\s+/, $args) ) {
1433 if ( $type =~ /^queues/ ) {
1434 push(@values, \@BgQueue, \@UserQueue, \@CmdQueue);
1435 push(@names, qw(*BgQueue *UserQueue *CmdQueue));
1436 } elsif ( $type =~ /^jobs/ ) {
1437 push(@values, \%Jobs);
1438 push(@names, qw(*Jobs));
1439 } elsif ( $type =~ /^queueLen/ ) {
1441 BgQueue => scalar(@BgQueue),
1442 UserQueue => scalar(@UserQueue),
1443 CmdQueue => scalar(@CmdQueue),
1445 push(@names, qw(*QueueLen));
1446 } elsif ( $type =~ /^info/ ) {
1447 push(@values, \%Info);
1448 push(@names, qw(*Info));
1449 } elsif ( $type =~ /^hosts/ ) {
1450 push(@values, \%Status);
1451 push(@names, qw(*Status));
1452 } elsif ( $type =~ /^host\((.*)\)/ ) {
1453 my $h = $bpc->uriUnesc($1);
1454 if ( defined($Status{$h}) ) {
1457 BgQueueOn => $BgQueueOn{$h},
1458 UserQueueOn => $UserQueueOn{$h},
1459 CmdQueueOn => $CmdQueueOn{$h},
1461 push(@names, qw(*StatusHost));
1463 print(LOG $bpc->timeStamp,
1464 "Unknown host $h for status request\n");
1467 print(LOG $bpc->timeStamp,
1468 "Unknown status request $type\n");
1471 $dump = Data::Dumper->new(\@values, \@names);
1473 $reply = $dump->Dump;
1474 } elsif ( $cmd =~ /^link\s+(.+)/ ) {
1476 $host = $bpc->uriUnesc($host);
1478 } elsif ( $cmd =~ /^log\s+(.*)/ ) {
1479 print(LOG $bpc->timeStamp, "$1\n");
1480 } elsif ( $cmd =~ /^server\s+(\w+)/ ) {
1482 if ( $type eq 'reload' ) {
1483 ServerReload("Reloading config/host files via CGI request");
1484 } elsif ( $type eq 'shutdown' ) {
1485 $reply = "Shutting down...\n";
1486 syswrite($Clients{$client}{fh}, $reply, length($reply));
1487 ServerShutdown("Server shutting down...");
1489 } elsif ( $cmd =~ /^quit/ || $cmd =~ /^exit/ ) {
1493 print(LOG $bpc->timeStamp, "Unknown command $cmd\n");
1494 $reply = "error: bad command $cmd";
1497 # send a reply to the client, at a minimum "ok\n".
1499 $reply = "ok" if ( $reply eq "" );
1501 syswrite($Clients{$client}{fh}, $reply, length($reply));
1504 # Detect possible denial-of-service attack from sending a huge line
1505 # (ie: never terminated). 32K seems to be plenty big enough as
1508 if ( length($Clients{$client}{mesg}) > 32 * 1024 ) {
1509 print(LOG $bpc->timeStamp, "Line too long from client"
1510 . " '$Clients{$client}{clientName}':"
1511 . " shutting down client connection\n");
1515 # Shut down the client connection if we read EOF
1517 if ( $nbytes <= 0 ) {
1518 close($Clients{$client}{fh});
1519 vec($FDread, $Clients{$client}{fn}, 1) = 0;
1520 delete($Clients{$client});
1524 # Accept any new connections on each of our listen sockets
1526 if ( vec($fdRead, fileno(SERVER_UNIX), 1) ) {
1528 my $paddr = accept(CLIENT, SERVER_UNIX);
1530 $Clients{$ClientConnCnt}{clientName} = "unix socket";
1531 $Clients{$ClientConnCnt}{mesg} = "";
1532 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1533 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1534 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1536 # Generate and send unique seed for MD5 digests to avoid
1537 # replay attacks. See BackupPC::Lib::ServerMesg().
1539 my $seed = time . ",$ClientConnCnt,$$,0\n";
1540 $Clients{$ClientConnCnt}{seed} = $seed;
1541 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1542 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1544 if ( $ServerInetPort > 0 && vec($fdRead, fileno(SERVER_INET), 1) ) {
1546 my $paddr = accept(CLIENT, SERVER_INET);
1547 my($port,$iaddr) = sockaddr_in($paddr);
1548 my $name = gethostbyaddr($iaddr, AF_INET);
1550 $Clients{$ClientConnCnt}{mesg} = "";
1551 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1552 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1553 $Clients{$ClientConnCnt}{clientName} = "$name:$port";
1554 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1556 # Generate and send unique seed for MD5 digests to avoid
1557 # replay attacks. See BackupPC::Lib::ServerMesg().
1559 my $seed = time . ",$ClientConnCnt,$$,$port\n";
1560 $Clients{$ClientConnCnt}{seed} = $seed;
1561 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1562 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1566 ###########################################################################
1567 # Miscellaneous subroutines
1568 ###########################################################################
1571 # Write the current status to $LogDir/status.pl
1575 my($dump) = Data::Dumper->new(
1576 [ \%Info, \%Status],
1577 [qw(*Info *Status)]);
1579 if ( open(STATUS, ">", "$LogDir/status.pl") ) {
1580 print(STATUS $dump->Dump);
1586 # Compare function for host sort. Hosts with errors go first,
1587 # sorted with the oldest errors first. The remaining hosts
1588 # are sorted so that those with the oldest backups go first.
1593 # Hosts with errors go before hosts without errors
1595 return -1 if ( $Status{$a}{error} ne "" && $Status{$b}{error} eq "" );
1598 # Hosts with no errors go after hosts with errors
1601 return 1 if ( $Status{$a}{error} eq "" && $Status{$b}{error} ne "" );
1604 # hosts with the older last good backups sort earlier
1606 my $r = $Status{$a}{lastGoodBackupTime} <=> $Status{$b}{lastGoodBackupTime};
1607 return $r if ( $r );
1610 # Finally, just sort based on host name
1616 # Queue all the hosts for backup. This means queuing all the fixed
1617 # ip hosts and all the dhcp address ranges. We also additionally
1618 # queue the dhcp hosts with a -e flag to check for expired dumps.
1623 foreach my $host ( sort(HostSortCompare keys(%$Hosts)) ) {
1624 delete($Status{$host}{backoffTime})
1625 if ( defined($Status{$host}{backoffTime})
1626 && $Status{$host}{backoffTime} < time );
1627 next if ( defined($Jobs{$host})
1628 || $BgQueueOn{$host}
1629 || $UserQueueOn{$host}
1630 || $CmdQueueOn{$host} );
1631 if ( $Hosts->{$host}{dhcp} ) {
1632 $Status{$host}{dhcpCheckCnt}++;
1633 if ( $RunNightlyWhenIdle ) {
1635 # Once per night queue a check for DHCP hosts that just
1636 # checks for expired dumps. We need to do this to handle
1637 # the case when a DHCP host has not been on the network for
1638 # a long time, and some of the old dumps need to be expired.
1639 # Normally expiry checks are done by BackupPC_dump only
1640 # after the DHCP hosts has been detected on the network.
1643 {host => $host, user => "BackupPC", reqTime => time,
1644 dhcp => 0, dumpExpire => 1});
1645 $BgQueueOn{$host} = 1;
1649 # this is a fixed ip host: queue it
1651 if ( $Info{DUlastValue} > $Conf{DfMaxUsagePct} ) {
1653 # Since we are out of disk space, instead of queuing
1654 # a regular job, queue an expire check instead. That
1655 # way if the admin reduces the number of backups to
1656 # keep then we will actually delete them. Otherwise
1657 # BackupPC_dump will never run since we have exceeded
1662 {host => $host, user => "BackupPC", reqTime => time,
1663 dhcp => $Hosts->{$host}{dhcp}, dumpExpire => 1});
1666 # Queue regular background backup
1669 {host => $host, user => "BackupPC", reqTime => time,
1670 dhcp => $Hosts->{$host}{dhcp}});
1672 $BgQueueOn{$host} = 1;
1676 print(LOG $bpc->timeStamp,
1677 "Disk too full ($Info{DUlastValue}%); skipped $nSkip hosts\n");
1678 $Info{DUDailySkipHostCnt} += $nSkip;
1680 foreach my $dhcp ( @{$Conf{DHCPAddressRanges}} ) {
1681 for ( my $i = $dhcp->{first} ; $i <= $dhcp->{last} ; $i++ ) {
1682 my $ipAddr = "$dhcp->{ipAddrBase}.$i";
1683 next if ( defined($Jobs{$ipAddr})
1684 || $BgQueueOn{$ipAddr}
1685 || $UserQueueOn{$ipAddr}
1686 || $CmdQueueOn{$ipAddr} );
1688 # this is a potential dhcp ip address (we don't know the
1689 # host name yet): queue it
1692 {host => $ipAddr, user => "BackupPC", reqTime => time,
1694 $BgQueueOn{$ipAddr} = 1;
1700 # Queue a BackupPC_link for the given host
1706 return if ( $CmdQueueOn{$host} );
1707 $Status{$host}{state} = "Status_link_pending";
1708 $Status{$host}{needLink} = 0;
1709 unshift(@CmdQueue, {
1713 cmd => ["$BinDir/BackupPC_link", $host],
1715 $CmdQueueOn{$host} = 1;
1719 # Read the hosts file, and update Status if any hosts have been
1720 # added or deleted. We also track the mtime so the only need to
1721 # update the hosts file on changes.
1723 # This function is called at startup, SIGHUP, and on each wakeup.
1724 # It returns 1 on success and undef on failure.
1731 # Nothing to do if we already have the current hosts file
1733 return 1 if ( !$force && defined($Hosts)
1734 && $Info{HostsModTime} == $bpc->HostsMTime() );
1735 if ( !defined($newHosts = $bpc->HostInfoRead()) ) {
1736 print(LOG $bpc->timeStamp, "Can't read hosts file!\n");
1739 print(LOG $bpc->timeStamp, "Reading hosts file\n");
1741 $Info{HostsModTime} = $bpc->HostsMTime();
1743 # Now update %Status in case any hosts have been added or deleted
1745 foreach my $host ( sort(keys(%$Hosts)) ) {
1746 next if ( defined($Status{$host}) );
1747 $Status{$host}{state} = "Status_idle";
1748 print(LOG $bpc->timeStamp, "Added host $host to backup list\n");
1750 foreach my $host ( sort(keys(%Status)) ) {
1751 next if ( $host eq $bpc->trashJob
1752 || $bpc->isAdminJob($host)
1753 || defined($Hosts->{$host})
1754 || defined($Jobs{$host})
1755 || $BgQueueOn{$host}
1756 || $UserQueueOn{$host}
1757 || $CmdQueueOn{$host} );
1758 print(LOG $bpc->timeStamp, "Deleted host $host from backup list\n");
1759 delete($Status{$host});
1765 # Remember the signal name for later processing
1771 foreach my $host ( keys(%Jobs) ) {
1772 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1775 # In case we are inside the exit handler, reopen the log file
1779 print(LOG "Fatal error: unhandled signal $SigName\n");
1780 unlink("$LogDir/BackupPC.pid");
1781 confess("Got new signal $SigName... quitting\n");
1788 # Open the log file and point STDOUT and STDERR there too
1792 mkpath($LogDir, 0, 0777) if ( !-d $LogDir );
1793 open(LOG, ">>$LogDir/LOG")
1794 || die("Can't create LOG file $LogDir/LOG");
1797 open(STDOUT, ">&LOG");
1798 open(STDERR, ">&LOG");
1799 select(LOG); $| = 1;
1800 select(STDERR); $| = 1;
1801 select(STDOUT); $| = 1;
1805 # Initialize the unix-domain and internet-domain sockets that
1806 # we listen to for client connections (from the CGI script and
1807 # some of the BackupPC sub-programs).
1809 sub ServerSocketInit
1811 if ( !defined(fileno(SERVER_UNIX)) ) {
1813 # one-time only: initialize unix-domain socket
1815 if ( !socket(SERVER_UNIX, PF_UNIX, SOCK_STREAM, 0) ) {
1816 print(LOG $bpc->timeStamp, "unix socket() failed: $!\n");
1819 my $sockFile = "$LogDir/BackupPC.sock";
1821 if ( !bind(SERVER_UNIX, sockaddr_un($sockFile)) ) {
1822 print(LOG $bpc->timeStamp, "unix bind() failed: $!\n");
1825 if ( !listen(SERVER_UNIX, SOMAXCONN) ) {
1826 print(LOG $bpc->timeStamp, "unix listen() failed: $!\n");
1829 vec($FDread, fileno(SERVER_UNIX), 1) = 1;
1831 return if ( $ServerInetPort == $Conf{ServerPort} );
1832 if ( $ServerInetPort > 0 ) {
1833 vec($FDread, fileno(SERVER_INET), 1) = 0;
1835 $ServerInetPort = -1;
1837 if ( $Conf{ServerPort} > 0 ) {
1839 # Setup a socket to listen on $Conf{ServerPort}
1841 my $proto = getprotobyname('tcp');
1842 if ( !socket(SERVER_INET, PF_INET, SOCK_STREAM, $proto) ) {
1843 print(LOG $bpc->timeStamp, "inet socket() failed: $!\n");
1846 if ( !setsockopt(SERVER_INET, SOL_SOCKET, SO_REUSEADDR, pack("l",1)) ) {
1847 print(LOG $bpc->timeStamp, "setsockopt() failed: $!\n");
1850 if ( !bind(SERVER_INET, sockaddr_in($Conf{ServerPort}, INADDR_ANY)) ) {
1851 print(LOG $bpc->timeStamp, "inet bind() failed: $!\n");
1854 if ( !listen(SERVER_INET, SOMAXCONN) ) {
1855 print(LOG $bpc->timeStamp, "inet listen() failed: $!\n");
1858 vec($FDread, fileno(SERVER_INET), 1) = 1;
1859 $ServerInetPort = $Conf{ServerPort};
1864 # Reload the server. Used by Main_Process_Signal when $SigName eq "HUP"
1865 # or when the command "server reload" is received.
1870 $mesg = $bpc->ConfigRead() || $mesg;
1871 print(LOG $bpc->timeStamp, "$mesg\n");
1872 $Info{ConfigModTime} = $bpc->ConfigMTime();
1873 %Conf = $bpc->Conf();
1874 umask($Conf{UmaskMode});
1878 $Info{ConfigLTime} = time;
1882 # Gracefully shutdown the server. Used by Main_Process_Signal when
1883 # $SigName ne "" && $SigName ne "HUP" or when the command
1884 # "server shutdown" is received.
1889 print(LOG $bpc->timeStamp, "$mesg\n");
1890 if ( keys(%Jobs) ) {
1891 foreach my $host ( keys(%Jobs) ) {
1892 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1895 foreach my $host ( keys(%Jobs) ) {
1896 kill($bpc->sigName2num("KILL"), $Jobs{$host}{pid});
1902 unlink("$LogDir/BackupPC.pid");