Annotation of loncom/lonmaxima, revision 1.13

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

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