File:  [LON-CAPA] / loncom / loncron
Revision 1.116: download - view: text, annotated - select for diffs
Sat Dec 22 20:05:16 2018 UTC (5 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Use LWP to retrieve domain configuration from domain's primary library server.

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

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