File:  [LON-CAPA] / loncom / lonmaxima
Revision 1.5: download - view: text, annotated - select for diffs
Fri Mar 3 23:41:38 2006 UTC (18 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- globals cleanup
- some style

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

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