File:  [LON-CAPA] / loncom / loncron
Revision 1.103.2.2: download - view: text, annotated - select for diffs
Sun Feb 10 03:02:10 2019 UTC (5 years, 2 months ago) by raeburn
Branches: version_2_11_X
Diff to branchpoint 1.103: preferred, unified
- For 2.11
  Backport 1.110, 1.111, 1.112.

    1: #!/usr/bin/perl
    2: 
    3: # Housekeeping program, started by cron, loncontrol and loncron.pl
    4: #
    5: # $Id: loncron,v 1.103.2.2 2019/02/10 03:02:10 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: #globals
   45: use vars qw (%perlvar %simplestatus $errors $warnings $notices $totalcount);
   46: 
   47: my $statusdir="/home/httpd/html/lon-status";
   48: 
   49: 
   50: # --------------------------------------------------------- Output error status
   51: 
   52: sub log {
   53:     my $fh=shift;
   54:     if ($fh) {	print $fh @_  }
   55: }
   56: 
   57: sub errout {
   58:    my $fh=shift;
   59:    &log($fh,(<<ENDERROUT));
   60:      <table border="2" bgcolor="#CCCCCC">
   61:      <tr><td>Notices</td><td>$notices</td></tr>
   62:      <tr><td>Warnings</td><td>$warnings</td></tr>
   63:      <tr><td>Errors</td><td>$errors</td></tr>
   64:      </table><p><a href="#top">Top</a></p>
   65: ENDERROUT
   66: }
   67: 
   68: sub rotate_logfile {
   69:     my ($file,$fh,$description) = @_;
   70:     my $size=(stat($file))[7];
   71:     if ($size>40000) {
   72: 	&log($fh,"<p>Rotating $description ...</p>");
   73: 	rename("$file.2","$file.3");
   74: 	rename("$file.1","$file.2");
   75: 	rename("$file","$file.1");
   76:     } 
   77: }
   78: 
   79: sub start_daemon {
   80:     my ($fh,$daemon,$pidfile,$args) = @_;
   81:     my $progname=$daemon;
   82:     if ($daemon eq 'lonc') {
   83: 	$progname='loncnew'; 
   84:     }
   85:     my $error_fname="$perlvar{'lonDaemons'}/logs/${daemon}_errors";
   86:     &rotate_logfile($error_fname,$fh,'error logs');
   87:     if ($daemon eq 'lonc') {
   88: 	&clean_sockets($fh);
   89:     }
   90:     system("$perlvar{'lonDaemons'}/$progname 2>$perlvar{'lonDaemons'}/logs/${daemon}_errors");
   91:     sleep 1;
   92:     if (-e $pidfile) {
   93: 	&log($fh,"<p>Seems like it started ...</p>");
   94: 	my $lfh=IO::File->new("$pidfile");
   95: 	my $daemonpid=<$lfh>;
   96: 	chomp($daemonpid);
   97: 	if ($daemonpid =~ /^\d+$/ && kill 0 => $daemonpid) {
   98: 	    return 1;
   99: 	} else {
  100: 	    return 0;
  101: 	}
  102:     }
  103:     &log($fh,"<p>Seems like that did not work!</p>");
  104:     $errors++;
  105:     return 0;
  106: }
  107: 
  108: sub checkon_daemon {
  109:     my ($fh,$daemon,$maxsize,$send,$args)=@_;
  110: 
  111:     my $result;
  112:     &log($fh,'<hr /><a name="'.$daemon.'" /><h2>'.$daemon.'</h2><h3>Log</h3><p style="white-space: pre;"><tt>');
  113:     printf("%-15s ",$daemon);
  114:     if ($fh) {
  115:         if (-e "$perlvar{'lonDaemons'}/logs/$daemon.log"){
  116: 	    if (open(DFH,"tail -n25 $perlvar{'lonDaemons'}/logs/$daemon.log|")) {
  117: 	        while (my $line=<DFH>) {
  118: 	            &log($fh,"$line");
  119: 	            if ($line=~/INFO/) { $notices++; }
  120: 	            if ($line=~/WARNING/) { $notices++; }
  121: 	            if ($line=~/CRITICAL/) { $warnings++; }
  122: 	        }
  123: 	        close (DFH);
  124:             }
  125:         }
  126:         &log($fh,"</tt></p>");
  127:     }
  128:    
  129:     my $pidfile="$perlvar{'lonDaemons'}/logs/$daemon.pid";
  130:     
  131:     my $restartflag=1;
  132:     my $daemonpid;
  133:     if (-e $pidfile) {
  134: 	my $lfh=IO::File->new("$pidfile");
  135: 	$daemonpid=<$lfh>;
  136: 	chomp($daemonpid);
  137: 	if ($daemonpid =~ /^\d+$/ && kill 0 => $daemonpid) {
  138: 	    &log($fh,"<h3>$daemon at pid $daemonpid responding");
  139: 	    if ($send) { &log($fh,", sending $send"); }
  140: 	    &log($fh,"</h3>");
  141: 	    if ($send eq 'USR1') { kill USR1 => $daemonpid; }
  142: 	    if ($send eq 'USR2') { kill USR2 => $daemonpid; }
  143: 	    $restartflag=0;
  144: 	    if ($send eq 'USR2') {
  145: 		$result = 'reloaded';
  146: 		print "reloaded\n";
  147: 	    } else {
  148: 		$result = 'running';
  149: 		print "running\n";
  150: 	    }
  151: 	} else {
  152: 	    $errors++;
  153: 	    &log($fh,"<h3>$daemon at pid $daemonpid not responding</h3>");
  154: 	    $restartflag=1;
  155: 	    &log($fh,"<h3>Decided to clean up stale .pid file and restart $daemon</h3>");
  156: 	}
  157:     }
  158:     if ($restartflag==1) {
  159: 	$simplestatus{$daemon}='off';
  160: 	$errors++;
  161: 	my $kadaemon=$daemon;
  162: 	if ($kadaemon eq 'lonmemcached') { $kadaemon='memcached'; }
  163: 	&log($fh,'<br /><font color="red">Killall '.$daemon.': '.
  164: 	    `killall $kadaemon 2>&1`.' - ');
  165: 	sleep 1;
  166: 	&log($fh,unlink($pidfile).' - '.
  167: 	    `killall -9 $kadaemon 2>&1`.
  168: 	    '</font><br />');
  169: 	&log($fh,"<h3>$daemon not running, trying to start</h3>");
  170: 
  171: 	if (&start_daemon($fh,$daemon,$pidfile,$args)) {
  172: 	    &log($fh,"<h3>$daemon at pid $daemonpid responding</h3>");
  173: 	    $simplestatus{$daemon}='restarted';
  174: 	    $result = 'started';
  175: 	    print "started\n";
  176: 	} else {
  177: 	    $errors++;
  178: 	    &log($fh,"<h3>$daemon at pid $daemonpid not responding</h3>");
  179: 	    &log($fh,"<p>Give it one more try ...</p>");
  180: 	    print " ";
  181: 	    if (&start_daemon($fh,$daemon,$pidfile,$args)) {
  182: 		&log($fh,"<h3>$daemon at pid $daemonpid responding</h3>");
  183: 		$simplestatus{$daemon}='restarted';
  184: 		$result = 'started';
  185: 		print "started\n";
  186: 	    } else {
  187: 		$result = 'failed';
  188: 		print " failed\n";
  189: 		$simplestatus{$daemon}='failed';
  190: 		$errors++; $errors++;
  191: 		&log($fh,"<h3>$daemon at pid $daemonpid not responding</h3>");
  192: 		&log($fh,"<p>Unable to start $daemon</p>");
  193: 	    }
  194: 	}
  195:         if ($fh) {
  196: 	    if (-e "$perlvar{'lonDaemons'}/logs/$daemon.log"){
  197: 	        &log($fh,"<p><pre>");
  198: 	        if (open(DFH,"tail -n100 $perlvar{'lonDaemons'}/logs/$daemon.log|")) {
  199: 	            while (my $line=<DFH>) { 
  200: 		        &log($fh,"$line");
  201: 		        if ($line=~/WARNING/) { $notices++; }
  202: 		        if ($line=~/CRITICAL/) { $notices++; }
  203: 	            }
  204: 	            close (DFH);
  205:                 }
  206: 	        &log($fh,"</pre></p>");
  207: 	    }
  208:         }
  209:     }
  210:     
  211:     my $fname="$perlvar{'lonDaemons'}/logs/$daemon.log";
  212:     &rotate_logfile($fname,$fh,'logs');
  213: 
  214:     &errout($fh);
  215:     return $result;
  216: }
  217: 
  218: # --------------------------------------------------------------------- Machine
  219: sub log_machine_info {
  220:     my ($fh)=@_;
  221:     &log($fh,'<hr /><a name="machine" /><h2>Machine Information</h2>');
  222:     &log($fh,"<h3>loadavg</h3>");
  223: 	
  224:     open (LOADAVGH,"/proc/loadavg");
  225:     my $loadavg=<LOADAVGH>;
  226:     close (LOADAVGH);
  227:     
  228:     &log($fh,"<tt>$loadavg</tt>");
  229:     
  230:     my @parts=split(/\s+/,$loadavg);
  231:     if ($parts[1]>4.0) {
  232: 	$errors++;
  233:     } elsif ($parts[1]>2.0) {
  234: 	$warnings++;
  235:     } elsif ($parts[1]>1.0) {
  236: 	$notices++;
  237:     }
  238: 
  239:     &log($fh,"<h3>df</h3>");
  240:     &log($fh,"<pre>");
  241: 
  242:     open (DFH,"df|");
  243:     while (my $line=<DFH>) { 
  244: 	&log($fh,&encode_entities($line,'<>&"')); 
  245: 	@parts=split(/\s+/,$line);
  246: 	my $usage=$parts[4];
  247: 	$usage=~s/\W//g;
  248: 	if ($usage>90) { 
  249: 	    $warnings++;
  250: 	    $notices++; 
  251: 	} elsif ($usage>80) {
  252: 	    $warnings++;
  253: 	} elsif ($usage>60) {
  254: 	    $notices++;
  255: 	}
  256: 	if ($usage>95) { $warnings++; $warnings++; $simplestatus{'diskfull'}++; }
  257:     }
  258:     close (DFH);
  259:     &log($fh,"</pre>");
  260: 
  261: 
  262:     &log($fh,"<h3>ps</h3>");
  263:     &log($fh,"<pre>");
  264:     my $psproc=0;
  265: 
  266:     open (PSH,"ps aux --cols 140 |");
  267:     while (my $line=<PSH>) { 
  268: 	&log($fh,&encode_entities($line,'<>&"')); 
  269: 	$psproc++;
  270:     }
  271:     close (PSH);
  272:     &log($fh,"</pre>");
  273: 
  274:     if ($psproc>200) { $notices++; }
  275:     if ($psproc>250) { $notices++; }
  276: 
  277:     &log($fh,"<h3>distprobe</h3>");
  278:     &log($fh,"<pre>");
  279:     &log($fh,&encode_entities(&LONCAPA::distro(),'<>&"'));
  280:     &log($fh,"</pre>");
  281: 
  282:     &errout($fh);
  283: }
  284: 
  285: sub start_logging {
  286:     my $fh=IO::File->new(">$statusdir/newstatus.html");
  287:     my %simplestatus=();
  288:     my $now=time;
  289:     my $date=localtime($now);
  290:     
  291: 
  292:     &log($fh,(<<ENDHEADERS));
  293: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  294: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  295: <head>
  296: <title>LON Status Report $perlvar{'lonHostID'}</title>
  297: <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  298: </head>
  299: <body bgcolor="#AAAAAA">
  300: <a name="top" />
  301: <h1>LON Status Report $perlvar{'lonHostID'}</h1>
  302: <h2>$date ($now)</h2>
  303: <ol>
  304: <li><a href="#configuration">Configuration</a></li>
  305: <li><a href="#machine">Machine Information</a></li>
  306: <li><a href="#tmp">Temporary Files</a></li>
  307: <li><a href="#tokens">Session Tokens</a></li>
  308: <li><a href="#webdav">WebDAV Session Tokens</a></li>
  309: <li><a href="#httpd">httpd</a></li>
  310: <li><a href="#lonsql">lonsql</a></li>
  311: <li><a href="#lond">lond</a></li>
  312: <li><a href="#lonc">lonc</a></li>
  313: <li><a href="#lonnet">lonnet</a></li>
  314: <li><a href="#connections">Connections</a></li>
  315: <li><a href="#delayed">Delayed Messages</a></li>
  316: <li><a href="#errcount">Error Count</a></li>
  317: </ol>
  318: <hr />
  319: <a name="configuration" />
  320: <h2>Configuration</h2>
  321: <h3>PerlVars</h3>
  322: <table border="2">
  323: ENDHEADERS
  324: 
  325:     foreach my $varname (sort(keys(%perlvar))) {
  326: 	&log($fh,"<tr><td>$varname</td><td>".
  327: 	     &encode_entities($perlvar{$varname},'<>&"')."</td></tr>\n");
  328:     }
  329:     &log($fh,"</table><h3>Hosts</h3><table border='2'>");
  330:     my %hostname = &Apache::lonnet::all_hostnames();
  331:     foreach my $id (sort(keys(%hostname))) {
  332: 	my $role = (&Apache::lonnet::is_library($id) ? 'library'
  333: 		                                     : 'access');
  334: 	&log($fh,
  335: 	    "<tr><td>$id</td><td>".&Apache::lonnet::host_domain($id).
  336: 	    "</td><td>".$role.
  337: 	    "</td><td>".&Apache::lonnet::hostname($id)."</td></tr>\n");
  338:     }
  339:     &log($fh,"</table><h3>Spare Hosts</h3>");
  340:     if (keys(%Apache::lonnet::spareid) > 0) {
  341:         &log($fh,"<ul>");
  342:         foreach my $type (sort(keys(%Apache::lonnet::spareid))) {
  343: 	    &log($fh,"<li>$type\n<ol>");
  344: 	    foreach my $id (@{ $Apache::lonnet::spareid{$type} }) {
  345: 	        &log($fh,"<li>$id</li>\n");
  346: 	    }
  347: 	    &log($fh,"</ol>\n</li>\n");
  348:         }
  349:         &log($fh,"</ul>\n");
  350:     } else {
  351:         &log($fh,"No spare hosts specified<br />\n");
  352:     }
  353:     return $fh;
  354: }
  355: 
  356: # --------------------------------------------------------------- clean out tmp
  357: sub clean_tmp {
  358:     my ($fh)=@_;
  359:     &log($fh,'<hr /><a name="tmp" /><h2>Temporary Files</h2>');
  360:     my ($cleaned,$old,$removed) = (0,0,0);
  361:     my %errors = (
  362:                      dir       => [],
  363:                      file      => [],
  364:                      failopen  => [],
  365:                  );
  366:     my %error_titles = (
  367:                          dir       => 'failed to remove empty directory:',
  368:                          file      => 'failed to unlike stale file',
  369:                          failopen  => 'failed to open file or directory'
  370:                        );
  371:     ($cleaned,$old,$removed) = &recursive_clean_tmp('',$cleaned,$old,$removed,\%errors);
  372:     &log($fh,"Cleaned up: ".$cleaned." files; removed: $removed empty directories; (found: $old old checkout tokens)");
  373:     foreach my $key (sort(keys(%errors))) {
  374:         if (ref($errors{$key}) eq 'ARRAY') {
  375:             if (@{$errors{$key}} > 0) {
  376:                 &log($fh,"Error during cleanup ($error_titles{$key}):<ul><li>".
  377:                      join('</li><li><tt>',@{$errors{$key}}).'</tt></li></ul><br />');
  378:             }
  379:         }
  380:     }
  381: }
  382: 
  383: sub recursive_clean_tmp {
  384:     my ($subdir,$cleaned,$old,$removed,$errors) = @_;
  385:     my $base = "$perlvar{'lonDaemons'}/tmp";
  386:     my $path = $base;
  387:     next if ($subdir =~ m{\.\./});
  388:     next unless (ref($errors) eq 'HASH');
  389:     unless ($subdir eq '') {
  390:         $path .= '/'.$subdir;
  391:     }
  392:     if (opendir(my $dh,"$path")) {
  393:         while (my $file = readdir($dh)) {
  394:             next if ($file =~ /^\.\.?$/);
  395:             my $fname = "$path/$file";
  396:             if (-d $fname) {
  397:                 my $innerdir;
  398:                 if ($subdir eq '') {
  399:                     $innerdir = $file;
  400:                 } else {
  401:                     $innerdir = $subdir.'/'.$file;
  402:                 }
  403:                 ($cleaned,$old,$removed) = 
  404:                      &recursive_clean_tmp($innerdir,$cleaned,$old,$removed,$errors);
  405:                 my @doms = &Apache::lonnet::current_machine_domains();
  406:                 
  407:                 if (open(my $dirhandle,$fname)) {
  408:                     unless (($innerdir eq 'helprequests') ||
  409:                             (($innerdir =~ /^addcourse/) && ($innerdir !~ m{/\d+$}))) {
  410:                         my @contents = grep {!/^\.\.?$/} readdir($dirhandle);
  411:                                       join('&&',@contents)."\n";    
  412:                         if (scalar(grep {!/^\.\.?$/} readdir($dirhandle)) == 0) {
  413:                             closedir($dirhandle);
  414:                             if ($fname =~ m{^\Q$perlvar{'lonDaemons'}\E/tmp/}) {
  415:                                 if (rmdir($fname)) {
  416:                                     $removed ++;
  417:                                 } elsif (ref($errors->{dir}) eq 'ARRAY') {
  418:                                     push(@{$errors->{dir}},$fname);
  419:                                 }
  420:                             }
  421:                         }
  422:                     } else {
  423:                         closedir($dirhandle);
  424:                     }
  425:                 }
  426:             } else {
  427:                 my ($dev,$ino,$mode,$nlink,
  428:                     $uid,$gid,$rdev,$size,
  429:                     $atime,$mtime,$ctime,
  430:                     $blksize,$blocks)=stat($fname);
  431:                 my $now=time;
  432:                 my $since=$now-$mtime;
  433:                 if ($since>$perlvar{'lonExpire'}) {
  434:                     if ($subdir eq '') {
  435:                         my $line='';
  436:                         if ($fname =~ /\.db$/) {
  437:                             if (unlink($fname)) {
  438:                                 $cleaned++;
  439:                             } elsif (ref($errors->{file}) eq 'ARRAY') {
  440:                                 push(@{$errors->{file}},$fname);
  441:                             }
  442:                         } elsif (open(PROBE,$fname)) {
  443:                             my $line='';
  444:                             $line=<PROBE>;
  445:                             close(PROBE);
  446:                             if ($line=~/^CHECKOUTTOKEN\&/) {
  447:                                 if ($since>365*$perlvar{'lonExpire'}) {
  448:                                     if (unlink($fname)) {
  449:                                         $cleaned++; 
  450:                                     } elsif (ref($errors->{file}) eq 'ARRAY') {
  451:                                         push(@{$errors->{file}},$fname);
  452:                                     }
  453:                                 } else {
  454:                                     $old++;
  455:                                 }
  456:                             } else {
  457:                                 if (unlink($fname)) {
  458:                                     $cleaned++;
  459:                                 } elsif (ref($errors->{file}) eq 'ARRAY') {
  460:                                     push(@{$errors->{file}},$fname);
  461:                                 }
  462:                             }
  463:                         } elsif (ref($errors->{failopen}) eq 'ARRAY') {
  464:                             push(@{$errors->{failopen}},$fname); 
  465:                         }
  466:                     } else {
  467:                         if (unlink($fname)) {
  468:                             $cleaned++;
  469:                         } elsif (ref($errors->{file}) eq 'ARRAY') {
  470:                             push(@{$errors->{file}},$fname);
  471:                         }
  472:                     }
  473:                 }
  474:             }
  475:         }
  476:         closedir($dh);
  477:     } elsif (ref($errors->{failopen}) eq 'ARRAY') {
  478:         push(@{$errors->{failopen}},$path);
  479:     }
  480:     return ($cleaned,$old,$removed);
  481: }
  482: 
  483: # ------------------------------------------------------------ clean out lonIDs
  484: sub clean_lonIDs {
  485:     my ($fh)=@_;
  486:     &log($fh,'<hr /><a name="tokens" /><h2>Session Tokens</h2>');
  487:     my $cleaned=0;
  488:     my $active=0;
  489:     while (my $fname=<$perlvar{'lonIDsDir'}/*>) {
  490: 	my ($dev,$ino,$mode,$nlink,
  491: 	    $uid,$gid,$rdev,$size,
  492: 	    $atime,$mtime,$ctime,
  493: 	    $blksize,$blocks)=stat($fname);
  494: 	my $now=time;
  495: 	my $since=$now-$mtime;
  496: 	if ($since>$perlvar{'lonExpire'}) {
  497: 	    $cleaned++;
  498: 	    &log($fh,"Unlinking $fname<br />");
  499: 	    unlink("$fname");
  500: 	} else {
  501: 	    $active++;
  502: 	}
  503:     }
  504:     &log($fh,"<p>Cleaned up ".$cleaned." stale session token(s).</p>");
  505:     &log($fh,"<h3>$active open session(s)</h3>");
  506: }
  507: 
  508: # ------------------------------------------------ clean out webDAV Session IDs
  509: sub clean_webDAV_sessionIDs {
  510:     my ($fh)=@_;
  511:     if ($perlvar{'lonRole'} eq 'library') {
  512:         &log($fh,'<hr /><a name="webdav" /><h2>WebDAV Session Tokens</h2>');
  513:         my $cleaned=0;
  514:         my $active=0;
  515:         my $now = time;
  516:         if (-d $perlvar{'lonDAVsessDir'}) {
  517:             while (my $fname=<$perlvar{'lonDAVsessDir'}/*>) {
  518:                 my @stats = stat($fname);
  519:                 my $since=$now-$stats[9];
  520:                 if ($since>$perlvar{'lonExpire'}) {
  521:                     $cleaned++;
  522:                     &log($fh,"Unlinking $fname<br />");
  523:                     unlink("$fname");
  524:                 } else {
  525:                     $active++;
  526:                 }
  527:             }
  528:             &log($fh,"<p>Cleaned up ".$cleaned." stale webDAV session token(s).</p>");
  529:             &log($fh,"<h3>$active open webDAV session(s)</h3>");
  530:         }
  531:     }
  532: }
  533: 
  534: # ----------------------------------------------------------- clean out sockets
  535: sub clean_sockets {
  536:     my ($fh)=@_;
  537:     my $cleaned=0;
  538:     opendir(SOCKETS,$perlvar{'lonSockDir'});
  539:     while (my $fname=readdir(SOCKETS)) {
  540: 	next if (-d $fname 
  541: 		 || $fname=~/(mysqlsock|maximasock|rsock|\Q$perlvar{'lonSockDir'}\E)/);
  542: 	$cleaned++;
  543: 	&log($fh,"Unlinking $fname<br />");
  544: 	unlink("/home/httpd/sockets/$fname");
  545:     }
  546:     &log($fh,"<p>Cleaned up ".$cleaned." stale sockets.</p>");
  547: }
  548: 
  549: 
  550: # ----------------------------------------------------------------------- httpd
  551: sub check_httpd_logs {
  552:     my ($fh)=@_;
  553:     if (open(PIPE,"./lchttpdlogs|")) {
  554:         while (my $line=<PIPE>) {
  555:             &log($fh,$line);
  556:             if ($line=~/\[error\]/) { $notices++; }
  557:         }
  558:         close(PIPE);
  559:     }
  560:     &errout($fh);
  561: }
  562: 
  563: # ---------------------------------------------------------------------- lonnet
  564: 
  565: sub rotate_lonnet_logs {
  566:     my ($fh)=@_;
  567:     &log($fh,'<hr /><a name="lonnet" /><h2>lonnet</h2><h3>Temp Log</h3><pre>');
  568:     print "Checking logs.\n";
  569:     if (-e "$perlvar{'lonDaemons'}/logs/lonnet.log"){
  570: 	open (DFH,"tail -n50 $perlvar{'lonDaemons'}/logs/lonnet.log|");
  571: 	while (my $line=<DFH>) { 
  572: 	    &log($fh,&encode_entities($line,'<>&"'));
  573: 	}
  574: 	close (DFH);
  575:     }
  576:     &log($fh,"</pre><h3>Perm Log</h3><pre>");
  577:     
  578:     if (-e "$perlvar{'lonDaemons'}/logs/lonnet.perm.log") {
  579: 	open(DFH,"tail -n10 $perlvar{'lonDaemons'}/logs/lonnet.perm.log|");
  580: 	while (my $line=<DFH>) { 
  581: 	    &log($fh,&encode_entities($line,'<>&"'));
  582: 	}
  583: 	close (DFH);
  584:     } else { &log($fh,"No perm log\n") }
  585: 
  586:     my $fname="$perlvar{'lonDaemons'}/logs/lonnet.log";
  587:     &rotate_logfile($fname,$fh,'lonnet log');
  588: 
  589:     &log($fh,"</pre>");
  590:     &errout($fh);
  591: }
  592: 
  593: sub rotate_other_logs {
  594:     my ($fh) = @_;
  595:     my %logs = (
  596:                   autoenroll          => 'Auto Enroll log',
  597:                   autocreate          => 'Create Course log',
  598:                   searchcat           => 'Search Cataloguing log',
  599:                   autoupdate          => 'Auto Update log',
  600:                   refreshcourseids_db => 'Refresh CourseIDs db log',
  601:                );
  602:     foreach my $item (keys(%logs)) {
  603:         my $fname=$perlvar{'lonDaemons'}.'/logs/'.$item.'.log';
  604:         &rotate_logfile($fname,$fh,$logs{$item});
  605:     }
  606: }
  607: 
  608: # ----------------------------------------------------------------- Connections
  609: sub test_connections {
  610:     my ($fh)=@_;
  611:     &log($fh,'<hr /><a name="connections" /><h2>Connections</h2>');
  612:     print "Testing connections.\n";
  613:     &log($fh,"<table border='2'>");
  614:     my ($good,$bad)=(0,0);
  615:     my %hostname = &Apache::lonnet::all_hostnames();
  616:     foreach my $tryserver (sort(keys(%hostname))) {
  617: 	print(".");
  618: 	my $result;
  619: 	my $answer=&Apache::lonnet::reply("ping",$tryserver);
  620: 	if ($answer eq "$tryserver:$perlvar{'lonHostID'}") {
  621: 	    $result="<b>ok</b>";
  622: 	    $good++;
  623: 	} else {
  624: 	    $result=$answer;
  625: 	    $warnings++;
  626: 	    if ($answer eq 'con_lost') {
  627: 		$bad++;
  628: 		$warnings++;
  629: 	    } else {
  630: 		$good++; #self connection
  631: 	    }
  632: 	}
  633: 	if ($answer =~ /con_lost/) { print(" $tryserver down\n"); }
  634: 	&log($fh,"<tr><td>$tryserver</td><td>$result</td></tr>\n");
  635:     }
  636:     &log($fh,"</table>");
  637:     print "\n$good good, $bad bad connections\n";
  638:     &errout($fh);
  639: }
  640: 
  641: 
  642: # ------------------------------------------------------------ Delayed messages
  643: sub check_delayed_msg {
  644:     my ($fh)=@_;
  645:     &log($fh,'<hr /><a name="delayed" /><h2>Delayed Messages</h2>');
  646:     print "Checking buffers.\n";
  647:     
  648:     &log($fh,'<h3>Scanning Permanent Log</h3>');
  649: 
  650:     my $unsend=0;
  651: 
  652:     my %hostname = &Apache::lonnet::all_hostnames();
  653:     my $numhosts = scalar(keys(%hostname));
  654: 
  655:     my $dfh=IO::File->new("$perlvar{'lonDaemons'}/logs/lonnet.perm.log");
  656:     while (my $line=<$dfh>) {
  657: 	my ($time,$sdf,$dserv,$dcmd)=split(/:/,$line);
  658:         if ($numhosts) {
  659:             next unless ($hostname{$dserv});
  660:         }
  661: 	if ($sdf eq 'F') { 
  662: 	    my $local=localtime($time);
  663: 	    &log($fh,"<b>Failed: $time, $dserv, $dcmd</b><br />");
  664: 	    $warnings++;
  665: 	}
  666: 	if ($sdf eq 'S') { $unsend--; }
  667: 	if ($sdf eq 'D') { $unsend++; }
  668:     }
  669: 
  670:     &log($fh,"<p>Total unsend messages: <b>$unsend</b></p>\n");
  671:     if ($unsend > 0) {
  672:         $warnings=$warnings+5*$unsend;
  673:     }
  674: 
  675:     if ($unsend) { $simplestatus{'unsend'}=$unsend; }
  676:     &log($fh,"<h3>Outgoing Buffer</h3>\n<pre>");
  677: # list directory with delayed messages and remember offline servers
  678:     my %servers=();
  679:     open (DFH,"ls -lF $perlvar{'lonSockDir'}/delayed|");
  680:     while (my $line=<DFH>) {
  681:         my ($server)=($line=~/\.(\w+)$/);
  682:         if ($server) { $servers{$server}=1; }
  683: 	&log($fh,&encode_entities($line,'<>&"'));
  684:     }
  685:     &log($fh,"</pre>\n");
  686:     close (DFH);
  687: # pong to all servers that have delayed messages
  688: # this will trigger a reverse connection, which should flush the buffers
  689:     foreach my $tryserver (sort(keys(%servers))) {
  690:         if ($hostname{$tryserver} || !$numhosts) {
  691:             my $answer;
  692:             eval {
  693:                 local $SIG{ ALRM } = sub { die "TIMEOUT" };
  694:                 alarm(20);
  695:                 $answer = &Apache::lonnet::reply("pong",$tryserver);
  696:                 alarm(0);
  697:             };
  698:             if ($@ && $@ =~ m/TIMEOUT/) {
  699:                 &log($fh,"Attempted pong to $tryserver timed out<br />");
  700:                 print "Time out while contacting: $tryserver for pong.\n";
  701:             } else {
  702:                 &log($fh,"Pong to $tryserver: $answer<br />");
  703:             }
  704:         } else {
  705:             &log($fh,"$tryserver has delayed messages, but is not part of the cluster -- skipping 'Pong'.<br />");
  706:         }
  707:     }
  708: }
  709: 
  710: sub finish_logging {
  711:     my ($fh)=@_;
  712:     &log($fh,"<a name='errcount' />\n");
  713:     $totalcount=$notices+4*$warnings+100*$errors;
  714:     &errout($fh);
  715:     &log($fh,"<h1>Total Error Count: $totalcount</h1>");
  716:     my $now=time;
  717:     my $date=localtime($now);
  718:     &log($fh,"<hr />$date ($now)</body></html>\n");
  719:     print "lon-status webpage updated.\n";
  720:     $fh->close();
  721: 
  722:     if ($errors) { $simplestatus{'errors'}=$errors; }
  723:     if ($warnings) { $simplestatus{'warnings'}=$warnings; }
  724:     if ($notices) { $simplestatus{'notices'}=$notices; }
  725:     $simplestatus{'time'}=time;
  726: }
  727: 
  728: sub log_simplestatus {
  729:     rename("$statusdir/newstatus.html","$statusdir/index.html");
  730:     
  731:     my $sfh=IO::File->new(">$statusdir/loncron_simple.txt");
  732:     foreach (keys %simplestatus) {
  733: 	print $sfh $_.'='.$simplestatus{$_}.'&';
  734:     }
  735:     print $sfh "\n";
  736:     $sfh->close();
  737: }
  738: 
  739: sub write_loncaparevs {
  740:     print "Retrieving LON-CAPA version information.\n";
  741:     my %hostname = &Apache::lonnet::all_hostnames();
  742:     my $output;
  743:     foreach my $id (sort(keys(%hostname))) {
  744:         if ($id ne '') {
  745:             my $loncaparev;
  746:             eval {
  747:                 local $SIG{ ALRM } = sub { die "TIMEOUT" };
  748:                 alarm(10);
  749:                 $loncaparev =
  750:                     &Apache::lonnet::get_server_loncaparev('',$id,1,'loncron');
  751:                 alarm(0);
  752:             };
  753:             if ($@ && $@ =~ m/TIMEOUT/) {
  754:                 print "Time out while contacting lonHost: $id for version.\n";   
  755:             }
  756:             if ($loncaparev =~ /^[\w.\-]+$/) {
  757:                 $output .= $id.':'.$loncaparev."\n";
  758:             }
  759:         }
  760:     }
  761:     if ($output) {
  762:         if (open(my $fh,">$perlvar{'lonTabDir'}/loncaparevs.tab")) {
  763:             print $fh $output;
  764:             close($fh);
  765:             &Apache::lonnet::load_loncaparevs();
  766:         }
  767:     }
  768:     return;
  769: }
  770: 
  771: sub write_serverhomeIDs {
  772:     print "Retrieving LON-CAPA lonHostID information.\n";
  773:     my %name_to_host = &Apache::lonnet::all_names();
  774:     my $output;
  775:     foreach my $name (sort(keys(%name_to_host))) {
  776:         if ($name ne '') {
  777:             if (ref($name_to_host{$name}) eq 'ARRAY') {
  778:                 my $serverhomeID;
  779:                 eval {
  780:                     local $SIG{ ALRM } = sub { die "TIMEOUT" };
  781:                     alarm(10);
  782:                     $serverhomeID = 
  783:                         &Apache::lonnet::get_server_homeID($name,1,'loncron');
  784:                     alarm(0);
  785:                 };
  786:                 if ($@ && $@ =~ m/TIMEOUT/) {
  787:                     print "Time out while contacting server: $name\n"; 
  788:                 }
  789:                 if ($serverhomeID ne '') {
  790:                     $output .= $name.':'.$serverhomeID."\n";
  791:                 } else {
  792:                     $output .= $name.':'.$name_to_host{$name}->[0]."\n";
  793:                 }
  794:             }
  795:         }
  796:     }
  797:     if ($output) {
  798:         if (open(my $fh,">$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
  799:             print $fh $output;
  800:             close($fh);
  801:             &Apache::lonnet::load_serverhomeIDs();
  802:         }
  803:     }
  804:     return;
  805: }
  806: 
  807: sub write_checksums {
  808:     my $distro = &LONCAPA::distro();
  809:     if ($distro) {
  810:         print "Retrieving file version and checksumming.\n";
  811:         my $numchksums = 0;
  812:         my ($chksumsref,$versionsref) =
  813:             &LONCAPA::Checksumming::get_checksums($distro,$perlvar{'lonDaemons'},
  814:                                                   $perlvar{'lonLib'},
  815:                                                   $perlvar{'lonIncludes'},
  816:                                                   $perlvar{'lonTabDir'});
  817:         if (ref($chksumsref) eq 'HASH') {
  818:             $numchksums = scalar(keys(%{$chksumsref}));
  819:         }
  820:         print "File version retrieved and checksumming completed for $numchksums files.\n";
  821:     } else {
  822:         print "File version retrieval and checksumming skipped - could not determine Linux distro.\n"; 
  823:     }
  824:     return;
  825: }
  826: 
  827: sub send_mail {
  828:     my $defdom = $perlvar{'lonDefDomain'};
  829:     my $origmail = $perlvar{'lonAdmEMail'};
  830:     my $emailto = &Apache::loncommon::build_recipient_list(undef,
  831:                                    'lonstatusmail',$defdom,$origmail);
  832:     if ($totalcount>2500) {
  833: 	$emailto.=",$perlvar{'lonSysEMail'}";
  834:     }
  835:     my $from;
  836:     my $hostname=`/bin/hostname`;
  837:     chop($hostname);
  838:     $hostname=~s/[^\w\.]//g;
  839:     if ($hostname) {
  840:         $from = 'www@'.$hostname;
  841:     }
  842:     my $subj="LON: $perlvar{'lonHostID'} E:$errors W:$warnings N:$notices";
  843:     my $loncronmail = "To: $emailto\n".
  844:                       "From: $from\n".
  845:                       "Subject: ".$subj."\n".
  846:                       "Content-type: text/html\; charset=UTF-8\n".
  847:                       "MIME-Version: 1.0\n\n";
  848:     if (open(my $fh,"<$statusdir/index.html")) {
  849:         while (<$fh>) {
  850:             $loncronmail .= $_;
  851:         }
  852:         close($fh);
  853:     } else {
  854:         $loncronmail .= "Failed to read from http://$hostname/lon-status/index.html\n";
  855:     }
  856:     $loncronmail .= "\n\n";
  857:     if (open(my $mailh, "|/usr/lib/sendmail -oi -t -odb")) {
  858:         print $mailh $loncronmail;
  859:         close($mailh);
  860:         print "Sending mail.\n";
  861:     } else {
  862:         print "Sending mail failed.\n";
  863:     }
  864: }
  865: 
  866: sub usage {
  867:     print(<<USAGE);
  868: loncron - housekeeping program that checks up on various parts of LON-CAPA
  869: 
  870: Options:
  871:    --help     Display 
  872:    --noemail  Do not send the status email
  873:    --justcheckconnections  Only check the current status of the lonc/d
  874:                                 connections, do not send emails do not
  875:                                 check if the daemons are running, do not
  876:                                 generate lon-status
  877:    --justcheckdaemons      Only check that all of the Lon-CAPA daemons are
  878:                                 running, do not send emails do not
  879:                                 check the lonc/d connections, do not
  880:                                 generate lon-status
  881:    --justreload            Only tell the daemons to reload the config files,
  882: 				do not send emails do not
  883:                                 check if the daemons are running, do not
  884:                                 generate lon-status
  885:                            
  886: USAGE
  887: }
  888: 
  889: # ================================================================ Main Program
  890: sub main () {
  891:     my ($help,$justcheckdaemons,$noemail,$justcheckconnections,
  892: 	$justreload);
  893:     &GetOptions("help"                 => \$help,
  894: 		"justcheckdaemons"     => \$justcheckdaemons,
  895: 		"noemail"              => \$noemail,
  896: 		"justcheckconnections" => \$justcheckconnections,
  897: 		"justreload"           => \$justreload
  898: 		);
  899:     if ($help) { &usage(); return; }
  900: # --------------------------------- Read loncapa_apache.conf and loncapa.conf
  901:     my $perlvarref=LONCAPA::Configuration::read_conf('loncapa.conf');
  902:     %perlvar=%{$perlvarref};
  903:     undef $perlvarref;
  904:     delete $perlvar{'lonReceipt'}; # remove since sensitive and not needed
  905:     delete $perlvar{'lonSqlAccess'}; # remove since sensitive and not needed
  906:     chdir($perlvar{'lonDaemons'});
  907: # --------------------------------------- Make sure that LON-CAPA is configured
  908: # I only test for one thing here (lonHostID).  This is just a safeguard.
  909:     if ('{[[[[lonHostID]]]]}' eq $perlvar{'lonHostID'}) {
  910: 	print("Unconfigured machine.\n");
  911: 	my $emailto=$perlvar{'lonSysEMail'};
  912: 	my $hostname=`/bin/hostname`;
  913: 	chop $hostname;
  914: 	$hostname=~s/[^\w\.]//g; # make sure is safe to pass through shell
  915: 	my $subj="LON: Unconfigured machine $hostname";
  916: 	system("echo 'Unconfigured machine $hostname.' |".
  917:                " mail -s '$subj' $emailto > /dev/null");
  918: 	exit 1;
  919:     }
  920: 
  921: # ----------------------------- Make sure this process is running from user=www
  922:     my $wwwid=getpwnam('www');
  923:     if ($wwwid!=$<) {
  924: 	print("User ID mismatch. This program must be run as user 'www'.\n");
  925: 	my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
  926: 	my $subj="LON: $perlvar{'lonHostID'} User ID mismatch";
  927: 	system("echo 'User ID mismatch. loncron must be run as user www.' |".
  928:                " mail -s '$subj' $emailto > /dev/null");
  929: 	exit 1;
  930:     }
  931: 
  932: # -------------------------------------------- Force reload of host information
  933:     my $nomemcache;
  934:     if ($justcheckdaemons) {
  935:         $nomemcache=1;
  936:         my $memcachepidfile="$perlvar{'lonDaemons'}/logs/memcached.pid";
  937:         my $memcachepid;
  938:         if (-e $memcachepidfile) {
  939:             my $memfh=IO::File->new($memcachepidfile);
  940:             $memcachepid=<$memfh>;
  941:             chomp($memcachepid);
  942:             if ($memcachepid =~ /^\d+$/ && kill 0 => $memcachepid) {
  943:                 undef($nomemcache);
  944:             }
  945:         }
  946:     }
  947:     &Apache::lonnet::load_hosts_tab(1,$nomemcache);
  948:     &Apache::lonnet::load_domain_tab(1,$nomemcache);
  949:     &Apache::lonnet::get_iphost(1,$nomemcache);
  950: 
  951: # ----------------------------------------- Force firewall update for lond port  
  952: 
  953:     if ((!$justcheckdaemons) && (!$justreload)) {
  954:         my $now = time;
  955:         my $tmpfile = $perlvar{'lonDaemons'}.'/tmp/lciptables_iphost_'.
  956:                       $now.$$.int(rand(10000));
  957:         if (open(my $fh,">$tmpfile")) {
  958:             my %iphosts = &Apache::lonnet::get_iphost();
  959:             foreach my $key (keys(%iphosts)) {
  960:                 print $fh "$key\n";
  961:             }
  962:             close($fh);
  963:             if (&LONCAPA::try_to_lock('/tmp/lock_lciptables')) {
  964:                 my $execpath = $perlvar{'lonDaemons'}.'/lciptables';
  965:                 system("$execpath $tmpfile");
  966:                 unlink('/tmp/lock_lciptables');  # Remove the lock file. 
  967:             }
  968:             unlink($tmpfile);
  969:         }
  970:     }
  971: 
  972: # ---------------------------------------------------------------- Start report
  973: 
  974:     $errors=0;
  975:     $warnings=0;
  976:     $notices=0;
  977: 
  978: 	
  979:     my $fh;
  980:     if (!$justcheckdaemons && !$justcheckconnections && !$justreload) {
  981: 	$fh=&start_logging();
  982: 
  983: 	&log_machine_info($fh);
  984: 	&clean_tmp($fh);
  985: 	&clean_lonIDs($fh);
  986:         &clean_webDAV_sessionIDs($fh);
  987: 	&check_httpd_logs($fh);
  988: 	&rotate_lonnet_logs($fh);
  989: 	&rotate_other_logs($fh);
  990:     }
  991:     if (!$justcheckconnections && !$justreload) {
  992: 	&checkon_daemon($fh,'lonmemcached',40000);
  993: 	&checkon_daemon($fh,'lonsql',200000);
  994: 	if ( &checkon_daemon($fh,'lond',40000,'USR1') eq 'running') {
  995: 	    &checkon_daemon($fh,'lond',40000,'USR2');
  996: 	}
  997: 	&checkon_daemon($fh,'lonc',40000,'USR1');
  998:         &checkon_daemon($fh,'lonmaxima',40000);
  999:         &checkon_daemon($fh,'lonr',40000);
 1000:     }
 1001:     if ($justreload) {
 1002: 	&checkon_daemon($fh,'lond',40000,'USR2');
 1003: 	&checkon_daemon($fh,'lonc',40000,'USR2');
 1004:     }
 1005:     if ($justcheckconnections) {
 1006: 	&test_connections($fh);
 1007:     }
 1008:     if (!$justcheckdaemons && !$justcheckconnections && !$justreload) {
 1009: 	&check_delayed_msg($fh);
 1010: 	&finish_logging($fh);
 1011: 	&log_simplestatus();
 1012:         &write_loncaparevs();
 1013:         &write_serverhomeIDs();
 1014: 	&write_checksums();
 1015: 	if ($totalcount>200 && !$noemail) { &send_mail(); }
 1016:     }
 1017: }
 1018: 
 1019: &main();
 1020: 1;
 1021: 

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