2 #============================================================= -*-perl-*-
4 # BackupPC: Main program for PC backups.
8 # BackupPC reads the configuration and status information from
9 # $ConfDir/conf. It then runs and manages all the backup activity.
11 # As specified by $Conf{WakeupSchedule}, BackupPC wakes up periodically
12 # to queue backups on all the PCs. This is a four step process:
13 # 1) For each host and DHCP address backup requests are queued on the
14 # background command queue.
15 # 2) For each PC, BackupPC_dump is forked. Several of these may
16 # be run in parallel, based on the configuration.
17 # 3) For each complete, good, backup, BackupPC_link is forked.
18 # Only one of these tasks runs at a time.
19 # 4) In the background BackupPC_trashClean is run to remove any expired
20 # backups. Once each night, BackupPC_nightly is run to complete some
21 # additional administrative tasks (pool cleaning etc).
23 # BackupPC also listens for connections on a unix domain socket and
24 # the tcp port $Conf{ServerPort}, which are used by various
25 # sub-programs and the CGI script BackupPC_Admin for status reporting
26 # and user-initiated backup or backup cancel requests.
29 # Craig Barratt <cbarratt@users.sourceforge.net>
32 # Copyright (C) 2001-2003 Craig Barratt
34 # This program is free software; you can redistribute it and/or modify
35 # it under the terms of the GNU General Public License as published by
36 # the Free Software Foundation; either version 2 of the License, or
37 # (at your option) any later version.
39 # This program is distributed in the hope that it will be useful,
40 # but WITHOUT ANY WARRANTY; without even the implied warranty of
41 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
42 # GNU General Public License for more details.
44 # You should have received a copy of the GNU General Public License
45 # along with this program; if not, write to the Free Software
46 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
48 #========================================================================
50 # Version 3.0.0beta2, released 11 Nov 2006.
52 # See http://backuppc.sourceforge.net.
54 #========================================================================
58 use vars qw(%Status %Info $Hosts);
59 use lib "/usr/local/BackupPC/lib";
61 use BackupPC::FileZIO;
71 ###########################################################################
72 # Handle command line options
73 ###########################################################################
75 if ( !getopts("d", \%opts) || @ARGV != 0 ) {
76 print("usage: $0 [-d]\n");
80 ###########################################################################
81 # Initialize major data structures and variables
82 ###########################################################################
85 # Get an instance of BackupPC::Lib and get some shortcuts.
87 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
88 my $TopDir = $bpc->TopDir();
89 my $BinDir = $bpc->BinDir();
90 my $LogDir = $bpc->LogDir();
91 my %Conf = $bpc->Conf();
94 # Verify we are running as the correct user
96 if ( $Conf{BackupPCUserVerify}
97 && $> != (my $uid = (getpwnam($Conf{BackupPCUser}))[2]) ) {
98 die "Wrong user: my userid is $>, instead of $uid ($Conf{BackupPCUser})\n";
102 # %Status maintain status information about each host.
103 # It is a hash of hashes, whose first index is the host.
108 # %Info is a hash giving general information about BackupPC status.
115 if ( -f "$LogDir/status.pl" && !(my $ret = do "$LogDir/status.pl") ) {
116 die "couldn't parse $LogDir/status.pl: $@" if $@;
117 die "couldn't do $LogDir/status.pl: $!" unless defined $ret;
118 die "couldn't run $LogDir/status.pl";
122 # %Jobs maintains information about currently running jobs.
123 # It is a hash of hashes, whose first index is the host.
128 # There are three command queues:
129 # - @UserQueue is a queue of user initiated backup requests.
130 # - @BgQueue is a queue of automatically scheduled backup requests.
131 # - @CmdQueue is a queue of administrative jobs, including tasks
132 # like BackupPC_link, BackupPC_trashClean, and BackupPC_nightly
133 # Each queue is an array of hashes. Each hash stores information
134 # about the command request.
141 # To quickly lookup if a given host is on a given queue, we keep
142 # a hash of flags for each queue type.
144 my(%CmdQueueOn, %UserQueueOn, %BgQueueOn);
147 # One or more clients can connect to the server to get status information
148 # or request/cancel backups etc. The %Clients hash maintains information
149 # about each of these socket connections. The hash key is an incrementing
150 # number stored in $ClientConnCnt. Each entry is a hash that contains
151 # various information about the client connection.
157 # Read file descriptor mask used by select(). Every file descriptor
158 # on which we expect to read (or accept) has the corresponding bit
164 # Unix seconds when we next wakeup. A value of zero forces the scheduler
165 # to compute the next wakeup time.
170 # Name of signal saved by catch_signal
177 my($RunNightlyWhenIdle, $FirstWakeup, $CmdJob, $ServerInetPort);
178 my($BackupPCNightlyJobs, $BackupPCNightlyLock);
181 # Complete the rest of the initialization
185 ###########################################################################
187 ###########################################################################
191 # Check if we can/should run BackupPC_nightly
193 Main_TryToRun_nightly();
196 # Check if we can run a new command from @CmdQueue.
198 Main_TryToRun_CmdQueue();
201 # Check if we can run a new command from @UserQueue or @BgQueue.
203 Main_TryToRun_Bg_or_User_Queue();
206 # Do a select() to wait for the next interesting thing to happen
207 # (timeout, signal, someone sends a message, child dies etc).
209 my $fdRead = Main_Select();
212 # Process a signal if we received one.
215 Main_Process_Signal();
220 # Check if a timeout has occurred.
222 Main_Check_Timeout();
225 # Check for, and process, any messages (output) from our jobs
227 Main_Check_Job_Messages($fdRead);
230 # Check for, and process, any output from our clients. Also checks
231 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
233 Main_Check_Client_Messages($fdRead);
236 ############################################################################
239 # Main initialization routine. Called once at statup.
240 ############################################################################
243 umask($Conf{UmaskMode});
246 # Check for another running process, check that PASSWD is set and
247 # verify executables are configured correctly.
249 if ( $Info{pid} ne "" && kill(0, $Info{pid}) ) {
250 print(STDERR $bpc->timeStamp,
251 "Another BackupPC is running (pid $Info{pid}); quitting...\n");
254 foreach my $progName ( qw(SmbClientPath NmbLookupPath PingPath DfPath
255 SendmailPath SshPath) ) {
256 next if ( $Conf{$progName} eq "" || -x $Conf{$progName} );
257 print(STDERR $bpc->timeStamp,
258 "\$Conf{$progName} = '$Conf{$progName}' is not a"
259 . " valid executable program\n");
265 # daemonize by forking; more robust method per:
266 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=301057
269 defined($pid = fork) or die("Can't fork: $!");
270 exit if( $pid ); # parent exits
273 defined($pid = fork) or die("Can't fork: $!");
274 exit if $pid; # parent exits
276 chdir ("/") or die("Cannot chdir to /: $!\n");
278 open(STDIN , ">/dev/null") or die("Cannot open /dev/null as stdin\n");
279 # STDOUT and STDERR are handled in LogFileOpen() right below,
280 # otherwise we would have to reopen them too.
284 # Open the LOG file and redirect STDOUT, STDERR etc
289 # Read the hosts file (force a read).
291 exit(1) if ( !HostsUpdate(1) );
294 # Clean up %ENV for taint checking
296 delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
297 $ENV{PATH} = $Conf{MyPath};
300 # Initialize server sockets
305 # Catch various signals
307 foreach my $sig ( qw(INT BUS SEGV PIPE TERM ALRM HUP) ) {
308 $SIG{$sig} = \&catch_signal;
312 # Report that we started, and update %Info.
314 print(LOG $bpc->timeStamp, "BackupPC started, pid $$\n");
315 $Info{ConfigModTime} = $bpc->ConfigMTime();
317 $Info{startTime} = time;
318 $Info{ConfigLTime} = time;
319 $Info{Version} = $bpc->{Version};
322 # Update the status left over form the last time BackupPC ran.
323 # Requeue any pending links.
325 foreach my $host ( sort(keys(%$Hosts)) ) {
326 if ( $Status{$host}{state} eq "Status_backup_in_progress" ) {
328 # should we restart it? skip it for now.
330 $Status{$host}{state} = "Status_idle";
331 } elsif ( $Status{$host}{state} eq "Status_link_pending"
332 || $Status{$host}{state} eq "Status_link_running" ) {
335 $Status{$host}{state} = "Status_idle";
337 $Status{$host}{activeJob} = 0;
339 foreach my $host ( sort(keys(%Status)) ) {
340 next if ( defined($Hosts->{$host}) );
341 delete($Status{$host});
345 # Write out our initial status and save our PID
348 unlink("$LogDir/BackupPC.pid");
349 if ( open(PID, ">", "$LogDir/BackupPC.pid") ) {
352 chmod(0444, "$LogDir/BackupPC.pid");
356 # For unknown reasons there is a very infrequent error about not
357 # being able to coerce GLOBs inside the XS Data::Dumper. I've
358 # only seen this on a particular platform and perl version.
359 # For now the workaround appears to be use the perl version of
362 $Data::Dumper::Useqq = 1;
365 ############################################################################
366 # Main_TryToRun_nightly()
368 # Checks to see if we can/should run BackupPC_nightly or
369 # BackupPC_trashClean. If so we push the appropriate command onto
371 ############################################################################
372 sub Main_TryToRun_nightly
375 # Check if we should run BackupPC_nightly or BackupPC_trashClean.
376 # BackupPC_nightly is run when the current job queue is empty.
377 # BackupPC_trashClean is run in the background always.
379 my $trashCleanRunning = defined($Jobs{$bpc->trashJob}) ? 1 : 0;
380 if ( !$trashCleanRunning && !$CmdQueueOn{$bpc->trashJob} ) {
382 # This should only happen once at startup, but just in case this
383 # code will re-start BackupPC_trashClean if it quits
386 host => $bpc->trashJob,
389 cmd => ["$BinDir/BackupPC_trashClean"],
391 $CmdQueueOn{$bpc->trashJob} = 1;
393 if ( $RunNightlyWhenIdle == 1 ) {
396 # Queue multiple nightly jobs based on the configuration
398 $Conf{MaxBackupPCNightlyJobs} = 1
399 if ( $Conf{MaxBackupPCNightlyJobs} <= 0 );
400 $Conf{BackupPCNightlyPeriod} = 1
401 if ( $Conf{BackupPCNightlyPeriod} <= 0 );
403 # Decide what subset of the 16 top-level directories 0..9a..f
404 # we run BackupPC_nightly on, based on $Conf{BackupPCNightlyPeriod}.
405 # If $Conf{BackupPCNightlyPeriod} == 1 then we run 0..15 every
406 # time. If $Conf{BackupPCNightlyPeriod} == 2 then we run
407 # 0..7 one night and 89a-f the next night. And so on.
409 # $Info{NightlyPhase} counts which night, from 0 to
410 # $Conf{BackupPCNightlyPeriod} - 1.
412 my $start = int($Info{NightlyPhase} * 16
413 / $Conf{BackupPCNightlyPeriod});
414 my $end = int(($Info{NightlyPhase} + 1) * 16
415 / $Conf{BackupPCNightlyPeriod});
416 $end = $start + 1 if ( $end <= $start );
417 $Info{NightlyPhase}++;
418 $Info{NightlyPhase} = 0 if ( $end >= 16 );
421 # Zero out the data we expect to get from BackupPC_nightly.
423 for my $p ( qw(pool cpool) ) {
424 for ( my $i = $start ; $i < $end ; $i++ ) {
425 $Info{pool}{$p}[$i]{FileCnt} = 0;
426 $Info{pool}{$p}[$i]{DirCnt} = 0;
427 $Info{pool}{$p}[$i]{Kb} = 0;
428 $Info{pool}{$p}[$i]{Kb2} = 0;
429 $Info{pool}{$p}[$i]{KbRm} = 0;
430 $Info{pool}{$p}[$i]{FileCntRm} = 0;
431 $Info{pool}{$p}[$i]{FileCntRep} = 0;
432 $Info{pool}{$p}[$i]{FileRepMax} = 0;
433 $Info{pool}{$p}[$i]{FileCntRename} = 0;
434 $Info{pool}{$p}[$i]{FileLinkMax} = 0;
435 $Info{pool}{$p}[$i]{Time} = 0;
438 print(LOG $bpc->timeStamp,
439 sprintf("Running %d BackupPC_nightly jobs from %d..%d"
440 . " (out of 0..15)\n",
441 $Conf{MaxBackupPCNightlyJobs}, $start, $end - 1));
444 # Now queue the $Conf{MaxBackupPCNightlyJobs} jobs.
445 # The granularity on start and end is now 0..255.
450 for ( my $i = 0 ; $i < $Conf{MaxBackupPCNightlyJobs} ; $i++ ) {
452 # The first nightly job gets the -m option (does email, log aging).
453 # All jobs get the start and end options from 0..255 telling
454 # them which parts of the pool to traverse.
456 my $cmd = ["$BinDir/BackupPC_nightly"];
457 push(@$cmd, "-m") if ( $i == 0 );
459 $start = $start0 + int(($end - $start0)
460 * ($i + 1) / $Conf{MaxBackupPCNightlyJobs});
461 push(@$cmd, $start - 1);
463 my $job = $bpc->adminJob($i);
470 $CmdQueueOn{$job} = 1;
472 $RunNightlyWhenIdle = 2;
476 ############################################################################
477 # Main_TryToRun_CmdQueue()
479 # Decide if we can run a new command from the @CmdQueue.
480 # We only run one of these at a time. The @CmdQueue is
481 # used to run BackupPC_link (for the corresponding host),
482 # BackupPC_trashClean, and BackupPC_nightly using a fake
483 # host name of $bpc->adminJob.
484 ############################################################################
485 sub Main_TryToRun_CmdQueue
489 while ( $CmdJob eq "" && @CmdQueue > 0 && $RunNightlyWhenIdle != 1
490 || @CmdQueue > 0 && $RunNightlyWhenIdle == 2
491 && $bpc->isAdminJob($CmdQueue[0]->{host})
494 $req = pop(@CmdQueue);
496 $host = $req->{host};
497 if ( defined($Jobs{$host}) ) {
498 print(LOG $bpc->timeStamp,
499 "Botch on admin job for $host: already in use!!\n");
501 # This could happen during normal opertion: a user could
502 # request a backup while a BackupPC_link is queued from
503 # a previous backup. But it is unlikely. Just put this
504 # request back on the end of the queue.
506 unshift(@CmdQueue, $req);
509 $CmdQueueOn{$host} = 0;
510 my $cmd = $req->{cmd};
511 my $pid = open(FH, "-|");
512 if ( !defined($pid) ) {
513 print(LOG $bpc->timeStamp,
514 "can't fork for $host, request by $req->{user}\n");
521 print(LOG $bpc->timeStamp, "can't exec @$cmd for $host\n");
524 $Jobs{$host}{pid} = $pid;
525 $Jobs{$host}{fh} = *FH;
526 $Jobs{$host}{fn} = fileno(FH);
527 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
528 $Jobs{$host}{startTime} = time;
529 $Jobs{$host}{reqTime} = $req->{reqTime};
530 $cmd = $bpc->execCmd2ShellCmd(@$cmd);
531 $Jobs{$host}{cmd} = $cmd;
532 $Jobs{$host}{user} = $req->{user};
533 $Jobs{$host}{type} = $Status{$host}{type};
534 $Status{$host}{state} = "Status_link_running";
535 $Status{$host}{activeJob} = 1;
536 $Status{$host}{endTime} = time;
537 $CmdJob = $host if ( $host ne $bpc->trashJob );
538 $cmd =~ s/$BinDir\///g;
539 print(LOG $bpc->timeStamp, "Running $cmd (pid=$pid)\n");
540 if ( $cmd =~ /^BackupPC_nightly\s/ ) {
541 $BackupPCNightlyJobs++;
542 $BackupPCNightlyLock++;
547 ############################################################################
548 # Main_TryToRun_Bg_or_User_Queue()
550 # Decide if we can run any new backup requests from @BgQueue
551 # or @UserQueue. Several of these can be run at the same time
552 # based on %Conf settings. Jobs from @UserQueue take priority,
553 # and at total of $Conf{MaxBackups} + $Conf{MaxUserBackups}
554 # simultaneous jobs can run from @UserQueue. After @UserQueue
555 # is exhausted, up to $Conf{MaxBackups} simultaneous jobs can
557 ############################################################################
558 sub Main_TryToRun_Bg_or_User_Queue
561 my(@deferUserQueue, @deferBgQueue);
564 if ( time - $Info{DUlastValueTime} >= 600 ) {
566 # Update our notion of disk usage no more than
567 # once every 10 minutes
569 $du = $bpc->CheckFileSystemUsage($TopDir);
570 $Info{DUlastValue} = $du;
571 $Info{DUlastValueTime} = time;
574 # if we recently checked it then just use the old value
576 $du = $Info{DUlastValue};
578 if ( $Info{DUDailyMaxReset} ) {
579 $Info{DUDailyMaxStartTime} = time;
580 $Info{DUDailyMaxReset} = 0;
581 $Info{DUDailyMax} = 0;
583 if ( $du > $Info{DUDailyMax} ) {
584 $Info{DUDailyMax} = $du;
585 $Info{DUDailyMaxTime} = time;
587 if ( $du > $Conf{DfMaxUsagePct} ) {
588 my @bgQueue = @BgQueue;
592 # When the disk is too full, only run backups that will
593 # do expires, not regular backups
596 foreach $req ( @bgQueue ) {
597 if ( $req->{dumpExpire} ) {
598 unshift(@BgQueue, $req);
600 $BgQueueOn{$req->{host}} = 0;
605 print(LOG $bpc->timeStamp,
606 "Disk too full ($du%); skipped $nSkip hosts\n");
607 $Info{DUDailySkipHostCnt} += $nSkip;
612 # Run background jobs anytime. Previously they were locked out
613 # when BackupPC_nightly was running or pending with this
614 # condition on the while loop:
616 # while ( $RunNightlyWhenIdle == 0 )
620 my(@args, $progName, $type);
621 my $nJobs = keys(%Jobs);
623 # CmdJob and trashClean don't count towards MaxBackups / MaxUserBackups
625 if ( $CmdJob ne "" ) {
626 if ( $BackupPCNightlyJobs ) {
627 $nJobs -= $BackupPCNightlyJobs;
632 $nJobs-- if ( defined($Jobs{$bpc->trashJob} ) );
633 if ( $nJobs < $Conf{MaxBackups} + $Conf{MaxUserBackups}
634 && @UserQueue > 0 ) {
635 $req = pop(@UserQueue);
636 if ( defined($Jobs{$req->{host}}) ) {
637 push(@deferUserQueue, $req);
640 push(@args, $req->{doFull} ? "-f" : "-i")
641 if (( !$req->{restore} ) && ( !$req->{archive} ));
642 $UserQueueOn{$req->{host}} = 0;
643 } elsif ( $nJobs < $Conf{MaxBackups}
644 && (@CmdQueue + $nJobs)
645 <= $Conf{MaxBackups} + $Conf{MaxPendingCmds}
647 $req = pop(@BgQueue);
648 if ( defined($Jobs{$req->{host}}) ) {
650 # Job is currently running for this host; save it for later
652 unshift(@deferBgQueue, $req);
655 $BgQueueOn{$req->{host}} = 0;
658 # Restore the deferred jobs
660 @BgQueue = (@BgQueue, @deferBgQueue);
661 @UserQueue = (@UserQueue, @deferUserQueue);
664 $host = $req->{host};
665 my $user = $req->{user};
666 if ( $req->{restore} ) {
667 $progName = "BackupPC_restore";
669 push(@args, $req->{hostIP}, $req->{host}, $req->{reqFileName});
670 } elsif ( $req->{archive} ) {
671 $progName = "BackupPC_archive";
673 push(@args, $req->{user}, $req->{host}, $req->{reqFileName});
675 $progName = "BackupPC_dump";
677 push(@args, "-d") if ( $req->{dhcp} );
678 push(@args, "-e") if ( $req->{dumpExpire} );
681 my $pid = open(FH, "-|");
682 if ( !defined($pid) ) {
683 print(LOG $bpc->timeStamp,
684 "can't fork to run $progName for $host, request by $user\n");
690 exec("$BinDir/$progName", @args);
691 print(LOG $bpc->timeStamp, "can't exec $progName for $host\n");
694 $Jobs{$host}{pid} = $pid;
695 $Jobs{$host}{fh} = *FH;
696 $Jobs{$host}{fn} = fileno(FH);
697 $Jobs{$host}{dhcp} = $req->{dhcp};
698 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
699 $Jobs{$host}{startTime} = time;
700 $Jobs{$host}{reqTime} = $req->{reqTime};
701 $Jobs{$host}{userReq} = $req->{userReq};
702 $Jobs{$host}{cmd} = $bpc->execCmd2ShellCmd($progName, @args);
703 $Jobs{$host}{user} = $user;
704 $Jobs{$host}{type} = $type;
705 $Status{$host}{userReq} = $req->{userReq}
706 if ( defined($Hosts->{$host}) );
707 if ( !$req->{dhcp} ) {
708 $Status{$host}{state} = "Status_".$type."_starting";
709 $Status{$host}{activeJob} = 1;
710 $Status{$host}{startTime} = time;
711 $Status{$host}{endTime} = "";
716 ############################################################################
719 # If necessary, figure out when to next wakeup based on $Conf{WakeupSchedule},
720 # and then do a select() to wait for the next thing to happen
721 # (timeout, signal, someone sends a message, child dies etc).
722 ############################################################################
725 if ( $NextWakeup <= 0 ) {
727 # Figure out when to next wakeup based on $Conf{WakeupSchedule}.
729 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
731 my($currHours) = $hour + $min / 60 + $sec / 3600;
732 if ( $bpc->ConfigMTime() != $Info{ConfigModTime} ) {
733 ServerReload("Re-read config file because mtime changed");
736 foreach my $t ( @{$Conf{WakeupSchedule} || [0..23]} ) {
737 next if ( $t < 0 || $t > 24 );
738 my $tomorrow = $t + 24;
740 || ($tomorrow - $currHours > 0
741 && $delta > $tomorrow - $currHours) ) {
742 $delta = $tomorrow - $currHours;
743 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
746 || ($t - $currHours > 0 && $delta > $t - $currHours) ) {
747 $delta = $t - $currHours;
748 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
751 $NextWakeup = time + $delta * 3600;
752 $Info{nextWakeup} = $NextWakeup;
753 print(LOG $bpc->timeStamp, "Next wakeup is ",
754 $bpc->timeStamp($NextWakeup, 1), "\n");
757 # Call select(), waiting until either a signal, a timeout,
758 # any output from our jobs, or any messages from clients
760 # select() is where we (hopefully) spend most of our time blocked...
762 my $timeout = $NextWakeup - time;
763 $timeout = 1 if ( $timeout <= 0 );
765 select(my $rout = $FDread, undef, $ein, $timeout);
770 ############################################################################
771 # Main_Process_Signal()
774 ############################################################################
775 sub Main_Process_Signal
780 if ( $SigName eq "HUP" ) {
781 ServerReload("Re-read config file because of a SIG_HUP");
782 } elsif ( $SigName ) {
783 ServerShutdown("Got signal $SigName... cleaning up");
788 ############################################################################
789 # Main_Check_Timeout()
791 # Check if a timeout has occured, and if so, queue all the PCs for backups.
792 # Also does log file aging on the first timeout after midnight.
793 ############################################################################
794 sub Main_Check_Timeout
799 return if ( time < $NextWakeup || $NextWakeup <= 0 );
801 if ( $FirstWakeup ) {
803 # This is the first wakeup after midnight. Do log file aging
804 # and various house keeping.
807 printf(LOG "%s24hr disk usage: %d%% max, %d%% recent,"
808 . " %d skipped hosts\n",
809 $bpc->timeStamp, $Info{DUDailyMax}, $Info{DUlastValue},
810 $Info{DUDailySkipHostCnt});
811 $Info{DUDailyMaxReset} = 1;
812 $Info{DUDailyMaxPrev} = $Info{DUDailyMax};
813 $Info{DUDailySkipHostCntPrev} = $Info{DUDailySkipHostCnt};
814 $Info{DUDailySkipHostCnt} = 0;
815 my $lastLog = $Conf{MaxOldLogFiles} - 1;
816 if ( -f "$LogDir/LOG.$lastLog" ) {
817 print(LOG $bpc->timeStamp,
818 "Removing $LogDir/LOG.$lastLog\n");
819 unlink("$LogDir/LOG.$lastLog");
821 if ( -f "$LogDir/LOG.$lastLog.z" ) {
822 print(LOG $bpc->timeStamp,
823 "Removing $LogDir/LOG.$lastLog.z\n");
824 unlink("$LogDir/LOG.$lastLog.z");
826 print(LOG $bpc->timeStamp, "Aging LOG files, LOG -> LOG.0 -> "
827 . "LOG.1 -> ... -> LOG.$lastLog\n");
828 close(STDERR); # dup of LOG
829 close(STDOUT); # dup of LOG
831 for ( my $i = $lastLog - 1 ; $i >= 0 ; $i-- ) {
833 rename("$LogDir/LOG.$i", "$LogDir/LOG.$j")
834 if ( -f "$LogDir/LOG.$i" );
835 rename("$LogDir/LOG.$i.z", "$LogDir/LOG.$j.z")
836 if ( -f "$LogDir/LOG.$i.z" );
839 # Compress the log file LOG -> LOG.0.z (if enabled).
840 # Otherwise, just rename LOG -> LOG.0.
842 BackupPC::FileZIO->compressCopy("$LogDir/LOG",
845 $Conf{CompressLevel}, 1);
848 # Remember to run the nightly script when the next CmdQueue
851 $RunNightlyWhenIdle = 1;
854 # Write out the current status and then queue all the PCs
858 %BgQueueOn = () if ( @BgQueue == 0 );
859 %UserQueueOn = () if ( @UserQueue == 0 );
860 %CmdQueueOn = () if ( @CmdQueue == 0 );
864 ############################################################################
865 # Main_Check_Job_Messages($fdRead)
867 # Check if select() says we have bytes waiting from any of our jobs.
868 # Handle each of the messages when complete (newline terminated).
869 ############################################################################
870 sub Main_Check_Job_Messages
873 foreach my $host ( keys(%Jobs) ) {
874 next if ( !vec($fdRead, $Jobs{$host}{fn}, 1) );
877 # do a last check to make sure there is something to read so
878 # we are absolutely sure we won't block.
880 vec(my $readMask, $Jobs{$host}{fn}, 1) = 1;
881 if ( !select($readMask, undef, undef, 0.0) ) {
882 print(LOG $bpc->timeStamp, "Botch in Main_Check_Job_Messages:"
883 . " nothing to read from $host. Debug dump:\n");
884 my($dump) = Data::Dumper->new(
885 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
886 [qw(*Clients, *Jobs *FDread, *fdRead)]);
888 print(LOG $dump->Dump);
891 my $nbytes = sysread($Jobs{$host}{fh}, $mesg, 1024);
892 $Jobs{$host}{mesg} .= $mesg if ( $nbytes > 0 );
894 # Process any complete lines of output from this jobs.
895 # Any output to STDOUT or STDERR from the children is processed here.
897 while ( $Jobs{$host}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
899 $Jobs{$host}{mesg} = $2;
900 if ( $Jobs{$host}{dhcp} ) {
901 if ( $mesg =~ /^DHCP (\S+) (\S+)/ ) {
902 my $newHost = $bpc->uriUnesc($2);
903 if ( defined($Jobs{$newHost}) ) {
904 print(LOG $bpc->timeStamp,
905 "Backup on $newHost is already running\n");
906 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
910 $Jobs{$host}{dhcpHostIP} = $host;
911 $Status{$newHost}{dhcpHostIP} = $host;
912 $Jobs{$newHost} = $Jobs{$host};
913 delete($Jobs{$host});
915 $Status{$host}{state} = "Status_backup_starting";
916 $Status{$host}{activeJob} = 1;
917 $Status{$host}{startTime} = $Jobs{$host}{startTime};
918 $Status{$host}{endTime} = "";
919 $Jobs{$host}{dhcp} = 0;
921 print(LOG $bpc->timeStamp, "dhcp $host: $mesg\n");
923 } elsif ( $mesg =~ /^started (.*) dump, share=(.*)/ ) {
924 $Jobs{$host}{type} = $1;
925 $Jobs{$host}{shareName} = $2;
926 print(LOG $bpc->timeStamp,
927 "Started $1 backup on $host (pid=$Jobs{$host}{pid}",
928 $Jobs{$host}{dhcpHostIP}
929 ? ", dhcp=$Jobs{$host}{dhcpHostIP}" : "",
930 ", share=$Jobs{$host}{shareName})\n");
931 $Status{$host}{state} = "Status_backup_in_progress";
932 $Status{$host}{reason} = "";
933 $Status{$host}{type} = $1;
934 $Status{$host}{startTime} = time;
935 $Status{$host}{deadCnt} = 0;
936 $Status{$host}{aliveCnt}++;
937 $Status{$host}{dhcpCheckCnt}--
938 if ( $Status{$host}{dhcpCheckCnt} > 0 );
939 } elsif ( $mesg =~ /^xferPids (.*)/ ) {
940 $Jobs{$host}{xferPid} = $1;
941 } elsif ( $mesg =~ /^started_restore/ ) {
942 $Jobs{$host}{type} = "restore";
943 print(LOG $bpc->timeStamp,
944 "Started restore on $host"
945 . " (pid=$Jobs{$host}{pid})\n");
946 $Status{$host}{state} = "Status_restore_in_progress";
947 $Status{$host}{reason} = "";
948 $Status{$host}{type} = "restore";
949 $Status{$host}{startTime} = time;
950 $Status{$host}{deadCnt} = 0;
951 $Status{$host}{aliveCnt}++;
952 } elsif ( $mesg =~ /^started_archive/ ) {
953 $Jobs{$host}{type} = "archive";
954 print(LOG $bpc->timeStamp,
955 "Started archive on $host"
956 . " (pid=$Jobs{$host}{pid})\n");
957 $Status{$host}{state} = "Status_archive_in_progress";
958 $Status{$host}{reason} = "";
959 $Status{$host}{type} = "archive";
960 $Status{$host}{startTime} = time;
961 $Status{$host}{deadCnt} = 0;
962 $Status{$host}{aliveCnt}++;
963 } elsif ( $mesg =~ /^(full|incr) backup complete/ ) {
964 print(LOG $bpc->timeStamp, "Finished $1 backup on $host\n");
965 $Status{$host}{reason} = "Reason_backup_done";
966 delete($Status{$host}{error});
967 delete($Status{$host}{errorTime});
968 $Status{$host}{endTime} = time;
969 $Status{$host}{lastGoodBackupTime} = time;
970 } elsif ( $mesg =~ /^backups disabled/ ) {
971 print(LOG $bpc->timeStamp,
972 "Ignoring old backup error on $host\n");
973 $Status{$host}{reason} = "Reason_backup_done";
974 delete($Status{$host}{error});
975 delete($Status{$host}{errorTime});
976 $Status{$host}{endTime} = time;
977 } elsif ( $mesg =~ /^restore complete/ ) {
978 print(LOG $bpc->timeStamp, "Finished restore on $host\n");
979 $Status{$host}{reason} = "Reason_restore_done";
980 delete($Status{$host}{error});
981 delete($Status{$host}{errorTime});
982 $Status{$host}{endTime} = time;
983 } elsif ( $mesg =~ /^archive complete/ ) {
984 print(LOG $bpc->timeStamp, "Finished archive on $host\n");
985 $Status{$host}{reason} = "Reason_archive_done";
986 delete($Status{$host}{error});
987 delete($Status{$host}{errorTime});
988 $Status{$host}{endTime} = time;
989 } elsif ( $mesg =~ /^nothing to do/ ) {
990 if ( $Status{$host}{reason} ne "Reason_backup_failed"
991 && $Status{$host}{reason} ne "Reason_restore_failed" ) {
992 $Status{$host}{state} = "Status_idle";
993 $Status{$host}{reason} = "Reason_nothing_to_do";
994 $Status{$host}{startTime} = time;
996 $Status{$host}{dhcpCheckCnt}--
997 if ( $Status{$host}{dhcpCheckCnt} > 0 );
998 } elsif ( $mesg =~ /^no ping response/
999 || $mesg =~ /^ping too slow/
1000 || $mesg =~ /^host not found/ ) {
1001 $Status{$host}{state} = "Status_idle";
1002 if ( $Status{$host}{userReq}
1003 || $Status{$host}{reason} ne "Reason_backup_failed"
1004 || $Status{$host}{error} =~ /^aborted by user/ ) {
1005 $Status{$host}{reason} = "Reason_no_ping";
1006 $Status{$host}{error} = $mesg;
1007 $Status{$host}{startTime} = time;
1009 $Status{$host}{deadCnt}++;
1010 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1011 $Status{$host}{aliveCnt} = 0;
1013 } elsif ( $mesg =~ /^dump failed: (.*)/ ) {
1014 $Status{$host}{state} = "Status_idle";
1015 $Status{$host}{error} = $1;
1016 $Status{$host}{errorTime} = time;
1017 $Status{$host}{endTime} = time;
1018 if ( $Status{$host}{reason}
1019 eq "Reason_backup_canceled_by_user" ) {
1020 print(LOG $bpc->timeStamp,
1021 "Backup canceled on $host ($1)\n");
1023 $Status{$host}{reason} = "Reason_backup_failed";
1024 print(LOG $bpc->timeStamp,
1025 "Backup failed on $host ($1)\n");
1027 } elsif ( $mesg =~ /^restore failed: (.*)/ ) {
1028 $Status{$host}{state} = "Status_idle";
1029 $Status{$host}{error} = $1;
1030 $Status{$host}{errorTime} = time;
1031 $Status{$host}{endTime} = time;
1032 if ( $Status{$host}{reason}
1033 eq "Reason_restore_canceled_by_user" ) {
1034 print(LOG $bpc->timeStamp,
1035 "Restore canceled on $host ($1)\n");
1037 $Status{$host}{reason} = "Reason_restore_failed";
1038 print(LOG $bpc->timeStamp,
1039 "Restore failed on $host ($1)\n");
1041 } elsif ( $mesg =~ /^archive failed: (.*)/ ) {
1042 $Status{$host}{state} = "Status_idle";
1043 $Status{$host}{error} = $1;
1044 $Status{$host}{errorTime} = time;
1045 $Status{$host}{endTime} = time;
1046 if ( $Status{$host}{reason}
1047 eq "Reason_archive_canceled_by_user" ) {
1048 print(LOG $bpc->timeStamp,
1049 "Archive canceled on $host ($1)\n");
1051 $Status{$host}{reason} = "Reason_archive_failed";
1052 print(LOG $bpc->timeStamp,
1053 "Archive failed on $host ($1)\n");
1055 } elsif ( $mesg =~ /^log\s+(.*)/ ) {
1056 print(LOG $bpc->timeStamp, "$1\n");
1057 } elsif ( $mesg =~ /^BackupPC_stats (\d+) = (.*)/ ) {
1058 my $chunk = int($1 / 16);
1059 my @f = split(/,/, $2);
1060 $Info{pool}{$f[0]}[$chunk]{FileCnt} += $f[1];
1061 $Info{pool}{$f[0]}[$chunk]{DirCnt} += $f[2];
1062 $Info{pool}{$f[0]}[$chunk]{Kb} += $f[3];
1063 $Info{pool}{$f[0]}[$chunk]{Kb2} += $f[4];
1064 $Info{pool}{$f[0]}[$chunk]{KbRm} += $f[5];
1065 $Info{pool}{$f[0]}[$chunk]{FileCntRm} += $f[6];
1066 $Info{pool}{$f[0]}[$chunk]{FileCntRep} += $f[7];
1067 $Info{pool}{$f[0]}[$chunk]{FileRepMax} = $f[8]
1068 if ( $Info{pool}{$f[0]}[$chunk]{FileRepMax} < $f[8] );
1069 $Info{pool}{$f[0]}[$chunk]{FileCntRename} += $f[9];
1070 $Info{pool}{$f[0]}[$chunk]{FileLinkMax} = $f[10]
1071 if ( $Info{pool}{$f[0]}[$chunk]{FileLinkMax} < $f[10] );
1072 $Info{pool}{$f[0]}[$chunk]{FileLinkTotal} += $f[11];
1073 $Info{pool}{$f[0]}[$chunk]{Time} = time;
1074 } elsif ( $mesg =~ /^BackupPC_nightly lock_off/ ) {
1075 $BackupPCNightlyLock--;
1076 if ( $BackupPCNightlyLock == 0 ) {
1078 # This means the last BackupPC_nightly is done with
1079 # the pool clean, so it's ok to start running regular
1080 # backups again. But starting in 3.0 regular jobs
1081 # are decoupled from BackupPC_nightly.
1083 $RunNightlyWhenIdle = 0;
1085 } elsif ( $mesg =~ /^processState\s+(.+)/ ) {
1086 $Jobs{$host}{processState} = $1;
1087 } elsif ( $mesg =~ /^link\s+(.+)/ ) {
1089 $Status{$h}{needLink} = 1;
1091 print(LOG $bpc->timeStamp, "$host: $mesg\n");
1095 # shut down the client connection if we read EOF
1097 if ( $nbytes <= 0 ) {
1098 close($Jobs{$host}{fh});
1099 vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1100 if ( $CmdJob eq $host || $bpc->isAdminJob($host) ) {
1101 my $cmd = $Jobs{$host}{cmd};
1102 $cmd =~ s/$BinDir\///g;
1103 print(LOG $bpc->timeStamp, "Finished $host ($cmd)\n");
1104 $Status{$host}{state} = "Status_idle";
1105 $Status{$host}{endTime} = time;
1106 if ( $cmd =~ /^BackupPC_nightly\s/ ) {
1107 $BackupPCNightlyJobs--;
1108 #print(LOG $bpc->timeStamp, "BackupPC_nightly done; now"
1109 # . " have $BackupPCNightlyJobs running\n");
1110 if ( $BackupPCNightlyJobs <= 0 ) {
1112 # Last BackupPC_nightly has finished
1114 $BackupPCNightlyJobs = 0;
1115 $RunNightlyWhenIdle = 0;
1118 # Combine the 16 per-directory results
1120 for my $p ( qw(pool cpool) ) {
1121 $Info{"${p}FileCnt"} = 0;
1122 $Info{"${p}DirCnt"} = 0;
1123 $Info{"${p}Kb"} = 0;
1124 $Info{"${p}Kb2"} = 0;
1125 $Info{"${p}KbRm"} = 0;
1126 $Info{"${p}FileCntRm"} = 0;
1127 $Info{"${p}FileCntRep"} = 0;
1128 $Info{"${p}FileRepMax"} = 0;
1129 $Info{"${p}FileCntRename"} = 0;
1130 $Info{"${p}FileLinkMax"} = 0;
1131 $Info{"${p}Time"} = 0;
1132 for ( my $i = 0 ; $i < 16 ; $i++ ) {
1133 $Info{"${p}FileCnt"}
1134 += $Info{pool}{$p}[$i]{FileCnt};
1136 += $Info{pool}{$p}[$i]{DirCnt};
1138 += $Info{pool}{$p}[$i]{Kb};
1140 += $Info{pool}{$p}[$i]{Kb2};
1142 += $Info{pool}{$p}[$i]{KbRm};
1143 $Info{"${p}FileCntRm"}
1144 += $Info{pool}{$p}[$i]{FileCntRm};
1145 $Info{"${p}FileCntRep"}
1146 += $Info{pool}{$p}[$i]{FileCntRep};
1147 $Info{"${p}FileRepMax"}
1148 = $Info{pool}{$p}[$i]{FileRepMax}
1149 if ( $Info{"${p}FileRepMax"} <
1150 $Info{pool}{$p}[$i]{FileRepMax} );
1151 $Info{"${p}FileCntRename"}
1152 += $Info{pool}{$p}[$i]{FileCntRename};
1153 $Info{"${p}FileLinkMax"}
1154 = $Info{pool}{$p}[$i]{FileLinkMax}
1155 if ( $Info{"${p}FileLinkMax"} <
1156 $Info{pool}{$p}[$i]{FileLinkMax} );
1157 $Info{"${p}Time"} = $Info{pool}{$p}[$i]{Time}
1158 if ( $Info{"${p}Time"} <
1159 $Info{pool}{$p}[$i]{Time} );
1161 printf(LOG "%s%s nightly clean removed %d files of"
1163 $bpc->timeStamp, ucfirst($p),
1164 $Info{"${p}FileCntRm"},
1165 $Info{"${p}KbRm"} / (1000 * 1024));
1166 printf(LOG "%s%s is %.2fGB, %d files (%d repeated, "
1167 . "%d max chain, %d max links), %d directories\n",
1168 $bpc->timeStamp, ucfirst($p),
1169 $Info{"${p}Kb"} / (1000 * 1024),
1170 $Info{"${p}FileCnt"}, $Info{"${p}FileCntRep"},
1171 $Info{"${p}FileRepMax"},
1172 $Info{"${p}FileLinkMax"}, $Info{"${p}DirCnt"});
1180 # Queue BackupPC_link to complete the backup
1181 # processing for this host.
1183 if ( defined($Status{$host})
1184 && ($Status{$host}{reason} eq "Reason_backup_done"
1185 || $Status{$host}{needLink}) ) {
1187 } elsif ( defined($Status{$host}) ) {
1188 $Status{$host}{state} = "Status_idle";
1191 delete($Jobs{$host});
1192 $Status{$host}{activeJob} = 0 if ( defined($Status{$host}) );
1196 # When we are idle (empty Jobs, CmdQueue, BgQueue, UserQueue) we
1197 # do a pass over %Status updating the deadCnt and aliveCnt for
1198 # DHCP hosts. The reason we need to do this later is we can't
1199 # be sure whether a DHCP host is alive or dead until we have passed
1200 # over all the DHCP pool.
1202 return if ( @CmdQueue || @BgQueue || @UserQueue || keys(%Jobs) > 1 );
1203 foreach my $host ( keys(%Status) ) {
1204 next if ( $Status{$host}{dhcpCheckCnt} <= 0 );
1205 $Status{$host}{deadCnt} += $Status{$host}{dhcpCheckCnt};
1206 $Status{$host}{dhcpCheckCnt} = 0;
1207 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1208 $Status{$host}{aliveCnt} = 0;
1213 ############################################################################
1214 # Main_Check_Client_Messages($fdRead)
1216 # Check for, and process, any output from our clients. Also checks
1217 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
1218 ############################################################################
1219 sub Main_Check_Client_Messages
1222 foreach my $client ( keys(%Clients) ) {
1223 next if ( !vec($fdRead, $Clients{$client}{fn}, 1) );
1226 # do a last check to make sure there is something to read so
1227 # we are absolutely sure we won't block.
1229 vec(my $readMask, $Clients{$client}{fn}, 1) = 1;
1230 if ( !select($readMask, undef, undef, 0.0) ) {
1231 print(LOG $bpc->timeStamp, "Botch in Main_Check_Client_Messages:"
1232 . " nothing to read from $client. Debug dump:\n");
1233 my($dump) = Data::Dumper->new(
1234 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
1235 [qw(*Clients, *Jobs *FDread, *fdRead)]);
1237 print(LOG $dump->Dump);
1240 my $nbytes = sysread($Clients{$client}{fh}, $mesg, 1024);
1241 $Clients{$client}{mesg} .= $mesg if ( $nbytes > 0 );
1243 # Process any complete lines received from this client.
1245 while ( $Clients{$client}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
1248 $Clients{$client}{mesg} = $2;
1250 # Authenticate the message by checking the MD5 digest
1252 my $md5 = Digest::MD5->new;
1253 if ( $cmd !~ /^(.{22}) (.*)/
1254 || ($md5->add($Clients{$client}{seed}
1255 . $Clients{$client}{mesgCnt}
1256 . $Conf{ServerMesgSecret} . $2),
1257 $md5->b64digest ne $1) ) {
1258 print(LOG $bpc->timeStamp, "Corrupted message '$cmd' from"
1259 . " client '$Clients{$client}{clientName}':"
1260 . " shutting down client connection\n");
1264 $Clients{$client}{mesgCnt}++;
1266 if ( $cmd =~ /^stop (\S+)\s+(\S+)\s+(\S*)/ ) {
1270 $host = $bpc->uriUnesc($host);
1271 if ( $CmdJob ne $host && defined($Status{$host})
1272 && defined($Jobs{$host}) ) {
1273 print(LOG $bpc->timeStamp,
1274 "Stopping current $Jobs{$host}{type} of $host,"
1275 . " request by $user (backoff=$backoff)\n");
1276 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1278 # Don't close the pipe now; wait until the child
1279 # really exits later. Otherwise close() will
1280 # block until the child has exited.
1282 ##vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1283 ##close($Jobs{$host}{fh});
1284 ##delete($Jobs{$host});
1286 $Status{$host}{state} = "Status_idle";
1287 if ( $Jobs{$host}{type} eq "restore" ) {
1288 $Status{$host}{reason}
1289 = "Reason_restore_canceled_by_user";
1290 } elsif ( $Jobs{$host}{type} eq "archive" ) {
1291 $Status{$host}{reason}
1292 = "Reason_archive_canceled_by_user";
1294 $Status{$host}{reason}
1295 = "Reason_backup_canceled_by_user";
1297 $Status{$host}{activeJob} = 0;
1298 $Status{$host}{startTime} = time;
1299 $reply = "ok: $Jobs{$host}{type} of $host canceled";
1300 } elsif ( $BgQueueOn{$host} || $UserQueueOn{$host} ) {
1301 print(LOG $bpc->timeStamp,
1302 "Stopping pending backup of $host,"
1303 . " request by $user (backoff=$backoff)\n");
1304 @BgQueue = grep($_->{host} ne $host, @BgQueue);
1305 @UserQueue = grep($_->{host} ne $host, @UserQueue);
1306 $BgQueueOn{$host} = $UserQueueOn{$host} = 0;
1307 $reply = "ok: pending backup of $host canceled";
1309 print(LOG $bpc->timeStamp,
1310 "Nothing to do for stop backup of $host,"
1311 . " request by $user (backoff=$backoff)\n");
1312 $reply = "ok: no backup was pending or running";
1314 if ( defined($Status{$host}) && $backoff ne "" ) {
1315 if ( $backoff > 0 ) {
1316 $Status{$host}{backoffTime} = time + $backoff * 3600;
1318 delete($Status{$host}{backoffTime});
1321 } elsif ( $cmd =~ /^backup all$/ ) {
1323 } elsif ( $cmd =~ /^BackupPC_nightly run$/ ) {
1324 $RunNightlyWhenIdle = 1;
1325 } elsif ( $cmd =~ /^backup (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1330 $host = $bpc->uriUnesc($host);
1331 $hostIP = $bpc->uriUnesc($hostIP);
1332 if ( !defined($Status{$host}) ) {
1333 print(LOG $bpc->timeStamp,
1334 "User $user requested backup of unknown host"
1336 $reply = "error: unknown host $host";
1338 print(LOG $bpc->timeStamp,
1339 "User $user requested backup of $host"
1341 if ( $BgQueueOn{$hostIP} ) {
1342 @BgQueue = grep($_->{host} ne $hostIP, @BgQueue);
1343 $BgQueueOn{$hostIP} = 0;
1345 if ( $UserQueueOn{$hostIP} ) {
1346 @UserQueue = grep($_->{host} ne $hostIP, @UserQueue);
1347 $UserQueueOn{$hostIP} = 0;
1349 unshift(@UserQueue, {
1355 dhcp => $hostIP eq $host ? 0 : 1,
1357 $UserQueueOn{$hostIP} = 1;
1358 $reply = "ok: requested backup of $host";
1360 } elsif ( $cmd =~ /^archive (\S+)\s+(\S+)\s+(\S+)/ ) {
1362 my $archivehost = $2;
1363 my $reqFileName = $3;
1364 $host = $bpc->uriUnesc($archivehost);
1365 if ( !defined($Status{$host}) ) {
1366 print(LOG $bpc->timeStamp,
1367 "User $user requested archive of unknown archive host"
1369 $reply = "archive error: unknown archive host $host";
1371 print(LOG $bpc->timeStamp,
1372 "User $user requested archive on $host"
1374 if ( defined($Jobs{$host}) ) {
1375 $reply = "Archive currently running on $host, please try later";
1377 unshift(@UserQueue, {
1380 reqFileName => $reqFileName,
1386 $UserQueueOn{$host} = 1;
1387 $reply = "ok: requested archive on $host";
1390 } elsif ( $cmd =~ /^restore (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1394 my $reqFileName = $4;
1395 $host = $bpc->uriUnesc($host);
1396 $hostIP = $bpc->uriUnesc($hostIP);
1397 if ( !defined($Status{$host}) ) {
1398 print(LOG $bpc->timeStamp,
1399 "User $user requested restore to unknown host"
1401 $reply = "restore error: unknown host $host";
1403 print(LOG $bpc->timeStamp,
1404 "User $user requested restore to $host"
1406 unshift(@UserQueue, {
1409 reqFileName => $reqFileName,
1415 $UserQueueOn{$host} = 1;
1416 if ( defined($Jobs{$host}) ) {
1417 $reply = "ok: requested restore of $host, but a"
1418 . " job is currently running,"
1419 . " so this request will start later";
1421 $reply = "ok: requested restore of $host";
1424 } elsif ( $cmd =~ /^status\s*(.*)/ ) {
1426 my($dump, @values, @names);
1427 foreach my $type ( split(/\s+/, $args) ) {
1428 if ( $type =~ /^queues/ ) {
1429 push(@values, \@BgQueue, \@UserQueue, \@CmdQueue);
1430 push(@names, qw(*BgQueue *UserQueue *CmdQueue));
1431 } elsif ( $type =~ /^jobs/ ) {
1432 push(@values, \%Jobs);
1433 push(@names, qw(*Jobs));
1434 } elsif ( $type =~ /^queueLen/ ) {
1436 BgQueue => scalar(@BgQueue),
1437 UserQueue => scalar(@UserQueue),
1438 CmdQueue => scalar(@CmdQueue),
1440 push(@names, qw(*QueueLen));
1441 } elsif ( $type =~ /^info/ ) {
1442 push(@values, \%Info);
1443 push(@names, qw(*Info));
1444 } elsif ( $type =~ /^hosts/ ) {
1445 push(@values, \%Status);
1446 push(@names, qw(*Status));
1447 } elsif ( $type =~ /^host\((.*)\)/ ) {
1448 my $h = $bpc->uriUnesc($1);
1449 if ( defined($Status{$h}) ) {
1452 BgQueueOn => $BgQueueOn{$h},
1453 UserQueueOn => $UserQueueOn{$h},
1454 CmdQueueOn => $CmdQueueOn{$h},
1456 push(@names, qw(*StatusHost));
1458 print(LOG $bpc->timeStamp,
1459 "Unknown host $h for status request\n");
1462 print(LOG $bpc->timeStamp,
1463 "Unknown status request $type\n");
1466 $dump = Data::Dumper->new(\@values, \@names);
1468 $reply = $dump->Dump;
1469 } elsif ( $cmd =~ /^link\s+(.+)/ ) {
1471 $host = $bpc->uriUnesc($host);
1473 } elsif ( $cmd =~ /^log\s+(.*)/ ) {
1474 print(LOG $bpc->timeStamp, "$1\n");
1475 } elsif ( $cmd =~ /^server\s+(\w+)/ ) {
1477 if ( $type eq 'reload' ) {
1478 ServerReload("Reloading config/host files via CGI request");
1479 } elsif ( $type eq 'shutdown' ) {
1480 $reply = "Shutting down...\n";
1481 syswrite($Clients{$client}{fh}, $reply, length($reply));
1482 ServerShutdown("Server shutting down...");
1484 } elsif ( $cmd =~ /^quit/ || $cmd =~ /^exit/ ) {
1488 print(LOG $bpc->timeStamp, "Unknown command $cmd\n");
1489 $reply = "error: bad command $cmd";
1492 # send a reply to the client, at a minimum "ok\n".
1494 $reply = "ok" if ( $reply eq "" );
1496 syswrite($Clients{$client}{fh}, $reply, length($reply));
1499 # Detect possible denial-of-service attack from sending a huge line
1500 # (ie: never terminated). 32K seems to be plenty big enough as
1503 if ( length($Clients{$client}{mesg}) > 32 * 1024 ) {
1504 print(LOG $bpc->timeStamp, "Line too long from client"
1505 . " '$Clients{$client}{clientName}':"
1506 . " shutting down client connection\n");
1510 # Shut down the client connection if we read EOF
1512 if ( $nbytes <= 0 ) {
1513 close($Clients{$client}{fh});
1514 vec($FDread, $Clients{$client}{fn}, 1) = 0;
1515 delete($Clients{$client});
1519 # Accept any new connections on each of our listen sockets
1521 if ( vec($fdRead, fileno(SERVER_UNIX), 1) ) {
1523 my $paddr = accept(CLIENT, SERVER_UNIX);
1525 $Clients{$ClientConnCnt}{clientName} = "unix socket";
1526 $Clients{$ClientConnCnt}{mesg} = "";
1527 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1528 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1529 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1531 # Generate and send unique seed for MD5 digests to avoid
1532 # replay attacks. See BackupPC::Lib::ServerMesg().
1534 my $seed = time . ",$ClientConnCnt,$$,0\n";
1535 $Clients{$ClientConnCnt}{seed} = $seed;
1536 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1537 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1539 if ( $ServerInetPort > 0 && vec($fdRead, fileno(SERVER_INET), 1) ) {
1541 my $paddr = accept(CLIENT, SERVER_INET);
1542 my($port,$iaddr) = sockaddr_in($paddr);
1543 my $name = gethostbyaddr($iaddr, AF_INET);
1545 $Clients{$ClientConnCnt}{mesg} = "";
1546 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1547 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1548 $Clients{$ClientConnCnt}{clientName} = "$name:$port";
1549 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1551 # Generate and send unique seed for MD5 digests to avoid
1552 # replay attacks. See BackupPC::Lib::ServerMesg().
1554 my $seed = time . ",$ClientConnCnt,$$,$port\n";
1555 $Clients{$ClientConnCnt}{seed} = $seed;
1556 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1557 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1561 ###########################################################################
1562 # Miscellaneous subroutines
1563 ###########################################################################
1566 # Write the current status to $LogDir/status.pl
1570 my($dump) = Data::Dumper->new(
1571 [ \%Info, \%Status],
1572 [qw(*Info *Status)]);
1574 if ( open(STATUS, ">", "$LogDir/status.pl") ) {
1575 print(STATUS $dump->Dump);
1581 # Compare function for host sort. Hosts with errors go first,
1582 # sorted with the oldest errors first. The remaining hosts
1583 # are sorted so that those with the oldest backups go first.
1588 # Hosts with errors go before hosts without errors
1590 return -1 if ( $Status{$a}{error} ne "" && $Status{$b}{error} eq "" );
1593 # Hosts with no errors go after hosts with errors
1596 return 1 if ( $Status{$a}{error} eq "" && $Status{$b}{error} ne "" );
1599 # hosts with the older last good backups sort earlier
1601 my $r = $Status{$a}{lastGoodBackupTime} <=> $Status{$b}{lastGoodBackupTime};
1602 return $r if ( $r );
1605 # Finally, just sort based on host name
1611 # Queue all the hosts for backup. This means queuing all the fixed
1612 # ip hosts and all the dhcp address ranges. We also additionally
1613 # queue the dhcp hosts with a -e flag to check for expired dumps.
1618 foreach my $host ( sort(HostSortCompare keys(%$Hosts)) ) {
1619 delete($Status{$host}{backoffTime})
1620 if ( defined($Status{$host}{backoffTime})
1621 && $Status{$host}{backoffTime} < time );
1622 next if ( defined($Jobs{$host})
1623 || $BgQueueOn{$host}
1624 || $UserQueueOn{$host}
1625 || $CmdQueueOn{$host} );
1626 if ( $Hosts->{$host}{dhcp} ) {
1627 $Status{$host}{dhcpCheckCnt}++;
1628 if ( $RunNightlyWhenIdle ) {
1630 # Once per night queue a check for DHCP hosts that just
1631 # checks for expired dumps. We need to do this to handle
1632 # the case when a DHCP host has not been on the network for
1633 # a long time, and some of the old dumps need to be expired.
1634 # Normally expiry checks are done by BackupPC_dump only
1635 # after the DHCP hosts has been detected on the network.
1638 {host => $host, user => "BackupPC", reqTime => time,
1639 dhcp => 0, dumpExpire => 1});
1640 $BgQueueOn{$host} = 1;
1644 # this is a fixed ip host: queue it
1646 if ( $Info{DUlastValue} > $Conf{DfMaxUsagePct} ) {
1648 # Since we are out of disk space, instead of queuing
1649 # a regular job, queue an expire check instead. That
1650 # way if the admin reduces the number of backups to
1651 # keep then we will actually delete them. Otherwise
1652 # BackupPC_dump will never run since we have exceeded
1657 {host => $host, user => "BackupPC", reqTime => time,
1658 dhcp => $Hosts->{$host}{dhcp}, dumpExpire => 1});
1661 # Queue regular background backup
1664 {host => $host, user => "BackupPC", reqTime => time,
1665 dhcp => $Hosts->{$host}{dhcp}});
1667 $BgQueueOn{$host} = 1;
1671 print(LOG $bpc->timeStamp,
1672 "Disk too full ($Info{DUlastValue}%); skipped $nSkip hosts\n");
1673 $Info{DUDailySkipHostCnt} += $nSkip;
1675 foreach my $dhcp ( @{$Conf{DHCPAddressRanges}} ) {
1676 for ( my $i = $dhcp->{first} ; $i <= $dhcp->{last} ; $i++ ) {
1677 my $ipAddr = "$dhcp->{ipAddrBase}.$i";
1678 next if ( defined($Jobs{$ipAddr})
1679 || $BgQueueOn{$ipAddr}
1680 || $UserQueueOn{$ipAddr}
1681 || $CmdQueueOn{$ipAddr} );
1683 # this is a potential dhcp ip address (we don't know the
1684 # host name yet): queue it
1687 {host => $ipAddr, user => "BackupPC", reqTime => time,
1689 $BgQueueOn{$ipAddr} = 1;
1695 # Queue a BackupPC_link for the given host
1701 return if ( $CmdQueueOn{$host} );
1702 $Status{$host}{state} = "Status_link_pending";
1703 $Status{$host}{needLink} = 0;
1704 unshift(@CmdQueue, {
1708 cmd => ["$BinDir/BackupPC_link", $host],
1710 $CmdQueueOn{$host} = 1;
1714 # Read the hosts file, and update Status if any hosts have been
1715 # added or deleted. We also track the mtime so the only need to
1716 # update the hosts file on changes.
1718 # This function is called at startup, SIGHUP, and on each wakeup.
1719 # It returns 1 on success and undef on failure.
1726 # Nothing to do if we already have the current hosts file
1728 return 1 if ( !$force && defined($Hosts)
1729 && $Info{HostsModTime} == $bpc->HostsMTime() );
1730 if ( !defined($newHosts = $bpc->HostInfoRead()) ) {
1731 print(LOG $bpc->timeStamp, "Can't read hosts file!\n");
1734 print(LOG $bpc->timeStamp, "Reading hosts file\n");
1736 $Info{HostsModTime} = $bpc->HostsMTime();
1738 # Now update %Status in case any hosts have been added or deleted
1740 foreach my $host ( sort(keys(%$Hosts)) ) {
1741 next if ( defined($Status{$host}) );
1742 $Status{$host}{state} = "Status_idle";
1743 print(LOG $bpc->timeStamp, "Added host $host to backup list\n");
1745 foreach my $host ( sort(keys(%Status)) ) {
1746 next if ( $host eq $bpc->trashJob
1747 || $bpc->isAdminJob($host)
1748 || defined($Hosts->{$host})
1749 || defined($Jobs{$host})
1750 || $BgQueueOn{$host}
1751 || $UserQueueOn{$host}
1752 || $CmdQueueOn{$host} );
1753 print(LOG $bpc->timeStamp, "Deleted host $host from backup list\n");
1754 delete($Status{$host});
1760 # Remember the signal name for later processing
1766 foreach my $host ( keys(%Jobs) ) {
1767 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1770 # In case we are inside the exit handler, reopen the log file
1774 print(LOG "Fatal error: unhandled signal $SigName\n");
1775 unlink("$LogDir/BackupPC.pid");
1776 confess("Got new signal $SigName... quitting\n");
1783 # Open the log file and point STDOUT and STDERR there too
1787 mkpath($LogDir, 0, 0777) if ( !-d $LogDir );
1788 open(LOG, ">>$LogDir/LOG")
1789 || die("Can't create LOG file $LogDir/LOG");
1792 open(STDOUT, ">&LOG");
1793 open(STDERR, ">&LOG");
1794 select(LOG); $| = 1;
1795 select(STDERR); $| = 1;
1796 select(STDOUT); $| = 1;
1800 # Initialize the unix-domain and internet-domain sockets that
1801 # we listen to for client connections (from the CGI script and
1802 # some of the BackupPC sub-programs).
1804 sub ServerSocketInit
1806 if ( !defined(fileno(SERVER_UNIX)) ) {
1808 # one-time only: initialize unix-domain socket
1810 if ( !socket(SERVER_UNIX, PF_UNIX, SOCK_STREAM, 0) ) {
1811 print(LOG $bpc->timeStamp, "unix socket() failed: $!\n");
1814 my $sockFile = "$LogDir/BackupPC.sock";
1816 if ( !bind(SERVER_UNIX, sockaddr_un($sockFile)) ) {
1817 print(LOG $bpc->timeStamp, "unix bind() failed: $!\n");
1820 if ( !listen(SERVER_UNIX, SOMAXCONN) ) {
1821 print(LOG $bpc->timeStamp, "unix listen() failed: $!\n");
1824 vec($FDread, fileno(SERVER_UNIX), 1) = 1;
1826 return if ( $ServerInetPort == $Conf{ServerPort} );
1827 if ( $ServerInetPort > 0 ) {
1828 vec($FDread, fileno(SERVER_INET), 1) = 0;
1830 $ServerInetPort = -1;
1832 if ( $Conf{ServerPort} > 0 ) {
1834 # Setup a socket to listen on $Conf{ServerPort}
1836 my $proto = getprotobyname('tcp');
1837 if ( !socket(SERVER_INET, PF_INET, SOCK_STREAM, $proto) ) {
1838 print(LOG $bpc->timeStamp, "inet socket() failed: $!\n");
1841 if ( !setsockopt(SERVER_INET, SOL_SOCKET, SO_REUSEADDR, pack("l",1)) ) {
1842 print(LOG $bpc->timeStamp, "setsockopt() failed: $!\n");
1845 if ( !bind(SERVER_INET, sockaddr_in($Conf{ServerPort}, INADDR_ANY)) ) {
1846 print(LOG $bpc->timeStamp, "inet bind() failed: $!\n");
1849 if ( !listen(SERVER_INET, SOMAXCONN) ) {
1850 print(LOG $bpc->timeStamp, "inet listen() failed: $!\n");
1853 vec($FDread, fileno(SERVER_INET), 1) = 1;
1854 $ServerInetPort = $Conf{ServerPort};
1859 # Reload the server. Used by Main_Process_Signal when $SigName eq "HUP"
1860 # or when the command "server reload" is received.
1865 $mesg = $bpc->ConfigRead() || $mesg;
1866 print(LOG $bpc->timeStamp, "$mesg\n");
1867 $Info{ConfigModTime} = $bpc->ConfigMTime();
1868 %Conf = $bpc->Conf();
1869 umask($Conf{UmaskMode});
1873 $Info{ConfigLTime} = time;
1877 # Gracefully shutdown the server. Used by Main_Process_Signal when
1878 # $SigName ne "" && $SigName ne "HUP" or when the command
1879 # "server shutdown" is received.
1884 print(LOG $bpc->timeStamp, "$mesg\n");
1885 if ( keys(%Jobs) ) {
1886 foreach my $host ( keys(%Jobs) ) {
1887 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1890 foreach my $host ( keys(%Jobs) ) {
1891 kill($bpc->sigName2num("KILL"), $Jobs{$host}{pid});
1897 unlink("$LogDir/BackupPC.pid");