Annotation of loncom/lonmaxima, revision 1.8

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

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