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-2007 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.1.0beta0, released 3 Sep 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;
62 use Encode qw/decode_utf8/;
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, verify executables are configured
252 # correctly and make sure $TopDir is on a file system that supports
255 if ( $Info{pid} ne "" && kill(0, $Info{pid}) ) {
256 print(STDERR $bpc->timeStamp,
257 "Another BackupPC is running (pid $Info{pid}); quitting...\n");
261 foreach my $progName ( qw(SmbClientPath NmbLookupPath PingPath DfPath
262 SendmailPath SshPath) ) {
263 next if ( $Conf{$progName} eq "" || -x $Conf{$progName} );
264 print(STDERR $bpc->timeStamp,
265 "\$Conf{$progName} = '$Conf{$progName}' is not a"
266 . " valid executable program\n");
270 if ( !$bpc->HardlinkTest("$TopDir/pc", "$TopDir/cpool") ) {
271 print(STDERR $bpc->timeStamp, "Can't create a test hardlink between a file"
272 . " in $TopDir/pc and $TopDir/cpool. Either these are different"
273 . " file systems, or this file system doesn't support hardlinks,"
274 . " or these directories don't exist, or there is a permissions"
275 . " problem, or the file system is out of inodes or full. Use"
276 . " df, df -i, and ls -ld to check each of these possibilities."
283 # daemonize by forking; more robust method per:
284 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=301057
287 defined($pid = fork) or die("Can't fork: $!");
288 exit if( $pid ); # parent exits
291 defined($pid = fork) or die("Can't fork: $!");
292 exit if $pid; # parent exits
294 chdir ("/") or die("Cannot chdir to /: $!\n");
296 open(STDIN , ">/dev/null") or die("Cannot open /dev/null as stdin\n");
297 # STDOUT and STDERR are handled in LogFileOpen() right below,
298 # otherwise we would have to reopen them too.
302 # Open the LOG file and redirect STDOUT, STDERR etc
307 # Read the hosts file (force a read).
309 exit(1) if ( !HostsUpdate(1) );
312 # Clean up %ENV for taint checking
314 delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
315 $ENV{PATH} = $Conf{MyPath};
318 # Initialize server sockets
323 # Catch various signals
325 foreach my $sig ( qw(INT BUS SEGV PIPE TERM ALRM HUP) ) {
326 $SIG{$sig} = \&catch_signal;
330 # Report that we started, and update %Info.
332 print(LOG $bpc->timeStamp, "BackupPC started, pid $$\n");
333 $Info{ConfigModTime} = $bpc->ConfigMTime();
335 $Info{startTime} = time;
336 $Info{ConfigLTime} = time;
337 $Info{Version} = $bpc->{Version};
340 # Update the status left over form the last time BackupPC ran.
341 # Requeue any pending links.
343 foreach my $host ( sort(keys(%$Hosts)) ) {
344 if ( $Status{$host}{state} eq "Status_backup_in_progress" ) {
346 # should we restart it? skip it for now.
348 $Status{$host}{state} = "Status_idle";
349 } elsif ( $Status{$host}{state} eq "Status_link_pending"
350 || $Status{$host}{state} eq "Status_link_running" ) {
353 $Status{$host}{state} = "Status_idle";
355 $Status{$host}{activeJob} = 0;
357 foreach my $host ( sort(keys(%Status)) ) {
358 next if ( defined($Hosts->{$host}) );
359 delete($Status{$host});
363 # Write out our initial status and save our PID
366 unlink("$LogDir/BackupPC.pid");
367 if ( open(PID, ">", "$LogDir/BackupPC.pid") ) {
370 chmod(0444, "$LogDir/BackupPC.pid");
374 # For unknown reasons there is a very infrequent error about not
375 # being able to coerce GLOBs inside the XS Data::Dumper. I've
376 # only seen this on a particular platform and perl version.
377 # For now the workaround appears to be use the perl version of
380 $Data::Dumper::Useqq = 1;
383 ############################################################################
384 # Main_TryToRun_nightly()
386 # Checks to see if we can/should run BackupPC_nightly or
387 # BackupPC_trashClean. If so we push the appropriate command onto
389 ############################################################################
390 sub Main_TryToRun_nightly
393 # Check if we should run BackupPC_nightly or BackupPC_trashClean.
394 # BackupPC_nightly is run when the current job queue is empty.
395 # BackupPC_trashClean is run in the background always.
397 my $trashCleanRunning = defined($Jobs{$bpc->trashJob}) ? 1 : 0;
398 if ( !$trashCleanRunning && !$CmdQueueOn{$bpc->trashJob} ) {
400 # This should only happen once at startup, but just in case this
401 # code will re-start BackupPC_trashClean if it quits
404 host => $bpc->trashJob,
407 cmd => ["$BinDir/BackupPC_trashClean"],
409 $CmdQueueOn{$bpc->trashJob} = 1;
411 if ( $RunNightlyWhenIdle == 1 ) {
414 # Queue multiple nightly jobs based on the configuration
416 $Conf{MaxBackupPCNightlyJobs} = 1
417 if ( $Conf{MaxBackupPCNightlyJobs} <= 0 );
418 $Conf{BackupPCNightlyPeriod} = 1
419 if ( $Conf{BackupPCNightlyPeriod} <= 0 );
421 # Decide what subset of the 16 top-level directories 0..9a..f
422 # we run BackupPC_nightly on, based on $Conf{BackupPCNightlyPeriod}.
423 # If $Conf{BackupPCNightlyPeriod} == 1 then we run 0..15 every
424 # time. If $Conf{BackupPCNightlyPeriod} == 2 then we run
425 # 0..7 one night and 89a-f the next night. And so on.
427 # $Info{NightlyPhase} counts which night, from 0 to
428 # $Conf{BackupPCNightlyPeriod} - 1.
430 my $start = int($Info{NightlyPhase} * 16
431 / $Conf{BackupPCNightlyPeriod});
432 my $end = int(($Info{NightlyPhase} + 1) * 16
433 / $Conf{BackupPCNightlyPeriod});
434 $end = $start + 1 if ( $end <= $start );
435 $Info{NightlyPhase}++;
436 $Info{NightlyPhase} = 0 if ( $end >= 16 );
439 # Zero out the data we expect to get from BackupPC_nightly.
441 for my $p ( qw(pool cpool) ) {
442 for ( my $i = $start ; $i < $end ; $i++ ) {
443 $Info{pool}{$p}[$i]{FileCnt} = 0;
444 $Info{pool}{$p}[$i]{DirCnt} = 0;
445 $Info{pool}{$p}[$i]{Kb} = 0;
446 $Info{pool}{$p}[$i]{Kb2} = 0;
447 $Info{pool}{$p}[$i]{KbRm} = 0;
448 $Info{pool}{$p}[$i]{FileCntRm} = 0;
449 $Info{pool}{$p}[$i]{FileCntRep} = 0;
450 $Info{pool}{$p}[$i]{FileRepMax} = 0;
451 $Info{pool}{$p}[$i]{FileCntRename} = 0;
452 $Info{pool}{$p}[$i]{FileLinkMax} = 0;
453 $Info{pool}{$p}[$i]{Time} = 0;
456 print(LOG $bpc->timeStamp,
457 sprintf("Running %d BackupPC_nightly jobs from %d..%d"
458 . " (out of 0..15)\n",
459 $Conf{MaxBackupPCNightlyJobs}, $start, $end - 1));
462 # Now queue the $Conf{MaxBackupPCNightlyJobs} jobs.
463 # The granularity on start and end is now 0..255.
468 for ( my $i = 0 ; $i < $Conf{MaxBackupPCNightlyJobs} ; $i++ ) {
470 # The first nightly job gets the -m option (does email, log aging).
471 # All jobs get the start and end options from 0..255 telling
472 # them which parts of the pool to traverse.
474 my $cmd = ["$BinDir/BackupPC_nightly"];
475 push(@$cmd, "-m") if ( $i == 0 );
477 $start = $start0 + int(($end - $start0)
478 * ($i + 1) / $Conf{MaxBackupPCNightlyJobs});
479 push(@$cmd, $start - 1);
481 my $job = $bpc->adminJob($i);
488 $CmdQueueOn{$job} = 1;
490 $RunNightlyWhenIdle = 2;
494 ############################################################################
495 # Main_TryToRun_CmdQueue()
497 # Decide if we can run a new command from the @CmdQueue.
498 # We only run one of these at a time. The @CmdQueue is
499 # used to run BackupPC_link (for the corresponding host),
500 # BackupPC_trashClean, and BackupPC_nightly using a fake
501 # host name of $bpc->adminJob.
502 ############################################################################
503 sub Main_TryToRun_CmdQueue
507 while ( $CmdJob eq "" && @CmdQueue > 0 && $RunNightlyWhenIdle != 1
508 || @CmdQueue > 0 && $RunNightlyWhenIdle == 2
509 && $bpc->isAdminJob($CmdQueue[0]->{host})
512 $req = pop(@CmdQueue);
514 $host = $req->{host};
515 if ( defined($Jobs{$host}) ) {
516 print(LOG $bpc->timeStamp,
517 "Botch on admin job for $host: already in use!!\n");
519 # This could happen during normal opertion: a user could
520 # request a backup while a BackupPC_link is queued from
521 # a previous backup. But it is unlikely. Just put this
522 # request back on the end of the queue.
524 unshift(@CmdQueue, $req);
527 $CmdQueueOn{$host} = 0;
528 my $cmd = $req->{cmd};
529 my $pid = open(FH, "-|");
530 if ( !defined($pid) ) {
531 print(LOG $bpc->timeStamp,
532 "can't fork for $host, request by $req->{user}\n");
538 $ENV{BPC_REQUSER} = $req->{user};
540 print(LOG $bpc->timeStamp, "can't exec @$cmd for $host\n");
543 $Jobs{$host}{pid} = $pid;
544 $Jobs{$host}{fh} = *FH;
545 $Jobs{$host}{fn} = fileno(FH);
546 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
547 $Jobs{$host}{startTime} = time;
548 $Jobs{$host}{reqTime} = $req->{reqTime};
549 $cmd = $bpc->execCmd2ShellCmd(@$cmd);
550 $Jobs{$host}{cmd} = $cmd;
551 $Jobs{$host}{user} = $req->{user};
552 $Jobs{$host}{type} = $Status{$host}{type};
553 $Status{$host}{state} = "Status_link_running";
554 $Status{$host}{activeJob} = 1;
555 $Status{$host}{endTime} = time;
556 $CmdJob = $host if ( $host ne $bpc->trashJob );
557 $cmd =~ s/$BinDir\///g;
558 print(LOG $bpc->timeStamp, "Running $cmd (pid=$pid)\n");
559 if ( $cmd =~ /^BackupPC_nightly\s/ ) {
560 $BackupPCNightlyJobs++;
561 $BackupPCNightlyLock++;
566 ############################################################################
567 # Main_TryToRun_Bg_or_User_Queue()
569 # Decide if we can run any new backup requests from @BgQueue
570 # or @UserQueue. Several of these can be run at the same time
571 # based on %Conf settings. Jobs from @UserQueue take priority,
572 # and at total of $Conf{MaxBackups} + $Conf{MaxUserBackups}
573 # simultaneous jobs can run from @UserQueue. After @UserQueue
574 # is exhausted, up to $Conf{MaxBackups} simultaneous jobs can
576 ############################################################################
577 sub Main_TryToRun_Bg_or_User_Queue
580 my(@deferUserQueue, @deferBgQueue);
583 if ( time - $Info{DUlastValueTime} >= 600 ) {
585 # Update our notion of disk usage no more than
586 # once every 10 minutes
588 $du = $bpc->CheckFileSystemUsage($TopDir);
589 $Info{DUlastValue} = $du;
590 $Info{DUlastValueTime} = time;
593 # if we recently checked it then just use the old value
595 $du = $Info{DUlastValue};
597 if ( $Info{DUDailyMaxReset} ) {
598 $Info{DUDailyMaxStartTime} = time;
599 $Info{DUDailyMaxReset} = 0;
600 $Info{DUDailyMax} = 0;
602 if ( $du > $Info{DUDailyMax} ) {
603 $Info{DUDailyMax} = $du;
604 $Info{DUDailyMaxTime} = time;
606 if ( $du > $Conf{DfMaxUsagePct} ) {
607 my @bgQueue = @BgQueue;
611 # When the disk is too full, only run backups that will
612 # do expires, not regular backups
615 foreach $req ( @bgQueue ) {
616 if ( $req->{dumpExpire} ) {
617 unshift(@BgQueue, $req);
619 $BgQueueOn{$req->{host}} = 0;
624 print(LOG $bpc->timeStamp,
625 "Disk too full ($du%); skipped $nSkip hosts\n");
626 $Info{DUDailySkipHostCnt} += $nSkip;
631 # Run background jobs anytime. Previously they were locked out
632 # when BackupPC_nightly was running or pending with this
633 # condition on the while loop:
635 # while ( $RunNightlyWhenIdle == 0 )
639 my(@args, $progName, $type);
640 my $nJobs = keys(%Jobs);
642 # CmdJob and trashClean don't count towards MaxBackups / MaxUserBackups
644 if ( $CmdJob ne "" ) {
645 if ( $BackupPCNightlyJobs ) {
646 $nJobs -= $BackupPCNightlyJobs;
651 $nJobs-- if ( defined($Jobs{$bpc->trashJob} ) );
652 if ( $nJobs < $Conf{MaxBackups} + $Conf{MaxUserBackups}
653 && @UserQueue > 0 ) {
654 $req = pop(@UserQueue);
655 if ( defined($Jobs{$req->{host}}) ) {
656 push(@deferUserQueue, $req);
659 push(@args, $req->{doFull} ? "-f" : "-i")
660 if (( !$req->{restore} ) && ( !$req->{archive} ));
661 $UserQueueOn{$req->{host}} = 0;
662 } elsif ( $nJobs < $Conf{MaxBackups}
663 && (@CmdQueue + $nJobs)
664 <= $Conf{MaxBackups} + $Conf{MaxPendingCmds}
666 $req = pop(@BgQueue);
667 if ( defined($Jobs{$req->{host}}) ) {
669 # Job is currently running for this host; save it for later
671 unshift(@deferBgQueue, $req);
674 $BgQueueOn{$req->{host}} = 0;
677 # Restore the deferred jobs
679 @BgQueue = (@BgQueue, @deferBgQueue);
680 @UserQueue = (@UserQueue, @deferUserQueue);
683 $host = $req->{host};
684 my $user = $req->{user};
685 if ( $req->{restore} ) {
686 $progName = "BackupPC_restore";
688 push(@args, $req->{hostIP}, $req->{host}, $req->{reqFileName});
689 } elsif ( $req->{archive} ) {
690 $progName = "BackupPC_archive";
692 push(@args, $req->{user}, $req->{host}, $req->{reqFileName});
694 $progName = "BackupPC_dump";
696 push(@args, "-d") if ( $req->{dhcp} );
697 push(@args, "-e") if ( $req->{dumpExpire} );
700 my $pid = open(FH, "-|");
701 if ( !defined($pid) ) {
702 print(LOG $bpc->timeStamp,
703 "can't fork to run $progName for $host, request by $user\n");
709 exec("$BinDir/$progName", @args);
710 print(LOG $bpc->timeStamp, "can't exec $progName for $host\n");
713 $Jobs{$host}{pid} = $pid;
714 $Jobs{$host}{fh} = *FH;
715 $Jobs{$host}{fn} = fileno(FH);
716 $Jobs{$host}{dhcp} = $req->{dhcp};
717 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
718 $Jobs{$host}{startTime} = time;
719 $Jobs{$host}{reqTime} = $req->{reqTime};
720 $Jobs{$host}{userReq} = $req->{userReq};
721 $Jobs{$host}{cmd} = $bpc->execCmd2ShellCmd($progName, @args);
722 $Jobs{$host}{user} = $user;
723 $Jobs{$host}{type} = $type;
724 $Status{$host}{userReq} = $req->{userReq}
725 if ( defined($Hosts->{$host}) );
726 if ( !$req->{dhcp} ) {
727 $Status{$host}{state} = "Status_".$type."_starting";
728 $Status{$host}{activeJob} = 1;
729 $Status{$host}{startTime} = time;
730 $Status{$host}{endTime} = "";
735 ############################################################################
738 # If necessary, figure out when to next wakeup based on $Conf{WakeupSchedule},
739 # and then do a select() to wait for the next thing to happen
740 # (timeout, signal, someone sends a message, child dies etc).
741 ############################################################################
744 if ( $NextWakeup <= 0 ) {
746 # Figure out when to next wakeup based on $Conf{WakeupSchedule}.
748 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
750 my($currHours) = $hour + $min / 60 + $sec / 3600;
751 if ( $bpc->ConfigMTime() != $Info{ConfigModTime} ) {
752 ServerReload("Re-read config file because mtime changed");
755 foreach my $t ( @{$Conf{WakeupSchedule} || [0..23]} ) {
756 next if ( $t < 0 || $t > 24 );
757 my $tomorrow = $t + 24;
759 || ($tomorrow - $currHours > 0
760 && $delta > $tomorrow - $currHours) ) {
761 $delta = $tomorrow - $currHours;
762 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
765 || ($t - $currHours > 0 && $delta > $t - $currHours) ) {
766 $delta = $t - $currHours;
767 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
770 $NextWakeup = time + $delta * 3600;
771 $Info{nextWakeup} = $NextWakeup;
772 print(LOG $bpc->timeStamp, "Next wakeup is ",
773 $bpc->timeStamp($NextWakeup, 1), "\n");
776 # Call select(), waiting until either a signal, a timeout,
777 # any output from our jobs, or any messages from clients
779 # select() is where we (hopefully) spend most of our time blocked...
781 my $timeout = $NextWakeup - time;
782 $timeout = 1 if ( $timeout <= 0 );
784 select(my $rout = $FDread, undef, $ein, $timeout);
789 ############################################################################
790 # Main_Process_Signal()
793 ############################################################################
794 sub Main_Process_Signal
799 if ( $SigName eq "HUP" ) {
800 ServerReload("Re-read config file because of a SIG_HUP");
801 } elsif ( $SigName ) {
802 ServerShutdown("Got signal $SigName... cleaning up");
807 ############################################################################
808 # Main_Check_Timeout()
810 # Check if a timeout has occured, and if so, queue all the PCs for backups.
811 # Also does log file aging on the first timeout after midnight.
812 ############################################################################
813 sub Main_Check_Timeout
818 return if ( time < $NextWakeup || $NextWakeup <= 0 );
820 if ( $FirstWakeup ) {
822 # This is the first wakeup after midnight. Do log file aging
823 # and various house keeping.
826 printf(LOG "%s24hr disk usage: %d%% max, %d%% recent,"
827 . " %d skipped hosts\n",
828 $bpc->timeStamp, $Info{DUDailyMax}, $Info{DUlastValue},
829 $Info{DUDailySkipHostCnt});
830 $Info{DUDailyMaxReset} = 1;
831 $Info{DUDailyMaxPrev} = $Info{DUDailyMax};
832 $Info{DUDailySkipHostCntPrev} = $Info{DUDailySkipHostCnt};
833 $Info{DUDailySkipHostCnt} = 0;
834 my $lastLog = $Conf{MaxOldLogFiles} - 1;
835 if ( -f "$LogDir/LOG.$lastLog" ) {
836 print(LOG $bpc->timeStamp,
837 "Removing $LogDir/LOG.$lastLog\n");
838 unlink("$LogDir/LOG.$lastLog");
840 if ( -f "$LogDir/LOG.$lastLog.z" ) {
841 print(LOG $bpc->timeStamp,
842 "Removing $LogDir/LOG.$lastLog.z\n");
843 unlink("$LogDir/LOG.$lastLog.z");
845 print(LOG $bpc->timeStamp, "Aging LOG files, LOG -> LOG.0 -> "
846 . "LOG.1 -> ... -> LOG.$lastLog\n");
847 close(STDERR); # dup of LOG
848 close(STDOUT); # dup of LOG
850 for ( my $i = $lastLog - 1 ; $i >= 0 ; $i-- ) {
852 rename("$LogDir/LOG.$i", "$LogDir/LOG.$j")
853 if ( -f "$LogDir/LOG.$i" );
854 rename("$LogDir/LOG.$i.z", "$LogDir/LOG.$j.z")
855 if ( -f "$LogDir/LOG.$i.z" );
858 # Compress the log file LOG -> LOG.0.z (if enabled).
859 # Otherwise, just rename LOG -> LOG.0.
861 BackupPC::FileZIO->compressCopy("$LogDir/LOG",
864 $Conf{CompressLevel}, 1);
867 # Remember to run the nightly script when the next CmdQueue
870 $RunNightlyWhenIdle = 1;
873 # Write out the current status and then queue all the PCs
877 %BgQueueOn = () if ( @BgQueue == 0 );
878 %UserQueueOn = () if ( @UserQueue == 0 );
879 %CmdQueueOn = () if ( @CmdQueue == 0 );
883 ############################################################################
884 # Main_Check_Job_Messages($fdRead)
886 # Check if select() says we have bytes waiting from any of our jobs.
887 # Handle each of the messages when complete (newline terminated).
888 ############################################################################
889 sub Main_Check_Job_Messages
892 foreach my $host ( keys(%Jobs) ) {
893 next if ( !vec($fdRead, $Jobs{$host}{fn}, 1) );
896 # do a last check to make sure there is something to read so
897 # we are absolutely sure we won't block.
899 vec(my $readMask, $Jobs{$host}{fn}, 1) = 1;
900 if ( !select($readMask, undef, undef, 0.0) ) {
901 print(LOG $bpc->timeStamp, "Botch in Main_Check_Job_Messages:"
902 . " nothing to read from $host. Debug dump:\n");
903 my($dump) = Data::Dumper->new(
904 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
905 [qw(*Clients, *Jobs *FDread, *fdRead)]);
907 print(LOG $dump->Dump);
910 my $nbytes = sysread($Jobs{$host}{fh}, $mesg, 1024);
911 $Jobs{$host}{mesg} .= $mesg if ( $nbytes > 0 );
913 # Process any complete lines of output from this jobs.
914 # Any output to STDOUT or STDERR from the children is processed here.
916 while ( $Jobs{$host}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
918 $Jobs{$host}{mesg} = $2;
919 if ( $Jobs{$host}{dhcp} ) {
920 if ( $mesg =~ /^DHCP (\S+) (\S+)/ ) {
921 my $newHost = $bpc->uriUnesc($2);
922 if ( defined($Jobs{$newHost}) ) {
923 print(LOG $bpc->timeStamp,
924 "Backup on $newHost is already running\n");
925 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
929 $Jobs{$host}{dhcpHostIP} = $host;
930 $Status{$newHost}{dhcpHostIP} = $host;
931 $Jobs{$newHost} = $Jobs{$host};
932 delete($Jobs{$host});
934 $Status{$host}{state} = "Status_backup_starting";
935 $Status{$host}{activeJob} = 1;
936 $Status{$host}{startTime} = $Jobs{$host}{startTime};
937 $Status{$host}{endTime} = "";
938 $Jobs{$host}{dhcp} = 0;
940 print(LOG $bpc->timeStamp, "dhcp $host: $mesg\n");
942 } elsif ( $mesg =~ /^started (.*) dump, share=(.*)/ ) {
943 $Jobs{$host}{type} = $1;
944 $Jobs{$host}{shareName} = $2;
945 print(LOG $bpc->timeStamp,
946 "Started $1 backup on $host (pid=$Jobs{$host}{pid}",
947 $Jobs{$host}{dhcpHostIP}
948 ? ", dhcp=$Jobs{$host}{dhcpHostIP}" : "",
949 ", share=$Jobs{$host}{shareName})\n");
950 $Status{$host}{state} = "Status_backup_in_progress";
951 $Status{$host}{reason} = "";
952 $Status{$host}{type} = $1;
953 $Status{$host}{startTime} = time;
954 $Status{$host}{deadCnt} = 0;
955 $Status{$host}{aliveCnt}++;
956 $Status{$host}{dhcpCheckCnt}--
957 if ( $Status{$host}{dhcpCheckCnt} > 0 );
958 } elsif ( $mesg =~ /^xferPids (.*)/ ) {
959 $Jobs{$host}{xferPid} = $1;
960 } elsif ( $mesg =~ /^started_restore/ ) {
961 $Jobs{$host}{type} = "restore";
962 print(LOG $bpc->timeStamp,
963 "Started restore on $host"
964 . " (pid=$Jobs{$host}{pid})\n");
965 $Status{$host}{state} = "Status_restore_in_progress";
966 $Status{$host}{reason} = "";
967 $Status{$host}{type} = "restore";
968 $Status{$host}{startTime} = time;
969 $Status{$host}{deadCnt} = 0;
970 $Status{$host}{aliveCnt}++;
971 } elsif ( $mesg =~ /^started_archive/ ) {
972 $Jobs{$host}{type} = "archive";
973 print(LOG $bpc->timeStamp,
974 "Started archive on $host"
975 . " (pid=$Jobs{$host}{pid})\n");
976 $Status{$host}{state} = "Status_archive_in_progress";
977 $Status{$host}{reason} = "";
978 $Status{$host}{type} = "archive";
979 $Status{$host}{startTime} = time;
980 $Status{$host}{deadCnt} = 0;
981 $Status{$host}{aliveCnt}++;
982 } elsif ( $mesg =~ /^(full|incr) backup complete/ ) {
983 print(LOG $bpc->timeStamp, "Finished $1 backup on $host\n");
984 $Status{$host}{reason} = "Reason_backup_done";
985 delete($Status{$host}{error});
986 delete($Status{$host}{errorTime});
987 $Status{$host}{endTime} = time;
988 $Status{$host}{lastGoodBackupTime} = time;
989 } elsif ( $mesg =~ /^backups disabled/ ) {
990 print(LOG $bpc->timeStamp,
991 "Ignoring old backup error on $host\n");
992 $Status{$host}{reason} = "Reason_backup_done";
993 delete($Status{$host}{error});
994 delete($Status{$host}{errorTime});
995 $Status{$host}{endTime} = time;
996 } elsif ( $mesg =~ /^restore complete/ ) {
997 print(LOG $bpc->timeStamp, "Finished restore on $host\n");
998 $Status{$host}{reason} = "Reason_restore_done";
999 delete($Status{$host}{error});
1000 delete($Status{$host}{errorTime});
1001 $Status{$host}{endTime} = time;
1002 } elsif ( $mesg =~ /^archive complete/ ) {
1003 print(LOG $bpc->timeStamp, "Finished archive on $host\n");
1004 $Status{$host}{reason} = "Reason_archive_done";
1005 delete($Status{$host}{error});
1006 delete($Status{$host}{errorTime});
1007 $Status{$host}{endTime} = time;
1008 } elsif ( $mesg =~ /^nothing to do/ ) {
1009 if ( $Status{$host}{reason} ne "Reason_backup_failed"
1010 && $Status{$host}{reason} ne "Reason_restore_failed" ) {
1011 $Status{$host}{state} = "Status_idle";
1012 $Status{$host}{reason} = "Reason_nothing_to_do";
1013 $Status{$host}{startTime} = time;
1015 $Status{$host}{dhcpCheckCnt}--
1016 if ( $Status{$host}{dhcpCheckCnt} > 0 );
1017 } elsif ( $mesg =~ /^no ping response/
1018 || $mesg =~ /^ping too slow/
1019 || $mesg =~ /^host not found/ ) {
1020 $Status{$host}{state} = "Status_idle";
1021 if ( $Status{$host}{userReq}
1022 || $Status{$host}{reason} ne "Reason_backup_failed"
1023 || $Status{$host}{error} =~ /^aborted by user/ ) {
1024 $Status{$host}{reason} = "Reason_no_ping";
1025 $Status{$host}{error} = $mesg;
1026 $Status{$host}{startTime} = time;
1028 $Status{$host}{deadCnt}++;
1029 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1030 $Status{$host}{aliveCnt} = 0;
1032 } elsif ( $mesg =~ /^dump 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_backup_canceled_by_user" ) {
1039 print(LOG $bpc->timeStamp,
1040 "Backup canceled on $host ($1)\n");
1042 $Status{$host}{reason} = "Reason_backup_failed";
1043 print(LOG $bpc->timeStamp,
1044 "Backup failed on $host ($1)\n");
1046 } elsif ( $mesg =~ /^restore 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_restore_canceled_by_user" ) {
1053 print(LOG $bpc->timeStamp,
1054 "Restore canceled on $host ($1)\n");
1056 $Status{$host}{reason} = "Reason_restore_failed";
1057 print(LOG $bpc->timeStamp,
1058 "Restore failed on $host ($1)\n");
1060 } elsif ( $mesg =~ /^archive failed: (.*)/ ) {
1061 $Status{$host}{state} = "Status_idle";
1062 $Status{$host}{error} = $1;
1063 $Status{$host}{errorTime} = time;
1064 $Status{$host}{endTime} = time;
1065 if ( $Status{$host}{reason}
1066 eq "Reason_archive_canceled_by_user" ) {
1067 print(LOG $bpc->timeStamp,
1068 "Archive canceled on $host ($1)\n");
1070 $Status{$host}{reason} = "Reason_archive_failed";
1071 print(LOG $bpc->timeStamp,
1072 "Archive failed on $host ($1)\n");
1074 } elsif ( $mesg =~ /^log\s+(.*)/ ) {
1075 print(LOG $bpc->timeStamp, "$1\n");
1076 } elsif ( $mesg =~ /^BackupPC_stats (\d+) = (.*)/ ) {
1077 my $chunk = int($1 / 16);
1078 my @f = split(/,/, $2);
1079 $Info{pool}{$f[0]}[$chunk]{FileCnt} += $f[1];
1080 $Info{pool}{$f[0]}[$chunk]{DirCnt} += $f[2];
1081 $Info{pool}{$f[0]}[$chunk]{Kb} += $f[3];
1082 $Info{pool}{$f[0]}[$chunk]{Kb2} += $f[4];
1083 $Info{pool}{$f[0]}[$chunk]{KbRm} += $f[5];
1084 $Info{pool}{$f[0]}[$chunk]{FileCntRm} += $f[6];
1085 $Info{pool}{$f[0]}[$chunk]{FileCntRep} += $f[7];
1086 $Info{pool}{$f[0]}[$chunk]{FileRepMax} = $f[8]
1087 if ( $Info{pool}{$f[0]}[$chunk]{FileRepMax} < $f[8] );
1088 $Info{pool}{$f[0]}[$chunk]{FileCntRename} += $f[9];
1089 $Info{pool}{$f[0]}[$chunk]{FileLinkMax} = $f[10]
1090 if ( $Info{pool}{$f[0]}[$chunk]{FileLinkMax} < $f[10] );
1091 $Info{pool}{$f[0]}[$chunk]{FileLinkTotal} += $f[11];
1092 $Info{pool}{$f[0]}[$chunk]{Time} = time;
1093 } elsif ( $mesg =~ /^BackupPC_nightly lock_off/ ) {
1094 $BackupPCNightlyLock--;
1095 if ( $BackupPCNightlyLock == 0 ) {
1097 # This means the last BackupPC_nightly is done with
1098 # the pool clean, so it's ok to start running regular
1099 # backups again. But starting in 3.0 regular jobs
1100 # are decoupled from BackupPC_nightly.
1102 $RunNightlyWhenIdle = 0;
1104 } elsif ( $mesg =~ /^processState\s+(.+)/ ) {
1105 $Jobs{$host}{processState} = $1;
1106 } elsif ( $mesg =~ /^link\s+(.+)/ ) {
1108 $Status{$h}{needLink} = 1;
1110 print(LOG $bpc->timeStamp, "$host: $mesg\n");
1114 # shut down the client connection if we read EOF
1116 if ( $nbytes <= 0 ) {
1117 close($Jobs{$host}{fh});
1118 vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1119 if ( $CmdJob eq $host || $bpc->isAdminJob($host) ) {
1120 my $cmd = $Jobs{$host}{cmd};
1121 $cmd =~ s/$BinDir\///g;
1122 print(LOG $bpc->timeStamp, "Finished $host ($cmd)\n");
1123 $Status{$host}{state} = "Status_idle";
1124 $Status{$host}{endTime} = time;
1125 if ( $cmd =~ /^BackupPC_nightly\s/ ) {
1126 $BackupPCNightlyJobs--;
1127 #print(LOG $bpc->timeStamp, "BackupPC_nightly done; now"
1128 # . " have $BackupPCNightlyJobs running\n");
1129 if ( $BackupPCNightlyJobs <= 0 ) {
1131 # Last BackupPC_nightly has finished
1133 $BackupPCNightlyJobs = 0;
1134 $RunNightlyWhenIdle = 0;
1137 # Combine the 16 per-directory results
1139 for my $p ( qw(pool cpool) ) {
1140 $Info{"${p}FileCnt"} = 0;
1141 $Info{"${p}DirCnt"} = 0;
1142 $Info{"${p}Kb"} = 0;
1143 $Info{"${p}Kb2"} = 0;
1144 $Info{"${p}KbRm"} = 0;
1145 $Info{"${p}FileCntRm"} = 0;
1146 $Info{"${p}FileCntRep"} = 0;
1147 $Info{"${p}FileRepMax"} = 0;
1148 $Info{"${p}FileCntRename"} = 0;
1149 $Info{"${p}FileLinkMax"} = 0;
1150 $Info{"${p}Time"} = 0;
1151 for ( my $i = 0 ; $i < 16 ; $i++ ) {
1152 $Info{"${p}FileCnt"}
1153 += $Info{pool}{$p}[$i]{FileCnt};
1155 += $Info{pool}{$p}[$i]{DirCnt};
1157 += $Info{pool}{$p}[$i]{Kb};
1159 += $Info{pool}{$p}[$i]{Kb2};
1161 += $Info{pool}{$p}[$i]{KbRm};
1162 $Info{"${p}FileCntRm"}
1163 += $Info{pool}{$p}[$i]{FileCntRm};
1164 $Info{"${p}FileCntRep"}
1165 += $Info{pool}{$p}[$i]{FileCntRep};
1166 $Info{"${p}FileRepMax"}
1167 = $Info{pool}{$p}[$i]{FileRepMax}
1168 if ( $Info{"${p}FileRepMax"} <
1169 $Info{pool}{$p}[$i]{FileRepMax} );
1170 $Info{"${p}FileCntRename"}
1171 += $Info{pool}{$p}[$i]{FileCntRename};
1172 $Info{"${p}FileLinkMax"}
1173 = $Info{pool}{$p}[$i]{FileLinkMax}
1174 if ( $Info{"${p}FileLinkMax"} <
1175 $Info{pool}{$p}[$i]{FileLinkMax} );
1176 $Info{"${p}Time"} = $Info{pool}{$p}[$i]{Time}
1177 if ( $Info{"${p}Time"} <
1178 $Info{pool}{$p}[$i]{Time} );
1180 printf(LOG "%s%s nightly clean removed %d files of"
1182 $bpc->timeStamp, ucfirst($p),
1183 $Info{"${p}FileCntRm"},
1184 $Info{"${p}KbRm"} / (1000 * 1024));
1185 printf(LOG "%s%s is %.2fGB, %d files (%d repeated, "
1186 . "%d max chain, %d max links), %d directories\n",
1187 $bpc->timeStamp, ucfirst($p),
1188 $Info{"${p}Kb"} / (1000 * 1024),
1189 $Info{"${p}FileCnt"}, $Info{"${p}FileCntRep"},
1190 $Info{"${p}FileRepMax"},
1191 $Info{"${p}FileLinkMax"}, $Info{"${p}DirCnt"});
1199 # Queue BackupPC_link to complete the backup
1200 # processing for this host.
1202 if ( defined($Status{$host})
1203 && ($Status{$host}{reason} eq "Reason_backup_done"
1204 || $Status{$host}{needLink}) ) {
1206 } elsif ( defined($Status{$host}) ) {
1207 $Status{$host}{state} = "Status_idle";
1210 delete($Jobs{$host});
1211 $Status{$host}{activeJob} = 0 if ( defined($Status{$host}) );
1215 # When we are idle (empty Jobs, CmdQueue, BgQueue, UserQueue) we
1216 # do a pass over %Status updating the deadCnt and aliveCnt for
1217 # DHCP hosts. The reason we need to do this later is we can't
1218 # be sure whether a DHCP host is alive or dead until we have passed
1219 # over all the DHCP pool.
1221 return if ( @CmdQueue || @BgQueue || @UserQueue || keys(%Jobs) > 1 );
1222 foreach my $host ( keys(%Status) ) {
1223 next if ( $Status{$host}{dhcpCheckCnt} <= 0 );
1224 $Status{$host}{deadCnt} += $Status{$host}{dhcpCheckCnt};
1225 $Status{$host}{dhcpCheckCnt} = 0;
1226 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1227 $Status{$host}{aliveCnt} = 0;
1232 ############################################################################
1233 # Main_Check_Client_Messages($fdRead)
1235 # Check for, and process, any output from our clients. Also checks
1236 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
1237 ############################################################################
1238 sub Main_Check_Client_Messages
1241 foreach my $client ( keys(%Clients) ) {
1242 next if ( !vec($fdRead, $Clients{$client}{fn}, 1) );
1245 # do a last check to make sure there is something to read so
1246 # we are absolutely sure we won't block.
1248 vec(my $readMask, $Clients{$client}{fn}, 1) = 1;
1249 if ( !select($readMask, undef, undef, 0.0) ) {
1250 print(LOG $bpc->timeStamp, "Botch in Main_Check_Client_Messages:"
1251 . " nothing to read from $client. Debug dump:\n");
1252 my($dump) = Data::Dumper->new(
1253 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
1254 [qw(*Clients, *Jobs *FDread, *fdRead)]);
1256 print(LOG $dump->Dump);
1259 my $nbytes = sysread($Clients{$client}{fh}, $mesg, 1024);
1260 $Clients{$client}{mesg} .= $mesg if ( $nbytes > 0 );
1262 # Process any complete lines received from this client.
1264 while ( $Clients{$client}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
1267 $Clients{$client}{mesg} = $2;
1269 # Authenticate the message by checking the MD5 digest
1271 my $md5 = Digest::MD5->new;
1272 if ( $cmd !~ /^(.{22}) (.*)/
1273 || ($md5->add($Clients{$client}{seed}
1274 . $Clients{$client}{mesgCnt}
1275 . $Conf{ServerMesgSecret} . $2),
1276 $md5->b64digest ne $1) ) {
1277 print(LOG $bpc->timeStamp, "Corrupted message '$cmd' from"
1278 . " client '$Clients{$client}{clientName}':"
1279 . " shutting down client connection\n");
1283 $Clients{$client}{mesgCnt}++;
1284 $cmd = decode_utf8($2);
1285 if ( $cmd =~ /^stop (\S+)\s+(\S+)\s+(\S*)/ ) {
1289 $host = $bpc->uriUnesc($host);
1290 if ( $CmdJob ne $host && defined($Status{$host})
1291 && defined($Jobs{$host}) ) {
1292 print(LOG $bpc->timeStamp,
1293 "Stopping current $Jobs{$host}{type} of $host,"
1294 . " request by $user (backoff=$backoff)\n");
1295 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1297 # Don't close the pipe now; wait until the child
1298 # really exits later. Otherwise close() will
1299 # block until the child has exited.
1301 ##vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1302 ##close($Jobs{$host}{fh});
1303 ##delete($Jobs{$host});
1305 $Status{$host}{state} = "Status_idle";
1306 if ( $Jobs{$host}{type} eq "restore" ) {
1307 $Status{$host}{reason}
1308 = "Reason_restore_canceled_by_user";
1309 } elsif ( $Jobs{$host}{type} eq "archive" ) {
1310 $Status{$host}{reason}
1311 = "Reason_archive_canceled_by_user";
1313 $Status{$host}{reason}
1314 = "Reason_backup_canceled_by_user";
1316 $Status{$host}{activeJob} = 0;
1317 $Status{$host}{startTime} = time;
1318 $reply = "ok: $Jobs{$host}{type} of $host canceled";
1319 } elsif ( $BgQueueOn{$host} || $UserQueueOn{$host} ) {
1320 print(LOG $bpc->timeStamp,
1321 "Stopping pending backup of $host,"
1322 . " request by $user (backoff=$backoff)\n");
1323 @BgQueue = grep($_->{host} ne $host, @BgQueue);
1324 @UserQueue = grep($_->{host} ne $host, @UserQueue);
1325 $BgQueueOn{$host} = $UserQueueOn{$host} = 0;
1326 $reply = "ok: pending backup of $host canceled";
1328 print(LOG $bpc->timeStamp,
1329 "Nothing to do for stop backup of $host,"
1330 . " request by $user (backoff=$backoff)\n");
1331 $reply = "ok: no backup was pending or running";
1333 if ( defined($Status{$host}) && $backoff ne "" ) {
1334 if ( $backoff > 0 ) {
1335 $Status{$host}{backoffTime} = time + $backoff * 3600;
1337 delete($Status{$host}{backoffTime});
1340 } elsif ( $cmd =~ /^backup all$/ ) {
1342 } elsif ( $cmd =~ /^BackupPC_nightly run$/ ) {
1343 $RunNightlyWhenIdle = 1;
1344 } elsif ( $cmd =~ /^backup (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1349 $host = $bpc->uriUnesc($host);
1350 $hostIP = $bpc->uriUnesc($hostIP);
1351 if ( !defined($Status{$host}) ) {
1352 print(LOG $bpc->timeStamp,
1353 "User $user requested backup of unknown host"
1355 $reply = "error: unknown host $host";
1357 print(LOG $bpc->timeStamp,
1358 "User $user requested backup of $host"
1360 if ( $BgQueueOn{$hostIP} ) {
1361 @BgQueue = grep($_->{host} ne $hostIP, @BgQueue);
1362 $BgQueueOn{$hostIP} = 0;
1364 if ( $UserQueueOn{$hostIP} ) {
1365 @UserQueue = grep($_->{host} ne $hostIP, @UserQueue);
1366 $UserQueueOn{$hostIP} = 0;
1368 unshift(@UserQueue, {
1374 dhcp => $hostIP eq $host ? 0 : 1,
1376 $UserQueueOn{$hostIP} = 1;
1377 $reply = "ok: requested backup of $host";
1379 } elsif ( $cmd =~ /^archive (\S+)\s+(\S+)\s+(\S+)/ ) {
1381 my $archivehost = $2;
1382 my $reqFileName = $3;
1383 $host = $bpc->uriUnesc($archivehost);
1384 if ( !defined($Status{$host}) ) {
1385 print(LOG $bpc->timeStamp,
1386 "User $user requested archive of unknown archive host"
1388 $reply = "archive error: unknown archive host $host";
1390 print(LOG $bpc->timeStamp,
1391 "User $user requested archive on $host"
1393 if ( defined($Jobs{$host}) ) {
1394 $reply = "Archive currently running on $host, please try later";
1396 unshift(@UserQueue, {
1399 reqFileName => $reqFileName,
1405 $UserQueueOn{$host} = 1;
1406 $reply = "ok: requested archive on $host";
1409 } elsif ( $cmd =~ /^restore (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1413 my $reqFileName = $4;
1414 $host = $bpc->uriUnesc($host);
1415 $hostIP = $bpc->uriUnesc($hostIP);
1416 if ( !defined($Status{$host}) ) {
1417 print(LOG $bpc->timeStamp,
1418 "User $user requested restore to unknown host"
1420 $reply = "restore error: unknown host $host";
1422 print(LOG $bpc->timeStamp,
1423 "User $user requested restore to $host"
1425 unshift(@UserQueue, {
1428 reqFileName => $reqFileName,
1434 $UserQueueOn{$host} = 1;
1435 if ( defined($Jobs{$host}) ) {
1436 $reply = "ok: requested restore of $host, but a"
1437 . " job is currently running,"
1438 . " so this request will start later";
1440 $reply = "ok: requested restore of $host";
1443 } elsif ( $cmd =~ /^status\s*(.*)/ ) {
1445 my($dump, @values, @names);
1446 foreach my $type ( split(/\s+/, $args) ) {
1447 if ( $type =~ /^queues/ ) {
1448 push(@values, \@BgQueue, \@UserQueue, \@CmdQueue);
1449 push(@names, qw(*BgQueue *UserQueue *CmdQueue));
1450 } elsif ( $type =~ /^jobs/ ) {
1451 push(@values, \%Jobs);
1452 push(@names, qw(*Jobs));
1453 } elsif ( $type =~ /^queueLen/ ) {
1455 BgQueue => scalar(@BgQueue),
1456 UserQueue => scalar(@UserQueue),
1457 CmdQueue => scalar(@CmdQueue),
1459 push(@names, qw(*QueueLen));
1460 } elsif ( $type =~ /^info/ ) {
1461 push(@values, \%Info);
1462 push(@names, qw(*Info));
1463 } elsif ( $type =~ /^hosts/ ) {
1464 push(@values, \%Status);
1465 push(@names, qw(*Status));
1466 } elsif ( $type =~ /^host\((.*)\)/ ) {
1467 my $h = $bpc->uriUnesc($1);
1468 if ( defined($Status{$h}) ) {
1471 BgQueueOn => $BgQueueOn{$h},
1472 UserQueueOn => $UserQueueOn{$h},
1473 CmdQueueOn => $CmdQueueOn{$h},
1475 push(@names, qw(*StatusHost));
1477 print(LOG $bpc->timeStamp,
1478 "Unknown host $h for status request\n");
1481 print(LOG $bpc->timeStamp,
1482 "Unknown status request $type\n");
1485 $dump = Data::Dumper->new(\@values, \@names);
1487 $reply = $dump->Dump;
1488 } elsif ( $cmd =~ /^link\s+(.+)/ ) {
1490 $host = $bpc->uriUnesc($host);
1492 } elsif ( $cmd =~ /^log\s+(.*)/ ) {
1493 print(LOG $bpc->timeStamp, "$1\n");
1494 } elsif ( $cmd =~ /^server\s+(\w+)/ ) {
1496 if ( $type eq 'reload' ) {
1497 ServerReload("Reloading config/host files via CGI request");
1498 } elsif ( $type eq 'shutdown' ) {
1499 $reply = "Shutting down...\n";
1500 syswrite($Clients{$client}{fh}, $reply, length($reply));
1501 ServerShutdown("Server shutting down...");
1503 } elsif ( $cmd =~ /^quit/ || $cmd =~ /^exit/ ) {
1507 print(LOG $bpc->timeStamp, "Unknown command $cmd\n");
1508 $reply = "error: bad command $cmd";
1511 # send a reply to the client, at a minimum "ok\n".
1513 $reply = "ok" if ( $reply eq "" );
1515 syswrite($Clients{$client}{fh}, $reply, length($reply));
1518 # Detect possible denial-of-service attack from sending a huge line
1519 # (ie: never terminated). 32K seems to be plenty big enough as
1522 if ( length($Clients{$client}{mesg}) > 32 * 1024 ) {
1523 print(LOG $bpc->timeStamp, "Line too long from client"
1524 . " '$Clients{$client}{clientName}':"
1525 . " shutting down client connection\n");
1529 # Shut down the client connection if we read EOF
1531 if ( $nbytes <= 0 ) {
1532 close($Clients{$client}{fh});
1533 vec($FDread, $Clients{$client}{fn}, 1) = 0;
1534 delete($Clients{$client});
1538 # Accept any new connections on each of our listen sockets
1540 if ( vec($fdRead, fileno(SERVER_UNIX), 1) ) {
1542 my $paddr = accept(CLIENT, SERVER_UNIX);
1544 $Clients{$ClientConnCnt}{clientName} = "unix socket";
1545 $Clients{$ClientConnCnt}{mesg} = "";
1546 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1547 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1548 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1550 # Generate and send unique seed for MD5 digests to avoid
1551 # replay attacks. See BackupPC::Lib::ServerMesg().
1553 my $seed = time . ",$ClientConnCnt,$$,0\n";
1554 $Clients{$ClientConnCnt}{seed} = $seed;
1555 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1556 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1558 if ( $ServerInetPort > 0 && vec($fdRead, fileno(SERVER_INET), 1) ) {
1560 my $paddr = accept(CLIENT, SERVER_INET);
1561 my($port,$iaddr) = sockaddr_in($paddr);
1562 my $name = gethostbyaddr($iaddr, AF_INET);
1564 $Clients{$ClientConnCnt}{mesg} = "";
1565 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1566 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1567 $Clients{$ClientConnCnt}{clientName} = "$name:$port";
1568 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1570 # Generate and send unique seed for MD5 digests to avoid
1571 # replay attacks. See BackupPC::Lib::ServerMesg().
1573 my $seed = time . ",$ClientConnCnt,$$,$port\n";
1574 $Clients{$ClientConnCnt}{seed} = $seed;
1575 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1576 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1580 ###########################################################################
1581 # Miscellaneous subroutines
1582 ###########################################################################
1585 # Write the current status to $LogDir/status.pl
1589 my($dump) = Data::Dumper->new(
1590 [ \%Info, \%Status],
1591 [qw(*Info *Status)]);
1593 $bpc->{storage}->TextFileWrite("$LogDir/status.pl", $dump->Dump);
1597 # Compare function for host sort. Hosts with errors go first,
1598 # sorted with the oldest errors first. The remaining hosts
1599 # are sorted so that those with the oldest backups go first.
1604 # Hosts with errors go before hosts without errors
1606 return -1 if ( $Status{$a}{error} ne "" && $Status{$b}{error} eq "" );
1609 # Hosts with no errors go after hosts with errors
1612 return 1 if ( $Status{$a}{error} eq "" && $Status{$b}{error} ne "" );
1615 # hosts with the older last good backups sort earlier
1617 my $r = $Status{$a}{lastGoodBackupTime} <=> $Status{$b}{lastGoodBackupTime};
1618 return $r if ( $r );
1621 # Finally, just sort based on host name
1627 # Queue all the hosts for backup. This means queuing all the fixed
1628 # ip hosts and all the dhcp address ranges. We also additionally
1629 # queue the dhcp hosts with a -e flag to check for expired dumps.
1634 foreach my $host ( sort(HostSortCompare keys(%$Hosts)) ) {
1635 delete($Status{$host}{backoffTime})
1636 if ( defined($Status{$host}{backoffTime})
1637 && $Status{$host}{backoffTime} < time );
1638 next if ( defined($Jobs{$host})
1639 || $BgQueueOn{$host}
1640 || $UserQueueOn{$host}
1641 || $CmdQueueOn{$host} );
1642 if ( $Hosts->{$host}{dhcp} ) {
1643 $Status{$host}{dhcpCheckCnt}++;
1644 if ( $RunNightlyWhenIdle ) {
1646 # Once per night queue a check for DHCP hosts that just
1647 # checks for expired dumps. We need to do this to handle
1648 # the case when a DHCP host has not been on the network for
1649 # a long time, and some of the old dumps need to be expired.
1650 # Normally expiry checks are done by BackupPC_dump only
1651 # after the DHCP hosts has been detected on the network.
1654 {host => $host, user => "BackupPC", reqTime => time,
1655 dhcp => 0, dumpExpire => 1});
1656 $BgQueueOn{$host} = 1;
1660 # this is a fixed ip host: queue it
1662 if ( $Info{DUlastValue} > $Conf{DfMaxUsagePct} ) {
1664 # Since we are out of disk space, instead of queuing
1665 # a regular job, queue an expire check instead. That
1666 # way if the admin reduces the number of backups to
1667 # keep then we will actually delete them. Otherwise
1668 # BackupPC_dump will never run since we have exceeded
1673 {host => $host, user => "BackupPC", reqTime => time,
1674 dhcp => $Hosts->{$host}{dhcp}, dumpExpire => 1});
1677 # Queue regular background backup
1680 {host => $host, user => "BackupPC", reqTime => time,
1681 dhcp => $Hosts->{$host}{dhcp}});
1683 $BgQueueOn{$host} = 1;
1687 print(LOG $bpc->timeStamp,
1688 "Disk too full ($Info{DUlastValue}%); skipped $nSkip hosts\n");
1689 $Info{DUDailySkipHostCnt} += $nSkip;
1691 foreach my $dhcp ( @{$Conf{DHCPAddressRanges}} ) {
1692 for ( my $i = $dhcp->{first} ; $i <= $dhcp->{last} ; $i++ ) {
1693 my $ipAddr = "$dhcp->{ipAddrBase}.$i";
1694 next if ( defined($Jobs{$ipAddr})
1695 || $BgQueueOn{$ipAddr}
1696 || $UserQueueOn{$ipAddr}
1697 || $CmdQueueOn{$ipAddr} );
1699 # this is a potential dhcp ip address (we don't know the
1700 # host name yet): queue it
1703 {host => $ipAddr, user => "BackupPC", reqTime => time,
1705 $BgQueueOn{$ipAddr} = 1;
1711 # Queue a BackupPC_link for the given host
1717 return if ( $CmdQueueOn{$host} );
1718 $Status{$host}{state} = "Status_link_pending";
1719 $Status{$host}{needLink} = 0;
1720 unshift(@CmdQueue, {
1724 cmd => ["$BinDir/BackupPC_link", $host],
1726 $CmdQueueOn{$host} = 1;
1730 # Read the hosts file, and update Status if any hosts have been
1731 # added or deleted. We also track the mtime so the only need to
1732 # update the hosts file on changes.
1734 # This function is called at startup, SIGHUP, and on each wakeup.
1735 # It returns 1 on success and undef on failure.
1742 # Nothing to do if we already have the current hosts file
1744 return 1 if ( !$force && defined($Hosts)
1745 && $Info{HostsModTime} == $bpc->HostsMTime() );
1746 if ( !defined($newHosts = $bpc->HostInfoRead()) ) {
1747 print(LOG $bpc->timeStamp, "Can't read hosts file!\n");
1750 print(LOG $bpc->timeStamp, "Reading hosts file\n");
1752 $Info{HostsModTime} = $bpc->HostsMTime();
1754 # Now update %Status in case any hosts have been added or deleted
1756 foreach my $host ( sort(keys(%$Hosts)) ) {
1757 next if ( defined($Status{$host}) );
1758 $Status{$host}{state} = "Status_idle";
1759 print(LOG $bpc->timeStamp, "Added host $host to backup list\n");
1761 foreach my $host ( sort(keys(%Status)) ) {
1762 next if ( $host eq $bpc->trashJob
1763 || $bpc->isAdminJob($host)
1764 || defined($Hosts->{$host})
1765 || defined($Jobs{$host})
1766 || $BgQueueOn{$host}
1767 || $UserQueueOn{$host}
1768 || $CmdQueueOn{$host} );
1769 print(LOG $bpc->timeStamp, "Deleted host $host from backup list\n");
1770 delete($Status{$host});
1776 # Remember the signal name for later processing
1782 foreach my $host ( keys(%Jobs) ) {
1783 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1786 # In case we are inside the exit handler, reopen the log file
1790 print(LOG "Fatal error: unhandled signal $SigName\n");
1791 unlink("$LogDir/BackupPC.pid");
1792 confess("Got new signal $SigName... quitting\n");
1799 # Open the log file and point STDOUT and STDERR there too
1803 mkpath($LogDir, 0, 0777) if ( !-d $LogDir );
1804 open(LOG, ">>$LogDir/LOG")
1805 || die("Can't create LOG file $LogDir/LOG");
1808 open(STDOUT, ">&LOG");
1809 open(STDERR, ">&LOG");
1810 select(LOG); $| = 1;
1811 select(STDERR); $| = 1;
1812 select(STDOUT); $| = 1;
1816 # Initialize the unix-domain and internet-domain sockets that
1817 # we listen to for client connections (from the CGI script and
1818 # some of the BackupPC sub-programs).
1820 sub ServerSocketInit
1822 if ( !defined(fileno(SERVER_UNIX)) ) {
1824 # one-time only: initialize unix-domain socket
1826 if ( !socket(SERVER_UNIX, PF_UNIX, SOCK_STREAM, 0) ) {
1827 print(LOG $bpc->timeStamp, "unix socket() failed: $!\n");
1830 my $sockFile = "$LogDir/BackupPC.sock";
1832 if ( !bind(SERVER_UNIX, sockaddr_un($sockFile)) ) {
1833 print(LOG $bpc->timeStamp, "unix bind() failed: $!\n");
1836 if ( !listen(SERVER_UNIX, SOMAXCONN) ) {
1837 print(LOG $bpc->timeStamp, "unix listen() failed: $!\n");
1840 vec($FDread, fileno(SERVER_UNIX), 1) = 1;
1842 return if ( $ServerInetPort == $Conf{ServerPort} );
1843 if ( $ServerInetPort > 0 ) {
1844 vec($FDread, fileno(SERVER_INET), 1) = 0;
1846 $ServerInetPort = -1;
1848 if ( $Conf{ServerPort} > 0 ) {
1850 # Setup a socket to listen on $Conf{ServerPort}
1852 my $proto = getprotobyname('tcp');
1853 if ( !socket(SERVER_INET, PF_INET, SOCK_STREAM, $proto) ) {
1854 print(LOG $bpc->timeStamp, "inet socket() failed: $!\n");
1857 if ( !setsockopt(SERVER_INET, SOL_SOCKET, SO_REUSEADDR, pack("l",1)) ) {
1858 print(LOG $bpc->timeStamp, "setsockopt() failed: $!\n");
1861 if ( !bind(SERVER_INET, sockaddr_in($Conf{ServerPort}, INADDR_ANY)) ) {
1862 print(LOG $bpc->timeStamp, "inet bind() failed: $!\n");
1865 if ( !listen(SERVER_INET, SOMAXCONN) ) {
1866 print(LOG $bpc->timeStamp, "inet listen() failed: $!\n");
1869 vec($FDread, fileno(SERVER_INET), 1) = 1;
1870 $ServerInetPort = $Conf{ServerPort};
1875 # Reload the server. Used by Main_Process_Signal when $SigName eq "HUP"
1876 # or when the command "server reload" is received.
1881 $mesg = $bpc->ConfigRead() || $mesg;
1882 print(LOG $bpc->timeStamp, "$mesg\n");
1883 $Info{ConfigModTime} = $bpc->ConfigMTime();
1884 %Conf = $bpc->Conf();
1885 umask($Conf{UmaskMode});
1889 $Info{ConfigLTime} = time;
1893 # Gracefully shutdown the server. Used by Main_Process_Signal when
1894 # $SigName ne "" && $SigName ne "HUP" or when the command
1895 # "server shutdown" is received.
1900 print(LOG $bpc->timeStamp, "$mesg\n");
1901 if ( keys(%Jobs) ) {
1902 foreach my $host ( keys(%Jobs) ) {
1903 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1906 foreach my $host ( keys(%Jobs) ) {
1907 kill($bpc->sigName2num("KILL"), $Jobs{$host}{pid});
1913 unlink("$LogDir/BackupPC.pid");