File:  [LON-CAPA] / loncom / loncron
Revision 1.100: download - view: text, annotated - select for diffs
Mon Mar 17 14:47:38 2014 UTC (10 years, 1 month ago) by bisitz
Branches: MAIN
CVS tags: version_2_11_0_RC3, version_2_11_0, HEAD
Consistent case and punctuation of output text

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

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