File:  [LON-CAPA] / loncom / lonmaxima
Revision 1.12: download - view: text, annotated - select for diffs
Wed Mar 8 03:18:42 2006 UTC (18 years, 1 month ago) by www
Branches: MAIN
CVS tags: HEAD
Does a lot of interesting things, except work

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

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