File:  [LON-CAPA] / loncom / lonmaxima
Revision 1.13: download - view: text, annotated - select for diffs
Wed Mar 8 12:57:30 2006 UTC (18 years, 1 month ago) by www
Branches: MAIN
CVS tags: HEAD
Even more interesting, still defunct.

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

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