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.
420 for my $p ( qw(pool cpool) ) {
421 for ( my $i = $start ; $i < $end ; $i++ ) {
422 $Info{pool}{$p}[$i]{FileCnt} = 0;
423 $Info{pool}{$p}[$i]{DirCnt} = 0;
424 $Info{pool}{$p}[$i]{Kb} = 0;
425 $Info{pool}{$p}[$i]{Kb2} = 0;
426 $Info{pool}{$p}[$i]{KbRm} = 0;
427 $Info{pool}{$p}[$i]{FileCntRm} = 0;
428 $Info{pool}{$p}[$i]{FileCntRep} = 0;
429 $Info{pool}{$p}[$i]{FileRepMax} = 0;
430 $Info{pool}{$p}[$i]{FileCntRename} = 0;
431 $Info{pool}{$p}[$i]{FileLinkMax} = 0;
432 $Info{pool}{$p}[$i]{Time} = 0;
435 print(LOG $bpc->timeStamp,
436 sprintf("Running %d BackupPC_nightly jobs from %d..%d"
437 . " (out of 0..15)\n",
438 $Conf{MaxBackupPCNightlyJobs}, $start, $end - 1));
441 # Now queue the $Conf{MaxBackupPCNightlyJobs} jobs.
442 # The granularity on start and end is now 0..255.
447 for ( my $i = 0 ; $i < $Conf{MaxBackupPCNightlyJobs} ; $i++ ) {
449 # The first nightly job gets the -m option (does email, log aging).
450 # All jobs get the start and end options from 0..255 telling
451 # them which parts of the pool to traverse.
453 my $cmd = ["$BinDir/BackupPC_nightly"];
454 push(@$cmd, "-m") if ( $i == 0 );
456 $start = $start0 + int(($end - $start0)
457 * ($i + 1) / $Conf{MaxBackupPCNightlyJobs});
458 push(@$cmd, $start - 1);
460 my $job = $bpc->adminJob($i);
467 $CmdQueueOn{$job} = 1;
469 $RunNightlyWhenIdle = 2;
473 ############################################################################
474 # Main_TryToRun_CmdQueue()
476 # Decide if we can run a new command from the @CmdQueue.
477 # We only run one of these at a time. The @CmdQueue is
478 # used to run BackupPC_link (for the corresponding host),
479 # BackupPC_trashClean, and BackupPC_nightly using a fake
480 # host name of $bpc->adminJob.
481 ############################################################################
482 sub Main_TryToRun_CmdQueue
486 while ( $CmdJob eq "" && @CmdQueue > 0 && $RunNightlyWhenIdle != 1
487 || @CmdQueue > 0 && $RunNightlyWhenIdle == 2
488 && $bpc->isAdminJob($CmdQueue[0]->{host})
491 $req = pop(@CmdQueue);
493 $host = $req->{host};
494 if ( defined($Jobs{$host}) ) {
495 print(LOG $bpc->timeStamp,
496 "Botch on admin job for $host: already in use!!\n");
498 # This could happen during normal opertion: a user could
499 # request a backup while a BackupPC_link is queued from
500 # a previous backup. But it is unlikely. Just put this
501 # request back on the end of the queue.
503 unshift(@CmdQueue, $req);
506 $CmdQueueOn{$host} = 0;
507 my $cmd = $req->{cmd};
508 my $pid = open(FH, "-|");
509 if ( !defined($pid) ) {
510 print(LOG $bpc->timeStamp,
511 "can't fork for $host, request by $req->{user}\n");
518 print(LOG $bpc->timeStamp, "can't exec @$cmd for $host\n");
521 $Jobs{$host}{pid} = $pid;
522 $Jobs{$host}{fh} = *FH;
523 $Jobs{$host}{fn} = fileno(FH);
524 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
525 $Jobs{$host}{startTime} = time;
526 $Jobs{$host}{reqTime} = $req->{reqTime};
527 $cmd = $bpc->execCmd2ShellCmd(@$cmd);
528 $Jobs{$host}{cmd} = $cmd;
529 $Jobs{$host}{user} = $req->{user};
530 $Jobs{$host}{type} = $Status{$host}{type};
531 $Status{$host}{state} = "Status_link_running";
532 $Status{$host}{activeJob} = 1;
533 $Status{$host}{endTime} = time;
534 $CmdJob = $host if ( $host ne $bpc->trashJob );
535 $cmd =~ s/$BinDir\///g;
536 print(LOG $bpc->timeStamp, "Running $cmd (pid=$pid)\n");
537 if ( $cmd =~ /^BackupPC_nightly\s/ ) {
538 $BackupPCNightlyJobs++;
539 $BackupPCNightlyLock++;
544 ############################################################################
545 # Main_TryToRun_Bg_or_User_Queue()
547 # Decide if we can run any new backup requests from @BgQueue
548 # or @UserQueue. Several of these can be run at the same time
549 # based on %Conf settings. Jobs from @UserQueue take priority,
550 # and at total of $Conf{MaxBackups} + $Conf{MaxUserBackups}
551 # simultaneous jobs can run from @UserQueue. After @UserQueue
552 # is exhausted, up to $Conf{MaxBackups} simultaneous jobs can
554 ############################################################################
555 sub Main_TryToRun_Bg_or_User_Queue
558 my(@deferUserQueue, @deferBgQueue);
561 if ( time - $Info{DUlastValueTime} >= 600 ) {
563 # Update our notion of disk usage no more than
564 # once every 10 minutes
566 $du = $bpc->CheckFileSystemUsage($TopDir);
567 $Info{DUlastValue} = $du;
568 $Info{DUlastValueTime} = time;
571 # if we recently checked it then just use the old value
573 $du = $Info{DUlastValue};
575 if ( $Info{DUDailyMaxReset} ) {
576 $Info{DUDailyMaxStartTime} = time;
577 $Info{DUDailyMaxReset} = 0;
578 $Info{DUDailyMax} = 0;
580 if ( $du > $Info{DUDailyMax} ) {
581 $Info{DUDailyMax} = $du;
582 $Info{DUDailyMaxTime} = time;
584 if ( $du > $Conf{DfMaxUsagePct} ) {
585 my @bgQueue = @BgQueue;
589 # When the disk is too full, only run backups that will
590 # do expires, not regular backups
593 foreach $req ( @bgQueue ) {
594 if ( $req->{dumpExpire} ) {
595 unshift(@BgQueue, $req);
597 $BgQueueOn{$req->{host}} = 0;
602 print(LOG $bpc->timeStamp,
603 "Disk too full ($du%); skipped $nSkip hosts\n");
604 $Info{DUDailySkipHostCnt} += $nSkip;
608 while ( $RunNightlyWhenIdle == 0 ) {
610 my(@args, $progName, $type);
611 my $nJobs = keys(%Jobs);
613 # CmdJob and trashClean don't count towards MaxBackups / MaxUserBackups
615 if ( $CmdJob ne "" ) {
616 if ( $BackupPCNightlyJobs ) {
617 $nJobs -= $BackupPCNightlyJobs;
622 $nJobs-- if ( defined($Jobs{$bpc->trashJob} ) );
623 if ( $nJobs < $Conf{MaxBackups} + $Conf{MaxUserBackups}
624 && @UserQueue > 0 ) {
625 $req = pop(@UserQueue);
626 if ( defined($Jobs{$req->{host}}) ) {
627 push(@deferUserQueue, $req);
630 push(@args, $req->{doFull} ? "-f" : "-i")
631 if (( !$req->{restore} ) && ( !$req->{archive} ));
632 $UserQueueOn{$req->{host}} = 0;
633 } elsif ( $nJobs < $Conf{MaxBackups}
634 && (@CmdQueue + $nJobs)
635 <= $Conf{MaxBackups} + $Conf{MaxPendingCmds}
637 $req = pop(@BgQueue);
638 if ( defined($Jobs{$req->{host}}) ) {
640 # Job is currently running for this host; save it for later
642 unshift(@deferBgQueue, $req);
645 $BgQueueOn{$req->{host}} = 0;
648 # Restore the deferred jobs
650 @BgQueue = (@BgQueue, @deferBgQueue);
651 @UserQueue = (@UserQueue, @deferUserQueue);
654 $host = $req->{host};
655 my $user = $req->{user};
656 if ( $req->{restore} ) {
657 $progName = "BackupPC_restore";
659 push(@args, $req->{hostIP}, $req->{host}, $req->{reqFileName});
660 } elsif ( $req->{archive} ) {
661 $progName = "BackupPC_archive";
663 push(@args, $req->{user}, $req->{host}, $req->{reqFileName});
665 $progName = "BackupPC_dump";
667 push(@args, "-d") if ( $req->{dhcp} );
668 push(@args, "-e") if ( $req->{dumpExpire} );
671 my $pid = open(FH, "-|");
672 if ( !defined($pid) ) {
673 print(LOG $bpc->timeStamp,
674 "can't fork to run $progName for $host, request by $user\n");
680 exec("$BinDir/$progName", @args);
681 print(LOG $bpc->timeStamp, "can't exec $progName for $host\n");
684 $Jobs{$host}{pid} = $pid;
685 $Jobs{$host}{fh} = *FH;
686 $Jobs{$host}{fn} = fileno(FH);
687 $Jobs{$host}{dhcp} = $req->{dhcp};
688 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
689 $Jobs{$host}{startTime} = time;
690 $Jobs{$host}{reqTime} = $req->{reqTime};
691 $Jobs{$host}{userReq} = $req->{userReq};
692 $Jobs{$host}{cmd} = $bpc->execCmd2ShellCmd($progName, @args);
693 $Jobs{$host}{user} = $user;
694 $Jobs{$host}{type} = $type;
695 $Status{$host}{userReq} = $req->{userReq}
696 if ( defined($Hosts->{$host}) );
697 if ( !$req->{dhcp} ) {
698 $Status{$host}{state} = "Status_".$type."_starting";
699 $Status{$host}{activeJob} = 1;
700 $Status{$host}{startTime} = time;
701 $Status{$host}{endTime} = "";
706 ############################################################################
709 # If necessary, figure out when to next wakeup based on $Conf{WakeupSchedule},
710 # and then do a select() to wait for the next thing to happen
711 # (timeout, signal, someone sends a message, child dies etc).
712 ############################################################################
715 if ( $NextWakeup <= 0 ) {
717 # Figure out when to next wakeup based on $Conf{WakeupSchedule}.
719 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
721 my($currHours) = $hour + $min / 60 + $sec / 3600;
722 if ( $bpc->ConfigMTime() != $Info{ConfigModTime} ) {
723 ServerReload("Re-read config file because mtime changed");
726 foreach my $t ( @{$Conf{WakeupSchedule} || [0..23]} ) {
727 next if ( $t < 0 || $t > 24 );
728 my $tomorrow = $t + 24;
730 || ($tomorrow - $currHours > 0
731 && $delta > $tomorrow - $currHours) ) {
732 $delta = $tomorrow - $currHours;
733 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
736 || ($t - $currHours > 0 && $delta > $t - $currHours) ) {
737 $delta = $t - $currHours;
738 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
741 $NextWakeup = time + $delta * 3600;
742 $Info{nextWakeup} = $NextWakeup;
743 print(LOG $bpc->timeStamp, "Next wakeup is ",
744 $bpc->timeStamp($NextWakeup, 1), "\n");
747 # Call select(), waiting until either a signal, a timeout,
748 # any output from our jobs, or any messages from clients
750 # select() is where we (hopefully) spend most of our time blocked...
752 my $timeout = $NextWakeup - time;
753 $timeout = 1 if ( $timeout <= 0 );
755 select(my $rout = $FDread, undef, $ein, $timeout);
760 ############################################################################
761 # Main_Process_Signal()
764 ############################################################################
765 sub Main_Process_Signal
770 if ( $SigName eq "HUP" ) {
771 ServerReload("Re-read config file because of a SIG_HUP");
772 } elsif ( $SigName ) {
773 ServerShutdown("Got signal $SigName... cleaning up");
778 ############################################################################
779 # Main_Check_Timeout()
781 # Check if a timeout has occured, and if so, queue all the PCs for backups.
782 # Also does log file aging on the first timeout after midnight.
783 ############################################################################
784 sub Main_Check_Timeout
789 return if ( time < $NextWakeup || $NextWakeup <= 0 );
791 if ( $FirstWakeup ) {
793 # This is the first wakeup after midnight. Do log file aging
794 # and various house keeping.
797 printf(LOG "%s24hr disk usage: %d%% max, %d%% recent,"
798 . " %d skipped hosts\n",
799 $bpc->timeStamp, $Info{DUDailyMax}, $Info{DUlastValue},
800 $Info{DUDailySkipHostCnt});
801 $Info{DUDailyMaxReset} = 1;
802 $Info{DUDailyMaxPrev} = $Info{DUDailyMax};
803 $Info{DUDailySkipHostCntPrev} = $Info{DUDailySkipHostCnt};
804 $Info{DUDailySkipHostCnt} = 0;
805 my $lastLog = $Conf{MaxOldLogFiles} - 1;
806 if ( -f "$TopDir/log/LOG.$lastLog" ) {
807 print(LOG $bpc->timeStamp,
808 "Removing $TopDir/log/LOG.$lastLog\n");
809 unlink("$TopDir/log/LOG.$lastLog");
811 if ( -f "$TopDir/log/LOG.$lastLog.z" ) {
812 print(LOG $bpc->timeStamp,
813 "Removing $TopDir/log/LOG.$lastLog.z\n");
814 unlink("$TopDir/log/LOG.$lastLog.z");
816 print(LOG $bpc->timeStamp, "Aging LOG files, LOG -> LOG.0 -> "
817 . "LOG.1 -> ... -> LOG.$lastLog\n");
818 close(STDERR); # dup of LOG
819 close(STDOUT); # dup of LOG
821 for ( my $i = $lastLog - 1 ; $i >= 0 ; $i-- ) {
823 rename("$TopDir/log/LOG.$i", "$TopDir/log/LOG.$j")
824 if ( -f "$TopDir/log/LOG.$i" );
825 rename("$TopDir/log/LOG.$i.z", "$TopDir/log/LOG.$j.z")
826 if ( -f "$TopDir/log/LOG.$i.z" );
829 # Compress the log file LOG -> LOG.0.z (if enabled).
830 # Otherwise, just rename LOG -> LOG.0.
832 BackupPC::FileZIO->compressCopy("$TopDir/log/LOG",
833 "$TopDir/log/LOG.0.z",
835 $Conf{CompressLevel}, 1);
838 # Remember to run nightly script after current jobs are done
840 $RunNightlyWhenIdle = 1;
843 # Write out the current status and then queue all the PCs
847 %BgQueueOn = () if ( @BgQueue == 0 );
848 %UserQueueOn = () if ( @UserQueue == 0 );
849 %CmdQueueOn = () if ( @CmdQueue == 0 );
853 ############################################################################
854 # Main_Check_Job_Messages($fdRead)
856 # Check if select() says we have bytes waiting from any of our jobs.
857 # Handle each of the messages when complete (newline terminated).
858 ############################################################################
859 sub Main_Check_Job_Messages
862 foreach my $host ( keys(%Jobs) ) {
863 next if ( !vec($fdRead, $Jobs{$host}{fn}, 1) );
866 # do a last check to make sure there is something to read so
867 # we are absolutely sure we won't block.
869 vec(my $readMask, $Jobs{$host}{fn}, 1) = 1;
870 if ( !select($readMask, undef, undef, 0.0) ) {
871 print(LOG $bpc->timeStamp, "Botch in Main_Check_Job_Messages:"
872 . " nothing to read from $host. Debug dump:\n");
873 my($dump) = Data::Dumper->new(
874 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
875 [qw(*Clients, *Jobs *FDread, *fdRead)]);
877 print(LOG $dump->Dump);
880 my $nbytes = sysread($Jobs{$host}{fh}, $mesg, 1024);
881 $Jobs{$host}{mesg} .= $mesg if ( $nbytes > 0 );
883 # Process any complete lines of output from this jobs.
884 # Any output to STDOUT or STDERR from the children is processed here.
886 while ( $Jobs{$host}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
888 $Jobs{$host}{mesg} = $2;
889 if ( $Jobs{$host}{dhcp} ) {
890 if ( $mesg =~ /^DHCP (\S+) (\S+)/ ) {
891 my $newHost = $bpc->uriUnesc($2);
892 if ( defined($Jobs{$newHost}) ) {
893 print(LOG $bpc->timeStamp,
894 "Backup on $newHost is already running\n");
895 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
899 $Jobs{$host}{dhcpHostIP} = $host;
900 $Status{$newHost}{dhcpHostIP} = $host;
901 $Jobs{$newHost} = $Jobs{$host};
902 delete($Jobs{$host});
904 $Status{$host}{state} = "Status_backup_starting";
905 $Status{$host}{activeJob} = 1;
906 $Status{$host}{startTime} = $Jobs{$host}{startTime};
907 $Status{$host}{endTime} = "";
908 $Jobs{$host}{dhcp} = 0;
910 print(LOG $bpc->timeStamp, "dhcp $host: $mesg\n");
912 } elsif ( $mesg =~ /^started (.*) dump, share=(.*)/ ) {
913 $Jobs{$host}{type} = $1;
914 $Jobs{$host}{shareName} = $2;
915 print(LOG $bpc->timeStamp,
916 "Started $1 backup on $host (pid=$Jobs{$host}{pid}",
917 $Jobs{$host}{dhcpHostIP}
918 ? ", dhcp=$Jobs{$host}{dhcpHostIP}" : "",
919 ", share=$Jobs{$host}{shareName})\n");
920 $Status{$host}{state} = "Status_backup_in_progress";
921 $Status{$host}{reason} = "";
922 $Status{$host}{type} = $1;
923 $Status{$host}{startTime} = time;
924 $Status{$host}{deadCnt} = 0;
925 $Status{$host}{aliveCnt}++;
926 $Status{$host}{dhcpCheckCnt}--
927 if ( $Status{$host}{dhcpCheckCnt} > 0 );
928 } elsif ( $mesg =~ /^xferPids (.*)/ ) {
929 $Jobs{$host}{xferPid} = $1;
930 } elsif ( $mesg =~ /^started_restore/ ) {
931 $Jobs{$host}{type} = "restore";
932 print(LOG $bpc->timeStamp,
933 "Started restore on $host"
934 . " (pid=$Jobs{$host}{pid})\n");
935 $Status{$host}{state} = "Status_restore_in_progress";
936 $Status{$host}{reason} = "";
937 $Status{$host}{type} = "restore";
938 $Status{$host}{startTime} = time;
939 $Status{$host}{deadCnt} = 0;
940 $Status{$host}{aliveCnt}++;
941 } elsif ( $mesg =~ /^started_archive/ ) {
942 $Jobs{$host}{type} = "archive";
943 print(LOG $bpc->timeStamp,
944 "Started archive on $host"
945 . " (pid=$Jobs{$host}{pid})\n");
946 $Status{$host}{state} = "Status_archive_in_progress";
947 $Status{$host}{reason} = "";
948 $Status{$host}{type} = "archive";
949 $Status{$host}{startTime} = time;
950 $Status{$host}{deadCnt} = 0;
951 $Status{$host}{aliveCnt}++;
952 } elsif ( $mesg =~ /^(full|incr) backup complete/ ) {
953 print(LOG $bpc->timeStamp, "Finished $1 backup on $host\n");
954 $Status{$host}{reason} = "Reason_backup_done";
955 delete($Status{$host}{error});
956 delete($Status{$host}{errorTime});
957 $Status{$host}{endTime} = time;
958 $Status{$host}{lastGoodBackupTime} = time;
959 } elsif ( $mesg =~ /^backups disabled/ ) {
960 print(LOG $bpc->timeStamp,
961 "Ignoring old backup error on $host\n");
962 $Status{$host}{reason} = "Reason_backup_done";
963 delete($Status{$host}{error});
964 delete($Status{$host}{errorTime});
965 $Status{$host}{endTime} = time;
966 } elsif ( $mesg =~ /^restore complete/ ) {
967 print(LOG $bpc->timeStamp, "Finished restore on $host\n");
968 $Status{$host}{reason} = "Reason_restore_done";
969 delete($Status{$host}{error});
970 delete($Status{$host}{errorTime});
971 $Status{$host}{endTime} = time;
972 } elsif ( $mesg =~ /^archive complete/ ) {
973 print(LOG $bpc->timeStamp, "Finished archive on $host\n");
974 $Status{$host}{reason} = "Reason_archive_done";
975 delete($Status{$host}{error});
976 delete($Status{$host}{errorTime});
977 $Status{$host}{endTime} = time;
978 } elsif ( $mesg =~ /^nothing to do/ ) {
979 if ( $Status{$host}{reason} ne "Reason_backup_failed"
980 && $Status{$host}{reason} ne "Reason_restore_failed" ) {
981 $Status{$host}{state} = "Status_idle";
982 $Status{$host}{reason} = "Reason_nothing_to_do";
983 $Status{$host}{startTime} = time;
985 $Status{$host}{dhcpCheckCnt}--
986 if ( $Status{$host}{dhcpCheckCnt} > 0 );
987 } elsif ( $mesg =~ /^no ping response/
988 || $mesg =~ /^ping too slow/
989 || $mesg =~ /^host not found/ ) {
990 $Status{$host}{state} = "Status_idle";
991 if ( $Status{$host}{userReq}
992 || $Status{$host}{reason} ne "Reason_backup_failed"
993 || $Status{$host}{error} =~ /^aborted by user/ ) {
994 $Status{$host}{reason} = "Reason_no_ping";
995 $Status{$host}{error} = $mesg;
996 $Status{$host}{startTime} = time;
998 $Status{$host}{deadCnt}++;
999 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1000 $Status{$host}{aliveCnt} = 0;
1002 } elsif ( $mesg =~ /^dump failed: (.*)/ ) {
1003 $Status{$host}{state} = "Status_idle";
1004 $Status{$host}{error} = $1;
1005 $Status{$host}{errorTime} = time;
1006 $Status{$host}{endTime} = time;
1007 if ( $Status{$host}{reason}
1008 eq "Reason_backup_canceled_by_user" ) {
1009 print(LOG $bpc->timeStamp,
1010 "Backup canceled on $host ($1)\n");
1012 $Status{$host}{reason} = "Reason_backup_failed";
1013 print(LOG $bpc->timeStamp,
1014 "Backup failed on $host ($1)\n");
1016 } elsif ( $mesg =~ /^restore failed: (.*)/ ) {
1017 $Status{$host}{state} = "Status_idle";
1018 $Status{$host}{error} = $1;
1019 $Status{$host}{errorTime} = time;
1020 $Status{$host}{endTime} = time;
1021 if ( $Status{$host}{reason}
1022 eq "Reason_restore_canceled_by_user" ) {
1023 print(LOG $bpc->timeStamp,
1024 "Restore canceled on $host ($1)\n");
1026 $Status{$host}{reason} = "Reason_restore_failed";
1027 print(LOG $bpc->timeStamp,
1028 "Restore failed on $host ($1)\n");
1030 } elsif ( $mesg =~ /^archive failed: (.*)/ ) {
1031 $Status{$host}{state} = "Status_idle";
1032 $Status{$host}{error} = $1;
1033 $Status{$host}{errorTime} = time;
1034 $Status{$host}{endTime} = time;
1035 if ( $Status{$host}{reason}
1036 eq "Reason_archive_canceled_by_user" ) {
1037 print(LOG $bpc->timeStamp,
1038 "Archive canceled on $host ($1)\n");
1040 $Status{$host}{reason} = "Reason_archive_failed";
1041 print(LOG $bpc->timeStamp,
1042 "Archive failed on $host ($1)\n");
1044 } elsif ( $mesg =~ /^log\s+(.*)/ ) {
1045 print(LOG $bpc->timeStamp, "$1\n");
1046 } elsif ( $mesg =~ /^BackupPC_stats (\d+) = (.*)/ ) {
1047 my $chunk = int($1 / 16);
1048 my @f = split(/,/, $2);
1049 $Info{pool}{$f[0]}[$chunk]{FileCnt} += $f[1];
1050 $Info{pool}{$f[0]}[$chunk]{DirCnt} += $f[2];
1051 $Info{pool}{$f[0]}[$chunk]{Kb} += $f[3];
1052 $Info{pool}{$f[0]}[$chunk]{Kb2} += $f[4];
1053 $Info{pool}{$f[0]}[$chunk]{KbRm} += $f[5];
1054 $Info{pool}{$f[0]}[$chunk]{FileCntRm} += $f[6];
1055 $Info{pool}{$f[0]}[$chunk]{FileCntRep} += $f[7];
1056 $Info{pool}{$f[0]}[$chunk]{FileRepMax} = $f[8]
1057 if ( $Info{pool}{$f[0]}[$chunk]{FileRepMax} < $f[8] );
1058 $Info{pool}{$f[0]}[$chunk]{FileCntRename} += $f[9];
1059 $Info{pool}{$f[0]}[$chunk]{FileLinkMax} = $f[10]
1060 if ( $Info{pool}{$f[0]}[$chunk]{FileLinkMax} < $f[10] );
1061 $Info{pool}{$f[0]}[$chunk]{FileLinkTotal} += $f[11];
1062 $Info{pool}{$f[0]}[$chunk]{Time} = time;
1063 } elsif ( $mesg =~ /^BackupPC_nightly lock_off/ ) {
1064 $BackupPCNightlyLock--;
1065 if ( $BackupPCNightlyLock == 0 ) {
1067 # This means the last BackupPC_nightly is done with
1068 # the pool clean, so it's ok to start running regular
1071 $RunNightlyWhenIdle = 0;
1073 } elsif ( $mesg =~ /^processState\s+(.+)/ ) {
1074 $Jobs{$host}{processState} = $1;
1075 } elsif ( $mesg =~ /^link\s+(.+)/ ) {
1077 $Status{$h}{needLink} = 1;
1079 print(LOG $bpc->timeStamp, "$host: $mesg\n");
1083 # shut down the client connection if we read EOF
1085 if ( $nbytes <= 0 ) {
1086 close($Jobs{$host}{fh});
1087 vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1088 if ( $CmdJob eq $host || $bpc->isAdminJob($host) ) {
1089 my $cmd = $Jobs{$host}{cmd};
1090 $cmd =~ s/$BinDir\///g;
1091 print(LOG $bpc->timeStamp, "Finished $host ($cmd)\n");
1092 $Status{$host}{state} = "Status_idle";
1093 $Status{$host}{endTime} = time;
1094 if ( $cmd =~ /^BackupPC_nightly\s/ ) {
1095 $BackupPCNightlyJobs--;
1096 #print(LOG $bpc->timeStamp, "BackupPC_nightly done; now"
1097 # . " have $BackupPCNightlyJobs running\n");
1098 if ( $BackupPCNightlyJobs <= 0 ) {
1099 $BackupPCNightlyJobs = 0;
1100 $RunNightlyWhenIdle = 0;
1103 # Combine the 16 per-directory results
1105 for my $p ( qw(pool cpool) ) {
1106 $Info{"${p}FileCnt"} = 0;
1107 $Info{"${p}DirCnt"} = 0;
1108 $Info{"${p}Kb"} = 0;
1109 $Info{"${p}Kb2"} = 0;
1110 $Info{"${p}KbRm"} = 0;
1111 $Info{"${p}FileCntRm"} = 0;
1112 $Info{"${p}FileCntRep"} = 0;
1113 $Info{"${p}FileRepMax"} = 0;
1114 $Info{"${p}FileCntRename"} = 0;
1115 $Info{"${p}FileLinkMax"} = 0;
1116 $Info{"${p}Time"} = 0;
1117 for ( my $i = 0 ; $i < 16 ; $i++ ) {
1118 $Info{"${p}FileCnt"}
1119 += $Info{pool}{$p}[$i]{FileCnt};
1121 += $Info{pool}{$p}[$i]{DirCnt};
1123 += $Info{pool}{$p}[$i]{Kb};
1125 += $Info{pool}{$p}[$i]{Kb2};
1127 += $Info{pool}{$p}[$i]{KbRm};
1128 $Info{"${p}FileCntRm"}
1129 += $Info{pool}{$p}[$i]{FileCntRm};
1130 $Info{"${p}FileCntRep"}
1131 += $Info{pool}{$p}[$i]{FileCntRep};
1132 $Info{"${p}FileRepMax"}
1133 = $Info{pool}{$p}[$i]{FileRepMax}
1134 if ( $Info{"${p}FileRepMax"} <
1135 $Info{pool}{$p}[$i]{FileRepMax} );
1136 $Info{"${p}FileCntRename"}
1137 += $Info{pool}{$p}[$i]{FileCntRename};
1138 $Info{"${p}FileLinkMax"}
1139 = $Info{pool}{$p}[$i]{FileLinkMax}
1140 if ( $Info{"${p}FileLinkMax"} <
1141 $Info{pool}{$p}[$i]{FileLinkMax} );
1142 $Info{"${p}Time"} = $Info{pool}{$p}[$i]{Time}
1143 if ( $Info{"${p}Time"} <
1144 $Info{pool}{$p}[$i]{Time} );
1146 printf(LOG "%s%s nightly clean removed %d files of"
1148 $bpc->timeStamp, ucfirst($p),
1149 $Info{"${p}FileCntRm"},
1150 $Info{"${p}KbRm"} / (1000 * 1024));
1151 printf(LOG "%s%s is %.2fGB, %d files (%d repeated, "
1152 . "%d max chain, %d max links), %d directories\n",
1153 $bpc->timeStamp, ucfirst($p),
1154 $Info{"${p}Kb"} / (1000 * 1024),
1155 $Info{"${p}FileCnt"}, $Info{"${p}FileCntRep"},
1156 $Info{"${p}FileRepMax"},
1157 $Info{"${p}FileLinkMax"}, $Info{"${p}DirCnt"});
1165 # Queue BackupPC_link to complete the backup
1166 # processing for this host.
1168 if ( defined($Status{$host})
1169 && ($Status{$host}{reason} eq "Reason_backup_done"
1170 || $Status{$host}{needLink}) ) {
1172 } elsif ( defined($Status{$host}) ) {
1173 $Status{$host}{state} = "Status_idle";
1176 delete($Jobs{$host});
1177 $Status{$host}{activeJob} = 0 if ( defined($Status{$host}) );
1181 # When we are idle (empty Jobs, CmdQueue, BgQueue, UserQueue) we
1182 # do a pass over %Status updating the deadCnt and aliveCnt for
1183 # DHCP hosts. The reason we need to do this later is we can't
1184 # be sure whether a DHCP host is alive or dead until we have passed
1185 # over all the DHCP pool.
1187 return if ( @CmdQueue || @BgQueue || @UserQueue || keys(%Jobs) > 1 );
1188 foreach my $host ( keys(%Status) ) {
1189 next if ( $Status{$host}{dhcpCheckCnt} <= 0 );
1190 $Status{$host}{deadCnt} += $Status{$host}{dhcpCheckCnt};
1191 $Status{$host}{dhcpCheckCnt} = 0;
1192 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1193 $Status{$host}{aliveCnt} = 0;
1198 ############################################################################
1199 # Main_Check_Client_Messages($fdRead)
1201 # Check for, and process, any output from our clients. Also checks
1202 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
1203 ############################################################################
1204 sub Main_Check_Client_Messages
1207 foreach my $client ( keys(%Clients) ) {
1208 next if ( !vec($fdRead, $Clients{$client}{fn}, 1) );
1211 # do a last check to make sure there is something to read so
1212 # we are absolutely sure we won't block.
1214 vec(my $readMask, $Clients{$client}{fn}, 1) = 1;
1215 if ( !select($readMask, undef, undef, 0.0) ) {
1216 print(LOG $bpc->timeStamp, "Botch in Main_Check_Client_Messages:"
1217 . " nothing to read from $client. Debug dump:\n");
1218 my($dump) = Data::Dumper->new(
1219 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
1220 [qw(*Clients, *Jobs *FDread, *fdRead)]);
1222 print(LOG $dump->Dump);
1225 my $nbytes = sysread($Clients{$client}{fh}, $mesg, 1024);
1226 $Clients{$client}{mesg} .= $mesg if ( $nbytes > 0 );
1228 # Process any complete lines received from this client.
1230 while ( $Clients{$client}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
1233 $Clients{$client}{mesg} = $2;
1235 # Authenticate the message by checking the MD5 digest
1237 my $md5 = Digest::MD5->new;
1238 if ( $cmd !~ /^(.{22}) (.*)/
1239 || ($md5->add($Clients{$client}{seed}
1240 . $Clients{$client}{mesgCnt}
1241 . $Conf{ServerMesgSecret} . $2),
1242 $md5->b64digest ne $1) ) {
1243 print(LOG $bpc->timeStamp, "Corrupted message '$cmd' from"
1244 . " client '$Clients{$client}{clientName}':"
1245 . " shutting down client connection\n");
1249 $Clients{$client}{mesgCnt}++;
1251 if ( $cmd =~ /^stop (\S+)\s+(\S+)\s+(\S*)/ ) {
1255 $host = $bpc->uriUnesc($host);
1256 if ( $CmdJob ne $host && defined($Status{$host})
1257 && defined($Jobs{$host}) ) {
1258 print(LOG $bpc->timeStamp,
1259 "Stopping current $Jobs{$host}{type} of $host,"
1260 . " request by $user (backoff=$backoff)\n");
1261 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1263 # Don't close the pipe now; wait until the child
1264 # really exits later. Otherwise close() will
1265 # block until the child has exited.
1267 ##vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1268 ##close($Jobs{$host}{fh});
1269 ##delete($Jobs{$host});
1271 $Status{$host}{state} = "Status_idle";
1272 if ( $Jobs{$host}{type} eq "restore" ) {
1273 $Status{$host}{reason}
1274 = "Reason_restore_canceled_by_user";
1275 } elsif ( $Jobs{$host}{type} eq "archive" ) {
1276 $Status{$host}{reason}
1277 = "Reason_archive_canceled_by_user";
1279 $Status{$host}{reason}
1280 = "Reason_backup_canceled_by_user";
1282 $Status{$host}{activeJob} = 0;
1283 $Status{$host}{startTime} = time;
1284 $reply = "ok: $Jobs{$host}{type} of $host canceled";
1285 } elsif ( $BgQueueOn{$host} || $UserQueueOn{$host} ) {
1286 print(LOG $bpc->timeStamp,
1287 "Stopping pending backup of $host,"
1288 . " request by $user (backoff=$backoff)\n");
1289 @BgQueue = grep($_->{host} ne $host, @BgQueue);
1290 @UserQueue = grep($_->{host} ne $host, @UserQueue);
1291 $BgQueueOn{$host} = $UserQueueOn{$host} = 0;
1292 $reply = "ok: pending backup of $host canceled";
1294 print(LOG $bpc->timeStamp,
1295 "Nothing to do for stop backup of $host,"
1296 . " request by $user (backoff=$backoff)\n");
1297 $reply = "ok: no backup was pending or running";
1299 if ( defined($Status{$host}) && $backoff ne "" ) {
1300 if ( $backoff > 0 ) {
1301 $Status{$host}{backoffTime} = time + $backoff * 3600;
1303 delete($Status{$host}{backoffTime});
1306 } elsif ( $cmd =~ /^backup all$/ ) {
1308 } elsif ( $cmd =~ /^BackupPC_nightly run$/ ) {
1309 $RunNightlyWhenIdle = 1;
1310 } elsif ( $cmd =~ /^backup (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1315 $host = $bpc->uriUnesc($host);
1316 $hostIP = $bpc->uriUnesc($hostIP);
1317 if ( !defined($Status{$host}) ) {
1318 print(LOG $bpc->timeStamp,
1319 "User $user requested backup of unknown host"
1321 $reply = "error: unknown host $host";
1323 print(LOG $bpc->timeStamp,
1324 "User $user requested backup of $host"
1326 if ( $BgQueueOn{$hostIP} ) {
1327 @BgQueue = grep($_->{host} ne $hostIP, @BgQueue);
1328 $BgQueueOn{$hostIP} = 0;
1330 if ( $UserQueueOn{$hostIP} ) {
1331 @UserQueue = grep($_->{host} ne $hostIP, @UserQueue);
1332 $UserQueueOn{$hostIP} = 0;
1334 unshift(@UserQueue, {
1340 dhcp => $hostIP eq $host ? 0 : 1,
1342 $UserQueueOn{$hostIP} = 1;
1343 $reply = "ok: requested backup of $host";
1345 } elsif ( $cmd =~ /^archive (\S+)\s+(\S+)\s+(\S+)/ ) {
1347 my $archivehost = $2;
1348 my $reqFileName = $3;
1349 $host = $bpc->uriUnesc($archivehost);
1350 if ( !defined($Status{$host}) ) {
1351 print(LOG $bpc->timeStamp,
1352 "User $user requested archive of unknown archive host"
1354 $reply = "archive error: unknown archive host $host";
1356 print(LOG $bpc->timeStamp,
1357 "User $user requested archive on $host"
1359 if ( defined($Jobs{$host}) ) {
1360 $reply = "Archive currently running on $host, please try later";
1362 unshift(@UserQueue, {
1365 reqFileName => $reqFileName,
1371 $UserQueueOn{$host} = 1;
1372 $reply = "ok: requested archive on $host";
1375 } elsif ( $cmd =~ /^restore (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1379 my $reqFileName = $4;
1380 $host = $bpc->uriUnesc($host);
1381 $hostIP = $bpc->uriUnesc($hostIP);
1382 if ( !defined($Status{$host}) ) {
1383 print(LOG $bpc->timeStamp,
1384 "User $user requested restore to unknown host"
1386 $reply = "restore error: unknown host $host";
1388 print(LOG $bpc->timeStamp,
1389 "User $user requested restore to $host"
1391 unshift(@UserQueue, {
1394 reqFileName => $reqFileName,
1400 $UserQueueOn{$host} = 1;
1401 if ( defined($Jobs{$host}) ) {
1402 $reply = "ok: requested restore of $host, but a"
1403 . " job is currently running,"
1404 . " so this request will start later";
1406 $reply = "ok: requested restore of $host";
1409 } elsif ( $cmd =~ /^status\s*(.*)/ ) {
1411 my($dump, @values, @names);
1412 foreach my $type ( split(/\s+/, $args) ) {
1413 if ( $type =~ /^queues/ ) {
1414 push(@values, \@BgQueue, \@UserQueue, \@CmdQueue);
1415 push(@names, qw(*BgQueue *UserQueue *CmdQueue));
1416 } elsif ( $type =~ /^jobs/ ) {
1417 push(@values, \%Jobs);
1418 push(@names, qw(*Jobs));
1419 } elsif ( $type =~ /^queueLen/ ) {
1421 BgQueue => scalar(@BgQueue),
1422 UserQueue => scalar(@UserQueue),
1423 CmdQueue => scalar(@CmdQueue),
1425 push(@names, qw(*QueueLen));
1426 } elsif ( $type =~ /^info/ ) {
1427 push(@values, \%Info);
1428 push(@names, qw(*Info));
1429 } elsif ( $type =~ /^hosts/ ) {
1430 push(@values, \%Status);
1431 push(@names, qw(*Status));
1432 } elsif ( $type =~ /^host\((.*)\)/ ) {
1433 my $h = $bpc->uriUnesc($1);
1434 if ( defined($Status{$h}) ) {
1437 BgQueueOn => $BgQueueOn{$h},
1438 UserQueueOn => $UserQueueOn{$h},
1439 CmdQueueOn => $CmdQueueOn{$h},
1441 push(@names, qw(*StatusHost));
1443 print(LOG $bpc->timeStamp,
1444 "Unknown host $h for status request\n");
1447 print(LOG $bpc->timeStamp,
1448 "Unknown status request $type\n");
1451 $dump = Data::Dumper->new(\@values, \@names);
1453 $reply = $dump->Dump;
1454 } elsif ( $cmd =~ /^link\s+(.+)/ ) {
1456 $host = $bpc->uriUnesc($host);
1458 } elsif ( $cmd =~ /^log\s+(.*)/ ) {
1459 print(LOG $bpc->timeStamp, "$1\n");
1460 } elsif ( $cmd =~ /^server\s+(\w+)/ ) {
1462 if ( $type eq 'reload' ) {
1463 ServerReload("Reloading config/host files via CGI request");
1464 } elsif ( $type eq 'shutdown' ) {
1465 $reply = "Shutting down...\n";
1466 syswrite($Clients{$client}{fh}, $reply, length($reply));
1467 ServerShutdown("Server shutting down...");
1469 } elsif ( $cmd =~ /^quit/ || $cmd =~ /^exit/ ) {
1473 print(LOG $bpc->timeStamp, "Unknown command $cmd\n");
1474 $reply = "error: bad command $cmd";
1477 # send a reply to the client, at a minimum "ok\n".
1479 $reply = "ok" if ( $reply eq "" );
1481 syswrite($Clients{$client}{fh}, $reply, length($reply));
1484 # Detect possible denial-of-service attack from sending a huge line
1485 # (ie: never terminated). 32K seems to be plenty big enough as
1488 if ( length($Clients{$client}{mesg}) > 32 * 1024 ) {
1489 print(LOG $bpc->timeStamp, "Line too long from client"
1490 . " '$Clients{$client}{clientName}':"
1491 . " shutting down client connection\n");
1495 # Shut down the client connection if we read EOF
1497 if ( $nbytes <= 0 ) {
1498 close($Clients{$client}{fh});
1499 vec($FDread, $Clients{$client}{fn}, 1) = 0;
1500 delete($Clients{$client});
1504 # Accept any new connections on each of our listen sockets
1506 if ( vec($fdRead, fileno(SERVER_UNIX), 1) ) {
1508 my $paddr = accept(CLIENT, SERVER_UNIX);
1510 $Clients{$ClientConnCnt}{clientName} = "unix socket";
1511 $Clients{$ClientConnCnt}{mesg} = "";
1512 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1513 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1514 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1516 # Generate and send unique seed for MD5 digests to avoid
1517 # replay attacks. See BackupPC::Lib::ServerMesg().
1519 my $seed = time . ",$ClientConnCnt,$$,0\n";
1520 $Clients{$ClientConnCnt}{seed} = $seed;
1521 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1522 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1524 if ( $ServerInetPort > 0 && vec($fdRead, fileno(SERVER_INET), 1) ) {
1526 my $paddr = accept(CLIENT, SERVER_INET);
1527 my($port,$iaddr) = sockaddr_in($paddr);
1528 my $name = gethostbyaddr($iaddr, AF_INET);
1530 $Clients{$ClientConnCnt}{mesg} = "";
1531 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1532 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1533 $Clients{$ClientConnCnt}{clientName} = "$name:$port";
1534 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1536 # Generate and send unique seed for MD5 digests to avoid
1537 # replay attacks. See BackupPC::Lib::ServerMesg().
1539 my $seed = time . ",$ClientConnCnt,$$,$port\n";
1540 $Clients{$ClientConnCnt}{seed} = $seed;
1541 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1542 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1546 ###########################################################################
1547 # Miscellaneous subroutines
1548 ###########################################################################
1551 # Write the current status to $TopDir/log/status.pl
1555 my($dump) = Data::Dumper->new(
1556 [ \%Info, \%Status],
1557 [qw(*Info *Status)]);
1559 if ( open(STATUS, ">", "$TopDir/log/status.pl") ) {
1560 print(STATUS $dump->Dump);
1566 # Compare function for host sort. Hosts with errors go first,
1567 # sorted with the oldest errors first. The remaining hosts
1568 # are sorted so that those with the oldest backups go first.
1573 # Hosts with errors go before hosts without errors
1575 return -1 if ( $Status{$a}{error} ne "" && $Status{$b}{error} eq "" );
1578 # Hosts with no errors go after hosts with errors
1581 return 1 if ( $Status{$a}{error} eq "" && $Status{$b}{error} ne "" );
1584 # hosts with the older last good backups sort earlier
1586 my $r = $Status{$a}{lastGoodBackupTime} <=> $Status{$b}{lastGoodBackupTime};
1587 return $r if ( $r );
1590 # Finally, just sort based on host name
1596 # Queue all the hosts for backup. This means queuing all the fixed
1597 # ip hosts and all the dhcp address ranges. We also additionally
1598 # queue the dhcp hosts with a -e flag to check for expired dumps.
1603 foreach my $host ( sort(HostSortCompare keys(%$Hosts)) ) {
1604 delete($Status{$host}{backoffTime})
1605 if ( defined($Status{$host}{backoffTime})
1606 && $Status{$host}{backoffTime} < time );
1607 next if ( defined($Jobs{$host})
1608 || $BgQueueOn{$host}
1609 || $UserQueueOn{$host}
1610 || $CmdQueueOn{$host} );
1611 if ( $Hosts->{$host}{dhcp} ) {
1612 $Status{$host}{dhcpCheckCnt}++;
1613 if ( $RunNightlyWhenIdle ) {
1615 # Once per night queue a check for DHCP hosts that just
1616 # checks for expired dumps. We need to do this to handle
1617 # the case when a DHCP host has not been on the network for
1618 # a long time, and some of the old dumps need to be expired.
1619 # Normally expiry checks are done by BackupPC_dump only
1620 # after the DHCP hosts has been detected on the network.
1623 {host => $host, user => "BackupPC", reqTime => time,
1624 dhcp => 0, dumpExpire => 1});
1625 $BgQueueOn{$host} = 1;
1629 # this is a fixed ip host: queue it
1631 if ( $Info{DUlastValue} > $Conf{DfMaxUsagePct} ) {
1633 # Since we are out of disk space, instead of queuing
1634 # a regular job, queue an expire check instead. That
1635 # way if the admin reduces the number of backups to
1636 # keep then we will actually delete them. Otherwise
1637 # BackupPC_dump will never run since we have exceeded
1642 {host => $host, user => "BackupPC", reqTime => time,
1643 dhcp => $Hosts->{$host}{dhcp}, dumpExpire => 1});
1646 # Queue regular background backup
1649 {host => $host, user => "BackupPC", reqTime => time,
1650 dhcp => $Hosts->{$host}{dhcp}});
1652 $BgQueueOn{$host} = 1;
1656 print(LOG $bpc->timeStamp,
1657 "Disk too full ($Info{DUlastValue}%); skipped $nSkip hosts\n");
1658 $Info{DUDailySkipHostCnt} += $nSkip;
1660 foreach my $dhcp ( @{$Conf{DHCPAddressRanges}} ) {
1661 for ( my $i = $dhcp->{first} ; $i <= $dhcp->{last} ; $i++ ) {
1662 my $ipAddr = "$dhcp->{ipAddrBase}.$i";
1663 next if ( defined($Jobs{$ipAddr})
1664 || $BgQueueOn{$ipAddr}
1665 || $UserQueueOn{$ipAddr}
1666 || $CmdQueueOn{$ipAddr} );
1668 # this is a potential dhcp ip address (we don't know the
1669 # host name yet): queue it
1672 {host => $ipAddr, user => "BackupPC", reqTime => time,
1674 $BgQueueOn{$ipAddr} = 1;
1680 # Queue a BackupPC_link for the given host
1686 return if ( $CmdQueueOn{$host} );
1687 $Status{$host}{state} = "Status_link_pending";
1688 $Status{$host}{needLink} = 0;
1689 unshift(@CmdQueue, {
1693 cmd => ["$BinDir/BackupPC_link", $host],
1695 $CmdQueueOn{$host} = 1;
1699 # Read the hosts file, and update Status if any hosts have been
1700 # added or deleted. We also track the mtime so the only need to
1701 # update the hosts file on changes.
1703 # This function is called at startup, SIGHUP, and on each wakeup.
1704 # It returns 1 on success and undef on failure.
1711 # Nothing to do if we already have the current hosts file
1713 return 1 if ( !$force && defined($Hosts)
1714 && $Info{HostsModTime} == $bpc->HostsMTime() );
1715 if ( !defined($newHosts = $bpc->HostInfoRead()) ) {
1716 print(LOG $bpc->timeStamp, "Can't read hosts file!\n");
1719 print(LOG $bpc->timeStamp, "Reading hosts file\n");
1721 $Info{HostsModTime} = $bpc->HostsMTime();
1723 # Now update %Status in case any hosts have been added or deleted
1725 foreach my $host ( sort(keys(%$Hosts)) ) {
1726 next if ( defined($Status{$host}) );
1727 $Status{$host}{state} = "Status_idle";
1728 print(LOG $bpc->timeStamp, "Added host $host to backup list\n");
1730 foreach my $host ( sort(keys(%Status)) ) {
1731 next if ( $host eq $bpc->trashJob
1732 || $bpc->isAdminJob($host)
1733 || defined($Hosts->{$host})
1734 || defined($Jobs{$host})
1735 || $BgQueueOn{$host}
1736 || $UserQueueOn{$host}
1737 || $CmdQueueOn{$host} );
1738 print(LOG $bpc->timeStamp, "Deleted host $host from backup list\n");
1739 delete($Status{$host});
1745 # Remember the signal name for later processing
1751 foreach my $host ( keys(%Jobs) ) {
1752 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1755 # In case we are inside the exit handler, reopen the log file
1759 print(LOG "Fatal error: unhandled signal $SigName\n");
1760 unlink("$TopDir/log/BackupPC.pid");
1761 confess("Got new signal $SigName... quitting\n");
1768 # Open the log file and point STDOUT and STDERR there too
1772 mkpath("$TopDir/log", 0, 0777) if ( !-d "$TopDir/log" );
1773 open(LOG, ">>$TopDir/log/LOG")
1774 || die("Can't create LOG file $TopDir/log/LOG");
1777 open(STDOUT, ">&LOG");
1778 open(STDERR, ">&LOG");
1779 select(LOG); $| = 1;
1780 select(STDERR); $| = 1;
1781 select(STDOUT); $| = 1;
1785 # Initialize the unix-domain and internet-domain sockets that
1786 # we listen to for client connections (from the CGI script and
1787 # some of the BackupPC sub-programs).
1789 sub ServerSocketInit
1791 if ( !defined(fileno(SERVER_UNIX)) ) {
1793 # one-time only: initialize unix-domain socket
1795 if ( !socket(SERVER_UNIX, PF_UNIX, SOCK_STREAM, 0) ) {
1796 print(LOG $bpc->timeStamp, "unix socket() failed: $!\n");
1799 my $sockFile = "$TopDir/log/BackupPC.sock";
1801 if ( !bind(SERVER_UNIX, sockaddr_un($sockFile)) ) {
1802 print(LOG $bpc->timeStamp, "unix bind() failed: $!\n");
1805 if ( !listen(SERVER_UNIX, SOMAXCONN) ) {
1806 print(LOG $bpc->timeStamp, "unix listen() failed: $!\n");
1809 vec($FDread, fileno(SERVER_UNIX), 1) = 1;
1811 return if ( $ServerInetPort == $Conf{ServerPort} );
1812 if ( $ServerInetPort > 0 ) {
1813 vec($FDread, fileno(SERVER_INET), 1) = 0;
1815 $ServerInetPort = -1;
1817 if ( $Conf{ServerPort} > 0 ) {
1819 # Setup a socket to listen on $Conf{ServerPort}
1821 my $proto = getprotobyname('tcp');
1822 if ( !socket(SERVER_INET, PF_INET, SOCK_STREAM, $proto) ) {
1823 print(LOG $bpc->timeStamp, "inet socket() failed: $!\n");
1826 if ( !setsockopt(SERVER_INET, SOL_SOCKET, SO_REUSEADDR, pack("l",1)) ) {
1827 print(LOG $bpc->timeStamp, "setsockopt() failed: $!\n");
1830 if ( !bind(SERVER_INET, sockaddr_in($Conf{ServerPort}, INADDR_ANY)) ) {
1831 print(LOG $bpc->timeStamp, "inet bind() failed: $!\n");
1834 if ( !listen(SERVER_INET, SOMAXCONN) ) {
1835 print(LOG $bpc->timeStamp, "inet listen() failed: $!\n");
1838 vec($FDread, fileno(SERVER_INET), 1) = 1;
1839 $ServerInetPort = $Conf{ServerPort};
1844 # Reload the server. Used by Main_Process_Signal when $SigName eq "HUP"
1845 # or when the command "server reload" is received.
1850 $mesg = $bpc->ConfigRead() || $mesg;
1851 print(LOG $bpc->timeStamp, "$mesg\n");
1852 $Info{ConfigModTime} = $bpc->ConfigMTime();
1853 %Conf = $bpc->Conf();
1854 umask($Conf{UmaskMode});
1858 $Info{ConfigLTime} = time;
1862 # Gracefully shutdown the server. Used by Main_Process_Signal when
1863 # $SigName ne "" && $SigName ne "HUP" or when the command
1864 # "server shutdown" is received.
1869 print(LOG $bpc->timeStamp, "$mesg\n");
1870 if ( keys(%Jobs) ) {
1871 foreach my $host ( keys(%Jobs) ) {
1872 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1875 foreach my $host ( keys(%Jobs) ) {
1876 kill($bpc->sigName2num("KILL"), $Jobs{$host}{pid});
1882 unlink("$TopDir/log/BackupPC.pid");