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;
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 %Conf = $bpc->Conf();
93 # Verify we are running as the correct user
95 if ( $Conf{BackupPCUserVerify}
96 && $> != (my $uid = (getpwnam($Conf{BackupPCUser}))[2]) ) {
97 die "Wrong user: my userid is $>, instead of $uid ($Conf{BackupPCUser})\n";
101 # %Status maintain status information about each host.
102 # It is a hash of hashes, whose first index is the host.
107 # %Info is a hash giving general information about BackupPC status.
114 if ( -f "$TopDir/log/status.pl" && !(my $ret = do "$TopDir/log/status.pl") ) {
115 die "couldn't parse $TopDir/log/status.pl: $@" if $@;
116 die "couldn't do $TopDir/log/status.pl: $!" unless defined $ret;
117 die "couldn't run $TopDir/log/status.pl";
121 # %Jobs maintains information about currently running jobs.
122 # It is a hash of hashes, whose first index is the host.
127 # There are three command queues:
128 # - @UserQueue is a queue of user initiated backup requests.
129 # - @BgQueue is a queue of automatically scheduled backup requests.
130 # - @CmdQueue is a queue of administrative jobs, including tasks
131 # like BackupPC_link, BackupPC_trashClean, and BackupPC_nightly
132 # Each queue is an array of hashes. Each hash stores information
133 # about the command request.
140 # To quickly lookup if a given host is on a given queue, we keep
141 # a hash of flags for each queue type.
143 my(%CmdQueueOn, %UserQueueOn, %BgQueueOn);
146 # One or more clients can connect to the server to get status information
147 # or request/cancel backups etc. The %Clients hash maintains information
148 # about each of these socket connections. The hash key is an incrementing
149 # number stored in $ClientConnCnt. Each entry is a hash that contains
150 # various information about the client connection.
156 # Read file descriptor mask used by select(). Every file descriptor
157 # on which we expect to read (or accept) has the corresponding bit
163 # Unix seconds when we next wakeup. A value of zero forces the scheduler
164 # to compute the next wakeup time.
169 # Name of signal saved by catch_signal
176 my($RunNightlyWhenIdle, $FirstWakeup, $CmdJob, $ServerInetPort);
177 my($BackupPCNightlyJobs, $BackupPCNightlyLock);
180 # Complete the rest of the initialization
184 ###########################################################################
186 ###########################################################################
190 # Check if we can/should run BackupPC_nightly
192 Main_TryToRun_nightly();
195 # Check if we can run a new command from @CmdQueue.
197 Main_TryToRun_CmdQueue();
200 # Check if we can run a new command from @UserQueue or @BgQueue.
202 Main_TryToRun_Bg_or_User_Queue();
205 # Do a select() to wait for the next interesting thing to happen
206 # (timeout, signal, someone sends a message, child dies etc).
208 my $fdRead = Main_Select();
211 # Process a signal if we received one.
214 Main_Process_Signal();
219 # Check if a timeout has occurred.
221 Main_Check_Timeout();
224 # Check for, and process, any messages (output) from our jobs
226 Main_Check_Job_Messages($fdRead);
229 # Check for, and process, any output from our clients. Also checks
230 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
232 Main_Check_Client_Messages($fdRead);
235 ############################################################################
238 # Main initialization routine. Called once at statup.
239 ############################################################################
242 umask($Conf{UmaskMode});
245 # Check for another running process, check that PASSWD is set and
246 # verify executables are configured correctly.
248 if ( $Info{pid} ne "" && kill(0, $Info{pid}) ) {
249 print(STDERR $bpc->timeStamp,
250 "Another BackupPC is running (pid $Info{pid}); quitting...\n");
253 foreach my $progName ( qw(SmbClientPath NmbLookupPath PingPath DfPath
254 SendmailPath SshPath) ) {
255 next if ( $Conf{$progName} eq "" || -x $Conf{$progName} );
256 print(STDERR $bpc->timeStamp,
257 "\$Conf{$progName} = '$Conf{$progName}' is not a"
258 . " valid executable program\n");
264 # daemonize by forking; more robust method per:
265 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=301057
268 defined($pid = fork) or die("Can't fork: $!");
269 exit if( $pid ); # parent exits
272 defined($pid = fork) or die("Can't fork: $!");
273 exit if $pid; # parent exits
275 chdir ("/") or die("Cannot chdir to /: $!\n");
277 open(STDIN , ">/dev/null") or die("Cannot open /dev/null as stdin\n");
278 # STDOUT and STDERR are handled in LogFileOpen() right below,
279 # otherwise we would have to reopen them too.
283 # Open the LOG file and redirect STDOUT, STDERR etc
288 # Read the hosts file (force a read).
290 exit(1) if ( !HostsUpdate(1) );
293 # Clean up %ENV for taint checking
295 delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
296 $ENV{PATH} = $Conf{MyPath};
299 # Initialize server sockets
304 # Catch various signals
306 foreach my $sig ( qw(INT BUS SEGV PIPE TERM ALRM HUP) ) {
307 $SIG{$sig} = \&catch_signal;
311 # Report that we started, and update %Info.
313 print(LOG $bpc->timeStamp, "BackupPC started, pid $$\n");
314 $Info{ConfigModTime} = $bpc->ConfigMTime();
316 $Info{startTime} = time;
317 $Info{ConfigLTime} = time;
318 $Info{Version} = $bpc->{Version};
321 # Update the status left over form the last time BackupPC ran.
322 # Requeue any pending links.
324 foreach my $host ( sort(keys(%$Hosts)) ) {
325 if ( $Status{$host}{state} eq "Status_backup_in_progress" ) {
327 # should we restart it? skip it for now.
329 $Status{$host}{state} = "Status_idle";
330 } elsif ( $Status{$host}{state} eq "Status_link_pending"
331 || $Status{$host}{state} eq "Status_link_running" ) {
334 $Status{$host}{state} = "Status_idle";
336 $Status{$host}{activeJob} = 0;
338 foreach my $host ( sort(keys(%Status)) ) {
339 next if ( defined($Hosts->{$host}) );
340 delete($Status{$host});
344 # Write out our initial status and save our PID
347 if ( open(PID, ">", "$TopDir/log/BackupPC.pid") ) {
353 # For unknown reasons there is a very infrequent error about not
354 # being able to coerce GLOBs inside the XS Data::Dumper. I've
355 # only seen this on a particular platform and perl version.
356 # For now the workaround appears to be use the perl version of
359 $Data::Dumper::Useqq = 1;
362 ############################################################################
363 # Main_TryToRun_nightly()
365 # Checks to see if we can/should run BackupPC_nightly or
366 # BackupPC_trashClean. If so we push the appropriate command onto
368 ############################################################################
369 sub Main_TryToRun_nightly
372 # Check if we should run BackupPC_nightly or BackupPC_trashClean.
373 # BackupPC_nightly is run when the current job queue is empty.
374 # BackupPC_trashClean is run in the background always.
376 my $trashCleanRunning = defined($Jobs{$bpc->trashJob}) ? 1 : 0;
377 if ( !$trashCleanRunning && !$CmdQueueOn{$bpc->trashJob} ) {
379 # This should only happen once at startup, but just in case this
380 # code will re-start BackupPC_trashClean if it quits
383 host => $bpc->trashJob,
386 cmd => ["$BinDir/BackupPC_trashClean"],
388 $CmdQueueOn{$bpc->trashJob} = 1;
390 if ( keys(%Jobs) == $trashCleanRunning && $RunNightlyWhenIdle == 1 ) {
393 # Queue multiple nightly jobs based on the configuration
395 $Conf{MaxBackupPCNightlyJobs} = 1
396 if ( $Conf{MaxBackupPCNightlyJobs} <= 0 );
397 $Conf{BackupPCNightlyPeriod} = 1
398 if ( $Conf{BackupPCNightlyPeriod} <= 0 );
400 # Decide what subset of the 16 top-level directories 0..9a..f
401 # we run BackupPC_nightly on, based on $Conf{BackupPCNightlyPeriod}.
402 # If $Conf{BackupPCNightlyPeriod} == 1 then we run 0..15 every
403 # time. If $Conf{BackupPCNightlyPeriod} == 2 then we run
404 # 0..7 one night and 89a-f the next night. And so on.
406 # $Info{NightlyPhase} counts which night, from 0 to
407 # $Conf{BackupPCNightlyPeriod} - 1.
409 my $start = int($Info{NightlyPhase} * 16
410 / $Conf{BackupPCNightlyPeriod});
411 my $end = int(($Info{NightlyPhase} + 1) * 16
412 / $Conf{BackupPCNightlyPeriod});
413 $end = $start + 1 if ( $end <= $start );
414 $Info{NightlyPhase}++;
415 $Info{NightlyPhase} = 0 if ( $end >= 16 );
418 # Zero out the data we expect to get from BackupPC_nightly.
419 # In the future if we want to split BackupPC_nightly over
420 # more than one night we will only zero out the portion
421 # that we are running right now.
423 for my $p ( qw(pool cpool) ) {
424 for ( my $i = $start ; $i < $end ; $i++ ) {
425 $Info{pool}{$p}[$i]{FileCnt} = 0;
426 $Info{pool}{$p}[$i]{DirCnt} = 0;
427 $Info{pool}{$p}[$i]{Kb} = 0;
428 $Info{pool}{$p}[$i]{Kb2} = 0;
429 $Info{pool}{$p}[$i]{KbRm} = 0;
430 $Info{pool}{$p}[$i]{FileCntRm} = 0;
431 $Info{pool}{$p}[$i]{FileCntRep} = 0;
432 $Info{pool}{$p}[$i]{FileRepMax} = 0;
433 $Info{pool}{$p}[$i]{FileCntRename} = 0;
434 $Info{pool}{$p}[$i]{FileLinkMax} = 0;
435 $Info{pool}{$p}[$i]{Time} = 0;
438 print(LOG $bpc->timeStamp,
439 sprintf("Running %d BackupPC_nightly jobs from %d..%d"
440 . " (out of 0..15)\n",
441 $Conf{MaxBackupPCNightlyJobs}, $start, $end - 1));
444 # Now queue the $Conf{MaxBackupPCNightlyJobs} jobs.
445 # The granularity on start and end is now 0..256.
450 for ( my $i = 0 ; $i < $Conf{MaxBackupPCNightlyJobs} ; $i++ ) {
452 # The first nightly job gets the -m option (does email, log aging).
453 # All jobs get the start and end options from 0..255 telling
454 # them which parts of the pool to traverse.
456 my $cmd = ["$BinDir/BackupPC_nightly"];
457 push(@$cmd, "-m") if ( $i == 0 );
459 $start = $start0 + int(($end - $start0)
460 * ($i + 1) / $Conf{MaxBackupPCNightlyJobs});
461 push(@$cmd, $start - 1);
463 my $job = $bpc->adminJob($i);
470 $CmdQueueOn{$job} = 1;
472 $RunNightlyWhenIdle = 2;
477 ############################################################################
478 # Main_TryToRun_CmdQueue()
480 # Decide if we can run a new command from the @CmdQueue.
481 # We only run one of these at a time. The @CmdQueue is
482 # used to run BackupPC_link (for the corresponding host),
483 # BackupPC_trashClean, and BackupPC_nightly using a fake
484 # host name of $bpc->adminJob.
485 ############################################################################
486 sub Main_TryToRun_CmdQueue
490 while ( $CmdJob eq "" && @CmdQueue > 0 && $RunNightlyWhenIdle != 1
491 || @CmdQueue > 0 && $RunNightlyWhenIdle == 2
492 && $bpc->isAdminJob($CmdQueue[0]->{host})
495 $req = pop(@CmdQueue);
497 $host = $req->{host};
498 if ( defined($Jobs{$host}) ) {
499 print(LOG $bpc->timeStamp,
500 "Botch on admin job for $host: already in use!!\n");
502 # This could happen during normal opertion: a user could
503 # request a backup while a BackupPC_link is queued from
504 # a previous backup. But it is unlikely. Just put this
505 # request back on the end of the queue.
507 unshift(@CmdQueue, $req);
510 $CmdQueueOn{$host} = 0;
511 my $cmd = $req->{cmd};
512 my $pid = open(FH, "-|");
513 if ( !defined($pid) ) {
514 print(LOG $bpc->timeStamp,
515 "can't fork for $host, request by $req->{user}\n");
522 print(LOG $bpc->timeStamp, "can't exec @$cmd for $host\n");
525 $Jobs{$host}{pid} = $pid;
526 $Jobs{$host}{fh} = *FH;
527 $Jobs{$host}{fn} = fileno(FH);
528 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
529 $Jobs{$host}{startTime} = time;
530 $Jobs{$host}{reqTime} = $req->{reqTime};
531 $cmd = $bpc->execCmd2ShellCmd(@$cmd);
532 $Jobs{$host}{cmd} = $cmd;
533 $Jobs{$host}{user} = $req->{user};
534 $Jobs{$host}{type} = $Status{$host}{type};
535 $Status{$host}{state} = "Status_link_running";
536 $Status{$host}{activeJob} = 1;
537 $Status{$host}{endTime} = time;
538 $CmdJob = $host if ( $host ne $bpc->trashJob );
539 $cmd =~ s/$BinDir\///g;
540 print(LOG $bpc->timeStamp, "Running $cmd (pid=$pid)\n");
541 if ( $cmd =~ /^BackupPC_nightly\s/ ) {
542 $BackupPCNightlyJobs++;
543 $BackupPCNightlyLock++;
548 ############################################################################
549 # Main_TryToRun_Bg_or_User_Queue()
551 # Decide if we can run any new backup requests from @BgQueue
552 # or @UserQueue. Several of these can be run at the same time
553 # based on %Conf settings. Jobs from @UserQueue take priority,
554 # and at total of $Conf{MaxBackups} + $Conf{MaxUserBackups}
555 # simultaneous jobs can run from @UserQueue. After @UserQueue
556 # is exhausted, up to $Conf{MaxBackups} simultaneous jobs can
558 ############################################################################
559 sub Main_TryToRun_Bg_or_User_Queue
562 my(@deferUserQueue, @deferBgQueue);
565 if ( time - $Info{DUlastValueTime} >= 600 ) {
567 # Update our notion of disk usage no more than
568 # once every 10 minutes
570 $du = $bpc->CheckFileSystemUsage($TopDir);
571 $Info{DUlastValue} = $du;
572 $Info{DUlastValueTime} = time;
575 # if we recently checked it then just use the old value
577 $du = $Info{DUlastValue};
579 if ( $Info{DUDailyMaxReset} ) {
580 $Info{DUDailyMaxStartTime} = time;
581 $Info{DUDailyMaxReset} = 0;
582 $Info{DUDailyMax} = 0;
584 if ( $du > $Info{DUDailyMax} ) {
585 $Info{DUDailyMax} = $du;
586 $Info{DUDailyMaxTime} = time;
588 if ( $du > $Conf{DfMaxUsagePct} ) {
589 my @bgQueue = @BgQueue;
593 # When the disk is too full, only run backups that will
594 # do expires, not regular backups
597 foreach $req ( @bgQueue ) {
598 if ( $req->{dumpExpire} ) {
599 unshift(@BgQueue, $req);
601 $BgQueueOn{$req->{host}} = 0;
606 print(LOG $bpc->timeStamp,
607 "Disk too full ($du%); skipped $nSkip hosts\n");
608 $Info{DUDailySkipHostCnt} += $nSkip;
612 while ( $RunNightlyWhenIdle == 0 ) {
614 my(@args, $progName, $type);
615 my $nJobs = keys(%Jobs);
617 # CmdJob and trashClean don't count towards MaxBackups / MaxUserBackups
619 if ( $CmdJob ne "" ) {
620 if ( $BackupPCNightlyJobs ) {
621 $nJobs -= $BackupPCNightlyJobs;
626 $nJobs-- if ( defined($Jobs{$bpc->trashJob} ) );
627 if ( $nJobs < $Conf{MaxBackups} + $Conf{MaxUserBackups}
628 && @UserQueue > 0 ) {
629 $req = pop(@UserQueue);
630 if ( defined($Jobs{$req->{host}}) ) {
631 push(@deferUserQueue, $req);
634 push(@args, $req->{doFull} ? "-f" : "-i")
635 if (( !$req->{restore} ) && ( !$req->{archive} ));
636 $UserQueueOn{$req->{host}} = 0;
637 } elsif ( $nJobs < $Conf{MaxBackups}
638 && (@CmdQueue + $nJobs)
639 <= $Conf{MaxBackups} + $Conf{MaxPendingCmds}
641 $req = pop(@BgQueue);
642 if ( defined($Jobs{$req->{host}}) ) {
644 # Job is currently running for this host; save it for later
646 unshift(@deferBgQueue, $req);
649 $BgQueueOn{$req->{host}} = 0;
652 # Restore the deferred jobs
654 @BgQueue = (@BgQueue, @deferBgQueue);
655 @UserQueue = (@UserQueue, @deferUserQueue);
658 $host = $req->{host};
659 my $user = $req->{user};
660 if ( $req->{restore} ) {
661 $progName = "BackupPC_restore";
663 push(@args, $req->{hostIP}, $req->{host}, $req->{reqFileName});
664 } elsif ( $req->{archive} ) {
665 $progName = "BackupPC_archive";
667 push(@args, $req->{user}, $req->{host}, $req->{reqFileName});
669 $progName = "BackupPC_dump";
671 push(@args, "-d") if ( $req->{dhcp} );
672 push(@args, "-e") if ( $req->{dumpExpire} );
675 my $pid = open(FH, "-|");
676 if ( !defined($pid) ) {
677 print(LOG $bpc->timeStamp,
678 "can't fork to run $progName for $host, request by $user\n");
684 exec("$BinDir/$progName", @args);
685 print(LOG $bpc->timeStamp, "can't exec $progName for $host\n");
688 $Jobs{$host}{pid} = $pid;
689 $Jobs{$host}{fh} = *FH;
690 $Jobs{$host}{fn} = fileno(FH);
691 $Jobs{$host}{dhcp} = $req->{dhcp};
692 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
693 $Jobs{$host}{startTime} = time;
694 $Jobs{$host}{reqTime} = $req->{reqTime};
695 $Jobs{$host}{userReq} = $req->{userReq};
696 $Jobs{$host}{cmd} = $bpc->execCmd2ShellCmd($progName, @args);
697 $Jobs{$host}{user} = $user;
698 $Jobs{$host}{type} = $type;
699 $Status{$host}{userReq} = $req->{userReq}
700 if ( defined($Hosts->{$host}) );
701 if ( !$req->{dhcp} ) {
702 $Status{$host}{state} = "Status_".$type."_starting";
703 $Status{$host}{activeJob} = 1;
704 $Status{$host}{startTime} = time;
705 $Status{$host}{endTime} = "";
710 ############################################################################
713 # If necessary, figure out when to next wakeup based on $Conf{WakeupSchedule},
714 # and then do a select() to wait for the next thing to happen
715 # (timeout, signal, someone sends a message, child dies etc).
716 ############################################################################
719 if ( $NextWakeup <= 0 ) {
721 # Figure out when to next wakeup based on $Conf{WakeupSchedule}.
723 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
725 my($currHours) = $hour + $min / 60 + $sec / 3600;
726 if ( $bpc->ConfigMTime() != $Info{ConfigModTime} ) {
727 ServerReload("Re-read config file because mtime changed");
730 foreach my $t ( @{$Conf{WakeupSchedule} || [0..23]} ) {
731 next if ( $t < 0 || $t > 24 );
732 my $tomorrow = $t + 24;
734 || ($tomorrow - $currHours > 0
735 && $delta > $tomorrow - $currHours) ) {
736 $delta = $tomorrow - $currHours;
737 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
740 || ($t - $currHours > 0 && $delta > $t - $currHours) ) {
741 $delta = $t - $currHours;
742 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
745 $NextWakeup = time + $delta * 3600;
746 $Info{nextWakeup} = $NextWakeup;
747 print(LOG $bpc->timeStamp, "Next wakeup is ",
748 $bpc->timeStamp($NextWakeup, 1), "\n");
751 # Call select(), waiting until either a signal, a timeout,
752 # any output from our jobs, or any messages from clients
754 # select() is where we (hopefully) spend most of our time blocked...
756 my $timeout = $NextWakeup - time;
757 $timeout = 1 if ( $timeout <= 0 );
759 select(my $rout = $FDread, undef, $ein, $timeout);
764 ############################################################################
765 # Main_Process_Signal()
768 ############################################################################
769 sub Main_Process_Signal
774 if ( $SigName eq "HUP" ) {
775 ServerReload("Re-read config file because of a SIG_HUP");
776 } elsif ( $SigName ) {
777 ServerShutdown("Got signal $SigName... cleaning up");
782 ############################################################################
783 # Main_Check_Timeout()
785 # Check if a timeout has occured, and if so, queue all the PCs for backups.
786 # Also does log file aging on the first timeout after midnight.
787 ############################################################################
788 sub Main_Check_Timeout
793 return if ( time < $NextWakeup || $NextWakeup <= 0 );
795 if ( $FirstWakeup ) {
797 # This is the first wakeup after midnight. Do log file aging
798 # and various house keeping.
801 printf(LOG "%s24hr disk usage: %d%% max, %d%% recent,"
802 . " %d skipped hosts\n",
803 $bpc->timeStamp, $Info{DUDailyMax}, $Info{DUlastValue},
804 $Info{DUDailySkipHostCnt});
805 $Info{DUDailyMaxReset} = 1;
806 $Info{DUDailyMaxPrev} = $Info{DUDailyMax};
807 $Info{DUDailySkipHostCntPrev} = $Info{DUDailySkipHostCnt};
808 $Info{DUDailySkipHostCnt} = 0;
809 my $lastLog = $Conf{MaxOldLogFiles} - 1;
810 if ( -f "$TopDir/log/LOG.$lastLog" ) {
811 print(LOG $bpc->timeStamp,
812 "Removing $TopDir/log/LOG.$lastLog\n");
813 unlink("$TopDir/log/LOG.$lastLog");
815 if ( -f "$TopDir/log/LOG.$lastLog.z" ) {
816 print(LOG $bpc->timeStamp,
817 "Removing $TopDir/log/LOG.$lastLog.z\n");
818 unlink("$TopDir/log/LOG.$lastLog.z");
820 print(LOG $bpc->timeStamp, "Aging LOG files, LOG -> LOG.0 -> "
821 . "LOG.1 -> ... -> LOG.$lastLog\n");
822 close(STDERR); # dup of LOG
823 close(STDOUT); # dup of LOG
825 for ( my $i = $lastLog - 1 ; $i >= 0 ; $i-- ) {
827 rename("$TopDir/log/LOG.$i", "$TopDir/log/LOG.$j")
828 if ( -f "$TopDir/log/LOG.$i" );
829 rename("$TopDir/log/LOG.$i.z", "$TopDir/log/LOG.$j.z")
830 if ( -f "$TopDir/log/LOG.$i.z" );
833 # Compress the log file LOG -> LOG.0.z (if enabled).
834 # Otherwise, just rename LOG -> LOG.0.
836 BackupPC::FileZIO->compressCopy("$TopDir/log/LOG",
837 "$TopDir/log/LOG.0.z",
839 $Conf{CompressLevel}, 1);
842 # Remember to run nightly script after current jobs are done
844 $RunNightlyWhenIdle = 1;
847 # Write out the current status and then queue all the PCs
851 %BgQueueOn = () if ( @BgQueue == 0 );
852 %UserQueueOn = () if ( @UserQueue == 0 );
853 %CmdQueueOn = () if ( @CmdQueue == 0 );
857 ############################################################################
858 # Main_Check_Job_Messages($fdRead)
860 # Check if select() says we have bytes waiting from any of our jobs.
861 # Handle each of the messages when complete (newline terminated).
862 ############################################################################
863 sub Main_Check_Job_Messages
866 foreach my $host ( keys(%Jobs) ) {
867 next if ( !vec($fdRead, $Jobs{$host}{fn}, 1) );
870 # do a last check to make sure there is something to read so
871 # we are absolutely sure we won't block.
873 vec(my $readMask, $Jobs{$host}{fn}, 1) = 1;
874 if ( !select($readMask, undef, undef, 0.0) ) {
875 print(LOG $bpc->timeStamp, "Botch in Main_Check_Job_Messages:"
876 . " nothing to read from $host. Debug dump:\n");
877 my($dump) = Data::Dumper->new(
878 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
879 [qw(*Clients, *Jobs *FDread, *fdRead)]);
881 print(LOG $dump->Dump);
884 my $nbytes = sysread($Jobs{$host}{fh}, $mesg, 1024);
885 $Jobs{$host}{mesg} .= $mesg if ( $nbytes > 0 );
887 # Process any complete lines of output from this jobs.
888 # Any output to STDOUT or STDERR from the children is processed here.
890 while ( $Jobs{$host}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
892 $Jobs{$host}{mesg} = $2;
893 if ( $Jobs{$host}{dhcp} ) {
894 if ( $mesg =~ /^DHCP (\S+) (\S+)/ ) {
895 my $newHost = $bpc->uriUnesc($2);
896 if ( defined($Jobs{$newHost}) ) {
897 print(LOG $bpc->timeStamp,
898 "Backup on $newHost is already running\n");
899 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
903 $Jobs{$host}{dhcpHostIP} = $host;
904 $Status{$newHost}{dhcpHostIP} = $host;
905 $Jobs{$newHost} = $Jobs{$host};
906 delete($Jobs{$host});
908 $Status{$host}{state} = "Status_backup_starting";
909 $Status{$host}{activeJob} = 1;
910 $Status{$host}{startTime} = $Jobs{$host}{startTime};
911 $Status{$host}{endTime} = "";
912 $Jobs{$host}{dhcp} = 0;
914 print(LOG $bpc->timeStamp, "dhcp $host: $mesg\n");
916 } elsif ( $mesg =~ /^started (.*) dump, share=(.*)/ ) {
917 $Jobs{$host}{type} = $1;
918 $Jobs{$host}{shareName} = $2;
919 print(LOG $bpc->timeStamp,
920 "Started $1 backup on $host (pid=$Jobs{$host}{pid}",
921 $Jobs{$host}{dhcpHostIP}
922 ? ", dhcp=$Jobs{$host}{dhcpHostIP}" : "",
923 ", share=$Jobs{$host}{shareName})\n");
924 $Status{$host}{state} = "Status_backup_in_progress";
925 $Status{$host}{reason} = "";
926 $Status{$host}{type} = $1;
927 $Status{$host}{startTime} = time;
928 $Status{$host}{deadCnt} = 0;
929 $Status{$host}{aliveCnt}++;
930 $Status{$host}{dhcpCheckCnt}--
931 if ( $Status{$host}{dhcpCheckCnt} > 0 );
932 } elsif ( $mesg =~ /^xferPids (.*)/ ) {
933 $Jobs{$host}{xferPid} = $1;
934 } elsif ( $mesg =~ /^started_restore/ ) {
935 $Jobs{$host}{type} = "restore";
936 print(LOG $bpc->timeStamp,
937 "Started restore on $host"
938 . " (pid=$Jobs{$host}{pid})\n");
939 $Status{$host}{state} = "Status_restore_in_progress";
940 $Status{$host}{reason} = "";
941 $Status{$host}{type} = "restore";
942 $Status{$host}{startTime} = time;
943 $Status{$host}{deadCnt} = 0;
944 $Status{$host}{aliveCnt}++;
945 } elsif ( $mesg =~ /^started_archive/ ) {
946 $Jobs{$host}{type} = "archive";
947 print(LOG $bpc->timeStamp,
948 "Started archive on $host"
949 . " (pid=$Jobs{$host}{pid})\n");
950 $Status{$host}{state} = "Status_archive_in_progress";
951 $Status{$host}{reason} = "";
952 $Status{$host}{type} = "archive";
953 $Status{$host}{startTime} = time;
954 $Status{$host}{deadCnt} = 0;
955 $Status{$host}{aliveCnt}++;
956 } elsif ( $mesg =~ /^(full|incr) backup complete/ ) {
957 print(LOG $bpc->timeStamp, "Finished $1 backup on $host\n");
958 $Status{$host}{reason} = "Reason_backup_done";
959 delete($Status{$host}{error});
960 delete($Status{$host}{errorTime});
961 $Status{$host}{endTime} = time;
962 $Status{$host}{lastGoodBackupTime} = time;
963 } elsif ( $mesg =~ /^backups disabled/ ) {
964 print(LOG $bpc->timeStamp,
965 "Ignoring old backup error on $host\n");
966 $Status{$host}{reason} = "Reason_backup_done";
967 delete($Status{$host}{error});
968 delete($Status{$host}{errorTime});
969 $Status{$host}{endTime} = time;
970 } elsif ( $mesg =~ /^restore complete/ ) {
971 print(LOG $bpc->timeStamp, "Finished restore on $host\n");
972 $Status{$host}{reason} = "Reason_restore_done";
973 delete($Status{$host}{error});
974 delete($Status{$host}{errorTime});
975 $Status{$host}{endTime} = time;
976 } elsif ( $mesg =~ /^archive complete/ ) {
977 print(LOG $bpc->timeStamp, "Finished archive on $host\n");
978 $Status{$host}{reason} = "Reason_archive_done";
979 delete($Status{$host}{error});
980 delete($Status{$host}{errorTime});
981 $Status{$host}{endTime} = time;
982 } elsif ( $mesg =~ /^nothing to do/ ) {
983 if ( $Status{$host}{reason} ne "Reason_backup_failed"
984 && $Status{$host}{reason} ne "Reason_restore_failed" ) {
985 $Status{$host}{state} = "Status_idle";
986 $Status{$host}{reason} = "Reason_nothing_to_do";
987 $Status{$host}{startTime} = time;
989 $Status{$host}{dhcpCheckCnt}--
990 if ( $Status{$host}{dhcpCheckCnt} > 0 );
991 } elsif ( $mesg =~ /^no ping response/
992 || $mesg =~ /^ping too slow/
993 || $mesg =~ /^host not found/ ) {
994 $Status{$host}{state} = "Status_idle";
995 if ( $Status{$host}{userReq}
996 || $Status{$host}{reason} ne "Reason_backup_failed"
997 || $Status{$host}{error} =~ /^aborted by user/ ) {
998 $Status{$host}{reason} = "Reason_no_ping";
999 $Status{$host}{error} = $mesg;
1000 $Status{$host}{startTime} = time;
1002 $Status{$host}{deadCnt}++;
1003 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1004 $Status{$host}{aliveCnt} = 0;
1006 } elsif ( $mesg =~ /^dump failed: (.*)/ ) {
1007 $Status{$host}{state} = "Status_idle";
1008 $Status{$host}{error} = $1;
1009 $Status{$host}{errorTime} = time;
1010 $Status{$host}{endTime} = time;
1011 if ( $Status{$host}{reason}
1012 eq "Reason_backup_canceled_by_user" ) {
1013 print(LOG $bpc->timeStamp,
1014 "Backup canceled on $host ($1)\n");
1016 $Status{$host}{reason} = "Reason_backup_failed";
1017 print(LOG $bpc->timeStamp,
1018 "Backup failed on $host ($1)\n");
1020 } elsif ( $mesg =~ /^restore failed: (.*)/ ) {
1021 $Status{$host}{state} = "Status_idle";
1022 $Status{$host}{error} = $1;
1023 $Status{$host}{errorTime} = time;
1024 $Status{$host}{endTime} = time;
1025 if ( $Status{$host}{reason}
1026 eq "Reason_restore_canceled_by_user" ) {
1027 print(LOG $bpc->timeStamp,
1028 "Restore canceled on $host ($1)\n");
1030 $Status{$host}{reason} = "Reason_restore_failed";
1031 print(LOG $bpc->timeStamp,
1032 "Restore failed on $host ($1)\n");
1034 } elsif ( $mesg =~ /^archive failed: (.*)/ ) {
1035 $Status{$host}{state} = "Status_idle";
1036 $Status{$host}{error} = $1;
1037 $Status{$host}{errorTime} = time;
1038 $Status{$host}{endTime} = time;
1039 if ( $Status{$host}{reason}
1040 eq "Reason_archive_canceled_by_user" ) {
1041 print(LOG $bpc->timeStamp,
1042 "Archive canceled on $host ($1)\n");
1044 $Status{$host}{reason} = "Reason_archive_failed";
1045 print(LOG $bpc->timeStamp,
1046 "Archive failed on $host ($1)\n");
1048 } elsif ( $mesg =~ /^log\s+(.*)/ ) {
1049 print(LOG $bpc->timeStamp, "$1\n");
1050 } elsif ( $mesg =~ /^BackupPC_stats (\d+) = (.*)/ ) {
1051 my $chunk = int($1 / 16);
1052 my @f = split(/,/, $2);
1053 $Info{pool}{$f[0]}[$chunk]{FileCnt} += $f[1];
1054 $Info{pool}{$f[0]}[$chunk]{DirCnt} += $f[2];
1055 $Info{pool}{$f[0]}[$chunk]{Kb} += $f[3];
1056 $Info{pool}{$f[0]}[$chunk]{Kb2} += $f[4];
1057 $Info{pool}{$f[0]}[$chunk]{KbRm} += $f[5];
1058 $Info{pool}{$f[0]}[$chunk]{FileCntRm} += $f[6];
1059 $Info{pool}{$f[0]}[$chunk]{FileCntRep} += $f[7];
1060 $Info{pool}{$f[0]}[$chunk]{FileRepMax} = $f[8]
1061 if ( $Info{pool}{$f[0]}[$chunk]{FileRepMax} < $f[8] );
1062 $Info{pool}{$f[0]}[$chunk]{FileCntRename} += $f[9];
1063 $Info{pool}{$f[0]}[$chunk]{FileLinkMax} = $f[10]
1064 if ( $Info{pool}{$f[0]}[$chunk]{FileLinkMax} < $f[10] );
1065 $Info{pool}{$f[0]}[$chunk]{FileLinkTotal} += $f[11];
1066 $Info{pool}{$f[0]}[$chunk]{Time} = time;
1067 } elsif ( $mesg =~ /^BackupPC_nightly lock_off/ ) {
1068 $BackupPCNightlyLock--;
1069 if ( $BackupPCNightlyLock == 0 ) {
1071 # This means the last BackupPC_nightly is done with
1072 # the pool clean, so it's ok to start running regular
1075 $RunNightlyWhenIdle = 0;
1077 } elsif ( $mesg =~ /^processState\s+(.+)/ ) {
1078 $Jobs{$host}{processState} = $1;
1079 } elsif ( $mesg =~ /^link\s+(.+)/ ) {
1081 $Status{$h}{needLink} = 1;
1083 print(LOG $bpc->timeStamp, "$host: $mesg\n");
1087 # shut down the client connection if we read EOF
1089 if ( $nbytes <= 0 ) {
1090 close($Jobs{$host}{fh});
1091 vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1092 if ( $CmdJob eq $host || $bpc->isAdminJob($host) ) {
1093 my $cmd = $Jobs{$host}{cmd};
1094 $cmd =~ s/$BinDir\///g;
1095 print(LOG $bpc->timeStamp, "Finished $host ($cmd)\n");
1096 $Status{$host}{state} = "Status_idle";
1097 $Status{$host}{endTime} = time;
1098 if ( $cmd =~ /^BackupPC_nightly\s/ ) {
1099 $BackupPCNightlyJobs--;
1100 #print(LOG $bpc->timeStamp, "BackupPC_nightly done; now"
1101 # . " have $BackupPCNightlyJobs running\n");
1102 if ( $BackupPCNightlyJobs <= 0 ) {
1103 $BackupPCNightlyJobs = 0;
1104 $RunNightlyWhenIdle = 0;
1107 # Combine the 16 per-directory results
1109 for my $p ( qw(pool cpool) ) {
1110 $Info{"${p}FileCnt"} = 0;
1111 $Info{"${p}DirCnt"} = 0;
1112 $Info{"${p}Kb"} = 0;
1113 $Info{"${p}Kb2"} = 0;
1114 $Info{"${p}KbRm"} = 0;
1115 $Info{"${p}FileCntRm"} = 0;
1116 $Info{"${p}FileCntRep"} = 0;
1117 $Info{"${p}FileRepMax"} = 0;
1118 $Info{"${p}FileCntRename"} = 0;
1119 $Info{"${p}FileLinkMax"} = 0;
1120 $Info{"${p}Time"} = 0;
1121 for ( my $i = 0 ; $i < 16 ; $i++ ) {
1122 $Info{"${p}FileCnt"}
1123 += $Info{pool}{$p}[$i]{FileCnt};
1125 += $Info{pool}{$p}[$i]{DirCnt};
1127 += $Info{pool}{$p}[$i]{Kb};
1129 += $Info{pool}{$p}[$i]{Kb2};
1131 += $Info{pool}{$p}[$i]{KbRm};
1132 $Info{"${p}FileCntRm"}
1133 += $Info{pool}{$p}[$i]{FileCntRm};
1134 $Info{"${p}FileCntRep"}
1135 += $Info{pool}{$p}[$i]{FileCntRep};
1136 $Info{"${p}FileRepMax"}
1137 = $Info{pool}{$p}[$i]{FileRepMax}
1138 if ( $Info{"${p}FileRepMax"} <
1139 $Info{pool}{$p}[$i]{FileRepMax} );
1140 $Info{"${p}FileCntRename"}
1141 += $Info{pool}{$p}[$i]{FileCntRename};
1142 $Info{"${p}FileLinkMax"}
1143 = $Info{pool}{$p}[$i]{FileLinkMax}
1144 if ( $Info{"${p}FileLinkMax"} <
1145 $Info{pool}{$p}[$i]{FileLinkMax} );
1146 $Info{"${p}Time"} = $Info{pool}{$p}[$i]{Time}
1147 if ( $Info{"${p}Time"} <
1148 $Info{pool}{$p}[$i]{Time} );
1150 printf(LOG "%s%s nightly clean removed %d files of"
1152 $bpc->timeStamp, ucfirst($p),
1153 $Info{"${p}FileCntRm"},
1154 $Info{"${p}KbRm"} / (1000 * 1024));
1155 printf(LOG "%s%s is %.2fGB, %d files (%d repeated, "
1156 . "%d max chain, %d max links), %d directories\n",
1157 $bpc->timeStamp, ucfirst($p),
1158 $Info{"${p}Kb"} / (1000 * 1024),
1159 $Info{"${p}FileCnt"}, $Info{"${p}FileCntRep"},
1160 $Info{"${p}FileRepMax"},
1161 $Info{"${p}FileLinkMax"}, $Info{"${p}DirCnt"});
1169 # Queue BackupPC_link to complete the backup
1170 # processing for this host.
1172 if ( defined($Status{$host})
1173 && ($Status{$host}{reason} eq "Reason_backup_done"
1174 || $Status{$host}{needLink}) ) {
1176 } elsif ( defined($Status{$host}) ) {
1177 $Status{$host}{state} = "Status_idle";
1180 delete($Jobs{$host});
1181 $Status{$host}{activeJob} = 0 if ( defined($Status{$host}) );
1185 # When we are idle (empty Jobs, CmdQueue, BgQueue, UserQueue) we
1186 # do a pass over %Status updating the deadCnt and aliveCnt for
1187 # DHCP hosts. The reason we need to do this later is we can't
1188 # be sure whether a DHCP host is alive or dead until we have passed
1189 # over all the DHCP pool.
1191 return if ( @CmdQueue || @BgQueue || @UserQueue || keys(%Jobs) > 1 );
1192 foreach my $host ( keys(%Status) ) {
1193 next if ( $Status{$host}{dhcpCheckCnt} <= 0 );
1194 $Status{$host}{deadCnt} += $Status{$host}{dhcpCheckCnt};
1195 $Status{$host}{dhcpCheckCnt} = 0;
1196 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1197 $Status{$host}{aliveCnt} = 0;
1202 ############################################################################
1203 # Main_Check_Client_Messages($fdRead)
1205 # Check for, and process, any output from our clients. Also checks
1206 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
1207 ############################################################################
1208 sub Main_Check_Client_Messages
1211 foreach my $client ( keys(%Clients) ) {
1212 next if ( !vec($fdRead, $Clients{$client}{fn}, 1) );
1215 # do a last check to make sure there is something to read so
1216 # we are absolutely sure we won't block.
1218 vec(my $readMask, $Clients{$client}{fn}, 1) = 1;
1219 if ( !select($readMask, undef, undef, 0.0) ) {
1220 print(LOG $bpc->timeStamp, "Botch in Main_Check_Client_Messages:"
1221 . " nothing to read from $client. Debug dump:\n");
1222 my($dump) = Data::Dumper->new(
1223 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
1224 [qw(*Clients, *Jobs *FDread, *fdRead)]);
1226 print(LOG $dump->Dump);
1229 my $nbytes = sysread($Clients{$client}{fh}, $mesg, 1024);
1230 $Clients{$client}{mesg} .= $mesg if ( $nbytes > 0 );
1232 # Process any complete lines received from this client.
1234 while ( $Clients{$client}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
1237 $Clients{$client}{mesg} = $2;
1239 # Authenticate the message by checking the MD5 digest
1241 my $md5 = Digest::MD5->new;
1242 if ( $cmd !~ /^(.{22}) (.*)/
1243 || ($md5->add($Clients{$client}{seed}
1244 . $Clients{$client}{mesgCnt}
1245 . $Conf{ServerMesgSecret} . $2),
1246 $md5->b64digest ne $1) ) {
1247 print(LOG $bpc->timeStamp, "Corrupted message '$cmd' from"
1248 . " client '$Clients{$client}{clientName}':"
1249 . " shutting down client connection\n");
1253 $Clients{$client}{mesgCnt}++;
1255 if ( $cmd =~ /^stop (\S+)\s+(\S+)\s+(\S*)/ ) {
1259 $host = $bpc->uriUnesc($host);
1260 if ( $CmdJob ne $host && defined($Status{$host})
1261 && defined($Jobs{$host}) ) {
1262 print(LOG $bpc->timeStamp,
1263 "Stopping current $Jobs{$host}{type} of $host,"
1264 . " request by $user (backoff=$backoff)\n");
1265 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1267 # Don't close the pipe now; wait until the child
1268 # really exits later. Otherwise close() will
1269 # block until the child has exited.
1271 ##vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1272 ##close($Jobs{$host}{fh});
1273 ##delete($Jobs{$host});
1275 $Status{$host}{state} = "Status_idle";
1276 if ( $Jobs{$host}{type} eq "restore" ) {
1277 $Status{$host}{reason}
1278 = "Reason_restore_canceled_by_user";
1279 } elsif ( $Jobs{$host}{type} eq "archive" ) {
1280 $Status{$host}{reason}
1281 = "Reason_archive_canceled_by_user";
1283 $Status{$host}{reason}
1284 = "Reason_backup_canceled_by_user";
1286 $Status{$host}{activeJob} = 0;
1287 $Status{$host}{startTime} = time;
1288 $reply = "ok: $Jobs{$host}{type} of $host canceled";
1289 } elsif ( $BgQueueOn{$host} || $UserQueueOn{$host} ) {
1290 print(LOG $bpc->timeStamp,
1291 "Stopping pending backup of $host,"
1292 . " request by $user (backoff=$backoff)\n");
1293 @BgQueue = grep($_->{host} ne $host, @BgQueue);
1294 @UserQueue = grep($_->{host} ne $host, @UserQueue);
1295 $BgQueueOn{$host} = $UserQueueOn{$host} = 0;
1296 $reply = "ok: pending backup of $host canceled";
1298 print(LOG $bpc->timeStamp,
1299 "Nothing to do for stop backup of $host,"
1300 . " request by $user (backoff=$backoff)\n");
1301 $reply = "ok: no backup was pending or running";
1303 if ( defined($Status{$host}) && $backoff ne "" ) {
1304 if ( $backoff > 0 ) {
1305 $Status{$host}{backoffTime} = time + $backoff * 3600;
1307 delete($Status{$host}{backoffTime});
1310 } elsif ( $cmd =~ /^backup all$/ ) {
1312 } elsif ( $cmd =~ /^BackupPC_nightly run$/ ) {
1313 $RunNightlyWhenIdle = 1;
1314 } elsif ( $cmd =~ /^backup (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1319 $host = $bpc->uriUnesc($host);
1320 $hostIP = $bpc->uriUnesc($hostIP);
1321 if ( !defined($Status{$host}) ) {
1322 print(LOG $bpc->timeStamp,
1323 "User $user requested backup of unknown host"
1325 $reply = "error: unknown host $host";
1327 print(LOG $bpc->timeStamp,
1328 "User $user requested backup of $host"
1330 if ( $BgQueueOn{$hostIP} ) {
1331 @BgQueue = grep($_->{host} ne $hostIP, @BgQueue);
1332 $BgQueueOn{$hostIP} = 0;
1334 if ( $UserQueueOn{$hostIP} ) {
1335 @UserQueue = grep($_->{host} ne $hostIP, @UserQueue);
1336 $UserQueueOn{$hostIP} = 0;
1338 unshift(@UserQueue, {
1344 dhcp => $hostIP eq $host ? 0 : 1,
1346 $UserQueueOn{$hostIP} = 1;
1347 $reply = "ok: requested backup of $host";
1349 } elsif ( $cmd =~ /^archive (\S+)\s+(\S+)\s+(\S+)/ ) {
1351 my $archivehost = $2;
1352 my $reqFileName = $3;
1353 $host = $bpc->uriUnesc($archivehost);
1354 if ( !defined($Status{$host}) ) {
1355 print(LOG $bpc->timeStamp,
1356 "User $user requested archive of unknown archive host"
1358 $reply = "archive error: unknown archive host $host";
1360 print(LOG $bpc->timeStamp,
1361 "User $user requested archive on $host"
1363 if ( defined($Jobs{$host}) ) {
1364 $reply = "Archive currently running on $host, please try later";
1366 unshift(@UserQueue, {
1369 reqFileName => $reqFileName,
1375 $UserQueueOn{$host} = 1;
1376 $reply = "ok: requested archive on $host";
1379 } elsif ( $cmd =~ /^restore (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1383 my $reqFileName = $4;
1384 $host = $bpc->uriUnesc($host);
1385 $hostIP = $bpc->uriUnesc($hostIP);
1386 if ( !defined($Status{$host}) ) {
1387 print(LOG $bpc->timeStamp,
1388 "User $user requested restore to unknown host"
1390 $reply = "restore error: unknown host $host";
1392 print(LOG $bpc->timeStamp,
1393 "User $user requested restore to $host"
1395 unshift(@UserQueue, {
1398 reqFileName => $reqFileName,
1404 $UserQueueOn{$host} = 1;
1405 if ( defined($Jobs{$host}) ) {
1406 $reply = "ok: requested restore of $host, but a"
1407 . " job is currently running,"
1408 . " so this request will start later";
1410 $reply = "ok: requested restore of $host";
1413 } elsif ( $cmd =~ /^status\s*(.*)/ ) {
1415 my($dump, @values, @names);
1416 foreach my $type ( split(/\s+/, $args) ) {
1417 if ( $type =~ /^queues/ ) {
1418 push(@values, \@BgQueue, \@UserQueue, \@CmdQueue);
1419 push(@names, qw(*BgQueue *UserQueue *CmdQueue));
1420 } elsif ( $type =~ /^jobs/ ) {
1421 push(@values, \%Jobs);
1422 push(@names, qw(*Jobs));
1423 } elsif ( $type =~ /^queueLen/ ) {
1425 BgQueue => scalar(@BgQueue),
1426 UserQueue => scalar(@UserQueue),
1427 CmdQueue => scalar(@CmdQueue),
1429 push(@names, qw(*QueueLen));
1430 } elsif ( $type =~ /^info/ ) {
1431 push(@values, \%Info);
1432 push(@names, qw(*Info));
1433 } elsif ( $type =~ /^hosts/ ) {
1434 push(@values, \%Status);
1435 push(@names, qw(*Status));
1436 } elsif ( $type =~ /^host\((.*)\)/ ) {
1437 my $h = $bpc->uriUnesc($1);
1438 if ( defined($Status{$h}) ) {
1441 BgQueueOn => $BgQueueOn{$h},
1442 UserQueueOn => $UserQueueOn{$h},
1443 CmdQueueOn => $CmdQueueOn{$h},
1445 push(@names, qw(*StatusHost));
1447 print(LOG $bpc->timeStamp,
1448 "Unknown host $h for status request\n");
1451 print(LOG $bpc->timeStamp,
1452 "Unknown status request $type\n");
1455 $dump = Data::Dumper->new(\@values, \@names);
1457 $reply = $dump->Dump;
1458 } elsif ( $cmd =~ /^link\s+(.+)/ ) {
1460 $host = $bpc->uriUnesc($host);
1462 } elsif ( $cmd =~ /^log\s+(.*)/ ) {
1463 print(LOG $bpc->timeStamp, "$1\n");
1464 } elsif ( $cmd =~ /^server\s+(\w+)/ ) {
1466 if ( $type eq 'reload' ) {
1467 ServerReload("Reloading config/host files via CGI request");
1468 } elsif ( $type eq 'shutdown' ) {
1469 $reply = "Shutting down...\n";
1470 syswrite($Clients{$client}{fh}, $reply, length($reply));
1471 ServerShutdown("Server shutting down...");
1473 } elsif ( $cmd =~ /^quit/ || $cmd =~ /^exit/ ) {
1477 print(LOG $bpc->timeStamp, "Unknown command $cmd\n");
1478 $reply = "error: bad command $cmd";
1481 # send a reply to the client, at a minimum "ok\n".
1483 $reply = "ok" if ( $reply eq "" );
1485 syswrite($Clients{$client}{fh}, $reply, length($reply));
1488 # Detect possible denial-of-service attack from sending a huge line
1489 # (ie: never terminated). 32K seems to be plenty big enough as
1492 if ( length($Clients{$client}{mesg}) > 32 * 1024 ) {
1493 print(LOG $bpc->timeStamp, "Line too long from client"
1494 . " '$Clients{$client}{clientName}':"
1495 . " shutting down client connection\n");
1499 # Shut down the client connection if we read EOF
1501 if ( $nbytes <= 0 ) {
1502 close($Clients{$client}{fh});
1503 vec($FDread, $Clients{$client}{fn}, 1) = 0;
1504 delete($Clients{$client});
1508 # Accept any new connections on each of our listen sockets
1510 if ( vec($fdRead, fileno(SERVER_UNIX), 1) ) {
1512 my $paddr = accept(CLIENT, SERVER_UNIX);
1514 $Clients{$ClientConnCnt}{clientName} = "unix socket";
1515 $Clients{$ClientConnCnt}{mesg} = "";
1516 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1517 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1518 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1520 # Generate and send unique seed for MD5 digests to avoid
1521 # replay attacks. See BackupPC::Lib::ServerMesg().
1523 my $seed = time . ",$ClientConnCnt,$$,0\n";
1524 $Clients{$ClientConnCnt}{seed} = $seed;
1525 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1526 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1528 if ( $ServerInetPort > 0 && vec($fdRead, fileno(SERVER_INET), 1) ) {
1530 my $paddr = accept(CLIENT, SERVER_INET);
1531 my($port,$iaddr) = sockaddr_in($paddr);
1532 my $name = gethostbyaddr($iaddr, AF_INET);
1534 $Clients{$ClientConnCnt}{mesg} = "";
1535 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1536 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1537 $Clients{$ClientConnCnt}{clientName} = "$name:$port";
1538 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1540 # Generate and send unique seed for MD5 digests to avoid
1541 # replay attacks. See BackupPC::Lib::ServerMesg().
1543 my $seed = time . ",$ClientConnCnt,$$,$port\n";
1544 $Clients{$ClientConnCnt}{seed} = $seed;
1545 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1546 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1550 ###########################################################################
1551 # Miscellaneous subroutines
1552 ###########################################################################
1555 # Write the current status to $TopDir/log/status.pl
1559 my($dump) = Data::Dumper->new(
1560 [ \%Info, \%Status],
1561 [qw(*Info *Status)]);
1563 if ( open(STATUS, ">", "$TopDir/log/status.pl") ) {
1564 print(STATUS $dump->Dump);
1570 # Compare function for host sort. Hosts with errors go first,
1571 # sorted with the oldest errors first. The remaining hosts
1572 # are sorted so that those with the oldest backups go first.
1577 # Hosts with errors go before hosts without errors
1579 return -1 if ( $Status{$a}{error} ne "" && $Status{$b}{error} eq "" );
1582 # Hosts with no errors go after hosts with errors
1585 return 1 if ( $Status{$a}{error} eq "" && $Status{$b}{error} ne "" );
1588 # hosts with the older last good backups sort earlier
1590 my $r = $Status{$a}{lastGoodBackupTime} <=> $Status{$b}{lastGoodBackupTime};
1591 return $r if ( $r );
1594 # Finally, just sort based on host name
1600 # Queue all the hosts for backup. This means queuing all the fixed
1601 # ip hosts and all the dhcp address ranges. We also additionally
1602 # queue the dhcp hosts with a -e flag to check for expired dumps.
1607 foreach my $host ( sort(HostSortCompare keys(%$Hosts)) ) {
1608 delete($Status{$host}{backoffTime})
1609 if ( defined($Status{$host}{backoffTime})
1610 && $Status{$host}{backoffTime} < time );
1611 next if ( defined($Jobs{$host})
1612 || $BgQueueOn{$host}
1613 || $UserQueueOn{$host}
1614 || $CmdQueueOn{$host} );
1615 if ( $Hosts->{$host}{dhcp} ) {
1616 $Status{$host}{dhcpCheckCnt}++;
1617 if ( $RunNightlyWhenIdle ) {
1619 # Once per night queue a check for DHCP hosts that just
1620 # checks for expired dumps. We need to do this to handle
1621 # the case when a DHCP host has not been on the network for
1622 # a long time, and some of the old dumps need to be expired.
1623 # Normally expiry checks are done by BackupPC_dump only
1624 # after the DHCP hosts has been detected on the network.
1627 {host => $host, user => "BackupPC", reqTime => time,
1628 dhcp => 0, dumpExpire => 1});
1629 $BgQueueOn{$host} = 1;
1633 # this is a fixed ip host: queue it
1635 if ( $Info{DUlastValue} > $Conf{DfMaxUsagePct} ) {
1637 # Since we are out of disk space, instead of queuing
1638 # a regular job, queue an expire check instead. That
1639 # way if the admin reduces the number of backups to
1640 # keep then we will actually delete them. Otherwise
1641 # BackupPC_dump will never run since we have exceeded
1646 {host => $host, user => "BackupPC", reqTime => time,
1647 dhcp => $Hosts->{$host}{dhcp}, dumpExpire => 1});
1650 # Queue regular background backup
1653 {host => $host, user => "BackupPC", reqTime => time,
1654 dhcp => $Hosts->{$host}{dhcp}});
1656 $BgQueueOn{$host} = 1;
1660 print(LOG $bpc->timeStamp,
1661 "Disk too full ($Info{DUlastValue}%); skipped $nSkip hosts\n");
1662 $Info{DUDailySkipHostCnt} += $nSkip;
1664 foreach my $dhcp ( @{$Conf{DHCPAddressRanges}} ) {
1665 for ( my $i = $dhcp->{first} ; $i <= $dhcp->{last} ; $i++ ) {
1666 my $ipAddr = "$dhcp->{ipAddrBase}.$i";
1667 next if ( defined($Jobs{$ipAddr})
1668 || $BgQueueOn{$ipAddr}
1669 || $UserQueueOn{$ipAddr}
1670 || $CmdQueueOn{$ipAddr} );
1672 # this is a potential dhcp ip address (we don't know the
1673 # host name yet): queue it
1676 {host => $ipAddr, user => "BackupPC", reqTime => time,
1678 $BgQueueOn{$ipAddr} = 1;
1684 # Queue a BackupPC_link for the given host
1690 return if ( $CmdQueueOn{$host} );
1691 $Status{$host}{state} = "Status_link_pending";
1692 $Status{$host}{needLink} = 0;
1693 unshift(@CmdQueue, {
1697 cmd => ["$BinDir/BackupPC_link", $host],
1699 $CmdQueueOn{$host} = 1;
1703 # Read the hosts file, and update Status if any hosts have been
1704 # added or deleted. We also track the mtime so the only need to
1705 # update the hosts file on changes.
1707 # This function is called at startup, SIGHUP, and on each wakeup.
1708 # It returns 1 on success and undef on failure.
1715 # Nothing to do if we already have the current hosts file
1717 return 1 if ( !$force && defined($Hosts)
1718 && $Info{HostsModTime} == $bpc->HostsMTime() );
1719 if ( !defined($newHosts = $bpc->HostInfoRead()) ) {
1720 print(LOG $bpc->timeStamp, "Can't read hosts file!\n");
1723 print(LOG $bpc->timeStamp, "Reading hosts file\n");
1725 $Info{HostsModTime} = $bpc->HostsMTime();
1727 # Now update %Status in case any hosts have been added or deleted
1729 foreach my $host ( sort(keys(%$Hosts)) ) {
1730 next if ( defined($Status{$host}) );
1731 $Status{$host}{state} = "Status_idle";
1732 print(LOG $bpc->timeStamp, "Added host $host to backup list\n");
1734 foreach my $host ( sort(keys(%Status)) ) {
1735 next if ( $host eq $bpc->trashJob
1736 || $bpc->isAdminJob($host)
1737 || defined($Hosts->{$host})
1738 || defined($Jobs{$host})
1739 || $BgQueueOn{$host}
1740 || $UserQueueOn{$host}
1741 || $CmdQueueOn{$host} );
1742 print(LOG $bpc->timeStamp, "Deleted host $host from backup list\n");
1743 delete($Status{$host});
1749 # Remember the signal name for later processing
1755 foreach my $host ( keys(%Jobs) ) {
1756 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1759 # In case we are inside the exit handler, reopen the log file
1763 print(LOG "Fatal error: unhandled signal $SigName\n");
1764 unlink("$TopDir/log/BackupPC.pid");
1765 confess("Got new signal $SigName... quitting\n");
1772 # Open the log file and point STDOUT and STDERR there too
1776 mkpath("$TopDir/log", 0, 0777) if ( !-d "$TopDir/log" );
1777 open(LOG, ">>$TopDir/log/LOG")
1778 || die("Can't create LOG file $TopDir/log/LOG");
1781 open(STDOUT, ">&LOG");
1782 open(STDERR, ">&LOG");
1783 select(LOG); $| = 1;
1784 select(STDERR); $| = 1;
1785 select(STDOUT); $| = 1;
1789 # Initialize the unix-domain and internet-domain sockets that
1790 # we listen to for client connections (from the CGI script and
1791 # some of the BackupPC sub-programs).
1793 sub ServerSocketInit
1795 if ( !defined(fileno(SERVER_UNIX)) ) {
1797 # one-time only: initialize unix-domain socket
1799 if ( !socket(SERVER_UNIX, PF_UNIX, SOCK_STREAM, 0) ) {
1800 print(LOG $bpc->timeStamp, "unix socket() failed: $!\n");
1803 my $sockFile = "$TopDir/log/BackupPC.sock";
1805 if ( !bind(SERVER_UNIX, sockaddr_un($sockFile)) ) {
1806 print(LOG $bpc->timeStamp, "unix bind() failed: $!\n");
1809 if ( !listen(SERVER_UNIX, SOMAXCONN) ) {
1810 print(LOG $bpc->timeStamp, "unix listen() failed: $!\n");
1813 vec($FDread, fileno(SERVER_UNIX), 1) = 1;
1815 return if ( $ServerInetPort == $Conf{ServerPort} );
1816 if ( $ServerInetPort > 0 ) {
1817 vec($FDread, fileno(SERVER_INET), 1) = 0;
1819 $ServerInetPort = -1;
1821 if ( $Conf{ServerPort} > 0 ) {
1823 # Setup a socket to listen on $Conf{ServerPort}
1825 my $proto = getprotobyname('tcp');
1826 if ( !socket(SERVER_INET, PF_INET, SOCK_STREAM, $proto) ) {
1827 print(LOG $bpc->timeStamp, "inet socket() failed: $!\n");
1830 if ( !setsockopt(SERVER_INET, SOL_SOCKET, SO_REUSEADDR, pack("l",1)) ) {
1831 print(LOG $bpc->timeStamp, "setsockopt() failed: $!\n");
1834 if ( !bind(SERVER_INET, sockaddr_in($Conf{ServerPort}, INADDR_ANY)) ) {
1835 print(LOG $bpc->timeStamp, "inet bind() failed: $!\n");
1838 if ( !listen(SERVER_INET, SOMAXCONN) ) {
1839 print(LOG $bpc->timeStamp, "inet listen() failed: $!\n");
1842 vec($FDread, fileno(SERVER_INET), 1) = 1;
1843 $ServerInetPort = $Conf{ServerPort};
1848 # Reload the server. Used by Main_Process_Signal when $SigName eq "HUP"
1849 # or when the command "server reload" is received.
1854 $mesg = $bpc->ConfigRead() || $mesg;
1855 print(LOG $bpc->timeStamp, "$mesg\n");
1856 $Info{ConfigModTime} = $bpc->ConfigMTime();
1857 %Conf = $bpc->Conf();
1858 umask($Conf{UmaskMode});
1862 $Info{ConfigLTime} = time;
1866 # Gracefully shutdown the server. Used by Main_Process_Signal when
1867 # $SigName ne "" && $SigName ne "HUP" or when the command
1868 # "server shutdown" is received.
1873 print(LOG $bpc->timeStamp, "$mesg\n");
1874 if ( keys(%Jobs) ) {
1875 foreach my $host ( keys(%Jobs) ) {
1876 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1879 foreach my $host ( keys(%Jobs) ) {
1880 kill($bpc->sigName2num("KILL"), $Jobs{$host}{pid});
1886 unlink("$TopDir/log/BackupPC.pid");