* Commit for 2.1.0.
[BackupPC.git] / bin / BackupPC
index 027bbf2..50d5500 100755 (executable)
@@ -1,4 +1,4 @@
-#!/bin/perl -T
+#!/bin/perl
 #============================================================= -*-perl-*-
 #
 # BackupPC: Main program for PC backups.
@@ -47,7 +47,7 @@
 #
 #========================================================================
 #
-# Version 2.1.0_CVS, released 3 Jul 2003.
+# Version 2.1.0, released 20 Jun 2004.
 #
 # See http://backuppc.sourceforge.net.
 #
@@ -173,6 +173,7 @@ my $SigName = "";
 # Misc variables
 #
 my($RunNightlyWhenIdle, $FirstWakeup, $CmdJob, $ServerInetPort);
+my($BackupPCNightlyJobs, $BackupPCNightlyLock);
 
 #
 # Complete the rest of the initialization
@@ -300,6 +301,7 @@ sub Main_Initialize
     $Info{ConfigModTime} = $bpc->ConfigMTime();
     $Info{pid} = $$;
     $Info{startTime} = time;
+    $Info{ConfigLTime} = time;
     $Info{Version} = $bpc->{Version};
 
     #
@@ -373,14 +375,89 @@ sub Main_TryToRun_nightly
        $CmdQueueOn{$bpc->trashJob} = 1;
     }
     if ( keys(%Jobs) == $trashCleanRunning && $RunNightlyWhenIdle == 1 ) {
-       push(@CmdQueue, {
-               host    => $bpc->adminJob,
-               user    => "BackupPC",
-               reqTime => time,
-               cmd     => ["$BinDir/BackupPC_nightly"],
-           });
-       $CmdQueueOn{$bpc->adminJob} = 1;
-       $RunNightlyWhenIdle = 2;
+
+        #
+        # Queue multiple nightly jobs based on the configuration
+        #
+       $Conf{MaxBackupPCNightlyJobs} = 1
+                   if ( $Conf{MaxBackupPCNightlyJobs} <= 0 );
+       $Conf{BackupPCNightlyPeriod} = 1
+                   if ( $Conf{BackupPCNightlyPeriod} <= 0 );
+       #
+       # Decide what subset of the 16 top-level directories 0..9a..f
+       # we run BackupPC_nightly on, based on $Conf{BackupPCNightlyPeriod}.
+       # If $Conf{BackupPCNightlyPeriod} == 1 then we run 0..15 every
+       # time.  If $Conf{BackupPCNightlyPeriod} == 2 then we run
+       # 0..7 one night and 89a-f the next night.  And so on.
+       #
+       # $Info{NightlyPhase} counts which night, from 0 to
+       # $Conf{BackupPCNightlyPeriod} - 1.
+       #
+        my $start = int($Info{NightlyPhase} * 16
+                           / $Conf{BackupPCNightlyPeriod});
+       my $end = int(($Info{NightlyPhase} + 1) * 16
+                           / $Conf{BackupPCNightlyPeriod});
+       $end = $start + 1 if ( $end <= $start );
+       $Info{NightlyPhase}++;
+       $Info{NightlyPhase} = 0 if ( $end >= 16 );
+
+       #
+       # Zero out the data we expect to get from BackupPC_nightly.
+       # In the future if we want to split BackupPC_nightly over
+       # more than one night we will only zero out the portion
+       # that we are running right now.
+       #
+       for my $p ( qw(pool cpool) ) {
+           for ( my $i = $start ; $i < $end ; $i++ ) {
+               $Info{pool}{$p}[$i]{FileCnt}       = 0;
+               $Info{pool}{$p}[$i]{DirCnt}        = 0;
+               $Info{pool}{$p}[$i]{Kb}            = 0;
+               $Info{pool}{$p}[$i]{Kb2}           = 0;
+               $Info{pool}{$p}[$i]{KbRm}          = 0;
+               $Info{pool}{$p}[$i]{FileCntRm}     = 0;
+               $Info{pool}{$p}[$i]{FileCntRep}    = 0;
+               $Info{pool}{$p}[$i]{FileRepMax}    = 0;
+               $Info{pool}{$p}[$i]{FileCntRename} = 0;
+               $Info{pool}{$p}[$i]{FileLinkMax}   = 0;
+               $Info{pool}{$p}[$i]{Time}          = 0;
+           }
+       }
+       print(LOG $bpc->timeStamp,
+               sprintf("Running %d BackupPC_nightly jobs from %d..%d"
+                     . " (out of 0..15)\n",
+                     $Conf{MaxBackupPCNightlyJobs}, $start, $end - 1));
+
+       #
+       # Now queue the $Conf{MaxBackupPCNightlyJobs} jobs.
+       # The granularity on start and end is now 0..256.
+       #
+       $start *= 16;
+       $end   *= 16;
+       my $start0 = $start;
+        for ( my $i = 0 ; $i < $Conf{MaxBackupPCNightlyJobs} ; $i++ ) {
+            #
+            # The first nightly job gets the -m option (does email, log aging).
+            # All jobs get the start and end options from 0..255 telling
+            # them which parts of the pool to traverse.
+            #
+            my $cmd = ["$BinDir/BackupPC_nightly"];
+            push(@$cmd, "-m") if ( $i == 0 );
+            push(@$cmd, $start);
+            $start = $start0 + int(($end - $start0)
+                                 * ($i + 1) / $Conf{MaxBackupPCNightlyJobs});
+            push(@$cmd, $start - 1);
+
+            my $job = $bpc->adminJob($i);
+            unshift(@CmdQueue, {
+                    host    => $job,
+                    user    => "BackupPC",
+                    reqTime => time,
+                    cmd     => $cmd,
+                });
+            $CmdQueueOn{$job} = 1;
+        }
+        $RunNightlyWhenIdle = 2;
+
     }
 }
 
