Annotation of loncom/lonmaxima, revision 1.9

1.1       www         1: #!/usr/bin/perl
                      2: #
                      3: # The LearningOnline Network with CAPA
                      4: # Connect to MAXIMA CAS
                      5: #
1.9     ! albertel    6: # $Id: lonmaxima,v 1.8 2006/03/04 06:44:11 albertel Exp $
1.1       www         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: #
1.2       www        32: 
1.1       www        33:  
                     34: use IPC::Open3;
                     35: use IO::Select;
1.2       www        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:  
1.3       albertel   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
1.5       albertel   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
1.3       albertel   55: use vars qw($PREFORK $MAX_CLIENTS_PER_CHILD %children $children $status
1.8       albertel   56: 	    $pidfile $port %perlvar $lastlog);
1.2       www        57:  
1.1       www        58: sub maximareply {
1.4       albertel   59:     my ($cmd) = @_;
1.1       www        60:     my $reply='';
                     61:     my $error='';
                     62:     my $exitstatus='';
                     63: 
                     64:     unless ($cmd=~/\;\n$/) { $cmd.=";\n"; }
1.5       albertel   65: 
                     66:     my ($cmd_in, $cmd_out, $cmd_err);
1.8       albertel   67:     my $maximapid = open3($cmd_in, $cmd_out, $cmd_err, 'maxima');
1.7       www        68:     $children{$maximapid} = 1;
1.1       www        69:     
                     70:     print $cmd_in $cmd;
1.5       albertel   71:     close($cmd_in);
1.1       www        72: 
1.2       www        73:     &status("Command sent");
                     74: 
1.7       www        75:     $SIG{ALRM} = sub { kill 9 => $maximapid; }; 
                     76:     alarm(5);
                     77: 
1.8       albertel   78:     my $selector = IO::Select->new();
1.7       www        79: 
1.1       www        80:     $selector->add($cmd_err, $cmd_out);
                     81:     
1.6       albertel   82:     while (my @ready = $selector->can_read()) {
1.1       www        83: 	foreach my $fh (@ready) {
1.9     ! albertel   84: 	    if (ref($fh) 
        !            85: 		&& ref($cmd_err)
        !            86: 		&& fileno($fh) == fileno($cmd_err)) {
1.1       www        87: 		$error.=<$cmd_err>;
                     88: 	    } else {
1.6       albertel   89: 		my $line = scalar(<$cmd_out>);
1.1       www        90:                 if ($line=~/^(\(\%o|\s)/) {
1.5       albertel   91: 		    $line=~s/^\(.*\)/     /; 
                     92: 		    $reply.=$line; 
                     93: 		}
1.1       www        94: 	    }
                     95: 	    $selector->remove($fh) if eof($fh);
                     96: 	}
                     97:     }
1.7       www        98:     alarm(0);
                     99:     $SIG{ALRM} = 'DEFAULT';
1.9     ! albertel  100:     if (ref($cmd_out)) { close($cmd_out); }
        !           101:     if (ref($cmd_err)) { close($cmd_err); }
        !           102: 
1.2       www       103:     &status("Command processed");
1.1       www       104:     return ($reply,$error,$exitstatus);
                    105: }
1.2       www       106:  
                    107: # ------------------------------------------------------------ Service routines 
                    108: sub REAPER {                        # takes care of dead children 
                    109:                                     # and MAXIMA processes
                    110:     $SIG{CHLD} = \&REAPER;
                    111:     my $pid = wait;
1.6       albertel  112:     $children--;
                    113:     delete($children{$pid});
1.2       www       114: }
                    115:  
                    116: sub HUNTSMAN {                      # signal handler for SIGINT
                    117:     local($SIG{CHLD}) = 'IGNORE';   # we're going to kill our children
1.6       albertel  118:     kill('INT' => keys(%children));
1.2       www       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 {
1.4       albertel  130:     my ($message)=@_;
1.2       www       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 {
1.4       albertel  142:     my ($what)=@_;
1.2       www       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 {
1.4       albertel  152:     my ($str)=@_;
1.2       www       153:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                    154:     return $str;
                    155: }
                    156:  
                    157: # ----------------------------------------------------- Un-Escape Special Chars
                    158:  
                    159: sub unescape {
1.4       albertel  160:     my ($str)=@_;
1.2       www       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);
1.5       albertel  171:     &logthis("<font color=\"red\">CRITICAL: "
                    172: 	     ."ABNORMAL EXIT. Child $$ died through "
                    173: 	     ."\"$signal\"</font>");
1.2       www       174:     die("Signal abend");
                    175: }
1.5       albertel  176: 
1.2       www       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");
1.3       albertel  188: %perlvar=%{&LONCAPA::Configuration::read_conf('loncapa.conf')};
1.2       www       189:  
                    190: # ----------------------------- Make sure this process is running from user=www
                    191: my $wwwid=getpwnam('www');
                    192: if ($wwwid!=$<) {
1.5       albertel  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.' |\
1.2       www       196:  mailto $emailto -s '$subj' > /dev/null");
1.5       albertel  197:     exit 1;
1.2       www       198: }
                    199:  
                    200: # --------------------------------------------- Check if other instance running
                    201:  
                    202: $pidfile="$perlvar{'lonDaemons'}/logs/lonmaxima.pid";
                    203:  
                    204: if (-e $pidfile) {
1.5       albertel  205:     my $lfh=IO::File->new("$pidfile");
                    206:     my $pide=<$lfh>;
                    207:     chomp($pide);
1.6       albertel  208:     if (kill(0 => $pide)) { die "already running"; }
1.2       www       209: }
1.5       albertel  210: 
1.2       www       211: # ------------------------------------------------------- Listen to UNIX socket
                    212: &status("Opening socket");
                    213:  
                    214: $port = "$perlvar{'lonSockDir'}/maximasock";
                    215:  
                    216: unlink($port);
                    217:  
                    218: 
1.6       albertel  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: }
1.2       www       231:     
                    232:  
                    233: # ---------------------------------------------------- Fork once and dissociate
                    234:  
                    235: my $fpid=fork;
                    236: exit if $fpid;
1.6       albertel  237: die("Couldn't fork: $!") unless defined($fpid);
1.2       www       238:  
                    239: POSIX::setsid() or die "Can't start new session: $!";
                    240:  
                    241: # ------------------------------------------------------- Write our PID on disk
                    242:  
                    243: my $execdir=$perlvar{'lonDaemons'};
1.5       albertel  244: open(PIDSAVE,">$execdir/logs/lonmaxima.pid");
1.2       www       245: print PIDSAVE "$$\n";
                    246: close(PIDSAVE);
                    247: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
                    248: &status('Starting');
1.6       albertel  249:      
1.2       www       250: 
                    251: # Fork off our children.
                    252: for (1 .. $PREFORK) {
1.5       albertel  253:     &make_new_child($server);
1.2       www       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)
1.3       albertel  264:     for (my $i = $children; $i < $PREFORK; $i++) {
1.2       www       265:         &status('Parent process, starting child');
1.5       albertel  266:         &make_new_child($server);           # top up the child pool
1.2       www       267:     }
                    268: }
                    269:                                                                                 
                    270: sub make_new_child {
1.5       albertel  271:     my ($server) = @_;
1.4       albertel  272: 
1.2       www       273:     # block signal for fork
1.4       albertel  274:     my $sigset = POSIX::SigSet->new(SIGINT);
1.2       www       275:     sigprocmask(SIG_BLOCK, $sigset)
1.6       albertel  276:         or die("Can't block SIGINT for fork: $!\n");
1.2       www       277:      
1.6       albertel  278:     die("fork: $!") unless defined(my $pid = fork);
1.2       www       279:      
                    280:     if ($pid) {
                    281:         # Parent records the child's birth and returns.
                    282:         sigprocmask(SIG_UNBLOCK, $sigset)
1.6       albertel  283:             or die("Can't unblock SIGINT for fork: $!\n");
1.2       www       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)
1.6       albertel  293:             or die("Can't unblock SIGINT for fork: $!\n");
1.4       albertel  294: 
1.5       albertel  295: 	&process_requests($server);
1.4       albertel  296: 
1.2       www       297:         # tidy up gracefully and finish
1.1       www       298: 
1.2       www       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: }
1.4       albertel  305: 
                    306: sub process_requests {
1.5       albertel  307:     my ($server) = @_;
1.4       albertel  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');     
1.5       albertel  311: 	my $client = $server->accept()     or last;
                    312: 	while (my $cmd=<$client>) {
1.4       albertel  313: 	    &status('Processing command');
                    314: 	    print $client &escape((&maximareply(&unescape($cmd)))[0])."\n";
                    315: 	}
                    316:     }    
                    317: }

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