File:  [LON-CAPA] / loncom / lonmaxima
Revision 1.20: download - view: text, annotated - select for diffs
Wed May 10 02:15:51 2006 UTC (17 years, 11 months ago) by www
Branches: MAIN
CVS tags: HEAD
Did not work with old Maxima version.

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

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