File:  [LON-CAPA] / loncom / loncron
Revision 1.103.2.15: download - view: text, annotated - select for diffs
Wed Jul 10 04:11:41 2024 UTC (6 weeks, 2 days ago) by raeburn
Branches: version_2_11_X
Diff to branchpoint 1.103: preferred, unified
- For 2.11
  Backport 1.131

    1: #!/usr/bin/perl
    2: 
    3: # Housekeeping program, started by cron, loncontrol and loncron.pl
    4: #
    5: # $Id: loncron,v 1.103.2.15 2024/07/10 04:11:41 raeburn Exp $
    6: #
    7: # Copyright Michigan State University Board of Trustees
    8: #
    9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
   10: #
   11: # LON-CAPA is free software; you can redistribute it and/or modify
   12: # it under the terms of the GNU General Public License as published by
   13: # the Free Software Foundation; either version 2 of the License, or
   14: # (at your option) any later version.
   15: #
   16: # LON-CAPA is distributed in the hope that it will be useful,
   17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   19: # GNU General Public License for more details.
   20: #
   21: # You should have received a copy of the GNU General Public License
   22: # along with LON-CAPA; if not, write to the Free Software
   23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   24: #
   25: # /home/httpd/html/adm/gpl.txt
   26: #
   27: # http://www.lon-capa.org/
   28: #
   29: 
   30: $|=1;
   31: use strict;
   32: 
   33: use lib '/home/httpd/lib/perl/';
   34: use LONCAPA::Configuration;
   35: use LONCAPA::Checksumming;
   36: use LONCAPA;
   37: use Apache::lonnet;
   38: use Apache::loncommon;
   39: 
   40: use LWP::UserAgent();
   41: use HTTP::Request();
   42: use IO::File;
   43: use IO::Socket;
   44: use HTML::Entities;
   45: use Getopt::Long;
   46: use GDBM_File qw(GDBM_READER);
   47: use Storable qw(thaw);
   48: use File::ReadBackwards;
   49: use File::Copy;
   50: use Sys::Hostname::FQDN();
   51: 
   52: #globals
   53: use vars qw (%perlvar %simplestatus $errors $warnings $notices $totalcount);
   54: 
   55: my $statusdir="/home/httpd/html/lon-status";
   56: 
   57: 
   58: # --------------------------------------------------------- Output error status
   59: 
   60: sub log {
   61:     my $fh=shift;
   62:     if ($fh) {	print $fh @_  }
   63: }
   64: 
   65: sub errout {
   66:    my $fh=shift;
   67:    &log($fh,(<<ENDERROUT));
   68:      <table border="2" bgcolor="#CCCCCC">
   69:      <tr><td>Notices</td><td>$notices</td></tr>
   70:      <tr><td>Warnings</td><td>$warnings</td></tr>
   71:      <tr><td>Errors</td><td>$errors</td></tr>
   72:      </table><p><a href="#top">Top</a></p>
   73: ENDERROUT
   74: }
   75: 
   76: sub rotate_logfile {
   77:     my ($file,$fh,$description) = @_;
   78:     my $size=(stat($file))[7];
   79:     if ($size>40000) {
   80: 	&log($fh,"<p>Rotating $description ...</p>");
   81: 	rename("$file.2","$file.3");
   82: 	rename("$file.1","$file.2");
   83: 	rename("$file","$file.1");
   84:     }
   85: }
   86: 
   87: sub start_daemon {
   88:     my ($fh,$daemon,$pidfile,$args) = @_;
   89:     my $progname=$daemon;
   90:     if ($daemon eq 'lonc') {
   91: 	$progname='loncnew';
   92:     }
   93:     my $error_fname="$perlvar{'lonDaemons'}/logs/${daemon}_errors";
   94:     &rotate_logfile($error_fname,$fh,'error logs');
   95:     if ($daemon eq 'lonc') {
   96: 	&clean_sockets($fh);
   97:     }
   98:     system("$perlvar{'lonDaemons'}/$progname 2>$perlvar{'lonDaemons'}/logs/${daemon}_errors");
   99:     sleep 1;
  100:     if (-e $pidfile) {
  101: 	&log($fh,"<p>Seems like it started ...</p>");
  102: 	my $lfh=IO::File->new("$pidfile");
  103: 	my $daemonpid=<$lfh>;
  104: 	chomp($daemonpid);
  105: 	if ($daemonpid =~ /^\d+$/ && kill 0 => $daemonpid) {
  106: 	    return 1;
  107: 	} else {
  108: 	    return 0;
  109: 	}
  110:     }
  111:     &log($fh,"<p>Seems like that did not work!</p>");
  112:     $errors++;
  113:     return 0;
  114: }
  115: 
  116: sub checkon_daemon {
  117:     my ($fh,$daemon,$maxsize,$send,$args)=@_;
  118: 
  119:     my $result;
  120:     &log($fh,'<hr /><a name="'.$daemon.'" /><h2>'.$daemon.'</h2><h3>Log</h3><p style="white-space: pre;"><tt>');
  121:     printf("%-15s ",$daemon);
  122:     if ($fh) {
  123:         if (-e "$perlvar{'lonDaemons'}/logs/$daemon.log"){
  124: 	    if (open(DFH,"tail -n25 $perlvar{'lonDaemons'}/logs/$daemon.log|")) {
  125: 	        while (my $line=<DFH>) {
  126: 	            &log($fh,"$line");
  127: 	            if ($line=~/INFO/) { $notices++; }
  128: 	            if ($line=~/WARNING/) { $notices++; }
  129: 	            if ($line=~/CRITICAL/) { $warnings++; }
  130: 	        }
  131: 	        close (DFH);
  132:             }
  133:         }
  134:         &log($fh,"</tt></p>");
  135:     }
  136: 
  137:     my $pidfile="$perlvar{'lonDaemons'}/logs/$daemon.pid";
  138:  
  139:     my $restartflag=1;
  140:     my $daemonpid;
  141:     if (-e $pidfile) {
  142: 	my $lfh=IO::File->new("$pidfile");
  143: 	$daemonpid=<$lfh>;
  144: 	chomp($daemonpid);
  145: 	if ($daemonpid =~ /^\d+$/ && kill 0 => $daemonpid) {
  146: 	    &log($fh,"<h3>$daemon at pid $daemonpid responding");
  147: 	    if ($send) { &log($fh,", sending $send"); }
  148: 	    &log($fh,"</h3>");
  149: 	    if ($send eq 'USR1') { kill USR1 => $daemonpid; }
  150: 	    if ($send eq 'USR2') { kill USR2 => $daemonpid; }
  151: 	    $restartflag=0;
  152: 	    if ($send eq 'USR2') {
  153: 		$result = 'reloaded';
  154: 		print "reloaded\n";
  155: 	    } else {
  156: 		$result = 'running';
  157: 		print "running\n";
  158: 	    }
  159: 	} else {
  160: 	    $errors++;
  161: 	    &log($fh,"<h3>$daemon at pid $daemonpid not responding</h3>");
  162: 	    $restartflag=1;
  163: 	    &log($fh,"<h3>Decided to clean up stale .pid file and restart $daemon</h3>");
  164: 	}
  165:     }
  166:     if ($restartflag==1) {
  167: 	$simplestatus{$daemon}='off';
  168: 	$errors++;
  169: 	my $kadaemon=$daemon;
  170: 	if ($kadaemon eq 'lonmemcached') { $kadaemon='memcached'; }
  171: 	&log($fh,'<br /><font color="red">Killall '.$daemon.': '.
  172: 	    `killall $kadaemon 2>&1`.' - ');
  173: 	sleep 1;
  174: 	&log($fh,unlink($pidfile).' - '.
  175: 	    `killall -9 $kadaemon 2>&1`.
  176: 	    '</font><br />');
  177: 	&log($fh,"<h3>$daemon not running, trying to start</h3>");
  178: 
  179: 	if (&start_daemon($fh,$daemon,$pidfile,$args)) {
  180: 	    &log($fh,"<h3>$daemon at pid $daemonpid responding</h3>");
  181: 	    $simplestatus{$daemon}='restarted';
  182: 	    $result = 'started';
  183: 	    print "started\n";
  184: 	} else {
  185: 	    $errors++;
  186: 	    &log($fh,"<h3>$daemon at pid $daemonpid not responding</h3>");
  187: 	    &log($fh,"<p>Give it one more try ...</p>");
  188: 	    print " ";
  189: 	    if (&start_daemon($fh,$daemon,$pidfile,$args)) {
  190: 		&log($fh,"<h3>$daemon at pid $daemonpid responding</h3>");
  191: 		$simplestatus{$daemon}='restarted';
  192: 		$result = 'started';
  193: 		print "started\n";
  194: 	    } else {
  195: 		$result = 'failed';
  196: 		print " failed\n";
  197: 		$simplestatus{$daemon}='failed';
  198: 		$errors++; $errors++;
  199: 		&log($fh,"<h3>$daemon at pid $daemonpid not responding</h3>");
  200: 		&log($fh,"<p>Unable to start $daemon</p>");
  201: 	    }
  202: 	}
  203:         if ($fh) {
  204: 	    if (-e "$perlvar{'lonDaemons'}/logs/$daemon.log"){
  205: 	        &log($fh,"<p><pre>");
  206: 	        if (open(DFH,"tail -n100 $perlvar{'lonDaemons'}/logs/$daemon.log|")) {
  207: 	            while (my $line=<DFH>) { 
  208: 		        &log($fh,"$line");
  209: 		        if ($line=~/WARNING/) { $notices++; }
  210: 		        if ($line=~/CRITICAL/) { $notices++; }
  211: 	            }
  212: 	            close (DFH);
  213:                 }
  214: 	        &log($fh,"</pre></p>");
  215: 	    }
  216:         }
  217:     }
  218: 
  219:     my $fname="$perlvar{'lonDaemons'}/logs/$daemon.log";
  220:     &rotate_logfile($fname,$fh,'logs');
  221: 
  222:     &errout($fh);
  223:     return $result;
  224: }
  225: 
  226: # --------------------------------------------------------------------- Machine
  227: sub log_machine_info {
  228:     my ($fh)=@_;
  229:     &log($fh,'<hr /><a name="machine" /><h2>Machine Information</h2>');
  230:     &log($fh,"<h3>loadavg</h3>");
  231: 
  232:     my $cpucount;
  233:     if (open(PIPE,"lscpu |grep '^CPU(s)' 2>&1 |")) {
  234:         my $info = <PIPE>;
  235:         chomp($info);
  236:         ($cpucount) = ($info =~ /^\QCPU(s):\E\s+(\d+)$/);
  237:         close(PIPE);
  238:     }
  239:     if (!$cpucount) {
  240:         $cpucount = 1;
  241:     }
  242:     my %loadtarget = (
  243:                         error => 4.0*$cpucount,
  244:                         warn  => 2.0*$cpucount,
  245:                         note  => 1.0*$cpucount,
  246:                      );
  247:     open (LOADAVGH,"/proc/loadavg");
  248:     my $loadavg=<LOADAVGH>;
  249:     close (LOADAVGH);
  250: 
  251:     &log($fh,"<tt>$loadavg</tt>");
  252: 
  253:     my @parts=split(/\s+/,$loadavg);
  254:     if ($parts[1]>$loadtarget{'error'}) {
  255: 	$errors++;
  256:     } elsif ($parts[1]>$loadtarget{'warn'}) {
  257: 	$warnings++;
  258:     } elsif ($parts[1]>$loadtarget{'note'}) {
  259: 	$notices++;
  260:     }
  261: 
  262:     &log($fh,"<h3>df</h3>");
  263:     &log($fh,"<pre>");
  264: 
  265:     open (DFH,"df|");
  266:     while (my $line=<DFH>) {
  267: 	&log($fh,&encode_entities($line,'<>&"'));
  268: 	@parts=split(/\s+/,$line);
  269: 	my $usage=$parts[4];
  270: 	$usage=~s/\W//g;
  271: 	if ($usage>90) {
  272: 	    $warnings++;
  273: 	    $notices++;
  274: 	} elsif ($usage>80) {
  275: 	    $warnings++;
  276: 	} elsif ($usage>60) {
  277: 	    $notices++;
  278: 	}
  279: 	if ($usage>95) { $warnings++; $warnings++; $simplestatus{'diskfull'}++; }
  280:     }
  281:     close (DFH);
  282:     &log($fh,"</pre>");
  283: 
  284: 
  285:     &log($fh,"<h3>ps</h3>");
  286:     &log($fh,"<pre>");
  287:     my $psproc=0;
  288: 
  289:     open (PSH,"ps aux --cols 140 |");
  290:     while (my $line=<PSH>) {
  291: 	&log($fh,&encode_entities($line,'<>&"'));
  292: 	$psproc++;
  293:     }
  294:     close (PSH);
  295:     &log($fh,"</pre>");
  296: 
  297:     if ($psproc>200) { $notices++; }
  298:     if ($psproc>250) { $notices++; }
  299: 
  300:     &log($fh,"<h3>distprobe</h3>");
  301:     &log($fh,"<pre>");
  302:     &log($fh,&encode_entities(&LONCAPA::distro(),'<>&"'));
  303:     &log($fh,"</pre>");
  304: 
  305:     &errout($fh);
  306: }
  307: 
  308: sub start_logging {
  309:     my $fh=IO::File->new(">$statusdir/newstatus.html");
  310:     my %simplestatus=();
  311:     my $now=time;
  312:     my $date=localtime($now);
  313: 
  314: 
  315:     &log($fh,(<<ENDHEADERS));
  316: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  317: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  318: <head>
  319: <title>LON Status Report $perlvar{'lonHostID'}</title>
  320: <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  321: </head>
  322: <body bgcolor="#AAAAAA">
  323: <a name="top" />
  324: <h1>LON Status Report $perlvar{'lonHostID'}</h1>
  325: <h2>$date ($now)</h2>
  326: <ol>
  327: <li><a href="#configuration">Configuration</a></li>
  328: <li><a href="#machine">Machine Information</a></li>
  329: <li><a href="#tmp">Temporary Files</a></li>
  330: <li><a href="#tokens">Session Tokens</a></li>
  331: <li><a href="#webdav">WebDAV Session Tokens</a></li>
  332: <li><a href="#httpd">httpd</a></li>
  333: <li><a href="#lonsql">lonsql</a></li>
  334: <li><a href="#lond">lond</a></li>
  335: <li><a href="#lonc">lonc</a></li>
  336: <li><a href="#lonnet">lonnet</a></li>
  337: <li><a href="#connections">Connections</a></li>
  338: <li><a href="#bashconf">bash readline config</a></li>
  339: <li><a href="#delayed">Delayed Messages</a></li>
  340: <li><a href="#errcount">Error Count</a></li>
  341: </ol>
  342: <hr />
  343: <a name="configuration" />
  344: <h2>Configuration</h2>
  345: <h3>PerlVars</h3>
  346: <table border="2">
  347: ENDHEADERS
  348: 
  349:     foreach my $varname (sort(keys(%perlvar))) {
  350: 	&log($fh,"<tr><td>$varname</td><td>".
  351: 	     &encode_entities($perlvar{$varname},'<>&"')."</td></tr>\n");
  352:     }
  353:     &log($fh,"</table><h3>Hosts</h3><table border='2'>");
  354:     my %hostname = &Apache::lonnet::all_hostnames();
  355:     foreach my $id (sort(keys(%hostname))) {
  356: 	my $role = (&Apache::lonnet::is_library($id) ? 'library'
  357: 		                                     : 'access');
  358: 	&log($fh,
  359: 	    "<tr><td>$id</td><td>".&Apache::lonnet::host_domain($id).
  360: 	    "</td><td>".$role.
  361: 	    "</td><td>".&Apache::lonnet::hostname($id)."</td></tr>\n");
  362:     }
  363:     &log($fh,"</table><h3>Spare Hosts</h3>");
  364:     if (keys(%Apache::lonnet::spareid) > 0) {
  365:         &log($fh,"<ul>");
  366:         foreach my $type (sort(keys(%Apache::lonnet::spareid))) {
  367: 	    &log($fh,"<li>$type\n<ol>");
  368: 	    foreach my $id (@{ $Apache::lonnet::spareid{$type} }) {
  369: 	        &log($fh,"<li>$id</li>\n");
  370: 	    }
  371: 	    &log($fh,"</ol>\n</li>\n");
  372:         }
  373:         &log($fh,"</ul>\n");
  374:     } else {
  375:         &log($fh,"No spare hosts specified<br />\n");
  376:     }
  377:     return $fh;
  378: }
  379: 
  380: # --------------------------------------------------------------- clean out tmp
  381: sub clean_tmp {
  382:     my ($fh)=@_;
  383:     &log($fh,'<hr /><a name="tmp" /><h2>Temporary Files</h2>');
  384:     my ($cleaned,$old,$removed) = (0,0,0);
  385:     my %errors = (
  386:                      dir       => [],
  387:                      file      => [],
  388:                      failopen  => [],
  389:                  );
  390:     my %error_titles = (
  391:                          dir       => 'failed to remove empty directory:',
  392:                          file      => 'failed to unlike stale file',
  393:                          failopen  => 'failed to open file or directory'
  394:                        );
  395:     ($cleaned,$old,$removed) = &recursive_clean_tmp('',$cleaned,$old,$removed,\%errors);
  396:     &log($fh,"Cleaned up: ".$cleaned." files; removed: $removed empty directories; (found: $old old checkout tokens)");
  397:     foreach my $key (sort(keys(%errors))) {
  398:         if (ref($errors{$key}) eq 'ARRAY') {
  399:             if (@{$errors{$key}} > 0) {
  400:                 &log($fh,"Error during cleanup ($error_titles{$key}):<ul><li>".
  401:                      join('</li><li><tt>',@{$errors{$key}}).'</tt></li></ul><br />');
  402:             }
  403:         }
  404:     }
  405: }
  406: 
  407: sub recursive_clean_tmp {
  408:     my ($subdir,$cleaned,$old,$removed,$errors) = @_;
  409:     my $base = "$perlvar{'lonDaemons'}/tmp";
  410:     my $path = $base;
  411:     next if ($subdir =~ m{\.\./});
  412:     next unless (ref($errors) eq 'HASH');
  413:     unless ($subdir eq '') {
  414:         $path .= '/'.$subdir;
  415:     }
  416:     if (opendir(my $dh,"$path")) {
  417:         while (my $file = readdir($dh)) {
  418:             next if ($file =~ /^\.\.?$/);
  419:             my $fname = "$path/$file";
  420:             if (-d $fname) {
  421:                 my $innerdir;
  422:                 if ($subdir eq '') {
  423:                     $innerdir = $file;
  424:                 } else {
  425:                     $innerdir = $subdir.'/'.$file;
  426:                 }
  427:                 ($cleaned,$old,$removed) = 
  428:                      &recursive_clean_tmp($innerdir,$cleaned,$old,$removed,$errors);
  429:                 my @doms = &Apache::lonnet::current_machine_domains();
  430: 
  431:                 if (open(my $dirhandle,$fname)) {
  432:                     unless (($innerdir eq 'helprequests') ||
  433:                             (($innerdir =~ /^addcourse/) && ($innerdir !~ m{/\d+$}))) {
  434:                         my @contents = grep {!/^\.\.?$/} readdir($dirhandle);
  435:                                       join('&&',@contents)."\n";
  436:                         if (scalar(grep {!/^\.\.?$/} readdir($dirhandle)) == 0) {
  437:                             closedir($dirhandle);
  438:                             if ($fname =~ m{^\Q$perlvar{'lonDaemons'}\E/tmp/}) {
  439:                                 if (rmdir($fname)) {
  440:                                     $removed ++;
  441:                                 } elsif (ref($errors->{dir}) eq 'ARRAY') {
  442:                                     push(@{$errors->{dir}},$fname);
  443:                                 }
  444:                             }
  445:                         }
  446:                     } else {
  447:                         closedir($dirhandle);
  448:                     }
  449:                 }
  450:             } else {
  451:                 my ($dev,$ino,$mode,$nlink,
  452:                     $uid,$gid,$rdev,$size,
  453:                     $atime,$mtime,$ctime,
  454:                     $blksize,$blocks)=stat($fname);
  455:                 my $now=time;
  456:                 my $since=$now-$mtime;
  457:                 if ($since>$perlvar{'lonExpire'}) {
  458:                     if ($subdir eq '') {
  459:                         my $line='';
  460:                         if ($fname =~ /\.db$/) {
  461:                             if (unlink($fname)) {
  462:                                 $cleaned++;
  463:                             } elsif (ref($errors->{file}) eq 'ARRAY') {
  464:                                 push(@{$errors->{file}},$fname);
  465:                             }
  466:                         } elsif (open(PROBE,$fname)) {
  467:                             my $line='';
  468:                             $line=<PROBE>;
  469:                             close(PROBE);
  470:                             if ($line=~/^CHECKOUTTOKEN\&/) {
  471:                                 if ($since>365*$perlvar{'lonExpire'}) {
  472:                                     if (unlink($fname)) {
  473:                                         $cleaned++; 
  474:                                     } elsif (ref($errors->{file}) eq 'ARRAY') {
  475:                                         push(@{$errors->{file}},$fname);
  476:                                     }
  477:                                 } else {
  478:                                     $old++;
  479:                                 }
  480:                             } else {
  481:                                 if (unlink($fname)) {
  482:                                     $cleaned++;
  483:                                 } elsif (ref($errors->{file}) eq 'ARRAY') {
  484:                                     push(@{$errors->{file}},$fname);
  485:                                 }
  486:                             }
  487:                         } elsif (ref($errors->{failopen}) eq 'ARRAY') {
  488:                             push(@{$errors->{failopen}},$fname);
  489:                         }
  490:                     } else {
  491:                         if (unlink($fname)) {
  492:                             $cleaned++;
  493:                         } elsif (ref($errors->{file}) eq 'ARRAY') {
  494:                             push(@{$errors->{file}},$fname);
  495:                         }
  496:                     }
  497:                 }
  498:             }
  499:         }
  500:         closedir($dh);
  501:     } elsif (ref($errors->{failopen}) eq 'ARRAY') {
  502:         push(@{$errors->{failopen}},$path);
  503:     }
  504:     return ($cleaned,$old,$removed);
  505: }
  506: 
  507: # ------------------------------------------------------------ clean out lonIDs
  508: sub clean_lonIDs {
  509:     my ($fh)=@_;
  510:     &log($fh,'<hr /><a name="tokens" /><h2>Session Tokens</h2>');
  511:     my $cleaned=0;
  512:     my $active=0;
  513:     while (my $fname=<$perlvar{'lonIDsDir'}/*>) {
  514:         my $now=time;
  515:         if (-l $fname) {
  516:             my $linkfname = readlink($fname);
  517:             if (-f $linkfname) {
  518:                 if ($linkfname =~ m{^$perlvar{'lonIDsDir'}/[^/]+\.id$}) {
  519:                     my @data = stat($linkfname);
  520:                     my $mtime = $data[9];
  521:                     my $since=$now-$mtime;
  522:                     if ($since>$perlvar{'lonExpire'}) {
  523:                         if (unlink($linkfname)) {
  524:                             $cleaned++;
  525:                             &log($fh,"Unlinking $linkfname<br />");
  526:                             unlink($fname);
  527:                         }
  528:                     }
  529:                 }
  530:             } else {
  531:                unlink($fname);
  532:             }
  533:         } elsif (-f $fname) {
  534:             my @data = stat($fname);
  535:             my $mtime = $data[9];
  536:             my $since=$now-$mtime;
  537:             if ($since>$perlvar{'lonExpire'}) {
  538:                 if (unlink($fname)) {
  539:                     $cleaned++;
  540:                     &log($fh,"Unlinking $fname<br />");
  541:                 }
  542:             } else {
  543:                 $active++;
  544:             }
  545:         }
  546:     }
  547:     &log($fh,"<p>Cleaned up ".$cleaned." stale session token(s).</p>");
  548:     &log($fh,"<h3>$active open session(s)</h3>");
  549: }
  550: 
  551: # -------------------------------------------------------- clean out balanceIDs
  552: 
  553: sub clean_balanceIDs {
  554:     my ($fh)=@_;
  555:     &log($fh,'<hr /><a name="balcookies" /><h2>Session Tokens</h2>');
  556:     my $cleaned=0;
  557:     my $active=0;
  558:     if (-d $perlvar{'lonBalanceDir'}) {
  559:         while (my $fname=<$perlvar{'lonBalanceDir'}/*.id>) {
  560:             my ($dev,$ino,$mode,$nlink,
  561:                 $uid,$gid,$rdev,$size,
  562:                 $atime,$mtime,$ctime,
  563:                 $blksize,$blocks)=stat($fname);
  564:             my $now=time;
  565:             my $since=$now-$mtime;
  566:             if ($since>$perlvar{'lonExpire'}) {
  567:                 $cleaned++;
  568:                 &log($fh,"Unlinking $fname<br />");
  569:                 unlink("$fname");
  570:             } else {
  571:                 $active++;
  572:             }
  573:         }
  574:     }
  575:     &log($fh,"<p>Cleaned up ".$cleaned." stale balancer files</p>");
  576:     &log($fh,"<h3>$active unexpired balancer files</h3>");
  577: }
  578: 
  579: # ------------------------------------------------ clean out webDAV Session IDs
  580: sub clean_webDAV_sessionIDs {
  581:     my ($fh)=@_;
  582:     if ($perlvar{'lonRole'} eq 'library') {
  583:         &log($fh,'<hr /><a name="webdav" /><h2>WebDAV Session Tokens</h2>');
  584:         my $cleaned=0;
  585:         my $active=0;
  586:         my $now = time;
  587:         if (-d $perlvar{'lonDAVsessDir'}) {
  588:             while (my $fname=<$perlvar{'lonDAVsessDir'}/*>) {
  589:                 my @stats = stat($fname);
  590:                 my $since=$now-$stats[9];
  591:                 if ($since>$perlvar{'lonExpire'}) {
  592:                     $cleaned++;
  593:                     &log($fh,"Unlinking $fname<br />");
  594:                     unlink("$fname");
  595:                 } else {
  596:                     $active++;
  597:                 }
  598:             }
  599:             &log($fh,"<p>Cleaned up ".$cleaned." stale webDAV session token(s).</p>");
  600:             &log($fh,"<h3>$active open webDAV session(s)</h3>");
  601:         }
  602:     }
  603: }
  604: 
  605: # ----------------------------------------------------------- clean out sockets
  606: sub clean_sockets {
  607:     my ($fh)=@_;
  608:     my $cleaned=0;
  609:     opendir(SOCKETS,$perlvar{'lonSockDir'});
  610:     while (my $fname=readdir(SOCKETS)) {
  611: 	next if (-d $fname 
  612: 		 || $fname=~/(mysqlsock|maximasock|rsock|\Q$perlvar{'lonSockDir'}\E)/);
  613: 	$cleaned++;
  614: 	&log($fh,"Unlinking $fname<br />");
  615: 	unlink("/home/httpd/sockets/$fname");
  616:     }
  617:     &log($fh,"<p>Cleaned up ".$cleaned." stale sockets.</p>");
  618: }
  619: 
  620: 
  621: # ----------------------------------------------------------------------- httpd
  622: sub check_httpd_logs {
  623:     my ($fh)=@_;
  624:     if (open(PIPE,"./lchttpdlogs|")) {
  625:         while (my $line=<PIPE>) {
  626:             &log($fh,$line);
  627:             if ($line=~/\[error\]/) { $notices++; }
  628:         }
  629:         close(PIPE);
  630:     }
  631:     &errout($fh);
  632: }
  633: 
  634: # ---------------------------------------------------------------------- lonnet
  635: 
  636: sub rotate_lonnet_logs {
  637:     my ($fh)=@_;
  638:     &log($fh,'<hr /><a name="lonnet" /><h2>lonnet</h2><h3>Temp Log</h3><pre>');
  639:     print "Checking logs.\n";
  640:     if (-e "$perlvar{'lonDaemons'}/logs/lonnet.log"){
  641: 	open (DFH,"tail -n50 $perlvar{'lonDaemons'}/logs/lonnet.log|");
  642: 	while (my $line=<DFH>) {
  643: 	    &log($fh,&encode_entities($line,'<>&"'));
  644: 	}
  645: 	close (DFH);
  646:     }
  647:     &log($fh,"</pre><h3>Perm Log</h3><pre>");
  648: 
  649:     if (-e "$perlvar{'lonDaemons'}/logs/lonnet.perm.log") {
  650: 	open(DFH,"tail -n10 $perlvar{'lonDaemons'}/logs/lonnet.perm.log|");
  651: 	while (my $line=<DFH>) {
  652: 	    &log($fh,&encode_entities($line,'<>&"'));
  653: 	}
  654: 	close (DFH);
  655:     } else { &log($fh,"No perm log\n") }
  656: 
  657:     my $fname="$perlvar{'lonDaemons'}/logs/lonnet.log";
  658:     &rotate_logfile($fname,$fh,'lonnet log');
  659: 
  660:     &log($fh,"</pre>");
  661:     &errout($fh);
  662: }
  663: 
  664: sub rotate_other_logs {
  665:     my ($fh) = @_;
  666:     my %logs = (
  667:                   autoenroll          => 'Auto Enroll log',
  668:                   autocreate          => 'Create Course log',
  669:                   searchcat           => 'Search Cataloguing log',
  670:                   autoupdate          => 'Auto Update log',
  671:                   refreshcourseids_db => 'Refresh CourseIDs db log',
  672:                );
  673:     foreach my $item (keys(%logs)) {
  674:         my $fname=$perlvar{'lonDaemons'}.'/logs/'.$item.'.log';
  675:         &rotate_logfile($fname,$fh,$logs{$item});
  676:     }
  677: }
  678: 
  679: # ----------------------------------------------------------------- Connections
  680: sub test_connections {
  681:     my ($fh)=@_;
  682:     &log($fh,'<hr /><a name="connections" /><h2>Connections</h2>');
  683:     print "Testing connections.\n";
  684:     &log($fh,"<table border='2'>");
  685:     my ($good,$bad)=(0,0);
  686:     my %hostname = &Apache::lonnet::all_hostnames();
  687:     foreach my $tryserver (sort(keys(%hostname))) {
  688: 	print(".");
  689: 	my $result;
  690: 	my $answer=&Apache::lonnet::reply("ping",$tryserver);
  691: 	if ($answer eq "$tryserver:$perlvar{'lonHostID'}") {
  692: 	    $result="<b>ok</b>";
  693: 	    $good++;
  694: 	} else {
  695: 	    $result=$answer;
  696: 	    $warnings++;
  697: 	    if ($answer eq 'con_lost') {
  698: 		$bad++;
  699: 		$warnings++;
  700: 	    } else {
  701: 		$good++; #self connection
  702: 	    }
  703: 	}
  704: 	if ($answer =~ /con_lost/) { print(" $tryserver down\n"); }
  705: 	&log($fh,"<tr><td>$tryserver</td><td>$result</td></tr>\n");
  706:     }
  707:     &log($fh,"</table>");
  708:     print "\n$good good, $bad bad connections\n";
  709:     &errout($fh);
  710: }
  711: 
  712: 
  713: # ------------------------------------------------------------ Delayed messages
  714: sub check_delayed_msg {
  715:     my ($fh,$weightsref,$exclusionsref)=@_;
  716:     &log($fh,'<hr /><a name="delayed" /><h2>Delayed Messages</h2>');
  717:     print "Checking buffers.\n";
  718:     
  719:     &log($fh,'<h3>Scanning Permanent Log</h3>');
  720: 
  721:     my $unsend=0;
  722:     my $ignored=0;
  723: 
  724:     my %hostname = &Apache::lonnet::all_hostnames();
  725:     my $numhosts = scalar(keys(%hostname));
  726:     my $checkbackwards = 0;
  727:     my $checkfrom = 0;
  728:     my $checkexcluded = 0;
  729:     my (%bymachine,%weights,%exclusions,%serverhomes);
  730:     if (ref($weightsref) eq 'HASH') {
  731:         %weights = %{$weightsref};
  732:     }
  733:     if (ref($exclusionsref) eq 'HASH') {
  734:         %exclusions = %{$exclusionsref};
  735:         if (keys(%exclusions)) {
  736:             $checkexcluded = 1;
  737:             %serverhomes = &read_serverhomeIDs();
  738:         }
  739:     }
  740: 
  741: #
  742: # For LON-CAPA 1.2.0 to 2.1.3 (release dates: 8/31/2004 and 3/31/2006) any
  743: # entry logged in lonnet.perm.log for completion of a delayed (critical)
  744: # transaction lacked the hostID for the remote node to which the command
  745: # to be completed was sent.
  746: #
  747: # Because of this, exclusion of items in lonnet.perm.log for nodes which are
  748: # no longer part of the cluster from adding to the overall "unsend" count
  749: # needs additional effort besides the changes made in loncron rev. 1.105.
  750: #
  751: # For "S" (completion) events logging in LON-CAPA 1.2.0 through 2.1.3 included
  752: # "LondTransaction=HASH(hexadecimal)->getClient() :$cmd, where the hexadecimal
  753: # is a memory location, and $cmd is the command sent to the remote node.
  754: #
  755: # Starting with 2.2.0 (released 8/21/2006) logging for "S" (completion) events
  756: # had sethost:$host_id:$cmd after LondTransaction=HASH(hexadecimal)->getClient()
  757: #
  758: # Starting with 2.4.1 (released 6/13/2007) logging for "S" replaced echoing the
  759: # getClient() call with the result of the Transaction->getClient() call itself
  760: # undef for completion of delivery of a delayed message.
  761: #
  762: # The net effect of these changes is that lonnet.perm.log is now accessed three
  763: # times: (a) oldest record is checked, if earlier than release date for 2.5.0
  764: # then (b) file is read backwards, with timestamp recorded for most recent
  765: # instance of logged "S" event for "update" command without "sethost:$host_id:"
  766: # then (c) file is read forward with records ignored which predate the timestamp
  767: # recorded in (b), if one was found.
  768: #
  769: # In (c), when calculating the unsend total, i.e., the difference between delayed
  770: # transactions ("D") and sent transactions ("S"), transactions are ignored if the
  771: # target node is no longer in the cluster, and also (for "update" commands), if
  772: # the target node is in the list of nodes excluded from the count, in the domain
  773: # configuration for this machine's default domain.  The idea here is to remove
  774: # delayed "update" commands for nodes for which inbound access to port 5663,
  775: # is blocked, but are still part of the LON-CAPA network, (i.e., they can still
  776: # replicate content from other nodes).
  777: #
  778: 
  779:     my $dfh=IO::File->new("$perlvar{'lonDaemons'}/logs/lonnet.perm.log","r");
  780:     if (defined($dfh)) {
  781:         while (my $line=<$dfh>) {
  782: 	    my ($time,$sdf,$rest)=split(/:/,$line,3);
  783:             if ($time < 1541185772) {
  784:                 $checkbackwards = 1;
  785:             }
  786:             last;
  787:         }
  788:         undef $dfh;
  789:     }
  790: 
  791:     if ($checkbackwards) {
  792:         if (tie *BW, 'File::ReadBackwards', "$perlvar{'lonDaemons'}/logs/lonnet.perm.log") {
  793:             while(my $line=<BW>) {
  794:                 if ($line =~ /\QLondTransaction=HASH\E[^:]+:update:/) {
  795:                     ($checkfrom) = split(/:/,$line,2);
  796:                     last;
  797:                 }
  798:             }
  799:             close(BW);
  800:         }
  801:     }
  802:     $dfh=IO::File->new("$perlvar{'lonDaemons'}/logs/lonnet.perm.log","r");
  803:     if (defined($dfh)) {
  804:         while (my $line=<$dfh>) {
  805:             my ($time,$sdf,$rest)=split(/:/,$line,3);
  806:             next unless (($sdf eq 'F') || ($sdf eq 'S') || ($sdf eq 'D'));
  807:             next if (($checkfrom) && ($time <= $checkfrom));
  808:             my ($dserv,$dcmd);
  809:             if ($sdf eq 'S') {
  810:                 my ($serva,$cmda,$servb,$cmdb) = split(/:/,$rest);
  811:                 if ($cmda eq 'sethost') {
  812:                     chomp($cmdb);
  813:                     $dcmd = $cmdb;
  814:                 } else {
  815:                     $dcmd = $cmda;
  816:                 }
  817:                 if (($serva =~ /^LondTransaction/) || ($serva eq '')) {
  818:                     unless (($servb eq '') || ($servb =~ m{^/})) {
  819:                         $dserv = $servb;
  820:                     }
  821:                 } else {
  822:                     $dserv = $serva;
  823:                 }
  824:             } else {
  825:                 ($dserv,$dcmd) = split(/:/,$rest);
  826:             }
  827:             if ($sdf eq 'F') {
  828:                 my $local=localtime($time);
  829:                 &log($fh,"<b>Failed: $time, $dserv, $dcmd</b><br />");
  830:                 $warnings++;
  831:             }
  832:             next if ((($dserv eq '') || ($dcmd eq '')) && ($sdf ne 'F'));
  833:             if ($sdf eq 'S') {
  834:                 if ($dcmd eq 'update') {
  835:                     if ($hostname{$dserv}) {
  836:                         if ($exclusions{$serverhomes{$hostname{$dserv}}}) {
  837:                             $ignored --;
  838:                         } else {
  839:                             $unsend --;
  840:                         }
  841:                     }
  842:                     if (exists($bymachine{$dserv})) {
  843:                         $bymachine{$dserv} --;
  844:                     } else {
  845:                         $bymachine{$dserv} = -1;
  846:                     }
  847:                 } else {
  848:                     if ($hostname{$dserv}) {
  849:                         $unsend --;
  850:                     }
  851:                 }
  852:             } elsif ($sdf eq 'D') {
  853:                 if ($dcmd eq 'update') {
  854:                     if ($hostname{$dserv}) {
  855:                         if ($exclusions{$serverhomes{$hostname{$dserv}}}) {
  856:                             $ignored ++;
  857:                         } else {
  858:                             $unsend ++;
  859:                         }
  860:                     }
  861:                     if (exists($bymachine{$dserv})) {
  862:                         $bymachine{$dserv} ++;
  863:                     } else {
  864:                         $bymachine{$dserv} = 1;
  865:                     }
  866:                 } else {
  867:                     if ($hostname{$dserv}) {
  868:                         $unsend ++;
  869:                     }
  870:                 }
  871:             }
  872:         }
  873:         undef $dfh;
  874:         my $nodest = 0;
  875:         my $retired = 0;
  876:         my %active;
  877:         if (keys(%bymachine)) {
  878:             unless ($checkexcluded) {
  879:                 %serverhomes = &read_serverhomeIDs();
  880:             }
  881:             foreach my $key (keys(%bymachine)) {
  882:                 if ($bymachine{$key} > 0) {
  883:                     if ($hostname{$key}) {
  884:                         $active{$serverhomes{$hostname{$key}}} += $bymachine{$key};
  885:                     } else {
  886:                         $retired ++;
  887:                         $nodest += $bymachine{$key};
  888:                     }
  889:                 }
  890:             }
  891:         }
  892:         if (keys(%active)) {
  893:             &log($fh,"<p>Unsend messages by node, active (undegraded) nodes in cluster</p>\n");
  894:             foreach my $key (sort(keys(%active))) {
  895:                 &log($fh,&encode_entities("$key => $active{$key}",'<>&"')."\n");
  896:             }
  897:         }
  898:         &log($fh,"<p>Total unsend messages: <b>$unsend</b> for ".scalar(keys(%active))." active (undegraded) nodes in cluster.</p>\n");
  899:         if (keys(%exclusions) > 0) {
  900:             &log($fh,"<p>Total incomplete updates <b>$ignored</b> for ".scalar(keys(%exclusions))." degraded nodes in cluster.</p>\n");
  901:         }
  902:         if ($retired) {
  903:             &log($fh,"<p>Total unsent <b>$nodest</b> for $retired nodes no longer in cluster.</p>\n");
  904:         }
  905:         if ($unsend > 0) {
  906:             $warnings=$warnings+$weights{'U'}*$unsend;
  907:         }
  908:     }
  909: 
  910:     if ($unsend) { $simplestatus{'unsend'}=$unsend; }
  911:     &log($fh,"<h3>Outgoing Buffer</h3>\n<pre>");
  912: # list directory with delayed messages and remember offline servers
  913:     my %servers=();
  914:     open (DFH,"ls -lF $perlvar{'lonSockDir'}/delayed|");
  915:     while (my $line=<DFH>) {
  916:         my ($server)=($line=~/\.(\w+)$/);
  917:         if ($server) { $servers{$server}=1; }
  918: 	&log($fh,&encode_entities($line,'<>&"'));
  919:     }
  920:     &log($fh,"</pre>\n");
  921:     close (DFH);
  922: # pong to all servers that have delayed messages
  923: # this will trigger a reverse connection, which should flush the buffers
  924:     foreach my $tryserver (sort(keys(%servers))) {
  925:         if ($hostname{$tryserver} || !$numhosts) {
  926:             my $answer;
  927:             eval {
  928:                 local $SIG{ ALRM } = sub { die "TIMEOUT" };
  929:                 alarm(20);
  930:                 $answer = &Apache::lonnet::reply("pong",$tryserver);
  931:                 alarm(0);
  932:             };
  933:             if ($@ && $@ =~ m/TIMEOUT/) {
  934:                 &log($fh,"Attempted pong to $tryserver timed out<br />");
  935:                 print "Time out while contacting: $tryserver for pong.\n";
  936:             } else {
  937:                 &log($fh,"Pong to $tryserver: $answer<br />");
  938:             }
  939:         } else {
  940:             &log($fh,"$tryserver has delayed messages, but is not part of the cluster -- skipping 'Pong'.<br />");
  941:         }
  942:     }
  943: }
  944: 
  945: sub finish_logging {
  946:     my ($fh,$weightsref)=@_;
  947:     my %weights;
  948:     if (ref($weightsref) eq 'HASH') {
  949:         %weights = %{$weightsref};
  950:     }
  951:     &log($fh,"<a name='errcount' />\n");
  952:     $totalcount=($weights{'N'}*$notices)+($weights{'W'}*$warnings)+($weights{'E'}*$errors);
  953:     &errout($fh);
  954:     &log($fh,"<h1>Total Error Count: $totalcount</h1>");
  955:     my $now=time;
  956:     my $date=localtime($now);
  957:     &log($fh,"<hr />$date ($now)</body></html>\n");
  958:     print "lon-status webpage updated.\n";
  959:     $fh->close();
  960: 
  961:     if ($errors) { $simplestatus{'errors'}=$errors; }
  962:     if ($warnings) { $simplestatus{'warnings'}=$warnings; }
  963:     if ($notices) { $simplestatus{'notices'}=$notices; }
  964:     $simplestatus{'time'}=time;
  965: }
  966: 
  967: sub log_simplestatus {
  968:     rename("$statusdir/newstatus.html","$statusdir/index.html");
  969:     
  970:     my $sfh=IO::File->new(">$statusdir/loncron_simple.txt");
  971:     foreach (keys %simplestatus) {
  972: 	print $sfh $_.'='.$simplestatus{$_}.'&';
  973:     }
  974:     print $sfh "\n";
  975:     $sfh->close();
  976: }
  977: 
  978: sub write_loncaparevs {
  979:     print "Retrieving LON-CAPA version information.\n";
  980:     my %hostname = &Apache::lonnet::all_hostnames();
  981:     my $output;
  982:     foreach my $id (sort(keys(%hostname))) {
  983:         if ($id ne '') {
  984:             my $loncaparev;
  985:             eval {
  986:                 local $SIG{ ALRM } = sub { die "TIMEOUT" };
  987:                 alarm(10);
  988:                 $loncaparev =
  989:                     &Apache::lonnet::get_server_loncaparev('',$id,1,'loncron');
  990:                 alarm(0);
  991:             };
  992:             if ($@ && $@ =~ m/TIMEOUT/) {
  993:                 print "Time out while contacting lonHost: $id for version.\n";   
  994:             }
  995:             if ($loncaparev =~ /^[\w.\-]+$/) {
  996:                 $output .= $id.':'.$loncaparev."\n";
  997:             }
  998:         }
  999:     }
 1000:     if ($output) {
 1001:         if (open(my $fh,">$perlvar{'lonTabDir'}/loncaparevs.tab")) {
 1002:             print $fh $output;
 1003:             close($fh);
 1004:             &Apache::lonnet::load_loncaparevs();
 1005:         }
 1006:     }
 1007:     return;
 1008: }
 1009: 
 1010: sub write_serverhomeIDs {
 1011:     print "Retrieving LON-CAPA lonHostID information.\n";
 1012:     my %name_to_host = &Apache::lonnet::all_names();
 1013:     my $output;
 1014:     foreach my $name (sort(keys(%name_to_host))) {
 1015:         if ($name ne '') {
 1016:             if (ref($name_to_host{$name}) eq 'ARRAY') {
 1017:                 my $serverhomeID;
 1018:                 eval {
 1019:                     local $SIG{ ALRM } = sub { die "TIMEOUT" };
 1020:                     alarm(10);
 1021:                     $serverhomeID =
 1022:                         &Apache::lonnet::get_server_homeID($name,1,'loncron');
 1023:                     alarm(0);
 1024:                 };
 1025:                 if ($@ && $@ =~ m/TIMEOUT/) {
 1026:                     print "Time out while contacting server: $name\n"; 
 1027:                 }
 1028:                 if ($serverhomeID ne '') {
 1029:                     $output .= $name.':'.$serverhomeID."\n";
 1030:                 } else {
 1031:                     $output .= $name.':'.$name_to_host{$name}->[0]."\n";
 1032:                 }
 1033:             }
 1034:         }
 1035:     }
 1036:     if ($output) {
 1037:         if (open(my $fh,">$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
 1038:             print $fh $output;
 1039:             close($fh);
 1040:             &Apache::lonnet::load_serverhomeIDs();
 1041:         }
 1042:     }
 1043:     return;
 1044: }
 1045: 
 1046: sub write_checksums {
 1047:     my $distro = &LONCAPA::distro();
 1048:     if ($distro) {
 1049:         print "Retrieving file version and checksumming.\n";
 1050:         my $numchksums = 0;
 1051:         my ($chksumsref,$versionsref) =
 1052:             &LONCAPA::Checksumming::get_checksums($distro,$perlvar{'lonDaemons'},
 1053:                                                   $perlvar{'lonLib'},
 1054:                                                   $perlvar{'lonIncludes'},
 1055:                                                   $perlvar{'lonTabDir'});
 1056:         if (ref($chksumsref) eq 'HASH') {
 1057:             $numchksums = scalar(keys(%{$chksumsref}));
 1058:         }
 1059:         print "File version retrieved and checksumming completed for $numchksums files.\n";
 1060:     } else {
 1061:         print "File version retrieval and checksumming skipped - could not determine Linux distro.\n"; 
 1062:     }
 1063:     return;
 1064: }
 1065: 
 1066: sub write_hostips {
 1067:     my $lontabdir = $perlvar{'lonTabDir'};
 1068:     my $defdom = $perlvar{'lonDefDomain'};
 1069:     my $lonhost = $perlvar{'lonHostID'};
 1070:     my $newfile = "$lontabdir/currhostips.tab";
 1071:     my $oldfile = "$lontabdir/prevhostips.tab";
 1072:     my (%prevhosts,%currhosts,%ipchange);
 1073:     if ((-e $newfile) && (-s $newfile)) {
 1074:         move($newfile,$oldfile);
 1075:         chmod(0644,$oldfile);
 1076:         if (open(my $fh,'<',$oldfile)) {
 1077:             while (my $line=<$fh>) {
 1078:                 chomp($line);
 1079:                 if ($line =~ /^([^:]+):([\d.]+)$/) {
 1080:                     $prevhosts{$1} = $2;
 1081:                 }
 1082:             }
 1083:             close($fh);
 1084:         }
 1085:     }
 1086:     my ($ip_info,$cached) =
 1087:         &Apache::lonnet::is_cached_new('iphost','iphost');
 1088:     if (!$cached) {
 1089:         &Apache::lonnet::get_iphost();
 1090:         ($ip_info,$cached) =
 1091:         &Apache::lonnet::is_cached_new('iphost','iphost');
 1092:     }
 1093:     if (ref($ip_info) eq 'ARRAY') {
 1094:         %currhosts = %{$ip_info->[1]};
 1095:         if (open(my $fh,'>',$newfile)) {
 1096:             foreach my $key (keys(%currhosts)) {
 1097:                 print $fh "$key:$currhosts{$key}\n";
 1098:             }
 1099:             close($fh);
 1100:             chmod(0644,$newfile);
 1101:         }
 1102:     }
 1103:     if (keys(%prevhosts) && keys(%currhosts)) {
 1104:         foreach my $key (keys(%prevhosts)) {
 1105:             unless ($currhosts{$key} eq $prevhosts{$key}) {
 1106:                 $ipchange{$key} = $prevhosts{$key}.' | '.$currhosts{$key};
 1107:             }
 1108:         }
 1109:         foreach my $key (keys(%currhosts)) {
 1110:             unless ($currhosts{$key} eq $prevhosts{$key}) {
 1111:                 $ipchange{$key} = $prevhosts{$key}.' | '.$currhosts{$key};
 1112:             }
 1113:         }
 1114:     }
 1115:     if (&Apache::lonnet::domain($defdom,'primary') eq $lonhost) {
 1116:         if (keys(%ipchange)) {
 1117:             if (open(my $fh,'>>',$perlvar{'lonDaemons'}.'/logs/hostip.log')) {
 1118:                print $fh "********************\n".localtime(time).' Changes --'."\n".
 1119:                          "| Hostname | Previous IP | New IP |\n".
 1120:                          " --------------------------------- \n";
 1121:                foreach my $hostname (sort(keys(%ipchange))) {
 1122:                     print $fh "| $hostname | $ipchange{$hostname} |\n";
 1123:                 }
 1124:                 print $fh "\n*******************\n\n";
 1125:                 close($fh);
 1126:             }
 1127:             my $emailto = &Apache::loncommon::build_recipient_list(undef,
 1128:                                    'hostipmail',$defdom);
 1129:             if ($emailto) {
 1130:                 my $subject = "LON-CAPA Hostname to IP change ($perlvar{'lonHostID'})";
 1131:                 my $chgmail = "To: $emailto\n".
 1132:                               "Subject: $subject\n".
 1133:                               "Content-type: text/plain\; charset=UTF-8\n".
 1134:                               "MIME-Version: 1.0\n\n".
 1135:                               "Host/IP changes\n".
 1136:                               " \n".
 1137:                               "| Hostname | Previous IP | New IP |\n".
 1138:                               " --------------------------------- \n";
 1139:                 foreach my $hostname (sort(keys(%ipchange))) {
 1140:                     $chgmail .= "| $hostname | $ipchange{$hostname} |\n";
 1141:                 }
 1142:                 $chgmail .= "\n\n";
 1143:                 if (open(my $mailh, "|/usr/lib/sendmail -oi -t -odb")) {
 1144:                     print $mailh $chgmail;
 1145:                     close($mailh);
 1146:                     print "Sending mail notification of hostname/IP changes.\n";
 1147:                 }
 1148:             }
 1149:         }
 1150:     }
 1151:     return;
 1152: }
 1153: 
 1154: sub get_domain_config {
 1155:     my ($dom,$primlibserv,$isprimary,$url,%confhash);
 1156:     $dom = $perlvar{'lonDefDomain'};
 1157:     $primlibserv = &Apache::lonnet::domain($dom,'primary');
 1158:     if ($primlibserv eq $perlvar{'lonHostID'}) {
 1159:         $isprimary = 1;
 1160:     } elsif ($primlibserv ne '') {
 1161:         my $protocol = $Apache::lonnet::protocol{$primlibserv};
 1162:         my $hostname = &Apache::lonnet::hostname($primlibserv);
 1163:         unless ($protocol eq 'https') {
 1164:             $protocol = 'http';
 1165:         }
 1166:         $url = $protocol.'://'.$hostname.'/cgi-bin/listdomconfig.pl?primary='.$primlibserv.'&format=raw';
 1167:     }
 1168:     if ($isprimary) {
 1169:         my $lonusersdir = $perlvar{'lonUsersDir'};
 1170:         my $fname = $lonusersdir.'/'.$dom.'/configuration.db';
 1171:         if (-e $fname) {
 1172:             my $dbref=&LONCAPA::locking_hash_tie($fname,&GDBM_READER());
 1173:             if (ref($dbref) eq 'HASH') {
 1174:                 foreach my $key (sort(keys(%{$dbref}))) {
 1175:                     my $value = $dbref->{$key};
 1176:                     if ($value =~ s/^__FROZEN__//) {
 1177:                         $value = thaw(&LONCAPA::unescape($value));
 1178:                     } else {
 1179:                         $value = &LONCAPA::unescape($value);
 1180:                     }
 1181:                     $confhash{$key} = $value;
 1182:                 }
 1183:                 &LONCAPA::locking_hash_untie($dbref);
 1184:             }
 1185:         }
 1186:     } else {
 1187:         my $ua=new LWP::UserAgent;
 1188:         $ua->timeout(5);
 1189:         my $request=new HTTP::Request('GET',$url);
 1190:         my $response=$ua->request($request);
 1191:         unless ($response->is_error()) {
 1192:             my $content = $response->content;
 1193:             if ($content) {
 1194:                 my @pairs=split(/\&/,$content);
 1195:                 foreach my $item (@pairs) {
 1196:                     my ($key,$value)=split(/=/,$item,2);
 1197:                     my $what = &LONCAPA::unescape($key);
 1198:                     if ($value =~ s/^__FROZEN__//) {
 1199:                         $value = thaw(&LONCAPA::unescape($value));
 1200:                     } else {
 1201:                         $value = &LONCAPA::unescape($value);
 1202:                     }
 1203:                     $confhash{$what}=$value;
 1204:                 }
 1205:             }
 1206:         }
 1207:     }
 1208:     return \%confhash;
 1209: }
 1210: 
 1211: sub get_permcount_settings {
 1212:     my ($domconf) = @_;
 1213:     my ($defaults,$names) = &Apache::loncommon::lon_status_items();
 1214:     my (%weights,$threshold,$sysmail,$reportstatus,%exclusions);
 1215:     foreach my $type ('E','W','N','U') {
 1216:         $weights{$type} = $defaults->{$type};
 1217:     }
 1218:     $threshold = $defaults->{'threshold'};
 1219:     $sysmail = $defaults->{'sysmail'};
 1220:     $reportstatus = 1;
 1221:     if (ref($domconf) eq 'HASH') {
 1222:         if (ref($domconf->{'contacts'}) eq 'HASH') {
 1223:             if ($domconf->{'contacts'}{'reportstatus'} == 0) {
 1224:                 $reportstatus = 0;
 1225:             }
 1226:             if (ref($domconf->{'contacts'}{'lonstatus'}) eq 'HASH') {
 1227:                 if (ref($domconf->{'contacts'}{'lonstatus'}{weights}) eq 'HASH') {
 1228:                     foreach my $type ('E','W','N','U') {
 1229:                         if (exists($domconf->{'contacts'}{'lonstatus'}{weights}{$type})) {
 1230:                             $weights{$type} = $domconf->{'contacts'}{'lonstatus'}{weights}{$type};
 1231:                         }
 1232:                     }
 1233:                 }
 1234:                 if (ref($domconf->{'contacts'}{'lonstatus'}{'excluded'}) eq 'ARRAY') {
 1235:                     my @excluded = @{$domconf->{'contacts'}{'lonstatus'}{'excluded'}};
 1236:                     if (@excluded) {
 1237:                         map { $exclusions{$_} = 1; } @excluded;
 1238:                     }
 1239:                 }
 1240:                 if (exists($domconf->{'contacts'}{'lonstatus'}{'threshold'})) {
 1241:                     $threshold = $domconf->{'contacts'}{'lonstatus'}{'threshold'};
 1242:                 }
 1243:                 if (exists($domconf->{'contacts'}{'lonstatus'}{'sysmail'})) {
 1244:                     $sysmail = $domconf->{'contacts'}{'lonstatus'}{'sysmail'};
 1245:                 }
 1246:             }
 1247:         }
 1248:     }
 1249:     return ($threshold,$sysmail,$reportstatus,\%weights,\%exclusions);
 1250: }
 1251: 
 1252: sub read_serverhomeIDs {
 1253:     my %server;
 1254:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
 1255:         if (open(my $fh,'<',"$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
 1256:             while (<$fh>) {
 1257:                 my($host,$id) = split(/:/);
 1258:                 chomp($id);
 1259:                 $server{$host} = $id;
 1260:             }
 1261:             close($fh);
 1262:         }
 1263:     }
 1264:     return %server;
 1265: }
 1266: 
 1267: sub check_bash_settings {
 1268:     my $distro = &LONCAPA::distro();
 1269:     my ($check_bracketed_paste,$bracketed_warning);
 1270:     if ($distro  =~ /^debian(\d+)$/) {
 1271:         if ($1 >= 12) {
 1272:             $check_bracketed_paste = 1;
 1273:         }
 1274:     } elsif ($distro =~ /^ubuntu(\d+)$/) {
 1275:         if ($1 >= 22) {
 1276:             $check_bracketed_paste = 1;
 1277:         }
 1278:     } elsif ($distro =~ /^(?:redhat|oracle|alma|rocky|centos-stream)(\d+)$/) {
 1279:         if ($1 >= 9) {
 1280:             $check_bracketed_paste = 1;
 1281:         }
 1282:     } elsif ($distro =~ /^fedora(\d+)/) {
 1283:         if ($1 >= 34) {
 1284:             $check_bracketed_paste = 1;
 1285:         }
 1286:     }
 1287:     if ($check_bracketed_paste) {
 1288:         if (open(PIPE,"bind -V 2>&1 | grep enable-bracketed-paste |")) {
 1289:             my $info = <PIPE>;
 1290:             chomp($info);
 1291:             my ($bracketed) = ($info =~ /^\Qenable-bracketed-paste\E\s+is\s+set\s+to\s+\W(on|off)\W$/);
 1292:             close(PIPE);
 1293:             if ($bracketed eq 'on') {
 1294:                 $bracketed_warning = 1;
 1295:             }
 1296:         } else {
 1297:             print "Unable to check if bracketed paste is set to off for www user's shell\n";
 1298:         }
 1299:     }
 1300:     return ($bracketed_warning,$check_bracketed_paste);
 1301: }
 1302: 
 1303: sub set_bracketed_paste_off {
 1304:     my $bash_www_cnf = '/home/www/.inputrc';
 1305:     my $result;
 1306:     if (!-e $bash_www_cnf) {
 1307:         system("touch $bash_www_cnf");
 1308:         if (open(my $cfh,'>',$bash_www_cnf)) {
 1309:             print $cfh "set enable-bracketed-paste off\n";
 1310:             close($cfh);
 1311:             $result = "Updated $bash_www_cnf";
 1312:         } else {
 1313:             $result = "Could not open $bash_www_cnf to add 'set enable-bracketed-paste to off'";
 1314:         }
 1315:         my $wwwuid = getpwnam('www');
 1316:         my $wwwgid = getgrnam('www');
 1317:         if ($wwwuid!=$<) {
 1318:             chown($wwwuid,$wwwgid,$bash_www_cnf);
 1319:         }
 1320:     } else {
 1321:         my ($bracketed_paste_on,$bracketed_paste_off,@preserve);
 1322:         if (open(my $cfh,'<',$bash_www_cnf)) {
 1323:             while (my $line=<$cfh>) {
 1324:                 chomp($line);
 1325:                 if ($line =~ /^\s*set\s+enable\-bracketed\-paste\s+(off|on)\s*$/) {
 1326:                     if ($1 eq 'off') {
 1327:                         $bracketed_paste_off = 1;
 1328:                     } else {
 1329:                         $bracketed_paste_on = 1;
 1330:                     }
 1331:                 } else {
 1332:                     push(@preserve,$line);
 1333:                 }
 1334:             }
 1335:             close($cfh);
 1336:             if ($bracketed_paste_on || !$bracketed_paste_off) {
 1337:                 if (open(my $cfh,'>',$bash_www_cnf)) {
 1338:                     print $cfh "set enable-bracketed-paste off\n";
 1339:                     if (@preserve) {
 1340:                         foreach my $entry (@preserve) {
 1341:                             print $cfh "$entry\n";
 1342:                         }
 1343:                     }
 1344:                     close($cfh);
 1345:                     $result = "Updated $bash_www_cnf";
 1346:                 } else {
 1347:                     $result = "Could not open $bash_www_cnf to add 'set enable-bracketed-paste to off'";
 1348:                 }
 1349:             } else {
 1350:                 $result = "No action needed; $bash_www_cnf already includes 'set enable-bracketed-paste to off'";
 1351:             }
 1352:         } else {
 1353:             $result = "Could not open $bash_www_cnf to check if a value is included for 'enable-bracketed-paste'.";
 1354:         }
 1355:     }
 1356:     return $result;
 1357: }
 1358: 
 1359: sub send_mail {
 1360:     my ($sysmail,$reportstatus) = @_;
 1361:     my $defdom = $perlvar{'lonDefDomain'};
 1362:     my $origmail = $perlvar{'lonAdmEMail'};
 1363:     my $emailto = &Apache::loncommon::build_recipient_list(undef,
 1364:                                    'lonstatusmail',$defdom,$origmail);
 1365:     if (($totalcount>$sysmail) && ($reportstatus)) {
 1366: 	$emailto.=",$perlvar{'lonSysEMail'}";
 1367:     }
 1368:     my $from;
 1369:     my $hostname=`/bin/hostname`;
 1370:     chop($hostname);
 1371:     $hostname=~s/[^\w\.]//g;
 1372:     if ($hostname) {
 1373:         $from = 'www@'.$hostname;
 1374:     }
 1375:     my $subj="LON: $perlvar{'lonHostID'} E:$errors W:$warnings N:$notices";
 1376:     my $loncronmail = "To: $emailto\n".
 1377:                       "From: $from\n".
 1378:                       "Subject: ".$subj."\n".
 1379:                       "Content-type: text/html\; charset=UTF-8\n".
 1380:                       "MIME-Version: 1.0\n\n";
 1381:     if (open(my $fh,"<$statusdir/index.html")) {
 1382:         while (<$fh>) {
 1383:             $loncronmail .= $_;
 1384:         }
 1385:         close($fh);
 1386:     } else {
 1387:         $loncronmail .= "Failed to read from http://$hostname/lon-status/index.html\n";
 1388:     }
 1389:     $loncronmail .= "\n\n";
 1390:     if (open(my $mailh, "|/usr/lib/sendmail -oi -t -odb")) {
 1391:         print $mailh $loncronmail;
 1392:         close($mailh);
 1393:         print "Sending mail.\n";
 1394:     } else {
 1395:         print "Sending mail failed.\n";
 1396:     }
 1397: }
 1398: 
 1399: sub usage {
 1400:     print(<<USAGE);
 1401: loncron - housekeeping program that checks up on various parts of LON-CAPA
 1402: 
 1403: Options:
 1404:    --help     Display 
 1405:    --noemail  Do not send the status email
 1406:    --justcheckconnections  Only check the current status of the lonc/d
 1407:                                 connections, do not send emails do not
 1408:                                 check if the daemons are running, do not
 1409:                                 generate lon-status
 1410:    --justcheckdaemons      Only check that all of the Lon-CAPA daemons are
 1411:                                 running, do not send emails do not
 1412:                                 check the lonc/d connections, do not
 1413:                                 generate lon-status
 1414:    --justreload            Only tell the daemons to reload the config files,
 1415: 				do not send emails do not
 1416:                                 check if the daemons are running, do not
 1417:                                 generate lon-status
 1418:    --justiptables          Only update the dynamic iptables rules for the
 1419:                                 lond port; do not send emails, do not
 1420:                                 check if the daemons are running, do not
 1421:                                 generate lon-status
 1422: USAGE
 1423: }
 1424: 
 1425: # ================================================================ Main Program
 1426: sub main () {
 1427:     my ($help,$justcheckdaemons,$noemail,$justcheckconnections,
 1428: 	$justreload,$justiptables);
 1429:     &GetOptions("help"                 => \$help,
 1430: 		"justcheckdaemons"     => \$justcheckdaemons,
 1431: 		"noemail"              => \$noemail,
 1432: 		"justcheckconnections" => \$justcheckconnections,
 1433: 		"justreload"           => \$justreload,
 1434:                 "justiptables"         => \$justiptables
 1435: 		);
 1436:     if ($help) { &usage(); return; }
 1437: # --------------------------------- Read loncapa_apache.conf and loncapa.conf
 1438:     my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
 1439:     %perlvar=%{$perlvarref};
 1440:     undef $perlvarref;
 1441:     delete $perlvar{'lonReceipt'}; # remove since sensitive and not needed
 1442:     delete $perlvar{'lonSqlAccess'}; # remove since sensitive and not needed
 1443:     chdir($perlvar{'lonDaemons'});
 1444: # --------------------------------------- Make sure that LON-CAPA is configured
 1445: # I only test for one thing here (lonHostID).  This is just a safeguard.
 1446:     if ('{[[[[lonHostID]]]]}' eq $perlvar{'lonHostID'}) {
 1447: 	print("Unconfigured machine.\n");
 1448: 	my $emailto=$perlvar{'lonSysEMail'};
 1449: 	my $hostname = Sys::Hostname::FQDN::fqdn();
 1450: 	$hostname=~s/\.+/./g;
 1451: 	$hostname=~s/\-+/-/g;
 1452: 	$hostname=~s/[^\w\.-]//g; # make sure is safe to pass through shell
 1453: 	my $subj="LON: Unconfigured machine $hostname";
 1454: 	system("echo 'Unconfigured machine $hostname.' |".
 1455:                " mail -s '$subj' $emailto > /dev/null");
 1456: 	exit 1;
 1457:     }
 1458: 
 1459: # ----------------------------- Make sure this process is running from user=www
 1460:     my $wwwid=getpwnam('www');
 1461:     if ($wwwid!=$<) {
 1462: 	print("User ID mismatch. This program must be run as user 'www'.\n");
 1463: 	my $emailto="$perlvar{'lonAdmEMail'} $perlvar{'lonSysEMail'}";
 1464: 	my $subj="LON: $perlvar{'lonHostID'} User ID mismatch";
 1465: 	system("echo 'User ID mismatch. loncron must be run as user www.' |".
 1466:                " mail -s '$subj' $emailto > /dev/null");
 1467: 	exit 1;
 1468:     }
 1469: 
 1470: # -------------------------------------------- Force reload of host information
 1471:     my $nomemcache;
 1472:     if ($justcheckdaemons) {
 1473:         $nomemcache=1;
 1474:         my $memcachepidfile="$perlvar{'lonDaemons'}/logs/memcached.pid";
 1475:         my $memcachepid;
 1476:         if (-e $memcachepidfile) {
 1477:             my $memfh=IO::File->new($memcachepidfile);
 1478:             $memcachepid=<$memfh>;
 1479:             chomp($memcachepid);
 1480:             if ($memcachepid =~ /^\d+$/ && kill 0 => $memcachepid) {
 1481:                 undef($nomemcache);
 1482:             }
 1483:         }
 1484:     }
 1485:     if (!$justiptables) {
 1486:         &Apache::lonnet::load_hosts_tab(1,$nomemcache);
 1487:         &Apache::lonnet::load_domain_tab(1,$nomemcache);
 1488:         &Apache::lonnet::get_iphost(1,$nomemcache);
 1489:     }
 1490: 
 1491: # ----------------------------------------- Force firewall update for lond port
 1492: 
 1493:     if ((!$justcheckdaemons) && (!$justreload)) {
 1494:         my $now = time;
 1495:         my $tmpfile = $perlvar{'lonDaemons'}.'/tmp/lciptables_iphost_'.
 1496:                       $now.$$.int(rand(10000));
 1497:         if (open(my $fh,">$tmpfile")) {
 1498:             my %iphosts = &Apache::lonnet::get_iphost();
 1499:             foreach my $key (keys(%iphosts)) {
 1500:                 print $fh "$key\n";
 1501:             }
 1502:             close($fh);
 1503:             if (&LONCAPA::try_to_lock('/tmp/lock_lciptables')) {
 1504:                 my $execpath = $perlvar{'lonDaemons'}.'/lciptables';
 1505:                 system("$execpath $tmpfile");
 1506:                 unlink('/tmp/lock_lciptables');  # Remove the lock file.
 1507:             }
 1508:             unlink($tmpfile);
 1509:         }
 1510:     }
 1511: 
 1512: # ---------------------------------------------------------------- Start report
 1513: 
 1514:     $errors=0;
 1515:     $warnings=0;
 1516:     $notices=0;
 1517: 
 1518: 
 1519:     my $fh;
 1520:     if (!$justcheckdaemons && !$justcheckconnections && !$justreload && !$justiptables) {
 1521: 	$fh=&start_logging();
 1522: 
 1523: 	&log_machine_info($fh);
 1524: 	&clean_tmp($fh);
 1525: 	&clean_lonIDs($fh);
 1526:         &clean_balanceIDs($fh);
 1527:         &clean_webDAV_sessionIDs($fh);
 1528: 	&check_httpd_logs($fh);
 1529: 	&rotate_lonnet_logs($fh);
 1530: 	&rotate_other_logs($fh);
 1531:     }
 1532:     if (!$justcheckconnections && !$justreload && !$justiptables) {
 1533: 	&checkon_daemon($fh,'lonmemcached',40000);
 1534: 	&checkon_daemon($fh,'lonsql',200000);
 1535: 	if ( &checkon_daemon($fh,'lond',40000,'USR1') eq 'running') {
 1536: 	    &checkon_daemon($fh,'lond',40000,'USR2');
 1537: 	}
 1538: 	&checkon_daemon($fh,'lonc',40000,'USR1');
 1539:         &checkon_daemon($fh,'lonmaxima',40000);
 1540:         &checkon_daemon($fh,'lonr',40000);
 1541:     }
 1542:     if ($justreload) {
 1543: 	&checkon_daemon($fh,'lond',40000,'USR2');
 1544: 	&checkon_daemon($fh,'lonc',40000,'USR2');
 1545:     }
 1546:     if ($justcheckconnections) {
 1547: 	&test_connections($fh);
 1548:     }
 1549:     if (!$justcheckdaemons && !$justcheckconnections && !$justreload && !$justiptables) {
 1550:         my ($bracketed_warning,$check_bracketed_paste) = &check_bash_settings();
 1551:         if ($check_bracketed_paste) {
 1552:            &log($fh,'<hr /><a name="bashconf" /><h2>bash readline config</h2><h3>Bracketed Paste</h3>'.
 1553:                 '<p>Distros using bash readline library 8.1 or later need bracketed paste disabled for www, so R commands sent to lon daemon will be processed.</p>');
 1554:            if ($bracketed_warning) {
 1555:                my $bash_update = &set_bracketed_paste_off();
 1556:                if ($bash_update) {
 1557:                    &log($fh,'<p>'.$bash_update.'</p>'."\n");
 1558:                }
 1559:            } else {
 1560:                &log($fh,'<p>No action needed; /home/www/.inputrc already set.</p>'."\n");
 1561:            }
 1562:         } else {
 1563:             &log($fh,'<hr /><a name="bashconf" /><h2>bash readline config</h2><h3>Bracketed Paste</h3>'.
 1564:                      '<p>No action needed for distros using pre-8.1 bash readline library</p>'."\n");
 1565:         }
 1566:         my $domconf = &get_domain_config();
 1567:         my ($threshold,$sysmail,$reportstatus,$weightsref,$exclusionsref) =
 1568:             &get_permcount_settings($domconf);
 1569: 	&check_delayed_msg($fh,$weightsref,$exclusionsref);
 1570: 	&finish_logging($fh,$weightsref);
 1571: 	&log_simplestatus();
 1572:         &write_loncaparevs();
 1573:         &write_serverhomeIDs();
 1574: 	&write_checksums();
 1575:         &write_hostips();
 1576:         if ($totalcount>$threshold && !$noemail) { &send_mail($sysmail,$reportstatus); }
 1577:     }
 1578: }
 1579: 
 1580: &main();
 1581: 1;
 1582: 

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>