File:  [LON-CAPA] / loncom / lonmaxima
Revision 1.7: download - view: text, annotated - select for diffs
Sat Mar 4 02:33:54 2006 UTC (18 years, 2 months ago) by www
Branches: MAIN
CVS tags: HEAD
Works.

    1: #!/usr/bin/perl
    2: #
    3: # The LearningOnline Network with CAPA
    4: # Connect to MAXIMA CAS
    5: #
    6: # $Id: lonmaxima,v 1.7 2006/03/04 02:33:54 www 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: my $maximapid;                         # PID of maxima process
   56: my $selector;                          # open3's selector
   57: use vars qw($PREFORK $MAX_CLIENTS_PER_CHILD %children $children $status
   58: 	    $pidfile $port %perlvar $lastlog $maximapid $selector);
   59:  
   60: sub maximareply {
   61:     my ($cmd) = @_;
   62:     my $reply='';
   63:     my $error='';
   64:     my $exitstatus='';
   65: 
   66:     unless ($cmd=~/\;\n$/) { $cmd.=";\n"; }
   67: 
   68:     my ($cmd_in, $cmd_out, $cmd_err);
   69:     $maximapid = open3($cmd_in, $cmd_out, $cmd_err, 'maxima');
   70:     $children{$maximapid} = 1;
   71:     
   72:     print $cmd_in $cmd;
   73:     close($cmd_in);
   74: 
   75:     &status("Command sent");
   76: 
   77:     $SIG{ALRM} = sub { kill 9 => $maximapid; }; 
   78:     alarm(5);
   79:     no strict 'refs';
   80: 
   81:     $selector = IO::Select->new();
   82: 
   83:     $selector->add($cmd_err, $cmd_out);
   84:     
   85:     while (my @ready = $selector->can_read()) {
   86: 	foreach my $fh (@ready) {
   87: 	    if (fileno($fh) == fileno($cmd_err)) {
   88: 		$error.=<$cmd_err>;
   89: 	    } else {
   90: 		my $line = scalar(<$cmd_out>);
   91:                 if ($line=~/^(\(\%o|\s)/) {
   92: 		    $line=~s/^\(.*\)/     /; 
   93: 		    $reply.=$line; 
   94: 		}
   95: 	    }
   96: 	    $selector->remove($fh) if eof($fh);
   97: 	}
   98:     }
   99:     alarm(0);
  100:     $SIG{ALRM} = 'DEFAULT';
  101:     close($cmd_out);
  102:     close($cmd_err);
  103:     use strict 'refs';
  104:     &status("Command processed");
  105:     return ($reply,$error,$exitstatus);
  106: }
  107:  
  108: # ------------------------------------------------------------ Service routines 
  109: sub REAPER {                        # takes care of dead children 
  110:                                     # and MAXIMA processes
  111:     $SIG{CHLD} = \&REAPER;
  112:     my $pid = wait;
  113:     $children--;
  114:     delete($children{$pid});
  115: }
  116:  
  117: sub HUNTSMAN {                      # signal handler for SIGINT
  118:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
  119:     kill('INT' => keys(%children));
  120:     unlink($pidfile);
  121:     unlink($port);
  122:     &logthis('---- Shutdown ----');
  123:     exit;                           # clean up with dignity
  124: }
  125: 
  126: 
  127:  
  128: # --------------------------------------------------------------------- Logging
  129:  
  130: sub logthis {
  131:     my ($message)=@_;
  132:     my $execdir=$perlvar{'lonDaemons'};
  133:     my $fh=IO::File->new(">>$execdir/logs/lonmaxima.log");
  134:     my $now=time;
  135:     my $local=localtime($now);
  136:     $lastlog=$local.': '.$message;
  137:     print $fh "$local ($$): $message\n";
  138: }
  139:  
  140: # -------------------------------------------------------------- Status setting
  141:  
  142: sub status {
  143:     my ($what)=@_;
  144:     my $now=time;
  145:     my $local=localtime($now);
  146:     $status=$local.': '.$what;
  147:     $0='lonmaxima: '.$what.' '.$local;
  148: }
  149:  
  150: # -------------------------------------------------------- Escape Special Chars
  151:  
  152: sub escape {
  153:     my ($str)=@_;
  154:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
  155:     return $str;
  156: }
  157:  
  158: # ----------------------------------------------------- Un-Escape Special Chars
  159:  
  160: sub unescape {
  161:     my ($str)=@_;
  162:     $str =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
  163:     return $str;
  164: }
  165:  
  166: # ------------------------ grabs exception and records it to log before exiting
  167: sub catchexception {
  168:     my ($signal)=@_;
  169:     $SIG{QUIT}='DEFAULT';
  170:     $SIG{__DIE__}='DEFAULT';
  171:     chomp($signal);
  172:     &logthis("<font color=\"red\">CRITICAL: "
  173: 	     ."ABNORMAL EXIT. Child $$ died through "
  174: 	     ."\"$signal\"</font>");
  175:     die("Signal abend");
  176: }
  177: 
  178: 
  179: 
  180: # ---------------------------------------------------------------- Main program
  181: # -------------------------------- Set signal handlers to record abnormal exits
  182:  
  183:  
  184: $SIG{'QUIT'}=\&catchexception;
  185: $SIG{__DIE__}=\&catchexception;
  186:  
  187: # ---------------------------------- Read loncapa_apache.conf and loncapa.conf
  188: &status("Read loncapa.conf and loncapa_apache.conf");
  189: %perlvar=%{&LONCAPA::Configuration::read_conf('loncapa.conf')};
  190:  
  191: # ----------------------------- Make sure this process is running from user=www
  192: my $wwwid=getpwnam('www');
  193: if ($wwwid!=$<) {
  194:     my $emailto="$perlvar{'lonAdmEMail'},$perlvar{'lonSysEMail'}";
  195:     my $subj="LON: User ID mismatch";
  196:     system("echo 'User ID mismatch.  lonmaxima must be run as user www.' |\
  197:  mailto $emailto -s '$subj' > /dev/null");
  198:     exit 1;
  199: }
  200:  
  201: # --------------------------------------------- Check if other instance running
  202:  
  203: $pidfile="$perlvar{'lonDaemons'}/logs/lonmaxima.pid";
  204:  
  205: if (-e $pidfile) {
  206:     my $lfh=IO::File->new("$pidfile");
  207:     my $pide=<$lfh>;
  208:     chomp($pide);
  209:     if (kill(0 => $pide)) { die "already running"; }
  210: }
  211: 
  212: # ------------------------------------------------------- Listen to UNIX socket
  213: &status("Opening socket");
  214:  
  215: $port = "$perlvar{'lonSockDir'}/maximasock";
  216:  
  217: unlink($port);
  218:  
  219: 
  220: my $server = IO::Socket::UNIX->new(Local  => $port,
  221: 				   Type   => SOCK_STREAM,
  222: 				   Listen => 10 );
  223: if (!$server) {
  224:     my $st=120+int(rand(240));
  225: 
  226:     &logthis("<font color=blue>WARNING: ".
  227: 	     "Can't make server socket ($st secs):  .. exiting</font>");
  228: 
  229:     sleep($st);
  230:     exit;
  231: }
  232:     
  233:  
  234: # ---------------------------------------------------- Fork once and dissociate
  235:  
  236: my $fpid=fork;
  237: exit if $fpid;
  238: die("Couldn't fork: $!") unless defined($fpid);
  239:  
  240: POSIX::setsid() or die "Can't start new session: $!";
  241:  
  242: # ------------------------------------------------------- Write our PID on disk
  243:  
  244: my $execdir=$perlvar{'lonDaemons'};
  245: open(PIDSAVE,">$execdir/logs/lonmaxima.pid");
  246: print PIDSAVE "$$\n";
  247: close(PIDSAVE);
  248: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
  249: &status('Starting');
  250:      
  251: 
  252: # Fork off our children.
  253: for (1 .. $PREFORK) {
  254:     &make_new_child($server);
  255: }
  256:  
  257: # Install signal handlers.
  258: $SIG{CHLD} = \&REAPER;
  259: $SIG{INT}  = $SIG{TERM} = \&HUNTSMAN;
  260:  
  261: # And maintain the population.
  262: while (1) {
  263:     &status('Parent process, sleeping');
  264:     sleep;                          # wait for a signal (i.e., child's death)
  265:     for (my $i = $children; $i < $PREFORK; $i++) {
  266:         &status('Parent process, starting child');
  267:         &make_new_child($server);           # top up the child pool
  268:     }
  269: }
  270:                                                                                 
  271: sub make_new_child {
  272:     my ($server) = @_;
  273: 
  274:     # block signal for fork
  275:     my $sigset = POSIX::SigSet->new(SIGINT);
  276:     sigprocmask(SIG_BLOCK, $sigset)
  277:         or die("Can't block SIGINT for fork: $!\n");
  278:      
  279:     die("fork: $!") unless defined(my $pid = fork);
  280:      
  281:     if ($pid) {
  282:         # Parent records the child's birth and returns.
  283:         sigprocmask(SIG_UNBLOCK, $sigset)
  284:             or die("Can't unblock SIGINT for fork: $!\n");
  285:         $children{$pid} = 1;
  286:         $children++;
  287:         return;
  288:     } else {
  289:         # Child can *not* return from this subroutine.
  290:         $SIG{INT} = 'DEFAULT';      # make SIGINT kill us as it did before
  291:      
  292:         # unblock signals
  293:         sigprocmask(SIG_UNBLOCK, $sigset)
  294:             or die("Can't unblock SIGINT for fork: $!\n");
  295: 
  296: 	&process_requests($server);
  297: 
  298:         # tidy up gracefully and finish
  299: 
  300:         # this exit is VERY important, otherwise the child will become
  301:         # a producer of more and more children, forking yourself into
  302:         # process death.
  303:         exit;
  304:     }
  305: }
  306: 
  307: sub process_requests {
  308:     my ($server) = @_;
  309:     # handle connections until we've reached $MAX_CLIENTS_PER_CHILD
  310:     for (my $i=0; $i < $MAX_CLIENTS_PER_CHILD; $i++) {
  311: 	&status('Accepting connections');     
  312: 	my $client = $server->accept()     or last;
  313: 	while (my $cmd=<$client>) {
  314: 	    &status('Processing command');
  315: 	    print $client &escape((&maximareply(&unescape($cmd)))[0])."\n";
  316: 	}
  317:     }    
  318: }

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