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.0beta1, released 9 Apr 2004.
52 # See http://backuppc.sourceforge.net.
54 #========================================================================
58 use vars qw(%Status %Info $Hosts);
59 use lib "/usr/local/BackupPC/lib";
61 use BackupPC::FileZIO;
70 ###########################################################################
71 # Handle command line options
72 ###########################################################################
74 if ( !getopts("d", \%opts) || @ARGV != 0 ) {
75 print("usage: $0 [-d]\n");
79 ###########################################################################
80 # Initialize major data structures and variables
81 ###########################################################################
84 # Get an instance of BackupPC::Lib and get some shortcuts.
86 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
87 my $TopDir = $bpc->TopDir();
88 my $BinDir = $bpc->BinDir();
89 my %Conf = $bpc->Conf();
92 # Verify we are running as the correct user
94 if ( $Conf{BackupPCUserVerify}
95 && $> != (my $uid = (getpwnam($Conf{BackupPCUser}))[2]) ) {
96 die "Wrong user: my userid is $>, instead of $uid ($Conf{BackupPCUser})\n";
100 # %Status maintain status information about each host.
101 # It is a hash of hashes, whose first index is the host.
106 # %Info is a hash giving general information about BackupPC status.
113 if ( -f "$TopDir/log/status.pl" && !(my $ret = do "$TopDir/log/status.pl") ) {
114 die "couldn't parse $TopDir/log/status.pl: $@" if $@;
115 die "couldn't do $TopDir/log/status.pl: $!" unless defined $ret;
116 die "couldn't run $TopDir/log/status.pl";
120 # %Jobs maintains information about currently running jobs.
121 # It is a hash of hashes, whose first index is the host.
126 # There are three command queues:
127 # - @UserQueue is a queue of user initiated backup requests.
128 # - @BgQueue is a queue of automatically scheduled backup requests.
129 # - @CmdQueue is a queue of administrative jobs, including tasks
130 # like BackupPC_link, BackupPC_trashClean, and BackupPC_nightly
131 # Each queue is an array of hashes. Each hash stores information
132 # about the command request.
139 # To quickly lookup if a given host is on a given queue, we keep
140 # a hash of flags for each queue type.
142 my(%CmdQueueOn, %UserQueueOn, %BgQueueOn);
145 # One or more clients can connect to the server to get status information
146 # or request/cancel backups etc. The %Clients hash maintains information
147 # about each of these socket connections. The hash key is an incrementing
148 # number stored in $ClientConnCnt. Each entry is a hash that contains
149 # various information about the client connection.
155 # Read file descriptor mask used by select(). Every file descriptor
156 # on which we expect to read (or accept) has the corresponding bit
162 # Unix seconds when we next wakeup. A value of zero forces the scheduler
163 # to compute the next wakeup time.
168 # Name of signal saved by catch_signal
175 my($RunNightlyWhenIdle, $FirstWakeup, $CmdJob, $ServerInetPort);
176 my($BackupPCNightlyJobs, $BackupPCNightlyLock);
179 # Complete the rest of the initialization
183 ###########################################################################
185 ###########################################################################
189 # Check if we can/should run BackupPC_nightly
191 Main_TryToRun_nightly();
194 # Check if we can run a new command from @CmdQueue.
196 Main_TryToRun_CmdQueue();
199 # Check if we can run a new command from @UserQueue or @BgQueue.
201 Main_TryToRun_Bg_or_User_Queue();
204 # Do a select() to wait for the next interesting thing to happen
205 # (timeout, signal, someone sends a message, child dies etc).
207 my $fdRead = Main_Select();
210 # Process a signal if we received one.
213 Main_Process_Signal();
218 # Check if a timeout has occurred.
220 Main_Check_Timeout();
223 # Check for, and process, any messages (output) from our jobs
225 Main_Check_Job_Messages($fdRead);
228 # Check for, and process, any output from our clients. Also checks
229 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
231 Main_Check_Client_Messages($fdRead);
234 ############################################################################
237 # Main initialization routine. Called once at statup.
238 ############################################################################
241 umask($Conf{UmaskMode});
244 # Check for another running process, check that PASSWD is set and
245 # verify executables are configured correctly.
247 if ( $Info{pid} ne "" && kill(0, $Info{pid}) ) {
248 print(STDERR $bpc->timeStamp,
249 "Another BackupPC is running (pid $Info{pid}); quitting...\n");
252 foreach my $progName ( qw(SmbClientPath NmbLookupPath PingPath DfPath
253 SendmailPath SshPath) ) {
254 next if ( $Conf{$progName} eq "" || -x $Conf{$progName} );
255 print(STDERR $bpc->timeStamp,
256 "\$Conf{$progName} = '$Conf{$progName}' is not a"
257 . " valid executable program\n");
263 # daemonize by forking
265 defined(my $pid = fork) or die "Can't fork: $!";
266 exit if $pid; # parent exits
270 # Open the LOG file and redirect STDOUT, STDERR etc
275 # Read the hosts file (force a read).
277 exit(1) if ( !HostsUpdate(1) );
280 # Clean up %ENV for taint checking
282 delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
283 $ENV{PATH} = $Conf{MyPath};
286 # Initialize server sockets
291 # Catch various signals
293 foreach my $sig ( qw(INT BUS SEGV PIPE TERM ALRM HUP) ) {
294 $SIG{$sig} = \&catch_signal;
298 # Report that we started, and update %Info.
300 print(LOG $bpc->timeStamp, "BackupPC started, pid $$\n");
301 $Info{ConfigModTime} = $bpc->ConfigMTime();
303 $Info{startTime} = time;
304 $Info{ConfigLTime} = time;
305 $Info{Version} = $bpc->{Version};
308 # Update the status left over form the last time BackupPC ran.
309 # Requeue any pending links.
311 foreach my $host ( sort(keys(%$Hosts)) ) {
312 if ( $Status{$host}{state} eq "Status_backup_in_progress" ) {
314 # should we restart it? skip it for now.
316 $Status{$host}{state} = "Status_idle";
317 } elsif ( $Status{$host}{state} eq "Status_link_pending"
318 || $Status{$host}{state} eq "Status_link_running" ) {
321 $Status{$host}{state} = "Status_idle";
323 $Status{$host}{activeJob} = 0;
325 foreach my $host ( sort(keys(%Status)) ) {
326 next if ( defined($Hosts->{$host}) );
327 delete($Status{$host});
331 # Write out our initial status and save our PID
334 if ( open(PID, ">", "$TopDir/log/BackupPC.pid") ) {
340 # For unknown reasons there is a very infrequent error about not
341 # being able to coerce GLOBs inside the XS Data::Dumper. I've
342 # only seen this on a particular platform and perl version.
343 # For now the workaround appears to be use the perl version of
346 $Data::Dumper::Useqq = 1;
349 ############################################################################
350 # Main_TryToRun_nightly()
352 # Checks to see if we can/should run BackupPC_nightly or
353 # BackupPC_trashClean. If so we push the appropriate command onto
355 ############################################################################
356 sub Main_TryToRun_nightly
359 # Check if we should run BackupPC_nightly or BackupPC_trashClean.
360 # BackupPC_nightly is run when the current job queue is empty.
361 # BackupPC_trashClean is run in the background always.
363 my $trashCleanRunning = defined($Jobs{$bpc->trashJob}) ? 1 : 0;
364 if ( !$trashCleanRunning && !$CmdQueueOn{$bpc->trashJob} ) {
366 # This should only happen once at startup, but just in case this
367 # code will re-start BackupPC_trashClean if it quits
370 host => $bpc->trashJob,
373 cmd => ["$BinDir/BackupPC_trashClean"],
375 $CmdQueueOn{$bpc->trashJob} = 1;
377 if ( keys(%Jobs) == $trashCleanRunning && $RunNightlyWhenIdle == 1 ) {
380 # Queue multiple nightly jobs based on the configuration
382 $Conf{MaxBackupPCNightlyJobs} = 1
383 if ( $Conf{MaxBackupPCNightlyJobs} <= 0 );
384 $Conf{BackupPCNightlyPeriod} = 1
385 if ( $Conf{BackupPCNightlyPeriod} <= 0 );
387 # Decide what subset of the 16 top-level directories 0..9a..f
388 # we run BackupPC_nightly on, based on $Conf{BackupPCNightlyPeriod}.
389 # If $Conf{BackupPCNightlyPeriod} == 1 then we run 0..15 every
390 # time. If $Conf{BackupPCNightlyPeriod} == 2 then we run
391 # 0..7 one night and 89a-f the next night. And so on.
393 # $Info{NightlyPhase} counts which night, from 0 to
394 # $Conf{BackupPCNightlyPeriod} - 1.
396 my $start = int($Info{NightlyPhase} * 16
397 / $Conf{BackupPCNightlyPeriod});
398 my $end = int(($Info{NightlyPhase} + 1) * 16
399 / $Conf{BackupPCNightlyPeriod});
400 $end = $start + 1 if ( $end <= $start );
401 $Info{NightlyPhase}++;
402 $Info{NightlyPhase} = 0 if ( $end >= 16 );
405 # Zero out the data we expect to get from BackupPC_nightly.
406 # In the future if we want to split BackupPC_nightly over
407 # more than one night we will only zero out the portion
408 # that we are running right now.
410 for my $p ( qw(pool cpool) ) {
411 for ( my $i = $start ; $i < $end ; $i++ ) {
412 $Info{pool}{$p}[$i]{FileCnt} = 0;
413 $Info{pool}{$p}[$i]{DirCnt} = 0;
414 $Info{pool}{$p}[$i]{Kb} = 0;
415 $Info{pool}{$p}[$i]{Kb2} = 0;
416 $Info{pool}{$p}[$i]{KbRm} = 0;
417 $Info{pool}{$p}[$i]{FileCntRm} = 0;
418 $Info{pool}{$p}[$i]{FileCntRep} = 0;
419 $Info{pool}{$p}[$i]{FileRepMax} = 0;
420 $Info{pool}{$p}[$i]{FileCntRename} = 0;
421 $Info{pool}{$p}[$i]{FileLinkMax} = 0;
422 $Info{pool}{$p}[$i]{Time} = 0;
425 print(LOG $bpc->timeStamp,
426 sprintf("Running %d BackupPC_nightly jobs from %d..%d"
427 . " (out of 0..15)\n",
428 $Conf{MaxBackupPCNightlyJobs}, $start, $end - 1));
431 # Now queue the $Conf{MaxBackupPCNightlyJobs} jobs.
432 # The granularity on start and end is now 0..256.
437 for ( my $i = 0 ; $i < $Conf{MaxBackupPCNightlyJobs} ; $i++ ) {
439 # The first nightly job gets the -m option (does email, log aging).
440 # All jobs get the start and end options from 0..255 telling
441 # them which parts of the pool to traverse.
443 my $cmd = ["$BinDir/BackupPC_nightly"];
444 push(@$cmd, "-m") if ( $i == 0 );
446 $start = $start0 + int(($end - $start0)
447 * ($i + 1) / $Conf{MaxBackupPCNightlyJobs});
448 push(@$cmd, $start - 1);
450 my $job = $bpc->adminJob($i);
457 $CmdQueueOn{$job} = 1;
459 $RunNightlyWhenIdle = 2;
464 ############################################################################
465 # Main_TryToRun_CmdQueue()
467 # Decide if we can run a new command from the @CmdQueue.
468 # We only run one of these at a time. The @CmdQueue is
469 # used to run BackupPC_link (for the corresponding host),
470 # BackupPC_trashClean, and BackupPC_nightly using a fake
471 # host name of $bpc->adminJob.
472 ############################################################################
473 sub Main_TryToRun_CmdQueue
477 while ( $CmdJob eq "" && @CmdQueue > 0 && $RunNightlyWhenIdle != 1
478 || @CmdQueue > 0 && $RunNightlyWhenIdle == 2
479 && $bpc->isAdminJob($CmdQueue[0]->{host})
482 $req = pop(@CmdQueue);
484 $host = $req->{host};
485 if ( defined($Jobs{$host}) ) {
486 print(LOG $bpc->timeStamp,
487 "Botch on admin job for $host: already in use!!\n");
489 # This could happen during normal opertion: a user could
490 # request a backup while a BackupPC_link is queued from
491 # a previous backup. But it is unlikely. Just put this
492 # request back on the end of the queue.
494 unshift(@CmdQueue, $req);
497 $CmdQueueOn{$host} = 0;
498 my $cmd = $req->{cmd};
499 my $pid = open(FH, "-|");
500 if ( !defined($pid) ) {
501 print(LOG $bpc->timeStamp,
502 "can't fork for $host, request by $req->{user}\n");
509 print(LOG $bpc->timeStamp, "can't exec @$cmd for $host\n");
512 $Jobs{$host}{pid} = $pid;
513 $Jobs{$host}{fh} = *FH;
514 $Jobs{$host}{fn} = fileno(FH);
515 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
516 $Jobs{$host}{startTime} = time;
517 $Jobs{$host}{reqTime} = $req->{reqTime};
518 $cmd = $bpc->execCmd2ShellCmd(@$cmd);
519 $Jobs{$host}{cmd} = $cmd;
520 $Jobs{$host}{user} = $req->{user};
521 $Jobs{$host}{type} = $Status{$host}{type};
522 $Status{$host}{state} = "Status_link_running";
523 $Status{$host}{activeJob} = 1;
524 $Status{$host}{endTime} = time;
525 $CmdJob = $host if ( $host ne $bpc->trashJob );
526 $cmd =~ s/$BinDir\///g;
527 print(LOG $bpc->timeStamp, "Running $cmd (pid=$pid)\n");
528 if ( $cmd =~ /^BackupPC_nightly\s/ ) {
529 $BackupPCNightlyJobs++;
530 $BackupPCNightlyLock++;
535 ############################################################################
536 # Main_TryToRun_Bg_or_User_Queue()
538 # Decide if we can run any new backup requests from @BgQueue
539 # or @UserQueue. Several of these can be run at the same time
540 # based on %Conf settings. Jobs from @UserQueue take priority,
541 # and at total of $Conf{MaxBackups} + $Conf{MaxUserBackups}
542 # simultaneous jobs can run from @UserQueue. After @UserQueue
543 # is exhausted, up to $Conf{MaxBackups} simultaneous jobs can
545 ############################################################################
546 sub Main_TryToRun_Bg_or_User_Queue
549 while ( $RunNightlyWhenIdle == 0 ) {
551 my(@args, @deferUserQueue, @deferBgQueue, $progName, $type);
552 my $nJobs = keys(%Jobs);
554 # CmdJob and trashClean don't count towards MaxBackups / MaxUserBackups
556 $nJobs -= $BackupPCNightlyJobs if ( $CmdJob ne "" );
557 $nJobs-- if ( defined($Jobs{$bpc->trashJob} ) );
558 if ( $nJobs < $Conf{MaxBackups} + $Conf{MaxUserBackups}
559 && @UserQueue > 0 ) {
560 $req = pop(@UserQueue);
561 if ( defined($Jobs{$req->{host}}) ) {
562 push(@deferUserQueue, $req);
565 push(@args, $req->{doFull} ? "-f" : "-i")
566 if (( !$req->{restore} ) && ( !$req->{archive} ));
567 $UserQueueOn{$req->{host}} = 0;
568 } elsif ( $nJobs < $Conf{MaxBackups}
569 && (@CmdQueue + $nJobs)
570 <= $Conf{MaxBackups} + $Conf{MaxPendingCmds}
573 if ( time - $Info{DUlastValueTime} >= 60 ) {
575 # Update our notion of disk usage no more than
578 $du = $bpc->CheckFileSystemUsage($TopDir);
579 $Info{DUlastValue} = $du;
580 $Info{DUlastValueTime} = time;
583 # if we recently checked it then just use the old value
585 $du = $Info{DUlastValue};
587 if ( $Info{DUDailyMaxReset} ) {
588 $Info{DUDailyMaxStartTime} = time;
589 $Info{DUDailyMaxReset} = 0;
590 $Info{DUDailyMax} = 0;
592 if ( $du > $Info{DUDailyMax} ) {
593 $Info{DUDailyMax} = $du;
594 $Info{DUDailyMaxTime} = time;
596 if ( $du > $Conf{DfMaxUsagePct} ) {
597 my $nSkip = @BgQueue + @deferBgQueue;
598 print(LOG $bpc->timeStamp,
599 "Disk too full ($du%%); skipping $nSkip hosts\n");
600 $Info{DUDailySkipHostCnt} += $nSkip;
606 $req = pop(@BgQueue);
607 if ( defined($Jobs{$req->{host}}) ) {
608 push(@deferBgQueue, $req);
611 $BgQueueOn{$req->{host}} = 0;
613 while ( @deferBgQueue ) {
614 push(@BgQueue, pop(@deferBgQueue));
616 while ( @deferUserQueue ) {
617 push(@UserQueue, pop(@deferUserQueue));
621 $host = $req->{host};
622 my $user = $req->{user};
623 if ( $req->{restore} ) {
624 $progName = "BackupPC_restore";
626 push(@args, $req->{hostIP}, $req->{host}, $req->{reqFileName});
627 } elsif ( $req->{archive} ) {
628 $progName = "BackupPC_archive";
630 push(@args, $req->{user}, $req->{host}, $req->{reqFileName});
632 $progName = "BackupPC_dump";
634 push(@args, "-d") if ( $req->{dhcp} );
635 push(@args, "-e") if ( $req->{dumpExpire} );
638 my $pid = open(FH, "-|");
639 if ( !defined($pid) ) {
640 print(LOG $bpc->timeStamp,
641 "can't fork to run $progName for $host, request by $user\n");
647 exec("$BinDir/$progName", @args);
648 print(LOG $bpc->timeStamp, "can't exec $progName for $host\n");
651 $Jobs{$host}{pid} = $pid;
652 $Jobs{$host}{fh} = *FH;
653 $Jobs{$host}{fn} = fileno(FH);
654 $Jobs{$host}{dhcp} = $req->{dhcp};
655 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
656 $Jobs{$host}{startTime} = time;
657 $Jobs{$host}{reqTime} = $req->{reqTime};
658 $Jobs{$host}{userReq} = $req->{userReq};
659 $Jobs{$host}{cmd} = $bpc->execCmd2ShellCmd($progName, @args);
660 $Jobs{$host}{user} = $user;
661 $Jobs{$host}{type} = $type;
662 $Status{$host}{userReq} = $req->{userReq}
663 if ( defined($Hosts->{$host}) );
664 if ( !$req->{dhcp} ) {
665 $Status{$host}{state} = "Status_".$type."_starting";
666 $Status{$host}{activeJob} = 1;
667 $Status{$host}{startTime} = time;
668 $Status{$host}{endTime} = "";
673 ############################################################################
676 # If necessary, figure out when to next wakeup based on $Conf{WakeupSchedule},
677 # and then do a select() to wait for the next thing to happen
678 # (timeout, signal, someone sends a message, child dies etc).
679 ############################################################################
682 if ( $NextWakeup <= 0 ) {
684 # Figure out when to next wakeup based on $Conf{WakeupSchedule}.
686 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
688 my($currHours) = $hour + $min / 60 + $sec / 3600;
689 if ( $bpc->ConfigMTime() != $Info{ConfigModTime} ) {
690 ServerReload("Re-read config file because mtime changed");
693 foreach my $t ( @{$Conf{WakeupSchedule} || [0..23]} ) {
694 next if ( $t < 0 || $t > 24 );
695 my $tomorrow = $t + 24;
697 || ($tomorrow - $currHours > 0
698 && $delta > $tomorrow - $currHours) ) {
699 $delta = $tomorrow - $currHours;
700 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
703 || ($t - $currHours > 0 && $delta > $t - $currHours) ) {
704 $delta = $t - $currHours;
705 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
708 $NextWakeup = time + $delta * 3600;
709 $Info{nextWakeup} = $NextWakeup;
710 print(LOG $bpc->timeStamp, "Next wakeup is ",
711 $bpc->timeStamp($NextWakeup, 1), "\n");
714 # Call select(), waiting until either a signal, a timeout,
715 # any output from our jobs, or any messages from clients
717 # select() is where we (hopefully) spend most of our time blocked...
719 my $timeout = $NextWakeup - time;
720 $timeout = 1 if ( $timeout <= 0 );
722 select(my $rout = $FDread, undef, $ein, $timeout);
727 ############################################################################
728 # Main_Process_Signal()
731 ############################################################################
732 sub Main_Process_Signal
737 if ( $SigName eq "HUP" ) {
738 ServerReload("Re-read config file because of a SIG_HUP");
739 } elsif ( $SigName ) {
740 ServerShutdown("Got signal $SigName... cleaning up");
745 ############################################################################
746 # Main_Check_Timeout()
748 # Check if a timeout has occured, and if so, queue all the PCs for backups.
749 # Also does log file aging on the first timeout after midnight.
750 ############################################################################
751 sub Main_Check_Timeout
756 return if ( time < $NextWakeup || $NextWakeup <= 0 );
758 if ( $FirstWakeup ) {
760 # This is the first wakeup after midnight. Do log file aging
761 # and various house keeping.
764 printf(LOG "%s24hr disk usage: %d%% max, %d%% recent,"
765 . " %d skipped hosts\n",
766 $bpc->timeStamp, $Info{DUDailyMax}, $Info{DUlastValue},
767 $Info{DUDailySkipHostCnt});
768 $Info{DUDailyMaxReset} = 1;
769 $Info{DUDailyMaxPrev} = $Info{DUDailyMax};
770 $Info{DUDailySkipHostCntPrev} = $Info{DUDailySkipHostCnt};
771 $Info{DUDailySkipHostCnt} = 0;
772 my $lastLog = $Conf{MaxOldLogFiles} - 1;
773 if ( -f "$TopDir/log/LOG.$lastLog" ) {
774 print(LOG $bpc->timeStamp,
775 "Removing $TopDir/log/LOG.$lastLog\n");
776 unlink("$TopDir/log/LOG.$lastLog");
778 if ( -f "$TopDir/log/LOG.$lastLog.z" ) {
779 print(LOG $bpc->timeStamp,
780 "Removing $TopDir/log/LOG.$lastLog.z\n");
781 unlink("$TopDir/log/LOG.$lastLog.z");
783 print(LOG $bpc->timeStamp, "Aging LOG files, LOG -> LOG.0 -> "
784 . "LOG.1 -> ... -> LOG.$lastLog\n");
786 for ( my $i = $lastLog - 1 ; $i >= 0 ; $i-- ) {
788 rename("$TopDir/log/LOG.$i", "$TopDir/log/LOG.$j")
789 if ( -f "$TopDir/log/LOG.$i" );
790 rename("$TopDir/log/LOG.$i.z", "$TopDir/log/LOG.$j.z")
791 if ( -f "$TopDir/log/LOG.$i.z" );
794 # Compress the log file LOG -> LOG.0.z (if enabled).
795 # Otherwise, just rename LOG -> LOG.0.
797 BackupPC::FileZIO->compressCopy("$TopDir/log/LOG",
798 "$TopDir/log/LOG.0.z",
800 $Conf{CompressLevel}, 1);
803 # Remember to run nightly script after current jobs are done
805 $RunNightlyWhenIdle = 1;
808 # Write out the current status and then queue all the PCs
812 %BgQueueOn = () if ( @BgQueue == 0 );
813 %UserQueueOn = () if ( @UserQueue == 0 );
814 %CmdQueueOn = () if ( @CmdQueue == 0 );
818 ############################################################################
819 # Main_Check_Job_Messages($fdRead)
821 # Check if select() says we have bytes waiting from any of our jobs.
822 # Handle each of the messages when complete (newline terminated).
823 ############################################################################
824 sub Main_Check_Job_Messages
827 foreach my $host ( keys(%Jobs) ) {
828 next if ( !vec($fdRead, $Jobs{$host}{fn}, 1) );
831 # do a last check to make sure there is something to read so
832 # we are absolutely sure we won't block.
834 vec(my $readMask, $Jobs{$host}{fn}, 1) = 1;
835 if ( !select($readMask, undef, undef, 0.0) ) {
836 print(LOG $bpc->timeStamp, "Botch in Main_Check_Job_Messages:"
837 . " nothing to read from $host. Debug dump:\n");
838 my($dump) = Data::Dumper->new(
839 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
840 [qw(*Clients, *Jobs *FDread, *fdRead)]);
842 print(LOG $dump->Dump);
845 my $nbytes = sysread($Jobs{$host}{fh}, $mesg, 1024);
846 $Jobs{$host}{mesg} .= $mesg if ( $nbytes > 0 );
848 # Process any complete lines of output from this jobs.
849 # Any output to STDOUT or STDERR from the children is processed here.
851 while ( $Jobs{$host}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
853 $Jobs{$host}{mesg} = $2;
854 if ( $Jobs{$host}{dhcp} ) {
855 if ( $mesg =~ /^DHCP (\S+) (\S+)/ ) {
856 my $newHost = $bpc->uriUnesc($2);
857 if ( defined($Jobs{$newHost}) ) {
858 print(LOG $bpc->timeStamp,
859 "Backup on $newHost is already running\n");
860 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
864 $Jobs{$host}{dhcpHostIP} = $host;
865 $Status{$newHost}{dhcpHostIP} = $host;
866 $Jobs{$newHost} = $Jobs{$host};
867 delete($Jobs{$host});
869 $Status{$host}{state} = "Status_backup_starting";
870 $Status{$host}{activeJob} = 1;
871 $Status{$host}{startTime} = $Jobs{$host}{startTime};
872 $Status{$host}{endTime} = "";
873 $Jobs{$host}{dhcp} = 0;
875 print(LOG $bpc->timeStamp, "dhcp $host: $mesg\n");
877 } elsif ( $mesg =~ /^started (.*) dump, share=(.*)/ ) {
878 $Jobs{$host}{type} = $1;
879 $Jobs{$host}{shareName} = $2;
880 print(LOG $bpc->timeStamp,
881 "Started $1 backup on $host (pid=$Jobs{$host}{pid}",
882 $Jobs{$host}{dhcpHostIP}
883 ? ", dhcp=$Jobs{$host}{dhcpHostIP}" : "",
884 ", share=$Jobs{$host}{shareName})\n");
885 $Status{$host}{state} = "Status_backup_in_progress";
886 $Status{$host}{reason} = "";
887 $Status{$host}{type} = $1;
888 $Status{$host}{startTime} = time;
889 $Status{$host}{deadCnt} = 0;
890 $Status{$host}{aliveCnt}++;
891 $Status{$host}{dhcpCheckCnt}--
892 if ( $Status{$host}{dhcpCheckCnt} > 0 );
893 } elsif ( $mesg =~ /^xferPids (.*)/ ) {
894 $Jobs{$host}{xferPid} = $1;
895 } elsif ( $mesg =~ /^started_restore/ ) {
896 $Jobs{$host}{type} = "restore";
897 print(LOG $bpc->timeStamp,
898 "Started restore on $host"
899 . " (pid=$Jobs{$host}{pid})\n");
900 $Status{$host}{state} = "Status_restore_in_progress";
901 $Status{$host}{reason} = "";
902 $Status{$host}{type} = "restore";
903 $Status{$host}{startTime} = time;
904 $Status{$host}{deadCnt} = 0;
905 $Status{$host}{aliveCnt}++;
906 } elsif ( $mesg =~ /^started_archive/ ) {
907 $Jobs{$host}{type} = "archive";
908 print(LOG $bpc->timeStamp,
909 "Started archive on $host"
910 . " (pid=$Jobs{$host}{pid})\n");
911 $Status{$host}{state} = "Status_archive_in_progress";
912 $Status{$host}{reason} = "";
913 $Status{$host}{type} = "archive";
914 $Status{$host}{startTime} = time;
915 $Status{$host}{deadCnt} = 0;
916 $Status{$host}{aliveCnt}++;
917 } elsif ( $mesg =~ /^(full|incr) backup complete/ ) {
918 print(LOG $bpc->timeStamp, "Finished $1 backup on $host\n");
919 $Status{$host}{reason} = "Reason_backup_done";
920 delete($Status{$host}{error});
921 delete($Status{$host}{errorTime});
922 $Status{$host}{endTime} = time;
923 } elsif ( $mesg =~ /^backups disabled/ ) {
924 print(LOG $bpc->timeStamp,
925 "Ignoring old backup error on $host\n");
926 $Status{$host}{reason} = "Reason_backup_done";
927 delete($Status{$host}{error});
928 delete($Status{$host}{errorTime});
929 $Status{$host}{endTime} = time;
930 } elsif ( $mesg =~ /^restore complete/ ) {
931 print(LOG $bpc->timeStamp, "Finished restore on $host\n");
932 $Status{$host}{reason} = "Reason_restore_done";
933 delete($Status{$host}{error});
934 delete($Status{$host}{errorTime});
935 $Status{$host}{endTime} = time;
936 } elsif ( $mesg =~ /^archive complete/ ) {
937 print(LOG $bpc->timeStamp, "Finished archive on $host\n");
938 $Status{$host}{reason} = "Reason_archive_done";
939 delete($Status{$host}{error});
940 delete($Status{$host}{errorTime});
941 $Status{$host}{endTime} = time;
942 } elsif ( $mesg =~ /^nothing to do/ ) {
943 if ( $Status{$host}{reason} ne "Reason_backup_failed"
944 && $Status{$host}{reason} ne "Reason_restore_failed" ) {
945 $Status{$host}{state} = "Status_idle";
946 $Status{$host}{reason} = "Reason_nothing_to_do";
947 $Status{$host}{startTime} = time;
949 $Status{$host}{dhcpCheckCnt}--
950 if ( $Status{$host}{dhcpCheckCnt} > 0 );
951 } elsif ( $mesg =~ /^no ping response/
952 || $mesg =~ /^ping too slow/
953 || $mesg =~ /^host not found/ ) {
954 $Status{$host}{state} = "Status_idle";
955 if ( $Status{$host}{userReq}
956 || $Status{$host}{reason} ne "Reason_backup_failed"
957 || $Status{$host}{error} =~ /^aborted by user/ ) {
958 $Status{$host}{reason} = "Reason_no_ping";
959 $Status{$host}{error} = $mesg;
960 $Status{$host}{startTime} = time;
962 $Status{$host}{deadCnt}++;
963 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
964 $Status{$host}{aliveCnt} = 0;
966 } elsif ( $mesg =~ /^dump failed: (.*)/ ) {
967 $Status{$host}{state} = "Status_idle";
968 $Status{$host}{error} = $1;
969 $Status{$host}{errorTime} = time;
970 $Status{$host}{endTime} = time;
971 if ( $Status{$host}{reason}
972 eq "Reason_backup_canceled_by_user" ) {
973 print(LOG $bpc->timeStamp,
974 "Backup canceled on $host ($1)\n");
976 $Status{$host}{reason} = "Reason_backup_failed";
977 print(LOG $bpc->timeStamp,
978 "Backup failed on $host ($1)\n");
980 } elsif ( $mesg =~ /^restore failed: (.*)/ ) {
981 $Status{$host}{state} = "Status_idle";
982 $Status{$host}{error} = $1;
983 $Status{$host}{errorTime} = time;
984 $Status{$host}{endTime} = time;
985 if ( $Status{$host}{reason}
986 eq "Reason_restore_canceled_by_user" ) {
987 print(LOG $bpc->timeStamp,
988 "Restore canceled on $host ($1)\n");
990 $Status{$host}{reason} = "Reason_restore_failed";
991 print(LOG $bpc->timeStamp,
992 "Restore failed on $host ($1)\n");
994 } elsif ( $mesg =~ /^archive failed: (.*)/ ) {
995 $Status{$host}{state} = "Status_idle";
996 $Status{$host}{error} = $1;
997 $Status{$host}{errorTime} = time;
998 $Status{$host}{endTime} = time;
999 if ( $Status{$host}{reason}
1000 eq "Reason_archive_canceled_by_user" ) {
1001 print(LOG $bpc->timeStamp,
1002 "Archive canceled on $host ($1)\n");
1004 $Status{$host}{reason} = "Reason_archive_failed";
1005 print(LOG $bpc->timeStamp,
1006 "Archive failed on $host ($1)\n");
1008 } elsif ( $mesg =~ /^log\s+(.*)/ ) {
1009 print(LOG $bpc->timeStamp, "$1\n");
1010 } elsif ( $mesg =~ /^BackupPC_stats (\d+) = (.*)/ ) {
1011 my $chunk = int($1 / 16);
1012 my @f = split(/,/, $2);
1013 $Info{pool}{$f[0]}[$chunk]{FileCnt} += $f[1];
1014 $Info{pool}{$f[0]}[$chunk]{DirCnt} += $f[2];
1015 $Info{pool}{$f[0]}[$chunk]{Kb} += $f[3];
1016 $Info{pool}{$f[0]}[$chunk]{Kb2} += $f[4];
1017 $Info{pool}{$f[0]}[$chunk]{KbRm} += $f[5];
1018 $Info{pool}{$f[0]}[$chunk]{FileCntRm} += $f[6];
1019 $Info{pool}{$f[0]}[$chunk]{FileCntRep} += $f[7];
1020 $Info{pool}{$f[0]}[$chunk]{FileRepMax} = $f[8]
1021 if ( $Info{pool}{$f[0]}[$chunk]{FileRepMax} < $f[8] );
1022 $Info{pool}{$f[0]}[$chunk]{FileCntRename} += $f[9];
1023 $Info{pool}{$f[0]}[$chunk]{FileLinkMax} = $f[10]
1024 if ( $Info{pool}{$f[0]}[$chunk]{FileLinkMax} < $f[10] );
1025 $Info{pool}{$f[0]}[$chunk]{Time} = time;
1026 } elsif ( $mesg =~ /^BackupPC_nightly lock_off/ ) {
1027 $BackupPCNightlyLock--;
1028 if ( $BackupPCNightlyLock == 0 ) {
1030 # This means the last BackupPC_nightly is done with
1031 # the pool clean, so it's to start running regular
1034 $RunNightlyWhenIdle = 0;
1036 } elsif ( $mesg =~ /^processState\s+(.+)/ ) {
1037 $Jobs{$host}{processState} = $1;
1038 } elsif ( $mesg =~ /^link\s+(.+)/ ) {
1040 $Status{$h}{needLink} = 1;
1042 print(LOG $bpc->timeStamp, "$host: $mesg\n");
1046 # shut down the client connection if we read EOF
1048 if ( $nbytes <= 0 ) {
1049 close($Jobs{$host}{fh});
1050 vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1051 if ( $CmdJob eq $host || $bpc->isAdminJob($host) ) {
1052 my $cmd = $Jobs{$host}{cmd};
1053 $cmd =~ s/$BinDir\///g;
1054 print(LOG $bpc->timeStamp, "Finished $host ($cmd)\n");
1055 $Status{$host}{state} = "Status_idle";
1056 $Status{$host}{endTime} = time;
1057 if ( $cmd =~ /^BackupPC_nightly\s/ ) {
1058 $BackupPCNightlyJobs--;
1059 #print(LOG $bpc->timeStamp, "BackupPC_nightly done; now"
1060 # . " have $BackupPCNightlyJobs running\n");
1061 if ( $BackupPCNightlyJobs <= 0 ) {
1062 $BackupPCNightlyJobs = 0;
1063 $RunNightlyWhenIdle = 0;
1066 # Combine the 16 per-directory results
1068 for my $p ( qw(pool cpool) ) {
1069 $Info{"${p}FileCnt"} = 0;
1070 $Info{"${p}DirCnt"} = 0;
1071 $Info{"${p}Kb"} = 0;
1072 $Info{"${p}Kb2"} = 0;
1073 $Info{"${p}KbRm"} = 0;
1074 $Info{"${p}FileCntRm"} = 0;
1075 $Info{"${p}FileCntRep"} = 0;
1076 $Info{"${p}FileRepMax"} = 0;
1077 $Info{"${p}FileCntRename"} = 0;
1078 $Info{"${p}FileLinkMax"} = 0;
1079 $Info{"${p}Time"} = 0;
1080 for ( my $i = 0 ; $i < 16 ; $i++ ) {
1081 $Info{"${p}FileCnt"}
1082 += $Info{pool}{$p}[$i]{FileCnt};
1084 += $Info{pool}{$p}[$i]{DirCnt};
1086 += $Info{pool}{$p}[$i]{Kb};
1088 += $Info{pool}{$p}[$i]{Kb2};
1090 += $Info{pool}{$p}[$i]{KbRm};
1091 $Info{"${p}FileCntRm"}
1092 += $Info{pool}{$p}[$i]{FileCntRm};
1093 $Info{"${p}FileCntRep"}
1094 += $Info{pool}{$p}[$i]{FileCntRep};
1095 $Info{"${p}FileRepMax"}
1096 = $Info{pool}{$p}[$i]{FileRepMax}
1097 if ( $Info{"${p}FileRepMax"} <
1098 $Info{pool}{$p}[$i]{FileRepMax} );
1099 $Info{"${p}FileCntRename"}
1100 += $Info{pool}{$p}[$i]{FileCntRename};
1101 $Info{"${p}FileLinkMax"}
1102 = $Info{pool}{$p}[$i]{FileLinkMax}
1103 if ( $Info{"${p}FileLinkMax"} <
1104 $Info{pool}{$p}[$i]{FileLinkMax} );
1105 $Info{"${p}Time"} = $Info{pool}{$p}[$i]{Time}
1106 if ( $Info{"${p}Time"} <
1107 $Info{pool}{$p}[$i]{Time} );
1109 printf(LOG "%s%s nightly clean removed %d files of"
1111 $bpc->timeStamp, ucfirst($p),
1112 $Info{"${p}FileCntRm"},
1113 $Info{"${p}KbRm"} / (1000 * 1024));
1114 printf(LOG "%s%s is %.2fGB, %d files (%d repeated, "
1115 . "%d max chain, %d max links), %d directories\n",
1116 $bpc->timeStamp, ucfirst($p),
1117 $Info{"${p}Kb"} / (1000 * 1024),
1118 $Info{"${p}FileCnt"}, $Info{"${p}FileCntRep"},
1119 $Info{"${p}FileRepMax"},
1120 $Info{"${p}FileLinkMax"}, $Info{"${p}DirCnt"});
1128 # Queue BackupPC_link to complete the backup
1129 # processing for this host.
1131 if ( defined($Status{$host})
1132 && ($Status{$host}{reason} eq "Reason_backup_done"
1133 || $Status{$host}{needLink}) ) {
1135 } elsif ( defined($Status{$host}) ) {
1136 $Status{$host}{state} = "Status_idle";
1139 delete($Jobs{$host});
1140 $Status{$host}{activeJob} = 0 if ( defined($Status{$host}) );
1144 # When we are idle (empty Jobs, CmdQueue, BgQueue, UserQueue) we
1145 # do a pass over %Status updating the deadCnt and aliveCnt for
1146 # DHCP hosts. The reason we need to do this later is we can't
1147 # be sure whether a DHCP host is alive or dead until we have passed
1148 # over all the DHCP pool.
1150 return if ( @CmdQueue || @BgQueue || @UserQueue || keys(%Jobs) > 1 );
1151 foreach my $host ( keys(%Status) ) {
1152 next if ( $Status{$host}{dhcpCheckCnt} <= 0 );
1153 $Status{$host}{deadCnt} += $Status{$host}{dhcpCheckCnt};
1154 $Status{$host}{dhcpCheckCnt} = 0;
1155 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1156 $Status{$host}{aliveCnt} = 0;
1161 ############################################################################
1162 # Main_Check_Client_Messages($fdRead)
1164 # Check for, and process, any output from our clients. Also checks
1165 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
1166 ############################################################################
1167 sub Main_Check_Client_Messages
1170 foreach my $client ( keys(%Clients) ) {
1171 next if ( !vec($fdRead, $Clients{$client}{fn}, 1) );
1174 # do a last check to make sure there is something to read so
1175 # we are absolutely sure we won't block.
1177 vec(my $readMask, $Clients{$client}{fn}, 1) = 1;
1178 if ( !select($readMask, undef, undef, 0.0) ) {
1179 print(LOG $bpc->timeStamp, "Botch in Main_Check_Client_Messages:"
1180 . " nothing to read from $client. Debug dump:\n");
1181 my($dump) = Data::Dumper->new(
1182 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
1183 [qw(*Clients, *Jobs *FDread, *fdRead)]);
1185 print(LOG $dump->Dump);
1188 my $nbytes = sysread($Clients{$client}{fh}, $mesg, 1024);
1189 $Clients{$client}{mesg} .= $mesg if ( $nbytes > 0 );
1191 # Process any complete lines received from this client.
1193 while ( $Clients{$client}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
1196 $Clients{$client}{mesg} = $2;
1198 # Authenticate the message by checking the MD5 digest
1200 my $md5 = Digest::MD5->new;
1201 if ( $cmd !~ /^(.{22}) (.*)/
1202 || ($md5->add($Clients{$client}{seed}
1203 . $Clients{$client}{mesgCnt}
1204 . $Conf{ServerMesgSecret} . $2),
1205 $md5->b64digest ne $1) ) {
1206 print(LOG $bpc->timeStamp, "Corrupted message '$cmd' from"
1207 . " client '$Clients{$client}{clientName}':"
1208 . " shutting down client connection\n");
1212 $Clients{$client}{mesgCnt}++;
1214 if ( $cmd =~ /^stop (\S+)\s+(\S+)\s+(\S*)/ ) {
1218 $host = $bpc->uriUnesc($host);
1219 if ( $CmdJob ne $host && defined($Status{$host})
1220 && defined($Jobs{$host}) ) {
1221 print(LOG $bpc->timeStamp,
1222 "Stopping current $Jobs{$host}{type} of $host,"
1223 . " request by $user (backoff=$backoff)\n");
1224 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1226 # Don't close the pipe now; wait until the child
1227 # really exits later. Otherwise close() will
1228 # block until the child has exited.
1230 ##vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1231 ##close($Jobs{$host}{fh});
1232 ##delete($Jobs{$host});
1234 $Status{$host}{state} = "Status_idle";
1235 if ( $Jobs{$host}{type} eq "restore" ) {
1236 $Status{$host}{reason}
1237 = "Reason_restore_canceled_by_user";
1238 } elsif ( $Jobs{$host}{type} eq "archive" ) {
1239 $Status{$host}{reason}
1240 = "Reason_archive_canceled_by_user";
1242 $Status{$host}{reason}
1243 = "Reason_backup_canceled_by_user";
1245 $Status{$host}{activeJob} = 0;
1246 $Status{$host}{startTime} = time;
1247 $reply = "ok: $Jobs{$host}{type} of $host canceled";
1248 } elsif ( $BgQueueOn{$host} || $UserQueueOn{$host} ) {
1249 print(LOG $bpc->timeStamp,
1250 "Stopping pending backup of $host,"
1251 . " request by $user (backoff=$backoff)\n");
1252 @BgQueue = grep($_->{host} ne $host, @BgQueue);
1253 @UserQueue = grep($_->{host} ne $host, @UserQueue);
1254 $BgQueueOn{$host} = $UserQueueOn{$host} = 0;
1255 $reply = "ok: pending backup of $host canceled";
1257 print(LOG $bpc->timeStamp,
1258 "Nothing to do for stop backup of $host,"
1259 . " request by $user (backoff=$backoff)\n");
1260 $reply = "ok: no backup was pending or running";
1262 if ( defined($Status{$host}) && $backoff ne "" ) {
1263 if ( $backoff > 0 ) {
1264 $Status{$host}{backoffTime} = time + $backoff * 3600;
1266 delete($Status{$host}{backoffTime});
1269 } elsif ( $cmd =~ /^backup all$/ ) {
1271 } elsif ( $cmd =~ /^BackupPC_nightly run$/ ) {
1272 $RunNightlyWhenIdle = 1;
1273 } elsif ( $cmd =~ /^backup (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1278 $host = $bpc->uriUnesc($host);
1279 $hostIP = $bpc->uriUnesc($hostIP);
1280 if ( !defined($Status{$host}) ) {
1281 print(LOG $bpc->timeStamp,
1282 "User $user requested backup of unknown host"
1284 $reply = "error: unknown host $host";
1285 } elsif ( defined($Jobs{$host})
1286 && $Jobs{$host}{type} ne "restore" ) {
1287 print(LOG $bpc->timeStamp,
1288 "User $user requested backup of $host,"
1289 . " but one is currently running\n");
1290 $reply = "error: backup of $host is already running";
1292 print(LOG $bpc->timeStamp,
1293 "User $user requested backup of $host"
1295 if ( $BgQueueOn{$hostIP} ) {
1296 @BgQueue = grep($_->{host} ne $hostIP, @BgQueue);
1297 $BgQueueOn{$hostIP} = 0;
1299 if ( $UserQueueOn{$hostIP} ) {
1300 @UserQueue = grep($_->{host} ne $hostIP, @UserQueue);
1301 $UserQueueOn{$hostIP} = 0;
1303 unshift(@UserQueue, {
1309 dhcp => $hostIP eq $host ? 0 : 1,
1311 $UserQueueOn{$hostIP} = 1;
1312 $reply = "ok: requested backup of $host";
1314 } elsif ( $cmd =~ /^archive (\S+)\s+(\S+)\s+(\S+)/ ) {
1316 my $archivehost = $2;
1317 my $reqFileName = $3;
1318 $host = $bpc->uriUnesc($archivehost);
1319 if ( !defined($Status{$host}) ) {
1320 print(LOG $bpc->timeStamp,
1321 "User $user requested archive of unknown archive host"
1323 $reply = "archive error: unknown archive host $host";
1325 print(LOG $bpc->timeStamp,
1326 "User $user requested archive on $host"
1328 if ( defined($Jobs{$host}) ) {
1329 $reply = "Archive currently running on $host, please try later";
1331 unshift(@UserQueue, {
1334 reqFileName => $reqFileName,
1340 $UserQueueOn{$host} = 1;
1341 $reply = "ok: requested archive on $host";
1344 } elsif ( $cmd =~ /^restore (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1348 my $reqFileName = $4;
1349 $host = $bpc->uriUnesc($host);
1350 $hostIP = $bpc->uriUnesc($hostIP);
1351 if ( !defined($Status{$host}) ) {
1352 print(LOG $bpc->timeStamp,
1353 "User $user requested restore to unknown host"
1355 $reply = "restore error: unknown host $host";
1357 print(LOG $bpc->timeStamp,
1358 "User $user requested restore to $host"
1360 unshift(@UserQueue, {
1363 reqFileName => $reqFileName,
1369 $UserQueueOn{$host} = 1;
1370 if ( defined($Jobs{$host}) ) {
1371 $reply = "ok: requested restore of $host, but a"
1372 . " job is currently running,"
1373 . " so this request will start later";
1375 $reply = "ok: requested restore of $host";
1378 } elsif ( $cmd =~ /^status\s*(.*)/ ) {
1380 my($dump, @values, @names);
1381 foreach my $type ( split(/\s+/, $args) ) {
1382 if ( $type =~ /^queues/ ) {
1383 push(@values, \@BgQueue, \@UserQueue, \@CmdQueue);
1384 push(@names, qw(*BgQueue *UserQueue *CmdQueue));
1385 } elsif ( $type =~ /^jobs/ ) {
1386 push(@values, \%Jobs);
1387 push(@names, qw(*Jobs));
1388 } elsif ( $type =~ /^queueLen/ ) {
1390 BgQueue => scalar(@BgQueue),
1391 UserQueue => scalar(@UserQueue),
1392 CmdQueue => scalar(@CmdQueue),
1394 push(@names, qw(*QueueLen));
1395 } elsif ( $type =~ /^info/ ) {
1396 push(@values, \%Info);
1397 push(@names, qw(*Info));
1398 } elsif ( $type =~ /^hosts/ ) {
1399 push(@values, \%Status);
1400 push(@names, qw(*Status));
1401 } elsif ( $type =~ /^host\((.*)\)/ ) {
1402 my $h = $bpc->uriUnesc($1);
1403 if ( defined($Status{$h}) ) {
1406 BgQueueOn => $BgQueueOn{$h},
1407 UserQueueOn => $UserQueueOn{$h},
1408 CmdQueueOn => $CmdQueueOn{$h},
1410 push(@names, qw(*StatusHost));
1412 print(LOG $bpc->timeStamp,
1413 "Unknown host $h for status request\n");
1416 print(LOG $bpc->timeStamp,
1417 "Unknown status request $type\n");
1420 $dump = Data::Dumper->new(\@values, \@names);
1422 $reply = $dump->Dump;
1423 } elsif ( $cmd =~ /^link\s+(.+)/ ) {
1425 $host = $bpc->uriUnesc($host);
1427 } elsif ( $cmd =~ /^log\s+(.*)/ ) {
1428 print(LOG $bpc->timeStamp, "$1\n");
1429 } elsif ( $cmd =~ /^server\s+(\w+)/ ) {
1431 if ( $type eq 'reload' ) {
1432 ServerReload("Reloading config/host files via CGI request");
1433 } elsif ( $type eq 'shutdown' ) {
1434 $reply = "Shutting down...\n";
1435 syswrite($Clients{$client}{fh}, $reply, length($reply));
1436 ServerShutdown("Server shutting down...");
1438 } elsif ( $cmd =~ /^quit/ || $cmd =~ /^exit/ ) {
1442 print(LOG $bpc->timeStamp, "Unknown command $cmd\n");
1443 $reply = "error: bad command $cmd";
1446 # send a reply to the client, at a minimum "ok\n".
1448 $reply = "ok" if ( $reply eq "" );
1450 syswrite($Clients{$client}{fh}, $reply, length($reply));
1453 # Detect possible denial-of-service attack from sending a huge line
1454 # (ie: never terminated). 32K seems to be plenty big enough as
1457 if ( length($Clients{$client}{mesg}) > 32 * 1024 ) {
1458 print(LOG $bpc->timeStamp, "Line too long from client"
1459 . " '$Clients{$client}{clientName}':"
1460 . " shutting down client connection\n");
1464 # Shut down the client connection if we read EOF
1466 if ( $nbytes <= 0 ) {
1467 close($Clients{$client}{fh});
1468 vec($FDread, $Clients{$client}{fn}, 1) = 0;
1469 delete($Clients{$client});
1473 # Accept any new connections on each of our listen sockets
1475 if ( vec($fdRead, fileno(SERVER_UNIX), 1) ) {
1477 my $paddr = accept(CLIENT, SERVER_UNIX);
1479 $Clients{$ClientConnCnt}{clientName} = "unix socket";
1480 $Clients{$ClientConnCnt}{mesg} = "";
1481 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1482 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1483 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1485 # Generate and send unique seed for MD5 digests to avoid
1486 # replay attacks. See BackupPC::Lib::ServerMesg().
1488 my $seed = time . ",$ClientConnCnt,$$,0\n";
1489 $Clients{$ClientConnCnt}{seed} = $seed;
1490 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1491 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1493 if ( $ServerInetPort > 0 && vec($fdRead, fileno(SERVER_INET), 1) ) {
1495 my $paddr = accept(CLIENT, SERVER_INET);
1496 my($port,$iaddr) = sockaddr_in($paddr);
1497 my $name = gethostbyaddr($iaddr, AF_INET);
1499 $Clients{$ClientConnCnt}{mesg} = "";
1500 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1501 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1502 $Clients{$ClientConnCnt}{clientName} = "$name:$port";
1503 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1505 # Generate and send unique seed for MD5 digests to avoid
1506 # replay attacks. See BackupPC::Lib::ServerMesg().
1508 my $seed = time . ",$ClientConnCnt,$$,$port\n";
1509 $Clients{$ClientConnCnt}{seed} = $seed;
1510 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1511 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1515 ###########################################################################
1516 # Miscellaneous subroutines
1517 ###########################################################################
1520 # Write the current status to $TopDir/log/status.pl
1524 my($dump) = Data::Dumper->new(
1525 [ \%Info, \%Status],
1526 [qw(*Info *Status)]);
1528 if ( open(STATUS, ">", "$TopDir/log/status.pl") ) {
1529 print(STATUS $dump->Dump);
1535 # Compare function for host sort. Hosts with errors go first,
1536 # sorted with the oldest errors first. The remaining hosts
1537 # are sorted so that those with the oldest backups go first.
1541 return -1 if ( $Status{$a}{error} ne "" && $Status{$b}{error} eq "" );
1542 return 1 if ( $Status{$a}{error} eq "" && $Status{$b}{error} ne "" );
1543 return $Status{$a}{endTime} <=> $Status{$b}{endTime};
1547 # Queue all the hosts for backup. This means queuing all the fixed
1548 # ip hosts and all the dhcp address ranges. We also additionally
1549 # queue the dhcp hosts with a -e flag to check for expired dumps.
1553 foreach my $host ( sort(HostSortCompare keys(%$Hosts)) ) {
1554 delete($Status{$host}{backoffTime})
1555 if ( defined($Status{$host}{backoffTime})
1556 && $Status{$host}{backoffTime} < time );
1557 next if ( defined($Jobs{$host})
1558 || $BgQueueOn{$host}
1559 || $UserQueueOn{$host}
1560 || $CmdQueueOn{$host} );
1561 if ( $Hosts->{$host}{dhcp} ) {
1562 $Status{$host}{dhcpCheckCnt}++;
1563 if ( $RunNightlyWhenIdle ) {
1565 # Once per night queue a check for DHCP hosts that just
1566 # checks for expired dumps. We need to do this to handle
1567 # the case when a DHCP host has not been on the network for
1568 # a long time, and some of the old dumps need to be expired.
1569 # Normally expiry checks are done by BackupPC_dump only
1570 # after the DHCP hosts has been detected on the network.
1573 {host => $host, user => "BackupPC", reqTime => time,
1574 dhcp => 0, dumpExpire => 1});
1575 $BgQueueOn{$host} = 1;
1579 # this is a fixed ip host: queue it
1582 {host => $host, user => "BackupPC", reqTime => time,
1583 dhcp => $Hosts->{$host}{dhcp}});
1584 $BgQueueOn{$host} = 1;
1587 foreach my $dhcp ( @{$Conf{DHCPAddressRanges}} ) {
1588 for ( my $i = $dhcp->{first} ; $i <= $dhcp->{last} ; $i++ ) {
1589 my $ipAddr = "$dhcp->{ipAddrBase}.$i";
1590 next if ( defined($Jobs{$ipAddr})
1591 || $BgQueueOn{$ipAddr}
1592 || $UserQueueOn{$ipAddr}
1593 || $CmdQueueOn{$ipAddr} );
1595 # this is a potential dhcp ip address (we don't know the
1596 # host name yet): queue it
1599 {host => $ipAddr, user => "BackupPC", reqTime => time,
1601 $BgQueueOn{$ipAddr} = 1;
1607 # Queue a BackupPC_link for the given host
1613 return if ( $CmdQueueOn{$host} );
1614 $Status{$host}{state} = "Status_link_pending";
1615 $Status{$host}{needLink} = 0;
1616 unshift(@CmdQueue, {
1620 cmd => ["$BinDir/BackupPC_link", $host],
1622 $CmdQueueOn{$host} = 1;
1626 # Read the hosts file, and update Status if any hosts have been
1627 # added or deleted. We also track the mtime so the only need to
1628 # update the hosts file on changes.
1630 # This function is called at startup, SIGHUP, and on each wakeup.
1631 # It returns 1 on success and undef on failure.
1638 # Nothing to do if we already have the current hosts file
1640 return 1 if ( !$force && defined($Hosts)
1641 && $Info{HostsModTime} == $bpc->HostsMTime() );
1642 if ( !defined($newHosts = $bpc->HostInfoRead()) ) {
1643 print(LOG $bpc->timeStamp, "Can't read hosts file!\n");
1646 print(LOG $bpc->timeStamp, "Reading hosts file\n");
1648 $Info{HostsModTime} = $bpc->HostsMTime();
1650 # Now update %Status in case any hosts have been added or deleted
1652 foreach my $host ( sort(keys(%$Hosts)) ) {
1653 next if ( defined($Status{$host}) );
1654 $Status{$host}{state} = "Status_idle";
1655 print(LOG $bpc->timeStamp, "Added host $host to backup list\n");
1657 foreach my $host ( sort(keys(%Status)) ) {
1658 next if ( $host eq $bpc->trashJob
1659 || $bpc->isAdminJob($host)
1660 || defined($Hosts->{$host})
1661 || defined($Jobs{$host})
1662 || $BgQueueOn{$host}
1663 || $UserQueueOn{$host}
1664 || $CmdQueueOn{$host} );
1665 print(LOG $bpc->timeStamp, "Deleted host $host from backup list\n");
1666 delete($Status{$host});
1672 # Remember the signal name for later processing
1678 foreach my $host ( keys(%Jobs) ) {
1679 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1682 # In case we are inside the exit handler, reopen the log file
1686 print(LOG "Fatal error: unhandled signal $SigName\n");
1687 unlink("$TopDir/log/BackupPC.pid");
1688 confess("Got new signal $SigName... quitting\n");
1695 # Open the log file and point STDOUT and STDERR there too
1699 mkpath("$TopDir/log", 0, 0777) if ( !-d "$TopDir/log" );
1700 open(LOG, ">>$TopDir/log/LOG")
1701 || die("Can't create LOG file $TopDir/log/LOG");
1704 open(STDOUT, ">&LOG");
1705 open(STDERR, ">&LOG");
1706 select(LOG); $| = 1;
1707 select(STDERR); $| = 1;
1708 select(STDOUT); $| = 1;
1712 # Initialize the unix-domain and internet-domain sockets that
1713 # we listen to for client connections (from the CGI script and
1714 # some of the BackupPC sub-programs).
1716 sub ServerSocketInit
1718 if ( !defined(fileno(SERVER_UNIX)) ) {
1720 # one-time only: initialize unix-domain socket
1722 if ( !socket(SERVER_UNIX, PF_UNIX, SOCK_STREAM, 0) ) {
1723 print(LOG $bpc->timeStamp, "unix socket() failed: $!\n");
1726 my $sockFile = "$TopDir/log/BackupPC.sock";
1728 if ( !bind(SERVER_UNIX, sockaddr_un($sockFile)) ) {
1729 print(LOG $bpc->timeStamp, "unix bind() failed: $!\n");
1732 if ( !listen(SERVER_UNIX, SOMAXCONN) ) {
1733 print(LOG $bpc->timeStamp, "unix listen() failed: $!\n");
1736 vec($FDread, fileno(SERVER_UNIX), 1) = 1;
1738 return if ( $ServerInetPort == $Conf{ServerPort} );
1739 if ( $ServerInetPort > 0 ) {
1740 vec($FDread, fileno(SERVER_INET), 1) = 0;
1742 $ServerInetPort = -1;
1744 if ( $Conf{ServerPort} > 0 ) {
1746 # Setup a socket to listen on $Conf{ServerPort}
1748 my $proto = getprotobyname('tcp');
1749 if ( !socket(SERVER_INET, PF_INET, SOCK_STREAM, $proto) ) {
1750 print(LOG $bpc->timeStamp, "inet socket() failed: $!\n");
1753 if ( !setsockopt(SERVER_INET, SOL_SOCKET, SO_REUSEADDR, pack("l",1)) ) {
1754 print(LOG $bpc->timeStamp, "setsockopt() failed: $!\n");
1757 if ( !bind(SERVER_INET, sockaddr_in($Conf{ServerPort}, INADDR_ANY)) ) {
1758 print(LOG $bpc->timeStamp, "inet bind() failed: $!\n");
1761 if ( !listen(SERVER_INET, SOMAXCONN) ) {
1762 print(LOG $bpc->timeStamp, "inet listen() failed: $!\n");
1765 vec($FDread, fileno(SERVER_INET), 1) = 1;
1766 $ServerInetPort = $Conf{ServerPort};
1771 # Reload the server. Used by Main_Process_Signal when $SigName eq "HUP"
1772 # or when the command "server reload" is received.
1777 $mesg = $bpc->ConfigRead() || $mesg;
1778 print(LOG $bpc->timeStamp, "$mesg\n");
1779 $Info{ConfigModTime} = $bpc->ConfigMTime();
1780 %Conf = $bpc->Conf();
1781 umask($Conf{UmaskMode});
1785 $Info{ConfigLTime} = time;
1789 # Gracefully shutdown the server. Used by Main_Process_Signal when
1790 # $SigName ne "" && $SigName ne "HUP" or when the command
1791 # "server shutdown" is received.
1796 print(LOG $bpc->timeStamp, "$mesg\n");
1797 if ( keys(%Jobs) ) {
1798 foreach my $host ( keys(%Jobs) ) {
1799 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1802 foreach my $host ( keys(%Jobs) ) {
1803 kill($bpc->sigName2num("KILL"), $Jobs{$host}{pid});
1808 unlink("$TopDir/log/BackupPC.pid");