2 #============================================================= -*-perl-*-
4 # BackupPC: Main program for PC backups.
8 # BackupPC reads the configuration and status information from
9 # $TopDir/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 2.1.0, released 20 Jun 2004.
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;
70 ###########################################################################
71 # Handle command line options
72 ###########################################################################
74 if ( !getopts("d", \%opts) || @ARGV != 0 ) {
75 print("usage: $0 [-d]\n");
79 ###########################################################################
80 # Initialize major data structures and variables
81 ###########################################################################
84 # Get an instance of BackupPC::Lib and get some shortcuts.
86 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
87 my $TopDir = $bpc->TopDir();
88 my $BinDir = $bpc->BinDir();
89 my %Conf = $bpc->Conf();
92 # Verify we are running as the correct user
94 if ( $Conf{BackupPCUserVerify}
95 && $> != (my $uid = (getpwnam($Conf{BackupPCUser}))[2]) ) {
96 die "Wrong user: my userid is $>, instead of $uid ($Conf{BackupPCUser})\n";
100 # %Status maintain status information about each host.
101 # It is a hash of hashes, whose first index is the host.
106 # %Info is a hash giving general information about BackupPC status.
113 if ( -f "$TopDir/log/status.pl" && !(my $ret = do "$TopDir/log/status.pl") ) {
114 die "couldn't parse $TopDir/log/status.pl: $@" if $@;
115 die "couldn't do $TopDir/log/status.pl: $!" unless defined $ret;
116 die "couldn't run $TopDir/log/status.pl";
120 # %Jobs maintains information about currently running jobs.
121 # It is a hash of hashes, whose first index is the host.
126 # There are three command queues:
127 # - @UserQueue is a queue of user initiated backup requests.
128 # - @BgQueue is a queue of automatically scheduled backup requests.
129 # - @CmdQueue is a queue of administrative jobs, including tasks
130 # like BackupPC_link, BackupPC_trashClean, and BackupPC_nightly
131 # Each queue is an array of hashes. Each hash stores information
132 # about the command request.
139 # To quickly lookup if a given host is on a given queue, we keep
140 # a hash of flags for each queue type.
142 my(%CmdQueueOn, %UserQueueOn, %BgQueueOn);
145 # One or more clients can connect to the server to get status information
146 # or request/cancel backups etc. The %Clients hash maintains information
147 # about each of these socket connections. The hash key is an incrementing
148 # number stored in $ClientConnCnt. Each entry is a hash that contains
149 # various information about the client connection.
155 # Read file descriptor mask used by select(). Every file descriptor
156 # on which we expect to read (or accept) has the corresponding bit
162 # Unix seconds when we next wakeup. A value of zero forces the scheduler
163 # to compute the next wakeup time.
168 # Name of signal saved by catch_signal
175 my($RunNightlyWhenIdle, $FirstWakeup, $CmdJob, $ServerInetPort);
176 my($BackupPCNightlyJobs, $BackupPCNightlyLock);
179 # Complete the rest of the initialization
183 ###########################################################################
185 ###########################################################################
189 # Check if we can/should run BackupPC_nightly
191 Main_TryToRun_nightly();
194 # Check if we can run a new command from @CmdQueue.
196 Main_TryToRun_CmdQueue();
199 # Check if we can run a new command from @UserQueue or @BgQueue.
201 Main_TryToRun_Bg_or_User_Queue();
204 # Do a select() to wait for the next interesting thing to happen
205 # (timeout, signal, someone sends a message, child dies etc).
207 my $fdRead = Main_Select();
210 # Process a signal if we received one.
213 Main_Process_Signal();
218 # Check if a timeout has occurred.
220 Main_Check_Timeout();
223 # Check for, and process, any messages (output) from our jobs
225 Main_Check_Job_Messages($fdRead);
228 # Check for, and process, any output from our clients. Also checks
229 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
231 Main_Check_Client_Messages($fdRead);
234 ############################################################################
237 # Main initialization routine. Called once at statup.
238 ############################################################################
241 umask($Conf{UmaskMode});
244 # Check for another running process, check that PASSWD is set and
245 # verify executables are configured correctly.
247 if ( $Info{pid} ne "" && kill(0, $Info{pid}) ) {
248 print(STDERR $bpc->timeStamp,
249 "Another BackupPC is running (pid $Info{pid}); quitting...\n");
252 foreach my $progName ( qw(SmbClientPath NmbLookupPath PingPath DfPath
253 SendmailPath SshPath) ) {
254 next if ( $Conf{$progName} eq "" || -x $Conf{$progName} );
255 print(STDERR $bpc->timeStamp,
256 "\$Conf{$progName} = '$Conf{$progName}' is not a"
257 . " valid executable program\n");
263 # daemonize by forking
265 defined(my $pid = fork) or die "Can't fork: $!";
266 exit if $pid; # parent exits
270 # Open the LOG file and redirect STDOUT, STDERR etc
275 # Read the hosts file (force a read).
277 exit(1) if ( !HostsUpdate(1) );
280 # Clean up %ENV for taint checking
282 delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
283 $ENV{PATH} = $Conf{MyPath};
286 # Initialize server sockets
291 # Catch various signals
293 foreach my $sig ( qw(INT BUS SEGV PIPE TERM ALRM HUP) ) {
294 $SIG{$sig} = \&catch_signal;
298 # Report that we started, and update %Info.
300 print(LOG $bpc->timeStamp, "BackupPC started, pid $$\n");
301 $Info{ConfigModTime} = $bpc->ConfigMTime();
303 $Info{startTime} = time;
304 $Info{ConfigLTime} = time;
305 $Info{Version} = $bpc->{Version};
308 # Update the status left over form the last time BackupPC ran.
309 # Requeue any pending links.
311 foreach my $host ( sort(keys(%$Hosts)) ) {
312 if ( $Status{$host}{state} eq "Status_backup_in_progress" ) {
314 # should we restart it? skip it for now.
316 $Status{$host}{state} = "Status_idle";
317 } elsif ( $Status{$host}{state} eq "Status_link_pending"
318 || $Status{$host}{state} eq "Status_link_running" ) {
321 $Status{$host}{state} = "Status_idle";
323 $Status{$host}{activeJob} = 0;
325 foreach my $host ( sort(keys(%Status)) ) {
326 next if ( defined($Hosts->{$host}) );
327 delete($Status{$host});
331 # Write out our initial status and save our PID
334 if ( open(PID, ">", "$TopDir/log/BackupPC.pid") ) {
340 # For unknown reasons there is a very infrequent error about not
341 # being able to coerce GLOBs inside the XS Data::Dumper. I've
342 # only seen this on a particular platform and perl version.
343 # For now the workaround appears to be use the perl version of
346 $Data::Dumper::Useqq = 1;
349 ############################################################################
350 # Main_TryToRun_nightly()
352 # Checks to see if we can/should run BackupPC_nightly or
353 # BackupPC_trashClean. If so we push the appropriate command onto
355 ############################################################################
356 sub Main_TryToRun_nightly
359 # Check if we should run BackupPC_nightly or BackupPC_trashClean.
360 # BackupPC_nightly is run when the current job queue is empty.
361 # BackupPC_trashClean is run in the background always.
363 my $trashCleanRunning = defined($Jobs{$bpc->trashJob}) ? 1 : 0;
364 if ( !$trashCleanRunning && !$CmdQueueOn{$bpc->trashJob} ) {
366 # This should only happen once at startup, but just in case this
367 # code will re-start BackupPC_trashClean if it quits
370 host => $bpc->trashJob,
373 cmd => ["$BinDir/BackupPC_trashClean"],
375 $CmdQueueOn{$bpc->trashJob} = 1;
377 if ( keys(%Jobs) == $trashCleanRunning && $RunNightlyWhenIdle == 1 ) {
380 # Queue multiple nightly jobs based on the configuration
382 $Conf{MaxBackupPCNightlyJobs} = 1
383 if ( $Conf{MaxBackupPCNightlyJobs} <= 0 );
384 $Conf{BackupPCNightlyPeriod} = 1
385 if ( $Conf{BackupPCNightlyPeriod} <= 0 );
387 # Decide what subset of the 16 top-level directories 0..9a..f
388 # we run BackupPC_nightly on, based on $Conf{BackupPCNightlyPeriod}.
389 # If $Conf{BackupPCNightlyPeriod} == 1 then we run 0..15 every
390 # time. If $Conf{BackupPCNightlyPeriod} == 2 then we run
391 # 0..7 one night and 89a-f the next night. And so on.
393 # $Info{NightlyPhase} counts which night, from 0 to
394 # $Conf{BackupPCNightlyPeriod} - 1.
396 my $start = int($Info{NightlyPhase} * 16
397 / $Conf{BackupPCNightlyPeriod});
398 my $end = int(($Info{NightlyPhase} + 1) * 16
399 / $Conf{BackupPCNightlyPeriod});
400 $end = $start + 1 if ( $end <= $start );
401 $Info{NightlyPhase}++;
402 $Info{NightlyPhase} = 0 if ( $end >= 16 );
405 # Zero out the data we expect to get from BackupPC_nightly.
406 # In the future if we want to split BackupPC_nightly over
407 # more than one night we will only zero out the portion
408 # that we are running right now.
410 for my $p ( qw(pool cpool) ) {
411 for ( my $i = $start ; $i < $end ; $i++ ) {
412 $Info{pool}{$p}[$i]{FileCnt} = 0;
413 $Info{pool}{$p}[$i]{DirCnt} = 0;
414 $Info{pool}{$p}[$i]{Kb} = 0;
415 $Info{pool}{$p}[$i]{Kb2} = 0;
416 $Info{pool}{$p}[$i]{KbRm} = 0;
417 $Info{pool}{$p}[$i]{FileCntRm} = 0;
418 $Info{pool}{$p}[$i]{FileCntRep} = 0;
419 $Info{pool}{$p}[$i]{FileRepMax} = 0;
420 $Info{pool}{$p}[$i]{FileCntRename} = 0;
421 $Info{pool}{$p}[$i]{FileLinkMax} = 0;
422 $Info{pool}{$p}[$i]{Time} = 0;
425 print(LOG $bpc->timeStamp,
426 sprintf("Running %d BackupPC_nightly jobs from %d..%d"
427 . " (out of 0..15)\n",
428 $Conf{MaxBackupPCNightlyJobs}, $start, $end - 1));
431 # Now queue the $Conf{MaxBackupPCNightlyJobs} jobs.
432 # The granularity on start and end is now 0..256.
437 for ( my $i = 0 ; $i < $Conf{MaxBackupPCNightlyJobs} ; $i++ ) {
439 # The first nightly job gets the -m option (does email, log aging).
440 # All jobs get the start and end options from 0..255 telling
441 # them which parts of the pool to traverse.
443 my $cmd = ["$BinDir/BackupPC_nightly"];
444 push(@$cmd, "-m") if ( $i == 0 );
446 $start = $start0 + int(($end - $start0)
447 * ($i + 1) / $Conf{MaxBackupPCNightlyJobs});
448 push(@$cmd, $start - 1);
450 my $job = $bpc->adminJob($i);
457 $CmdQueueOn{$job} = 1;
459 $RunNightlyWhenIdle = 2;
464 ############################################################################
465 # Main_TryToRun_CmdQueue()
467 # Decide if we can run a new command from the @CmdQueue.
468 # We only run one of these at a time. The @CmdQueue is
469 # used to run BackupPC_link (for the corresponding host),
470 # BackupPC_trashClean, and BackupPC_nightly using a fake
471 # host name of $bpc->adminJob.
472 ############################################################################
473 sub Main_TryToRun_CmdQueue
477 while ( $CmdJob eq "" && @CmdQueue > 0 && $RunNightlyWhenIdle != 1
478 || @CmdQueue > 0 && $RunNightlyWhenIdle == 2
479 && $bpc->isAdminJob($CmdQueue[0]->{host})
482 $req = pop(@CmdQueue);
484 $host = $req->{host};
485 if ( defined($Jobs{$host}) ) {
486 print(LOG $bpc->timeStamp,
487 "Botch on admin job for $host: already in use!!\n");
489 # This could happen during normal opertion: a user could
490 # request a backup while a BackupPC_link is queued from
491 # a previous backup. But it is unlikely. Just put this
492 # request back on the end of the queue.
494 unshift(@CmdQueue, $req);
497 $CmdQueueOn{$host} = 0;
498 my $cmd = $req->{cmd};
499 my $pid = open(FH, "-|");
500 if ( !defined($pid) ) {
501 print(LOG $bpc->timeStamp,
502 "can't fork for $host, request by $req->{user}\n");
509 print(LOG $bpc->timeStamp, "can't exec @$cmd for $host\n");
512 $Jobs{$host}{pid} = $pid;
513 $Jobs{$host}{fh} = *FH;
514 $Jobs{$host}{fn} = fileno(FH);
515 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
516 $Jobs{$host}{startTime} = time;
517 $Jobs{$host}{reqTime} = $req->{reqTime};
518 $cmd = $bpc->execCmd2ShellCmd(@$cmd);
519 $Jobs{$host}{cmd} = $cmd;
520 $Jobs{$host}{user} = $req->{user};
521 $Jobs{$host}{type} = $Status{$host}{type};
522 $Status{$host}{state} = "Status_link_running";
523 $Status{$host}{activeJob} = 1;
524 $Status{$host}{endTime} = time;
525 $CmdJob = $host if ( $host ne $bpc->trashJob );
526 $cmd =~ s/$BinDir\///g;
527 print(LOG $bpc->timeStamp, "Running $cmd (pid=$pid)\n");
528 if ( $cmd =~ /^BackupPC_nightly\s/ ) {
529 $BackupPCNightlyJobs++;
530 $BackupPCNightlyLock++;
535 ############################################################################
536 # Main_TryToRun_Bg_or_User_Queue()
538 # Decide if we can run any new backup requests from @BgQueue
539 # or @UserQueue. Several of these can be run at the same time
540 # based on %Conf settings. Jobs from @UserQueue take priority,
541 # and at total of $Conf{MaxBackups} + $Conf{MaxUserBackups}
542 # simultaneous jobs can run from @UserQueue. After @UserQueue
543 # is exhausted, up to $Conf{MaxBackups} simultaneous jobs can
545 ############################################################################
546 sub Main_TryToRun_Bg_or_User_Queue
549 my(@deferUserQueue, @deferBgQueue);
552 if ( time - $Info{DUlastValueTime} >= 600 ) {
554 # Update our notion of disk usage no more than
555 # once every 10 minutes
557 $du = $bpc->CheckFileSystemUsage($TopDir);
558 $Info{DUlastValue} = $du;
559 $Info{DUlastValueTime} = time;
562 # if we recently checked it then just use the old value
564 $du = $Info{DUlastValue};
566 if ( $Info{DUDailyMaxReset} ) {
567 $Info{DUDailyMaxStartTime} = time;
568 $Info{DUDailyMaxReset} = 0;
569 $Info{DUDailyMax} = 0;
571 if ( $du > $Info{DUDailyMax} ) {
572 $Info{DUDailyMax} = $du;
573 $Info{DUDailyMaxTime} = time;
575 if ( $du > $Conf{DfMaxUsagePct} ) {
576 my @bgQueue = @BgQueue;
580 # When the disk is too full, only run backups that will
581 # do expires, not regular backups
584 foreach $req ( @bgQueue ) {
585 if ( $req->{dumpExpire} ) {
586 unshift(@BgQueue, $req);
588 $BgQueueOn{$req->{host}} = 0;
593 print(LOG $bpc->timeStamp,
594 "Disk too full ($du%); skipped $nSkip hosts\n");
595 $Info{DUDailySkipHostCnt} += $nSkip;
599 while ( $RunNightlyWhenIdle == 0 ) {
601 my(@args, $progName, $type);
602 my $nJobs = keys(%Jobs);
604 # CmdJob and trashClean don't count towards MaxBackups / MaxUserBackups
606 if ( $CmdJob ne "" ) {
607 if ( $BackupPCNightlyJobs ) {
608 $nJobs -= $BackupPCNightlyJobs;
613 $nJobs-- if ( defined($Jobs{$bpc->trashJob} ) );
614 if ( $nJobs < $Conf{MaxBackups} + $Conf{MaxUserBackups}
615 && @UserQueue > 0 ) {
616 $req = pop(@UserQueue);
617 if ( defined($Jobs{$req->{host}}) ) {
618 push(@deferUserQueue, $req);
621 push(@args, $req->{doFull} ? "-f" : "-i")
622 if (( !$req->{restore} ) && ( !$req->{archive} ));
623 $UserQueueOn{$req->{host}} = 0;
624 } elsif ( $nJobs < $Conf{MaxBackups}
625 && (@CmdQueue + $nJobs)
626 <= $Conf{MaxBackups} + $Conf{MaxPendingCmds}
628 $req = pop(@BgQueue);
629 if ( defined($Jobs{$req->{host}}) ) {
631 # Job is currently running for this host; save it for later
633 unshift(@deferBgQueue, $req);
636 $BgQueueOn{$req->{host}} = 0;
639 # Restore the deferred jobs
641 @BgQueue = (@BgQueue, @deferBgQueue);
642 @UserQueue = (@UserQueue, @deferUserQueue);
645 $host = $req->{host};
646 my $user = $req->{user};
647 if ( $req->{restore} ) {
648 $progName = "BackupPC_restore";
650 push(@args, $req->{hostIP}, $req->{host}, $req->{reqFileName});
651 } elsif ( $req->{archive} ) {
652 $progName = "BackupPC_archive";
654 push(@args, $req->{user}, $req->{host}, $req->{reqFileName});
656 $progName = "BackupPC_dump";
658 push(@args, "-d") if ( $req->{dhcp} );
659 push(@args, "-e") if ( $req->{dumpExpire} );
662 my $pid = open(FH, "-|");
663 if ( !defined($pid) ) {
664 print(LOG $bpc->timeStamp,
665 "can't fork to run $progName for $host, request by $user\n");
671 exec("$BinDir/$progName", @args);
672 print(LOG $bpc->timeStamp, "can't exec $progName for $host\n");
675 $Jobs{$host}{pid} = $pid;
676 $Jobs{$host}{fh} = *FH;
677 $Jobs{$host}{fn} = fileno(FH);
678 $Jobs{$host}{dhcp} = $req->{dhcp};
679 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
680 $Jobs{$host}{startTime} = time;
681 $Jobs{$host}{reqTime} = $req->{reqTime};
682 $Jobs{$host}{userReq} = $req->{userReq};
683 $Jobs{$host}{cmd} = $bpc->execCmd2ShellCmd($progName, @args);
684 $Jobs{$host}{user} = $user;
685 $Jobs{$host}{type} = $type;
686 $Status{$host}{userReq} = $req->{userReq}
687 if ( defined($Hosts->{$host}) );
688 if ( !$req->{dhcp} ) {
689 $Status{$host}{state} = "Status_".$type."_starting";
690 $Status{$host}{activeJob} = 1;
691 $Status{$host}{startTime} = time;
692 $Status{$host}{endTime} = "";
697 ############################################################################
700 # If necessary, figure out when to next wakeup based on $Conf{WakeupSchedule},
701 # and then do a select() to wait for the next thing to happen
702 # (timeout, signal, someone sends a message, child dies etc).
703 ############################################################################
706 if ( $NextWakeup <= 0 ) {
708 # Figure out when to next wakeup based on $Conf{WakeupSchedule}.
710 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
712 my($currHours) = $hour + $min / 60 + $sec / 3600;
713 if ( $bpc->ConfigMTime() != $Info{ConfigModTime} ) {
714 ServerReload("Re-read config file because mtime changed");
717 foreach my $t ( @{$Conf{WakeupSchedule} || [0..23]} ) {
718 next if ( $t < 0 || $t > 24 );
719 my $tomorrow = $t + 24;
721 || ($tomorrow - $currHours > 0
722 && $delta > $tomorrow - $currHours) ) {
723 $delta = $tomorrow - $currHours;
724 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
727 || ($t - $currHours > 0 && $delta > $t - $currHours) ) {
728 $delta = $t - $currHours;
729 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
732 $NextWakeup = time + $delta * 3600;
733 $Info{nextWakeup} = $NextWakeup;
734 print(LOG $bpc->timeStamp, "Next wakeup is ",
735 $bpc->timeStamp($NextWakeup, 1), "\n");
738 # Call select(), waiting until either a signal, a timeout,
739 # any output from our jobs, or any messages from clients
741 # select() is where we (hopefully) spend most of our time blocked...
743 my $timeout = $NextWakeup - time;
744 $timeout = 1 if ( $timeout <= 0 );
746 select(my $rout = $FDread, undef, $ein, $timeout);
751 ############################################################################
752 # Main_Process_Signal()
755 ############################################################################
756 sub Main_Process_Signal
761 if ( $SigName eq "HUP" ) {
762 ServerReload("Re-read config file because of a SIG_HUP");
763 } elsif ( $SigName ) {
764 ServerShutdown("Got signal $SigName... cleaning up");
769 ############################################################################
770 # Main_Check_Timeout()
772 # Check if a timeout has occured, and if so, queue all the PCs for backups.
773 # Also does log file aging on the first timeout after midnight.
774 ############################################################################
775 sub Main_Check_Timeout
780 return if ( time < $NextWakeup || $NextWakeup <= 0 );
782 if ( $FirstWakeup ) {
784 # This is the first wakeup after midnight. Do log file aging
785 # and various house keeping.
788 printf(LOG "%s24hr disk usage: %d%% max, %d%% recent,"
789 . " %d skipped hosts\n",
790 $bpc->timeStamp, $Info{DUDailyMax}, $Info{DUlastValue},
791 $Info{DUDailySkipHostCnt});
792 $Info{DUDailyMaxReset} = 1;
793 $Info{DUDailyMaxPrev} = $Info{DUDailyMax};
794 $Info{DUDailySkipHostCntPrev} = $Info{DUDailySkipHostCnt};
795 $Info{DUDailySkipHostCnt} = 0;
796 my $lastLog = $Conf{MaxOldLogFiles} - 1;
797 if ( -f "$TopDir/log/LOG.$lastLog" ) {
798 print(LOG $bpc->timeStamp,
799 "Removing $TopDir/log/LOG.$lastLog\n");
800 unlink("$TopDir/log/LOG.$lastLog");
802 if ( -f "$TopDir/log/LOG.$lastLog.z" ) {
803 print(LOG $bpc->timeStamp,
804 "Removing $TopDir/log/LOG.$lastLog.z\n");
805 unlink("$TopDir/log/LOG.$lastLog.z");
807 print(LOG $bpc->timeStamp, "Aging LOG files, LOG -> LOG.0 -> "
808 . "LOG.1 -> ... -> LOG.$lastLog\n");
809 close(STDERR); # dup of LOG
810 close(STDOUT); # dup of LOG
812 for ( my $i = $lastLog - 1 ; $i >= 0 ; $i-- ) {
814 rename("$TopDir/log/LOG.$i", "$TopDir/log/LOG.$j")
815 if ( -f "$TopDir/log/LOG.$i" );
816 rename("$TopDir/log/LOG.$i.z", "$TopDir/log/LOG.$j.z")
817 if ( -f "$TopDir/log/LOG.$i.z" );
820 # Compress the log file LOG -> LOG.0.z (if enabled).
821 # Otherwise, just rename LOG -> LOG.0.
823 BackupPC::FileZIO->compressCopy("$TopDir/log/LOG",
824 "$TopDir/log/LOG.0.z",
826 $Conf{CompressLevel}, 1);
829 # Remember to run nightly script after current jobs are done
831 $RunNightlyWhenIdle = 1;
834 # Write out the current status and then queue all the PCs
838 %BgQueueOn = () if ( @BgQueue == 0 );
839 %UserQueueOn = () if ( @UserQueue == 0 );
840 %CmdQueueOn = () if ( @CmdQueue == 0 );
844 ############################################################################
845 # Main_Check_Job_Messages($fdRead)
847 # Check if select() says we have bytes waiting from any of our jobs.
848 # Handle each of the messages when complete (newline terminated).
849 ############################################################################
850 sub Main_Check_Job_Messages
853 foreach my $host ( keys(%Jobs) ) {
854 next if ( !vec($fdRead, $Jobs{$host}{fn}, 1) );
857 # do a last check to make sure there is something to read so
858 # we are absolutely sure we won't block.
860 vec(my $readMask, $Jobs{$host}{fn}, 1) = 1;
861 if ( !select($readMask, undef, undef, 0.0) ) {
862 print(LOG $bpc->timeStamp, "Botch in Main_Check_Job_Messages:"
863 . " nothing to read from $host. Debug dump:\n");
864 my($dump) = Data::Dumper->new(
865 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
866 [qw(*Clients, *Jobs *FDread, *fdRead)]);
868 print(LOG $dump->Dump);
871 my $nbytes = sysread($Jobs{$host}{fh}, $mesg, 1024);
872 $Jobs{$host}{mesg} .= $mesg if ( $nbytes > 0 );
874 # Process any complete lines of output from this jobs.
875 # Any output to STDOUT or STDERR from the children is processed here.
877 while ( $Jobs{$host}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
879 $Jobs{$host}{mesg} = $2;
880 if ( $Jobs{$host}{dhcp} ) {
881 if ( $mesg =~ /^DHCP (\S+) (\S+)/ ) {
882 my $newHost = $bpc->uriUnesc($2);
883 if ( defined($Jobs{$newHost}) ) {
884 print(LOG $bpc->timeStamp,
885 "Backup on $newHost is already running\n");
886 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
890 $Jobs{$host}{dhcpHostIP} = $host;
891 $Status{$newHost}{dhcpHostIP} = $host;
892 $Jobs{$newHost} = $Jobs{$host};
893 delete($Jobs{$host});
895 $Status{$host}{state} = "Status_backup_starting";
896 $Status{$host}{activeJob} = 1;
897 $Status{$host}{startTime} = $Jobs{$host}{startTime};
898 $Status{$host}{endTime} = "";
899 $Jobs{$host}{dhcp} = 0;
901 print(LOG $bpc->timeStamp, "dhcp $host: $mesg\n");
903 } elsif ( $mesg =~ /^started (.*) dump, share=(.*)/ ) {
904 $Jobs{$host}{type} = $1;
905 $Jobs{$host}{shareName} = $2;
906 print(LOG $bpc->timeStamp,
907 "Started $1 backup on $host (pid=$Jobs{$host}{pid}",
908 $Jobs{$host}{dhcpHostIP}
909 ? ", dhcp=$Jobs{$host}{dhcpHostIP}" : "",
910 ", share=$Jobs{$host}{shareName})\n");
911 $Status{$host}{state} = "Status_backup_in_progress";
912 $Status{$host}{reason} = "";
913 $Status{$host}{type} = $1;
914 $Status{$host}{startTime} = time;
915 $Status{$host}{deadCnt} = 0;
916 $Status{$host}{aliveCnt}++;
917 $Status{$host}{dhcpCheckCnt}--
918 if ( $Status{$host}{dhcpCheckCnt} > 0 );
919 } elsif ( $mesg =~ /^xferPids (.*)/ ) {
920 $Jobs{$host}{xferPid} = $1;
921 } elsif ( $mesg =~ /^started_restore/ ) {
922 $Jobs{$host}{type} = "restore";
923 print(LOG $bpc->timeStamp,
924 "Started restore on $host"
925 . " (pid=$Jobs{$host}{pid})\n");
926 $Status{$host}{state} = "Status_restore_in_progress";
927 $Status{$host}{reason} = "";
928 $Status{$host}{type} = "restore";
929 $Status{$host}{startTime} = time;
930 $Status{$host}{deadCnt} = 0;
931 $Status{$host}{aliveCnt}++;
932 } elsif ( $mesg =~ /^started_archive/ ) {
933 $Jobs{$host}{type} = "archive";
934 print(LOG $bpc->timeStamp,
935 "Started archive on $host"
936 . " (pid=$Jobs{$host}{pid})\n");
937 $Status{$host}{state} = "Status_archive_in_progress";
938 $Status{$host}{reason} = "";
939 $Status{$host}{type} = "archive";
940 $Status{$host}{startTime} = time;
941 $Status{$host}{deadCnt} = 0;
942 $Status{$host}{aliveCnt}++;
943 } elsif ( $mesg =~ /^(full|incr) backup complete/ ) {
944 print(LOG $bpc->timeStamp, "Finished $1 backup on $host\n");
945 $Status{$host}{reason} = "Reason_backup_done";
946 delete($Status{$host}{error});
947 delete($Status{$host}{errorTime});
948 $Status{$host}{endTime} = time;
949 $Status{$host}{lastGoodBackupTime} = time;
950 } elsif ( $mesg =~ /^backups disabled/ ) {
951 print(LOG $bpc->timeStamp,
952 "Ignoring old backup error on $host\n");
953 $Status{$host}{reason} = "Reason_backup_done";
954 delete($Status{$host}{error});
955 delete($Status{$host}{errorTime});
956 $Status{$host}{endTime} = time;
957 } elsif ( $mesg =~ /^restore complete/ ) {
958 print(LOG $bpc->timeStamp, "Finished restore on $host\n");
959 $Status{$host}{reason} = "Reason_restore_done";
960 delete($Status{$host}{error});
961 delete($Status{$host}{errorTime});
962 $Status{$host}{endTime} = time;
963 } elsif ( $mesg =~ /^archive complete/ ) {
964 print(LOG $bpc->timeStamp, "Finished archive on $host\n");
965 $Status{$host}{reason} = "Reason_archive_done";
966 delete($Status{$host}{error});
967 delete($Status{$host}{errorTime});
968 $Status{$host}{endTime} = time;
969 } elsif ( $mesg =~ /^nothing to do/ ) {
970 if ( $Status{$host}{reason} ne "Reason_backup_failed"
971 && $Status{$host}{reason} ne "Reason_restore_failed" ) {
972 $Status{$host}{state} = "Status_idle";
973 $Status{$host}{reason} = "Reason_nothing_to_do";
974 $Status{$host}{startTime} = time;
976 $Status{$host}{dhcpCheckCnt}--
977 if ( $Status{$host}{dhcpCheckCnt} > 0 );
978 } elsif ( $mesg =~ /^no ping response/
979 || $mesg =~ /^ping too slow/
980 || $mesg =~ /^host not found/ ) {
981 $Status{$host}{state} = "Status_idle";
982 if ( $Status{$host}{userReq}
983 || $Status{$host}{reason} ne "Reason_backup_failed"
984 || $Status{$host}{error} =~ /^aborted by user/ ) {
985 $Status{$host}{reason} = "Reason_no_ping";
986 $Status{$host}{error} = $mesg;
987 $Status{$host}{startTime} = time;
989 $Status{$host}{deadCnt}++;
990 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
991 $Status{$host}{aliveCnt} = 0;
993 } elsif ( $mesg =~ /^dump failed: (.*)/ ) {
994 $Status{$host}{state} = "Status_idle";
995 $Status{$host}{error} = $1;
996 $Status{$host}{errorTime} = time;
997 $Status{$host}{endTime} = time;
998 if ( $Status{$host}{reason}
999 eq "Reason_backup_canceled_by_user" ) {
1000 print(LOG $bpc->timeStamp,
1001 "Backup canceled on $host ($1)\n");
1003 $Status{$host}{reason} = "Reason_backup_failed";
1004 print(LOG $bpc->timeStamp,
1005 "Backup failed on $host ($1)\n");
1007 } elsif ( $mesg =~ /^restore failed: (.*)/ ) {
1008 $Status{$host}{state} = "Status_idle";
1009 $Status{$host}{error} = $1;
1010 $Status{$host}{errorTime} = time;
1011 $Status{$host}{endTime} = time;
1012 if ( $Status{$host}{reason}
1013 eq "Reason_restore_canceled_by_user" ) {
1014 print(LOG $bpc->timeStamp,
1015 "Restore canceled on $host ($1)\n");
1017 $Status{$host}{reason} = "Reason_restore_failed";
1018 print(LOG $bpc->timeStamp,
1019 "Restore failed on $host ($1)\n");
1021 } elsif ( $mesg =~ /^archive failed: (.*)/ ) {
1022 $Status{$host}{state} = "Status_idle";
1023 $Status{$host}{error} = $1;
1024 $Status{$host}{errorTime} = time;
1025 $Status{$host}{endTime} = time;
1026 if ( $Status{$host}{reason}
1027 eq "Reason_archive_canceled_by_user" ) {
1028 print(LOG $bpc->timeStamp,
1029 "Archive canceled on $host ($1)\n");
1031 $Status{$host}{reason} = "Reason_archive_failed";
1032 print(LOG $bpc->timeStamp,
1033 "Archive failed on $host ($1)\n");
1035 } elsif ( $mesg =~ /^log\s+(.*)/ ) {
1036 print(LOG $bpc->timeStamp, "$1\n");
1037 } elsif ( $mesg =~ /^BackupPC_stats (\d+) = (.*)/ ) {
1038 my $chunk = int($1 / 16);
1039 my @f = split(/,/, $2);
1040 $Info{pool}{$f[0]}[$chunk]{FileCnt} += $f[1];
1041 $Info{pool}{$f[0]}[$chunk]{DirCnt} += $f[2];
1042 $Info{pool}{$f[0]}[$chunk]{Kb} += $f[3];
1043 $Info{pool}{$f[0]}[$chunk]{Kb2} += $f[4];
1044 $Info{pool}{$f[0]}[$chunk]{KbRm} += $f[5];
1045 $Info{pool}{$f[0]}[$chunk]{FileCntRm} += $f[6];
1046 $Info{pool}{$f[0]}[$chunk]{FileCntRep} += $f[7];
1047 $Info{pool}{$f[0]}[$chunk]{FileRepMax} = $f[8]
1048 if ( $Info{pool}{$f[0]}[$chunk]{FileRepMax} < $f[8] );
1049 $Info{pool}{$f[0]}[$chunk]{FileCntRename} += $f[9];
1050 $Info{pool}{$f[0]}[$chunk]{FileLinkMax} = $f[10]
1051 if ( $Info{pool}{$f[0]}[$chunk]{FileLinkMax} < $f[10] );
1052 $Info{pool}{$f[0]}[$chunk]{FileLinkTotal} += $f[11];
1053 $Info{pool}{$f[0]}[$chunk]{Time} = time;
1054 } elsif ( $mesg =~ /^BackupPC_nightly lock_off/ ) {
1055 $BackupPCNightlyLock--;
1056 if ( $BackupPCNightlyLock == 0 ) {
1058 # This means the last BackupPC_nightly is done with
1059 # the pool clean, so it's ok to start running regular
1062 $RunNightlyWhenIdle = 0;
1064 } elsif ( $mesg =~ /^processState\s+(.+)/ ) {
1065 $Jobs{$host}{processState} = $1;
1066 } elsif ( $mesg =~ /^link\s+(.+)/ ) {
1068 $Status{$h}{needLink} = 1;
1070 print(LOG $bpc->timeStamp, "$host: $mesg\n");
1074 # shut down the client connection if we read EOF
1076 if ( $nbytes <= 0 ) {
1077 close($Jobs{$host}{fh});
1078 vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1079 if ( $CmdJob eq $host || $bpc->isAdminJob($host) ) {
1080 my $cmd = $Jobs{$host}{cmd};
1081 $cmd =~ s/$BinDir\///g;
1082 print(LOG $bpc->timeStamp, "Finished $host ($cmd)\n");
1083 $Status{$host}{state} = "Status_idle";
1084 $Status{$host}{endTime} = time;
1085 if ( $cmd =~ /^BackupPC_nightly\s/ ) {
1086 $BackupPCNightlyJobs--;
1087 #print(LOG $bpc->timeStamp, "BackupPC_nightly done; now"
1088 # . " have $BackupPCNightlyJobs running\n");
1089 if ( $BackupPCNightlyJobs <= 0 ) {
1090 $BackupPCNightlyJobs = 0;
1091 $RunNightlyWhenIdle = 0;
1094 # Combine the 16 per-directory results
1096 for my $p ( qw(pool cpool) ) {
1097 $Info{"${p}FileCnt"} = 0;
1098 $Info{"${p}DirCnt"} = 0;
1099 $Info{"${p}Kb"} = 0;
1100 $Info{"${p}Kb2"} = 0;
1101 $Info{"${p}KbRm"} = 0;
1102 $Info{"${p}FileCntRm"} = 0;
1103 $Info{"${p}FileCntRep"} = 0;
1104 $Info{"${p}FileRepMax"} = 0;
1105 $Info{"${p}FileCntRename"} = 0;
1106 $Info{"${p}FileLinkMax"} = 0;
1107 $Info{"${p}Time"} = 0;
1108 for ( my $i = 0 ; $i < 16 ; $i++ ) {
1109 $Info{"${p}FileCnt"}
1110 += $Info{pool}{$p}[$i]{FileCnt};
1112 += $Info{pool}{$p}[$i]{DirCnt};
1114 += $Info{pool}{$p}[$i]{Kb};
1116 += $Info{pool}{$p}[$i]{Kb2};
1118 += $Info{pool}{$p}[$i]{KbRm};
1119 $Info{"${p}FileCntRm"}
1120 += $Info{pool}{$p}[$i]{FileCntRm};
1121 $Info{"${p}FileCntRep"}
1122 += $Info{pool}{$p}[$i]{FileCntRep};
1123 $Info{"${p}FileRepMax"}
1124 = $Info{pool}{$p}[$i]{FileRepMax}
1125 if ( $Info{"${p}FileRepMax"} <
1126 $Info{pool}{$p}[$i]{FileRepMax} );
1127 $Info{"${p}FileCntRename"}
1128 += $Info{pool}{$p}[$i]{FileCntRename};
1129 $Info{"${p}FileLinkMax"}
1130 = $Info{pool}{$p}[$i]{FileLinkMax}
1131 if ( $Info{"${p}FileLinkMax"} <
1132 $Info{pool}{$p}[$i]{FileLinkMax} );
1133 $Info{"${p}Time"} = $Info{pool}{$p}[$i]{Time}
1134 if ( $Info{"${p}Time"} <
1135 $Info{pool}{$p}[$i]{Time} );
1137 printf(LOG "%s%s nightly clean removed %d files of"
1139 $bpc->timeStamp, ucfirst($p),
1140 $Info{"${p}FileCntRm"},
1141 $Info{"${p}KbRm"} / (1000 * 1024));
1142 printf(LOG "%s%s is %.2fGB, %d files (%d repeated, "
1143 . "%d max chain, %d max links), %d directories\n",
1144 $bpc->timeStamp, ucfirst($p),
1145 $Info{"${p}Kb"} / (1000 * 1024),
1146 $Info{"${p}FileCnt"}, $Info{"${p}FileCntRep"},
1147 $Info{"${p}FileRepMax"},
1148 $Info{"${p}FileLinkMax"}, $Info{"${p}DirCnt"});
1156 # Queue BackupPC_link to complete the backup
1157 # processing for this host.
1159 if ( defined($Status{$host})
1160 && ($Status{$host}{reason} eq "Reason_backup_done"
1161 || $Status{$host}{needLink}) ) {
1163 } elsif ( defined($Status{$host}) ) {
1164 $Status{$host}{state} = "Status_idle";
1167 delete($Jobs{$host});
1168 $Status{$host}{activeJob} = 0 if ( defined($Status{$host}) );
1172 # When we are idle (empty Jobs, CmdQueue, BgQueue, UserQueue) we
1173 # do a pass over %Status updating the deadCnt and aliveCnt for
1174 # DHCP hosts. The reason we need to do this later is we can't
1175 # be sure whether a DHCP host is alive or dead until we have passed
1176 # over all the DHCP pool.
1178 return if ( @CmdQueue || @BgQueue || @UserQueue || keys(%Jobs) > 1 );
1179 foreach my $host ( keys(%Status) ) {
1180 next if ( $Status{$host}{dhcpCheckCnt} <= 0 );
1181 $Status{$host}{deadCnt} += $Status{$host}{dhcpCheckCnt};
1182 $Status{$host}{dhcpCheckCnt} = 0;
1183 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1184 $Status{$host}{aliveCnt} = 0;
1189 ############################################################################
1190 # Main_Check_Client_Messages($fdRead)
1192 # Check for, and process, any output from our clients. Also checks
1193 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
1194 ############################################################################
1195 sub Main_Check_Client_Messages
1198 foreach my $client ( keys(%Clients) ) {
1199 next if ( !vec($fdRead, $Clients{$client}{fn}, 1) );
1202 # do a last check to make sure there is something to read so
1203 # we are absolutely sure we won't block.
1205 vec(my $readMask, $Clients{$client}{fn}, 1) = 1;
1206 if ( !select($readMask, undef, undef, 0.0) ) {
1207 print(LOG $bpc->timeStamp, "Botch in Main_Check_Client_Messages:"
1208 . " nothing to read from $client. Debug dump:\n");
1209 my($dump) = Data::Dumper->new(
1210 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
1211 [qw(*Clients, *Jobs *FDread, *fdRead)]);
1213 print(LOG $dump->Dump);
1216 my $nbytes = sysread($Clients{$client}{fh}, $mesg, 1024);
1217 $Clients{$client}{mesg} .= $mesg if ( $nbytes > 0 );
1219 # Process any complete lines received from this client.
1221 while ( $Clients{$client}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
1224 $Clients{$client}{mesg} = $2;
1226 # Authenticate the message by checking the MD5 digest
1228 my $md5 = Digest::MD5->new;
1229 if ( $cmd !~ /^(.{22}) (.*)/
1230 || ($md5->add($Clients{$client}{seed}
1231 . $Clients{$client}{mesgCnt}
1232 . $Conf{ServerMesgSecret} . $2),
1233 $md5->b64digest ne $1) ) {
1234 print(LOG $bpc->timeStamp, "Corrupted message '$cmd' from"
1235 . " client '$Clients{$client}{clientName}':"
1236 . " shutting down client connection\n");
1240 $Clients{$client}{mesgCnt}++;
1242 if ( $cmd =~ /^stop (\S+)\s+(\S+)\s+(\S*)/ ) {
1246 $host = $bpc->uriUnesc($host);
1247 if ( $CmdJob ne $host && defined($Status{$host})
1248 && defined($Jobs{$host}) ) {
1249 print(LOG $bpc->timeStamp,
1250 "Stopping current $Jobs{$host}{type} of $host,"
1251 . " request by $user (backoff=$backoff)\n");
1252 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1254 # Don't close the pipe now; wait until the child
1255 # really exits later. Otherwise close() will
1256 # block until the child has exited.
1258 ##vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1259 ##close($Jobs{$host}{fh});
1260 ##delete($Jobs{$host});
1262 $Status{$host}{state} = "Status_idle";
1263 if ( $Jobs{$host}{type} eq "restore" ) {
1264 $Status{$host}{reason}
1265 = "Reason_restore_canceled_by_user";
1266 } elsif ( $Jobs{$host}{type} eq "archive" ) {
1267 $Status{$host}{reason}
1268 = "Reason_archive_canceled_by_user";
1270 $Status{$host}{reason}
1271 = "Reason_backup_canceled_by_user";
1273 $Status{$host}{activeJob} = 0;
1274 $Status{$host}{startTime} = time;
1275 $reply = "ok: $Jobs{$host}{type} of $host canceled";
1276 } elsif ( $BgQueueOn{$host} || $UserQueueOn{$host} ) {
1277 print(LOG $bpc->timeStamp,
1278 "Stopping pending backup of $host,"
1279 . " request by $user (backoff=$backoff)\n");
1280 @BgQueue = grep($_->{host} ne $host, @BgQueue);
1281 @UserQueue = grep($_->{host} ne $host, @UserQueue);
1282 $BgQueueOn{$host} = $UserQueueOn{$host} = 0;
1283 $reply = "ok: pending backup of $host canceled";
1285 print(LOG $bpc->timeStamp,
1286 "Nothing to do for stop backup of $host,"
1287 . " request by $user (backoff=$backoff)\n");
1288 $reply = "ok: no backup was pending or running";
1290 if ( defined($Status{$host}) && $backoff ne "" ) {
1291 if ( $backoff > 0 ) {
1292 $Status{$host}{backoffTime} = time + $backoff * 3600;
1294 delete($Status{$host}{backoffTime});
1297 } elsif ( $cmd =~ /^backup all$/ ) {
1299 } elsif ( $cmd =~ /^BackupPC_nightly run$/ ) {
1300 $RunNightlyWhenIdle = 1;
1301 } elsif ( $cmd =~ /^backup (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1306 $host = $bpc->uriUnesc($host);
1307 $hostIP = $bpc->uriUnesc($hostIP);
1308 if ( !defined($Status{$host}) ) {
1309 print(LOG $bpc->timeStamp,
1310 "User $user requested backup of unknown host"
1312 $reply = "error: unknown host $host";
1314 print(LOG $bpc->timeStamp,
1315 "User $user requested backup of $host"
1317 if ( $BgQueueOn{$hostIP} ) {
1318 @BgQueue = grep($_->{host} ne $hostIP, @BgQueue);
1319 $BgQueueOn{$hostIP} = 0;
1321 if ( $UserQueueOn{$hostIP} ) {
1322 @UserQueue = grep($_->{host} ne $hostIP, @UserQueue);
1323 $UserQueueOn{$hostIP} = 0;
1325 unshift(@UserQueue, {
1331 dhcp => $hostIP eq $host ? 0 : 1,
1333 $UserQueueOn{$hostIP} = 1;
1334 $reply = "ok: requested backup of $host";
1336 } elsif ( $cmd =~ /^archive (\S+)\s+(\S+)\s+(\S+)/ ) {
1338 my $archivehost = $2;
1339 my $reqFileName = $3;
1340 $host = $bpc->uriUnesc($archivehost);
1341 if ( !defined($Status{$host}) ) {
1342 print(LOG $bpc->timeStamp,
1343 "User $user requested archive of unknown archive host"
1345 $reply = "archive error: unknown archive host $host";
1347 print(LOG $bpc->timeStamp,
1348 "User $user requested archive on $host"
1350 if ( defined($Jobs{$host}) ) {
1351 $reply = "Archive currently running on $host, please try later";
1353 unshift(@UserQueue, {
1356 reqFileName => $reqFileName,
1362 $UserQueueOn{$host} = 1;
1363 $reply = "ok: requested archive on $host";
1366 } elsif ( $cmd =~ /^restore (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1370 my $reqFileName = $4;
1371 $host = $bpc->uriUnesc($host);
1372 $hostIP = $bpc->uriUnesc($hostIP);
1373 if ( !defined($Status{$host}) ) {
1374 print(LOG $bpc->timeStamp,
1375 "User $user requested restore to unknown host"
1377 $reply = "restore error: unknown host $host";
1379 print(LOG $bpc->timeStamp,
1380 "User $user requested restore to $host"
1382 unshift(@UserQueue, {
1385 reqFileName => $reqFileName,
1391 $UserQueueOn{$host} = 1;
1392 if ( defined($Jobs{$host}) ) {
1393 $reply = "ok: requested restore of $host, but a"
1394 . " job is currently running,"
1395 . " so this request will start later";
1397 $reply = "ok: requested restore of $host";
1400 } elsif ( $cmd =~ /^status\s*(.*)/ ) {
1402 my($dump, @values, @names);
1403 foreach my $type ( split(/\s+/, $args) ) {
1404 if ( $type =~ /^queues/ ) {
1405 push(@values, \@BgQueue, \@UserQueue, \@CmdQueue);
1406 push(@names, qw(*BgQueue *UserQueue *CmdQueue));
1407 } elsif ( $type =~ /^jobs/ ) {
1408 push(@values, \%Jobs);
1409 push(@names, qw(*Jobs));
1410 } elsif ( $type =~ /^queueLen/ ) {
1412 BgQueue => scalar(@BgQueue),
1413 UserQueue => scalar(@UserQueue),
1414 CmdQueue => scalar(@CmdQueue),
1416 push(@names, qw(*QueueLen));
1417 } elsif ( $type =~ /^info/ ) {
1418 push(@values, \%Info);
1419 push(@names, qw(*Info));
1420 } elsif ( $type =~ /^hosts/ ) {
1421 push(@values, \%Status);
1422 push(@names, qw(*Status));
1423 } elsif ( $type =~ /^host\((.*)\)/ ) {
1424 my $h = $bpc->uriUnesc($1);
1425 if ( defined($Status{$h}) ) {
1428 BgQueueOn => $BgQueueOn{$h},
1429 UserQueueOn => $UserQueueOn{$h},
1430 CmdQueueOn => $CmdQueueOn{$h},
1432 push(@names, qw(*StatusHost));
1434 print(LOG $bpc->timeStamp,
1435 "Unknown host $h for status request\n");
1438 print(LOG $bpc->timeStamp,
1439 "Unknown status request $type\n");
1442 $dump = Data::Dumper->new(\@values, \@names);
1444 $reply = $dump->Dump;
1445 } elsif ( $cmd =~ /^link\s+(.+)/ ) {
1447 $host = $bpc->uriUnesc($host);
1449 } elsif ( $cmd =~ /^log\s+(.*)/ ) {
1450 print(LOG $bpc->timeStamp, "$1\n");
1451 } elsif ( $cmd =~ /^server\s+(\w+)/ ) {
1453 if ( $type eq 'reload' ) {
1454 ServerReload("Reloading config/host files via CGI request");
1455 } elsif ( $type eq 'shutdown' ) {
1456 $reply = "Shutting down...\n";
1457 syswrite($Clients{$client}{fh}, $reply, length($reply));
1458 ServerShutdown("Server shutting down...");
1460 } elsif ( $cmd =~ /^quit/ || $cmd =~ /^exit/ ) {
1464 print(LOG $bpc->timeStamp, "Unknown command $cmd\n");
1465 $reply = "error: bad command $cmd";
1468 # send a reply to the client, at a minimum "ok\n".
1470 $reply = "ok" if ( $reply eq "" );
1472 syswrite($Clients{$client}{fh}, $reply, length($reply));
1475 # Detect possible denial-of-service attack from sending a huge line
1476 # (ie: never terminated). 32K seems to be plenty big enough as
1479 if ( length($Clients{$client}{mesg}) > 32 * 1024 ) {
1480 print(LOG $bpc->timeStamp, "Line too long from client"
1481 . " '$Clients{$client}{clientName}':"
1482 . " shutting down client connection\n");
1486 # Shut down the client connection if we read EOF
1488 if ( $nbytes <= 0 ) {
1489 close($Clients{$client}{fh});
1490 vec($FDread, $Clients{$client}{fn}, 1) = 0;
1491 delete($Clients{$client});
1495 # Accept any new connections on each of our listen sockets
1497 if ( vec($fdRead, fileno(SERVER_UNIX), 1) ) {
1499 my $paddr = accept(CLIENT, SERVER_UNIX);
1501 $Clients{$ClientConnCnt}{clientName} = "unix socket";
1502 $Clients{$ClientConnCnt}{mesg} = "";
1503 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1504 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1505 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1507 # Generate and send unique seed for MD5 digests to avoid
1508 # replay attacks. See BackupPC::Lib::ServerMesg().
1510 my $seed = time . ",$ClientConnCnt,$$,0\n";
1511 $Clients{$ClientConnCnt}{seed} = $seed;
1512 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1513 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1515 if ( $ServerInetPort > 0 && vec($fdRead, fileno(SERVER_INET), 1) ) {
1517 my $paddr = accept(CLIENT, SERVER_INET);
1518 my($port,$iaddr) = sockaddr_in($paddr);
1519 my $name = gethostbyaddr($iaddr, AF_INET);
1521 $Clients{$ClientConnCnt}{mesg} = "";
1522 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1523 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1524 $Clients{$ClientConnCnt}{clientName} = "$name:$port";
1525 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1527 # Generate and send unique seed for MD5 digests to avoid
1528 # replay attacks. See BackupPC::Lib::ServerMesg().
1530 my $seed = time . ",$ClientConnCnt,$$,$port\n";
1531 $Clients{$ClientConnCnt}{seed} = $seed;
1532 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1533 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1537 ###########################################################################
1538 # Miscellaneous subroutines
1539 ###########################################################################
1542 # Write the current status to $TopDir/log/status.pl
1546 my($dump) = Data::Dumper->new(
1547 [ \%Info, \%Status],
1548 [qw(*Info *Status)]);
1550 if ( open(STATUS, ">", "$TopDir/log/status.pl") ) {
1551 print(STATUS $dump->Dump);
1557 # Compare function for host sort. Hosts with errors go first,
1558 # sorted with the oldest errors first. The remaining hosts
1559 # are sorted so that those with the oldest backups go first.
1564 # Hosts with errors go before hosts without errors
1566 return -1 if ( $Status{$a}{error} ne "" && $Status{$b}{error} eq "" );
1569 # Hosts with no errors go after hosts with errors
1572 return 1 if ( $Status{$a}{error} eq "" && $Status{$b}{error} ne "" );
1575 # hosts with the older last good backups sort earlier
1577 my $r = $Status{$a}{lastGoodBackupTime} <=> $Status{$b}{lastGoodBackupTime};
1578 return $r if ( $r );
1581 # Finally, just sort based on host name
1587 # Queue all the hosts for backup. This means queuing all the fixed
1588 # ip hosts and all the dhcp address ranges. We also additionally
1589 # queue the dhcp hosts with a -e flag to check for expired dumps.
1594 foreach my $host ( sort(HostSortCompare keys(%$Hosts)) ) {
1595 delete($Status{$host}{backoffTime})
1596 if ( defined($Status{$host}{backoffTime})
1597 && $Status{$host}{backoffTime} < time );
1598 next if ( defined($Jobs{$host})
1599 || $BgQueueOn{$host}
1600 || $UserQueueOn{$host}
1601 || $CmdQueueOn{$host} );
1602 if ( $Hosts->{$host}{dhcp} ) {
1603 $Status{$host}{dhcpCheckCnt}++;
1604 if ( $RunNightlyWhenIdle ) {
1606 # Once per night queue a check for DHCP hosts that just
1607 # checks for expired dumps. We need to do this to handle
1608 # the case when a DHCP host has not been on the network for
1609 # a long time, and some of the old dumps need to be expired.
1610 # Normally expiry checks are done by BackupPC_dump only
1611 # after the DHCP hosts has been detected on the network.
1614 {host => $host, user => "BackupPC", reqTime => time,
1615 dhcp => 0, dumpExpire => 1});
1616 $BgQueueOn{$host} = 1;
1620 # this is a fixed ip host: queue it
1622 if ( $Info{DUlastValue} > $Conf{DfMaxUsagePct} ) {
1624 # Since we are out of disk space, instead of queuing
1625 # a regular job, queue an expire check instead. That
1626 # way if the admin reduces the number of backups to
1627 # keep then we will actually delete them. Otherwise
1628 # BackupPC_dump will never run since we have exceeded
1633 {host => $host, user => "BackupPC", reqTime => time,
1634 dhcp => $Hosts->{$host}{dhcp}, dumpExpire => 1});
1637 # Queue regular background backup
1640 {host => $host, user => "BackupPC", reqTime => time,
1641 dhcp => $Hosts->{$host}{dhcp}});
1643 $BgQueueOn{$host} = 1;
1647 print(LOG $bpc->timeStamp,
1648 "Disk too full ($Info{DUlastValue}%); skipped $nSkip hosts\n");
1649 $Info{DUDailySkipHostCnt} += $nSkip;
1651 foreach my $dhcp ( @{$Conf{DHCPAddressRanges}} ) {
1652 for ( my $i = $dhcp->{first} ; $i <= $dhcp->{last} ; $i++ ) {
1653 my $ipAddr = "$dhcp->{ipAddrBase}.$i";
1654 next if ( defined($Jobs{$ipAddr})
1655 || $BgQueueOn{$ipAddr}
1656 || $UserQueueOn{$ipAddr}
1657 || $CmdQueueOn{$ipAddr} );
1659 # this is a potential dhcp ip address (we don't know the
1660 # host name yet): queue it
1663 {host => $ipAddr, user => "BackupPC", reqTime => time,
1665 $BgQueueOn{$ipAddr} = 1;
1671 # Queue a BackupPC_link for the given host
1677 return if ( $CmdQueueOn{$host} );
1678 $Status{$host}{state} = "Status_link_pending";
1679 $Status{$host}{needLink} = 0;
1680 unshift(@CmdQueue, {
1684 cmd => ["$BinDir/BackupPC_link", $host],
1686 $CmdQueueOn{$host} = 1;
1690 # Read the hosts file, and update Status if any hosts have been
1691 # added or deleted. We also track the mtime so the only need to
1692 # update the hosts file on changes.
1694 # This function is called at startup, SIGHUP, and on each wakeup.
1695 # It returns 1 on success and undef on failure.
1702 # Nothing to do if we already have the current hosts file
1704 return 1 if ( !$force && defined($Hosts)
1705 && $Info{HostsModTime} == $bpc->HostsMTime() );
1706 if ( !defined($newHosts = $bpc->HostInfoRead()) ) {
1707 print(LOG $bpc->timeStamp, "Can't read hosts file!\n");
1710 print(LOG $bpc->timeStamp, "Reading hosts file\n");
1712 $Info{HostsModTime} = $bpc->HostsMTime();
1714 # Now update %Status in case any hosts have been added or deleted
1716 foreach my $host ( sort(keys(%$Hosts)) ) {
1717 next if ( defined($Status{$host}) );
1718 $Status{$host}{state} = "Status_idle";
1719 print(LOG $bpc->timeStamp, "Added host $host to backup list\n");
1721 foreach my $host ( sort(keys(%Status)) ) {
1722 next if ( $host eq $bpc->trashJob
1723 || $bpc->isAdminJob($host)
1724 || defined($Hosts->{$host})
1725 || defined($Jobs{$host})
1726 || $BgQueueOn{$host}
1727 || $UserQueueOn{$host}
1728 || $CmdQueueOn{$host} );
1729 print(LOG $bpc->timeStamp, "Deleted host $host from backup list\n");
1730 delete($Status{$host});
1736 # Remember the signal name for later processing
1742 foreach my $host ( keys(%Jobs) ) {
1743 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1746 # In case we are inside the exit handler, reopen the log file
1750 print(LOG "Fatal error: unhandled signal $SigName\n");
1751 unlink("$TopDir/log/BackupPC.pid");
1752 confess("Got new signal $SigName... quitting\n");
1759 # Open the log file and point STDOUT and STDERR there too
1763 mkpath("$TopDir/log", 0, 0777) if ( !-d "$TopDir/log" );
1764 open(LOG, ">>$TopDir/log/LOG")
1765 || die("Can't create LOG file $TopDir/log/LOG");
1768 open(STDOUT, ">&LOG");
1769 open(STDERR, ">&LOG");
1770 select(LOG); $| = 1;
1771 select(STDERR); $| = 1;
1772 select(STDOUT); $| = 1;
1776 # Initialize the unix-domain and internet-domain sockets that
1777 # we listen to for client connections (from the CGI script and
1778 # some of the BackupPC sub-programs).
1780 sub ServerSocketInit
1782 if ( !defined(fileno(SERVER_UNIX)) ) {
1784 # one-time only: initialize unix-domain socket
1786 if ( !socket(SERVER_UNIX, PF_UNIX, SOCK_STREAM, 0) ) {
1787 print(LOG $bpc->timeStamp, "unix socket() failed: $!\n");
1790 my $sockFile = "$TopDir/log/BackupPC.sock";
1792 if ( !bind(SERVER_UNIX, sockaddr_un($sockFile)) ) {
1793 print(LOG $bpc->timeStamp, "unix bind() failed: $!\n");
1796 if ( !listen(SERVER_UNIX, SOMAXCONN) ) {
1797 print(LOG $bpc->timeStamp, "unix listen() failed: $!\n");
1800 vec($FDread, fileno(SERVER_UNIX), 1) = 1;
1802 return if ( $ServerInetPort == $Conf{ServerPort} );
1803 if ( $ServerInetPort > 0 ) {
1804 vec($FDread, fileno(SERVER_INET), 1) = 0;
1806 $ServerInetPort = -1;
1808 if ( $Conf{ServerPort} > 0 ) {
1810 # Setup a socket to listen on $Conf{ServerPort}
1812 my $proto = getprotobyname('tcp');
1813 if ( !socket(SERVER_INET, PF_INET, SOCK_STREAM, $proto) ) {
1814 print(LOG $bpc->timeStamp, "inet socket() failed: $!\n");
1817 if ( !setsockopt(SERVER_INET, SOL_SOCKET, SO_REUSEADDR, pack("l",1)) ) {
1818 print(LOG $bpc->timeStamp, "setsockopt() failed: $!\n");
1821 if ( !bind(SERVER_INET, sockaddr_in($Conf{ServerPort}, INADDR_ANY)) ) {
1822 print(LOG $bpc->timeStamp, "inet bind() failed: $!\n");
1825 if ( !listen(SERVER_INET, SOMAXCONN) ) {
1826 print(LOG $bpc->timeStamp, "inet listen() failed: $!\n");
1829 vec($FDread, fileno(SERVER_INET), 1) = 1;
1830 $ServerInetPort = $Conf{ServerPort};
1835 # Reload the server. Used by Main_Process_Signal when $SigName eq "HUP"
1836 # or when the command "server reload" is received.
1841 $mesg = $bpc->ConfigRead() || $mesg;
1842 print(LOG $bpc->timeStamp, "$mesg\n");
1843 $Info{ConfigModTime} = $bpc->ConfigMTime();
1844 %Conf = $bpc->Conf();
1845 umask($Conf{UmaskMode});
1849 $Info{ConfigLTime} = time;
1853 # Gracefully shutdown the server. Used by Main_Process_Signal when
1854 # $SigName ne "" && $SigName ne "HUP" or when the command
1855 # "server shutdown" is received.
1860 print(LOG $bpc->timeStamp, "$mesg\n");
1861 if ( keys(%Jobs) ) {
1862 foreach my $host ( keys(%Jobs) ) {
1863 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1866 foreach my $host ( keys(%Jobs) ) {
1867 kill($bpc->sigName2num("KILL"), $Jobs{$host}{pid});
1873 unlink("$TopDir/log/BackupPC.pid");