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 ( $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;
610 # Run background jobs anytime. Previously they were locked out
611 # when BackupPC_nightly was running or pending with this
612 # condition on the while loop:
614 # while ( $RunNightlyWhenIdle == 0 )
618 my(@args, $progName, $type);
619 my $nJobs = keys(%Jobs);
621 # CmdJob and trashClean don't count towards MaxBackups / MaxUserBackups
623 if ( $CmdJob ne "" ) {
624 if ( $BackupPCNightlyJobs ) {
625 $nJobs -= $BackupPCNightlyJobs;
630 $nJobs-- if ( defined($Jobs{$bpc->trashJob} ) );
631 if ( $nJobs < $Conf{MaxBackups} + $Conf{MaxUserBackups}
632 && @UserQueue > 0 ) {
633 $req = pop(@UserQueue);
634 if ( defined($Jobs{$req->{host}}) ) {
635 push(@deferUserQueue, $req);
638 push(@args, $req->{doFull} ? "-f" : "-i")
639 if (( !$req->{restore} ) && ( !$req->{archive} ));
640 $UserQueueOn{$req->{host}} = 0;
641 } elsif ( $nJobs < $Conf{MaxBackups}
642 && (@CmdQueue + $nJobs)
643 <= $Conf{MaxBackups} + $Conf{MaxPendingCmds}
645 $req = pop(@BgQueue);
646 if ( defined($Jobs{$req->{host}}) ) {
648 # Job is currently running for this host; save it for later
650 unshift(@deferBgQueue, $req);
653 $BgQueueOn{$req->{host}} = 0;
656 # Restore the deferred jobs
658 @BgQueue = (@BgQueue, @deferBgQueue);
659 @UserQueue = (@UserQueue, @deferUserQueue);
662 $host = $req->{host};
663 my $user = $req->{user};
664 if ( $req->{restore} ) {
665 $progName = "BackupPC_restore";
667 push(@args, $req->{hostIP}, $req->{host}, $req->{reqFileName});
668 } elsif ( $req->{archive} ) {
669 $progName = "BackupPC_archive";
671 push(@args, $req->{user}, $req->{host}, $req->{reqFileName});
673 $progName = "BackupPC_dump";
675 push(@args, "-d") if ( $req->{dhcp} );
676 push(@args, "-e") if ( $req->{dumpExpire} );
679 my $pid = open(FH, "-|");
680 if ( !defined($pid) ) {
681 print(LOG $bpc->timeStamp,
682 "can't fork to run $progName for $host, request by $user\n");
688 exec("$BinDir/$progName", @args);
689 print(LOG $bpc->timeStamp, "can't exec $progName for $host\n");
692 $Jobs{$host}{pid} = $pid;
693 $Jobs{$host}{fh} = *FH;
694 $Jobs{$host}{fn} = fileno(FH);
695 $Jobs{$host}{dhcp} = $req->{dhcp};
696 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
697 $Jobs{$host}{startTime} = time;
698 $Jobs{$host}{reqTime} = $req->{reqTime};
699 $Jobs{$host}{userReq} = $req->{userReq};
700 $Jobs{$host}{cmd} = $bpc->execCmd2ShellCmd($progName, @args);
701 $Jobs{$host}{user} = $user;
702 $Jobs{$host}{type} = $type;
703 $Status{$host}{userReq} = $req->{userReq}
704 if ( defined($Hosts->{$host}) );
705 if ( !$req->{dhcp} ) {
706 $Status{$host}{state} = "Status_".$type."_starting";
707 $Status{$host}{activeJob} = 1;
708 $Status{$host}{startTime} = time;
709 $Status{$host}{endTime} = "";
714 ############################################################################
717 # If necessary, figure out when to next wakeup based on $Conf{WakeupSchedule},
718 # and then do a select() to wait for the next thing to happen
719 # (timeout, signal, someone sends a message, child dies etc).
720 ############################################################################
723 if ( $NextWakeup <= 0 ) {
725 # Figure out when to next wakeup based on $Conf{WakeupSchedule}.
727 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
729 my($currHours) = $hour + $min / 60 + $sec / 3600;
730 if ( $bpc->ConfigMTime() != $Info{ConfigModTime} ) {
731 ServerReload("Re-read config file because mtime changed");
734 foreach my $t ( @{$Conf{WakeupSchedule} || [0..23]} ) {
735 next if ( $t < 0 || $t > 24 );
736 my $tomorrow = $t + 24;
738 || ($tomorrow - $currHours > 0
739 && $delta > $tomorrow - $currHours) ) {
740 $delta = $tomorrow - $currHours;
741 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
744 || ($t - $currHours > 0 && $delta > $t - $currHours) ) {
745 $delta = $t - $currHours;
746 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
749 $NextWakeup = time + $delta * 3600;
750 $Info{nextWakeup} = $NextWakeup;
751 print(LOG $bpc->timeStamp, "Next wakeup is ",
752 $bpc->timeStamp($NextWakeup, 1), "\n");
755 # Call select(), waiting until either a signal, a timeout,
756 # any output from our jobs, or any messages from clients
758 # select() is where we (hopefully) spend most of our time blocked...
760 my $timeout = $NextWakeup - time;
761 $timeout = 1 if ( $timeout <= 0 );
763 select(my $rout = $FDread, undef, $ein, $timeout);
768 ############################################################################
769 # Main_Process_Signal()
772 ############################################################################
773 sub Main_Process_Signal
778 if ( $SigName eq "HUP" ) {
779 ServerReload("Re-read config file because of a SIG_HUP");
780 } elsif ( $SigName ) {
781 ServerShutdown("Got signal $SigName... cleaning up");
786 ############################################################################
787 # Main_Check_Timeout()
789 # Check if a timeout has occured, and if so, queue all the PCs for backups.
790 # Also does log file aging on the first timeout after midnight.
791 ############################################################################
792 sub Main_Check_Timeout
797 return if ( time < $NextWakeup || $NextWakeup <= 0 );
799 if ( $FirstWakeup ) {
801 # This is the first wakeup after midnight. Do log file aging
802 # and various house keeping.
805 printf(LOG "%s24hr disk usage: %d%% max, %d%% recent,"
806 . " %d skipped hosts\n",
807 $bpc->timeStamp, $Info{DUDailyMax}, $Info{DUlastValue},
808 $Info{DUDailySkipHostCnt});
809 $Info{DUDailyMaxReset} = 1;
810 $Info{DUDailyMaxPrev} = $Info{DUDailyMax};
811 $Info{DUDailySkipHostCntPrev} = $Info{DUDailySkipHostCnt};
812 $Info{DUDailySkipHostCnt} = 0;
813 my $lastLog = $Conf{MaxOldLogFiles} - 1;
814 if ( -f "$LogDir/LOG.$lastLog" ) {
815 print(LOG $bpc->timeStamp,
816 "Removing $LogDir/LOG.$lastLog\n");
817 unlink("$LogDir/LOG.$lastLog");
819 if ( -f "$LogDir/LOG.$lastLog.z" ) {
820 print(LOG $bpc->timeStamp,
821 "Removing $LogDir/LOG.$lastLog.z\n");
822 unlink("$LogDir/LOG.$lastLog.z");
824 print(LOG $bpc->timeStamp, "Aging LOG files, LOG -> LOG.0 -> "
825 . "LOG.1 -> ... -> LOG.$lastLog\n");
826 close(STDERR); # dup of LOG
827 close(STDOUT); # dup of LOG
829 for ( my $i = $lastLog - 1 ; $i >= 0 ; $i-- ) {
831 rename("$LogDir/LOG.$i", "$LogDir/LOG.$j")
832 if ( -f "$LogDir/LOG.$i" );
833 rename("$LogDir/LOG.$i.z", "$LogDir/LOG.$j.z")
834 if ( -f "$LogDir/LOG.$i.z" );
837 # Compress the log file LOG -> LOG.0.z (if enabled).
838 # Otherwise, just rename LOG -> LOG.0.
840 BackupPC::FileZIO->compressCopy("$LogDir/LOG",
843 $Conf{CompressLevel}, 1);
846 # Remember to run the nightly script when the next CmdQueue
849 $RunNightlyWhenIdle = 1;
852 # Write out the current status and then queue all the PCs
856 %BgQueueOn = () if ( @BgQueue == 0 );
857 %UserQueueOn = () if ( @UserQueue == 0 );
858 %CmdQueueOn = () if ( @CmdQueue == 0 );
862 ############################################################################
863 # Main_Check_Job_Messages($fdRead)
865 # Check if select() says we have bytes waiting from any of our jobs.
866 # Handle each of the messages when complete (newline terminated).
867 ############################################################################
868 sub Main_Check_Job_Messages
871 foreach my $host ( keys(%Jobs) ) {
872 next if ( !vec($fdRead, $Jobs{$host}{fn}, 1) );
875 # do a last check to make sure there is something to read so
876 # we are absolutely sure we won't block.
878 vec(my $readMask, $Jobs{$host}{fn}, 1) = 1;
879 if ( !select($readMask, undef, undef, 0.0) ) {
880 print(LOG $bpc->timeStamp, "Botch in Main_Check_Job_Messages:"
881 . " nothing to read from $host. Debug dump:\n");
882 my($dump) = Data::Dumper->new(
883 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
884 [qw(*Clients, *Jobs *FDread, *fdRead)]);
886 print(LOG $dump->Dump);
889 my $nbytes = sysread($Jobs{$host}{fh}, $mesg, 1024);
890 $Jobs{$host}{mesg} .= $mesg if ( $nbytes > 0 );
892 # Process any complete lines of output from this jobs.
893 # Any output to STDOUT or STDERR from the children is processed here.
895 while ( $Jobs{$host}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
897 $Jobs{$host}{mesg} = $2;
898 if ( $Jobs{$host}{dhcp} ) {
899 if ( $mesg =~ /^DHCP (\S+) (\S+)/ ) {
900 my $newHost = $bpc->uriUnesc($2);
901 if ( defined($Jobs{$newHost}) ) {
902 print(LOG $bpc->timeStamp,
903 "Backup on $newHost is already running\n");
904 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
908 $Jobs{$host}{dhcpHostIP} = $host;
909 $Status{$newHost}{dhcpHostIP} = $host;
910 $Jobs{$newHost} = $Jobs{$host};
911 delete($Jobs{$host});
913 $Status{$host}{state} = "Status_backup_starting";
914 $Status{$host}{activeJob} = 1;
915 $Status{$host}{startTime} = $Jobs{$host}{startTime};
916 $Status{$host}{endTime} = "";
917 $Jobs{$host}{dhcp} = 0;
919 print(LOG $bpc->timeStamp, "dhcp $host: $mesg\n");
921 } elsif ( $mesg =~ /^started (.*) dump, share=(.*)/ ) {
922 $Jobs{$host}{type} = $1;
923 $Jobs{$host}{shareName} = $2;
924 print(LOG $bpc->timeStamp,
925 "Started $1 backup on $host (pid=$Jobs{$host}{pid}",
926 $Jobs{$host}{dhcpHostIP}
927 ? ", dhcp=$Jobs{$host}{dhcpHostIP}" : "",
928 ", share=$Jobs{$host}{shareName})\n");
929 $Status{$host}{state} = "Status_backup_in_progress";
930 $Status{$host}{reason} = "";
931 $Status{$host}{type} = $1;
932 $Status{$host}{startTime} = time;
933 $Status{$host}{deadCnt} = 0;
934 $Status{$host}{aliveCnt}++;
935 $Status{$host}{dhcpCheckCnt}--
936 if ( $Status{$host}{dhcpCheckCnt} > 0 );
937 } elsif ( $mesg =~ /^xferPids (.*)/ ) {
938 $Jobs{$host}{xferPid} = $1;
939 } elsif ( $mesg =~ /^started_restore/ ) {
940 $Jobs{$host}{type} = "restore";
941 print(LOG $bpc->timeStamp,
942 "Started restore on $host"
943 . " (pid=$Jobs{$host}{pid})\n");
944 $Status{$host}{state} = "Status_restore_in_progress";
945 $Status{$host}{reason} = "";
946 $Status{$host}{type} = "restore";
947 $Status{$host}{startTime} = time;
948 $Status{$host}{deadCnt} = 0;
949 $Status{$host}{aliveCnt}++;
950 } elsif ( $mesg =~ /^started_archive/ ) {
951 $Jobs{$host}{type} = "archive";
952 print(LOG $bpc->timeStamp,
953 "Started archive on $host"
954 . " (pid=$Jobs{$host}{pid})\n");
955 $Status{$host}{state} = "Status_archive_in_progress";
956 $Status{$host}{reason} = "";
957 $Status{$host}{type} = "archive";
958 $Status{$host}{startTime} = time;
959 $Status{$host}{deadCnt} = 0;
960 $Status{$host}{aliveCnt}++;
961 } elsif ( $mesg =~ /^(full|incr) backup complete/ ) {
962 print(LOG $bpc->timeStamp, "Finished $1 backup 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 $Status{$host}{lastGoodBackupTime} = time;
968 } elsif ( $mesg =~ /^backups disabled/ ) {
969 print(LOG $bpc->timeStamp,
970 "Ignoring old backup error on $host\n");
971 $Status{$host}{reason} = "Reason_backup_done";
972 delete($Status{$host}{error});
973 delete($Status{$host}{errorTime});
974 $Status{$host}{endTime} = time;
975 } elsif ( $mesg =~ /^restore complete/ ) {
976 print(LOG $bpc->timeStamp, "Finished restore on $host\n");
977 $Status{$host}{reason} = "Reason_restore_done";
978 delete($Status{$host}{error});
979 delete($Status{$host}{errorTime});
980 $Status{$host}{endTime} = time;
981 } elsif ( $mesg =~ /^archive complete/ ) {
982 print(LOG $bpc->timeStamp, "Finished archive on $host\n");
983 $Status{$host}{reason} = "Reason_archive_done";
984 delete($Status{$host}{error});
985 delete($Status{$host}{errorTime});
986 $Status{$host}{endTime} = time;
987 } elsif ( $mesg =~ /^nothing to do/ ) {
988 if ( $Status{$host}{reason} ne "Reason_backup_failed"
989 && $Status{$host}{reason} ne "Reason_restore_failed" ) {
990 $Status{$host}{state} = "Status_idle";
991 $Status{$host}{reason} = "Reason_nothing_to_do";
992 $Status{$host}{startTime} = time;
994 $Status{$host}{dhcpCheckCnt}--
995 if ( $Status{$host}{dhcpCheckCnt} > 0 );
996 } elsif ( $mesg =~ /^no ping response/
997 || $mesg =~ /^ping too slow/
998 || $mesg =~ /^host not found/ ) {
999 $Status{$host}{state} = "Status_idle";
1000 if ( $Status{$host}{userReq}
1001 || $Status{$host}{reason} ne "Reason_backup_failed"
1002 || $Status{$host}{error} =~ /^aborted by user/ ) {
1003 $Status{$host}{reason} = "Reason_no_ping";
1004 $Status{$host}{error} = $mesg;
1005 $Status{$host}{startTime} = time;
1007 $Status{$host}{deadCnt}++;
1008 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1009 $Status{$host}{aliveCnt} = 0;
1011 } elsif ( $mesg =~ /^dump failed: (.*)/ ) {
1012 $Status{$host}{state} = "Status_idle";
1013 $Status{$host}{error} = $1;
1014 $Status{$host}{errorTime} = time;
1015 $Status{$host}{endTime} = time;
1016 if ( $Status{$host}{reason}
1017 eq "Reason_backup_canceled_by_user" ) {
1018 print(LOG $bpc->timeStamp,
1019 "Backup canceled on $host ($1)\n");
1021 $Status{$host}{reason} = "Reason_backup_failed";
1022 print(LOG $bpc->timeStamp,
1023 "Backup failed on $host ($1)\n");
1025 } elsif ( $mesg =~ /^restore failed: (.*)/ ) {
1026 $Status{$host}{state} = "Status_idle";
1027 $Status{$host}{error} = $1;
1028 $Status{$host}{errorTime} = time;
1029 $Status{$host}{endTime} = time;
1030 if ( $Status{$host}{reason}
1031 eq "Reason_restore_canceled_by_user" ) {
1032 print(LOG $bpc->timeStamp,
1033 "Restore canceled on $host ($1)\n");
1035 $Status{$host}{reason} = "Reason_restore_failed";
1036 print(LOG $bpc->timeStamp,
1037 "Restore failed on $host ($1)\n");
1039 } elsif ( $mesg =~ /^archive failed: (.*)/ ) {
1040 $Status{$host}{state} = "Status_idle";
1041 $Status{$host}{error} = $1;
1042 $Status{$host}{errorTime} = time;
1043 $Status{$host}{endTime} = time;
1044 if ( $Status{$host}{reason}
1045 eq "Reason_archive_canceled_by_user" ) {
1046 print(LOG $bpc->timeStamp,
1047 "Archive canceled on $host ($1)\n");
1049 $Status{$host}{reason} = "Reason_archive_failed";
1050 print(LOG $bpc->timeStamp,
1051 "Archive failed on $host ($1)\n");
1053 } elsif ( $mesg =~ /^log\s+(.*)/ ) {
1054 print(LOG $bpc->timeStamp, "$1\n");
1055 } elsif ( $mesg =~ /^BackupPC_stats (\d+) = (.*)/ ) {
1056 my $chunk = int($1 / 16);
1057 my @f = split(/,/, $2);
1058 $Info{pool}{$f[0]}[$chunk]{FileCnt} += $f[1];
1059 $Info{pool}{$f[0]}[$chunk]{DirCnt} += $f[2];
1060 $Info{pool}{$f[0]}[$chunk]{Kb} += $f[3];
1061 $Info{pool}{$f[0]}[$chunk]{Kb2} += $f[4];
1062 $Info{pool}{$f[0]}[$chunk]{KbRm} += $f[5];
1063 $Info{pool}{$f[0]}[$chunk]{FileCntRm} += $f[6];
1064 $Info{pool}{$f[0]}[$chunk]{FileCntRep} += $f[7];
1065 $Info{pool}{$f[0]}[$chunk]{FileRepMax} = $f[8]
1066 if ( $Info{pool}{$f[0]}[$chunk]{FileRepMax} < $f[8] );
1067 $Info{pool}{$f[0]}[$chunk]{FileCntRename} += $f[9];
1068 $Info{pool}{$f[0]}[$chunk]{FileLinkMax} = $f[10]
1069 if ( $Info{pool}{$f[0]}[$chunk]{FileLinkMax} < $f[10] );
1070 $Info{pool}{$f[0]}[$chunk]{FileLinkTotal} += $f[11];
1071 $Info{pool}{$f[0]}[$chunk]{Time} = time;
1072 } elsif ( $mesg =~ /^BackupPC_nightly lock_off/ ) {
1073 $BackupPCNightlyLock--;
1074 if ( $BackupPCNightlyLock == 0 ) {
1076 # This means the last BackupPC_nightly is done with
1077 # the pool clean, so it's ok to start running regular
1078 # backups again. But starting in 3.0 regular jobs
1079 # are decoupled from BackupPC_nightly.
1081 $RunNightlyWhenIdle = 0;
1083 } elsif ( $mesg =~ /^processState\s+(.+)/ ) {
1084 $Jobs{$host}{processState} = $1;
1085 } elsif ( $mesg =~ /^link\s+(.+)/ ) {
1087 $Status{$h}{needLink} = 1;
1089 print(LOG $bpc->timeStamp, "$host: $mesg\n");
1093 # shut down the client connection if we read EOF
1095 if ( $nbytes <= 0 ) {
1096 close($Jobs{$host}{fh});
1097 vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1098 if ( $CmdJob eq $host || $bpc->isAdminJob($host) ) {
1099 my $cmd = $Jobs{$host}{cmd};
1100 $cmd =~ s/$BinDir\///g;
1101 print(LOG $bpc->timeStamp, "Finished $host ($cmd)\n");
1102 $Status{$host}{state} = "Status_idle";
1103 $Status{$host}{endTime} = time;
1104 if ( $cmd =~ /^BackupPC_nightly\s/ ) {
1105 $BackupPCNightlyJobs--;
1106 #print(LOG $bpc->timeStamp, "BackupPC_nightly done; now"
1107 # . " have $BackupPCNightlyJobs running\n");
1108 if ( $BackupPCNightlyJobs <= 0 ) {
1110 # Last BackupPC_nightly has finished
1112 $BackupPCNightlyJobs = 0;
1113 $RunNightlyWhenIdle = 0;
1116 # Combine the 16 per-directory results
1118 for my $p ( qw(pool cpool) ) {
1119 $Info{"${p}FileCnt"} = 0;
1120 $Info{"${p}DirCnt"} = 0;
1121 $Info{"${p}Kb"} = 0;
1122 $Info{"${p}Kb2"} = 0;
1123 $Info{"${p}KbRm"} = 0;
1124 $Info{"${p}FileCntRm"} = 0;
1125 $Info{"${p}FileCntRep"} = 0;
1126 $Info{"${p}FileRepMax"} = 0;
1127 $Info{"${p}FileCntRename"} = 0;
1128 $Info{"${p}FileLinkMax"} = 0;
1129 $Info{"${p}Time"} = 0;
1130 for ( my $i = 0 ; $i < 16 ; $i++ ) {
1131 $Info{"${p}FileCnt"}
1132 += $Info{pool}{$p}[$i]{FileCnt};
1134 += $Info{pool}{$p}[$i]{DirCnt};
1136 += $Info{pool}{$p}[$i]{Kb};
1138 += $Info{pool}{$p}[$i]{Kb2};
1140 += $Info{pool}{$p}[$i]{KbRm};
1141 $Info{"${p}FileCntRm"}
1142 += $Info{pool}{$p}[$i]{FileCntRm};
1143 $Info{"${p}FileCntRep"}
1144 += $Info{pool}{$p}[$i]{FileCntRep};
1145 $Info{"${p}FileRepMax"}
1146 = $Info{pool}{$p}[$i]{FileRepMax}
1147 if ( $Info{"${p}FileRepMax"} <
1148 $Info{pool}{$p}[$i]{FileRepMax} );
1149 $Info{"${p}FileCntRename"}
1150 += $Info{pool}{$p}[$i]{FileCntRename};
1151 $Info{"${p}FileLinkMax"}
1152 = $Info{pool}{$p}[$i]{FileLinkMax}
1153 if ( $Info{"${p}FileLinkMax"} <
1154 $Info{pool}{$p}[$i]{FileLinkMax} );
1155 $Info{"${p}Time"} = $Info{pool}{$p}[$i]{Time}
1156 if ( $Info{"${p}Time"} <
1157 $Info{pool}{$p}[$i]{Time} );
1159 printf(LOG "%s%s nightly clean removed %d files of"
1161 $bpc->timeStamp, ucfirst($p),
1162 $Info{"${p}FileCntRm"},
1163 $Info{"${p}KbRm"} / (1000 * 1024));
1164 printf(LOG "%s%s is %.2fGB, %d files (%d repeated, "
1165 . "%d max chain, %d max links), %d directories\n",
1166 $bpc->timeStamp, ucfirst($p),
1167 $Info{"${p}Kb"} / (1000 * 1024),
1168 $Info{"${p}FileCnt"}, $Info{"${p}FileCntRep"},
1169 $Info{"${p}FileRepMax"},
1170 $Info{"${p}FileLinkMax"}, $Info{"${p}DirCnt"});
1178 # Queue BackupPC_link to complete the backup
1179 # processing for this host.
1181 if ( defined($Status{$host})
1182 && ($Status{$host}{reason} eq "Reason_backup_done"
1183 || $Status{$host}{needLink}) ) {
1185 } elsif ( defined($Status{$host}) ) {
1186 $Status{$host}{state} = "Status_idle";
1189 delete($Jobs{$host});
1190 $Status{$host}{activeJob} = 0 if ( defined($Status{$host}) );
1194 # When we are idle (empty Jobs, CmdQueue, BgQueue, UserQueue) we
1195 # do a pass over %Status updating the deadCnt and aliveCnt for
1196 # DHCP hosts. The reason we need to do this later is we can't
1197 # be sure whether a DHCP host is alive or dead until we have passed
1198 # over all the DHCP pool.
1200 return if ( @CmdQueue || @BgQueue || @UserQueue || keys(%Jobs) > 1 );
1201 foreach my $host ( keys(%Status) ) {
1202 next if ( $Status{$host}{dhcpCheckCnt} <= 0 );
1203 $Status{$host}{deadCnt} += $Status{$host}{dhcpCheckCnt};
1204 $Status{$host}{dhcpCheckCnt} = 0;
1205 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1206 $Status{$host}{aliveCnt} = 0;
1211 ############################################################################
1212 # Main_Check_Client_Messages($fdRead)
1214 # Check for, and process, any output from our clients. Also checks
1215 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
1216 ############################################################################
1217 sub Main_Check_Client_Messages
1220 foreach my $client ( keys(%Clients) ) {
1221 next if ( !vec($fdRead, $Clients{$client}{fn}, 1) );
1224 # do a last check to make sure there is something to read so
1225 # we are absolutely sure we won't block.
1227 vec(my $readMask, $Clients{$client}{fn}, 1) = 1;
1228 if ( !select($readMask, undef, undef, 0.0) ) {
1229 print(LOG $bpc->timeStamp, "Botch in Main_Check_Client_Messages:"
1230 . " nothing to read from $client. Debug dump:\n");
1231 my($dump) = Data::Dumper->new(
1232 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
1233 [qw(*Clients, *Jobs *FDread, *fdRead)]);
1235 print(LOG $dump->Dump);
1238 my $nbytes = sysread($Clients{$client}{fh}, $mesg, 1024);
1239 $Clients{$client}{mesg} .= $mesg if ( $nbytes > 0 );
1241 # Process any complete lines received from this client.
1243 while ( $Clients{$client}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
1246 $Clients{$client}{mesg} = $2;
1248 # Authenticate the message by checking the MD5 digest
1250 my $md5 = Digest::MD5->new;
1251 if ( $cmd !~ /^(.{22}) (.*)/
1252 || ($md5->add($Clients{$client}{seed}
1253 . $Clients{$client}{mesgCnt}
1254 . $Conf{ServerMesgSecret} . $2),
1255 $md5->b64digest ne $1) ) {
1256 print(LOG $bpc->timeStamp, "Corrupted message '$cmd' from"
1257 . " client '$Clients{$client}{clientName}':"
1258 . " shutting down client connection\n");
1262 $Clients{$client}{mesgCnt}++;
1264 if ( $cmd =~ /^stop (\S+)\s+(\S+)\s+(\S*)/ ) {
1268 $host = $bpc->uriUnesc($host);
1269 if ( $CmdJob ne $host && defined($Status{$host})
1270 && defined($Jobs{$host}) ) {
1271 print(LOG $bpc->timeStamp,
1272 "Stopping current $Jobs{$host}{type} of $host,"
1273 . " request by $user (backoff=$backoff)\n");
1274 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1276 # Don't close the pipe now; wait until the child
1277 # really exits later. Otherwise close() will
1278 # block until the child has exited.
1280 ##vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1281 ##close($Jobs{$host}{fh});
1282 ##delete($Jobs{$host});
1284 $Status{$host}{state} = "Status_idle";
1285 if ( $Jobs{$host}{type} eq "restore" ) {
1286 $Status{$host}{reason}
1287 = "Reason_restore_canceled_by_user";
1288 } elsif ( $Jobs{$host}{type} eq "archive" ) {
1289 $Status{$host}{reason}
1290 = "Reason_archive_canceled_by_user";
1292 $Status{$host}{reason}
1293 = "Reason_backup_canceled_by_user";
1295 $Status{$host}{activeJob} = 0;
1296 $Status{$host}{startTime} = time;
1297 $reply = "ok: $Jobs{$host}{type} of $host canceled";
1298 } elsif ( $BgQueueOn{$host} || $UserQueueOn{$host} ) {
1299 print(LOG $bpc->timeStamp,
1300 "Stopping pending backup of $host,"
1301 . " request by $user (backoff=$backoff)\n");
1302 @BgQueue = grep($_->{host} ne $host, @BgQueue);
1303 @UserQueue = grep($_->{host} ne $host, @UserQueue);
1304 $BgQueueOn{$host} = $UserQueueOn{$host} = 0;
1305 $reply = "ok: pending backup of $host canceled";
1307 print(LOG $bpc->timeStamp,
1308 "Nothing to do for stop backup of $host,"
1309 . " request by $user (backoff=$backoff)\n");
1310 $reply = "ok: no backup was pending or running";
1312 if ( defined($Status{$host}) && $backoff ne "" ) {
1313 if ( $backoff > 0 ) {
1314 $Status{$host}{backoffTime} = time + $backoff * 3600;
1316 delete($Status{$host}{backoffTime});
1319 } elsif ( $cmd =~ /^backup all$/ ) {
1321 } elsif ( $cmd =~ /^BackupPC_nightly run$/ ) {
1322 $RunNightlyWhenIdle = 1;
1323 } elsif ( $cmd =~ /^backup (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1328 $host = $bpc->uriUnesc($host);
1329 $hostIP = $bpc->uriUnesc($hostIP);
1330 if ( !defined($Status{$host}) ) {
1331 print(LOG $bpc->timeStamp,
1332 "User $user requested backup of unknown host"
1334 $reply = "error: unknown host $host";
1336 print(LOG $bpc->timeStamp,
1337 "User $user requested backup of $host"
1339 if ( $BgQueueOn{$hostIP} ) {
1340 @BgQueue = grep($_->{host} ne $hostIP, @BgQueue);
1341 $BgQueueOn{$hostIP} = 0;
1343 if ( $UserQueueOn{$hostIP} ) {
1344 @UserQueue = grep($_->{host} ne $hostIP, @UserQueue);
1345 $UserQueueOn{$hostIP} = 0;
1347 unshift(@UserQueue, {
1353 dhcp => $hostIP eq $host ? 0 : 1,
1355 $UserQueueOn{$hostIP} = 1;
1356 $reply = "ok: requested backup of $host";
1358 } elsif ( $cmd =~ /^archive (\S+)\s+(\S+)\s+(\S+)/ ) {
1360 my $archivehost = $2;
1361 my $reqFileName = $3;
1362 $host = $bpc->uriUnesc($archivehost);
1363 if ( !defined($Status{$host}) ) {
1364 print(LOG $bpc->timeStamp,
1365 "User $user requested archive of unknown archive host"
1367 $reply = "archive error: unknown archive host $host";
1369 print(LOG $bpc->timeStamp,
1370 "User $user requested archive on $host"
1372 if ( defined($Jobs{$host}) ) {
1373 $reply = "Archive currently running on $host, please try later";
1375 unshift(@UserQueue, {
1378 reqFileName => $reqFileName,
1384 $UserQueueOn{$host} = 1;
1385 $reply = "ok: requested archive on $host";
1388 } elsif ( $cmd =~ /^restore (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1392 my $reqFileName = $4;
1393 $host = $bpc->uriUnesc($host);
1394 $hostIP = $bpc->uriUnesc($hostIP);
1395 if ( !defined($Status{$host}) ) {
1396 print(LOG $bpc->timeStamp,
1397 "User $user requested restore to unknown host"
1399 $reply = "restore error: unknown host $host";
1401 print(LOG $bpc->timeStamp,
1402 "User $user requested restore to $host"
1404 unshift(@UserQueue, {
1407 reqFileName => $reqFileName,
1413 $UserQueueOn{$host} = 1;
1414 if ( defined($Jobs{$host}) ) {
1415 $reply = "ok: requested restore of $host, but a"
1416 . " job is currently running,"
1417 . " so this request will start later";
1419 $reply = "ok: requested restore of $host";
1422 } elsif ( $cmd =~ /^status\s*(.*)/ ) {
1424 my($dump, @values, @names);
1425 foreach my $type ( split(/\s+/, $args) ) {
1426 if ( $type =~ /^queues/ ) {
1427 push(@values, \@BgQueue, \@UserQueue, \@CmdQueue);
1428 push(@names, qw(*BgQueue *UserQueue *CmdQueue));
1429 } elsif ( $type =~ /^jobs/ ) {
1430 push(@values, \%Jobs);
1431 push(@names, qw(*Jobs));
1432 } elsif ( $type =~ /^queueLen/ ) {
1434 BgQueue => scalar(@BgQueue),
1435 UserQueue => scalar(@UserQueue),
1436 CmdQueue => scalar(@CmdQueue),
1438 push(@names, qw(*QueueLen));
1439 } elsif ( $type =~ /^info/ ) {
1440 push(@values, \%Info);
1441 push(@names, qw(*Info));
1442 } elsif ( $type =~ /^hosts/ ) {
1443 push(@values, \%Status);
1444 push(@names, qw(*Status));
1445 } elsif ( $type =~ /^host\((.*)\)/ ) {
1446 my $h = $bpc->uriUnesc($1);
1447 if ( defined($Status{$h}) ) {
1450 BgQueueOn => $BgQueueOn{$h},
1451 UserQueueOn => $UserQueueOn{$h},
1452 CmdQueueOn => $CmdQueueOn{$h},
1454 push(@names, qw(*StatusHost));
1456 print(LOG $bpc->timeStamp,
1457 "Unknown host $h for status request\n");
1460 print(LOG $bpc->timeStamp,
1461 "Unknown status request $type\n");
1464 $dump = Data::Dumper->new(\@values, \@names);
1466 $reply = $dump->Dump;
1467 } elsif ( $cmd =~ /^link\s+(.+)/ ) {
1469 $host = $bpc->uriUnesc($host);
1471 } elsif ( $cmd =~ /^log\s+(.*)/ ) {
1472 print(LOG $bpc->timeStamp, "$1\n");
1473 } elsif ( $cmd =~ /^server\s+(\w+)/ ) {
1475 if ( $type eq 'reload' ) {
1476 ServerReload("Reloading config/host files via CGI request");
1477 } elsif ( $type eq 'shutdown' ) {
1478 $reply = "Shutting down...\n";
1479 syswrite($Clients{$client}{fh}, $reply, length($reply));
1480 ServerShutdown("Server shutting down...");
1482 } elsif ( $cmd =~ /^quit/ || $cmd =~ /^exit/ ) {
1486 print(LOG $bpc->timeStamp, "Unknown command $cmd\n");
1487 $reply = "error: bad command $cmd";
1490 # send a reply to the client, at a minimum "ok\n".
1492 $reply = "ok" if ( $reply eq "" );
1494 syswrite($Clients{$client}{fh}, $reply, length($reply));
1497 # Detect possible denial-of-service attack from sending a huge line
1498 # (ie: never terminated). 32K seems to be plenty big enough as
1501 if ( length($Clients{$client}{mesg}) > 32 * 1024 ) {
1502 print(LOG $bpc->timeStamp, "Line too long from client"
1503 . " '$Clients{$client}{clientName}':"
1504 . " shutting down client connection\n");
1508 # Shut down the client connection if we read EOF
1510 if ( $nbytes <= 0 ) {
1511 close($Clients{$client}{fh});
1512 vec($FDread, $Clients{$client}{fn}, 1) = 0;
1513 delete($Clients{$client});
1517 # Accept any new connections on each of our listen sockets
1519 if ( vec($fdRead, fileno(SERVER_UNIX), 1) ) {
1521 my $paddr = accept(CLIENT, SERVER_UNIX);
1523 $Clients{$ClientConnCnt}{clientName} = "unix socket";
1524 $Clients{$ClientConnCnt}{mesg} = "";
1525 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1526 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1527 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1529 # Generate and send unique seed for MD5 digests to avoid
1530 # replay attacks. See BackupPC::Lib::ServerMesg().
1532 my $seed = time . ",$ClientConnCnt,$$,0\n";
1533 $Clients{$ClientConnCnt}{seed} = $seed;
1534 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1535 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1537 if ( $ServerInetPort > 0 && vec($fdRead, fileno(SERVER_INET), 1) ) {
1539 my $paddr = accept(CLIENT, SERVER_INET);
1540 my($port,$iaddr) = sockaddr_in($paddr);
1541 my $name = gethostbyaddr($iaddr, AF_INET);
1543 $Clients{$ClientConnCnt}{mesg} = "";
1544 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1545 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1546 $Clients{$ClientConnCnt}{clientName} = "$name:$port";
1547 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1549 # Generate and send unique seed for MD5 digests to avoid
1550 # replay attacks. See BackupPC::Lib::ServerMesg().
1552 my $seed = time . ",$ClientConnCnt,$$,$port\n";
1553 $Clients{$ClientConnCnt}{seed} = $seed;
1554 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1555 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1559 ###########################################################################
1560 # Miscellaneous subroutines
1561 ###########################################################################
1564 # Write the current status to $LogDir/status.pl
1568 my($dump) = Data::Dumper->new(
1569 [ \%Info, \%Status],
1570 [qw(*Info *Status)]);
1572 if ( open(STATUS, ">", "$LogDir/status.pl") ) {
1573 print(STATUS $dump->Dump);
1579 # Compare function for host sort. Hosts with errors go first,
1580 # sorted with the oldest errors first. The remaining hosts
1581 # are sorted so that those with the oldest backups go first.
1586 # Hosts with errors go before hosts without errors
1588 return -1 if ( $Status{$a}{error} ne "" && $Status{$b}{error} eq "" );
1591 # Hosts with no errors go after hosts with errors
1594 return 1 if ( $Status{$a}{error} eq "" && $Status{$b}{error} ne "" );
1597 # hosts with the older last good backups sort earlier
1599 my $r = $Status{$a}{lastGoodBackupTime} <=> $Status{$b}{lastGoodBackupTime};
1600 return $r if ( $r );
1603 # Finally, just sort based on host name
1609 # Queue all the hosts for backup. This means queuing all the fixed
1610 # ip hosts and all the dhcp address ranges. We also additionally
1611 # queue the dhcp hosts with a -e flag to check for expired dumps.
1616 foreach my $host ( sort(HostSortCompare keys(%$Hosts)) ) {
1617 delete($Status{$host}{backoffTime})
1618 if ( defined($Status{$host}{backoffTime})
1619 && $Status{$host}{backoffTime} < time );
1620 next if ( defined($Jobs{$host})
1621 || $BgQueueOn{$host}
1622 || $UserQueueOn{$host}
1623 || $CmdQueueOn{$host} );
1624 if ( $Hosts->{$host}{dhcp} ) {
1625 $Status{$host}{dhcpCheckCnt}++;
1626 if ( $RunNightlyWhenIdle ) {
1628 # Once per night queue a check for DHCP hosts that just
1629 # checks for expired dumps. We need to do this to handle
1630 # the case when a DHCP host has not been on the network for
1631 # a long time, and some of the old dumps need to be expired.
1632 # Normally expiry checks are done by BackupPC_dump only
1633 # after the DHCP hosts has been detected on the network.
1636 {host => $host, user => "BackupPC", reqTime => time,
1637 dhcp => 0, dumpExpire => 1});
1638 $BgQueueOn{$host} = 1;
1642 # this is a fixed ip host: queue it
1644 if ( $Info{DUlastValue} > $Conf{DfMaxUsagePct} ) {
1646 # Since we are out of disk space, instead of queuing
1647 # a regular job, queue an expire check instead. That
1648 # way if the admin reduces the number of backups to
1649 # keep then we will actually delete them. Otherwise
1650 # BackupPC_dump will never run since we have exceeded
1655 {host => $host, user => "BackupPC", reqTime => time,
1656 dhcp => $Hosts->{$host}{dhcp}, dumpExpire => 1});
1659 # Queue regular background backup
1662 {host => $host, user => "BackupPC", reqTime => time,
1663 dhcp => $Hosts->{$host}{dhcp}});
1665 $BgQueueOn{$host} = 1;
1669 print(LOG $bpc->timeStamp,
1670 "Disk too full ($Info{DUlastValue}%); skipped $nSkip hosts\n");
1671 $Info{DUDailySkipHostCnt} += $nSkip;
1673 foreach my $dhcp ( @{$Conf{DHCPAddressRanges}} ) {
1674 for ( my $i = $dhcp->{first} ; $i <= $dhcp->{last} ; $i++ ) {
1675 my $ipAddr = "$dhcp->{ipAddrBase}.$i";
1676 next if ( defined($Jobs{$ipAddr})
1677 || $BgQueueOn{$ipAddr}
1678 || $UserQueueOn{$ipAddr}
1679 || $CmdQueueOn{$ipAddr} );
1681 # this is a potential dhcp ip address (we don't know the
1682 # host name yet): queue it
1685 {host => $ipAddr, user => "BackupPC", reqTime => time,
1687 $BgQueueOn{$ipAddr} = 1;
1693 # Queue a BackupPC_link for the given host
1699 return if ( $CmdQueueOn{$host} );
1700 $Status{$host}{state} = "Status_link_pending";
1701 $Status{$host}{needLink} = 0;
1702 unshift(@CmdQueue, {
1706 cmd => ["$BinDir/BackupPC_link", $host],
1708 $CmdQueueOn{$host} = 1;
1712 # Read the hosts file, and update Status if any hosts have been
1713 # added or deleted. We also track the mtime so the only need to
1714 # update the hosts file on changes.
1716 # This function is called at startup, SIGHUP, and on each wakeup.
1717 # It returns 1 on success and undef on failure.
1724 # Nothing to do if we already have the current hosts file
1726 return 1 if ( !$force && defined($Hosts)
1727 && $Info{HostsModTime} == $bpc->HostsMTime() );
1728 if ( !defined($newHosts = $bpc->HostInfoRead()) ) {
1729 print(LOG $bpc->timeStamp, "Can't read hosts file!\n");
1732 print(LOG $bpc->timeStamp, "Reading hosts file\n");
1734 $Info{HostsModTime} = $bpc->HostsMTime();
1736 # Now update %Status in case any hosts have been added or deleted
1738 foreach my $host ( sort(keys(%$Hosts)) ) {
1739 next if ( defined($Status{$host}) );
1740 $Status{$host}{state} = "Status_idle";
1741 print(LOG $bpc->timeStamp, "Added host $host to backup list\n");
1743 foreach my $host ( sort(keys(%Status)) ) {
1744 next if ( $host eq $bpc->trashJob
1745 || $bpc->isAdminJob($host)
1746 || defined($Hosts->{$host})
1747 || defined($Jobs{$host})
1748 || $BgQueueOn{$host}
1749 || $UserQueueOn{$host}
1750 || $CmdQueueOn{$host} );
1751 print(LOG $bpc->timeStamp, "Deleted host $host from backup list\n");
1752 delete($Status{$host});
1758 # Remember the signal name for later processing
1764 foreach my $host ( keys(%Jobs) ) {
1765 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1768 # In case we are inside the exit handler, reopen the log file
1772 print(LOG "Fatal error: unhandled signal $SigName\n");
1773 unlink("$LogDir/BackupPC.pid");
1774 confess("Got new signal $SigName... quitting\n");
1781 # Open the log file and point STDOUT and STDERR there too
1785 mkpath($LogDir, 0, 0777) if ( !-d $LogDir );
1786 open(LOG, ">>$LogDir/LOG")
1787 || die("Can't create LOG file $LogDir/LOG");
1790 open(STDOUT, ">&LOG");
1791 open(STDERR, ">&LOG");
1792 select(LOG); $| = 1;
1793 select(STDERR); $| = 1;
1794 select(STDOUT); $| = 1;
1798 # Initialize the unix-domain and internet-domain sockets that
1799 # we listen to for client connections (from the CGI script and
1800 # some of the BackupPC sub-programs).
1802 sub ServerSocketInit
1804 if ( !defined(fileno(SERVER_UNIX)) ) {
1806 # one-time only: initialize unix-domain socket
1808 if ( !socket(SERVER_UNIX, PF_UNIX, SOCK_STREAM, 0) ) {
1809 print(LOG $bpc->timeStamp, "unix socket() failed: $!\n");
1812 my $sockFile = "$LogDir/BackupPC.sock";
1814 if ( !bind(SERVER_UNIX, sockaddr_un($sockFile)) ) {
1815 print(LOG $bpc->timeStamp, "unix bind() failed: $!\n");
1818 if ( !listen(SERVER_UNIX, SOMAXCONN) ) {
1819 print(LOG $bpc->timeStamp, "unix listen() failed: $!\n");
1822 vec($FDread, fileno(SERVER_UNIX), 1) = 1;
1824 return if ( $ServerInetPort == $Conf{ServerPort} );
1825 if ( $ServerInetPort > 0 ) {
1826 vec($FDread, fileno(SERVER_INET), 1) = 0;
1828 $ServerInetPort = -1;
1830 if ( $Conf{ServerPort} > 0 ) {
1832 # Setup a socket to listen on $Conf{ServerPort}
1834 my $proto = getprotobyname('tcp');
1835 if ( !socket(SERVER_INET, PF_INET, SOCK_STREAM, $proto) ) {
1836 print(LOG $bpc->timeStamp, "inet socket() failed: $!\n");
1839 if ( !setsockopt(SERVER_INET, SOL_SOCKET, SO_REUSEADDR, pack("l",1)) ) {
1840 print(LOG $bpc->timeStamp, "setsockopt() failed: $!\n");
1843 if ( !bind(SERVER_INET, sockaddr_in($Conf{ServerPort}, INADDR_ANY)) ) {
1844 print(LOG $bpc->timeStamp, "inet bind() failed: $!\n");
1847 if ( !listen(SERVER_INET, SOMAXCONN) ) {
1848 print(LOG $bpc->timeStamp, "inet listen() failed: $!\n");
1851 vec($FDread, fileno(SERVER_INET), 1) = 1;
1852 $ServerInetPort = $Conf{ServerPort};
1857 # Reload the server. Used by Main_Process_Signal when $SigName eq "HUP"
1858 # or when the command "server reload" is received.
1863 $mesg = $bpc->ConfigRead() || $mesg;
1864 print(LOG $bpc->timeStamp, "$mesg\n");
1865 $Info{ConfigModTime} = $bpc->ConfigMTime();
1866 %Conf = $bpc->Conf();
1867 umask($Conf{UmaskMode});
1871 $Info{ConfigLTime} = time;
1875 # Gracefully shutdown the server. Used by Main_Process_Signal when
1876 # $SigName ne "" && $SigName ne "HUP" or when the command
1877 # "server shutdown" is received.
1882 print(LOG $bpc->timeStamp, "$mesg\n");
1883 if ( keys(%Jobs) ) {
1884 foreach my $host ( keys(%Jobs) ) {
1885 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1888 foreach my $host ( keys(%Jobs) ) {
1889 kill($bpc->sigName2num("KILL"), $Jobs{$host}{pid});
1895 unlink("$LogDir/BackupPC.pid");