File:  [LON-CAPA] / loncom / lonmaxima
Revision 1.8: download - view: text, annotated - select for diffs
Sat Mar 4 06:44:11 2006 UTC (18 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: HEAD
- eliminating unneeded globals

    1: #!/usr/bin/perl
    2: #
    3: # The LearningOnline Network with CAPA
    4: # Connect to MAXIMA CAS
    5: #
    6: # $Id: lonmaxima,v 1.8 2006/03/04 06:44:11 albertel Exp $
    7: #
    8: # Copyright Michigan State University Board of Trustees
    9: #
   10: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
   11: #
   12: # LON-CAPA is free software; you can redistribute it and/or modify
   13: # it under the terms of the GNU General Public License as published by
   14: # the Free Software Foundation; either version 2 of the License, or
   15: # (at your option) any later version.
   16: #
   17: # LON-CAPA is distributed in the hope that it will be useful,
   18: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   19: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   20: # GNU General Public License for more details.
   21: #
   22: # You should have received a copy of the GNU General Public License
   23: # along with LON-CAPA; if not, write to the Free Software
   24: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   25: #
   26: # /home/httpd/html/adm/gpl.txt
   27: #
   28: 
   29: # 
   30: # http://www.lon-capa.org/
   31: #
   32: 
   33:  
   34: use IPC::Open3;
   35: use IO::Select;
   36: use IO::Socket;
   37: use IO::File;
   38: use Symbol;
   39: use POSIX;
   40: use lib '/home/httpd/lib/perl/';
   41: use LONCAPA::Configuration;
   42:  
   43: use strict;
   44: 
   45: # global variables
   46: my $PREFORK                = 5;        # number of children to maintain
   47: my $MAX_CLIENTS_PER_CHILD  = 5;        # number of clients each child should process
   48: my %children               = ();       # keys are current child process IDs
   49: my $children               = 0;        # current number of children
   50: my $status;                            # string for current status
   51: my $pidfile;                           # file containg parent process pid
   52: my $port;                              # path to UNIX socket file
   53: my %perlvar;                           # configuration file info
   54: my $lastlog;                           # last string that was logged
   55: use vars qw($PREFORK $MAX_CLIENTS_PER_CHILD %children $children $status
   56: 	    $pidfile $port %perlvar $lastlog);
   57:  
   58: sub maximareply {
   59:     my ($cmd) = @_;
   60:     my $reply='';
   61:     my $error='';
   62:     my $exitstatus='';
   63: 
   64:     unless ($cmd=~/\;\n$/) { $cmd.=";\n"; }
   65: 
   66:     my ($cmd_in, $cmd_out, $cmd_err);
   67:     my $maximapid = open3($cmd_in, $cmd_out, $cmd_err, 'maxima');
   68:     $children{$maximapid} = 1;
   69:     
   70:     print $cmd_in $cmd;
   71:     close($cmd_in);
   72: 
   73:     &status("Command sent");
   74: 
   75:     $SIG{ALRM} = sub { kill 9 => $maximapid; }; 
   76:     alarm(5);
   77:     no strict 'refs';
   78: 
   79:     my $selector = IO::Select->new();
   80: 
   81:     $selector->add($cmd_err, $cmd_out);
   82:     
   83:     while (my @ready = $selector->can_read()) {
   84: 	foreach my $fh (@ready) {
   85: 	    if (fileno($fh) == fileno($cmd_err)) {
   86: 		$error.=<$cmd_err>;
   87: 	    } else {
   88: 		my $line = scalar(<$cmd_out>);
   89:                 if ($line=~/^(\(\%o|\s)/) {
   90: 		    $line=~s/^\(.*\)/     /; 
   91: 		    $reply.=$line; 
   92: 		}
   93: 	    }
   94: 	    $selector->remove($fh) if eof($fh);
   95: 	}
   96:     }
   97:     alarm(0);
   98:     $SIG{ALRM} = 'DEFAULT';
   99:     close($cmd_out);
  100:     close($cmd_err);
  101:     use strict 'refs';
  102:     &status("Command processed");
  103:     return ($reply,$error,$exitstatus);
  104: }
  105:  
  106: # ------------------------------------------------------------ Service routines 
  107: sub REAPER {                        # takes care of dead children 
  108:                                     # and MAXIMA processes
  109:     $SIG{CHLD} = \&REAPER;
  110:     my $pid = wait;
  111:     $children--;
  112:     delete($children{$pid});
  113: }
  114:  
  115: sub HUNTSMAN {                      # signal handler for SIGINT
  116:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
  117:     kill('INT' => keys(%children));
  118:     unlink($pidfile);
  119:     unlink($port);
  120:     &logthis('---- Shutdown ----');
  121:     exit;                           # clean up with dignity
  122: }
  123: 
  124: 
  125:  
  126: # --------------------------------------------------------------------- Logging
  127:  
  128: sub logthis {
  129:     my ($message)=@_;
  130:     my $execdir=$perlvar{'lonDaemons'};
  131:     my $fh=IO::File->new(">>$execdir/logs/lonmaxima.log");
  132:     my $now=time;
  133:     my $local=localtime($now);
  134:     $lastlog=$local.': '.$message;
  135:     print $fh "$local ($$): $message\n";
  136: }
  137:  
  138: # -------------------------------------------------------------- Status setting
  139:  
  140: sub status {
  141:     my ($what)=@_;
  142:     my $now=time;
  143:     my $local=localtime($now);
  144:     $status=$local.': '.$what;
  145:     $0='lonmaxima: '.$what.' '.$local;
  146: }
  147:  
  148: # -------------------------------------------------------- Escape Special Chars
  149:  
  150: sub escape {
  151:     my ($str)=@_;
  152:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
  153:     return $str;
  154: }
  155:  
  156: # ----------------------------------------------------- Un-Escape Special Chars
  157:  
  158: sub unescape {
  159:     my ($str)=@_;
  160:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  161:     return $str;
  162: }
  163:  
  164: # ------------------------ grabs exception and records it to log before exiting
  165: sub catchexception {
  166:     my ($signal)=@_;
  167:     $SIG{QUIT}='DEFAULT';
  168:     $SIG{__DIE__}='DEFAULT';
  169:     chomp($signal);
  170:     &logthis("<font color=\"red\">CRITICAL: "
  171: 	     ."ABNORMAL EXIT. Child $$ died through "
  172: 	     ."\"$signal\"</font>");
  173:     die("Signal abend");
  174: }
  175: 
  176: 
  177: 
  178: # ---------------------------------------------------------------- Main program
  179: # -------------------------------- Set signal handlers to record abnormal exits
  180:  
  181:  
  182: $SIG{'QUIT'}=\&catchexception;
  183: $SIG{__DIE__}=\&catchexception;
  184:  
  185: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
  186: &status("Read loncapa.conf and loncapa_apache.conf");
  187: %perlvar=%{&LONCAPA::Configuration::read_conf('loncapa.conf')};
  188:  
  189: # ----------------------------- Make sure this process is running from user=www
  190: my $wwwid=getpwnam('www');
  191: if ($wwwid!=$<) {
  192:     my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
  193:     my $subj="LON: User ID mismatch";
  194:     system("echo 'User ID mismatch.  lonmaxima must be run as user www.' |\
  195:  mailto $emailto -s '$subj' > /dev/null");
  196:     exit 1;
  197: }
  198:  
  199: # --------------------------------------------- Check if other instance running
  200:  
  201: $pidfile="$perlvar{'lonDaemons'}/logs/lonmaxima.pid";
  202:  
  203: if (-e $pidfile) {
  204:     my $lfh=IO::File->new("$pidfile");
  205:     my $pide=<$lfh>;
  206:     chomp($pide);
  207:     if (kill(0 => $pide)) { die "already running"; }
  208: }
  209: 
  210: # ------------------------------------------------------- Listen to UNIX socket
  211: &status("Opening socket");
  212:  
  213: $port = "$perlvar{'lonSockDir'}/maximasock";
  214:  
  215: unlink($port);
  216:  
  217: 
  218: my $server = IO::Socket::UNIX->new(Local  => $port,
  219: 				   Type   => SOCK_STREAM,
  220: 				   Listen => 10 );
  221: if (!$server) {
  222:     my $st=120+int(rand(240));
  223: 
  224:     &logthis("<font color=blue>WARNING: ".
  225: 	     "Can't make server socket ($st secs):  .. exiting</font>");
  226: 
  227:     sleep($st);
  228:     exit;
  229: }
  230:     
  231:  
  232: # ---------------------------------------------------- Fork once and dissociate
  233:  
  234: my $fpid=fork;
  235: exit if $fpid;
  236: die("Couldn't fork: $!") unless defined($fpid);
  237:  
  238: POSIX::setsid() or die "Can't start new session: $!";
  239:  
  240: # ------------------------------------------------------- Write our PID on disk
  241:  
  242: my $execdir=$perlvar{'lonDaemons'};
  243: open(PIDSAVE,">$execdir/logs/lonmaxima.pid");
  244: print PIDSAVE "$$\n";
  245: close(PIDSAVE);
  246: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
  247: &status('Starting');
  248:      
  249: 
  250: # Fork off our children.
  251: for (1 .. $PREFORK) {
  252:     &make_new_child($server);
  253: }
  254:  
  255: # Install signal handlers.
  256: $SIG{CHLD} = \&REAPER;
  257: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
  258:  
  259: # And maintain the population.
  260: while (1) {
  261:     &status('Parent process, sleeping');
  262:     sleep;                          # wait for a signal (i.e., child's death)
  263:     for (my $i = $children; $i < $PREFORK; $i++) {
  264:         &status('Parent process, starting child');
  265:         &make_new_child($server);           # top up the child pool
  266:     }
  267: }
  268:                                                                                 
  269: sub make_new_child {
  270:     my ($server) = @_;
  271: 
  272:     # block signal for fork
  273:     my $sigset = POSIX::SigSet->new(SIGINT);
  274:     sigprocmask(SIG_BLOCK, $sigset)
  275:         or die("Can't block SIGINT for fork: $!\n");
  276:      
  277:     die("fork: $!") unless defined(my $pid = fork);
  278:      
  279:     if ($pid) {
  280:         # Parent records the child's birth and returns.
  281:         sigprocmask(SIG_UNBLOCK, $sigset)
  282:             or die("Can't unblock SIGINT for fork: $!\n");
  283:         $children{$pid} = 1;
  284:         $children++;
  285:         return;
  286:     } else {
  287:         # Child can *not* return from this subroutine.
  288:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
  289:      
  290:         # unblock signals
  291:         sigprocmask(SIG_UNBLOCK, $sigset)
  292:             or die("Can't unblock SIGINT for fork: $!\n");
  293: 
  294: 	&process_requests($server);
  295: 
  296:         # tidy up gracefully and finish
  297: 
  298:         # this exit is VERY important, otherwise the child will become
  299:         # a producer of more and more children, forking yourself into
  300:         # process death.
  301:         exit;
  302:     }
  303: }
  304: 
  305: sub process_requests {
  306:     my ($server) = @_;
  307:     # handle connections until we've reached $MAX_CLIENTS_PER_CHILD
  308:     for (my $i=0; $i < $MAX_CLIENTS_PER_CHILD; $i++) {
  309: 	&status('Accepting connections');     
  310: 	my $client = $server->accept()     or last;
  311: 	while (my $cmd=<$client>) {
  312: 	    &status('Processing command');
  313: 	    print $client &escape((&maximareply(&unescape($cmd)))[0])."\n";
  314: 	}
  315:     }    
  316: }

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