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