Annotation of loncom/lonmaxima, revision 1.5

1.1       www         1: #!/usr/bin/perl
                      2: #
                      3: # The LearningOnline Network with CAPA
                      4: # Connect to MAXIMA CAS
                      5: #
1.5     ! albertel    6: # $Id: lonmaxima,v 1.4 2006/03/03 23:31:06 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: 
                     56: use vars qw($PREFORK $MAX_CLIENTS_PER_CHILD %children $children $status
1.5     ! albertel   57: 	    $pidfile $port %perlvar $lastlog);
1.2       www        58:  
1.1       www        59: sub maximareply {
1.4       albertel   60:     my ($cmd) = @_;
1.1       www        61:     my $reply='';
                     62:     my $error='';
                     63:     my $exitstatus='';
                     64: 
                     65:     unless ($cmd=~/\;\n$/) { $cmd.=";\n"; }
1.5     ! albertel   66: 
        !            67:     my ($cmd_in, $cmd_out, $cmd_err);
1.1       www        68:     my $pid = open3($cmd_in, $cmd_out, $cmd_err, 'maxima');
1.2       www        69:     $children{$pid} = 1;
1.1       www        70:     
                     71:     print $cmd_in $cmd;
1.5     ! albertel   72:     close($cmd_in);
1.1       www        73: 
1.2       www        74:     &status("Command sent");
                     75: 
                     76:     my $selector = IO::Select->new();
1.1       www        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)/) {
1.5     ! albertel   86: 		    $line=~s/^\(.*\)/     /; 
        !            87: 		    $reply.=$line; 
        !            88: 		}
1.1       www        89: 	    }
                     90: 	    $selector->remove($fh) if eof($fh);
                     91: 	}
                     92:     }
1.5     ! albertel   93:     close($cmd_out);
        !            94:     close($cmd_err);
1.2       www        95:     &status("Command processed");
1.1       www        96:     return ($reply,$error,$exitstatus);
                     97: }
1.2       www        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 {
1.4       albertel  122:     my ($message)=@_;
1.2       www       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 {
1.4       albertel  134:     my ($what)=@_;
1.2       www       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 {
1.4       albertel  144:     my ($str)=@_;
1.2       www       145:     $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
                    146:     return $str;
                    147: }
                    148:  
                    149: # ----------------------------------------------------- Un-Escape Special Chars
                    150:  
                    151: sub unescape {
1.4       albertel  152:     my ($str)=@_;
1.2       www       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);
1.5     ! albertel  163:     &logthis("<font color=\"red\">CRITICAL: "
        !           164: 	     ."ABNORMAL EXIT. Child $$ died through "
        !           165: 	     ."\"$signal\"</font>");
1.2       www       166:     die("Signal abend");
                    167: }
1.5     ! albertel  168: 
1.2       www       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");
1.3       albertel  180: %perlvar=%{&LONCAPA::Configuration::read_conf('loncapa.conf')};
1.2       www       181:  
                    182: # ----------------------------- Make sure this process is running from user=www
                    183: my $wwwid=getpwnam('www');
                    184: if ($wwwid!=$<) {
1.5     ! albertel  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.' |\
1.2       www       188:  mailto $emailto -s '$subj' > /dev/null");
1.5     ! albertel  189:     exit 1;
1.2       www       190: }
                    191:  
                    192: # --------------------------------------------- Check if other instance running
                    193:  
                    194: $pidfile="$perlvar{'lonDaemons'}/logs/lonmaxima.pid";
                    195:  
                    196: if (-e $pidfile) {
1.5     ! albertel  197:     my $lfh=IO::File->new("$pidfile");
        !           198:     my $pide=<$lfh>;
        !           199:     chomp($pide);
        !           200:     if (kill 0 => $pide) { die "already running"; }
1.2       www       201: }
1.5     ! albertel  202: 
1.2       www       203: # ------------------------------------------------------- Listen to UNIX socket
                    204: &status("Opening socket");
                    205:  
                    206: $port = "$perlvar{'lonSockDir'}/maximasock";
                    207:  
                    208: unlink($port);
                    209:  
                    210: 
1.5     ! albertel  211: my $server;
1.2       www       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'};
1.5     ! albertel  237: open(PIDSAVE,">$execdir/logs/lonmaxima.pid");
1.2       www       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) {
1.5     ! albertel  249:     &make_new_child($server);
1.2       www       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)
1.3       albertel  260:     for (my $i = $children; $i < $PREFORK; $i++) {
1.2       www       261:         &status('Parent process, starting child');
1.5     ! albertel  262:         &make_new_child($server);           # top up the child pool
1.2       www       263:     }
                    264: }
                    265:                                                                                 
                    266: sub make_new_child {
1.5     ! albertel  267:     my ($server) = @_;
1.4       albertel  268: 
1.2       www       269:     # block signal for fork
1.4       albertel  270:     my $sigset = POSIX::SigSet->new(SIGINT);
1.2       www       271:     sigprocmask(SIG_BLOCK, $sigset)
                    272:         or die "Can't block SIGINT for fork: $!\n";
                    273:      
1.4       albertel  274:     die "fork: $!" unless defined (my $pid = fork);
1.2       www       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";
1.4       albertel  290: 
1.5     ! albertel  291: 	&process_requests($server);
1.4       albertel  292: 
1.2       www       293:         # tidy up gracefully and finish
1.1       www       294: 
1.2       www       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: }
1.4       albertel  301: 
                    302: sub process_requests {
1.5     ! albertel  303:     my ($server) = @_;
1.4       albertel  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');     
1.5     ! albertel  307: 	my $client = $server->accept()     or last;
        !           308: 	while (my $cmd=<$client>) {
1.4       albertel  309: 	    &status('Processing command');
                    310: 	    print $client &escape((&maximareply(&unescape($cmd)))[0])."\n";
                    311: 	}
                    312:     }    
                    313: }

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