File:  [LON-CAPA] / loncom / lonmaxima
Revision 1.14: download - view: text, annotated - select for diffs
Wed Mar 8 14:22:14 2006 UTC (18 years, 1 month ago) by www
Branches: MAIN
CVS tags: HEAD
At least process management now works, but Maxima behaving oddly.

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

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