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.0alpha, released 23 Jan 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 if ( open(PID, ">", "$LogDir/BackupPC.pid") ) {
354 # For unknown reasons there is a very infrequent error about not
355 # being able to coerce GLOBs inside the XS Data::Dumper. I've
356 # only seen this on a particular platform and perl version.
357 # For now the workaround appears to be use the perl version of
360 $Data::Dumper::Useqq = 1;
363 ############################################################################
364 # Main_TryToRun_nightly()
366 # Checks to see if we can/should run BackupPC_nightly or
367 # BackupPC_trashClean. If so we push the appropriate command onto
369 ############################################################################
370 sub Main_TryToRun_nightly
373 # Check if we should run BackupPC_nightly or BackupPC_trashClean.
374 # BackupPC_nightly is run when the current job queue is empty.
375 # BackupPC_trashClean is run in the background always.
377 my $trashCleanRunning = defined($Jobs{$bpc->trashJob}) ? 1 : 0;
378 if ( !$trashCleanRunning && !$CmdQueueOn{$bpc->trashJob} ) {
380 # This should only happen once at startup, but just in case this
381 # code will re-start BackupPC_trashClean if it quits
384 host => $bpc->trashJob,
387 cmd => ["$BinDir/BackupPC_trashClean"],
389 $CmdQueueOn{$bpc->trashJob} = 1;
391 if ( keys(%Jobs) == $trashCleanRunning && $RunNightlyWhenIdle == 1 ) {
394 # Queue multiple nightly jobs based on the configuration
396 $Conf{MaxBackupPCNightlyJobs} = 1
397 if ( $Conf{MaxBackupPCNightlyJobs} <= 0 );
398 $Conf{BackupPCNightlyPeriod} = 1
399 if ( $Conf{BackupPCNightlyPeriod} <= 0 );
401 # Decide what subset of the 16 top-level directories 0..9a..f
402 # we run BackupPC_nightly on, based on $Conf{BackupPCNightlyPeriod}.
403 # If $Conf{BackupPCNightlyPeriod} == 1 then we run 0..15 every
404 # time. If $Conf{BackupPCNightlyPeriod} == 2 then we run
405 # 0..7 one night and 89a-f the next night. And so on.
407 # $Info{NightlyPhase} counts which night, from 0 to
408 # $Conf{BackupPCNightlyPeriod} - 1.
410 my $start = int($Info{NightlyPhase} * 16
411 / $Conf{BackupPCNightlyPeriod});
412 my $end = int(($Info{NightlyPhase} + 1) * 16
413 / $Conf{BackupPCNightlyPeriod});
414 $end = $start + 1 if ( $end <= $start );
415 $Info{NightlyPhase}++;
416 $Info{NightlyPhase} = 0 if ( $end >= 16 );
419 # Zero out the data we expect to get from BackupPC_nightly.
421 for my $p ( qw(pool cpool) ) {
422 for ( my $i = $start ; $i < $end ; $i++ ) {
423 $Info{pool}{$p}[$i]{FileCnt} = 0;
424 $Info{pool}{$p}[$i]{DirCnt} = 0;
425 $Info{pool}{$p}[$i]{Kb} = 0;
426 $Info{pool}{$p}[$i]{Kb2} = 0;
427 $Info{pool}{$p}[$i]{KbRm} = 0;
428 $Info{pool}{$p}[$i]{FileCntRm} = 0;
429 $Info{pool}{$p}[$i]{FileCntRep} = 0;
430 $Info{pool}{$p}[$i]{FileRepMax} = 0;
431 $Info{pool}{$p}[$i]{FileCntRename} = 0;
432 $Info{pool}{$p}[$i]{FileLinkMax} = 0;
433 $Info{pool}{$p}[$i]{Time} = 0;
436 print(LOG $bpc->timeStamp,
437 sprintf("Running %d BackupPC_nightly jobs from %d..%d"
438 . " (out of 0..15)\n",
439 $Conf{MaxBackupPCNightlyJobs}, $start, $end - 1));
442 # Now queue the $Conf{MaxBackupPCNightlyJobs} jobs.
443 # The granularity on start and end is now 0..255.
448 for ( my $i = 0 ; $i < $Conf{MaxBackupPCNightlyJobs} ; $i++ ) {
450 # The first nightly job gets the -m option (does email, log aging).
451 # All jobs get the start and end options from 0..255 telling
452 # them which parts of the pool to traverse.
454 my $cmd = ["$BinDir/BackupPC_nightly"];
455 push(@$cmd, "-m") if ( $i == 0 );
457 $start = $start0 + int(($end - $start0)
458 * ($i + 1) / $Conf{MaxBackupPCNightlyJobs});
459 push(@$cmd, $start - 1);
461 my $job = $bpc->adminJob($i);
468 $CmdQueueOn{$job} = 1;
470 $RunNightlyWhenIdle = 2;
474 ############################################################################
475 # Main_TryToRun_CmdQueue()
477 # Decide if we can run a new command from the @CmdQueue.
478 # We only run one of these at a time. The @CmdQueue is
479 # used to run BackupPC_link (for the corresponding host),
480 # BackupPC_trashClean, and BackupPC_nightly using a fake
481 # host name of $bpc->adminJob.
482 ############################################################################
483 sub Main_TryToRun_CmdQueue
487 while ( $CmdJob eq "" && @CmdQueue > 0 && $RunNightlyWhenIdle != 1
488 || @CmdQueue > 0 && $RunNightlyWhenIdle == 2
489 && $bpc->isAdminJob($CmdQueue[0]->{host})
492 $req = pop(@CmdQueue);
494 $host = $req->{host};
495 if ( defined($Jobs{$host}) ) {
496 print(LOG $bpc->timeStamp,
497 "Botch on admin job for $host: already in use!!\n");
499 # This could happen during normal opertion: a user could
500 # request a backup while a BackupPC_link is queued from
501 # a previous backup. But it is unlikely. Just put this
502 # request back on the end of the queue.
504 unshift(@CmdQueue, $req);
507 $CmdQueueOn{$host} = 0;
508 my $cmd = $req->{cmd};
509 my $pid = open(FH, "-|");
510 if ( !defined($pid) ) {
511 print(LOG $bpc->timeStamp,
512 "can't fork for $host, request by $req->{user}\n");
519 print(LOG $bpc->timeStamp, "can't exec @$cmd for $host\n");
522 $Jobs{$host}{pid} = $pid;
523 $Jobs{$host}{fh} = *FH;
524 $Jobs{$host}{fn} = fileno(FH);
525 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
526 $Jobs{$host}{startTime} = time;
527 $Jobs{$host}{reqTime} = $req->{reqTime};
528 $cmd = $bpc->execCmd2ShellCmd(@$cmd);
529 $Jobs{$host}{cmd} = $cmd;
530 $Jobs{$host}{user} = $req->{user};
531 $Jobs{$host}{type} = $Status{$host}{type};
532 $Status{$host}{state} = "Status_link_running";
533 $Status{$host}{activeJob} = 1;
534 $Status{$host}{endTime} = time;
535 $CmdJob = $host if ( $host ne $bpc->trashJob );
536 $cmd =~ s/$BinDir\///g;
537 print(LOG $bpc->timeStamp, "Running $cmd (pid=$pid)\n");
538 if ( $cmd =~ /^BackupPC_nightly\s/ ) {
539 $BackupPCNightlyJobs++;
540 $BackupPCNightlyLock++;
545 ############################################################################
546 # Main_TryToRun_Bg_or_User_Queue()
548 # Decide if we can run any new backup requests from @BgQueue
549 # or @UserQueue. Several of these can be run at the same time
550 # based on %Conf settings. Jobs from @UserQueue take priority,
551 # and at total of $Conf{MaxBackups} + $Conf{MaxUserBackups}
552 # simultaneous jobs can run from @UserQueue. After @UserQueue
553 # is exhausted, up to $Conf{MaxBackups} simultaneous jobs can
555 ############################################################################
556 sub Main_TryToRun_Bg_or_User_Queue
559 my(@deferUserQueue, @deferBgQueue);
562 if ( time - $Info{DUlastValueTime} >= 600 ) {
564 # Update our notion of disk usage no more than
565 # once every 10 minutes
567 $du = $bpc->CheckFileSystemUsage($TopDir);
568 $Info{DUlastValue} = $du;
569 $Info{DUlastValueTime} = time;
572 # if we recently checked it then just use the old value
574 $du = $Info{DUlastValue};
576 if ( $Info{DUDailyMaxReset} ) {
577 $Info{DUDailyMaxStartTime} = time;
578 $Info{DUDailyMaxReset} = 0;
579 $Info{DUDailyMax} = 0;
581 if ( $du > $Info{DUDailyMax} ) {
582 $Info{DUDailyMax} = $du;
583 $Info{DUDailyMaxTime} = time;
585 if ( $du > $Conf{DfMaxUsagePct} ) {
586 my @bgQueue = @BgQueue;
590 # When the disk is too full, only run backups that will
591 # do expires, not regular backups
594 foreach $req ( @bgQueue ) {
595 if ( $req->{dumpExpire} ) {
596 unshift(@BgQueue, $req);
598 $BgQueueOn{$req->{host}} = 0;
603 print(LOG $bpc->timeStamp,
604 "Disk too full ($du%); skipped $nSkip hosts\n");
605 $Info{DUDailySkipHostCnt} += $nSkip;
609 while ( $RunNightlyWhenIdle == 0 ) {
611 my(@args, $progName, $type);
612 my $nJobs = keys(%Jobs);
614 # CmdJob and trashClean don't count towards MaxBackups / MaxUserBackups
616 if ( $CmdJob ne "" ) {
617 if ( $BackupPCNightlyJobs ) {
618 $nJobs -= $BackupPCNightlyJobs;
623 $nJobs-- if ( defined($Jobs{$bpc->trashJob} ) );
624 if ( $nJobs < $Conf{MaxBackups} + $Conf{MaxUserBackups}
625 && @UserQueue > 0 ) {
626 $req = pop(@UserQueue);
627 if ( defined($Jobs{$req->{host}}) ) {
628 push(@deferUserQueue, $req);
631 push(@args, $req->{doFull} ? "-f" : "-i")
632 if (( !$req->{restore} ) && ( !$req->{archive} ));
633 $UserQueueOn{$req->{host}} = 0;
634 } elsif ( $nJobs < $Conf{MaxBackups}
635 && (@CmdQueue + $nJobs)
636 <= $Conf{MaxBackups} + $Conf{MaxPendingCmds}
638 $req = pop(@BgQueue);
639 if ( defined($Jobs{$req->{host}}) ) {
641 # Job is currently running for this host; save it for later
643 unshift(@deferBgQueue, $req);
646 $BgQueueOn{$req->{host}} = 0;
649 # Restore the deferred jobs
651 @BgQueue = (@BgQueue, @deferBgQueue);
652 @UserQueue = (@UserQueue, @deferUserQueue);
655 $host = $req->{host};
656 my $user = $req->{user};
657 if ( $req->{restore} ) {
658 $progName = "BackupPC_restore";
660 push(@args, $req->{hostIP}, $req->{host}, $req->{reqFileName});
661 } elsif ( $req->{archive} ) {
662 $progName = "BackupPC_archive";
664 push(@args, $req->{user}, $req->{host}, $req->{reqFileName});
666 $progName = "BackupPC_dump";
668 push(@args, "-d") if ( $req->{dhcp} );
669 push(@args, "-e") if ( $req->{dumpExpire} );
672 my $pid = open(FH, "-|");
673 if ( !defined($pid) ) {
674 print(LOG $bpc->timeStamp,
675 "can't fork to run $progName for $host, request by $user\n");
681 exec("$BinDir/$progName", @args);
682 print(LOG $bpc->timeStamp, "can't exec $progName for $host\n");
685 $Jobs{$host}{pid} = $pid;
686 $Jobs{$host}{fh} = *FH;
687 $Jobs{$host}{fn} = fileno(FH);
688 $Jobs{$host}{dhcp} = $req->{dhcp};
689 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
690 $Jobs{$host}{startTime} = time;
691 $Jobs{$host}{reqTime} = $req->{reqTime};
692 $Jobs{$host}{userReq} = $req->{userReq};
693 $Jobs{$host}{cmd} = $bpc->execCmd2ShellCmd($progName, @args);
694 $Jobs{$host}{user} = $user;
695 $Jobs{$host}{type} = $type;
696 $Status{$host}{userReq} = $req->{userReq}
697 if ( defined($Hosts->{$host}) );
698 if ( !$req->{dhcp} ) {
699 $Status{$host}{state} = "Status_".$type."_starting";
700 $Status{$host}{activeJob} = 1;
701 $Status{$host}{startTime} = time;
702 $Status{$host}{endTime} = "";
707 ############################################################################
710 # If necessary, figure out when to next wakeup based on $Conf{WakeupSchedule},
711 # and then do a select() to wait for the next thing to happen
712 # (timeout, signal, someone sends a message, child dies etc).
713 ############################################################################
716 if ( $NextWakeup <= 0 ) {
718 # Figure out when to next wakeup based on $Conf{WakeupSchedule}.
720 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
722 my($currHours) = $hour + $min / 60 + $sec / 3600;
723 if ( $bpc->ConfigMTime() != $Info{ConfigModTime} ) {
724 ServerReload("Re-read config file because mtime changed");
727 foreach my $t ( @{$Conf{WakeupSchedule} || [0..23]} ) {
728 next if ( $t < 0 || $t > 24 );
729 my $tomorrow = $t + 24;
731 || ($tomorrow - $currHours > 0
732 && $delta > $tomorrow - $currHours) ) {
733 $delta = $tomorrow - $currHours;
734 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
737 || ($t - $currHours > 0 && $delta > $t - $currHours) ) {
738 $delta = $t - $currHours;
739 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
742 $NextWakeup = time + $delta * 3600;
743 $Info{nextWakeup} = $NextWakeup;
744 print(LOG $bpc->timeStamp, "Next wakeup is ",
745 $bpc->timeStamp($NextWakeup, 1), "\n");
748 # Call select(), waiting until either a signal, a timeout,
749 # any output from our jobs, or any messages from clients
751 # select() is where we (hopefully) spend most of our time blocked...
753 my $timeout = $NextWakeup - time;
754 $timeout = 1 if ( $timeout <= 0 );
756 select(my $rout = $FDread, undef, $ein, $timeout);
761 ############################################################################
762 # Main_Process_Signal()
765 ############################################################################
766 sub Main_Process_Signal
771 if ( $SigName eq "HUP" ) {
772 ServerReload("Re-read config file because of a SIG_HUP");
773 } elsif ( $SigName ) {
774 ServerShutdown("Got signal $SigName... cleaning up");
779 ############################################################################
780 # Main_Check_Timeout()
782 # Check if a timeout has occured, and if so, queue all the PCs for backups.
783 # Also does log file aging on the first timeout after midnight.
784 ############################################################################
785 sub Main_Check_Timeout
790 return if ( time < $NextWakeup || $NextWakeup <= 0 );
792 if ( $FirstWakeup ) {
794 # This is the first wakeup after midnight. Do log file aging
795 # and various house keeping.
798 printf(LOG "%s24hr disk usage: %d%% max, %d%% recent,"
799 . " %d skipped hosts\n",
800 $bpc->timeStamp, $Info{DUDailyMax}, $Info{DUlastValue},
801 $Info{DUDailySkipHostCnt});
802 $Info{DUDailyMaxReset} = 1;
803 $Info{DUDailyMaxPrev} = $Info{DUDailyMax};
804 $Info{DUDailySkipHostCntPrev} = $Info{DUDailySkipHostCnt};
805 $Info{DUDailySkipHostCnt} = 0;
806 my $lastLog = $Conf{MaxOldLogFiles} - 1;
807 if ( -f "$LogDir/LOG.$lastLog" ) {
808 print(LOG $bpc->timeStamp,
809 "Removing $LogDir/LOG.$lastLog\n");
810 unlink("$LogDir/LOG.$lastLog");
812 if ( -f "$LogDir/LOG.$lastLog.z" ) {
813 print(LOG $bpc->timeStamp,
814 "Removing $LogDir/LOG.$lastLog.z\n");
815 unlink("$LogDir/LOG.$lastLog.z");
817 print(LOG $bpc->timeStamp, "Aging LOG files, LOG -> LOG.0 -> "
818 . "LOG.1 -> ... -> LOG.$lastLog\n");
819 close(STDERR); # dup of LOG
820 close(STDOUT); # dup of LOG
822 for ( my $i = $lastLog - 1 ; $i >= 0 ; $i-- ) {
824 rename("$LogDir/LOG.$i", "$LogDir/LOG.$j")
825 if ( -f "$LogDir/LOG.$i" );
826 rename("$LogDir/LOG.$i.z", "$LogDir/LOG.$j.z")
827 if ( -f "$LogDir/LOG.$i.z" );
830 # Compress the log file LOG -> LOG.0.z (if enabled).
831 # Otherwise, just rename LOG -> LOG.0.
833 BackupPC::FileZIO->compressCopy("$LogDir/LOG",
836 $Conf{CompressLevel}, 1);
839 # Remember to run nightly script after current jobs are done
841 $RunNightlyWhenIdle = 1;
844 # Write out the current status and then queue all the PCs
848 %BgQueueOn = () if ( @BgQueue == 0 );
849 %UserQueueOn = () if ( @UserQueue == 0 );
850 %CmdQueueOn = () if ( @CmdQueue == 0 );
854 ############################################################################
855 # Main_Check_Job_Messages($fdRead)
857 # Check if select() says we have bytes waiting from any of our jobs.
858 # Handle each of the messages when complete (newline terminated).
859 ############################################################################
860 sub Main_Check_Job_Messages
863 foreach my $host ( keys(%Jobs) ) {
864 next if ( !vec($fdRead, $Jobs{$host}{fn}, 1) );
867 # do a last check to make sure there is something to read so
868 # we are absolutely sure we won't block.
870 vec(my $readMask, $Jobs{$host}{fn}, 1) = 1;
871 if ( !select($readMask, undef, undef, 0.0) ) {
872 print(LOG $bpc->timeStamp, "Botch in Main_Check_Job_Messages:"
873 . " nothing to read from $host. Debug dump:\n");
874 my($dump) = Data::Dumper->new(
875 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
876 [qw(*Clients, *Jobs *FDread, *fdRead)]);
878 print(LOG $dump->Dump);
881 my $nbytes = sysread($Jobs{$host}{fh}, $mesg, 1024);
882 $Jobs{$host}{mesg} .= $mesg if ( $nbytes > 0 );
884 # Process any complete lines of output from this jobs.
885 # Any output to STDOUT or STDERR from the children is processed here.
887 while ( $Jobs{$host}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
889 $Jobs{$host}{mesg} = $2;
890 if ( $Jobs{$host}{dhcp} ) {
891 if ( $mesg =~ /^DHCP (\S+) (\S+)/ ) {
892 my $newHost = $bpc->uriUnesc($2);
893 if ( defined($Jobs{$newHost}) ) {
894 print(LOG $bpc->timeStamp,
895 "Backup on $newHost is already running\n");
896 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
900 $Jobs{$host}{dhcpHostIP} = $host;
901 $Status{$newHost}{dhcpHostIP} = $host;
902 $Jobs{$newHost} = $Jobs{$host};
903 delete($Jobs{$host});
905 $Status{$host}{state} = "Status_backup_starting";
906 $Status{$host}{activeJob} = 1;
907 $Status{$host}{startTime} = $Jobs{$host}{startTime};
908 $Status{$host}{endTime} = "";
909 $Jobs{$host}{dhcp} = 0;
911 print(LOG $bpc->timeStamp, "dhcp $host: $mesg\n");
913 } elsif ( $mesg =~ /^started (.*) dump, share=(.*)/ ) {
914 $Jobs{$host}{type} = $1;
915 $Jobs{$host}{shareName} = $2;
916 print(LOG $bpc->timeStamp,
917 "Started $1 backup on $host (pid=$Jobs{$host}{pid}",
918 $Jobs{$host}{dhcpHostIP}
919 ? ", dhcp=$Jobs{$host}{dhcpHostIP}" : "",
920 ", share=$Jobs{$host}{shareName})\n");
921 $Status{$host}{state} = "Status_backup_in_progress";
922 $Status{$host}{reason} = "";
923 $Status{$host}{type} = $1;
924 $Status{$host}{startTime} = time;
925 $Status{$host}{deadCnt} = 0;
926 $Status{$host}{aliveCnt}++;
927 $Status{$host}{dhcpCheckCnt}--
928 if ( $Status{$host}{dhcpCheckCnt} > 0 );
929 } elsif ( $mesg =~ /^xferPids (.*)/ ) {
930 $Jobs{$host}{xferPid} = $1;
931 } elsif ( $mesg =~ /^started_restore/ ) {
932 $Jobs{$host}{type} = "restore";
933 print(LOG $bpc->timeStamp,
934 "Started restore on $host"
935 . " (pid=$Jobs{$host}{pid})\n");
936 $Status{$host}{state} = "Status_restore_in_progress";
937 $Status{$host}{reason} = "";
938 $Status{$host}{type} = "restore";
939 $Status{$host}{startTime} = time;
940 $Status{$host}{deadCnt} = 0;
941 $Status{$host}{aliveCnt}++;
942 } elsif ( $mesg =~ /^started_archive/ ) {
943 $Jobs{$host}{type} = "archive";
944 print(LOG $bpc->timeStamp,
945 "Started archive on $host"
946 . " (pid=$Jobs{$host}{pid})\n");
947 $Status{$host}{state} = "Status_archive_in_progress";
948 $Status{$host}{reason} = "";
949 $Status{$host}{type} = "archive";
950 $Status{$host}{startTime} = time;
951 $Status{$host}{deadCnt} = 0;
952 $Status{$host}{aliveCnt}++;
953 } elsif ( $mesg =~ /^(full|incr) backup complete/ ) {
954 print(LOG $bpc->timeStamp, "Finished $1 backup on $host\n");
955 $Status{$host}{reason} = "Reason_backup_done";
956 delete($Status{$host}{error});
957 delete($Status{$host}{errorTime});
958 $Status{$host}{endTime} = time;
959 $Status{$host}{lastGoodBackupTime} = time;
960 } elsif ( $mesg =~ /^backups disabled/ ) {
961 print(LOG $bpc->timeStamp,
962 "Ignoring old backup error on $host\n");
963 $Status{$host}{reason} = "Reason_backup_done";
964 delete($Status{$host}{error});
965 delete($Status{$host}{errorTime});
966 $Status{$host}{endTime} = time;
967 } elsif ( $mesg =~ /^restore complete/ ) {
968 print(LOG $bpc->timeStamp, "Finished restore on $host\n");
969 $Status{$host}{reason} = "Reason_restore_done";
970 delete($Status{$host}{error});
971 delete($Status{$host}{errorTime});
972 $Status{$host}{endTime} = time;
973 } elsif ( $mesg =~ /^archive complete/ ) {
974 print(LOG $bpc->timeStamp, "Finished archive on $host\n");
975 $Status{$host}{reason} = "Reason_archive_done";
976 delete($Status{$host}{error});
977 delete($Status{$host}{errorTime});
978 $Status{$host}{endTime} = time;
979 } elsif ( $mesg =~ /^nothing to do/ ) {
980 if ( $Status{$host}{reason} ne "Reason_backup_failed"
981 && $Status{$host}{reason} ne "Reason_restore_failed" ) {
982 $Status{$host}{state} = "Status_idle";
983 $Status{$host}{reason} = "Reason_nothing_to_do";
984 $Status{$host}{startTime} = time;
986 $Status{$host}{dhcpCheckCnt}--
987 if ( $Status{$host}{dhcpCheckCnt} > 0 );
988 } elsif ( $mesg =~ /^no ping response/
989 || $mesg =~ /^ping too slow/
990 || $mesg =~ /^host not found/ ) {
991 $Status{$host}{state} = "Status_idle";
992 if ( $Status{$host}{userReq}
993 || $Status{$host}{reason} ne "Reason_backup_failed"
994 || $Status{$host}{error} =~ /^aborted by user/ ) {
995 $Status{$host}{reason} = "Reason_no_ping";
996 $Status{$host}{error} = $mesg;
997 $Status{$host}{startTime} = time;
999 $Status{$host}{deadCnt}++;
1000 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1001 $Status{$host}{aliveCnt} = 0;
1003 } elsif ( $mesg =~ /^dump failed: (.*)/ ) {
1004 $Status{$host}{state} = "Status_idle";
1005 $Status{$host}{error} = $1;
1006 $Status{$host}{errorTime} = time;
1007 $Status{$host}{endTime} = time;
1008 if ( $Status{$host}{reason}
1009 eq "Reason_backup_canceled_by_user" ) {
1010 print(LOG $bpc->timeStamp,
1011 "Backup canceled on $host ($1)\n");
1013 $Status{$host}{reason} = "Reason_backup_failed";
1014 print(LOG $bpc->timeStamp,
1015 "Backup failed on $host ($1)\n");
1017 } elsif ( $mesg =~ /^restore failed: (.*)/ ) {
1018 $Status{$host}{state} = "Status_idle";
1019 $Status{$host}{error} = $1;
1020 $Status{$host}{errorTime} = time;
1021 $Status{$host}{endTime} = time;
1022 if ( $Status{$host}{reason}
1023 eq "Reason_restore_canceled_by_user" ) {
1024 print(LOG $bpc->timeStamp,
1025 "Restore canceled on $host ($1)\n");
1027 $Status{$host}{reason} = "Reason_restore_failed";
1028 print(LOG $bpc->timeStamp,
1029 "Restore failed on $host ($1)\n");
1031 } elsif ( $mesg =~ /^archive failed: (.*)/ ) {
1032 $Status{$host}{state} = "Status_idle";
1033 $Status{$host}{error} = $1;
1034 $Status{$host}{errorTime} = time;
1035 $Status{$host}{endTime} = time;
1036 if ( $Status{$host}{reason}
1037 eq "Reason_archive_canceled_by_user" ) {
1038 print(LOG $bpc->timeStamp,
1039 "Archive canceled on $host ($1)\n");
1041 $Status{$host}{reason} = "Reason_archive_failed";
1042 print(LOG $bpc->timeStamp,
1043 "Archive failed on $host ($1)\n");
1045 } elsif ( $mesg =~ /^log\s+(.*)/ ) {
1046 print(LOG $bpc->timeStamp, "$1\n");
1047 } elsif ( $mesg =~ /^BackupPC_stats (\d+) = (.*)/ ) {
1048 my $chunk = int($1 / 16);
1049 my @f = split(/,/, $2);
1050 $Info{pool}{$f[0]}[$chunk]{FileCnt} += $f[1];
1051 $Info{pool}{$f[0]}[$chunk]{DirCnt} += $f[2];
1052 $Info{pool}{$f[0]}[$chunk]{Kb} += $f[3];
1053 $Info{pool}{$f[0]}[$chunk]{Kb2} += $f[4];
1054 $Info{pool}{$f[0]}[$chunk]{KbRm} += $f[5];
1055 $Info{pool}{$f[0]}[$chunk]{FileCntRm} += $f[6];
1056 $Info{pool}{$f[0]}[$chunk]{FileCntRep} += $f[7];
1057 $Info{pool}{$f[0]}[$chunk]{FileRepMax} = $f[8]
1058 if ( $Info{pool}{$f[0]}[$chunk]{FileRepMax} < $f[8] );
1059 $Info{pool}{$f[0]}[$chunk]{FileCntRename} += $f[9];
1060 $Info{pool}{$f[0]}[$chunk]{FileLinkMax} = $f[10]
1061 if ( $Info{pool}{$f[0]}[$chunk]{FileLinkMax} < $f[10] );
1062 $Info{pool}{$f[0]}[$chunk]{FileLinkTotal} += $f[11];
1063 $Info{pool}{$f[0]}[$chunk]{Time} = time;
1064 } elsif ( $mesg =~ /^BackupPC_nightly lock_off/ ) {
1065 $BackupPCNightlyLock--;
1066 if ( $BackupPCNightlyLock == 0 ) {
1068 # This means the last BackupPC_nightly is done with
1069 # the pool clean, so it's ok to start running regular
1072 $RunNightlyWhenIdle = 0;
1074 } elsif ( $mesg =~ /^processState\s+(.+)/ ) {
1075 $Jobs{$host}{processState} = $1;
1076 } elsif ( $mesg =~ /^link\s+(.+)/ ) {
1078 $Status{$h}{needLink} = 1;
1080 print(LOG $bpc->timeStamp, "$host: $mesg\n");
1084 # shut down the client connection if we read EOF
1086 if ( $nbytes <= 0 ) {
1087 close($Jobs{$host}{fh});
1088 vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1089 if ( $CmdJob eq $host || $bpc->isAdminJob($host) ) {
1090 my $cmd = $Jobs{$host}{cmd};
1091 $cmd =~ s/$BinDir\///g;
1092 print(LOG $bpc->timeStamp, "Finished $host ($cmd)\n");
1093 $Status{$host}{state} = "Status_idle";
1094 $Status{$host}{endTime} = time;
1095 if ( $cmd =~ /^BackupPC_nightly\s/ ) {
1096 $BackupPCNightlyJobs--;
1097 #print(LOG $bpc->timeStamp, "BackupPC_nightly done; now"
1098 # . " have $BackupPCNightlyJobs running\n");
1099 if ( $BackupPCNightlyJobs <= 0 ) {
1100 $BackupPCNightlyJobs = 0;
1101 $RunNightlyWhenIdle = 0;
1104 # Combine the 16 per-directory results
1106 for my $p ( qw(pool cpool) ) {
1107 $Info{"${p}FileCnt"} = 0;
1108 $Info{"${p}DirCnt"} = 0;
1109 $Info{"${p}Kb"} = 0;
1110 $Info{"${p}Kb2"} = 0;
1111 $Info{"${p}KbRm"} = 0;
1112 $Info{"${p}FileCntRm"} = 0;
1113 $Info{"${p}FileCntRep"} = 0;
1114 $Info{"${p}FileRepMax"} = 0;
1115 $Info{"${p}FileCntRename"} = 0;
1116 $Info{"${p}FileLinkMax"} = 0;
1117 $Info{"${p}Time"} = 0;
1118 for ( my $i = 0 ; $i < 16 ; $i++ ) {
1119 $Info{"${p}FileCnt"}
1120 += $Info{pool}{$p}[$i]{FileCnt};
1122 += $Info{pool}{$p}[$i]{DirCnt};
1124 += $Info{pool}{$p}[$i]{Kb};
1126 += $Info{pool}{$p}[$i]{Kb2};
1128 += $Info{pool}{$p}[$i]{KbRm};
1129 $Info{"${p}FileCntRm"}
1130 += $Info{pool}{$p}[$i]{FileCntRm};
1131 $Info{"${p}FileCntRep"}
1132 += $Info{pool}{$p}[$i]{FileCntRep};
1133 $Info{"${p}FileRepMax"}
1134 = $Info{pool}{$p}[$i]{FileRepMax}
1135 if ( $Info{"${p}FileRepMax"} <
1136 $Info{pool}{$p}[$i]{FileRepMax} );
1137 $Info{"${p}FileCntRename"}
1138 += $Info{pool}{$p}[$i]{FileCntRename};
1139 $Info{"${p}FileLinkMax"}
1140 = $Info{pool}{$p}[$i]{FileLinkMax}
1141 if ( $Info{"${p}FileLinkMax"} <
1142 $Info{pool}{$p}[$i]{FileLinkMax} );
1143 $Info{"${p}Time"} = $Info{pool}{$p}[$i]{Time}
1144 if ( $Info{"${p}Time"} <
1145 $Info{pool}{$p}[$i]{Time} );
1147 printf(LOG "%s%s nightly clean removed %d files of"
1149 $bpc->timeStamp, ucfirst($p),
1150 $Info{"${p}FileCntRm"},
1151 $Info{"${p}KbRm"} / (1000 * 1024));
1152 printf(LOG "%s%s is %.2fGB, %d files (%d repeated, "
1153 . "%d max chain, %d max links), %d directories\n",
1154 $bpc->timeStamp, ucfirst($p),
1155 $Info{"${p}Kb"} / (1000 * 1024),
1156 $Info{"${p}FileCnt"}, $Info{"${p}FileCntRep"},
1157 $Info{"${p}FileRepMax"},
1158 $Info{"${p}FileLinkMax"}, $Info{"${p}DirCnt"});
1166 # Queue BackupPC_link to complete the backup
1167 # processing for this host.
1169 if ( defined($Status{$host})
1170 && ($Status{$host}{reason} eq "Reason_backup_done"
1171 || $Status{$host}{needLink}) ) {
1173 } elsif ( defined($Status{$host}) ) {
1174 $Status{$host}{state} = "Status_idle";
1177 delete($Jobs{$host});
1178 $Status{$host}{activeJob} = 0 if ( defined($Status{$host}) );
1182 # When we are idle (empty Jobs, CmdQueue, BgQueue, UserQueue) we
1183 # do a pass over %Status updating the deadCnt and aliveCnt for
1184 # DHCP hosts. The reason we need to do this later is we can't
1185 # be sure whether a DHCP host is alive or dead until we have passed
1186 # over all the DHCP pool.
1188 return if ( @CmdQueue || @BgQueue || @UserQueue || keys(%Jobs) > 1 );
1189 foreach my $host ( keys(%Status) ) {
1190 next if ( $Status{$host}{dhcpCheckCnt} <= 0 );
1191 $Status{$host}{deadCnt} += $Status{$host}{dhcpCheckCnt};
1192 $Status{$host}{dhcpCheckCnt} = 0;
1193 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1194 $Status{$host}{aliveCnt} = 0;
1199 ############################################################################
1200 # Main_Check_Client_Messages($fdRead)
1202 # Check for, and process, any output from our clients. Also checks
1203 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
1204 ############################################################################
1205 sub Main_Check_Client_Messages
1208 foreach my $client ( keys(%Clients) ) {
1209 next if ( !vec($fdRead, $Clients{$client}{fn}, 1) );
1212 # do a last check to make sure there is something to read so
1213 # we are absolutely sure we won't block.
1215 vec(my $readMask, $Clients{$client}{fn}, 1) = 1;
1216 if ( !select($readMask, undef, undef, 0.0) ) {
1217 print(LOG $bpc->timeStamp, "Botch in Main_Check_Client_Messages:"
1218 . " nothing to read from $client. Debug dump:\n");
1219 my($dump) = Data::Dumper->new(
1220 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
1221 [qw(*Clients, *Jobs *FDread, *fdRead)]);
1223 print(LOG $dump->Dump);
1226 my $nbytes = sysread($Clients{$client}{fh}, $mesg, 1024);
1227 $Clients{$client}{mesg} .= $mesg if ( $nbytes > 0 );
1229 # Process any complete lines received from this client.
1231 while ( $Clients{$client}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
1234 $Clients{$client}{mesg} = $2;
1236 # Authenticate the message by checking the MD5 digest
1238 my $md5 = Digest::MD5->new;
1239 if ( $cmd !~ /^(.{22}) (.*)/
1240 || ($md5->add($Clients{$client}{seed}
1241 . $Clients{$client}{mesgCnt}
1242 . $Conf{ServerMesgSecret} . $2),
1243 $md5->b64digest ne $1) ) {
1244 print(LOG $bpc->timeStamp, "Corrupted message '$cmd' from"
1245 . " client '$Clients{$client}{clientName}':"
1246 . " shutting down client connection\n");
1250 $Clients{$client}{mesgCnt}++;
1252 if ( $cmd =~ /^stop (\S+)\s+(\S+)\s+(\S*)/ ) {
1256 $host = $bpc->uriUnesc($host);
1257 if ( $CmdJob ne $host && defined($Status{$host})
1258 && defined($Jobs{$host}) ) {
1259 print(LOG $bpc->timeStamp,
1260 "Stopping current $Jobs{$host}{type} of $host,"
1261 . " request by $user (backoff=$backoff)\n");
1262 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1264 # Don't close the pipe now; wait until the child
1265 # really exits later. Otherwise close() will
1266 # block until the child has exited.
1268 ##vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1269 ##close($Jobs{$host}{fh});
1270 ##delete($Jobs{$host});
1272 $Status{$host}{state} = "Status_idle";
1273 if ( $Jobs{$host}{type} eq "restore" ) {
1274 $Status{$host}{reason}
1275 = "Reason_restore_canceled_by_user";
1276 } elsif ( $Jobs{$host}{type} eq "archive" ) {
1277 $Status{$host}{reason}
1278 = "Reason_archive_canceled_by_user";
1280 $Status{$host}{reason}
1281 = "Reason_backup_canceled_by_user";
1283 $Status{$host}{activeJob} = 0;
1284 $Status{$host}{startTime} = time;
1285 $reply = "ok: $Jobs{$host}{type} of $host canceled";
1286 } elsif ( $BgQueueOn{$host} || $UserQueueOn{$host} ) {
1287 print(LOG $bpc->timeStamp,
1288 "Stopping pending backup of $host,"
1289 . " request by $user (backoff=$backoff)\n");
1290 @BgQueue = grep($_->{host} ne $host, @BgQueue);
1291 @UserQueue = grep($_->{host} ne $host, @UserQueue);
1292 $BgQueueOn{$host} = $UserQueueOn{$host} = 0;
1293 $reply = "ok: pending backup of $host canceled";
1295 print(LOG $bpc->timeStamp,
1296 "Nothing to do for stop backup of $host,"
1297 . " request by $user (backoff=$backoff)\n");
1298 $reply = "ok: no backup was pending or running";
1300 if ( defined($Status{$host}) && $backoff ne "" ) {
1301 if ( $backoff > 0 ) {
1302 $Status{$host}{backoffTime} = time + $backoff * 3600;
1304 delete($Status{$host}{backoffTime});
1307 } elsif ( $cmd =~ /^backup all$/ ) {
1309 } elsif ( $cmd =~ /^BackupPC_nightly run$/ ) {
1310 $RunNightlyWhenIdle = 1;
1311 } elsif ( $cmd =~ /^backup (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1316 $host = $bpc->uriUnesc($host);
1317 $hostIP = $bpc->uriUnesc($hostIP);
1318 if ( !defined($Status{$host}) ) {
1319 print(LOG $bpc->timeStamp,
1320 "User $user requested backup of unknown host"
1322 $reply = "error: unknown host $host";
1324 print(LOG $bpc->timeStamp,
1325 "User $user requested backup of $host"
1327 if ( $BgQueueOn{$hostIP} ) {
1328 @BgQueue = grep($_->{host} ne $hostIP, @BgQueue);
1329 $BgQueueOn{$hostIP} = 0;
1331 if ( $UserQueueOn{$hostIP} ) {
1332 @UserQueue = grep($_->{host} ne $hostIP, @UserQueue);
1333 $UserQueueOn{$hostIP} = 0;
1335 unshift(@UserQueue, {
1341 dhcp => $hostIP eq $host ? 0 : 1,
1343 $UserQueueOn{$hostIP} = 1;
1344 $reply = "ok: requested backup of $host";
1346 } elsif ( $cmd =~ /^archive (\S+)\s+(\S+)\s+(\S+)/ ) {
1348 my $archivehost = $2;
1349 my $reqFileName = $3;
1350 $host = $bpc->uriUnesc($archivehost);
1351 if ( !defined($Status{$host}) ) {
1352 print(LOG $bpc->timeStamp,
1353 "User $user requested archive of unknown archive host"
1355 $reply = "archive error: unknown archive host $host";
1357 print(LOG $bpc->timeStamp,
1358 "User $user requested archive on $host"
1360 if ( defined($Jobs{$host}) ) {
1361 $reply = "Archive currently running on $host, please try later";
1363 unshift(@UserQueue, {
1366 reqFileName => $reqFileName,
1372 $UserQueueOn{$host} = 1;
1373 $reply = "ok: requested archive on $host";
1376 } elsif ( $cmd =~ /^restore (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1380 my $reqFileName = $4;
1381 $host = $bpc->uriUnesc($host);
1382 $hostIP = $bpc->uriUnesc($hostIP);
1383 if ( !defined($Status{$host}) ) {
1384 print(LOG $bpc->timeStamp,
1385 "User $user requested restore to unknown host"
1387 $reply = "restore error: unknown host $host";
1389 print(LOG $bpc->timeStamp,
1390 "User $user requested restore to $host"
1392 unshift(@UserQueue, {
1395 reqFileName => $reqFileName,
1401 $UserQueueOn{$host} = 1;
1402 if ( defined($Jobs{$host}) ) {
1403 $reply = "ok: requested restore of $host, but a"
1404 . " job is currently running,"
1405 . " so this request will start later";
1407 $reply = "ok: requested restore of $host";
1410 } elsif ( $cmd =~ /^status\s*(.*)/ ) {
1412 my($dump, @values, @names);
1413 foreach my $type ( split(/\s+/, $args) ) {
1414 if ( $type =~ /^queues/ ) {
1415 push(@values, \@BgQueue, \@UserQueue, \@CmdQueue);
1416 push(@names, qw(*BgQueue *UserQueue *CmdQueue));
1417 } elsif ( $type =~ /^jobs/ ) {
1418 push(@values, \%Jobs);
1419 push(@names, qw(*Jobs));
1420 } elsif ( $type =~ /^queueLen/ ) {
1422 BgQueue => scalar(@BgQueue),
1423 UserQueue => scalar(@UserQueue),
1424 CmdQueue => scalar(@CmdQueue),
1426 push(@names, qw(*QueueLen));
1427 } elsif ( $type =~ /^info/ ) {
1428 push(@values, \%Info);
1429 push(@names, qw(*Info));
1430 } elsif ( $type =~ /^hosts/ ) {
1431 push(@values, \%Status);
1432 push(@names, qw(*Status));
1433 } elsif ( $type =~ /^host\((.*)\)/ ) {
1434 my $h = $bpc->uriUnesc($1);
1435 if ( defined($Status{$h}) ) {
1438 BgQueueOn => $BgQueueOn{$h},
1439 UserQueueOn => $UserQueueOn{$h},
1440 CmdQueueOn => $CmdQueueOn{$h},
1442 push(@names, qw(*StatusHost));
1444 print(LOG $bpc->timeStamp,
1445 "Unknown host $h for status request\n");
1448 print(LOG $bpc->timeStamp,
1449 "Unknown status request $type\n");
1452 $dump = Data::Dumper->new(\@values, \@names);
1454 $reply = $dump->Dump;
1455 } elsif ( $cmd =~ /^link\s+(.+)/ ) {
1457 $host = $bpc->uriUnesc($host);
1459 } elsif ( $cmd =~ /^log\s+(.*)/ ) {
1460 print(LOG $bpc->timeStamp, "$1\n");
1461 } elsif ( $cmd =~ /^server\s+(\w+)/ ) {
1463 if ( $type eq 'reload' ) {
1464 ServerReload("Reloading config/host files via CGI request");
1465 } elsif ( $type eq 'shutdown' ) {
1466 $reply = "Shutting down...\n";
1467 syswrite($Clients{$client}{fh}, $reply, length($reply));
1468 ServerShutdown("Server shutting down...");
1470 } elsif ( $cmd =~ /^quit/ || $cmd =~ /^exit/ ) {
1474 print(LOG $bpc->timeStamp, "Unknown command $cmd\n");
1475 $reply = "error: bad command $cmd";
1478 # send a reply to the client, at a minimum "ok\n".
1480 $reply = "ok" if ( $reply eq "" );
1482 syswrite($Clients{$client}{fh}, $reply, length($reply));
1485 # Detect possible denial-of-service attack from sending a huge line
1486 # (ie: never terminated). 32K seems to be plenty big enough as
1489 if ( length($Clients{$client}{mesg}) > 32 * 1024 ) {
1490 print(LOG $bpc->timeStamp, "Line too long from client"
1491 . " '$Clients{$client}{clientName}':"
1492 . " shutting down client connection\n");
1496 # Shut down the client connection if we read EOF
1498 if ( $nbytes <= 0 ) {
1499 close($Clients{$client}{fh});
1500 vec($FDread, $Clients{$client}{fn}, 1) = 0;
1501 delete($Clients{$client});
1505 # Accept any new connections on each of our listen sockets
1507 if ( vec($fdRead, fileno(SERVER_UNIX), 1) ) {
1509 my $paddr = accept(CLIENT, SERVER_UNIX);
1511 $Clients{$ClientConnCnt}{clientName} = "unix socket";
1512 $Clients{$ClientConnCnt}{mesg} = "";
1513 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1514 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1515 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1517 # Generate and send unique seed for MD5 digests to avoid
1518 # replay attacks. See BackupPC::Lib::ServerMesg().
1520 my $seed = time . ",$ClientConnCnt,$$,0\n";
1521 $Clients{$ClientConnCnt}{seed} = $seed;
1522 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1523 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1525 if ( $ServerInetPort > 0 && vec($fdRead, fileno(SERVER_INET), 1) ) {
1527 my $paddr = accept(CLIENT, SERVER_INET);
1528 my($port,$iaddr) = sockaddr_in($paddr);
1529 my $name = gethostbyaddr($iaddr, AF_INET);
1531 $Clients{$ClientConnCnt}{mesg} = "";
1532 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1533 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1534 $Clients{$ClientConnCnt}{clientName} = "$name:$port";
1535 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1537 # Generate and send unique seed for MD5 digests to avoid
1538 # replay attacks. See BackupPC::Lib::ServerMesg().
1540 my $seed = time . ",$ClientConnCnt,$$,$port\n";
1541 $Clients{$ClientConnCnt}{seed} = $seed;
1542 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1543 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1547 ###########################################################################
1548 # Miscellaneous subroutines
1549 ###########################################################################
1552 # Write the current status to $LogDir/status.pl
1556 my($dump) = Data::Dumper->new(
1557 [ \%Info, \%Status],
1558 [qw(*Info *Status)]);
1560 if ( open(STATUS, ">", "$LogDir/status.pl") ) {
1561 print(STATUS $dump->Dump);
1567 # Compare function for host sort. Hosts with errors go first,
1568 # sorted with the oldest errors first. The remaining hosts
1569 # are sorted so that those with the oldest backups go first.
1574 # Hosts with errors go before hosts without errors
1576 return -1 if ( $Status{$a}{error} ne "" && $Status{$b}{error} eq "" );
1579 # Hosts with no errors go after hosts with errors
1582 return 1 if ( $Status{$a}{error} eq "" && $Status{$b}{error} ne "" );
1585 # hosts with the older last good backups sort earlier
1587 my $r = $Status{$a}{lastGoodBackupTime} <=> $Status{$b}{lastGoodBackupTime};
1588 return $r if ( $r );
1591 # Finally, just sort based on host name
1597 # Queue all the hosts for backup. This means queuing all the fixed
1598 # ip hosts and all the dhcp address ranges. We also additionally
1599 # queue the dhcp hosts with a -e flag to check for expired dumps.
1604 foreach my $host ( sort(HostSortCompare keys(%$Hosts)) ) {
1605 delete($Status{$host}{backoffTime})
1606 if ( defined($Status{$host}{backoffTime})
1607 && $Status{$host}{backoffTime} < time );
1608 next if ( defined($Jobs{$host})
1609 || $BgQueueOn{$host}
1610 || $UserQueueOn{$host}
1611 || $CmdQueueOn{$host} );
1612 if ( $Hosts->{$host}{dhcp} ) {
1613 $Status{$host}{dhcpCheckCnt}++;
1614 if ( $RunNightlyWhenIdle ) {
1616 # Once per night queue a check for DHCP hosts that just
1617 # checks for expired dumps. We need to do this to handle
1618 # the case when a DHCP host has not been on the network for
1619 # a long time, and some of the old dumps need to be expired.
1620 # Normally expiry checks are done by BackupPC_dump only
1621 # after the DHCP hosts has been detected on the network.
1624 {host => $host, user => "BackupPC", reqTime => time,
1625 dhcp => 0, dumpExpire => 1});
1626 $BgQueueOn{$host} = 1;
1630 # this is a fixed ip host: queue it
1632 if ( $Info{DUlastValue} > $Conf{DfMaxUsagePct} ) {
1634 # Since we are out of disk space, instead of queuing
1635 # a regular job, queue an expire check instead. That
1636 # way if the admin reduces the number of backups to
1637 # keep then we will actually delete them. Otherwise
1638 # BackupPC_dump will never run since we have exceeded
1643 {host => $host, user => "BackupPC", reqTime => time,
1644 dhcp => $Hosts->{$host}{dhcp}, dumpExpire => 1});
1647 # Queue regular background backup
1650 {host => $host, user => "BackupPC", reqTime => time,
1651 dhcp => $Hosts->{$host}{dhcp}});
1653 $BgQueueOn{$host} = 1;
1657 print(LOG $bpc->timeStamp,
1658 "Disk too full ($Info{DUlastValue}%); skipped $nSkip hosts\n");
1659 $Info{DUDailySkipHostCnt} += $nSkip;
1661 foreach my $dhcp ( @{$Conf{DHCPAddressRanges}} ) {
1662 for ( my $i = $dhcp->{first} ; $i <= $dhcp->{last} ; $i++ ) {
1663 my $ipAddr = "$dhcp->{ipAddrBase}.$i";
1664 next if ( defined($Jobs{$ipAddr})
1665 || $BgQueueOn{$ipAddr}
1666 || $UserQueueOn{$ipAddr}
1667 || $CmdQueueOn{$ipAddr} );
1669 # this is a potential dhcp ip address (we don't know the
1670 # host name yet): queue it
1673 {host => $ipAddr, user => "BackupPC", reqTime => time,
1675 $BgQueueOn{$ipAddr} = 1;
1681 # Queue a BackupPC_link for the given host
1687 return if ( $CmdQueueOn{$host} );
1688 $Status{$host}{state} = "Status_link_pending";
1689 $Status{$host}{needLink} = 0;
1690 unshift(@CmdQueue, {
1694 cmd => ["$BinDir/BackupPC_link", $host],
1696 $CmdQueueOn{$host} = 1;
1700 # Read the hosts file, and update Status if any hosts have been
1701 # added or deleted. We also track the mtime so the only need to
1702 # update the hosts file on changes.
1704 # This function is called at startup, SIGHUP, and on each wakeup.
1705 # It returns 1 on success and undef on failure.
1712 # Nothing to do if we already have the current hosts file
1714 return 1 if ( !$force && defined($Hosts)
1715 && $Info{HostsModTime} == $bpc->HostsMTime() );
1716 if ( !defined($newHosts = $bpc->HostInfoRead()) ) {
1717 print(LOG $bpc->timeStamp, "Can't read hosts file!\n");
1720 print(LOG $bpc->timeStamp, "Reading hosts file\n");
1722 $Info{HostsModTime} = $bpc->HostsMTime();
1724 # Now update %Status in case any hosts have been added or deleted
1726 foreach my $host ( sort(keys(%$Hosts)) ) {
1727 next if ( defined($Status{$host}) );
1728 $Status{$host}{state} = "Status_idle";
1729 print(LOG $bpc->timeStamp, "Added host $host to backup list\n");
1731 foreach my $host ( sort(keys(%Status)) ) {
1732 next if ( $host eq $bpc->trashJob
1733 || $bpc->isAdminJob($host)
1734 || defined($Hosts->{$host})
1735 || defined($Jobs{$host})
1736 || $BgQueueOn{$host}
1737 || $UserQueueOn{$host}
1738 || $CmdQueueOn{$host} );
1739 print(LOG $bpc->timeStamp, "Deleted host $host from backup list\n");
1740 delete($Status{$host});
1746 # Remember the signal name for later processing
1752 foreach my $host ( keys(%Jobs) ) {
1753 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1756 # In case we are inside the exit handler, reopen the log file
1760 print(LOG "Fatal error: unhandled signal $SigName\n");
1761 unlink("$LogDir/BackupPC.pid");
1762 confess("Got new signal $SigName... quitting\n");
1769 # Open the log file and point STDOUT and STDERR there too
1773 mkpath($LogDir, 0, 0777) if ( !-d $LogDir );
1774 open(LOG, ">>$LogDir/LOG")
1775 || die("Can't create LOG file $LogDir/LOG");
1778 open(STDOUT, ">&LOG");
1779 open(STDERR, ">&LOG");
1780 select(LOG); $| = 1;
1781 select(STDERR); $| = 1;
1782 select(STDOUT); $| = 1;
1786 # Initialize the unix-domain and internet-domain sockets that
1787 # we listen to for client connections (from the CGI script and
1788 # some of the BackupPC sub-programs).
1790 sub ServerSocketInit
1792 if ( !defined(fileno(SERVER_UNIX)) ) {
1794 # one-time only: initialize unix-domain socket
1796 if ( !socket(SERVER_UNIX, PF_UNIX, SOCK_STREAM, 0) ) {
1797 print(LOG $bpc->timeStamp, "unix socket() failed: $!\n");
1800 my $sockFile = "$LogDir/BackupPC.sock";
1802 if ( !bind(SERVER_UNIX, sockaddr_un($sockFile)) ) {
1803 print(LOG $bpc->timeStamp, "unix bind() failed: $!\n");
1806 if ( !listen(SERVER_UNIX, SOMAXCONN) ) {
1807 print(LOG $bpc->timeStamp, "unix listen() failed: $!\n");
1810 vec($FDread, fileno(SERVER_UNIX), 1) = 1;
1812 return if ( $ServerInetPort == $Conf{ServerPort} );
1813 if ( $ServerInetPort > 0 ) {
1814 vec($FDread, fileno(SERVER_INET), 1) = 0;
1816 $ServerInetPort = -1;
1818 if ( $Conf{ServerPort} > 0 ) {
1820 # Setup a socket to listen on $Conf{ServerPort}
1822 my $proto = getprotobyname('tcp');
1823 if ( !socket(SERVER_INET, PF_INET, SOCK_STREAM, $proto) ) {
1824 print(LOG $bpc->timeStamp, "inet socket() failed: $!\n");
1827 if ( !setsockopt(SERVER_INET, SOL_SOCKET, SO_REUSEADDR, pack("l",1)) ) {
1828 print(LOG $bpc->timeStamp, "setsockopt() failed: $!\n");
1831 if ( !bind(SERVER_INET, sockaddr_in($Conf{ServerPort}, INADDR_ANY)) ) {
1832 print(LOG $bpc->timeStamp, "inet bind() failed: $!\n");
1835 if ( !listen(SERVER_INET, SOMAXCONN) ) {
1836 print(LOG $bpc->timeStamp, "inet listen() failed: $!\n");
1839 vec($FDread, fileno(SERVER_INET), 1) = 1;
1840 $ServerInetPort = $Conf{ServerPort};
1845 # Reload the server. Used by Main_Process_Signal when $SigName eq "HUP"
1846 # or when the command "server reload" is received.
1851 $mesg = $bpc->ConfigRead() || $mesg;
1852 print(LOG $bpc->timeStamp, "$mesg\n");
1853 $Info{ConfigModTime} = $bpc->ConfigMTime();
1854 %Conf = $bpc->Conf();
1855 umask($Conf{UmaskMode});
1859 $Info{ConfigLTime} = time;
1863 # Gracefully shutdown the server. Used by Main_Process_Signal when
1864 # $SigName ne "" && $SigName ne "HUP" or when the command
1865 # "server shutdown" is received.
1870 print(LOG $bpc->timeStamp, "$mesg\n");
1871 if ( keys(%Jobs) ) {
1872 foreach my $host ( keys(%Jobs) ) {
1873 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1876 foreach my $host ( keys(%Jobs) ) {
1877 kill($bpc->sigName2num("KILL"), $Jobs{$host}{pid});
1883 unlink("$LogDir/BackupPC.pid");