/[BackupPC]/trunk/bin/BackupPC
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Annotation of /trunk/bin/BackupPC

Parent Directory Parent Directory | Revision Log Revision Log


Revision 316 - (hide annotations)
Mon Jan 30 13:37:17 2006 UTC (18 years, 4 months ago) by dpavlin
File size: 69776 byte(s)
 r9152@llin:  dpavlin | 2006-01-30 14:11:45 +0100
 update to upstream 2.1.2

1 dpavlin 1 #!/bin/perl
2     #============================================================= -*-perl-*-
3     #
4     # BackupPC: Main program for PC backups.
5     #
6     # DESCRIPTION
7     #
8     # BackupPC reads the configuration and status information from
9     # $TopDir/conf. It then runs and manages all the backup activity.
10     #
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).
22     #
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.
27     #
28     # AUTHOR
29     # Craig Barratt <cbarratt@users.sourceforge.net>
30     #
31     # COPYRIGHT
32     # Copyright (C) 2001-2003 Craig Barratt
33     #
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.
38     #
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.
43     #
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
47     #
48     #========================================================================
49     #
50 dpavlin 316 # Version 2.1.2, released 5 Sep 2005.
51 dpavlin 1 #
52     # See http://backuppc.sourceforge.net.
53     #
54     #========================================================================
55    
56     use strict;
57     no utf8;
58     use vars qw(%Status %Info $Hosts);
59     use lib "__INSTALLDIR__/lib";
60     use BackupPC::Lib;
61     use BackupPC::FileZIO;
62    
63     use File::Path;
64     use Data::Dumper;
65     use Getopt::Std;
66     use Socket;
67     use Carp;
68     use Digest::MD5;
69 dpavlin 316 use POSIX qw(setsid);
70 dpavlin 1
71     ###########################################################################
72     # Handle command line options
73     ###########################################################################
74     my %opts;
75     if ( !getopts("d", \%opts) || @ARGV != 0 ) {
76     print("usage: $0 [-d]\n");
77     exit(1);
78     }
79    
80     ###########################################################################
81     # Initialize major data structures and variables
82     ###########################################################################
83    
84     #
85     # Get an instance of BackupPC::Lib and get some shortcuts.
86     #
87     die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );
88     my $TopDir = $bpc->TopDir();
89     my $BinDir = $bpc->BinDir();
90     my %Conf = $bpc->Conf();
91    
92     #
93     # Verify we are running as the correct user
94     #
95     if ( $Conf{BackupPCUserVerify}
96     && $> != (my $uid = (getpwnam($Conf{BackupPCUser}))[2]) ) {
97     die "Wrong user: my userid is $>, instead of $uid ($Conf{BackupPCUser})\n";
98     }
99    
100     #
101     # %Status maintain status information about each host.
102     # It is a hash of hashes, whose first index is the host.
103     #
104     %Status = ();
105    
106     #
107     # %Info is a hash giving general information about BackupPC status.
108     #
109     %Info = ();
110    
111     #
112     # Read old status
113     #
114     if ( -f "$TopDir/log/status.pl" && !(my $ret = do "$TopDir/log/status.pl") ) {
115     die "couldn't parse $TopDir/log/status.pl: $@" if $@;
116     die "couldn't do $TopDir/log/status.pl: $!" unless defined $ret;
117     die "couldn't run $TopDir/log/status.pl";
118     }
119    
120     #
121     # %Jobs maintains information about currently running jobs.
122     # It is a hash of hashes, whose first index is the host.
123     #
124     my %Jobs = ();
125    
126     #
127     # There are three command queues:
128     # - @UserQueue is a queue of user initiated backup requests.
129     # - @BgQueue is a queue of automatically scheduled backup requests.
130     # - @CmdQueue is a queue of administrative jobs, including tasks
131     # like BackupPC_link, BackupPC_trashClean, and BackupPC_nightly
132     # Each queue is an array of hashes. Each hash stores information
133     # about the command request.
134     #
135     my @UserQueue = ();
136     my @CmdQueue = ();
137     my @BgQueue = ();
138    
139     #
140     # To quickly lookup if a given host is on a given queue, we keep
141     # a hash of flags for each queue type.
142     #
143     my(%CmdQueueOn, %UserQueueOn, %BgQueueOn);
144    
145     #
146     # One or more clients can connect to the server to get status information
147     # or request/cancel backups etc. The %Clients hash maintains information
148     # about each of these socket connections. The hash key is an incrementing
149     # number stored in $ClientConnCnt. Each entry is a hash that contains
150     # various information about the client connection.
151     #
152     my %Clients = ();
153     my $ClientConnCnt;
154    
155     #
156     # Read file descriptor mask used by select(). Every file descriptor
157     # on which we expect to read (or accept) has the corresponding bit
158     # set.
159     #
160     my $FDread = '';
161    
162     #
163     # Unix seconds when we next wakeup. A value of zero forces the scheduler
164     # to compute the next wakeup time.
165     #
166     my $NextWakeup = 0;
167    
168     #
169     # Name of signal saved by catch_signal
170     #
171     my $SigName = "";
172    
173     #
174     # Misc variables
175     #
176     my($RunNightlyWhenIdle, $FirstWakeup, $CmdJob, $ServerInetPort);
177     my($BackupPCNightlyJobs, $BackupPCNightlyLock);
178    
179     #
180     # Complete the rest of the initialization
181     #
182     Main_Initialize();
183    
184     ###########################################################################
185     # Main loop
186     ###########################################################################
187     while ( 1 )
188     {
189     #
190     # Check if we can/should run BackupPC_nightly
191     #
192     Main_TryToRun_nightly();
193    
194     #
195     # Check if we can run a new command from @CmdQueue.
196     #
197     Main_TryToRun_CmdQueue();
198    
199     #
200     # Check if we can run a new command from @UserQueue or @BgQueue.
201     #
202     Main_TryToRun_Bg_or_User_Queue();
203    
204     #
205     # Do a select() to wait for the next interesting thing to happen
206     # (timeout, signal, someone sends a message, child dies etc).
207     #
208     my $fdRead = Main_Select();
209    
210     #
211     # Process a signal if we received one.
212     #
213     if ( $SigName ) {
214     Main_Process_Signal();
215     $fdRead = undef;
216     }
217    
218     #
219     # Check if a timeout has occurred.
220     #
221     Main_Check_Timeout();
222    
223     #
224     # Check for, and process, any messages (output) from our jobs
225     #
226     Main_Check_Job_Messages($fdRead);
227    
228     #
229     # Check for, and process, any output from our clients. Also checks
230     # for new connections to our SERVER_UNIX and SERVER_INET sockets.
231     #
232     Main_Check_Client_Messages($fdRead);
233     }
234    
235     ############################################################################
236     # Main_Initialize()
237     #
238     # Main initialization routine. Called once at statup.
239     ############################################################################
240     sub Main_Initialize
241     {
242     umask($Conf{UmaskMode});
243    
244     #
245     # Check for another running process, check that PASSWD is set and
246     # verify executables are configured correctly.
247     #
248     if ( $Info{pid} ne "" && kill(0, $Info{pid}) ) {
249     print(STDERR $bpc->timeStamp,
250     "Another BackupPC is running (pid $Info{pid}); quitting...\n");
251     exit(1);
252     }
253     foreach my $progName ( qw(SmbClientPath NmbLookupPath PingPath DfPath
254     SendmailPath SshPath) ) {
255     next if ( $Conf{$progName} eq "" || -x $Conf{$progName} );
256     print(STDERR $bpc->timeStamp,
257     "\$Conf{$progName} = '$Conf{$progName}' is not a"
258     . " valid executable program\n");
259     exit(1);
260     }
261    
262     if ( $opts{d} ) {
263     #
264 dpavlin 316 # daemonize by forking; more robust method per:
265     # http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=301057
266 dpavlin 1 #
267 dpavlin 316 my $pid;
268     defined($pid = fork) or die("Can't fork: $!");
269     exit if( $pid ); # parent exits
270    
271     POSIX::setsid();
272     defined($pid = fork) or die("Can't fork: $!");
273 dpavlin 1 exit if $pid; # parent exits
274 dpavlin 316
275     chdir ("/") or die("Cannot chdir to /: $!\n");
276     close(STDIN);
277     open(STDIN , ">/dev/null") or die("Cannot open /dev/null as stdin\n");
278     # STDOUT and STDERR are handled in LogFileOpen() right below,
279     # otherwise we would have to reopen them too.
280 dpavlin 1 }
281    
282     #
283     # Open the LOG file and redirect STDOUT, STDERR etc
284     #
285     LogFileOpen();
286    
287     #
288     # Read the hosts file (force a read).
289     #
290     exit(1) if ( !HostsUpdate(1) );
291    
292     #
293     # Clean up %ENV for taint checking
294     #
295     delete @ENV{qw(IFS CDPATH ENV BASH_ENV)};
296     $ENV{PATH} = $Conf{MyPath};
297    
298     #
299     # Initialize server sockets
300     #
301     ServerSocketInit();
302    
303     #
304     # Catch various signals
305     #
306     foreach my $sig ( qw(INT BUS SEGV PIPE TERM ALRM HUP) ) {
307     $SIG{$sig} = \&catch_signal;
308     }
309    
310     #
311     # Report that we started, and update %Info.
312     #
313     print(LOG $bpc->timeStamp, "BackupPC started, pid $$\n");
314     $Info{ConfigModTime} = $bpc->ConfigMTime();
315     $Info{pid} = $$;
316     $Info{startTime} = time;
317     $Info{ConfigLTime} = time;
318     $Info{Version} = $bpc->{Version};
319    
320     #
321     # Update the status left over form the last time BackupPC ran.
322     # Requeue any pending links.
323     #
324     foreach my $host ( sort(keys(%$Hosts)) ) {
325     if ( $Status{$host}{state} eq "Status_backup_in_progress" ) {
326     #
327     # should we restart it? skip it for now.
328     #
329     $Status{$host}{state} = "Status_idle";
330     } elsif ( $Status{$host}{state} eq "Status_link_pending"
331     || $Status{$host}{state} eq "Status_link_running" ) {
332     QueueLink($host);
333     } else {
334     $Status{$host}{state} = "Status_idle";
335     }
336     $Status{$host}{activeJob} = 0;
337     }
338     foreach my $host ( sort(keys(%Status)) ) {
339     next if ( defined($Hosts->{$host}) );
340     delete($Status{$host});
341     }
342    
343     #
344     # Write out our initial status and save our PID
345     #
346     StatusWrite();
347     if ( open(PID, ">", "$TopDir/log/BackupPC.pid") ) {
348     print(PID $$);
349     close(PID);
350     }
351    
352     #
353     # For unknown reasons there is a very infrequent error about not
354     # being able to coerce GLOBs inside the XS Data::Dumper. I've
355     # only seen this on a particular platform and perl version.
356     # For now the workaround appears to be use the perl version of
357     # XS Data::Dumper.
358     #
359     $Data::Dumper::Useqq = 1;
360     }
361    
362     ############################################################################
363     # Main_TryToRun_nightly()
364     #
365     # Checks to see if we can/should run BackupPC_nightly or
366     # BackupPC_trashClean. If so we push the appropriate command onto
367     # @CmdQueue.
368     ############################################################################
369     sub Main_TryToRun_nightly
370     {
371     #
372     # Check if we should run BackupPC_nightly or BackupPC_trashClean.
373     # BackupPC_nightly is run when the current job queue is empty.
374     # BackupPC_trashClean is run in the background always.
375     #
376     my $trashCleanRunning = defined($Jobs{$bpc->trashJob}) ? 1 : 0;
377     if ( !$trashCleanRunning && !$CmdQueueOn{$bpc->trashJob} ) {
378     #
379     # This should only happen once at startup, but just in case this
380     # code will re-start BackupPC_trashClean if it quits
381     #
382     unshift(@CmdQueue, {
383     host => $bpc->trashJob,
384     user => "BackupPC",
385     reqTime => time,
386     cmd => ["$BinDir/BackupPC_trashClean"],
387     });
388     $CmdQueueOn{$bpc->trashJob} = 1;
389     }
390     if ( keys(%Jobs) == $trashCleanRunning && $RunNightlyWhenIdle == 1 ) {
391    
392     #
393     # Queue multiple nightly jobs based on the configuration
394     #
395     $Conf{MaxBackupPCNightlyJobs} = 1
396     if ( $Conf{MaxBackupPCNightlyJobs} <= 0 );
397     $Conf{BackupPCNightlyPeriod} = 1
398     if ( $Conf{BackupPCNightlyPeriod} <= 0 );
399     #
400     # Decide what subset of the 16 top-level directories 0..9a..f
401     # we run BackupPC_nightly on, based on $Conf{BackupPCNightlyPeriod}.
402     # If $Conf{BackupPCNightlyPeriod} == 1 then we run 0..15 every
403     # time. If $Conf{BackupPCNightlyPeriod} == 2 then we run
404     # 0..7 one night and 89a-f the next night. And so on.
405     #
406     # $Info{NightlyPhase} counts which night, from 0 to
407     # $Conf{BackupPCNightlyPeriod} - 1.
408     #
409     my $start = int($Info{NightlyPhase} * 16
410     / $Conf{BackupPCNightlyPeriod});
411     my $end = int(($Info{NightlyPhase} + 1) * 16
412     / $Conf{BackupPCNightlyPeriod});
413     $end = $start + 1 if ( $end <= $start );
414     $Info{NightlyPhase}++;
415     $Info{NightlyPhase} = 0 if ( $end >= 16 );
416    
417     #
418     # Zero out the data we expect to get from BackupPC_nightly.
419     # In the future if we want to split BackupPC_nightly over
420     # more than one night we will only zero out the portion
421     # that we are running right now.
422     #
423     for my $p ( qw(pool cpool) ) {
424     for ( my $i = $start ; $i < $end ; $i++ ) {
425     $Info{pool}{$p}[$i]{FileCnt} = 0;
426     $Info{pool}{$p}[$i]{DirCnt} = 0;
427     $Info{pool}{$p}[$i]{Kb} = 0;
428     $Info{pool}{$p}[$i]{Kb2} = 0;
429     $Info{pool}{$p}[$i]{KbRm} = 0;
430     $Info{pool}{$p}[$i]{FileCntRm} = 0;
431     $Info{pool}{$p}[$i]{FileCntRep} = 0;
432     $Info{pool}{$p}[$i]{FileRepMax} = 0;
433     $Info{pool}{$p}[$i]{FileCntRename} = 0;
434     $Info{pool}{$p}[$i]{FileLinkMax} = 0;
435     $Info{pool}{$p}[$i]{Time} = 0;
436     }
437     }
438     print(LOG $bpc->timeStamp,
439     sprintf("Running %d BackupPC_nightly jobs from %d..%d"
440     . " (out of 0..15)\n",
441     $Conf{MaxBackupPCNightlyJobs}, $start, $end - 1));
442    
443     #
444     # Now queue the $Conf{MaxBackupPCNightlyJobs} jobs.
445     # The granularity on start and end is now 0..256.
446     #
447     $start *= 16;
448     $end *= 16;
449     my $start0 = $start;
450     for ( my $i = 0 ; $i < $Conf{MaxBackupPCNightlyJobs} ; $i++ ) {
451     #
452     # The first nightly job gets the -m option (does email, log aging).
453     # All jobs get the start and end options from 0..255 telling
454     # them which parts of the pool to traverse.
455     #
456     my $cmd = ["$BinDir/BackupPC_nightly"];
457     push(@$cmd, "-m") if ( $i == 0 );
458     push(@$cmd, $start);
459     $start = $start0 + int(($end - $start0)
460     * ($i + 1) / $Conf{MaxBackupPCNightlyJobs});
461     push(@$cmd, $start - 1);
462    
463     my $job = $bpc->adminJob($i);
464     unshift(@CmdQueue, {
465     host => $job,
466     user => "BackupPC",
467     reqTime => time,
468     cmd => $cmd,
469     });
470     $CmdQueueOn{$job} = 1;
471     }
472     $RunNightlyWhenIdle = 2;
473    
474     }
475     }
476    
477     ############################################################################
478     # Main_TryToRun_CmdQueue()
479     #
480     # Decide if we can run a new command from the @CmdQueue.
481     # We only run one of these at a time. The @CmdQueue is
482     # used to run BackupPC_link (for the corresponding host),
483     # BackupPC_trashClean, and BackupPC_nightly using a fake
484     # host name of $bpc->adminJob.
485     ############################################################################
486     sub Main_TryToRun_CmdQueue
487     {
488     my($req, $host);
489    
490     while ( $CmdJob eq "" && @CmdQueue > 0 && $RunNightlyWhenIdle != 1
491     || @CmdQueue > 0 && $RunNightlyWhenIdle == 2
492     && $bpc->isAdminJob($CmdQueue[0]->{host})
493     ) {
494     local(*FH);
495     $req = pop(@CmdQueue);
496    
497     $host = $req->{host};
498     if ( defined($Jobs{$host}) ) {
499     print(LOG $bpc->timeStamp,
500     "Botch on admin job for $host: already in use!!\n");
501     #
502     # This could happen during normal opertion: a user could
503     # request a backup while a BackupPC_link is queued from
504     # a previous backup. But it is unlikely. Just put this
505     # request back on the end of the queue.
506     #
507     unshift(@CmdQueue, $req);
508     return;
509     }
510     $CmdQueueOn{$host} = 0;
511     my $cmd = $req->{cmd};
512     my $pid = open(FH, "-|");
513     if ( !defined($pid) ) {
514     print(LOG $bpc->timeStamp,
515     "can't fork for $host, request by $req->{user}\n");
516     close(FH);
517     next;
518     }
519     if ( !$pid ) {
520     setpgrp 0,0;
521     exec(@$cmd);
522     print(LOG $bpc->timeStamp, "can't exec @$cmd for $host\n");
523     exit(0);
524     }
525     $Jobs{$host}{pid} = $pid;
526     $Jobs{$host}{fh} = *FH;
527     $Jobs{$host}{fn} = fileno(FH);
528     vec($FDread, $Jobs{$host}{fn}, 1) = 1;
529     $Jobs{$host}{startTime} = time;
530     $Jobs{$host}{reqTime} = $req->{reqTime};
531     $cmd = $bpc->execCmd2ShellCmd(@$cmd);
532     $Jobs{$host}{cmd} = $cmd;
533     $Jobs{$host}{user} = $req->{user};
534     $Jobs{$host}{type} = $Status{$host}{type};
535     $Status{$host}{state} = "Status_link_running";
536     $Status{$host}{activeJob} = 1;
537     $Status{$host}{endTime} = time;
538     $CmdJob = $host if ( $host ne $bpc->trashJob );
539     $cmd =~ s/$BinDir\///g;
540     print(LOG $bpc->timeStamp, "Running $cmd (pid=$pid)\n");
541     if ( $cmd =~ /^BackupPC_nightly\s/ ) {
542     $BackupPCNightlyJobs++;
543     $BackupPCNightlyLock++;
544     }
545     }
546     }
547    
548     ############################################################################
549     # Main_TryToRun_Bg_or_User_Queue()
550     #
551     # Decide if we can run any new backup requests from @BgQueue
552     # or @UserQueue. Several of these can be run at the same time
553     # based on %Conf settings. Jobs from @UserQueue take priority,
554     # and at total of $Conf{MaxBackups} + $Conf{MaxUserBackups}
555     # simultaneous jobs can run from @UserQueue. After @UserQueue
556     # is exhausted, up to $Conf{MaxBackups} simultaneous jobs can
557     # run from @BgQueue.
558     ############################################################################
559     sub Main_TryToRun_Bg_or_User_Queue
560     {
561     my($req, $host);
562     while ( $RunNightlyWhenIdle == 0 ) {
563     local(*FH);
564     my(@args, @deferUserQueue, @deferBgQueue, $progName, $type);
565     my $nJobs = keys(%Jobs);
566     #
567     # CmdJob and trashClean don't count towards MaxBackups / MaxUserBackups
568     #
569     $nJobs -= $BackupPCNightlyJobs if ( $CmdJob ne "" );
570     $nJobs-- if ( defined($Jobs{$bpc->trashJob} ) );
571     if ( $nJobs < $Conf{MaxBackups} + $Conf{MaxUserBackups}
572     && @UserQueue > 0 ) {
573     $req = pop(@UserQueue);
574     if ( defined($Jobs{$req->{host}}) ) {
575     push(@deferUserQueue, $req);
576     next;
577     }
578     push(@args, $req->{doFull} ? "-f" : "-i")
579     if (( !$req->{restore} ) && ( !$req->{archive} ));
580     $UserQueueOn{$req->{host}} = 0;
581     } elsif ( $nJobs < $Conf{MaxBackups}
582     && (@CmdQueue + $nJobs)
583     <= $Conf{MaxBackups} + $Conf{MaxPendingCmds}
584     && @BgQueue > 0 ) {
585     my $du;
586     if ( time - $Info{DUlastValueTime} >= 60 ) {
587     #
588     # Update our notion of disk usage no more than
589     # once every minute
590     #
591     $du = $bpc->CheckFileSystemUsage($TopDir);
592     $Info{DUlastValue} = $du;
593     $Info{DUlastValueTime} = time;
594     } else {
595     #
596     # if we recently checked it then just use the old value
597     #
598     $du = $Info{DUlastValue};
599     }
600     if ( $Info{DUDailyMaxReset} ) {
601     $Info{DUDailyMaxStartTime} = time;
602     $Info{DUDailyMaxReset} = 0;
603     $Info{DUDailyMax} = 0;
604     }
605     if ( $du > $Info{DUDailyMax} ) {
606     $Info{DUDailyMax} = $du;
607     $Info{DUDailyMaxTime} = time;
608     }
609     if ( $du > $Conf{DfMaxUsagePct} ) {
610     my $nSkip = @BgQueue + @deferBgQueue;
611     print(LOG $bpc->timeStamp,
612     "Disk too full ($du%); skipping $nSkip hosts\n");
613     $Info{DUDailySkipHostCnt} += $nSkip;
614     @BgQueue = ();
615     @deferBgQueue = ();
616     %BgQueueOn = ();
617     next;
618     }
619     $req = pop(@BgQueue);
620     if ( defined($Jobs{$req->{host}}) ) {
621     push(@deferBgQueue, $req);
622     next;
623     }
624     $BgQueueOn{$req->{host}} = 0;
625     } else {
626     while ( @deferBgQueue ) {
627     push(@BgQueue, pop(@deferBgQueue));
628     }
629     while ( @deferUserQueue ) {
630     push(@UserQueue, pop(@deferUserQueue));
631     }
632     last;
633     }
634     $host = $req->{host};
635     my $user = $req->{user};
636     if ( $req->{restore} ) {
637     $progName = "BackupPC_restore";
638     $type = "restore";
639     push(@args, $req->{hostIP}, $req->{host}, $req->{reqFileName});
640     } elsif ( $req->{archive} ) {
641     $progName = "BackupPC_archive";
642     $type = "archive";
643     push(@args, $req->{user}, $req->{host}, $req->{reqFileName});
644     } else {
645     $progName = "BackupPC_dump";
646     $type = "backup";
647     push(@args, "-d") if ( $req->{dhcp} );
648     push(@args, "-e") if ( $req->{dumpExpire} );
649     push(@args, $host);
650     }
651     my $pid = open(FH, "-|");
652     if ( !defined($pid) ) {
653     print(LOG $bpc->timeStamp,
654     "can't fork to run $progName for $host, request by $user\n");
655     close(FH);
656     next;
657     }
658     if ( !$pid ) {
659     setpgrp 0,0;
660     exec("$BinDir/$progName", @args);
661     print(LOG $bpc->timeStamp, "can't exec $progName for $host\n");
662     exit(0);
663     }
664     $Jobs{$host}{pid} = $pid;
665     $Jobs{$host}{fh} = *FH;
666     $Jobs{$host}{fn} = fileno(FH);
667     $Jobs{$host}{dhcp} = $req->{dhcp};
668     vec($FDread, $Jobs{$host}{fn}, 1) = 1;
669     $Jobs{$host}{startTime} = time;
670     $Jobs{$host}{reqTime} = $req->{reqTime};
671     $Jobs{$host}{userReq} = $req->{userReq};
672     $Jobs{$host}{cmd} = $bpc->execCmd2ShellCmd($progName, @args);
673     $Jobs{$host}{user} = $user;
674     $Jobs{$host}{type} = $type;
675     $Status{$host}{userReq} = $req->{userReq}
676     if ( defined($Hosts->{$host}) );
677     if ( !$req->{dhcp} ) {
678     $Status{$host}{state} = "Status_".$type."_starting";
679     $Status{$host}{activeJob} = 1;
680     $Status{$host}{startTime} = time;
681     $Status{$host}{endTime} = "";
682     }
683     }
684     }
685    
686     ############################################################################
687     # Main_Select()
688     #
689     # If necessary, figure out when to next wakeup based on $Conf{WakeupSchedule},
690     # and then do a select() to wait for the next thing to happen
691     # (timeout, signal, someone sends a message, child dies etc).
692     ############################################################################
693     sub Main_Select
694     {
695     if ( $NextWakeup <= 0 ) {
696     #
697     # Figure out when to next wakeup based on $Conf{WakeupSchedule}.
698     #
699     my($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)
700     = localtime(time);
701     my($currHours) = $hour + $min / 60 + $sec / 3600;
702     if ( $bpc->ConfigMTime() != $Info{ConfigModTime} ) {
703     ServerReload("Re-read config file because mtime changed");
704     }
705     my $delta = -1;
706     foreach my $t ( @{$Conf{WakeupSchedule} || [0..23]} ) {
707     next if ( $t < 0 || $t > 24 );
708     my $tomorrow = $t + 24;
709     if ( $delta < 0
710     || ($tomorrow - $currHours > 0
711     && $delta > $tomorrow - $currHours) ) {
712     $delta = $tomorrow - $currHours;
713     $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
714     }
715     if ( $delta < 0
716     || ($t - $currHours > 0 && $delta > $t - $currHours) ) {
717     $delta = $t - $currHours;
718     $FirstWakeup = $t == $Conf{WakeupSchedule}[0];
719     }
720     }
721     $NextWakeup = time + $delta * 3600;
722     $Info{nextWakeup} = $NextWakeup;
723     print(LOG $bpc->timeStamp, "Next wakeup is ",
724     $bpc->timeStamp($NextWakeup, 1), "\n");
725     }
726     #
727     # Call select(), waiting until either a signal, a timeout,
728     # any output from our jobs, or any messages from clients
729     # connected via tcp.
730     # select() is where we (hopefully) spend most of our time blocked...
731     #
732     my $timeout = $NextWakeup - time;
733     $timeout = 1 if ( $timeout <= 0 );
734     my $ein = $FDread;
735     select(my $rout = $FDread, undef, $ein, $timeout);
736    
737     return $rout;
738     }
739    
740     ############################################################################
741     # Main_Process_Signal()
742     #
743     # Signal handler.
744     ############################################################################
745     sub Main_Process_Signal
746     {
747     #
748     # Process signals
749     #
750     if ( $SigName eq "HUP" ) {
751     ServerReload("Re-read config file because of a SIG_HUP");
752     } elsif ( $SigName ) {
753     ServerShutdown("Got signal $SigName... cleaning up");
754     }
755     $SigName = "";
756     }
757    
758     ############################################################################
759     # Main_Check_Timeout()
760     #
761     # Check if a timeout has occured, and if so, queue all the PCs for backups.
762     # Also does log file aging on the first timeout after midnight.
763     ############################################################################
764     sub Main_Check_Timeout
765     {
766     #
767     # Process timeouts
768     #
769     return if ( time < $NextWakeup || $NextWakeup <= 0 );
770     $NextWakeup = 0;
771     if ( $FirstWakeup ) {
772     #
773     # This is the first wakeup after midnight. Do log file aging
774     # and various house keeping.
775     #
776     $FirstWakeup = 0;
777     printf(LOG "%s24hr disk usage: %d%% max, %d%% recent,"
778     . " %d skipped hosts\n",
779     $bpc->timeStamp, $Info{DUDailyMax}, $Info{DUlastValue},
780     $Info{DUDailySkipHostCnt});
781     $Info{DUDailyMaxReset} = 1;
782     $Info{DUDailyMaxPrev} = $Info{DUDailyMax};
783     $Info{DUDailySkipHostCntPrev} = $Info{DUDailySkipHostCnt};
784     $Info{DUDailySkipHostCnt} = 0;
785     my $lastLog = $Conf{MaxOldLogFiles} - 1;
786     if ( -f "$TopDir/log/LOG.$lastLog" ) {
787     print(LOG $bpc->timeStamp,
788     "Removing $TopDir/log/LOG.$lastLog\n");
789     unlink("$TopDir/log/LOG.$lastLog");
790     }
791     if ( -f "$TopDir/log/LOG.$lastLog.z" ) {
792     print(LOG $bpc->timeStamp,
793     "Removing $TopDir/log/LOG.$lastLog.z\n");
794     unlink("$TopDir/log/LOG.$lastLog.z");
795     }
796     print(LOG $bpc->timeStamp, "Aging LOG files, LOG -> LOG.0 -> "
797     . "LOG.1 -> ... -> LOG.$lastLog\n");
798     close(STDERR); # dup of LOG
799     close(STDOUT); # dup of LOG
800     close(LOG);
801     for ( my $i = $lastLog - 1 ; $i >= 0 ; $i-- ) {
802     my $j = $i + 1;
803     rename("$TopDir/log/LOG.$i", "$TopDir/log/LOG.$j")
804     if ( -f "$TopDir/log/LOG.$i" );
805     rename("$TopDir/log/LOG.$i.z", "$TopDir/log/LOG.$j.z")
806     if ( -f "$TopDir/log/LOG.$i.z" );
807     }
808     #
809     # Compress the log file LOG -> LOG.0.z (if enabled).
810     # Otherwise, just rename LOG -> LOG.0.
811     #
812     BackupPC::FileZIO->compressCopy("$TopDir/log/LOG",
813     "$TopDir/log/LOG.0.z",
814     "$TopDir/log/LOG.0",
815     $Conf{CompressLevel}, 1);
816     LogFileOpen();
817     #
818     # Remember to run nightly script after current jobs are done
819     #
820     $RunNightlyWhenIdle = 1;
821     }
822     #
823     # Write out the current status and then queue all the PCs
824     #
825     HostsUpdate(0);
826     StatusWrite();
827     %BgQueueOn = () if ( @BgQueue == 0 );
828     %UserQueueOn = () if ( @UserQueue == 0 );
829     %CmdQueueOn = () if ( @CmdQueue == 0 );
830     QueueAllPCs();
831     }
832    
833     ############################################################################
834     # Main_Check_Job_Messages($fdRead)
835     #
836     # Check if select() says we have bytes waiting from any of our jobs.
837     # Handle each of the messages when complete (newline terminated).
838     ############################################################################
839     sub Main_Check_Job_Messages
840     {
841     my($fdRead) = @_;
842     foreach my $host ( keys(%Jobs) ) {
843     next if ( !vec($fdRead, $Jobs{$host}{fn}, 1) );
844     my $mesg;
845     #
846     # do a last check to make sure there is something to read so
847     # we are absolutely sure we won't block.
848     #
849     vec(my $readMask, $Jobs{$host}{fn}, 1) = 1;
850     if ( !select($readMask, undef, undef, 0.0) ) {
851     print(LOG $bpc->timeStamp, "Botch in Main_Check_Job_Messages:"
852     . " nothing to read from $host. Debug dump:\n");
853     my($dump) = Data::Dumper->new(
854     [ \%Clients, \%Jobs, \$FDread, \$fdRead],
855     [qw(*Clients, *Jobs *FDread, *fdRead)]);
856     $dump->Indent(1);
857     print(LOG $dump->Dump);
858     next;
859     }
860     my $nbytes = sysread($Jobs{$host}{fh}, $mesg, 1024);
861     $Jobs{$host}{mesg} .= $mesg if ( $nbytes > 0 );
862     #
863     # Process any complete lines of output from this jobs.
864     # Any output to STDOUT or STDERR from the children is processed here.
865     #
866     while ( $Jobs{$host}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
867     $mesg = $1;
868     $Jobs{$host}{mesg} = $2;
869     if ( $Jobs{$host}{dhcp} ) {
870     if ( $mesg =~ /^DHCP (\S+) (\S+)/ ) {
871     my $newHost = $bpc->uriUnesc($2);
872     if ( defined($Jobs{$newHost}) ) {
873     print(LOG $bpc->timeStamp,
874     "Backup on $newHost is already running\n");
875     kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
876     $nbytes = 0;
877     last;
878     }
879     $Jobs{$host}{dhcpHostIP} = $host;
880     $Status{$newHost}{dhcpHostIP} = $host;
881     $Jobs{$newHost} = $Jobs{$host};
882     delete($Jobs{$host});
883     $host = $newHost;
884     $Status{$host}{state} = "Status_backup_starting";
885     $Status{$host}{activeJob} = 1;
886     $Status{$host}{startTime} = $Jobs{$host}{startTime};
887     $Status{$host}{endTime} = "";
888     $Jobs{$host}{dhcp} = 0;
889     } else {
890     print(LOG $bpc->timeStamp, "dhcp $host: $mesg\n");
891     }
892     } elsif ( $mesg =~ /^started (.*) dump, share=(.*)/ ) {
893     $Jobs{$host}{type} = $1;
894     $Jobs{$host}{shareName} = $2;
895     print(LOG $bpc->timeStamp,
896     "Started $1 backup on $host (pid=$Jobs{$host}{pid}",
897     $Jobs{$host}{dhcpHostIP}
898     ? ", dhcp=$Jobs{$host}{dhcpHostIP}" : "",
899     ", share=$Jobs{$host}{shareName})\n");
900     $Status{$host}{state} = "Status_backup_in_progress";
901     $Status{$host}{reason} = "";
902     $Status{$host}{type} = $1;
903     $Status{$host}{startTime} = time;
904     $Status{$host}{deadCnt} = 0;
905     $Status{$host}{aliveCnt}++;
906     $Status{$host}{dhcpCheckCnt}--
907     if ( $Status{$host}{dhcpCheckCnt} > 0 );
908     } elsif ( $mesg =~ /^xferPids (.*)/ ) {
909     $Jobs{$host}{xferPid} = $1;
910     } elsif ( $mesg =~ /^started_restore/ ) {
911     $Jobs{$host}{type} = "restore";
912     print(LOG $bpc->timeStamp,
913     "Started restore on $host"
914     . " (pid=$Jobs{$host}{pid})\n");
915     $Status{$host}{state} = "Status_restore_in_progress";
916     $Status{$host}{reason} = "";
917     $Status{$host}{type} = "restore";
918     $Status{$host}{startTime} = time;
919     $Status{$host}{deadCnt} = 0;
920     $Status{$host}{aliveCnt}++;
921     } elsif ( $mesg =~ /^started_archive/ ) {
922     $Jobs{$host}{type} = "archive";
923     print(LOG $bpc->timeStamp,
924     "Started archive on $host"
925     . " (pid=$Jobs{$host}{pid})\n");
926     $Status{$host}{state} = "Status_archive_in_progress";
927     $Status{$host}{reason} = "";
928     $Status{$host}{type} = "archive";
929     $Status{$host}{startTime} = time;
930     $Status{$host}{deadCnt} = 0;
931     $Status{$host}{aliveCnt}++;
932     } elsif ( $mesg =~ /^(full|incr) backup complete/ ) {
933     print(LOG $bpc->timeStamp, "Finished $1 backup on $host\n");
934     $Status{$host}{reason} = "Reason_backup_done";
935     delete($Status{$host}{error});
936     delete($Status{$host}{errorTime});
937     $Status{$host}{endTime} = time;
938 dpavlin 316 $Status{$host}{lastGoodBackupTime} = time;
939 dpavlin 1 } elsif ( $mesg =~ /^backups disabled/ ) {
940     print(LOG $bpc->timeStamp,
941     "Ignoring old backup error on $host\n");
942     $Status{$host}{reason} = "Reason_backup_done";
943     delete($Status{$host}{error});
944     delete($Status{$host}{errorTime});
945     $Status{$host}{endTime} = time;
946     } elsif ( $mesg =~ /^restore complete/ ) {
947     print(LOG $bpc->timeStamp, "Finished restore on $host\n");
948     $Status{$host}{reason} = "Reason_restore_done";
949     delete($Status{$host}{error});
950     delete($Status{$host}{errorTime});
951     $Status{$host}{endTime} = time;
952     } elsif ( $mesg =~ /^archive complete/ ) {
953     print(LOG $bpc->timeStamp, "Finished archive on $host\n");
954     $Status{$host}{reason} = "Reason_archive_done";
955     delete($Status{$host}{error});
956     delete($Status{$host}{errorTime});
957     $Status{$host}{endTime} = time;
958     } elsif ( $mesg =~ /^nothing to do/ ) {
959     if ( $Status{$host}{reason} ne "Reason_backup_failed"
960     && $Status{$host}{reason} ne "Reason_restore_failed" ) {
961     $Status{$host}{state} = "Status_idle";
962     $Status{$host}{reason} = "Reason_nothing_to_do";
963     $Status{$host}{startTime} = time;
964     }
965     $Status{$host}{dhcpCheckCnt}--
966     if ( $Status{$host}{dhcpCheckCnt} > 0 );
967     } elsif ( $mesg =~ /^no ping response/
968     || $mesg =~ /^ping too slow/
969     || $mesg =~ /^host not found/ ) {
970     $Status{$host}{state} = "Status_idle";
971     if ( $Status{$host}{userReq}
972     || $Status{$host}{reason} ne "Reason_backup_failed"
973     || $Status{$host}{error} =~ /^aborted by user/ ) {
974     $Status{$host}{reason} = "Reason_no_ping";
975     $Status{$host}{error} = $mesg;
976     $Status{$host}{startTime} = time;
977     }
978     $Status{$host}{deadCnt}++;
979     if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
980     $Status{$host}{aliveCnt} = 0;
981     }
982     } elsif ( $mesg =~ /^dump failed: (.*)/ ) {
983     $Status{$host}{state} = "Status_idle";
984     $Status{$host}{error} = $1;
985     $Status{$host}{errorTime} = time;
986     $Status{$host}{endTime} = time;
987     if ( $Status{$host}{reason}
988     eq "Reason_backup_canceled_by_user" ) {
989     print(LOG $bpc->timeStamp,
990     "Backup canceled on $host ($1)\n");
991     } else {
992     $Status{$host}{reason} = "Reason_backup_failed";
993     print(LOG $bpc->timeStamp,
994     "Backup failed on $host ($1)\n");
995     }
996     } elsif ( $mesg =~ /^restore failed: (.*)/ ) {
997     $Status{$host}{state} = "Status_idle";
998     $Status{$host}{error} = $1;
999     $Status{$host}{errorTime} = time;
1000     $Status{$host}{endTime} = time;
1001     if ( $Status{$host}{reason}
1002     eq "Reason_restore_canceled_by_user" ) {
1003     print(LOG $bpc->timeStamp,
1004     "Restore canceled on $host ($1)\n");
1005     } else {
1006     $Status{$host}{reason} = "Reason_restore_failed";
1007     print(LOG $bpc->timeStamp,
1008     "Restore failed on $host ($1)\n");
1009     }
1010     } elsif ( $mesg =~ /^archive failed: (.*)/ ) {
1011     $Status{$host}{state} = "Status_idle";
1012     $Status{$host}{error} = $1;
1013     $Status{$host}{errorTime} = time;
1014     $Status{$host}{endTime} = time;
1015     if ( $Status{$host}{reason}
1016     eq "Reason_archive_canceled_by_user" ) {
1017     print(LOG $bpc->timeStamp,
1018     "Archive canceled on $host ($1)\n");
1019     } else {
1020     $Status{$host}{reason} = "Reason_archive_failed";
1021     print(LOG $bpc->timeStamp,
1022     "Archive failed on $host ($1)\n");
1023     }
1024     } elsif ( $mesg =~ /^log\s+(.*)/ ) {
1025     print(LOG $bpc->timeStamp, "$1\n");
1026     } elsif ( $mesg =~ /^BackupPC_stats (\d+) = (.*)/ ) {
1027     my $chunk = int($1 / 16);
1028     my @f = split(/,/, $2);
1029     $Info{pool}{$f[0]}[$chunk]{FileCnt} += $f[1];
1030     $Info{pool}{$f[0]}[$chunk]{DirCnt} += $f[2];
1031     $Info{pool}{$f[0]}[$chunk]{Kb} += $f[3];
1032     $Info{pool}{$f[0]}[$chunk]{Kb2} += $f[4];
1033     $Info{pool}{$f[0]}[$chunk]{KbRm} += $f[5];
1034     $Info{pool}{$f[0]}[$chunk]{FileCntRm} += $f[6];
1035     $Info{pool}{$f[0]}[$chunk]{FileCntRep} += $f[7];
1036     $Info{pool}{$f[0]}[$chunk]{FileRepMax} = $f[8]
1037     if ( $Info{pool}{$f[0]}[$chunk]{FileRepMax} < $f[8] );
1038     $Info{pool}{$f[0]}[$chunk]{FileCntRename} += $f[9];
1039     $Info{pool}{$f[0]}[$chunk]{FileLinkMax} = $f[10]
1040     if ( $Info{pool}{$f[0]}[$chunk]{FileLinkMax} < $f[10] );
1041     $Info{pool}{$f[0]}[$chunk]{Time} = time;
1042     } elsif ( $mesg =~ /^BackupPC_nightly lock_off/ ) {
1043     $BackupPCNightlyLock--;
1044     if ( $BackupPCNightlyLock == 0 ) {
1045     #
1046     # This means the last BackupPC_nightly is done with
1047     # the pool clean, so it's to start running regular
1048     # backups again.
1049     #
1050     $RunNightlyWhenIdle = 0;
1051     }
1052     } elsif ( $mesg =~ /^processState\s+(.+)/ ) {
1053     $Jobs{$host}{processState} = $1;
1054     } elsif ( $mesg =~ /^link\s+(.+)/ ) {
1055     my($h) = $1;
1056     $Status{$h}{needLink} = 1;
1057     } else {
1058     print(LOG $bpc->timeStamp, "$host: $mesg\n");
1059     }
1060     }
1061     #
1062     # shut down the client connection if we read EOF
1063     #
1064     if ( $nbytes <= 0 ) {
1065     close($Jobs{$host}{fh});
1066     vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1067     if ( $CmdJob eq $host || $bpc->isAdminJob($host) ) {
1068     my $cmd = $Jobs{$host}{cmd};
1069     $cmd =~ s/$BinDir\///g;
1070     print(LOG $bpc->timeStamp, "Finished $host ($cmd)\n");
1071     $Status{$host}{state} = "Status_idle";
1072     $Status{$host}{endTime} = time;
1073     if ( $cmd =~ /^BackupPC_nightly\s/ ) {
1074     $BackupPCNightlyJobs--;
1075     #print(LOG $bpc->timeStamp, "BackupPC_nightly done; now"
1076     # . " have $BackupPCNightlyJobs running\n");
1077     if ( $BackupPCNightlyJobs <= 0 ) {
1078     $BackupPCNightlyJobs = 0;
1079     $RunNightlyWhenIdle = 0;
1080     $CmdJob = "";
1081     #
1082     # Combine the 16 per-directory results
1083     #
1084     for my $p ( qw(pool cpool) ) {
1085     $Info{"${p}FileCnt"} = 0;
1086     $Info{"${p}DirCnt"} = 0;
1087     $Info{"${p}Kb"} = 0;
1088     $Info{"${p}Kb2"} = 0;
1089     $Info{"${p}KbRm"} = 0;
1090     $Info{"${p}FileCntRm"} = 0;
1091     $Info{"${p}FileCntRep"} = 0;
1092     $Info{"${p}FileRepMax"} = 0;
1093     $Info{"${p}FileCntRename"} = 0;
1094     $Info{"${p}FileLinkMax"} = 0;
1095     $Info{"${p}Time"} = 0;
1096     for ( my $i = 0 ; $i < 16 ; $i++ ) {
1097     $Info{"${p}FileCnt"}
1098     += $Info{pool}{$p}[$i]{FileCnt};
1099     $Info{"${p}DirCnt"}
1100     += $Info{pool}{$p}[$i]{DirCnt};
1101     $Info{"${p}Kb"}
1102     += $Info{pool}{$p}[$i]{Kb};
1103     $Info{"${p}Kb2"}
1104     += $Info{pool}{$p}[$i]{Kb2};
1105     $Info{"${p}KbRm"}
1106     += $Info{pool}{$p}[$i]{KbRm};
1107     $Info{"${p}FileCntRm"}
1108     += $Info{pool}{$p}[$i]{FileCntRm};
1109     $Info{"${p}FileCntRep"}
1110     += $Info{pool}{$p}[$i]{FileCntRep};
1111     $Info{"${p}FileRepMax"}
1112     = $Info{pool}{$p}[$i]{FileRepMax}
1113     if ( $Info{"${p}FileRepMax"} <
1114     $Info{pool}{$p}[$i]{FileRepMax} );
1115     $Info{"${p}FileCntRename"}
1116     += $Info{pool}{$p}[$i]{FileCntRename};
1117     $Info{"${p}FileLinkMax"}
1118     = $Info{pool}{$p}[$i]{FileLinkMax}
1119     if ( $Info{"${p}FileLinkMax"} <
1120     $Info{pool}{$p}[$i]{FileLinkMax} );
1121     $Info{"${p}Time"} = $Info{pool}{$p}[$i]{Time}
1122     if ( $Info{"${p}Time"} <
1123     $Info{pool}{$p}[$i]{Time} );
1124     }
1125     printf(LOG "%s%s nightly clean removed %d files of"
1126     . " size %.2fGB\n",
1127     $bpc->timeStamp, ucfirst($p),
1128     $Info{"${p}FileCntRm"},
1129     $Info{"${p}KbRm"} / (1000 * 1024));
1130     printf(LOG "%s%s is %.2fGB, %d files (%d repeated, "
1131     . "%d max chain, %d max links), %d directories\n",
1132     $bpc->timeStamp, ucfirst($p),
1133     $Info{"${p}Kb"} / (1000 * 1024),
1134     $Info{"${p}FileCnt"}, $Info{"${p}FileCntRep"},
1135     $Info{"${p}FileRepMax"},
1136     $Info{"${p}FileLinkMax"}, $Info{"${p}DirCnt"});
1137     }
1138     }
1139     } else {
1140     $CmdJob = "";
1141     }
1142     } else {
1143     #
1144     # Queue BackupPC_link to complete the backup
1145     # processing for this host.
1146     #
1147     if ( defined($Status{$host})
1148     && ($Status{$host}{reason} eq "Reason_backup_done"
1149     || $Status{$host}{needLink}) ) {
1150     QueueLink($host);
1151     } elsif ( defined($Status{$host}) ) {
1152     $Status{$host}{state} = "Status_idle";
1153     }
1154     }
1155     delete($Jobs{$host});
1156     $Status{$host}{activeJob} = 0 if ( defined($Status{$host}) );
1157     }
1158     }
1159     #
1160     # When we are idle (empty Jobs, CmdQueue, BgQueue, UserQueue) we
1161     # do a pass over %Status updating the deadCnt and aliveCnt for
1162     # DHCP hosts. The reason we need to do this later is we can't
1163     # be sure whether a DHCP host is alive or dead until we have passed
1164     # over all the DHCP pool.
1165     #
1166     return if ( @CmdQueue || @BgQueue || @UserQueue || keys(%Jobs) > 1 );
1167     foreach my $host ( keys(%Status) ) {
1168     next if ( $Status{$host}{dhcpCheckCnt} <= 0 );
1169     $Status{$host}{deadCnt} += $Status{$host}{dhcpCheckCnt};
1170     $Status{$host}{dhcpCheckCnt} = 0;
1171     if ( $Status{$host}{deadCnt} >= $Conf{BlackoutBadPingLimit} ) {
1172     $Status{$host}{aliveCnt} = 0;
1173     }
1174     }
1175     }
1176    
1177     ############################################################################
1178     # Main_Check_Client_Messages($fdRead)
1179     #
1180     # Check for, and process, any output from our clients. Also checks
1181     # for new connections to our SERVER_UNIX and SERVER_INET sockets.
1182     ############################################################################
1183     sub Main_Check_Client_Messages
1184     {
1185     my($fdRead) = @_;
1186     foreach my $client ( keys(%Clients) ) {
1187     next if ( !vec($fdRead, $Clients{$client}{fn}, 1) );
1188     my($mesg, $host);
1189     #
1190     # do a last check to make sure there is something to read so
1191     # we are absolutely sure we won't block.
1192     #
1193     vec(my $readMask, $Clients{$client}{fn}, 1) = 1;
1194     if ( !select($readMask, undef, undef, 0.0) ) {
1195     print(LOG $bpc->timeStamp, "Botch in Main_Check_Client_Messages:"
1196     . " nothing to read from $client. Debug dump:\n");
1197     my($dump) = Data::Dumper->new(
1198     [ \%Clients, \%Jobs, \$FDread, \$fdRead],
1199     [qw(*Clients, *Jobs *FDread, *fdRead)]);
1200     $dump->Indent(1);
1201     print(LOG $dump->Dump);
1202     next;
1203     }
1204     my $nbytes = sysread($Clients{$client}{fh}, $mesg, 1024);
1205     $Clients{$client}{mesg} .= $mesg if ( $nbytes > 0 );
1206     #
1207     # Process any complete lines received from this client.
1208     #
1209     while ( $Clients{$client}{mesg} =~ /(.*?)[\n\r]+(.*)/s ) {
1210     my($reply);
1211     my $cmd = $1;
1212     $Clients{$client}{mesg} = $2;
1213     #
1214     # Authenticate the message by checking the MD5 digest
1215     #
1216     my $md5 = Digest::MD5->new;
1217     if ( $cmd !~ /^(.{22}) (.*)/
1218     || ($md5->add($Clients{$client}{seed}
1219     . $Clients{$client}{mesgCnt}
1220     . $Conf{ServerMesgSecret} . $2),
1221     $md5->b64digest ne $1) ) {
1222     print(LOG $bpc->timeStamp, "Corrupted message '$cmd' from"
1223     . " client '$Clients{$client}{clientName}':"
1224     . " shutting down client connection\n");
1225     $nbytes = 0;
1226     last;
1227     }
1228     $Clients{$client}{mesgCnt}++;
1229     $cmd = $2;
1230     if ( $cmd =~ /^stop (\S+)\s+(\S+)\s+(\S*)/ ) {
1231     $host = $1;
1232     my $user = $2;
1233     my $backoff = $3;
1234     $host = $bpc->uriUnesc($host);
1235     if ( $CmdJob ne $host && defined($Status{$host})
1236     && defined($Jobs{$host}) ) {
1237     print(LOG $bpc->timeStamp,
1238     "Stopping current $Jobs{$host}{type} of $host,"
1239     . " request by $user (backoff=$backoff)\n");
1240     kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1241     #
1242     # Don't close the pipe now; wait until the child
1243     # really exits later. Otherwise close() will
1244     # block until the child has exited.
1245     # old code:
1246     ##vec($FDread, $Jobs{$host}{fn}, 1) = 0;
1247     ##close($Jobs{$host}{fh});
1248     ##delete($Jobs{$host});
1249    
1250     $Status{$host}{state} = "Status_idle";
1251     if ( $Jobs{$host}{type} eq "restore" ) {
1252     $Status{$host}{reason}
1253     = "Reason_restore_canceled_by_user";
1254     } elsif ( $Jobs{$host}{type} eq "archive" ) {
1255     $Status{$host}{reason}
1256     = "Reason_archive_canceled_by_user";
1257     } else {
1258     $Status{$host}{reason}
1259     = "Reason_backup_canceled_by_user";
1260     }
1261     $Status{$host}{activeJob} = 0;
1262     $Status{$host}{startTime} = time;
1263     $reply = "ok: $Jobs{$host}{type} of $host canceled";
1264     } elsif ( $BgQueueOn{$host} || $UserQueueOn{$host} ) {
1265     print(LOG $bpc->timeStamp,
1266     "Stopping pending backup of $host,"
1267     . " request by $user (backoff=$backoff)\n");
1268     @BgQueue = grep($_->{host} ne $host, @BgQueue);
1269     @UserQueue = grep($_->{host} ne $host, @UserQueue);
1270     $BgQueueOn{$host} = $UserQueueOn{$host} = 0;
1271     $reply = "ok: pending backup of $host canceled";
1272     } else {
1273     print(LOG $bpc->timeStamp,
1274     "Nothing to do for stop backup of $host,"
1275     . " request by $user (backoff=$backoff)\n");
1276     $reply = "ok: no backup was pending or running";
1277     }
1278     if ( defined($Status{$host}) && $backoff ne "" ) {
1279     if ( $backoff > 0 ) {
1280     $Status{$host}{backoffTime} = time + $backoff * 3600;
1281     } else {
1282     delete($Status{$host}{backoffTime});
1283     }
1284     }
1285     } elsif ( $cmd =~ /^backup all$/ ) {
1286     QueueAllPCs();
1287     } elsif ( $cmd =~ /^BackupPC_nightly run$/ ) {
1288     $RunNightlyWhenIdle = 1;
1289     } elsif ( $cmd =~ /^backup (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1290     my $hostIP = $1;
1291     $host = $2;
1292     my $user = $3;
1293     my $doFull = $4;
1294     $host = $bpc->uriUnesc($host);
1295     $hostIP = $bpc->uriUnesc($hostIP);
1296     if ( !defined($Status{$host}) ) {
1297     print(LOG $bpc->timeStamp,
1298     "User $user requested backup of unknown host"
1299     . " $host\n");
1300     $reply = "error: unknown host $host";
1301     } elsif ( defined($Jobs{$host})
1302     && $Jobs{$host}{type} ne "restore" ) {
1303     print(LOG $bpc->timeStamp,
1304     "User $user requested backup of $host,"
1305     . " but one is currently running\n");
1306     $reply = "error: backup of $host is already running";
1307     } else {
1308     print(LOG $bpc->timeStamp,
1309     "User $user requested backup of $host"
1310     . " ($hostIP)\n");
1311     if ( $BgQueueOn{$hostIP} ) {
1312     @BgQueue = grep($_->{host} ne $hostIP, @BgQueue);
1313     $BgQueueOn{$hostIP} = 0;
1314     }
1315     if ( $UserQueueOn{$hostIP} ) {
1316     @UserQueue = grep($_->{host} ne $hostIP, @UserQueue);
1317     $UserQueueOn{$hostIP} = 0;
1318     }
1319     unshift(@UserQueue, {
1320     host => $hostIP,
1321     user => $user,
1322     reqTime => time,
1323     doFull => $doFull,
1324     userReq => 1,
1325     dhcp => $hostIP eq $host ? 0 : 1,
1326     });
1327     $UserQueueOn{$hostIP} = 1;
1328     $reply = "ok: requested backup of $host";
1329     }
1330     } elsif ( $cmd =~ /^archive (\S+)\s+(\S+)\s+(\S+)/ ) {
1331     my $user = $1;
1332     my $archivehost = $2;
1333     my $reqFileName = $3;
1334     $host = $bpc->uriUnesc($archivehost);
1335     if ( !defined($Status{$host}) ) {
1336     print(LOG $bpc->timeStamp,
1337     "User $user requested archive of unknown archive host"
1338     . " $host");
1339     $reply = "archive error: unknown archive host $host";
1340     } else {
1341     print(LOG $bpc->timeStamp,
1342     "User $user requested archive on $host"
1343     . " ($host)\n");
1344     if ( defined($Jobs{$host}) ) {
1345     $reply = "Archive currently running on $host, please try later";
1346     } else {
1347     unshift(@UserQueue, {
1348     host => $host,
1349     hostIP => $user,
1350     reqFileName => $reqFileName,
1351     reqTime => time,
1352     dhcp => 0,
1353     archive => 1,
1354     userReq => 1,
1355     });
1356     $UserQueueOn{$host} = 1;
1357     $reply = "ok: requested archive on $host";
1358     }
1359     }
1360     } elsif ( $cmd =~ /^restore (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
1361     my $hostIP = $1;
1362     $host = $2;
1363     my $user = $3;
1364     my $reqFileName = $4;
1365     $host = $bpc->uriUnesc($host);
1366     $hostIP = $bpc->uriUnesc($hostIP);
1367     if ( !defined($Status{$host}) ) {
1368     print(LOG $bpc->timeStamp,
1369     "User $user requested restore to unknown host"
1370     . " $host");
1371     $reply = "restore error: unknown host $host";
1372     } else {
1373     print(LOG $bpc->timeStamp,
1374     "User $user requested restore to $host"
1375     . " ($hostIP)\n");
1376     unshift(@UserQueue, {
1377     host => $host,
1378     hostIP => $hostIP,
1379     reqFileName => $reqFileName,
1380     reqTime => time,
1381     dhcp => 0,
1382     restore => 1,
1383     userReq => 1,
1384     });
1385     $UserQueueOn{$host} = 1;
1386     if ( defined($Jobs{$host}) ) {
1387     $reply = "ok: requested restore of $host, but a"
1388     . " job is currently running,"
1389     . " so this request will start later";
1390     } else {
1391     $reply = "ok: requested restore of $host";
1392     }
1393     }
1394     } elsif ( $cmd =~ /^status\s*(.*)/ ) {
1395     my($args) = $1;
1396     my($dump, @values, @names);
1397     foreach my $type ( split(/\s+/, $args) ) {
1398     if ( $type =~ /^queues/ ) {
1399     push(@values, \@BgQueue, \@UserQueue, \@CmdQueue);
1400     push(@names, qw(*BgQueue *UserQueue *CmdQueue));
1401     } elsif ( $type =~ /^jobs/ ) {
1402     push(@values, \%Jobs);
1403     push(@names, qw(*Jobs));
1404     } elsif ( $type =~ /^queueLen/ ) {
1405     push(@values, {
1406     BgQueue => scalar(@BgQueue),
1407     UserQueue => scalar(@UserQueue),
1408     CmdQueue => scalar(@CmdQueue),
1409     });
1410     push(@names, qw(*QueueLen));
1411     } elsif ( $type =~ /^info/ ) {
1412     push(@values, \%Info);
1413     push(@names, qw(*Info));
1414     } elsif ( $type =~ /^hosts/ ) {
1415     push(@values, \%Status);
1416     push(@names, qw(*Status));
1417     } elsif ( $type =~ /^host\((.*)\)/ ) {
1418     my $h = $bpc->uriUnesc($1);
1419     if ( defined($Status{$h}) ) {
1420     push(@values, {
1421     %{$Status{$h}},
1422     BgQueueOn => $BgQueueOn{$h},
1423     UserQueueOn => $UserQueueOn{$h},
1424     CmdQueueOn => $CmdQueueOn{$h},
1425     });
1426     push(@names, qw(*StatusHost));
1427     } else {
1428     print(LOG $bpc->timeStamp,
1429     "Unknown host $h for status request\n");
1430     }
1431     } else {
1432     print(LOG $bpc->timeStamp,
1433     "Unknown status request $type\n");
1434     }
1435     }
1436     $dump = Data::Dumper->new(\@values, \@names);
1437     $dump->Indent(0);
1438     $reply = $dump->Dump;
1439     } elsif ( $cmd =~ /^link\s+(.+)/ ) {
1440     my($host) = $1;
1441     $host = $bpc->uriUnesc($host);
1442     QueueLink($host);
1443     } elsif ( $cmd =~ /^log\s+(.*)/ ) {
1444     print(LOG $bpc->timeStamp, "$1\n");
1445     } elsif ( $cmd =~ /^server\s+(\w+)/ ) {
1446     my($type) = $1;
1447     if ( $type eq 'reload' ) {
1448     ServerReload("Reloading config/host files via CGI request");
1449     } elsif ( $type eq 'shutdown' ) {
1450     $reply = "Shutting down...\n";
1451     syswrite($Clients{$client}{fh}, $reply, length($reply));
1452     ServerShutdown("Server shutting down...");
1453     }
1454     } elsif ( $cmd =~ /^quit/ || $cmd =~ /^exit/ ) {
1455     $nbytes = 0;
1456     last;
1457     } else {
1458     print(LOG $bpc->timeStamp, "Unknown command $cmd\n");
1459     $reply = "error: bad command $cmd";
1460     }
1461     #
1462     # send a reply to the client, at a minimum "ok\n".
1463     #
1464     $reply = "ok" if ( $reply eq "" );
1465     $reply .= "\n";
1466     syswrite($Clients{$client}{fh}, $reply, length($reply));
1467     }
1468     #
1469     # Detect possible denial-of-service attack from sending a huge line
1470     # (ie: never terminated). 32K seems to be plenty big enough as
1471     # a limit.
1472     #
1473     if ( length($Clients{$client}{mesg}) > 32 * 1024 ) {
1474     print(LOG $bpc->timeStamp, "Line too long from client"
1475     . " '$Clients{$client}{clientName}':"
1476     . " shutting down client connection\n");
1477     $nbytes = 0;
1478     }
1479     #
1480     # Shut down the client connection if we read EOF
1481     #
1482     if ( $nbytes <= 0 ) {
1483     close($Clients{$client}{fh});
1484     vec($FDread, $Clients{$client}{fn}, 1) = 0;
1485     delete($Clients{$client});
1486     }
1487     }
1488     #
1489     # Accept any new connections on each of our listen sockets
1490     #
1491     if ( vec($fdRead, fileno(SERVER_UNIX), 1) ) {
1492     local(*CLIENT);
1493     my $paddr = accept(CLIENT, SERVER_UNIX);
1494     $ClientConnCnt++;
1495     $Clients{$ClientConnCnt}{clientName} = "unix socket";
1496     $Clients{$ClientConnCnt}{mesg} = "";
1497     $Clients{$ClientConnCnt}{fh} = *CLIENT;
1498     $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1499     vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1500     #
1501     # Generate and send unique seed for MD5 digests to avoid
1502     # replay attacks. See BackupPC::Lib::ServerMesg().
1503     #
1504     my $seed = time . ",$ClientConnCnt,$$,0\n";
1505     $Clients{$ClientConnCnt}{seed} = $seed;
1506     $Clients{$ClientConnCnt}{mesgCnt} = 0;
1507     syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1508     }
1509     if ( $ServerInetPort > 0 && vec($fdRead, fileno(SERVER_INET), 1) ) {
1510     local(*CLIENT);
1511     my $paddr = accept(CLIENT, SERVER_INET);
1512     my($port,$iaddr) = sockaddr_in($paddr);
1513     my $name = gethostbyaddr($iaddr, AF_INET);
1514     $ClientConnCnt++;
1515     $Clients{$ClientConnCnt}{mesg} = "";
1516     $Clients{$ClientConnCnt}{fh} = *CLIENT;
1517     $Clients{$ClientConnCnt}{fn} = fileno(CLIENT);
1518     $Clients{$ClientConnCnt}{clientName} = "$name:$port";
1519     vec($FDread, $Clients{$ClientConnCnt}{fn}, 1) = 1;
1520     #
1521     # Generate and send unique seed for MD5 digests to avoid
1522     # replay attacks. See BackupPC::Lib::ServerMesg().
1523     #
1524     my $seed = time . ",$ClientConnCnt,$$,$port\n";
1525     $Clients{$ClientConnCnt}{seed} = $seed;
1526     $Clients{$ClientConnCnt}{mesgCnt} = 0;
1527     syswrite($Clients{$ClientConnCnt}{fh}, $seed, length($seed));
1528     }
1529     }
1530    
1531     ###########################################################################
1532     # Miscellaneous subroutines
1533     ###########################################################################
1534    
1535     #
1536     # Write the current status to $TopDir/log/status.pl
1537     #
1538     sub StatusWrite
1539     {
1540     my($dump) = Data::Dumper->new(
1541     [ \%Info, \%Status],
1542     [qw(*Info *Status)]);
1543     $dump->Indent(1);
1544     if ( open(STATUS, ">", "$TopDir/log/status.pl") ) {
1545     print(STATUS $dump->Dump);
1546     close(STATUS);
1547     }
1548     }
1549    
1550     #
1551     # Compare function for host sort. Hosts with errors go first,
1552     # sorted with the oldest errors first. The remaining hosts
1553     # are sorted so that those with the oldest backups go first.
1554     #
1555     sub HostSortCompare
1556     {
1557 dpavlin 316 #
1558     # Hosts with errors go before hosts without errors
1559     #
1560 dpavlin 1 return -1 if ( $Status{$a}{error} ne "" && $Status{$b}{error} eq "" );
1561 dpavlin 316
1562     #
1563     # Hosts with no errors go after hosts with errors
1564     #
1565    
1566 dpavlin 1 return 1 if ( $Status{$a}{error} eq "" && $Status{$b}{error} ne "" );
1567 dpavlin 316
1568     #
1569     # hosts with the older last good backups sort earlier
1570     #
1571     my $r = $Status{$a}{lastGoodBackupTime} <=> $Status{$b}{lastGoodBackupTime};
1572     return $r if ( $r );
1573    
1574     #
1575     # Finally, just sort based on host name
1576     #
1577     return $a cmp $b;
1578 dpavlin 1 }
1579    
1580 dpavlin 316
1581 dpavlin 1 #
1582     # Queue all the hosts for backup. This means queuing all the fixed
1583     # ip hosts and all the dhcp address ranges. We also additionally
1584     # queue the dhcp hosts with a -e flag to check for expired dumps.
1585     #
1586     sub QueueAllPCs
1587     {
1588     foreach my $host ( sort(HostSortCompare keys(%$Hosts)) ) {
1589     delete($Status{$host}{backoffTime})
1590     if ( defined($Status{$host}{backoffTime})
1591     && $Status{$host}{backoffTime} < time );
1592     next if ( defined($Jobs{$host})
1593     || $BgQueueOn{$host}
1594     || $UserQueueOn{$host}
1595     || $CmdQueueOn{$host} );
1596     if ( $Hosts->{$host}{dhcp} ) {
1597     $Status{$host}{dhcpCheckCnt}++;
1598     if ( $RunNightlyWhenIdle ) {
1599     #
1600     # Once per night queue a check for DHCP hosts that just
1601     # checks for expired dumps. We need to do this to handle
1602     # the case when a DHCP host has not been on the network for
1603     # a long time, and some of the old dumps need to be expired.
1604     # Normally expiry checks are done by BackupPC_dump only
1605     # after the DHCP hosts has been detected on the network.
1606     #
1607     unshift(@BgQueue,
1608     {host => $host, user => "BackupPC", reqTime => time,
1609     dhcp => 0, dumpExpire => 1});
1610     $BgQueueOn{$host} = 1;
1611     }
1612     } else {
1613     #
1614     # this is a fixed ip host: queue it
1615     #
1616     unshift(@BgQueue,
1617     {host => $host, user => "BackupPC", reqTime => time,
1618     dhcp => $Hosts->{$host}{dhcp}});
1619     $BgQueueOn{$host} = 1;
1620     }
1621     }
1622     foreach my $dhcp ( @{$Conf{DHCPAddressRanges}} ) {
1623     for ( my $i = $dhcp->{first} ; $i <= $dhcp->{last} ; $i++ ) {
1624     my $ipAddr = "$dhcp->{ipAddrBase}.$i";
1625     next if ( defined($Jobs{$ipAddr})
1626     || $BgQueueOn{$ipAddr}
1627     || $UserQueueOn{$ipAddr}
1628     || $CmdQueueOn{$ipAddr} );
1629     #
1630     # this is a potential dhcp ip address (we don't know the
1631     # host name yet): queue it
1632     #
1633     unshift(@BgQueue,
1634     {host => $ipAddr, user => "BackupPC", reqTime => time,
1635     dhcp => 1});
1636     $BgQueueOn{$ipAddr} = 1;
1637     }
1638     }
1639     }
1640    
1641     #
1642     # Queue a BackupPC_link for the given host
1643     #
1644     sub QueueLink
1645     {
1646     my($host) = @_;
1647    
1648     return if ( $CmdQueueOn{$host} );
1649     $Status{$host}{state} = "Status_link_pending";
1650     $Status{$host}{needLink} = 0;
1651     unshift(@CmdQueue, {
1652     host => $host,
1653     user => "BackupPC",
1654     reqTime => time,
1655     cmd => ["$BinDir/BackupPC_link", $host],
1656     });
1657     $CmdQueueOn{$host} = 1;
1658     }
1659    
1660     #
1661     # Read the hosts file, and update Status if any hosts have been
1662     # added or deleted. We also track the mtime so the only need to
1663     # update the hosts file on changes.
1664     #
1665     # This function is called at startup, SIGHUP, and on each wakeup.
1666     # It returns 1 on success and undef on failure.
1667     #
1668     sub HostsUpdate
1669     {
1670     my($force) = @_;
1671     my $newHosts;
1672     #
1673     # Nothing to do if we already have the current hosts file
1674     #
1675     return 1 if ( !$force && defined($Hosts)
1676     && $Info{HostsModTime} == $bpc->HostsMTime() );
1677     if ( !defined($newHosts = $bpc->HostInfoRead()) ) {
1678     print(LOG $bpc->timeStamp, "Can't read hosts file!\n");
1679     return;
1680     }
1681     print(LOG $bpc->timeStamp, "Reading hosts file\n");
1682     $Hosts = $newHosts;
1683     $Info{HostsModTime} = $bpc->HostsMTime();
1684     #
1685     # Now update %Status in case any hosts have been added or deleted
1686     #
1687     foreach my $host ( sort(keys(%$Hosts)) ) {
1688     next if ( defined($Status{$host}) );
1689     $Status{$host}{state} = "Status_idle";
1690     print(LOG $bpc->timeStamp, "Added host $host to backup list\n");
1691     }
1692     foreach my $host ( sort(keys(%Status)) ) {
1693     next if ( $host eq $bpc->trashJob
1694     || $bpc->isAdminJob($host)
1695     || defined($Hosts->{$host})
1696     || defined($Jobs{$host})
1697     || $BgQueueOn{$host}
1698     || $UserQueueOn{$host}
1699     || $CmdQueueOn{$host} );
1700     print(LOG $bpc->timeStamp, "Deleted host $host from backup list\n");
1701     delete($Status{$host});
1702     }
1703     return 1;
1704     }
1705    
1706     #
1707     # Remember the signal name for later processing
1708     #
1709     sub catch_signal
1710     {
1711     if ( $SigName ) {
1712     $SigName = shift;
1713     foreach my $host ( keys(%Jobs) ) {
1714     kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1715     }
1716     #
1717     # In case we are inside the exit handler, reopen the log file
1718     #
1719     close(LOG);
1720     LogFileOpen();
1721     print(LOG "Fatal error: unhandled signal $SigName\n");
1722     unlink("$TopDir/log/BackupPC.pid");
1723     confess("Got new signal $SigName... quitting\n");
1724     } else {
1725     $SigName = shift;
1726     }
1727     }
1728    
1729     #
1730     # Open the log file and point STDOUT and STDERR there too
1731     #
1732     sub LogFileOpen
1733     {
1734     mkpath("$TopDir/log", 0, 0777) if ( !-d "$TopDir/log" );
1735     open(LOG, ">>$TopDir/log/LOG")
1736     || die("Can't create LOG file $TopDir/log/LOG");
1737     close(STDOUT);
1738     close(STDERR);
1739     open(STDOUT, ">&LOG");
1740     open(STDERR, ">&LOG");
1741     select(LOG); $| = 1;
1742     select(STDERR); $| = 1;
1743     select(STDOUT); $| = 1;
1744     }
1745    
1746     #
1747     # Initialize the unix-domain and internet-domain sockets that
1748     # we listen to for client connections (from the CGI script and
1749     # some of the BackupPC sub-programs).
1750     #
1751     sub ServerSocketInit
1752     {
1753     if ( !defined(fileno(SERVER_UNIX)) ) {
1754     #
1755     # one-time only: initialize unix-domain socket
1756     #
1757     if ( !socket(SERVER_UNIX, PF_UNIX, SOCK_STREAM, 0) ) {
1758     print(LOG $bpc->timeStamp, "unix socket() failed: $!\n");
1759     exit(1);
1760     }
1761     my $sockFile = "$TopDir/log/BackupPC.sock";
1762     unlink($sockFile);
1763     if ( !bind(SERVER_UNIX, sockaddr_un($sockFile)) ) {
1764     print(LOG $bpc->timeStamp, "unix bind() failed: $!\n");
1765     exit(1);
1766     }
1767     if ( !listen(SERVER_UNIX, SOMAXCONN) ) {
1768     print(LOG $bpc->timeStamp, "unix listen() failed: $!\n");
1769     exit(1);
1770     }
1771     vec($FDread, fileno(SERVER_UNIX), 1) = 1;
1772     }
1773     return if ( $ServerInetPort == $Conf{ServerPort} );
1774     if ( $ServerInetPort > 0 ) {
1775     vec($FDread, fileno(SERVER_INET), 1) = 0;
1776     close(SERVER_INET);
1777     $ServerInetPort = -1;
1778     }
1779     if ( $Conf{ServerPort} > 0 ) {
1780     #
1781     # Setup a socket to listen on $Conf{ServerPort}
1782     #
1783     my $proto = getprotobyname('tcp');
1784     if ( !socket(SERVER_INET, PF_INET, SOCK_STREAM, $proto) ) {
1785     print(LOG $bpc->timeStamp, "inet socket() failed: $!\n");
1786     exit(1);
1787     }
1788     if ( !setsockopt(SERVER_INET, SOL_SOCKET, SO_REUSEADDR, pack("l",1)) ) {
1789     print(LOG $bpc->timeStamp, "setsockopt() failed: $!\n");
1790     exit(1);
1791     }
1792     if ( !bind(SERVER_INET, sockaddr_in($Conf{ServerPort}, INADDR_ANY)) ) {
1793     print(LOG $bpc->timeStamp, "inet bind() failed: $!\n");
1794     exit(1);
1795     }
1796     if ( !listen(SERVER_INET, SOMAXCONN) ) {
1797     print(LOG $bpc->timeStamp, "inet listen() failed: $!\n");
1798     exit(1);
1799     }
1800     vec($FDread, fileno(SERVER_INET), 1) = 1;
1801     $ServerInetPort = $Conf{ServerPort};
1802     }
1803     }
1804    
1805     #
1806     # Reload the server. Used by Main_Process_Signal when $SigName eq "HUP"
1807     # or when the command "server reload" is received.
1808     #
1809     sub ServerReload
1810     {
1811     my($mesg) = @_;
1812     $mesg = $bpc->ConfigRead() || $mesg;
1813     print(LOG $bpc->timeStamp, "$mesg\n");
1814     $Info{ConfigModTime} = $bpc->ConfigMTime();
1815     %Conf = $bpc->Conf();
1816     umask($Conf{UmaskMode});
1817     ServerSocketInit();
1818     HostsUpdate(0);
1819     $NextWakeup = 0;
1820     $Info{ConfigLTime} = time;
1821     }
1822    
1823     #
1824     # Gracefully shutdown the server. Used by Main_Process_Signal when
1825     # $SigName ne "" && $SigName ne "HUP" or when the command
1826     # "server shutdown" is received.
1827     #
1828     sub ServerShutdown
1829     {
1830     my($mesg) = @_;
1831     print(LOG $bpc->timeStamp, "$mesg\n");
1832     if ( keys(%Jobs) ) {
1833     foreach my $host ( keys(%Jobs) ) {
1834     kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
1835     }
1836     sleep(1);
1837     foreach my $host ( keys(%Jobs) ) {
1838     kill($bpc->sigName2num("KILL"), $Jobs{$host}{pid});
1839     }
1840     %Jobs = ();
1841     }
1842 dpavlin 316 delete($Info{pid});
1843 dpavlin 1 StatusWrite();
1844     unlink("$TopDir/log/BackupPC.pid");
1845     exit(1);
1846     }
1847    

Properties

Name Value
svn:executable

  ViewVC Help
Powered by ViewVC 1.1.26