Annotation of loncom/loncron, revision 1.118

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

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