Annotation of loncom/lonmaxima, revision 1.14

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

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