@@ -396,7 +473,11 @@ sub Main_TryToRun_nightly
 sub Main_TryToRun_CmdQueue
 {
     my($req, $host);
-    if ( $CmdJob eq "" && @CmdQueue > 0 && $RunNightlyWhenIdle != 1 ) {
+
+    while ( $CmdJob eq "" && @CmdQueue > 0 && $RunNightlyWhenIdle != 1
+            || @CmdQueue > 0 && $RunNightlyWhenIdle == 2
+                             && $bpc->isAdminJob($CmdQueue[0]->{host})
+                ) {
         local(*FH);
         $req = pop(@CmdQueue);
 
@@ -434,8 +515,9 @@ sub Main_TryToRun_CmdQueue
         vec($FDread, $Jobs{$host}{fn}, 1) = 1;
         $Jobs{$host}{startTime} = time;
         $Jobs{$host}{reqTime}   = $req->{reqTime};
-       $cmd                    = join(" ", @$cmd);
+       $cmd                    = $bpc->execCmd2ShellCmd(@$cmd);
         $Jobs{$host}{cmd}       = $cmd;
+        $Jobs{$host}{user}      = $req->{user};
         $Jobs{$host}{type}      = $Status{$host}{type};
         $Status{$host}{state}   = "Status_link_running";
         $Status{$host}{activeJob} = 1;
@@ -443,6 +525,10 @@ sub Main_TryToRun_CmdQueue
         $CmdJob = $host if ( $host ne $bpc->trashJob );
         $cmd =~ s/$BinDir\///g;
         print(LOG $bpc->timeStamp, "Running $cmd (pid=$pid)\n");
+       if ( $cmd =~ /^BackupPC_nightly\s/ ) {
+           $BackupPCNightlyJobs++;
+           $BackupPCNightlyLock++;
+       }
     }
 }
 
@@ -467,7 +553,7 @@ sub Main_TryToRun_Bg_or_User_Queue
         #
         # CmdJob and trashClean don't count towards MaxBackups / MaxUserBackups
         #
-        $nJobs-- if ( $CmdJob ne "" );
+        $nJobs -= $BackupPCNightlyJobs if ( $CmdJob ne "" );
         $nJobs-- if ( defined($Jobs{$bpc->trashJob} ) );
         if ( $nJobs < $Conf{MaxBackups} + $Conf{MaxUserBackups}
                         && @UserQueue > 0 ) {
@@ -477,7 +563,7 @@ sub Main_TryToRun_Bg_or_User_Queue
                 next;
             }
             push(@args, $req->{doFull} ? "-f" : "-i")
-                            if ( !$req->{restore} );
+                            if (( !$req->{restore} ) && ( !$req->{archive} ));
             $UserQueueOn{$req->{host}} = 0;
         } elsif ( $nJobs < $Conf{MaxBackups}
                         && (@CmdQueue + $nJobs)
@@ -510,7 +596,7 @@ sub Main_TryToRun_Bg_or_User_Queue
             if ( $du > $Conf{DfMaxUsagePct} ) {
                 my $nSkip = @BgQueue + @deferBgQueue;
                 print(LOG $bpc->timeStamp,
-                           "Disk too full ($du%%); skipping $nSkip hosts\n");
+                           "Disk too full ($du%); skipping $nSkip hosts\n");
                $Info{DUDailySkipHostCnt} += $nSkip;
                 @BgQueue = ();
                 @deferBgQueue = ();
@@ -538,6 +624,10 @@ sub Main_TryToRun_Bg_or_User_Queue
             $progName = "BackupPC_restore";
             $type     = "restore";
             push(@args, $req->{hostIP}, $req->{host}, $req->{reqFileName});
+       } elsif ( $req->{archive} ) {
+            $progName = "BackupPC_archive";
+            $type     = "archive";
+            push(@args, $req->{user}, $req->{host}, $req->{reqFileName});
         } else {
             $progName = "BackupPC_dump";
             $type     = "backup";
@@ -566,7 +656,7 @@ sub Main_TryToRun_Bg_or_User_Queue
         $Jobs{$host}{startTime}  = time;
         $Jobs{$host}{reqTime}    = $req->{reqTime};
         $Jobs{$host}{userReq}    = $req->{userReq};
-        $Jobs{$host}{cmd}        = join(" ", $progName, @args);
+        $Jobs{$host}{cmd}        = $bpc->execCmd2ShellCmd($progName, @args);
         $Jobs{$host}{user}       = $user;
         $Jobs{$host}{type}       = $type;
        $Status{$host}{userReq}  = $req->{userReq}
@@ -597,13 +687,7 @@ sub Main_Select
                                                = localtime(time);
         my($currHours) = $hour + $min / 60 + $sec / 3600;
         if ( $bpc->ConfigMTime() != $Info{ConfigModTime} ) {
-            my($mesg) = $bpc->ConfigRead()
-                        || "Re-read config file because mtime changed";
-            print(LOG $bpc->timeStamp, "$mesg\n");
-            %Conf = $bpc->Conf();
-            $Info{ConfigModTime} = $bpc->ConfigMTime();
-            umask($Conf{UmaskMode});
-            ServerSocketInit();
+            ServerReload("Re-read config file because mtime changed");
         }
         my $delta = -1;
         foreach my $t ( @{$Conf{WakeupSchedule} || [0..23]} ) {
@@ -651,30 +735,9 @@ sub Main_Process_Signal
     # Process signals
     #
     if ( $SigName eq "HUP" ) {
-        my($mesg) = $bpc->ConfigRead()
-                    || "Re-read config file because of a SIG_HUP";
-        print(LOG $bpc->timeStamp, "$mesg\n");
-        $Info{ConfigModTime} = $bpc->ConfigMTime();
-        %Conf = $bpc->Conf();
-        umask($Conf{UmaskMode});
-        ServerSocketInit();
-        HostsUpdate(0);
-        $NextWakeup = 0;
+        ServerReload("Re-read config file because of a SIG_HUP");
     } elsif ( $SigName ) {
-        print(LOG $bpc->timeStamp, "Got signal $SigName... cleaning up\n");
-       if ( keys(%Jobs) ) {
-           foreach my $host ( keys(%Jobs) ) {
-               kill(2, $Jobs{$host}{pid});
-           }
-           sleep(1);
-           foreach my $host ( keys(%Jobs) ) {
-               kill(9, $Jobs{$host}{pid});
-           }
-           %Jobs = ();
-       }
-        StatusWrite();
-        unlink("$TopDir/log/BackupPC.pid");
-        exit(1);
+        ServerShutdown("Got signal $SigName... cleaning up");
     }
     $SigName = "";
 }
@@ -719,6 +782,8 @@ sub Main_Check_Timeout
         }
         print(LOG $bpc->timeStamp, "Aging LOG files, LOG -> LOG.0 -> "
                    . "LOG.1 -> ... -> LOG.$lastLog\n");
