File:  [LON-CAPA] / loncom / loncron
Revision 1.114: download - view: text, annotated - select for diffs
Sun Nov 18 22:50:46 2018 UTC (5 years, 6 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Scanning of lonnet.perm.log by loncron
  - Information about which nodes have unsent update transactions is logged.
  - Specific nodes can be excluded from unsend count (for delayed updates)
    via domain configuration.
  - Weight for unsend count (before adding to "warnings") is configurable.

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

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