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.2.0, released 31 Dec 2008.
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 ) {
413 # Queue multiple nightly jobs based on the configuration
415 $Conf{MaxBackupPCNightlyJobs} = 1
416 if ( $Conf{MaxBackupPCNightlyJobs} <= 0 );
417 $Conf{BackupPCNightlyPeriod} = 1
418 if ( $Conf{BackupPCNightlyPeriod} <= 0 );
420 # Decide what subset of the 16 top-level directories 0..9a..f
421 # we run BackupPC_nightly on, based on $Conf{BackupPCNightlyPeriod}.
422 # If $Conf{BackupPCNightlyPeriod} == 1 then we run 0..15 every
423 # time. If $Conf{BackupPCNightlyPeriod} == 2 then we run
424 # 0..7 one night and 89a-f the next night. And so on.
426 # $Info{NightlyPhase} counts which night, from 0 to
427 # $Conf{BackupPCNightlyPeriod} - 1.
429 my $start = int($Info{NightlyPhase} * 16
430 / $Conf{BackupPCNightlyPeriod});
431 my $end = int(($Info{NightlyPhase} + 1) * 16
432 / $Conf{BackupPCNightlyPeriod});
433 $end = $start + 1 if ( $end <= $start );
434 $Info{NightlyPhase}++;
435 $Info{NightlyPhase} = 0 if ( $end >= 16 );
438 # Zero out the data we expect to get from BackupPC_nightly.
440 for my $p ( qw(pool cpool) ) {
441 for ( my $i = $start ; $i < $end ; $i++ ) {
442 $Info{pool}{$p}[$i]{FileCnt} = 0;
443 $Info{pool}{$p}[$i]{DirCnt} = 0;
444 $Info{pool}{$p}[$i]{Kb} = 0;
445 $Info{pool}{$p}[$i]{Kb2} = 0;
446 $Info{pool}{$p}[$i]{KbRm} = 0;
447 $Info{pool}{$p}[$i]{FileCntRm} = 0;
448 $Info{pool}{$p}[$i]{FileCntRep} = 0;
449 $Info{pool}{$p}[$i]{FileRepMax} = 0;
450 $Info{pool}{$p}[$i]{FileCntRename} = 0;
451 $Info{pool}{$p}[$i]{FileLinkMax} = 0;
452 $Info{pool}{$p}[$i]{Time} = 0;
455 print(LOG $bpc->timeStamp,
456 sprintf("Running %d BackupPC_nightly jobs from %d..%d"
457 . " (out of 0..15)\n",
458 $Conf{MaxBackupPCNightlyJobs}, $start, $end - 1));
461 # Now queue the $Conf{MaxBackupPCNightlyJobs} jobs.
462 # The granularity on start and end is now 0..255.
467 for ( my $i = 0 ; $i < $Conf{MaxBackupPCNightlyJobs} ; $i++ ) {
469 # The first nightly job gets the -m option (does email, log aging).
470 # All jobs get the start and end options from 0..255 telling
471 # them which parts of the pool to traverse.
473 my $cmd = ["$BinDir/BackupPC_nightly"];
474 push(@$cmd, "-m") if ( $i == 0 );
476 $start = $start0 + int(($end - $start0)
477 * ($i + 1) / $Conf{MaxBackupPCNightlyJobs});
478 push(@$cmd, $start - 1);
479 my $job = $bpc->adminJob($i);
486 $CmdQueueOn{$job} = 1;
488 $RunNightlyWhenIdle = 2;
492 ############################################################################
493 # Main_TryToRun_CmdQueue()
495 # Decide if we can run a new command from the @CmdQueue.
496 # We only run one of these at a time. The @CmdQueue is
497 # used to run BackupPC_link (for the corresponding host),
498 # BackupPC_trashClean, and BackupPC_nightly using a fake
499 # host name of $bpc->adminJob.
500 ############################################################################
501 sub Main_TryToRun_CmdQueue
505 while ( $CmdJob eq "" && @CmdQueue > 0 && $RunNightlyWhenIdle != 1
506 || @CmdQueue > 0 && $RunNightlyWhenIdle == 2
507 && $bpc->isAdminJob($CmdQueue[0]->{host})
510 $req = pop(@CmdQueue);
512 $host = $req->{host};
513 if ( defined($Jobs{$host}) ) {
514 print(LOG $bpc->timeStamp,
515 "Botch on admin job for $host: already in use!!\n");
517 # This could happen during normal opertion: a user could
518 # request a backup while a BackupPC_link is queued from
519 # a previous backup. But it is unlikely. Just put this
520 # request back on the end of the queue.
522 unshift(@CmdQueue, $req);
525 $CmdQueueOn{$host} = 0;
526 my $cmd = $req->{cmd};
527 my $pid = open(FH, "-|");
528 if ( !defined($pid) ) {
529 print(LOG $bpc->timeStamp,
530 "can't fork for $host, request by $req->{user}\n");
536 $ENV{BPC_REQUSER} = $req->{user};
537 POSIX::nice($Conf{CmdQueueNice}) if ( $Conf{CmdQueueNice} );
539 print(LOG $bpc->timeStamp, "can't exec @$cmd for $host\n");
542 $Jobs{$host}{pid} = $pid;
543 $Jobs{$host}{fh} = *FH;
544 $Jobs{$host}{fn} = fileno(FH);
545 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
546 $Jobs{$host}{startTime} = time;
547 $Jobs{$host}{reqTime} = $req->{reqTime};
548 $cmd = $bpc->execCmd2ShellCmd(@$cmd);
549 $Jobs{$host}{cmd} = $cmd;
550 $Jobs{$host}{user} = $req->{user};
551 $Jobs{$host}{type} = $Status{$host}{type};
552 $Status{$host}{state} = "Status_link_running";
553 $Status{$host}{activeJob} = 1;
554 $Status{$host}{endTime} = time;
555 $CmdJob = $host if ( $host ne $bpc->trashJob );
556 $cmd =~ s/$BinDir\///g;
557 print(LOG $bpc->timeStamp, "Running $cmd (pid=$pid)\n");
558 if ( $cmd =~ /^BackupPC_nightly\s/ ) {
559 $BackupPCNightlyJobs++;
560 $BackupPCNightlyLock++;
565 ############################################################################
566 # Main_TryToRun_Bg_or_User_Queue()
568 # Decide if we can run any new backup requests from @BgQueue
569 # or @UserQueue. Several of these can be run at the same time
570 # based on %Conf settings. Jobs from @UserQueue take priority,
571 # and at total of $Conf{MaxBackups} + $Conf{MaxUserBackups}
572 # simultaneous jobs can run from @UserQueue. After @UserQueue
573 # is exhausted, up to $Conf{MaxBackups} simultaneous jobs can
575 ############################################################################
576 sub Main_TryToRun_Bg_or_User_Queue
579 my(@deferUserQueue, @deferBgQueue);
582 if ( time - $Info{DUlastValueTime} >= 600 ) {
584 # Update our notion of disk usage no more than
585 # once every 10 minutes
587 $du = $bpc->CheckFileSystemUsage($TopDir);
588 $Info{DUlastValue} = $du;
589 $Info{DUlastValueTime} = time;
592 # if we recently checked it then just use the old value
594 $du = $Info{DUlastValue};
596 if ( $Info{DUDailyMaxReset} ) {
597 $Info{DUDailyMaxStartTime} = time;
598 $Info{DUDailyMaxReset} = 0;
599 $Info{DUDailyMax} = 0;
601 if ( $du > $Info{DUDailyMax} ) {
602 $Info{DUDailyMax} = $du;
603 $Info{DUDailyMaxTime} = time;
605 if ( $du > $Conf{DfMaxUsagePct} ) {
606 my @bgQueue = @BgQueue;
610 # When the disk is too full, only run backups that will
611 # do expires, not regular backups
614 foreach $req ( @bgQueue ) {
615 if ( $req->{dumpExpire} ) {
616 unshift(@BgQueue, $req);
618 $BgQueueOn{$req->{host}} = 0;
623 print(LOG $bpc->timeStamp,
624 "Disk too full ($du%); skipped $nSkip hosts\n");
625 $Info{DUDailySkipHostCnt} += $nSkip;
630 # Run background jobs anytime. Previously they were locked out
631 # when BackupPC_nightly was running or pending with this
632 # condition on the while loop:
634 # while ( $RunNightlyWhenIdle == 0 )
638 my(@args, $progName, $type);
639 my $nJobs = keys(%Jobs);
641 # CmdJob and trashClean don't count towards MaxBackups / MaxUserBackups
643 if ( $CmdJob ne "" ) {
644 if ( $BackupPCNightlyJobs ) {
645 $nJobs -= $BackupPCNightlyJobs;
650 $nJobs-- if ( defined($Jobs{$bpc->trashJob} ) );
651 if ( $nJobs < $Conf{MaxBackups} + $Conf{MaxUserBackups}
652 && @UserQueue > 0 ) {
653 $req = pop(@UserQueue);
654 if ( defined($Jobs{$req->{host}}) ) {
655 push(@deferUserQueue, $req);
658 push(@args, $req->{doFull} ? "-f" : "-i")
659 if (( !$req->{restore} ) && ( !$req->{archive} ));
660 $UserQueueOn{$req->{host}} = 0;
661 } elsif ( $nJobs < $Conf{MaxBackups}
662 && (@CmdQueue + $nJobs)
663 <= $Conf{MaxBackups} + $Conf{MaxPendingCmds}
665 $req = pop(@BgQueue);
666 if ( defined($Jobs{$req->{host}}) ) {
668 # Job is currently running for this host; save it for later
670 unshift(@deferBgQueue, $req);
673 $BgQueueOn{$req->{host}} = 0;
676 # Restore the deferred jobs
678 @BgQueue = (@BgQueue, @deferBgQueue);
679 @UserQueue = (@UserQueue, @deferUserQueue);
682 $host = $req->{host};
683 my $user = $req->{user};
684 if ( $req->{restore} ) {
685 $progName = "BackupPC_restore";
687 push(@args, $req->{hostIP}, $req->{host}, $req->{reqFileName});
688 } elsif ( $req->{archive} ) {
689 $progName = "BackupPC_archive";
691 push(@args, $req->{user}, $req->{host}, $req->{reqFileName});
693 $progName = "BackupPC_dump";
695 push(@args, "-d") if ( $req->{dhcp} );
696 push(@args, "-e") if ( $req->{dumpExpire} );
699 my $pid = open(FH, "-|");
700 if ( !defined($pid) ) {
701 print(LOG $bpc->timeStamp,
702 "can't fork to run $progName for $host, request by $user\n");
708 exec("$BinDir/$progName", @args);
709 print(LOG $bpc->timeStamp, "can't exec $progName for $host\n");
712 $Jobs{$host}{pid} = $pid;
713 $Jobs{$host}{fh} = *FH;
714 $Jobs{$host}{fn} = fileno(FH);
715 $Jobs{$host}{dhcp} = $req->{dhcp};
716 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
717 $Jobs{$host}{startTime} = time;
718 $Jobs{$host}{reqTime} = $req->{reqTime};
719 $Jobs{$host}{userReq} = $req->{userReq};
720 $Jobs{$host}{cmd} = $bpc->execCmd2ShellCmd($progName, @args);
721 $Jobs{$host}{user} = $user;
722 $Jobs{$host}{type} = $type;
723 $Status{$host}{userReq} = $req->{userReq}
724 if ( defined($Hosts->{$host}) );
725 if ( !$req->{dhcp} ) {
726 $Status{$host}{state} = "Status_".$type."_starting";
727 $Status{$host}{activeJob} = 1;
728 $Status{$host}{startTime} = time;
729 $Status{$host}{endTime} = "";
734 ############################################################################
737 # If necessary, figure out when to next wakeup based on $Conf{WakeupSchedule},
738 # and then do a select() to wait for the next thing to happen
739 # (timeout, signal, someone sends a message, child dies etc).
740 ############################################################################
743 if ( $NextWakeup <= 0 ) {
745 # Figure out when to next wakeup based on $Conf{WakeupSchedule}.
747 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
749 my($currHours) = $hour + $min / 60 + $sec / 3600;
750 if ( $bpc->ConfigMTime() != $Info{ConfigModTime} ) {
751 ServerReload("Re-read config file because mtime changed");
754 foreach my $t ( @{$Conf{WakeupSchedule} || [0..23]} ) {
755 next if ( $t < 0 || $t > 24 );
756 my $tomorrow = $t + 24;
758 || ($tomorrow - $currHours > 0
759 && $delta > $tomorrow - $currHours) ) {
760 $delta = $tomorrow - $currHours;
761 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
764 || ($t - $currHours > 0 && $delta > $t - $currHours) ) {
765 $delta = $t - $currHours;
766 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
769 $NextWakeup = time + $delta * 3600;
770 $Info{nextWakeup} = $NextWakeup;
771 print(LOG $bpc->timeStamp, "Next wakeup is ",
772 $bpc->timeStamp($NextWakeup, 1), "\n");
775 # Call select(), waiting until either a signal, a timeout,
776 # any output from our jobs, or any messages from clients
778 # select() is where we (hopefully) spend most of our time blocked...
780 my $timeout = $NextWakeup - time;
781 $timeout = 1 if ( $timeout <= 0 );
783 select(my $rout = $FDread, undef, $ein, $timeout);
788 ############################################################################
789 # Main_Process_Signal()
792 ############################################################################
793 sub Main_Process_Signal
798 if ( $SigName eq "HUP" ) {
799 ServerReload("Re-read config file because of a SIG_HUP");
800 } elsif ( $SigName ) {
801 ServerShutdown("Got signal $SigName... cleaning up");
806 ############################################################################
807 # Main_Check_Timeout()
809 # Check if a timeout has occured, and if so, queue all the PCs for backups.
810 # Also does log file aging on the first timeout after midnight.
811 ############################################################################
812 sub Main_Check_Timeout
817 return if ( time < $NextWakeup || $NextWakeup <= 0 );
819 if ( $FirstWakeup ) {
821 # This is the first wakeup after midnight. Do log file aging
822 # and various house keeping.
825 printf(LOG "%s24hr disk usage: %d%% max, %d%% recent,"
826 . " %d skipped hosts\n",
827 $bpc->timeStamp, $Info{DUDailyMax}, $Info{DUlastValue},
828 $Info{DUDailySkipHostCnt});
829 $Info{DUDailyMaxReset} = 1;
830 $Info{DUDailyMaxPrev} = $Info{DUDailyMax};
831 $Info{DUDailySkipHostCntPrev} = $Info{DUDailySkipHostCnt};
832 $Info{DUDailySkipHostCnt} = 0;
833 my $lastLog = $Conf{MaxOldLogFiles} - 1;
834 if ( -f "$LogDir/LOG.$lastLog" ) {
835 print(LOG $bpc->timeStamp,
836 "Removing $LogDir/LOG.$lastLog\n");
837 unlink("$LogDir/LOG.$lastLog");
839 if ( -f "$LogDir/LOG.$lastLog.z" ) {
840 print(LOG $bpc->timeStamp,
841 "Removing $LogDir/LOG.$lastLog.z\n");
842 unlink("$LogDir/LOG.$lastLog.z");
844 print(LOG $bpc->timeStamp, "Aging LOG files, LOG -> LOG.0 -> "
845 . "LOG.1 -> ... -> LOG.$lastLog\n");
846 close(STDERR); # dup of LOG
847 close(STDOUT); # dup of LOG
849 for ( my $i = $lastLog - 1 ; $i >= 0 ; $i-- ) {
851 rename("$LogDir/LOG.$i", "$LogDir/LOG.$j")
852 if ( -f "$LogDir/LOG.$i" );
853 rename("$LogDir/LOG.$i.z", "$LogDir/LOG.$j.z")
854 if ( -f "$LogDir/LOG.$i.z" );
857 # Compress the log file LOG -> LOG.0.z (if enabled).
858 # Otherwise, just rename LOG -> LOG.0.
860 BackupPC::FileZIO->compressCopy("$LogDir/LOG",
863 $Conf{CompressLevel}, 1);
866 # Remember to run the nightly script when the next CmdQueue
869 if ( $RunNightlyWhenIdle == 2 ) {
870 print(LOG $bpc->timeStamp, "BackupPC_nightly is still running after 24 hours!!"
871 . " You should adjust the config settings; Skipping this run\n");
873 $RunNightlyWhenIdle = 1;
877 # Write out the current status and then queue all the PCs
881 %BgQueueOn = () if ( @BgQueue == 0 );
882 %UserQueueOn = () if ( @UserQueue == 0 );
883 %CmdQueueOn = () if ( @CmdQueue == 0 );
887 ############################################################################
888 # Main_Check_Job_Messages($fdRead)
890 # Check if select() says we have bytes waiting from any of our jobs.
891 # Handle each of the messages when complete (newline terminated).
892 ############################################################################
893 sub Main_Check_Job_Messages
896 foreach my $host ( keys(%Jobs) ) {
897 next if ( !vec($fdRead, $Jobs{$host}{fn}, 1) );
900 # do a last check to make sure there is something to read so
901 # we are absolutely sure we won't block.
903 vec(my $readMask, $Jobs{$host}{fn}, 1) = 1;
904 if ( !select($readMask, undef, undef, 0.0) ) {
905 print(LOG $bpc->timeStamp, "Botch in Main_Check_Job_Messages:"
906 . " nothing to read from $host. Debug dump:\n");
907 my($dump) = Data::Dumper->new(
908 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
909 [qw(*Clients, *Jobs *FDread, *fdRead)]);
911 print(LOG $dump->Dump);
914 my $nbytes = sysread($Jobs{$host}{fh}, $mesg, 1024);
915 $Jobs{$host}{mesg} .= $mesg if ( $nbytes > 0 );
917 # Process any complete lines of output from this jobs.
918 # Any output to STDOUT or STDERR from the children is processed here.
920 while ( $Jobs{$host}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
922 $Jobs{$host}{mesg} = $2;
923 if ( $Jobs{$host}{dhcp} ) {
924 if ( $mesg =~ /^DHCP (\S+) (\S+)/ ) {
925 my $newHost = $bpc->uriUnesc($2);
926 if ( defined($Jobs{$newHost}) ) {
927 print(LOG $bpc->timeStamp,
928 "Backup on $newHost is already running\n");
929 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
933 $Jobs{$host}{dhcpHostIP} = $host;
934 $Status{$newHost}{dhcpHostIP} = $host;
935 $Jobs{$newHost} = $Jobs{$host};
936 delete($Jobs{$host});
938 $Status{$host}{state} = "Status_backup_starting";
939 $Status{$host}{activeJob} = 1;
940 $Status{$host}{startTime} = $Jobs{$host}{startTime};
941 $Status{$host}{endTime} = "";
942 $Jobs{$host}{dhcp} = 0;
944 print(LOG $bpc->timeStamp, "dhcp $host: $mesg\n");
946 } elsif ( $mesg =~ /^started (.*) dump, share=(.*)/ ) {
947 $Jobs{$host}{type} = $1;
948 $Jobs{$host}{shareName} = $2;
949 print(LOG $bpc->timeStamp,
950 "Started $1 backup on $host (pid=$Jobs{$host}{pid}",
951 $Jobs{$host}{dhcpHostIP}
952 ? ", dhcp=$Jobs{$host}{dhcpHostIP}" : "",
953 ", share=$Jobs{$host}{shareName})\n");
954 $Status{$host}{state} = "Status_backup_in_progress";
955 $Status{$host}{reason} = "";
956 $Status{$host}{type} = $1;
957 $Status{$host}{startTime} = time;
958 $Status{$host}{deadCnt} = 0;
959 $Status{$host}{aliveCnt}++;
960 $Status{$host}{dhcpCheckCnt}--
961 if ( $Status{$host}{dhcpCheckCnt} > 0 );
962 } elsif ( $mesg =~ /^xferPids (.*)/ ) {
963 $Jobs{$host}{xferPid} = $1;
964 } elsif ( $mesg =~ /^started_restore/ ) {
965 $Jobs{$host}{type} = "restore";
966 print(LOG $bpc->timeStamp,
967 "Started restore on $host"
968 . " (pid=$Jobs{$host}{pid})\n");
969 $Status{$host}{state} = "Status_restore_in_progress";
970 $Status{$host}{reason} = "";
971 $Status{$host}{type} = "restore";
972 $Status{$host}{startTime} = time;
973 $Status{$host}{deadCnt} = 0;
974 $Status{$host}{aliveCnt}++;
975 } elsif ( $mesg =~ /^started_archive/ ) {
976 $Jobs{$host}{type} = "archive";
977 print(LOG $bpc->timeStamp,
978 "Started archive on $host"
979 . " (pid=$Jobs{$host}{pid})\n");
980 $Status{$host}{state} = "Status_archive_in_progress";
981 $Status{$host}{reason} = "";
982 $Status{$host}{type} = "archive";
983 $Status{$host}{startTime} = time;
984 $Status{$host}{deadCnt} = 0;
985 $Status{$host}{aliveCnt}++;
986 } elsif ( $mesg =~ /^(full|incr) backup complete/ ) {
987 print(LOG $bpc->timeStamp, "Finished $1 backup on $host\n");
988 $Status{$host}{reason} = "Reason_backup_done";
989 delete($Status{$host}{error});
990 delete($Status{$host}{errorTime});
991 $Status{$host}{endTime} = time;
992 $Status{$host}{lastGoodBackupTime} = time;
993 } elsif ( $mesg =~ /^backups disabled/ ) {
994 print(LOG $bpc->timeStamp,
995 "Ignoring old backup error on $host\n");
996 $Status{$host}{reason} = "Reason_backup_done";
997 delete($Status{$host}{error});
998 delete($Status{$host}{errorTime});
999 $Status{$host}{endTime} = time;
1000 } elsif ( $mesg =~ /^restore complete/ ) {
1001 print(LOG $bpc->timeStamp, "Finished restore on $host\n");
1002 $Status{$host}{reason} = "Reason_restore_done";
1003 delete($Status{$host}{error});
1004 delete($Status{$host}{errorTime});
1005 $Status{$host}{endTime} = time;
1006 } elsif ( $mesg =~ /^archive complete/ ) {
1007 print(LOG $bpc->timeStamp, "Finished archive on $host\n");
1008 $Status{$host}{reason} = "Reason_archive_done";
1009 delete($Status{$host}{error});
1010 delete($Status{$host}{errorTime});
1011 $Status{$host}{endTime} = time;
1012 } elsif ( $mesg =~ /^nothing to do/ ) {
1013 if ( $Status{$host}{reason} ne "Reason_backup_failed"
1014 && $Status{$host}{reason} ne "Reason_restore_failed" ) {
1015 $Status{$host}{state} = "Status_idle";
1016 $Status{$host}{reason} = "Reason_nothing_to_do";
1017 $Status{$host}{startTime} = time;
1019 $Status{$host}{dhcpCheckCnt}--
1020 if ( $Status{$host}{dhcpCheckCnt} > 0 );
1021 } elsif ( $mesg =~ /^no ping response/
1022 || $mesg =~ /^ping too slow/
1023 || $mesg =~ /^host not found/ ) {
1024 $Status{$host}{state} = "Status_idle";
1025 if ( $Status{$host}{userReq}
1026 || $Status{$host}{reason} ne "Reason_backup_failed"
1027 || $Status{$host}{error} =~ /^aborted by user/ ) {
1028 $Status{$host}{reason} = "Reason_no_ping";
1029 $Status{$host}{error} = $mesg;
1030 $Status{$host}{startTime} = time;
1032 $Status{$host}{deadCnt}++;
1033 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1034 $Status{$host}{aliveCnt} = 0;
1036 } elsif ( $mesg =~ /^dump failed: (.*)/ ) {
1037 $Status{$host}{state} = "Status_idle";
1038 $Status{$host}{error} = $1;
1039 $Status{$host}{errorTime} = time;
1040 $Status{$host}{endTime} = time;
1041 if ( $Status{$host}{reason}
1042 eq "Reason_backup_canceled_by_user" ) {
1043 print(LOG $bpc->timeStamp,
1044 "Backup canceled on $host ($1)\n");
1046 $Status{$host}{reason} = "Reason_backup_failed";
1047 print(LOG $bpc->timeStamp,
1048 "Backup failed on $host ($1)\n");
1050 } elsif ( $mesg =~ /^restore failed: (.*)/ ) {
1051 $Status{$host}{state} = "Status_idle";
1052 $Status{$host}{error} = $1;
1053 $Status{$host}{errorTime} = time;
1054 $Status{$host}{endTime} = time;
1055 if ( $Status{$host}{reason}
1056 eq "Reason_restore_canceled_by_user" ) {
1057 print(LOG $bpc->timeStamp,
1058 "Restore canceled on $host ($1)\n");
1060 $Status{$host}{reason} = "Reason_restore_failed";
1061 print(LOG $bpc->timeStamp,
1062 "Restore failed on $host ($1)\n");
1064 } elsif ( $mesg =~ /^archive failed: (.*)/ ) {
1065 $Status{$host}{state} = "Status_idle";
1066 $Status{$host}{error} = $1;
1067 $Status{$host}{errorTime} = time;
1068 $Status{$host}{endTime} = time;
1069 if ( $Status{$host}{reason}
1070 eq "Reason_archive_canceled_by_user" ) {
1071 print(LOG $bpc->timeStamp,
1072 "Archive canceled on $host ($1)\n");
1074 $Status{$host}{reason} = "Reason_archive_failed";
1075 print(LOG $bpc->timeStamp,
1076 "Archive failed on $host ($1)\n");
1078 } elsif ( $mesg =~ /^log\s+(.*)/ ) {
1079 print(LOG $bpc->timeStamp, "$1\n");
1080 } elsif ( $mesg =~ /^BackupPC_stats (\d+) = (.*)/ ) {
1081 my $chunk = int($1 / 16);
1082 my @f = split(/,/, $2);
1083 $Info{pool}{$f[0]}[$chunk]{FileCnt} += $f[1];
1084 $Info{pool}{$f[0]}[$chunk]{DirCnt} += $f[2];
1085 $Info{pool}{$f[0]}[$chunk]{Kb} += $f[3];
1086 $Info{pool}{$f[0]}[$chunk]{Kb2} += $f[4];
1087 $Info{pool}{$f[0]}[$chunk]{KbRm} += $f[5];
1088 $Info{pool}{$f[0]}[$chunk]{FileCntRm} += $f[6];
1089 $Info{pool}{$f[0]}[$chunk]{FileCntRep} += $f[7];
1090 $Info{pool}{$f[0]}[$chunk]{FileRepMax} = $f[8]
1091 if ( $Info{pool}{$f[0]}[$chunk]{FileRepMax} < $f[8] );
1092 $Info{pool}{$f[0]}[$chunk]{FileCntRename} += $f[9];
1093 $Info{pool}{$f[0]}[$chunk]{FileLinkMax} = $f[10]
1094 if ( $Info{pool}{$f[0]}[$chunk]{FileLinkMax} < $f[10] );
1095 $Info{pool}{$f[0]}[$chunk]{FileLinkTotal} += $f[11];
1096 $Info{pool}{$f[0]}[$chunk]{Time} = time;
1097 } elsif ( $mesg =~ /^BackupPC_nightly lock_off/ ) {
1098 $BackupPCNightlyLock--;
1099 if ( $BackupPCNightlyLock == 0 ) {
1101 # This means the last BackupPC_nightly is done with
1102 # the pool clean, so it's ok to start running regular
1103 # backups again. But starting in 3.0 regular jobs
1104 # are decoupled from BackupPC_nightly.
1106 $RunNightlyWhenIdle = 0;
1108 } elsif ( $mesg =~ /^processState\s+(.+)/ ) {
1109 $Jobs{$host}{processState} = $1;
1110 } elsif ( $mesg =~ /^link\s+(.+)/ ) {
1112 $Status{$h}{needLink} = 1;
1114 print(LOG $bpc->timeStamp, "$host: $mesg\n");
1118 # shut down the client connection if we read EOF
1120 if ( $nbytes <= 0 ) {
1121 close($Jobs{$host}{fh});
1122 vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1123 if ( $CmdJob eq $host || $bpc->isAdminJob($host) ) {
1124 my $cmd = $Jobs{$host}{cmd};
1125 $cmd =~ s/$BinDir\///g;
1126 print(LOG $bpc->timeStamp, "Finished $host ($cmd)\n");
1127 $Status{$host}{state} = "Status_idle";
1128 $Status{$host}{endTime} = time;
1129 if ( $cmd =~ /^BackupPC_nightly\s/ ) {
1130 $BackupPCNightlyJobs--;
1131 #print(LOG $bpc->timeStamp, "BackupPC_nightly done; now"
1132 # . " have $BackupPCNightlyJobs running\n");
1133 if ( $BackupPCNightlyJobs <= 0 ) {
1135 # Last BackupPC_nightly has finished
1137 $BackupPCNightlyJobs = 0;
1138 $RunNightlyWhenIdle = 0;
1141 # Combine the 16 per-directory results
1143 for my $p ( qw(pool cpool) ) {
1144 $Info{"${p}FileCnt"} = 0;
1145 $Info{"${p}DirCnt"} = 0;
1146 $Info{"${p}Kb"} = 0;
1147 $Info{"${p}Kb2"} = 0;
1148 $Info{"${p}KbRm"} = 0;
1149 $Info{"${p}FileCntRm"} = 0;
1150 $Info{"${p}FileCntRep"} = 0;
1151 $Info{"${p}FileRepMax"} = 0;
1152 $Info{"${p}FileCntRename"} = 0;
1153 $Info{"${p}FileLinkMax"} = 0;
1154 $Info{"${p}Time"} = 0;
1155 for ( my $i = 0 ; $i < 16 ; $i++ ) {
1156 $Info{"${p}FileCnt"}
1157 += $Info{pool}{$p}[$i]{FileCnt};
1159 += $Info{pool}{$p}[$i]{DirCnt};
1161 += $Info{pool}{$p}[$i]{Kb};
1163 += $Info{pool}{$p}[$i]{Kb2};
1165 += $Info{pool}{$p}[$i]{KbRm};
1166 $Info{"${p}FileCntRm"}
1167 += $Info{pool}{$p}[$i]{FileCntRm};
1168 $Info{"${p}FileCntRep"}
1169 += $Info{pool}{$p}[$i]{FileCntRep};
1170 $Info{"${p}FileRepMax"}
1171 = $Info{pool}{$p}[$i]{FileRepMax}
1172 if ( $Info{"${p}FileRepMax"} <
1173 $Info{pool}{$p}[$i]{FileRepMax} );
1174 $Info{"${p}FileCntRename"}
1175 += $Info{pool}{$p}[$i]{FileCntRename};
1176 $Info{"${p}FileLinkMax"}
1177 = $Info{pool}{$p}[$i]{FileLinkMax}
1178 if ( $Info{"${p}FileLinkMax"} <
1179 $Info{pool}{$p}[$i]{FileLinkMax} );
1180 $Info{"${p}Time"} = $Info{pool}{$p}[$i]{Time}
1181 if ( $Info{"${p}Time"} <
1182 $Info{pool}{$p}[$i]{Time} );
1184 printf(LOG "%s%s nightly clean removed %d files of"
1186 $bpc->timeStamp, ucfirst($p),
1187 $Info{"${p}FileCntRm"},
1188 $Info{"${p}KbRm"} / (1000 * 1024));
1189 printf(LOG "%s%s is %.2fGB, %d files (%d repeated, "
1190 . "%d max chain, %d max links), %d directories\n",
1191 $bpc->timeStamp, ucfirst($p),
1192 $Info{"${p}Kb"} / (1000 * 1024),
1193 $Info{"${p}FileCnt"}, $Info{"${p}FileCntRep"},
1194 $Info{"${p}FileRepMax"},
1195 $Info{"${p}FileLinkMax"}, $Info{"${p}DirCnt"});
1203 # Queue BackupPC_link to complete the backup
1204 # processing for this host.
1206 if ( defined($Status{$host})
1207 && ($Status{$host}{reason} eq "Reason_backup_done"
1208 || $Status{$host}{needLink}) ) {
1210 } elsif ( defined($Status{$host}) ) {
1211 $Status{$host}{state} = "Status_idle";
1214 delete($Jobs{$host});
1215 $Status{$host}{activeJob} = 0 if ( defined($Status{$host}) );
1219 # When we are idle (empty Jobs, CmdQueue, BgQueue, UserQueue) we
1220 # do a pass over %Status updating the deadCnt and aliveCnt for
1221 # DHCP hosts. The reason we need to do this later is we can't
1222 # be sure whether a DHCP host is alive or dead until we have passed
1223 # over all the DHCP pool.
1225 return if ( @CmdQueue || @BgQueue || @UserQueue || keys(%Jobs) > 1 );
1226 foreach my $host ( keys(%Status) ) {
1227 next if ( $Status{$host}{dhcpCheckCnt} <= 0 );
1228 $Status{$host}{deadCnt} += $Status{$host}{dhcpCheckCnt};
1229 $Status{$host}{dhcpCheckCnt} = 0;
1230 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1231 $Status{$host}{aliveCnt} = 0;
1236 ############################################################################
1237 # Main_Check_Client_Messages($fdRead)
1239 # Check for, and process, any output from our clients. Also checks
1240 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
1241 ############################################################################
1242 sub Main_Check_Client_Messages
1245 foreach my $client ( keys(%Clients) ) {
1246 next if ( !vec($fdRead, $Clients{$client}{fn}, 1) );
1249 # do a last check to make sure there is something to read so
1250 # we are absolutely sure we won't block.
1252 vec(my $readMask, $Clients{$client}{fn}, 1) = 1;
1253 if ( !select($readMask, undef, undef, 0.0) ) {
1254 print(LOG $bpc->timeStamp, "Botch in Main_Check_Client_Messages:"
1255 . " nothing to read from $client. Debug dump:\n");
1256 my($dump) = Data::Dumper->new(
1257 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
1258 [qw(*Clients, *Jobs *FDread, *fdRead)]);
1260 print(LOG $dump->Dump);
1263 my $nbytes = sysread($Clients{$client}{fh}, $mesg, 1024);
1264 $Clients{$client}{mesg} .= $mesg if ( $nbytes > 0 );
1266 # Process any complete lines received from this client.
1268 while ( $Clients{$client}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
1271 $Clients{$client}{mesg} = $2;
1273 # Authenticate the message by checking the MD5 digest
1275 my $md5 = Digest::MD5->new;
1276 if ( $cmd !~ /^(.{22}) (.*)/
1277 || ($md5->add($Clients{$client}{seed}
1278 . $Clients{$client}{mesgCnt}
1279 . $Conf{ServerMesgSecret} . $2),
1280 $md5->b64digest ne $1) ) {
1281 print(LOG $bpc->timeStamp, "Corrupted message '$cmd' from"
1282 . " client '$Clients{$client}{clientName}':"
1283 . " shutting down client connection\n");
1287 $Clients{$client}{mesgCnt}++;
1288 $cmd = decode_utf8($2);
1289 if ( $cmd =~ /^stop (\S+)\s+(\S+)\s+(\S*)/ ) {
1293 $host = $bpc->uriUnesc($host);
1294 if ( $CmdJob ne $host && defined($Status{$host})
1295 && defined($Jobs{$host}) ) {
1296 print(LOG $bpc->timeStamp,
1297 "Stopping current $Jobs{$host}{type} of $host,"
1298 . " request by $user (backoff=$backoff)\n");
1299 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1301 # Don't close the pipe now; wait until the child
1302 # really exits later. Otherwise close() will
1303 # block until the child has exited.
1305 ##vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1306 ##close($Jobs{$host}{fh});
1307 ##delete($Jobs{$host});
1309 $Status{$host}{state} = "Status_idle";
1310 if ( $Jobs{$host}{type} eq "restore" ) {
1311 $Status{$host}{reason}
1312 = "Reason_restore_canceled_by_user";
1313 } elsif ( $Jobs{$host}{type} eq "archive" ) {
1314 $Status{$host}{reason}
1315 = "Reason_archive_canceled_by_user";
1317 $Status{$host}{reason}
1318 = "Reason_backup_canceled_by_user";
1320 $Status{$host}{activeJob} = 0;
1321 $Status{$host}{startTime} = time;
1322 $reply = "ok: $Jobs{$host}{type} of $host canceled";
1323 } elsif ( $BgQueueOn{$host} || $UserQueueOn{$host} ) {
1324 print(LOG $bpc->timeStamp,
1325 "Stopping pending backup of $host,"
1326 . " request by $user (backoff=$backoff)\n");
1327 @BgQueue = grep($_->{host} ne $host, @BgQueue);
1328 @UserQueue = grep($_->{host} ne $host, @UserQueue);
1329 $BgQueueOn{$host} = $UserQueueOn{$host} = 0;
1330 $reply = "ok: pending backup of $host canceled";
1332 print(LOG $bpc->timeStamp,
1333 "Nothing to do for stop backup of $host,"
1334 . " request by $user (backoff=$backoff)\n");
1335 $reply = "ok: no backup was pending or running";
1337 if ( defined($Status{$host}) && $backoff ne "" ) {
1338 if ( $backoff > 0 ) {
1339 $Status{$host}{backoffTime} = time + $backoff * 3600;
1341 delete($Status{$host}{backoffTime});
1344 } elsif ( $cmd =~ /^backup all$/ ) {
1346 } elsif ( $cmd =~ /^BackupPC_nightly run$/ ) {
1347 $RunNightlyWhenIdle = 1;
1348 } elsif ( $cmd =~ /^queue (\S+)$/ ) {
1350 $host = $bpc->uriUnesc($host);
1351 if ( !defined($Hosts->{$host}) ) {
1352 print(LOG $bpc->timeStamp,
1353 "User requested backup of unknown host $host\n");
1354 $reply = "error: unknown host $host";
1356 if ( QueueOnePC($host) ) {
1357 print(LOG $bpc->timeStamp,
1358 "Disk too full ($Info{DUlastValue}%); skipped 1 host\n");
1359 $Info{DUDailySkipHostCnt}++;
1360 $reply = "error: disk too full to queue $host";
1362 print(LOG $bpc->timeStamp, "Host $host queued by user.\n");
1363 $reply = "ok: $host queued";
1366 } elsif ( $cmd =~ /^backup (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1371 $host = $bpc->uriUnesc($host);
1372 $hostIP = $bpc->uriUnesc($hostIP);
1373 if ( !defined($Hosts->{$host}) ) {
1374 print(LOG $bpc->timeStamp,
1375 "User $user requested backup of unknown host"
1377 $reply = "error: unknown host $host";
1379 print(LOG $bpc->timeStamp,
1380 "User $user requested backup of $host"
1382 if ( $BgQueueOn{$hostIP} ) {
1383 @BgQueue = grep($_->{host} ne $hostIP, @BgQueue);
1384 $BgQueueOn{$hostIP} = 0;
1386 if ( $UserQueueOn{$hostIP} ) {
1387 @UserQueue = grep($_->{host} ne $hostIP, @UserQueue);
1388 $UserQueueOn{$hostIP} = 0;
1390 unshift(@UserQueue, {
1396 dhcp => $hostIP eq $host ? 0 : 1,
1398 $UserQueueOn{$hostIP} = 1;
1399 $reply = "ok: requested backup of $host";
1401 } elsif ( $cmd =~ /^archive (\S+)\s+(\S+)\s+(\S+)/ ) {
1403 my $archivehost = $2;
1404 my $reqFileName = $3;
1405 $host = $bpc->uriUnesc($archivehost);
1406 if ( !defined($Status{$host}) ) {
1407 print(LOG $bpc->timeStamp,
1408 "User $user requested archive of unknown archive host"
1410 $reply = "archive error: unknown archive host $host";
1412 print(LOG $bpc->timeStamp,
1413 "User $user requested archive on $host"
1415 if ( defined($Jobs{$host}) ) {
1416 $reply = "Archive currently running on $host, please try later";
1418 unshift(@UserQueue, {
1421 reqFileName => $reqFileName,
1427 $UserQueueOn{$host} = 1;
1428 $reply = "ok: requested archive on $host";
1431 } elsif ( $cmd =~ /^restore (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1435 my $reqFileName = $4;
1436 $host = $bpc->uriUnesc($host);
1437 $hostIP = $bpc->uriUnesc($hostIP);
1438 if ( !defined($Hosts->{$host}) ) {
1439 print(LOG $bpc->timeStamp,
1440 "User $user requested restore to unknown host"
1442 $reply = "restore error: unknown host $host";
1444 print(LOG $bpc->timeStamp,
1445 "User $user requested restore to $host"
1447 unshift(@UserQueue, {
1450 reqFileName => $reqFileName,
1456 $UserQueueOn{$host} = 1;
1457 if ( defined($Jobs{$host}) ) {
1458 $reply = "ok: requested restore of $host, but a"
1459 . " job is currently running,"
1460 . " so this request will start later";
1462 $reply = "ok: requested restore of $host";
1465 } elsif ( $cmd =~ /^status\s*(.*)/ ) {
1467 my($dump, @values, @names);
1468 foreach my $type ( split(/\s+/, $args) ) {
1469 if ( $type =~ /^queues/ ) {
1470 push(@values, \@BgQueue, \@UserQueue, \@CmdQueue);
1471 push(@names, qw(*BgQueue *UserQueue *CmdQueue));
1472 } elsif ( $type =~ /^jobs/ ) {
1473 push(@values, \%Jobs);
1474 push(@names, qw(*Jobs));
1475 } elsif ( $type =~ /^queueLen/ ) {
1477 BgQueue => scalar(@BgQueue),
1478 UserQueue => scalar(@UserQueue),
1479 CmdQueue => scalar(@CmdQueue),
1481 push(@names, qw(*QueueLen));
1482 } elsif ( $type =~ /^info/ ) {
1483 push(@values, \%Info);
1484 push(@names, qw(*Info));
1485 } elsif ( $type =~ /^hosts/ ) {
1486 push(@values, \%Status);
1487 push(@names, qw(*Status));
1488 } elsif ( $type =~ /^host\((.*)\)/ ) {
1489 my $h = $bpc->uriUnesc($1);
1490 if ( defined($Status{$h}) ) {
1493 BgQueueOn => $BgQueueOn{$h},
1494 UserQueueOn => $UserQueueOn{$h},
1495 CmdQueueOn => $CmdQueueOn{$h},
1497 push(@names, qw(*StatusHost));
1499 print(LOG $bpc->timeStamp,
1500 "Unknown host $h for status request\n");
1503 print(LOG $bpc->timeStamp,
1504 "Unknown status request $type\n");
1507 $dump = Data::Dumper->new(\@values, \@names);
1509 $reply = $dump->Dump;
1510 } elsif ( $cmd =~ /^link\s+(.+)/ ) {
1512 $host = $bpc->uriUnesc($host);
1514 } elsif ( $cmd =~ /^log\s+(.*)/ ) {
1515 print(LOG $bpc->timeStamp, "$1\n");
1516 } elsif ( $cmd =~ /^server\s+(\w+)/ ) {
1518 if ( $type eq 'reload' ) {
1519 ServerReload("Reloading config/host files via CGI request");
1520 } elsif ( $type eq 'shutdown' ) {
1521 $reply = "Shutting down...\n";
1522 syswrite($Clients{$client}{fh}, $reply, length($reply));
1523 ServerShutdown("Server shutting down...");
1525 } elsif ( $cmd =~ /^quit/ || $cmd =~ /^exit/ ) {
1529 print(LOG $bpc->timeStamp, "Unknown command $cmd\n");
1530 $reply = "error: bad command $cmd";
1533 # send a reply to the client, at a minimum "ok\n".
1535 $reply = "ok" if ( $reply eq "" );
1537 syswrite($Clients{$client}{fh}, $reply, length($reply));
1540 # Detect possible denial-of-service attack from sending a huge line
1541 # (ie: never terminated). 32K seems to be plenty big enough as
1544 if ( length($Clients{$client}{mesg}) > 32 * 1024 ) {
1545 print(LOG $bpc->timeStamp, "Line too long from client"
1546 . " '$Clients{$client}{clientName}':"
1547 . " shutting down client connection\n");
1551 # Shut down the client connection if we read EOF
1553 if ( $nbytes <= 0 ) {
1554 close($Clients{$client}{fh});
1555 vec($FDread, $Clients{$client}{fn}, 1) = 0;
1556 delete($Clients{$client});
1560 # Accept any new connections on each of our listen sockets
1562 if ( vec($fdRead, fileno(SERVER_UNIX), 1) ) {
1564 my $paddr = accept(CLIENT, SERVER_UNIX);
1566 $Clients{$ClientConnCnt}{clientName} = "unix socket";
1567 $Clients{$ClientConnCnt}{mesg} = "";
1568 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1569 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1570 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1572 # Generate and send unique seed for MD5 digests to avoid
1573 # replay attacks. See BackupPC::Lib::ServerMesg().
1575 my $seed = time . ",$ClientConnCnt,$$,0\n";
1576 $Clients{$ClientConnCnt}{seed} = $seed;
1577 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1578 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1580 if ( $ServerInetPort > 0 && vec($fdRead, fileno(SERVER_INET), 1) ) {
1582 my $paddr = accept(CLIENT, SERVER_INET);
1583 my($port,$iaddr) = sockaddr_in($paddr);
1584 my $name = gethostbyaddr($iaddr, AF_INET);
1586 $Clients{$ClientConnCnt}{mesg} = "";
1587 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1588 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1589 $Clients{$ClientConnCnt}{clientName} = "$name:$port";
1590 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1592 # Generate and send unique seed for MD5 digests to avoid
1593 # replay attacks. See BackupPC::Lib::ServerMesg().
1595 my $seed = time . ",$ClientConnCnt,$$,$port\n";
1596 $Clients{$ClientConnCnt}{seed} = $seed;
1597 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1598 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1602 ###########################################################################
1603 # Miscellaneous subroutines
1604 ###########################################################################
1607 # Write the current status to $LogDir/status.pl
1611 my($dump) = Data::Dumper->new(
1612 [ \%Info, \%Status],
1613 [qw(*Info *Status)]);
1615 my $text = $dump->Dump;
1616 $bpc->{storage}->TextFileWrite("$LogDir/status.pl", $text);
1620 # Compare function for host sort. Hosts with errors go first,
1621 # sorted with the oldest errors first. The remaining hosts
1622 # are sorted so that those with the oldest backups go first.
1627 # Hosts with errors go before hosts without errors
1629 return -1 if ( $Status{$a}{error} ne "" && $Status{$b}{error} eq "" );
1632 # Hosts with no errors go after hosts with errors
1634 return 1 if ( $Status{$a}{error} eq "" && $Status{$b}{error} ne "" );
1637 # hosts with the older last good backups sort earlier
1639 my $r = $Status{$a}{lastGoodBackupTime} <=> $Status{$b}{lastGoodBackupTime};
1640 return $r if ( $r );
1643 # Finally, just sort based on host name
1653 delete($Status{$host}{backoffTime})
1654 if ( defined($Status{$host}{backoffTime})
1655 && $Status{$host}{backoffTime} < time );
1656 return if ( defined($Jobs{$host})
1657 || $BgQueueOn{$host}
1658 || $UserQueueOn{$host}
1659 || $CmdQueueOn{$host} );
1660 if ( $Hosts->{$host}{dhcp} ) {
1661 $Status{$host}{dhcpCheckCnt}++;
1662 if ( $RunNightlyWhenIdle ) {
1664 # Once per night queue a check for DHCP hosts that just
1665 # checks for expired dumps. We need to do this to handle
1666 # the case when a DHCP host has not been on the network for
1667 # a long time, and some of the old dumps need to be expired.
1668 # Normally expiry checks are done by BackupPC_dump only
1669 # after the DHCP hosts has been detected on the network.
1672 {host => $host, user => "BackupPC", reqTime => time,
1673 dhcp => 0, dumpExpire => 1});
1674 $BgQueueOn{$host} = 1;
1678 # this is a fixed ip host: queue it
1680 if ( $Info{DUlastValue} > $Conf{DfMaxUsagePct} ) {
1682 # Since we are out of disk space, instead of queuing
1683 # a regular job, queue an expire check instead. That
1684 # way if the admin reduces the number of backups to
1685 # keep then we will actually delete them. Otherwise
1686 # BackupPC_dump will never run since we have exceeded
1691 {host => $host, user => "BackupPC", reqTime => time,
1692 dhcp => $Hosts->{$host}{dhcp}, dumpExpire => 1});
1695 # Queue regular background backup
1698 {host => $host, user => "BackupPC", reqTime => time,
1699 dhcp => $Hosts->{$host}{dhcp}});
1701 $BgQueueOn{$host} = 1;
1708 # Queue all the hosts for backup. This means queuing all the fixed
1709 # ip hosts and all the dhcp address ranges. We also additionally
1710 # queue the dhcp hosts with a -e flag to check for expired dumps.
1716 foreach my $host ( sort(HostSortCompare keys(%$Hosts)) ) {
1717 $nSkip += QueueOnePC($host);
1720 print(LOG $bpc->timeStamp,
1721 "Disk too full ($Info{DUlastValue}%); skipped $nSkip hosts\n");
1722 $Info{DUDailySkipHostCnt} += $nSkip;
1724 foreach my $dhcp ( @{$Conf{DHCPAddressRanges}} ) {
1725 for ( my $i = $dhcp->{first} ; $i <= $dhcp->{last} ; $i++ ) {
1726 my $ipAddr = "$dhcp->{ipAddrBase}.$i";
1727 next if ( defined($Jobs{$ipAddr})
1728 || $BgQueueOn{$ipAddr}
1729 || $UserQueueOn{$ipAddr}
1730 || $CmdQueueOn{$ipAddr} );
1732 # this is a potential dhcp ip address (we don't know the
1733 # host name yet): queue it
1736 {host => $ipAddr, user => "BackupPC", reqTime => time,
1738 $BgQueueOn{$ipAddr} = 1;
1744 # Queue a BackupPC_link for the given host
1750 return if ( $CmdQueueOn{$host} );
1751 $Status{$host}{state} = "Status_link_pending";
1752 $Status{$host}{needLink} = 0;
1753 unshift(@CmdQueue, {
1757 cmd => ["$BinDir/BackupPC_link", $host],
1759 $CmdQueueOn{$host} = 1;
1763 # Read the hosts file, and update Status if any hosts have been
1764 # added or deleted. We also track the mtime so the only need to
1765 # update the hosts file on changes.
1767 # This function is called at startup, SIGHUP, and on each wakeup.
1768 # It returns 1 on success and undef on failure.
1775 # Nothing to do if we already have the current hosts file
1777 return 1 if ( !$force && defined($Hosts)
1778 && $Info{HostsModTime} == $bpc->HostsMTime() );
1779 if ( !defined($newHosts = $bpc->HostInfoRead()) ) {
1780 print(LOG $bpc->timeStamp, "Can't read hosts file!\n");
1783 print(LOG $bpc->timeStamp, "Reading hosts file\n");
1785 $Info{HostsModTime} = $bpc->HostsMTime();
1787 # Now update %Status in case any hosts have been added or deleted
1789 foreach my $host ( sort(keys(%$Hosts)) ) {
1790 next if ( defined($Status{$host}) );
1791 $Status{$host}{state} = "Status_idle";
1792 print(LOG $bpc->timeStamp, "Added host $host to backup list\n");
1794 foreach my $host ( sort(keys(%Status)) ) {
1795 next if ( $host eq $bpc->trashJob
1796 || $bpc->isAdminJob($host)
1797 || defined($Hosts->{$host})
1798 || defined($Jobs{$host})
1799 || $BgQueueOn{$host}
1800 || $UserQueueOn{$host}
1801 || $CmdQueueOn{$host} );
1802 print(LOG $bpc->timeStamp, "Deleted host $host from backup list\n");
1803 delete($Status{$host});
1809 # Remember the signal name for later processing
1815 foreach my $host ( keys(%Jobs) ) {
1816 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1819 # In case we are inside the exit handler, reopen the log file
1823 print(LOG "Fatal error: unhandled signal $SigName\n");
1824 unlink("$LogDir/BackupPC.pid");
1825 confess("Got new signal $SigName... quitting\n");
1832 # Open the log file and point STDOUT and STDERR there too
1836 mkpath($LogDir, 0, 0777) if ( !-d $LogDir );
1837 open(LOG, ">>$LogDir/LOG")
1838 || die("Can't create LOG file $LogDir/LOG");
1841 open(STDOUT, ">&LOG");
1842 open(STDERR, ">&LOG");
1843 select(LOG); $| = 1;
1844 select(STDERR); $| = 1;
1845 select(STDOUT); $| = 1;
1849 # Initialize the unix-domain and internet-domain sockets that
1850 # we listen to for client connections (from the CGI script and
1851 # some of the BackupPC sub-programs).
1853 sub ServerSocketInit
1855 if ( !defined(fileno(SERVER_UNIX)) ) {
1857 # one-time only: initialize unix-domain socket
1859 if ( !socket(SERVER_UNIX, PF_UNIX, SOCK_STREAM, 0) ) {
1860 print(LOG $bpc->timeStamp, "unix socket() failed: $!\n");
1863 my $sockFile = "$LogDir/BackupPC.sock";
1865 if ( !bind(SERVER_UNIX, sockaddr_un($sockFile)) ) {
1866 print(LOG $bpc->timeStamp, "unix bind() failed: $!\n");
1869 if ( !listen(SERVER_UNIX, SOMAXCONN) ) {
1870 print(LOG $bpc->timeStamp, "unix listen() failed: $!\n");
1873 vec($FDread, fileno(SERVER_UNIX), 1) = 1;
1875 return if ( $ServerInetPort == $Conf{ServerPort} );
1876 if ( $ServerInetPort > 0 ) {
1877 vec($FDread, fileno(SERVER_INET), 1) = 0;
1879 $ServerInetPort = -1;
1881 if ( $Conf{ServerPort} > 0 ) {
1883 # Setup a socket to listen on $Conf{ServerPort}
1885 my $proto = getprotobyname('tcp');
1886 if ( !socket(SERVER_INET, PF_INET, SOCK_STREAM, $proto) ) {
1887 print(LOG $bpc->timeStamp, "inet socket() failed: $!\n");
1890 if ( !setsockopt(SERVER_INET, SOL_SOCKET, SO_REUSEADDR, pack("l",1)) ) {
1891 print(LOG $bpc->timeStamp, "setsockopt() failed: $!\n");
1894 if ( !bind(SERVER_INET, sockaddr_in($Conf{ServerPort}, INADDR_ANY)) ) {
1895 print(LOG $bpc->timeStamp, "inet bind() failed: $!\n");
1898 if ( !listen(SERVER_INET, SOMAXCONN) ) {
1899 print(LOG $bpc->timeStamp, "inet listen() failed: $!\n");
1902 vec($FDread, fileno(SERVER_INET), 1) = 1;
1903 $ServerInetPort = $Conf{ServerPort};
1908 # Reload the server. Used by Main_Process_Signal when $SigName eq "HUP"
1909 # or when the command "server reload" is received.
1914 $mesg = $bpc->ConfigRead() || $mesg;
1915 print(LOG $bpc->timeStamp, "$mesg\n");
1916 $Info{ConfigModTime} = $bpc->ConfigMTime();
1917 %Conf = $bpc->Conf();
1918 umask($Conf{UmaskMode});
1922 $Info{ConfigLTime} = time;
1926 # Gracefully shutdown the server. Used by Main_Process_Signal when
1927 # $SigName ne "" && $SigName ne "HUP" or when the command
1928 # "server shutdown" is received.
1933 print(LOG $bpc->timeStamp, "$mesg\n");
1934 if ( keys(%Jobs) ) {
1935 foreach my $host ( keys(%Jobs) ) {
1936 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1939 foreach my $host ( keys(%Jobs) ) {
1940 kill($bpc->sigName2num("KILL"), $Jobs{$host}{pid});
1946 unlink("$LogDir/BackupPC.pid");