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