2 #============================================================= -*-perl-*-
4 # BackupPC: Main program for PC backups.
8 # BackupPC reads the configuration and status information from
9 # $ConfDir/conf. It then runs and manages all the backup activity.
11 # As specified by $Conf{WakeupSchedule}, BackupPC wakes up periodically
12 # to queue backups on all the PCs. This is a four step process:
13 # 1) For each host and DHCP address backup requests are queued on the
14 # background command queue.
15 # 2) For each PC, BackupPC_dump is forked. Several of these may
16 # be run in parallel, based on the configuration.
17 # 3) For each complete, good, backup, BackupPC_link is forked.
18 # Only one of these tasks runs at a time.
19 # 4) In the background BackupPC_trashClean is run to remove any expired
20 # backups. Once each night, BackupPC_nightly is run to complete some
21 # additional administrative tasks (pool cleaning etc).
23 # BackupPC also listens for connections on a unix domain socket and
24 # the tcp port $Conf{ServerPort}, which are used by various
25 # sub-programs and the CGI script BackupPC_Admin for status reporting
26 # and user-initiated backup or backup cancel requests.
29 # Craig Barratt <cbarratt@users.sourceforge.net>
32 # Copyright (C) 2001-2009 Craig Barratt
34 # This program is free software; you can redistribute it and/or modify
35 # it under the terms of the GNU General Public License as published by
36 # the Free Software Foundation; either version 2 of the License, or
37 # (at your option) any later version.
39 # This program is distributed in the hope that it will be useful,
40 # but WITHOUT ANY WARRANTY; without even the implied warranty of
41 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
42 # GNU General Public License for more details.
44 # You should have received a copy of the GNU General Public License
45 # along with this program; if not, write to the Free Software
46 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
48 #========================================================================
50 # Version 3.2.0, released 31 Jul 2010.
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;
62 use Encode qw/decode_utf8/;
72 ###########################################################################
73 # Handle command line options
74 ###########################################################################
76 if ( !getopts("d", \%opts) || @ARGV != 0 ) {
77 print("usage: $0 [-d]\n");
81 ###########################################################################
82 # Initialize major data structures and variables
83 ###########################################################################
86 # Get an instance of BackupPC::Lib and get some shortcuts.
88 die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
89 my $TopDir = $bpc->TopDir();
90 my $BinDir = $bpc->BinDir();
91 my $LogDir = $bpc->LogDir();
92 my %Conf = $bpc->Conf();
95 # Verify we are running as the correct user
97 if ( $Conf{BackupPCUserVerify}
98 && $> != (my $uid = (getpwnam($Conf{BackupPCUser}))[2]) ) {
99 die "Wrong user: my userid is $>, instead of $uid ($Conf{BackupPCUser})\n";
103 # %Status maintain status information about each host.
104 # It is a hash of hashes, whose first index is the host.
109 # %Info is a hash giving general information about BackupPC status.
116 if ( -f "$LogDir/status.pl" && !(my $ret = do "$LogDir/status.pl") ) {
118 print STDERR "couldn't parse $LogDir/status.pl: $@";
119 } elsif ( !defined($ret) ) {
120 print STDERR "couldn't do $LogDir/status.pl: $!";
122 print STDERR "couldn't run $LogDir/status.pl";
127 # %Jobs maintains information about currently running jobs.
128 # It is a hash of hashes, whose first index is the host.
133 # There are three command queues:
134 # - @UserQueue is a queue of user initiated backup requests.
135 # - @BgQueue is a queue of automatically scheduled backup requests.
136 # - @CmdQueue is a queue of administrative jobs, including tasks
137 # like BackupPC_link, BackupPC_trashClean, and BackupPC_nightly
138 # Each queue is an array of hashes. Each hash stores information
139 # about the command request.
146 # To quickly lookup if a given host is on a given queue, we keep
147 # a hash of flags for each queue type.
149 my(%CmdQueueOn, %UserQueueOn, %BgQueueOn);
152 # One or more clients can connect to the server to get status information
153 # or request/cancel backups etc. The %Clients hash maintains information
154 # about each of these socket connections. The hash key is an incrementing
155 # number stored in $ClientConnCnt. Each entry is a hash that contains
156 # various information about the client connection.
162 # Read file descriptor mask used by select(). Every file descriptor
163 # on which we expect to read (or accept) has the corresponding bit
169 # Unix seconds when we next wakeup. A value of zero forces the scheduler
170 # to compute the next wakeup time.
175 # Name of signal saved by catch_signal
182 my($RunNightlyWhenIdle, $FirstWakeup, $CmdJob, $ServerInetPort);
183 my($BackupPCNightlyJobs, $BackupPCNightlyLock);
186 # Complete the rest of the initialization
190 ###########################################################################
192 ###########################################################################
196 # Check if we can/should run BackupPC_nightly
198 Main_TryToRun_nightly();
201 # Check if we can run a new command from @CmdQueue.
203 Main_TryToRun_CmdQueue();
206 # Check if we can run a new command from @UserQueue or @BgQueue.
208 Main_TryToRun_Bg_or_User_Queue();
211 # Do a select() to wait for the next interesting thing to happen
212 # (timeout, signal, someone sends a message, child dies etc).
214 my $fdRead = Main_Select();
217 # Process a signal if we received one.
220 Main_Process_Signal();
225 # Check if a timeout has occurred.
227 Main_Check_Timeout();
230 # Check for, and process, any messages (output) from our jobs
232 Main_Check_Job_Messages($fdRead);
235 # Check for, and process, any output from our clients. Also checks
236 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
238 Main_Check_Client_Messages($fdRead);
241 ############################################################################
244 # Main initialization routine. Called once at statup.
245 ############################################################################
248 umask($Conf{UmaskMode});
251 # Check for another running process, verify executables are configured
252 # correctly and make sure $TopDir is on a file system that supports
255 if ( $Info{pid} ne "" && kill(0, $Info{pid}) ) {
256 print(STDERR $bpc->timeStamp,
257 "Another BackupPC is running (pid $Info{pid}); quitting...\n");
261 foreach my $progName ( qw(SmbClientPath NmbLookupPath PingPath DfPath
262 SendmailPath SshPath) ) {
263 next if ( $Conf{$progName} eq "" || -x $Conf{$progName} );
264 print(STDERR $bpc->timeStamp,
265 "\$Conf{$progName} = '$Conf{$progName}' is not a"
266 . " valid executable program\n");
270 if ( !$bpc->HardlinkTest("$TopDir/pc", "$TopDir/cpool") ) {
271 print(STDERR $bpc->timeStamp, "Can't create a test hardlink between a file"
272 . " in $TopDir/pc and $TopDir/cpool. Either these are different"
273 . " file systems, or this file system doesn't support hardlinks,"
274 . " or these directories don't exist, or there is a permissions"
275 . " problem, or the file system is out of inodes or full. Use"
276 . " df, df -i, and ls -ld to check each of these possibilities."
283 # daemonize by forking; more robust method per:
284 # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=301057
287 defined($pid = fork) or die("Can't fork: $!");
288 exit if ( $pid ); # parent exits
291 defined($pid = fork) or die("Can't fork: $!");
292 exit if $pid; # parent exits
294 chdir ("/") or die("Cannot chdir to /: $!\n");
296 open(STDIN , ">/dev/null") or die("Cannot open /dev/null as stdin\n");
297 # STDOUT and STDERR are handled in LogFileOpen() right below,
298 # otherwise we would have to reopen them too.
302 # Open the LOG file and redirect STDOUT, STDERR etc
307 # Read the hosts file (force a read).
309 exit(1) if ( !HostsUpdate(1) );
312 # Clean up %ENV for taint checking
314 delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
315 $ENV{PATH} = $Conf{MyPath};
318 # Initialize server sockets
323 # Catch various signals
325 foreach my $sig ( qw(INT BUS SEGV PIPE TERM ALRM HUP) ) {
326 $SIG{$sig} = \&catch_signal;
330 # Report that we started, and update %Info.
332 print(LOG $bpc->timeStamp, "BackupPC started, pid $$\n");
333 $Info{ConfigModTime} = $bpc->ConfigMTime();
335 $Info{startTime} = time;
336 $Info{ConfigLTime} = time;
337 $Info{Version} = $bpc->{Version};
340 # Update the status left over form the last time BackupPC ran.
341 # Requeue any pending links.
343 foreach my $host ( sort(keys(%$Hosts)) ) {
344 if ( $Status{$host}{state} eq "Status_backup_in_progress" ) {
346 # should we restart it? skip it for now.
348 $Status{$host}{state} = "Status_idle";
349 } elsif ( $Status{$host}{state} eq "Status_link_pending"
350 || $Status{$host}{state} eq "Status_link_running" ) {
353 $Status{$host}{state} = "Status_idle";
355 $Status{$host}{activeJob} = 0;
357 foreach my $host ( sort(keys(%Status)) ) {
358 next if ( defined($Hosts->{$host}) );
359 delete($Status{$host});
363 # Write out our initial status and save our PID
366 unlink("$LogDir/BackupPC.pid");
367 if ( open(PID, ">", "$LogDir/BackupPC.pid") ) {
370 chmod(0444, "$LogDir/BackupPC.pid");
374 # For unknown reasons there is a very infrequent error about not
375 # being able to coerce GLOBs inside the XS Data::Dumper. I've
376 # only seen this on a particular platform and perl version.
377 # For now the workaround appears to be use the perl version of
380 $Data::Dumper::Useqq = 1;
383 ############################################################################
384 # Main_TryToRun_nightly()
386 # Checks to see if we can/should run BackupPC_nightly or
387 # BackupPC_trashClean. If so we push the appropriate command onto
389 ############################################################################
390 sub Main_TryToRun_nightly
393 # Check if we should run BackupPC_nightly or BackupPC_trashClean.
394 # BackupPC_nightly is run when the current job queue is empty.
395 # BackupPC_trashClean is run in the background always.
397 my $trashCleanRunning = defined($Jobs{$bpc->trashJob}) ? 1 : 0;
398 if ( !$trashCleanRunning && !$CmdQueueOn{$bpc->trashJob} ) {
400 # This should only happen once at startup, but just in case this
401 # code will re-start BackupPC_trashClean if it quits
404 host => $bpc->trashJob,
407 cmd => ["$BinDir/BackupPC_trashClean"],
409 $CmdQueueOn{$bpc->trashJob} = 1;
411 if ( $RunNightlyWhenIdle == 1 ) {
413 # Queue multiple nightly jobs based on the configuration
415 $Conf{MaxBackupPCNightlyJobs} = 1
416 if ( $Conf{MaxBackupPCNightlyJobs} <= 0 );
417 $Conf{BackupPCNightlyPeriod} = 1
418 if ( $Conf{BackupPCNightlyPeriod} <= 0 );
420 # Decide what subset of the 16 top-level directories 0..9a..f
421 # we run BackupPC_nightly on, based on $Conf{BackupPCNightlyPeriod}.
422 # If $Conf{BackupPCNightlyPeriod} == 1 then we run 0..15 every
423 # time. If $Conf{BackupPCNightlyPeriod} == 2 then we run
424 # 0..7 one night and 89a-f the next night. And so on.
426 # $Info{NightlyPhase} counts which night, from 0 to
427 # $Conf{BackupPCNightlyPeriod} - 1.
429 my $start = int($Info{NightlyPhase} * 16
430 / $Conf{BackupPCNightlyPeriod});
431 my $end = int(($Info{NightlyPhase} + 1) * 16
432 / $Conf{BackupPCNightlyPeriod});
433 $end = $start + 1 if ( $end <= $start );
434 $Info{NightlyPhase}++;
435 $Info{NightlyPhase} = 0 if ( $end >= 16 );
438 # Zero out the data we expect to get from BackupPC_nightly.
440 for my $p ( qw(pool cpool) ) {
441 for ( my $i = $start ; $i < $end ; $i++ ) {
442 $Info{pool}{$p}[$i]{FileCnt} = 0;
443 $Info{pool}{$p}[$i]{DirCnt} = 0;
444 $Info{pool}{$p}[$i]{Kb} = 0;
445 $Info{pool}{$p}[$i]{Kb2} = 0;
446 $Info{pool}{$p}[$i]{KbRm} = 0;
447 $Info{pool}{$p}[$i]{FileCntRm} = 0;
448 $Info{pool}{$p}[$i]{FileCntRep} = 0;
449 $Info{pool}{$p}[$i]{FileRepMax} = 0;
450 $Info{pool}{$p}[$i]{FileCntRename} = 0;
451 $Info{pool}{$p}[$i]{FileLinkMax} = 0;
452 $Info{pool}{$p}[$i]{Time} = 0;
455 print(LOG $bpc->timeStamp,
456 sprintf("Running %d BackupPC_nightly jobs from %d..%d"
457 . " (out of 0..15)\n",
458 $Conf{MaxBackupPCNightlyJobs}, $start, $end - 1));
461 # Now queue the $Conf{MaxBackupPCNightlyJobs} jobs.
462 # The granularity on start and end is now 0..255.
467 for ( my $i = 0 ; $i < $Conf{MaxBackupPCNightlyJobs} ; $i++ ) {
469 # The first nightly job gets the -m option (does email, log aging).
470 # All jobs get the start and end options from 0..255 telling
471 # them which parts of the pool to traverse.
473 my $cmd = ["$BinDir/BackupPC_nightly"];
474 push(@$cmd, "-m") if ( $i == 0 );
476 $start = $start0 + int(($end - $start0)
477 * ($i + 1) / $Conf{MaxBackupPCNightlyJobs});
478 push(@$cmd, $start - 1);
479 my $job = $bpc->adminJob($i);
486 $CmdQueueOn{$job} = 1;
488 $RunNightlyWhenIdle = 2;
492 ############################################################################
493 # Main_TryToRun_CmdQueue()
495 # Decide if we can run a new command from the @CmdQueue.
496 # We only run one of these at a time. The @CmdQueue is
497 # used to run BackupPC_link (for the corresponding host),
498 # BackupPC_trashClean, and BackupPC_nightly using a fake
499 # host name of $bpc->adminJob.
500 ############################################################################
501 sub Main_TryToRun_CmdQueue
505 while ( $CmdJob eq "" && @CmdQueue > 0 && $RunNightlyWhenIdle != 1
506 || @CmdQueue > 0 && $RunNightlyWhenIdle == 2
507 && $bpc->isAdminJob($CmdQueue[0]->{host})
510 $req = pop(@CmdQueue);
512 $host = $req->{host};
513 if ( defined($Jobs{$host}) ) {
514 print(LOG $bpc->timeStamp,
515 "Botch on admin job for $host: already in use!!\n");
517 # This could happen during normal opertion: a user could
518 # request a backup while a BackupPC_link is queued from
519 # a previous backup. But it is unlikely. Just put this
520 # request back on the end of the queue.
522 unshift(@CmdQueue, $req);
525 $CmdQueueOn{$host} = 0;
526 my $cmd = $req->{cmd};
527 my $pid = open(FH, "-|");
528 if ( !defined($pid) ) {
529 print(LOG $bpc->timeStamp,
530 "can't fork for $host, request by $req->{user}\n");
536 $ENV{BPC_REQUSER} = $req->{user};
537 POSIX::nice($Conf{CmdQueueNice}) if ( $Conf{CmdQueueNice} );
539 print(LOG $bpc->timeStamp, "can't exec @$cmd for $host\n");
542 $Jobs{$host}{pid} = $pid;
543 $Jobs{$host}{fh} = *FH;
544 $Jobs{$host}{fn} = fileno(FH);
545 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
546 $Jobs{$host}{startTime} = time;
547 $Jobs{$host}{reqTime} = $req->{reqTime};
548 $cmd = $bpc->execCmd2ShellCmd(@$cmd);
549 $Jobs{$host}{cmd} = $cmd;
550 $Jobs{$host}{user} = $req->{user};
551 $Jobs{$host}{type} = $Status{$host}{type};
552 $Status{$host}{state} = "Status_link_running";
553 $Status{$host}{activeJob} = 1;
554 $Status{$host}{endTime} = time;
555 $CmdJob = $host if ( $host ne $bpc->trashJob );
556 $cmd =~ s/$BinDir\///g;
557 print(LOG $bpc->timeStamp, "Running $cmd (pid=$pid)\n");
558 if ( $cmd =~ /^BackupPC_nightly\s/ ) {
559 $BackupPCNightlyJobs++;
560 $BackupPCNightlyLock++;
565 ############################################################################
566 # Main_TryToRun_Bg_or_User_Queue()
568 # Decide if we can run any new backup requests from @BgQueue
569 # or @UserQueue. Several of these can be run at the same time
570 # based on %Conf settings. Jobs from @UserQueue take priority,
571 # and at total of $Conf{MaxBackups} + $Conf{MaxUserBackups}
572 # simultaneous jobs can run from @UserQueue. After @UserQueue
573 # is exhausted, up to $Conf{MaxBackups} simultaneous jobs can
575 ############################################################################
576 sub Main_TryToRun_Bg_or_User_Queue
579 my(@deferUserQueue, @deferBgQueue);
582 if ( time - $Info{DUlastValueTime} >= 600 ) {
584 # Update our notion of disk usage no more than
585 # once every 10 minutes
587 $du = $bpc->CheckFileSystemUsage($TopDir);
588 $Info{DUlastValue} = $du;
589 $Info{DUlastValueTime} = time;
592 # if we recently checked it then just use the old value
594 $du = $Info{DUlastValue};
596 if ( $Info{DUDailyMaxReset} ) {
597 $Info{DUDailyMaxStartTime} = time;
598 $Info{DUDailyMaxReset} = 0;
599 $Info{DUDailyMax} = 0;
601 if ( $du > $Info{DUDailyMax} ) {
602 $Info{DUDailyMax} = $du;
603 $Info{DUDailyMaxTime} = time;
605 if ( $du > $Conf{DfMaxUsagePct} ) {
606 my @bgQueue = @BgQueue;
610 # When the disk is too full, only run backups that will
611 # do expires, not regular backups
614 foreach $req ( @bgQueue ) {
615 if ( $req->{dumpExpire} ) {
616 unshift(@BgQueue, $req);
618 $BgQueueOn{$req->{host}} = 0;
623 print(LOG $bpc->timeStamp,
624 "Disk too full ($du%); skipped $nSkip hosts\n");
625 $Info{DUDailySkipHostCnt} += $nSkip;
630 # Run background jobs anytime. Previously they were locked out
631 # when BackupPC_nightly was running or pending with this
632 # condition on the while loop:
634 # while ( $RunNightlyWhenIdle == 0 )
638 my(@args, $progName, $type);
639 my $nJobs = keys(%Jobs);
641 # CmdJob and trashClean don't count towards MaxBackups / MaxUserBackups
643 if ( $CmdJob ne "" ) {
644 if ( $BackupPCNightlyJobs ) {
645 $nJobs -= $BackupPCNightlyJobs;
650 $nJobs-- if ( defined($Jobs{$bpc->trashJob} ) );
651 if ( $nJobs < $Conf{MaxBackups} + $Conf{MaxUserBackups}
652 && @UserQueue > 0 ) {
653 $req = pop(@UserQueue);
654 if ( defined($Jobs{$req->{host}}) ) {
655 push(@deferUserQueue, $req);
658 $UserQueueOn{$req->{host}} = 0;
659 } elsif ( $nJobs < $Conf{MaxBackups}
660 && (@CmdQueue + $nJobs)
661 <= $Conf{MaxBackups} + $Conf{MaxPendingCmds}
663 $req = pop(@BgQueue);
664 if ( defined($Jobs{$req->{host}}) ) {
666 # Job is currently running for this host; save it for later
668 unshift(@deferBgQueue, $req);
671 $BgQueueOn{$req->{host}} = 0;
674 # Restore the deferred jobs
676 @BgQueue = (@BgQueue, @deferBgQueue);
677 @UserQueue = (@UserQueue, @deferUserQueue);
680 $host = $req->{host};
681 my $user = $req->{user};
682 if ( $req->{restore} ) {
683 $progName = "BackupPC_restore";
685 push(@args, $req->{hostIP}, $req->{host}, $req->{reqFileName});
686 } elsif ( $req->{archive} ) {
687 $progName = "BackupPC_archive";
689 push(@args, $req->{user}, $req->{host}, $req->{reqFileName});
691 $progName = "BackupPC_dump";
693 push(@args, "-I") if ( $req->{backupType} eq "autoIncr" );
694 push(@args, "-F") if ( $req->{backupType} eq "autoFull" );
695 push(@args, "-i") if ( $req->{backupType} eq "doIncr" );
696 push(@args, "-f") if ( $req->{backupType} eq "doFull" );
697 push(@args, "-d") if ( $req->{backupType} eq "dhcpPoll" );
698 push(@args, "-e") if ( $req->{dumpExpire} );
701 my $pid = open(FH, "-|");
702 if ( !defined($pid) ) {
703 print(LOG $bpc->timeStamp,
704 "can't fork to run $progName for $host, request by $user\n");
710 exec("$BinDir/$progName", @args);
711 print(LOG $bpc->timeStamp, "can't exec $progName for $host\n");
714 $Jobs{$host}{pid} = $pid;
715 $Jobs{$host}{fh} = *FH;
716 $Jobs{$host}{fn} = fileno(FH);
717 $Jobs{$host}{dhcp} = $req->{dhcp};
718 vec($FDread, $Jobs{$host}{fn}, 1) = 1;
719 $Jobs{$host}{startTime} = time;
720 $Jobs{$host}{reqTime} = $req->{reqTime};
721 $Jobs{$host}{userReq} = $req->{userReq};
722 $Jobs{$host}{cmd} = $bpc->execCmd2ShellCmd($progName, @args);
723 $Jobs{$host}{user} = $user;
724 $Jobs{$host}{type} = $type;
725 $Status{$host}{userReq} = $req->{userReq}
726 if ( defined($Hosts->{$host}) );
727 if ( !$req->{dhcp} ) {
728 $Status{$host}{state} = "Status_".$type."_starting";
729 $Status{$host}{activeJob} = 1;
730 $Status{$host}{startTime} = time;
731 $Status{$host}{endTime} = "";
736 ############################################################################
739 # If necessary, figure out when to next wakeup based on $Conf{WakeupSchedule},
740 # and then do a select() to wait for the next thing to happen
741 # (timeout, signal, someone sends a message, child dies etc).
742 ############################################################################
745 if ( $NextWakeup <= 0 ) {
747 # Figure out when to next wakeup based on $Conf{WakeupSchedule}.
749 my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
751 my($currHours) = $hour + $min / 60 + $sec / 3600;
752 if ( $bpc->ConfigMTime() != $Info{ConfigModTime} ) {
753 ServerReload("Re-read config file because mtime changed");
756 foreach my $t ( @{$Conf{WakeupSchedule} || [0..23]} ) {
757 next if ( $t < 0 || $t > 24 );
758 my $tomorrow = $t + 24;
760 || ($tomorrow - $currHours > 0
761 && $delta > $tomorrow - $currHours) ) {
762 $delta = $tomorrow - $currHours;
763 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
766 || ($t - $currHours > 0 && $delta > $t - $currHours) ) {
767 $delta = $t - $currHours;
768 $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
771 $NextWakeup = time + $delta * 3600;
772 $Info{nextWakeup} = $NextWakeup;
773 print(LOG $bpc->timeStamp, "Next wakeup is ",
774 $bpc->timeStamp($NextWakeup, 1), "\n");
777 # Call select(), waiting until either a signal, a timeout,
778 # any output from our jobs, or any messages from clients
780 # select() is where we (hopefully) spend most of our time blocked...
782 my $timeout = $NextWakeup - time;
783 $timeout = 1 if ( $timeout <= 0 );
785 select(my $rout = $FDread, undef, $ein, $timeout);
790 ############################################################################
791 # Main_Process_Signal()
794 ############################################################################
795 sub Main_Process_Signal
800 if ( $SigName eq "HUP" ) {
801 ServerReload("Re-read config file because of a SIG_HUP");
802 } elsif ( $SigName ) {
803 ServerShutdown("Got signal $SigName... cleaning up");
808 ############################################################################
809 # Main_Check_Timeout()
811 # Check if a timeout has occured, and if so, queue all the PCs for backups.
812 # Also does log file aging on the first timeout after midnight.
813 ############################################################################
814 sub Main_Check_Timeout
819 return if ( time < $NextWakeup || $NextWakeup <= 0 );
821 if ( $FirstWakeup ) {
823 # This is the first wakeup after midnight. Do log file aging
824 # and various house keeping.
827 printf(LOG "%s24hr disk usage: %d%% max, %d%% recent,"
828 . " %d skipped hosts\n",
829 $bpc->timeStamp, $Info{DUDailyMax}, $Info{DUlastValue},
830 $Info{DUDailySkipHostCnt});
831 $Info{DUDailyMaxReset} = 1;
832 $Info{DUDailyMaxPrev} = $Info{DUDailyMax};
833 $Info{DUDailySkipHostCntPrev} = $Info{DUDailySkipHostCnt};
834 $Info{DUDailySkipHostCnt} = 0;
835 my $lastLog = $Conf{MaxOldLogFiles} - 1;
836 if ( -f "$LogDir/LOG.$lastLog" ) {
837 print(LOG $bpc->timeStamp,
838 "Removing $LogDir/LOG.$lastLog\n");
839 unlink("$LogDir/LOG.$lastLog");
841 if ( -f "$LogDir/LOG.$lastLog.z" ) {
842 print(LOG $bpc->timeStamp,
843 "Removing $LogDir/LOG.$lastLog.z\n");
844 unlink("$LogDir/LOG.$lastLog.z");
846 print(LOG $bpc->timeStamp, "Aging LOG files, LOG -> LOG.0 -> "
847 . "LOG.1 -> ... -> LOG.$lastLog\n");
848 close(STDERR); # dup of LOG
849 close(STDOUT); # dup of LOG
851 for ( my $i = $lastLog - 1 ; $i >= 0 ; $i-- ) {
853 rename("$LogDir/LOG.$i", "$LogDir/LOG.$j")
854 if ( -f "$LogDir/LOG.$i" );
855 rename("$LogDir/LOG.$i.z", "$LogDir/LOG.$j.z")
856 if ( -f "$LogDir/LOG.$i.z" );
859 # Compress the log file LOG -> LOG.0.z (if enabled).
860 # Otherwise, just rename LOG -> LOG.0.
862 BackupPC::FileZIO->compressCopy("$LogDir/LOG",
865 $Conf{CompressLevel}, 1);
868 # Remember to run the nightly script when the next CmdQueue
871 if ( $RunNightlyWhenIdle == 2 ) {
872 print(LOG $bpc->timeStamp, "BackupPC_nightly is still running after 24 hours!!"
873 . " You should adjust the config settings; Skipping this run\n");
875 $RunNightlyWhenIdle = 1;
879 # Write out the current status and then queue all the PCs
883 %BgQueueOn = () if ( @BgQueue == 0 );
884 %UserQueueOn = () if ( @UserQueue == 0 );
885 %CmdQueueOn = () if ( @CmdQueue == 0 );
889 ############################################################################
890 # Main_Check_Job_Messages($fdRead)
892 # Check if select() says we have bytes waiting from any of our jobs.
893 # Handle each of the messages when complete (newline terminated).
894 ############################################################################
895 sub Main_Check_Job_Messages
898 foreach my $host ( keys(%Jobs) ) {
899 next if ( !vec($fdRead, $Jobs{$host}{fn}, 1) );
902 # do a last check to make sure there is something to read so
903 # we are absolutely sure we won't block.
905 vec(my $readMask, $Jobs{$host}{fn}, 1) = 1;
906 if ( !select($readMask, undef, undef, 0.0) ) {
907 print(LOG $bpc->timeStamp, "Botch in Main_Check_Job_Messages:"
908 . " nothing to read from $host. Debug dump:\n");
909 my($dump) = Data::Dumper->new(
910 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
911 [qw(*Clients, *Jobs *FDread, *fdRead)]);
913 print(LOG $dump->Dump);
916 my $nbytes = sysread($Jobs{$host}{fh}, $mesg, 1024);
917 $Jobs{$host}{mesg} .= $mesg if ( $nbytes > 0 );
919 # Process any complete lines of output from this jobs.
920 # Any output to STDOUT or STDERR from the children is processed here.
922 while ( $Jobs{$host}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
924 $Jobs{$host}{mesg} = $2;
925 if ( $Jobs{$host}{dhcp} ) {
926 if ( $mesg =~ /^DHCP (\S+) (\S+)/ ) {
927 my $newHost = $bpc->uriUnesc($2);
928 if ( defined($Jobs{$newHost}) ) {
929 print(LOG $bpc->timeStamp,
930 "Backup on $newHost is already running\n");
931 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
935 $Jobs{$host}{dhcpHostIP} = $host;
936 $Status{$newHost}{dhcpHostIP} = $host;
937 $Jobs{$newHost} = $Jobs{$host};
938 delete($Jobs{$host});
940 $Status{$host}{state} = "Status_backup_starting";
941 $Status{$host}{activeJob} = 1;
942 $Status{$host}{startTime} = $Jobs{$host}{startTime};
943 $Status{$host}{endTime} = "";
944 $Jobs{$host}{dhcp} = 0;
946 print(LOG $bpc->timeStamp, "dhcp $host: $mesg\n");
948 } elsif ( $mesg =~ /^started (.*) dump, share=(.*)/ ) {
949 $Jobs{$host}{type} = $1;
950 $Jobs{$host}{shareName} = $2;
951 print(LOG $bpc->timeStamp,
952 "Started $1 backup on $host (pid=$Jobs{$host}{pid}",
953 $Jobs{$host}{dhcpHostIP}
954 ? ", dhcp=$Jobs{$host}{dhcpHostIP}" : "",
955 ", share=$Jobs{$host}{shareName})\n");
956 $Status{$host}{state} = "Status_backup_in_progress";
957 $Status{$host}{reason} = "";
958 $Status{$host}{type} = $1;
959 $Status{$host}{startTime} = time;
960 $Status{$host}{deadCnt} = 0;
961 $Status{$host}{aliveCnt}++;
962 $Status{$host}{dhcpCheckCnt}--
963 if ( $Status{$host}{dhcpCheckCnt} > 0 );
964 } elsif ( $mesg =~ /^xferPids (.*)/ ) {
965 $Jobs{$host}{xferPid} = $1;
966 } elsif ( $mesg =~ /^completionPercent (.*)/ ) {
967 $Jobs{$host}{completionPercent} = $1;
968 } elsif ( $mesg =~ /^started_restore/ ) {
969 $Jobs{$host}{type} = "restore";
970 print(LOG $bpc->timeStamp,
971 "Started restore on $host"
972 . " (pid=$Jobs{$host}{pid})\n");
973 $Status{$host}{state} = "Status_restore_in_progress";
974 $Status{$host}{reason} = "";
975 $Status{$host}{type} = "restore";
976 $Status{$host}{startTime} = time;
977 $Status{$host}{deadCnt} = 0;
978 $Status{$host}{aliveCnt}++;
979 } elsif ( $mesg =~ /^started_archive/ ) {
980 $Jobs{$host}{type} = "archive";
981 print(LOG $bpc->timeStamp,
982 "Started archive on $host"
983 . " (pid=$Jobs{$host}{pid})\n");
984 $Status{$host}{state} = "Status_archive_in_progress";
985 $Status{$host}{reason} = "";
986 $Status{$host}{type} = "archive";
987 $Status{$host}{startTime} = time;
988 $Status{$host}{deadCnt} = 0;
989 $Status{$host}{aliveCnt}++;
990 } elsif ( $mesg =~ /^(full|incr) backup complete/ ) {
991 print(LOG $bpc->timeStamp, "Finished $1 backup on $host\n");
992 $Status{$host}{reason} = "Reason_backup_done";
993 delete($Status{$host}{error});
994 delete($Status{$host}{errorTime});
995 $Status{$host}{endTime} = time;
996 $Status{$host}{lastGoodBackupTime} = time;
997 } elsif ( $mesg =~ /^backups disabled/ ) {
998 print(LOG $bpc->timeStamp,
999 "Ignoring old backup error on $host\n");
1000 $Status{$host}{reason} = "Reason_backup_done";
1001 delete($Status{$host}{error});
1002 delete($Status{$host}{errorTime});
1003 $Status{$host}{endTime} = time;
1004 } elsif ( $mesg =~ /^restore complete/ ) {
1005 print(LOG $bpc->timeStamp, "Finished restore on $host\n");
1006 $Status{$host}{reason} = "Reason_restore_done";
1007 delete($Status{$host}{error});
1008 delete($Status{$host}{errorTime});
1009 $Status{$host}{endTime} = time;
1010 } elsif ( $mesg =~ /^archive complete/ ) {
1011 print(LOG $bpc->timeStamp, "Finished archive on $host\n");
1012 $Status{$host}{reason} = "Reason_archive_done";
1013 delete($Status{$host}{error});
1014 delete($Status{$host}{errorTime});
1015 $Status{$host}{endTime} = time;
1016 } elsif ( $mesg =~ /^nothing to do/ ) {
1017 if ( $Status{$host}{reason} ne "Reason_backup_failed"
1018 && $Status{$host}{reason} ne "Reason_restore_failed" ) {
1019 $Status{$host}{state} = "Status_idle";
1020 $Status{$host}{reason} = "Reason_nothing_to_do";
1021 $Status{$host}{startTime} = time;
1023 $Status{$host}{dhcpCheckCnt}--
1024 if ( $Status{$host}{dhcpCheckCnt} > 0 );
1025 } elsif ( $mesg =~ /^no ping response/
1026 || $mesg =~ /^ping too slow/
1027 || $mesg =~ /^host not found/ ) {
1028 $Status{$host}{state} = "Status_idle";
1029 if ( $Status{$host}{userReq}
1030 || $Status{$host}{reason} ne "Reason_backup_failed"
1031 || $Status{$host}{error} =~ /^aborted by user/ ) {
1032 $Status{$host}{reason} = "Reason_no_ping";
1033 $Status{$host}{error} = $mesg;
1034 $Status{$host}{startTime} = time;
1036 $Status{$host}{deadCnt}++;
1037 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1038 $Status{$host}{aliveCnt} = 0;
1040 } elsif ( $mesg =~ /^dump failed: (.*)/ ) {
1041 $Status{$host}{state} = "Status_idle";
1042 $Status{$host}{error} = $1;
1043 $Status{$host}{errorTime} = time;
1044 $Status{$host}{endTime} = time;
1045 if ( $Status{$host}{reason}
1046 eq "Reason_backup_canceled_by_user" ) {
1047 print(LOG $bpc->timeStamp,
1048 "Backup canceled on $host ($1)\n");
1050 $Status{$host}{reason} = "Reason_backup_failed";
1051 print(LOG $bpc->timeStamp,
1052 "Backup failed on $host ($1)\n");
1054 } elsif ( $mesg =~ /^restore failed: (.*)/ ) {
1055 $Status{$host}{state} = "Status_idle";
1056 $Status{$host}{error} = $1;
1057 $Status{$host}{errorTime} = time;
1058 $Status{$host}{endTime} = time;
1059 if ( $Status{$host}{reason}
1060 eq "Reason_restore_canceled_by_user" ) {
1061 print(LOG $bpc->timeStamp,
1062 "Restore canceled on $host ($1)\n");
1064 $Status{$host}{reason} = "Reason_restore_failed";
1065 print(LOG $bpc->timeStamp,
1066 "Restore failed on $host ($1)\n");
1068 } elsif ( $mesg =~ /^archive failed: (.*)/ ) {
1069 $Status{$host}{state} = "Status_idle";
1070 $Status{$host}{error} = $1;
1071 $Status{$host}{errorTime} = time;
1072 $Status{$host}{endTime} = time;
1073 if ( $Status{$host}{reason}
1074 eq "Reason_archive_canceled_by_user" ) {
1075 print(LOG $bpc->timeStamp,
1076 "Archive canceled on $host ($1)\n");
1078 $Status{$host}{reason} = "Reason_archive_failed";
1079 print(LOG $bpc->timeStamp,
1080 "Archive failed on $host ($1)\n");
1082 } elsif ( $mesg =~ /^log\s+(.*)/ ) {
1083 print(LOG $bpc->timeStamp, "$1\n");
1084 } elsif ( $mesg =~ /^BackupPC_stats (\d+) = (.*)/ ) {
1085 my $chunk = int($1 / 16);
1086 my @f = split(/,/, $2);
1087 $Info{pool}{$f[0]}[$chunk]{FileCnt} += $f[1];
1088 $Info{pool}{$f[0]}[$chunk]{DirCnt} += $f[2];
1089 $Info{pool}{$f[0]}[$chunk]{Kb} += $f[3];
1090 $Info{pool}{$f[0]}[$chunk]{Kb2} += $f[4];
1091 $Info{pool}{$f[0]}[$chunk]{KbRm} += $f[5];
1092 $Info{pool}{$f[0]}[$chunk]{FileCntRm} += $f[6];
1093 $Info{pool}{$f[0]}[$chunk]{FileCntRep} += $f[7];
1094 $Info{pool}{$f[0]}[$chunk]{FileRepMax} = $f[8]
1095 if ( $Info{pool}{$f[0]}[$chunk]{FileRepMax} < $f[8] );
1096 $Info{pool}{$f[0]}[$chunk]{FileCntRename} += $f[9];
1097 $Info{pool}{$f[0]}[$chunk]{FileLinkMax} = $f[10]
1098 if ( $Info{pool}{$f[0]}[$chunk]{FileLinkMax} < $f[10] );
1099 $Info{pool}{$f[0]}[$chunk]{FileLinkTotal} += $f[11];
1100 $Info{pool}{$f[0]}[$chunk]{Time} = time;
1101 } elsif ( $mesg =~ /^BackupPC_nightly lock_off/ ) {
1102 $BackupPCNightlyLock--;
1103 if ( $BackupPCNightlyLock == 0 ) {
1105 # This means the last BackupPC_nightly is done with
1106 # the pool clean, so it's ok to start running regular
1107 # backups again. But starting in 3.0 regular jobs
1108 # are decoupled from BackupPC_nightly.
1110 $RunNightlyWhenIdle = 0;
1112 } elsif ( $mesg =~ /^processState\s+(.+)/ ) {
1113 $Jobs{$host}{processState} = $1;
1114 } elsif ( $mesg =~ /^link\s+(.+)/ ) {
1116 $Status{$h}{needLink} = 1;
1118 print(LOG $bpc->timeStamp, "$host: $mesg\n");
1122 # shut down the client connection if we read EOF
1124 if ( $nbytes <= 0 ) {
1125 close($Jobs{$host}{fh});
1126 vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1127 if ( $CmdJob eq $host || $bpc->isAdminJob($host) ) {
1128 my $cmd = $Jobs{$host}{cmd};
1129 $cmd =~ s/$BinDir\///g;
1130 print(LOG $bpc->timeStamp, "Finished $host ($cmd)\n");
1131 $Status{$host}{state} = "Status_idle";
1132 $Status{$host}{endTime} = time;
1133 if ( $cmd =~ /^BackupPC_nightly\s/ ) {
1134 $BackupPCNightlyJobs--;
1135 #print(LOG $bpc->timeStamp, "BackupPC_nightly done; now"
1136 # . " have $BackupPCNightlyJobs running\n");
1137 if ( $BackupPCNightlyJobs <= 0 ) {
1139 # Last BackupPC_nightly has finished
1141 $BackupPCNightlyJobs = 0;
1142 $RunNightlyWhenIdle = 0;
1145 # Combine the 16 per-directory results
1147 for my $p ( qw(pool cpool) ) {
1148 $Info{"${p}FileCnt"} = 0;
1149 $Info{"${p}DirCnt"} = 0;
1150 $Info{"${p}Kb"} = 0;
1151 $Info{"${p}Kb2"} = 0;
1152 $Info{"${p}KbRm"} = 0;
1153 $Info{"${p}FileCntRm"} = 0;
1154 $Info{"${p}FileCntRep"} = 0;
1155 $Info{"${p}FileRepMax"} = 0;
1156 $Info{"${p}FileCntRename"} = 0;
1157 $Info{"${p}FileLinkMax"} = 0;
1158 $Info{"${p}Time"} = 0;
1159 for ( my $i = 0 ; $i < 16 ; $i++ ) {
1160 $Info{"${p}FileCnt"}
1161 += $Info{pool}{$p}[$i]{FileCnt};
1163 += $Info{pool}{$p}[$i]{DirCnt};
1165 += $Info{pool}{$p}[$i]{Kb};
1167 += $Info{pool}{$p}[$i]{Kb2};
1169 += $Info{pool}{$p}[$i]{KbRm};
1170 $Info{"${p}FileCntRm"}
1171 += $Info{pool}{$p}[$i]{FileCntRm};
1172 $Info{"${p}FileCntRep"}
1173 += $Info{pool}{$p}[$i]{FileCntRep};
1174 $Info{"${p}FileRepMax"}
1175 = $Info{pool}{$p}[$i]{FileRepMax}
1176 if ( $Info{"${p}FileRepMax"} <
1177 $Info{pool}{$p}[$i]{FileRepMax} );
1178 $Info{"${p}FileCntRename"}
1179 += $Info{pool}{$p}[$i]{FileCntRename};
1180 $Info{"${p}FileLinkMax"}
1181 = $Info{pool}{$p}[$i]{FileLinkMax}
1182 if ( $Info{"${p}FileLinkMax"} <
1183 $Info{pool}{$p}[$i]{FileLinkMax} );
1184 $Info{"${p}Time"} = $Info{pool}{$p}[$i]{Time}
1185 if ( $Info{"${p}Time"} <
1186 $Info{pool}{$p}[$i]{Time} );
1188 printf(LOG "%s%s nightly clean removed %d files of"
1190 $bpc->timeStamp, ucfirst($p),
1191 $Info{"${p}FileCntRm"},
1192 $Info{"${p}KbRm"} / (1000 * 1024));
1193 printf(LOG "%s%s is %.2fGB, %d files (%d repeated, "
1194 . "%d max chain, %d max links), %d directories\n",
1195 $bpc->timeStamp, ucfirst($p),
1196 $Info{"${p}Kb"} / (1000 * 1024),
1197 $Info{"${p}FileCnt"}, $Info{"${p}FileCntRep"},
1198 $Info{"${p}FileRepMax"},
1199 $Info{"${p}FileLinkMax"}, $Info{"${p}DirCnt"});
1207 # Queue BackupPC_link to complete the backup
1208 # processing for this host.
1210 if ( defined($Status{$host})
1211 && ($Status{$host}{reason} eq "Reason_backup_done"
1212 || $Status{$host}{needLink}) ) {
1214 } elsif ( defined($Status{$host}) ) {
1215 $Status{$host}{state} = "Status_idle";
1218 delete($Jobs{$host});
1219 $Status{$host}{activeJob} = 0 if ( defined($Status{$host}) );
1223 # When we are idle (empty Jobs, CmdQueue, BgQueue, UserQueue) we
1224 # do a pass over %Status updating the deadCnt and aliveCnt for
1225 # DHCP hosts. The reason we need to do this later is we can't
1226 # be sure whether a DHCP host is alive or dead until we have passed
1227 # over all the DHCP pool.
1229 return if ( @CmdQueue || @BgQueue || @UserQueue || keys(%Jobs) > 1 );
1230 foreach my $host ( keys(%Status) ) {
1231 next if ( $Status{$host}{dhcpCheckCnt} <= 0 );
1232 $Status{$host}{deadCnt} += $Status{$host}{dhcpCheckCnt};
1233 $Status{$host}{dhcpCheckCnt} = 0;
1234 if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1235 $Status{$host}{aliveCnt} = 0;
1240 ############################################################################
1241 # Main_Check_Client_Messages($fdRead)
1243 # Check for, and process, any output from our clients. Also checks
1244 # for new connections to our SERVER_UNIX and SERVER_INET sockets.
1245 ############################################################################
1246 sub Main_Check_Client_Messages
1249 foreach my $client ( keys(%Clients) ) {
1250 next if ( !vec($fdRead, $Clients{$client}{fn}, 1) );
1253 # do a last check to make sure there is something to read so
1254 # we are absolutely sure we won't block.
1256 vec(my $readMask, $Clients{$client}{fn}, 1) = 1;
1257 if ( !select($readMask, undef, undef, 0.0) ) {
1258 print(LOG $bpc->timeStamp, "Botch in Main_Check_Client_Messages:"
1259 . " nothing to read from $client. Debug dump:\n");
1260 my($dump) = Data::Dumper->new(
1261 [ \%Clients, \%Jobs, \$FDread, \$fdRead],
1262 [qw(*Clients, *Jobs *FDread, *fdRead)]);
1264 print(LOG $dump->Dump);
1267 my $nbytes = sysread($Clients{$client}{fh}, $mesg, 1024);
1268 $Clients{$client}{mesg} .= $mesg if ( $nbytes > 0 );
1270 # Process any complete lines received from this client.
1272 while ( $Clients{$client}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
1275 $Clients{$client}{mesg} = $2;
1277 # Authenticate the message by checking the MD5 digest
1279 my $md5 = Digest::MD5->new;
1280 if ( $cmd !~ /^(.{22}) (.*)/
1281 || ($md5->add($Clients{$client}{seed}
1282 . $Clients{$client}{mesgCnt}
1283 . $Conf{ServerMesgSecret} . $2),
1284 $md5->b64digest ne $1) ) {
1285 print(LOG $bpc->timeStamp, "Corrupted message '$cmd' from"
1286 . " client '$Clients{$client}{clientName}':"
1287 . " shutting down client connection\n");
1291 $Clients{$client}{mesgCnt}++;
1292 $cmd = decode_utf8($2);
1293 if ( $cmd =~ /^stop (\S+)\s+(\S+)\s+(\S*)/ ) {
1297 $host = $bpc->uriUnesc($host);
1298 if ( $CmdJob ne $host && defined($Status{$host})
1299 && defined($Jobs{$host}) ) {
1300 print(LOG $bpc->timeStamp,
1301 "Stopping current $Jobs{$host}{type} of $host,"
1302 . " request by $user (backoff=$backoff)\n");
1303 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1305 # Don't close the pipe now; wait until the child
1306 # really exits later. Otherwise close() will
1307 # block until the child has exited.
1309 ##vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1310 ##close($Jobs{$host}{fh});
1311 ##delete($Jobs{$host});
1313 $Status{$host}{state} = "Status_idle";
1314 if ( $Jobs{$host}{type} eq "restore" ) {
1315 $Status{$host}{reason}
1316 = "Reason_restore_canceled_by_user";
1317 } elsif ( $Jobs{$host}{type} eq "archive" ) {
1318 $Status{$host}{reason}
1319 = "Reason_archive_canceled_by_user";
1321 $Status{$host}{reason}
1322 = "Reason_backup_canceled_by_user";
1324 $Status{$host}{activeJob} = 0;
1325 $Status{$host}{startTime} = time;
1326 $reply = "ok: $Jobs{$host}{type} of $host canceled";
1327 } elsif ( $BgQueueOn{$host} || $UserQueueOn{$host} ) {
1328 print(LOG $bpc->timeStamp,
1329 "Stopping pending backup of $host,"
1330 . " request by $user (backoff=$backoff)\n");
1331 @BgQueue = grep($_->{host} ne $host, @BgQueue);
1332 @UserQueue = grep($_->{host} ne $host, @UserQueue);
1333 $BgQueueOn{$host} = $UserQueueOn{$host} = 0;
1334 $reply = "ok: pending backup of $host canceled";
1336 print(LOG $bpc->timeStamp,
1337 "Nothing to do for stop backup of $host,"
1338 . " request by $user (backoff=$backoff)\n");
1339 $reply = "ok: no backup was pending or running";
1341 if ( defined($Status{$host}) && $backoff ne "" ) {
1342 if ( $backoff > 0 ) {
1343 $Status{$host}{backoffTime} = time + $backoff * 3600;
1345 delete($Status{$host}{backoffTime});
1348 } elsif ( $cmd =~ /^backup all$/ ) {
1350 } elsif ( $cmd =~ /^BackupPC_nightly run$/ ) {
1351 $RunNightlyWhenIdle = 1;
1352 } elsif ( $cmd =~ /^backup (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1356 my $backupType = $4;
1357 $host = $bpc->uriUnesc($host);
1358 $hostIP = $bpc->uriUnesc($hostIP);
1359 if ( !defined($Hosts->{$host}) ) {
1360 print(LOG $bpc->timeStamp,
1361 "User $user requested backup of unknown host"
1363 $reply = "error: unknown host $host";
1366 # Handle numeric backupType for backward compatibility
1367 # (technically -1 is a new feature for auto)
1369 $backupType = 'auto' if ( $backupType eq '-1' );
1370 $backupType = 'doIncr' if ( $backupType eq '0' );
1371 $backupType = 'doFull' if ( $backupType eq '1' );
1372 if ( $backupType !~ /^doIncr|doFull|autoIncr|autoFull|auto$/i ) {
1373 $reply = "error: unknown backup type $backupType";
1375 print(LOG $bpc->timeStamp,
1376 "User $user requested backup of $host"
1378 if ( $BgQueueOn{$hostIP} ) {
1379 @BgQueue = grep($_->{host} ne $hostIP, @BgQueue);
1380 $BgQueueOn{$hostIP} = 0;
1382 if ( $UserQueueOn{$hostIP} ) {
1383 @UserQueue = grep($_->{host} ne $hostIP, @UserQueue);
1384 $UserQueueOn{$hostIP} = 0;
1386 my $status = QueueOnePC($host, $hostIP, $user, 'user', $backupType);
1387 if ( $status == 0 ) {
1388 $reply = "ok: requested backup of $host ($backupType)";
1389 } elsif ( $status == 1 ) {
1390 #should never see this we just dequeued it
1391 $reply = "warning: $host was already queued."
1392 . " Ignoring this request";
1393 } elsif ( $status == 2 ) {
1394 print(LOG $bpc->timeStamp,
1395 "Disk too full ($Info{DUlastValue}%)."
1396 . " Not queueing backup of $host\n");
1397 $reply = "error: disk too full ($Info{DUlastValue}%)";
1398 $Info{DUDailySkipHostCnt}++;
1399 } elsif ( $status == 3 ) {
1400 # should never reach this because
1401 # it's set to "user" above
1402 $reply = "error: unknown queue name";
1404 $reply = "error: unknown queue status $status";
1405 if ( $BgQueueOn{$hostIP} || $UserQueueOn{$hostIP} ) {
1406 $reply .= ". Host is queued.";
1408 $reply .= ". Host is not queued.";
1413 } elsif ( $cmd =~ /^archive (\S+)\s+(\S+)\s+(\S+)/ ) {
1415 my $archivehost = $2;
1416 my $reqFileName = $3;
1417 $host = $bpc->uriUnesc($archivehost);
1418 if ( !defined($Status{$host}) ) {
1419 print(LOG $bpc->timeStamp,
1420 "User $user requested archive of unknown archive host"
1422 $reply = "archive error: unknown archive host $host";
1424 print(LOG $bpc->timeStamp,
1425 "User $user requested archive on $host"
1427 if ( defined($Jobs{$host}) ) {
1428 $reply = "Archive currently running on $host, please try later";
1430 unshift(@UserQueue, {
1433 reqFileName => $reqFileName,
1439 $UserQueueOn{$host} = 1;
1440 $reply = "ok: requested archive on $host";
1443 } elsif ( $cmd =~ /^restore (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1447 my $reqFileName = $4;
1448 $host = $bpc->uriUnesc($host);
1449 $hostIP = $bpc->uriUnesc($hostIP);
1450 if ( !defined($Hosts->{$host}) ) {
1451 print(LOG $bpc->timeStamp,
1452 "User $user requested restore to unknown host"
1454 $reply = "restore error: unknown host $host";
1456 print(LOG $bpc->timeStamp,
1457 "User $user requested restore to $host"
1459 unshift(@UserQueue, {
1462 reqFileName => $reqFileName,
1468 $UserQueueOn{$host} = 1;
1469 if ( defined($Jobs{$host}) ) {
1470 $reply = "ok: requested restore of $host, but a"
1471 . " job is currently running,"
1472 . " so this request will start later";
1474 $reply = "ok: requested restore of $host";
1477 } elsif ( $cmd =~ /^status\s*(.*)/ ) {
1479 my($dump, @values, @names);
1480 foreach my $type ( split(/\s+/, $args) ) {
1481 if ( $type =~ /^queues/ ) {
1482 push(@values, \@BgQueue, \@UserQueue, \@CmdQueue);
1483 push(@names, qw(*BgQueue *UserQueue *CmdQueue));
1484 } elsif ( $type =~ /^jobs/ ) {
1485 push(@values, \%Jobs);
1486 push(@names, qw(*Jobs));
1487 } elsif ( $type =~ /^queueLen/ ) {
1489 BgQueue => scalar(@BgQueue),
1490 UserQueue => scalar(@UserQueue),
1491 CmdQueue => scalar(@CmdQueue),
1493 push(@names, qw(*QueueLen));
1494 } elsif ( $type =~ /^info/ ) {
1495 push(@values, \%Info);
1496 push(@names, qw(*Info));
1497 } elsif ( $type =~ /^hosts/ ) {
1498 push(@values, \%Status);
1499 push(@names, qw(*Status));
1500 } elsif ( $type =~ /^host\((.*)\)/ ) {
1501 my $h = $bpc->uriUnesc($1);
1502 if ( defined($Status{$h}) ) {
1505 BgQueueOn => $BgQueueOn{$h},
1506 UserQueueOn => $UserQueueOn{$h},
1507 CmdQueueOn => $CmdQueueOn{$h},
1509 push(@names, qw(*StatusHost));
1511 print(LOG $bpc->timeStamp,
1512 "Unknown host $h for status request\n");
1515 print(LOG $bpc->timeStamp,
1516 "Unknown status request $type\n");
1519 $dump = Data::Dumper->new(\@values, \@names);
1521 $reply = $dump->Dump;
1522 } elsif ( $cmd =~ /^link\s+(.+)/ ) {
1524 $host = $bpc->uriUnesc($host);
1526 } elsif ( $cmd =~ /^log\s+(.*)/ ) {
1527 print(LOG $bpc->timeStamp, "$1\n");
1528 } elsif ( $cmd =~ /^server\s+(\w+)/ ) {
1530 if ( $type eq 'reload' ) {
1531 ServerReload("Reloading config/host files via CGI request");
1532 } elsif ( $type eq 'shutdown' ) {
1533 $reply = "Shutting down...\n";
1534 syswrite($Clients{$client}{fh}, $reply, length($reply));
1535 ServerShutdown("Server shutting down...");
1537 } elsif ( $cmd =~ /^quit/ || $cmd =~ /^exit/ ) {
1541 print(LOG $bpc->timeStamp, "Unknown command $cmd\n");
1542 $reply = "error: bad command $cmd";
1545 # send a reply to the client, at a minimum "ok\n".
1547 $reply = "ok" if ( $reply eq "" );
1549 syswrite($Clients{$client}{fh}, $reply, length($reply));
1552 # Detect possible denial-of-service attack from sending a huge line
1553 # (ie: never terminated). 32K seems to be plenty big enough as
1556 if ( length($Clients{$client}{mesg}) > 32 * 1024 ) {
1557 print(LOG $bpc->timeStamp, "Line too long from client"
1558 . " '$Clients{$client}{clientName}':"
1559 . " shutting down client connection\n");
1563 # Shut down the client connection if we read EOF
1565 if ( $nbytes <= 0 ) {
1566 close($Clients{$client}{fh});
1567 vec($FDread, $Clients{$client}{fn}, 1) = 0;
1568 delete($Clients{$client});
1572 # Accept any new connections on each of our listen sockets
1574 if ( vec($fdRead, fileno(SERVER_UNIX), 1) ) {
1576 my $paddr = accept(CLIENT, SERVER_UNIX);
1578 $Clients{$ClientConnCnt}{clientName} = "unix socket";
1579 $Clients{$ClientConnCnt}{mesg} = "";
1580 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1581 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1582 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1584 # Generate and send unique seed for MD5 digests to avoid
1585 # replay attacks. See BackupPC::Lib::ServerMesg().
1587 my $seed = time . ",$ClientConnCnt,$$,0\n";
1588 $Clients{$ClientConnCnt}{seed} = $seed;
1589 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1590 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1592 if ( $ServerInetPort > 0 && vec($fdRead, fileno(SERVER_INET), 1) ) {
1594 my $paddr = accept(CLIENT, SERVER_INET);
1595 my($port,$iaddr) = sockaddr_in($paddr);
1596 my $name = gethostbyaddr($iaddr, AF_INET);
1598 $Clients{$ClientConnCnt}{mesg} = "";
1599 $Clients{$ClientConnCnt}{fh} = *CLIENT;
1600 $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1601 $Clients{$ClientConnCnt}{clientName} = "$name:$port";
1602 vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1604 # Generate and send unique seed for MD5 digests to avoid
1605 # replay attacks. See BackupPC::Lib::ServerMesg().
1607 my $seed = time . ",$ClientConnCnt,$$,$port\n";
1608 $Clients{$ClientConnCnt}{seed} = $seed;
1609 $Clients{$ClientConnCnt}{mesgCnt} = 0;
1610 syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1614 ###########################################################################
1615 # Miscellaneous subroutines
1616 ###########################################################################
1619 # Write the current status to $LogDir/status.pl
1623 my($dump) = Data::Dumper->new(
1624 [ \%Info, \%Status],
1625 [qw(*Info *Status)]);
1627 my $text = $dump->Dump;
1628 $bpc->{storage}->TextFileWrite("$LogDir/status.pl", $text);
1632 # Compare function for host sort. Hosts with errors go first,
1633 # sorted with the oldest errors first. The remaining hosts
1634 # are sorted so that those with the oldest backups go first.
1639 # Hosts with errors go before hosts without errors
1641 return -1 if ( $Status{$a}{error} ne "" && $Status{$b}{error} eq "" );
1644 # Hosts with no errors go after hosts with errors
1646 return 1 if ( $Status{$a}{error} eq "" && $Status{$b}{error} ne "" );
1649 # hosts with the older last good backups sort earlier
1651 my $r = $Status{$a}{lastGoodBackupTime} <=> $Status{$b}{lastGoodBackupTime};
1652 return $r if ( $r );
1655 # Finally, just sort based on host name
1661 # Attempt to queue a host.
1662 # Returns 0 on success; 1 if host is already queued;
1663 # 2 if host was skipped; 3 on invalid queue name
1665 # $host is the client's host name
1666 # $hostIP is usually the client's host name too, or IP address
1667 # if the user specified it in the manual backup command
1668 # $user is the user name, or BackupPC by default
1669 # $queue is which queue to use ("bg" by default)
1670 # $backupType is the backup type (doIncr|doFull|autoIncr|autoFull|auto|dhcpPoll)
1672 # Note: starting in 3.2.0, the PC is queued even if it has a current
1677 my($host, $hostIP, $user, $queue, $backupType) = @_;
1679 $user = "BackupPC" if ( $user eq '' );
1680 $queue = "bg" if ( $queue eq '' && $user eq 'BackupPC' );
1681 $backupType = "auto" if ( $backupType eq '' );
1683 delete($Status{$host}{backoffTime})
1684 if ( defined($Status{$host}{backoffTime})
1685 && $Status{$host}{backoffTime} < time );
1686 return 1 if ( $BgQueueOn{$host} || $UserQueueOn{$host} );
1687 if ( $Hosts->{$host}{dhcp} ) {
1688 $Status{$host}{dhcpCheckCnt}++;
1689 if ( $RunNightlyWhenIdle ) {
1691 # Once per night queue a check for DHCP hosts that just
1692 # checks for expired dumps. We need to do this to handle
1693 # the case when a DHCP host has not been on the network for
1694 # a long time, and some of the old dumps need to be expired.
1695 # Normally expiry checks are done by BackupPC_dump only
1696 # after the DHCP hosts has been detected on the network.
1699 {host => $hostIP, user => $user, reqTime => time,
1700 dhcp => 0, dumpExpire => 1});
1701 $BgQueueOn{$host} = 1;
1705 # this is a fixed ip host or DHCP ip address: queue it
1707 if ( $Info{DUlastValue} > $Conf{DfMaxUsagePct} ) {
1709 # Since we are out of disk space, instead of queuing
1710 # a regular job, queue an expire check instead. That
1711 # way if the admin reduces the number of backups to
1712 # keep then we will actually delete them. Otherwise
1713 # BackupPC_dump will never run since we have exceeded
1718 {host => $hostIP, user => $user, reqTime => time, dumpExpire => 1});
1719 $BgQueueOn{$host} = 1;
1720 } elsif( $queue eq 'bg' ) {
1722 # Queue regular background backup
1725 {host => $hostIP, user => $user, reqTime => time, backupType => $backupType});
1726 $BgQueueOn{$host} = 1;
1727 } elsif( $queue eq 'user' ) {
1732 {host => $hostIP, user => $user, reqTime => time, backupType => $backupType});
1733 $UserQueueOn{$host} = 1;
1735 # unknown $queue type
1744 # Queue all the hosts for backup. This means queuing all the fixed
1745 # ip hosts and all the dhcp address ranges. We also additionally
1746 # queue the dhcp hosts with a -e flag to check for expired dumps.
1752 foreach my $host ( sort HostSortCompare keys(%$Hosts) ) {
1753 $nSkip++ if ( QueueOnePC($host, $host, 'BackupPC', 'bg', 'auto') == 2 );
1755 foreach my $dhcp ( @{$Conf{DHCPAddressRanges}} ) {
1756 for ( my $i = $dhcp->{first} ; $i <= $dhcp->{last} ; $i++ ) {
1757 my $ipAddr = "$dhcp->{ipAddrBase}.$i";
1758 $nSkip++ if ( QueueOnePC($ipAddr, $ipAddr, 'BackupPC', 'bg', 'dhcpPoll') == 2 );
1762 print(LOG $bpc->timeStamp,
1763 "Disk too full ($Info{DUlastValue}%); skipped $nSkip hosts\n");
1764 $Info{DUDailySkipHostCnt} += $nSkip;
1769 # Queue a BackupPC_link for the given host
1775 return if ( $CmdQueueOn{$host} );
1776 $Status{$host}{state} = "Status_link_pending";
1777 $Status{$host}{needLink} = 0;
1778 unshift(@CmdQueue, {
1782 cmd => ["$BinDir/BackupPC_link", $host],
1784 $CmdQueueOn{$host} = 1;
1788 # Read the hosts file, and update Status if any hosts have been
1789 # added or deleted. We also track the mtime so the only need to
1790 # update the hosts file on changes.
1792 # This function is called at startup, SIGHUP, and on each wakeup.
1793 # It returns 1 on success and undef on failure.
1800 # Nothing to do if we already have the current hosts file
1802 return 1 if ( !$force && defined($Hosts)
1803 && $Info{HostsModTime} == $bpc->HostsMTime() );
1804 if ( !defined($newHosts = $bpc->HostInfoRead()) ) {
1805 print(LOG $bpc->timeStamp, "Can't read hosts file!\n");
1808 print(LOG $bpc->timeStamp, "Reading hosts file\n");
1810 $Info{HostsModTime} = $bpc->HostsMTime();
1812 # Now update %Status in case any hosts have been added or deleted
1814 foreach my $host ( sort(keys(%$Hosts)) ) {
1815 next if ( defined($Status{$host}) );
1816 $Status{$host}{state} = "Status_idle";
1817 print(LOG $bpc->timeStamp, "Added host $host to backup list\n");
1819 foreach my $host ( sort(keys(%Status)) ) {
1820 next if ( $host eq $bpc->trashJob
1821 || $bpc->isAdminJob($host)
1822 || defined($Hosts->{$host})
1823 || defined($Jobs{$host})
1824 || $BgQueueOn{$host}
1825 || $UserQueueOn{$host}
1826 || $CmdQueueOn{$host} );
1827 print(LOG $bpc->timeStamp, "Deleted host $host from backup list\n");
1828 delete($Status{$host});
1834 # Remember the signal name for later processing
1840 foreach my $host ( keys(%Jobs) ) {
1841 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1844 # In case we are inside the exit handler, reopen the log file
1848 print(LOG "Fatal error: unhandled signal $SigName\n");
1849 unlink("$LogDir/BackupPC.pid");
1850 confess("Got new signal $SigName... quitting\n");
1857 # Open the log file and point STDOUT and STDERR there too
1861 mkpath($LogDir, 0, 0777) if ( !-d $LogDir );
1862 open(LOG, ">>$LogDir/LOG")
1863 || die("Can't create LOG file $LogDir/LOG");
1866 open(STDOUT, ">&LOG");
1867 open(STDERR, ">&LOG");
1868 select(LOG); $| = 1;
1869 select(STDERR); $| = 1;
1870 select(STDOUT); $| = 1;
1874 # Initialize the unix-domain and internet-domain sockets that
1875 # we listen to for client connections (from the CGI script and
1876 # some of the BackupPC sub-programs).
1878 sub ServerSocketInit
1880 if ( !defined(fileno(SERVER_UNIX)) ) {
1882 # one-time only: initialize unix-domain socket
1884 if ( !socket(SERVER_UNIX, PF_UNIX, SOCK_STREAM, 0) ) {
1885 print(LOG $bpc->timeStamp, "unix socket() failed: $!\n");
1888 my $sockFile = "$LogDir/BackupPC.sock";
1890 if ( !bind(SERVER_UNIX, sockaddr_un($sockFile)) ) {
1891 print(LOG $bpc->timeStamp, "unix bind() failed: $!\n");
1894 if ( !listen(SERVER_UNIX, SOMAXCONN) ) {
1895 print(LOG $bpc->timeStamp, "unix listen() failed: $!\n");
1898 vec($FDread, fileno(SERVER_UNIX), 1) = 1;
1900 return if ( $ServerInetPort == $Conf{ServerPort} );
1901 if ( $ServerInetPort > 0 ) {
1902 vec($FDread, fileno(SERVER_INET), 1) = 0;
1904 $ServerInetPort = -1;
1906 if ( $Conf{ServerPort} > 0 ) {
1908 # Setup a socket to listen on $Conf{ServerPort}
1910 my $proto = getprotobyname('tcp');
1911 if ( !socket(SERVER_INET, PF_INET, SOCK_STREAM, $proto) ) {
1912 print(LOG $bpc->timeStamp, "inet socket() failed: $!\n");
1915 if ( !setsockopt(SERVER_INET, SOL_SOCKET, SO_REUSEADDR, pack("l",1)) ) {
1916 print(LOG $bpc->timeStamp, "setsockopt() failed: $!\n");
1919 if ( !bind(SERVER_INET, sockaddr_in($Conf{ServerPort}, INADDR_ANY)) ) {
1920 print(LOG $bpc->timeStamp, "inet bind() failed: $!\n");
1923 if ( !listen(SERVER_INET, SOMAXCONN) ) {
1924 print(LOG $bpc->timeStamp, "inet listen() failed: $!\n");
1927 vec($FDread, fileno(SERVER_INET), 1) = 1;
1928 $ServerInetPort = $Conf{ServerPort};
1933 # Reload the server. Used by Main_Process_Signal when $SigName eq "HUP"
1934 # or when the command "server reload" is received.
1939 $mesg = $bpc->ConfigRead() || $mesg;
1940 print(LOG $bpc->timeStamp, "$mesg\n");
1941 $Info{ConfigModTime} = $bpc->ConfigMTime();
1942 %Conf = $bpc->Conf();
1943 umask($Conf{UmaskMode});
1947 $Info{ConfigLTime} = time;
1951 # Gracefully shutdown the server. Used by Main_Process_Signal when
1952 # $SigName ne "" && $SigName ne "HUP" or when the command
1953 # "server shutdown" is received.
1958 print(LOG $bpc->timeStamp, "$mesg\n");
1959 if ( keys(%Jobs) ) {
1960 foreach my $host ( keys(%Jobs) ) {
1961 kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1964 foreach my $host ( keys(%Jobs) ) {
1965 kill($bpc->sigName2num("KILL"), $Jobs{$host}{pid});
1971 unlink("$LogDir/BackupPC.pid");