Annotation of loncom/lonmaxima, revision 1.7

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

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