+       close(STDERR);          # dup of LOG
+       close(STDOUT);          # dup of LOG
         close(LOG);
         for ( my $i = $lastLog - 1 ; $i >= 0 ; $i-- ) {
             my $j = $i + 1;
@@ -794,7 +859,7 @@ sub Main_Check_Job_Messages
                     if ( defined($Jobs{$newHost}) ) {
                         print(LOG $bpc->timeStamp,
                                 "Backup on $newHost is already running\n");
-                        kill(2, $Jobs{$host}{pid});
+                        kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
                         $nbytes = 0;
                         last;
                     }
@@ -840,18 +905,42 @@ sub Main_Check_Job_Messages
                 $Status{$host}{startTime} = time;
                 $Status{$host}{deadCnt}   = 0;
                 $Status{$host}{aliveCnt}++;
+            } elsif ( $mesg =~ /^started_archive/ ) {
+                $Jobs{$host}{type}    = "archive";
+                print(LOG $bpc->timeStamp,
+                          "Started archive on $host"
+                          . " (pid=$Jobs{$host}{pid})\n");
+                $Status{$host}{state}     = "Status_archive_in_progress";
+                $Status{$host}{reason}    = "";
+                $Status{$host}{type}      = "archive";
+                $Status{$host}{startTime} = time;
+                $Status{$host}{deadCnt}   = 0;
+                $Status{$host}{aliveCnt}++;
             } elsif ( $mesg =~ /^(full|incr) backup complete/ ) {
                 print(LOG $bpc->timeStamp, "Finished $1 backup on $host\n");
                 $Status{$host}{reason}    = "Reason_backup_done";
                 delete($Status{$host}{error});
                 delete($Status{$host}{errorTime});
                 $Status{$host}{endTime}   = time;
+            } elsif ( $mesg =~ /^backups disabled/ ) {
+                print(LOG $bpc->timeStamp,
+                           "Ignoring old backup error on $host\n");
+                $Status{$host}{reason}    = "Reason_backup_done";
+                delete($Status{$host}{error});
+                delete($Status{$host}{errorTime});
+                $Status{$host}{endTime}   = time;
             } elsif ( $mesg =~ /^restore complete/ ) {
                 print(LOG $bpc->timeStamp, "Finished restore on $host\n");
                 $Status{$host}{reason}    = "Reason_restore_done";
                 delete($Status{$host}{error});
                 delete($Status{$host}{errorTime});
                 $Status{$host}{endTime}   = time;
+            } elsif ( $mesg =~ /^archive complete/ ) {
+                print(LOG $bpc->timeStamp, "Finished archive on $host\n");
+                $Status{$host}{reason}    = "Reason_archive_done";
+                delete($Status{$host}{error});
+                delete($Status{$host}{errorTime});
+                $Status{$host}{endTime}   = time;
             } elsif ( $mesg =~ /^nothing to do/ ) {
                if ( $Status{$host}{reason} ne "Reason_backup_failed"
                        && $Status{$host}{reason} ne "Reason_restore_failed" ) {
@@ -878,47 +967,74 @@ sub Main_Check_Job_Messages
                }
             } elsif ( $mesg =~ /^dump failed: (.*)/ ) {
                 $Status{$host}{state}     = "Status_idle";
-                $Status{$host}{reason}    = "Reason_backup_failed";
+               $Status{$host}{error}     = $1;
+               $Status{$host}{errorTime} = time;
+               $Status{$host}{endTime}   = time;
+               if ( $Status{$host}{reason}
+                       eq "Reason_backup_canceled_by_user" ) {
+                   print(LOG $bpc->timeStamp,
+                           "Backup canceled on $host ($1)\n");
+               } else {
+                   $Status{$host}{reason} = "Reason_backup_failed";
+                   print(LOG $bpc->timeStamp,
+                           "Backup failed on $host ($1)\n");
+               }
+            } elsif ( $mesg =~ /^restore failed: (.*)/ ) {
+                $Status{$host}{state}     = "Status_idle";
                 $Status{$host}{error}     = $1;
                 $Status{$host}{errorTime} = time;
                 $Status{$host}{endTime}   = time;
-                print(LOG $bpc->timeStamp, "Backup failed on $host ($1)\n");
-            } elsif ( $mesg =~ /^restore failed: (.*)/ ) {
+               if ( $Status{$host}{reason}
+                        eq "Reason_restore_canceled_by_user" ) {
+                   print(LOG $bpc->timeStamp,
+                           "Restore canceled on $host ($1)\n");
+               } else {
+                   $Status{$host}{reason} = "Reason_restore_failed";
+                   print(LOG $bpc->timeStamp,
+                           "Restore failed on $host ($1)\n");
+               }
+            } elsif ( $mesg =~ /^archive failed: (.*)/ ) {
                 $Status{$host}{state}     = "Status_idle";
-                $Status{$host}{reason}    = "Reason_restore_failed";
                 $Status{$host}{error}     = $1;
                 $Status{$host}{errorTime} = time;
                 $Status{$host}{endTime}   = time;
-                print(LOG $bpc->timeStamp, "Restore failed on $host ($1)\n");
+               if ( $Status{$host}{reason}
+                        eq "Reason_archive_canceled_by_user" ) {
+                   print(LOG $bpc->timeStamp,
+                           "Archive canceled on $host ($1)\n");
+               } else {
+                   $Status{$host}{reason} = "Reason_archive_failed";
+                   print(LOG $bpc->timeStamp,
+                           "Archive failed on $host ($1)\n");
+               }
             } elsif ( $mesg =~ /^log\s+(.*)/ ) {
                 print(LOG $bpc->timeStamp, "$1\n");
-            } elsif ( $mesg =~ /^BackupPC_stats = (.*)/ ) {
-                my @f = split(/,/, $1);
-                $Info{"$f[0]FileCnt"}       = $f[1];
-                $Info{"$f[0]DirCnt"}        = $f[2];
-                $Info{"$f[0]Kb"}            = $f[3];
-                $Info{"$f[0]Kb2"}           = $f[4];
-                $Info{"$f[0]KbRm"}          = $f[5];
-                $Info{"$f[0]FileCntRm"}     = $f[6];
-                $Info{"$f[0]FileCntRep"}    = $f[7];
-                $Info{"$f[0]FileRepMax"}    = $f[8];
-                $Info{"$f[0]FileCntRename"} = $f[9];
-                $Info{"$f[0]FileLinkMax"}   = $f[10];
-                $Info{"$f[0]Time"}          = time;
-                printf(LOG "%s%s nightly clean removed %d files of"
-                           . " size %.2fGB\n",
-                             $bpc->timeStamp, ucfirst($f[0]),
-                             $Info{"$f[0]FileCntRm"},
-                             $Info{"$f[0]KbRm"} / (1000 * 1024));
-                printf(LOG "%s%s is %.2fGB, %d files (%d repeated, "
-                          . "%d max chain, %d max links), %d directories\n",
-                             $bpc->timeStamp, ucfirst($f[0]),
-                             $Info{"$f[0]Kb"} / (1000 * 1024),
-                             $Info{"$f[0]FileCnt"}, $Info{"$f[0]FileCntRep"},
-                            $Info{"$f[0]FileRepMax"},
-                            $Info{"$f[0]FileLinkMax"}, $Info{"$f[0]DirCnt"});
+            } elsif ( $mesg =~ /^BackupPC_stats (\d+) = (.*)/ ) {
+                my $chunk = int($1 / 16);
+                my @f = split(/,/, $2);
+                $Info{pool}{$f[0]}[$chunk]{FileCnt}       += $f[1];
+                $Info{pool}{$f[0]}[$chunk]{DirCnt}        += $f[2];
+                $Info{pool}{$f[0]}[$chunk]{Kb}            += $f[3];
+                $Info{pool}{$f[0]}[$chunk]{Kb2}           += $f[4];
+                $Info{pool}{$f[0]}[$chunk]{KbRm}          += $f[5];
+                $Info{pool}{$f[0]}[$chunk]{FileCntRm}     += $f[6];
+                $Info{pool}{$f[0]}[$chunk]{FileCntRep}    += $f[7];
+                $Info{pool}{$f[0]}[$chunk]{FileRepMax}     = $f[8]
+                        if ( $Info{pool}{$f[0]}[$chunk]{FileRepMax} < $f[8] );
+                $Info{pool}{$f[0]}[$chunk]{FileCntRename} += $f[9];
+                $Info{pool}{$f[0]}[$chunk]{FileLinkMax}    = $f[10]
+                        if ( $Info{pool}{$f[0]}[$chunk]{FileLinkMax} < $f[10] );
+                $Info{pool}{$f[0]}[$chunk]{Time}           = time;
             } elsif ( $mesg =~ /^BackupPC_nightly lock_off/ ) {
-               $RunNightlyWhenIdle = 0;
+               $BackupPCNightlyLock--;
+                if ( $BackupPCNightlyLock == 0 ) {
+                    #
+                    # This means the last BackupPC_nightly is done with
+                   # the pool clean, so it's to start running regular
+                   # backups again.
+                    #
+                    $RunNightlyWhenIdle = 0;
+               }
             } elsif ( $mesg =~ /^processState\s+(.+)/ ) {
                 $Jobs{$host}{processState} = $1;
             } elsif ( $mesg =~ /^link\s+(.+)/ ) {
@@ -934,15 +1050,81 @@ sub Main_Check_Job_Messages
         if ( $nbytes <= 0 ) {
             close($Jobs{$host}{fh});
             vec($FDread, $Jobs{$host}{fn}, 1) = 0;
-            if ( $CmdJob eq $host ) {
+            if ( $CmdJob eq $host || $bpc->isAdminJob($host) ) {
                 my $cmd = $Jobs{$host}{cmd};
                 $cmd =~ s/$BinDir\///g;
                 print(LOG $bpc->timeStamp, "Finished $host ($cmd)\n");
                 $Status{$host}{state}    = "Status_idle";
                 $Status{$host}{endTime}  = time;
-                $CmdJob = "";
-                $RunNightlyWhenIdle = 0 if ( $cmd eq "BackupPC_nightly"
-                                            && $RunNightlyWhenIdle );
+                if ( $cmd =~ /^BackupPC_nightly\s/ ) {
+                    $BackupPCNightlyJobs--;
+                   #print(LOG $bpc->timeStamp, "BackupPC_nightly done; now"
+                   #         . " have $BackupPCNightlyJobs running\n");
+                    if ( $BackupPCNightlyJobs <= 0 ) {
+                        $BackupPCNightlyJobs = 0;
+                        $RunNightlyWhenIdle = 0;
+                        $CmdJob = "";
+                       #
+                       # Combine the 16 per-directory results
+                       #
+                       for my $p ( qw(pool cpool) ) {
+                           $Info{"${p}FileCnt"}       = 0;
+                           $Info{"${p}DirCnt"}        = 0;
+                           $Info{"${p}Kb"}            = 0;
+                           $Info{"${p}Kb2"}           = 0;
+                           $Info{"${p}KbRm"}          = 0;
+                           $Info{"${p}FileCntRm"}     = 0;
+                           $Info{"${p}FileCntRep"}    = 0;
+                           $Info{"${p}FileRepMax"}    = 0;
+                           $Info{"${p}FileCntRename"} = 0;
+                           $Info{"${p}FileLinkMax"}   = 0;
+                           $Info{"${p}Time"}          = 0;
+                           for ( my $i = 0 ; $i < 16 ; $i++ ) {
+                               $Info{"${p}FileCnt"}
+                                      += $Info{pool}{$p}[$i]{FileCnt};
+                               $Info{"${p}DirCnt"}
+                                      += $Info{pool}{$p}[$i]{DirCnt};
+                               $Info{"${p}Kb"}
+                                      += $Info{pool}{$p}[$i]{Kb};
+                               $Info{"${p}Kb2"}
+                                      += $Info{pool}{$p}[$i]{Kb2};
+                               $Info{"${p}KbRm"}
+                                      += $Info{pool}{$p}[$i]{KbRm};
+                               $Info{"${p}FileCntRm"}
+                                      += $Info{pool}{$p}[$i]{FileCntRm};
+                               $Info{"${p}FileCntRep"}
+                                      += $Info{pool}{$p}[$i]{FileCntRep};
+                               $Info{"${p}FileRepMax"}
+                                       = $Info{pool}{$p}[$i]{FileRepMax}
+                                         if ( $Info{"${p}FileRepMax"} <
+                                             $Info{pool}{$p}[$i]{FileRepMax} );
+                               $Info{"${p}FileCntRename"}
+                                      += $Info{pool}{$p}[$i]{FileCntRename};
+                               $Info{"${p}FileLinkMax"}
+                                       = $Info{pool}{$p}[$i]{FileLinkMax}
+                                         if ( $Info{"${p}FileLinkMax"} <
+                                            $Info{pool}{$p}[$i]{FileLinkMax} );
+                               $Info{"${p}Time"} = $Info{pool}{$p}[$i]{Time}
+                                         if ( $Info{"${p}Time"} <
+                                                $Info{pool}{$p}[$i]{Time} );
+                           }
+                           printf(LOG "%s%s nightly clean removed %d files of"
+                                  . " size %.2fGB\n",
+                                    $bpc->timeStamp, ucfirst($p),
+                                    $Info{"${p}FileCntRm"},
+                                    $Info{"${p}KbRm"} / (1000 * 1024));
+                           printf(LOG "%s%s is %.2fGB, %d files (%d repeated, "
+                                  . "%d max chain, %d max links), %d directories\n",
+                                    $bpc->timeStamp, ucfirst($p),
+                                    $Info{"${p}Kb"} / (1000 * 1024),
+                                    $Info{"${p}FileCnt"}, $Info{"${p}FileCntRep"},
+                                    $Info{"${p}FileRepMax"},
+                                    $Info{"${p}FileLinkMax"}, $Info{"${p}DirCnt"});
+                       }
+                    }
+                } else {
+                    $CmdJob = "";
+                }
             } else {
                 #
                 # Queue BackupPC_link to complete the backup
@@ -1041,7 +1223,7 @@ sub Main_Check_Client_Messages
                     print(LOG $bpc->timeStamp,
                                "Stopping current $Jobs{$host}{type} of $host,"
                              . " request by $user (backoff=$backoff)\n");
-                    kill(2, $Jobs{$host}{pid});
+                    kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
                    #
                    # Don't close the pipe now; wait until the child
                    # really exits later.  Otherwise close() will
@@ -1055,13 +1237,16 @@ sub Main_Check_Client_Messages
                    if ( $Jobs{$host}{type} eq "restore" ) {
                        $Status{$host}{reason}
                                    = "Reason_restore_canceled_by_user";
+                   } elsif ( $Jobs{$host}{type} eq "archive" ) {
+                       $Status{$host}{reason}
+                                   = "Reason_archive_canceled_by_user";
                    } else {
                        $Status{$host}{reason}
                                    = "Reason_backup_canceled_by_user";
                    }
                     $Status{$host}{activeJob} = 0;
                     $Status{$host}{startTime} = time;
-                    $reply = "ok: $Jobs{$host}{type} of $host cancelled";
+                    $reply = "ok: $Jobs{$host}{type} of $host canceled";
                 } elsif ( $BgQueueOn{$host} || $UserQueueOn{$host} ) {
                     print(LOG $bpc->timeStamp,
                                "Stopping pending backup of $host,"
@@ -1069,7 +1254,7 @@ sub Main_Check_Client_Messages
                     @BgQueue = grep($_->{host} ne $host, @BgQueue);
                     @UserQueue = grep($_->{host} ne $host, @UserQueue);
                     $BgQueueOn{$host} = $UserQueueOn{$host} = 0;
-                    $reply = "ok: pending backup of $host cancelled";
+                    $reply = "ok: pending backup of $host canceled";
                 } else {
                     print(LOG $bpc->timeStamp,
                                "Nothing to do for stop backup of $host,"
@@ -1085,6 +1270,8 @@ sub Main_Check_Client_Messages
                 }
             } elsif ( $cmd =~ /^backup all$/ ) {
                 QueueAllPCs();
+            } elsif ( $cmd =~ /^BackupPC_nightly run$/ ) {
+                $RunNightlyWhenIdle = 1;
             } elsif ( $cmd =~ /^backup (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
                 my $hostIP = $1;
                 $host      = $2;
@@ -1126,6 +1313,36 @@ sub Main_Check_Client_Messages
                     $UserQueueOn{$hostIP} = 1;
                     $reply = "ok: requested backup of $host";
                 }
+            } elsif ( $cmd =~ /^archive (\S+)\s+(\S+)\s+(\S+)/ ) {
+                my $user         = $1;
+                my $archivehost  = $2;
+                my $reqFileName  = $3;
+               $host      = $bpc->uriUnesc($archivehost);
+                if ( !defined($Status{$host}) ) {
+                    print(LOG $bpc->timeStamp,
+                               "User $user requested archive of unknown archive host"
+                             . " $host");
+                    $reply = "archive error: unknown archive host $host";
+                } else {
+                    print(LOG $bpc->timeStamp,
+                               "User $user requested archive on $host"
+                             . " ($host)\n");
+                    if ( defined($Jobs{$host}) ) {
+                        $reply = "Archive currently running on $host, please try later";
+                    } else {
+                        unshift(@UserQueue, {
+                                host    => $host,
+                                hostIP  => $user,
+                                reqFileName => $reqFileName,
+                                reqTime => time,
+                                dhcp    => 0,
+                                archive => 1,
+                               userReq => 1,
+                        });
+                        $UserQueueOn{$host} = 1;
+                        $reply = "ok: requested archive on $host";
+                    }
+                }
             } elsif ( $cmd =~ /^restore (\S+)\s+(\S+)\s+(\S+)\s+(\S+)/ ) {
                 my $hostIP = $1;
                 $host      = $2;
@@ -1211,6 +1428,15 @@ sub Main_Check_Client_Messages
                 QueueLink($host);
             } elsif ( $cmd =~ /^log\s+(.*)/ ) {
                 print(LOG $bpc->timeStamp, "$1\n");
+            } elsif ( $cmd =~ /^server\s+(\w+)/ ) {
+                my($type) = $1;
+                if ( $type eq 'reload' ) {
+                    ServerReload("Reloading config/host files via CGI request");
+                } elsif ( $type eq 'shutdown' ) {
+                    $reply = "Shutting down...\n";
+                    syswrite($Clients{$client}{fh}, $reply, length($reply));
+                    ServerShutdown("Server shutting down...");
+                }
             } elsif ( $cmd =~ /^quit/ || $cmd =~ /^exit/ ) {
                 $nbytes = 0;
                 last;
@@ -1307,6 +1533,18 @@ sub StatusWrite
     }
 }
 
+#
+# Compare function for host sort.  Hosts with errors go first,
+# sorted with the oldest errors first.  The remaining hosts
+# are sorted so that those with the oldest backups go first.
+#
+sub HostSortCompare
+{
+    return -1 if ( $Status{$a}{error} ne "" && $Status{$b}{error} eq "" );
+    return  1 if ( $Status{$a}{error} eq "" && $Status{$b}{error} ne "" );
+    return $Status{$a}{endTime} <=> $Status{$b}{endTime};
+}
+
 #
 # Queue all the hosts for backup.  This means queuing all the fixed
 # ip hosts and all the dhcp address ranges.  We also additionally
@@ -1314,7 +1552,7 @@ sub StatusWrite
 #
 sub QueueAllPCs
 {
-    foreach my $host ( sort(keys(%$Hosts)) ) {
+    foreach my $host ( sort(HostSortCompare keys(%$Hosts)) ) {
         delete($Status{$host}{backoffTime})
                 if ( defined($Status{$host}{backoffTime})
                   && $Status{$host}{backoffTime} < time );
@@ -1420,7 +1658,7 @@ sub HostsUpdate
     }
     foreach my $host ( sort(keys(%Status)) ) {
         next if ( $host eq $bpc->trashJob
-                     || $host eq $bpc->adminJob
+                     || $bpc->isAdminJob($host)
                      || defined($Hosts->{$host})
                      || defined($Jobs{$host})
                      || $BgQueueOn{$host}
@@ -1440,7 +1678,7 @@ sub catch_signal
     if ( $SigName ) {
         $SigName = shift;
         foreach my $host ( keys(%Jobs) ) {
-            kill(2, $Jobs{$host}{pid});
+            kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
         }
         #
         # In case we are inside the exit handler, reopen the log file
@@ -1530,3 +1768,46 @@ sub ServerSocketInit
         $ServerInetPort = $Conf{ServerPort};
     }
 }
+
+#
+# Reload the server.  Used by Main_Process_Signal when $SigName eq "HUP"
+# or when the command "server reload" is received.
+#
+sub ServerReload
+{
+    my($mesg) = @_;
+    $mesg = $bpc->ConfigRead() || $mesg;
+    print(LOG $bpc->timeStamp, "$mesg\n");
+    $Info{ConfigModTime} = $bpc->ConfigMTime();
+    %Conf = $bpc->Conf();
+    umask($Conf{UmaskMode});
+    ServerSocketInit();
+    HostsUpdate(0);
+    $NextWakeup = 0;
+    $Info{ConfigLTime} = time;
+}
+
+#
+# Gracefully shutdown the server.  Used by Main_Process_Signal when
+# $SigName ne "" && $SigName ne "HUP" or when the command
+# "server shutdown" is received.
+#
+sub ServerShutdown
+{
+    my($mesg) = @_;
+    print(LOG $bpc->timeStamp, "$mesg\n");
+    if ( keys(%Jobs) ) {
+        foreach my $host ( keys(%Jobs) ) {
+            kill($bpc->sigName2num("INT"), $Jobs{$host}{pid});
+        }
+        sleep(1);
+        foreach my $host ( keys(%Jobs) ) {
+            kill($bpc->sigName2num("KILL"), $Jobs{$host}{pid});
+        }
+        %Jobs = ();
+    }
+    StatusWrite();
+    unlink("$TopDir/log/BackupPC.pid");
+    exit(1);
+}
+