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