File:  [LON-CAPA] / loncom / lonmaxima
Revision 1.9: download - view: text, annotated - select for diffs
Sat Mar 4 06:51:02 2006 UTC (18 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- check for ref status before trying to use them as such

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

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