1: #!/usr/bin/perl
2: #
3: # The LearningOnline Network with CAPA
4: # Connect to MAXIMA CAS
5: #
6: # $Id: lonmaxima,v 1.15 2006/03/08 15:58:03 www Exp $
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: #
32:
33:
34: use IPC::Open3;
35: use IO::Select;
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:
43: use strict;
44:
45: # global variables
46: my $STARTPORT = 5664; # port for first child's server
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
50: my %usedmaximaports = (); # keys are the used maximaports
51: my $children = 0; # current number of children
52: my $status; # string for current status
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
57: use vars qw($PREFORK $MAX_CLIENTS_PER_CHILD %children $children %usedmaximaports $status
58: $pidfile $port %perlvar $lastlog);
59:
60: # ------------------------------------------------------------ Service routines
61: sub REAPER { # takes care of dead children
62: # and MAXIMA processes
63: $SIG{CHLD} = \&REAPER;
64: my $pid = wait;
65: $children--;
66: &logthis("Child $pid for port or process $children{$pid} died");
67: delete($usedmaximaports{$children{$pid}});
68: delete($children{$pid});
69: }
70:
71: sub HUNTSMAN { # signal handler for SIGINT
72: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
73: kill('INT' => keys(%children));
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 {
85: my ($message)=@_;
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 {
97: my ($what)=@_;
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 {
107: my ($str)=@_;
108: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
109: return $str;
110: }
111:
112: # ----------------------------------------------------- Un-Escape Special Chars
113:
114: sub unescape {
115: my ($str)=@_;
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);
126: &logthis("<font color=\"red\">CRITICAL: "
127: ."ABNORMAL EXIT. Child $$ died through "
128: ."\"$signal\"</font>");
129: die("Signal abend");
130: }
131:
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");
141: %perlvar=%{&LONCAPA::Configuration::read_conf('loncapa.conf')};
142:
143: # ----------------------------- Make sure this process is running from user=www
144: my $wwwid=getpwnam('www');
145: if ($wwwid!=$<) {
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.' |\
149: mailto $emailto -s '$subj' > /dev/null");
150: exit 1;
151: }
152:
153: # --------------------------------------------- Check if other instance running
154:
155: $pidfile="$perlvar{'lonDaemons'}/logs/lonmaxima.pid";
156:
157: if (-e $pidfile) {
158: my $lfh=IO::File->new("$pidfile");
159: my $pide=<$lfh>;
160: chomp($pide);
161: if (kill(0 => $pide)) { die "already running"; }
162: }
163:
164: # ------------------------------------------------------- Listen to UNIX socket
165: &status("Opening socket");
166:
167: $port = "$perlvar{'lonSockDir'}/maximasock";
168:
169: unlink($port);
170:
171:
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: }
184:
185:
186: # ---------------------------------------------------- Fork once and dissociate
187:
188: my $fpid=fork;
189: exit if $fpid;
190: die("Couldn't fork: $!") unless defined($fpid);
191:
192: POSIX::setsid() or die "Can't start new session: $!";
193:
194: # ------------------------------------------------------- Write our PID on disk
195:
196: my $execdir=$perlvar{'lonDaemons'};
197: open(PIDSAVE,">$execdir/logs/lonmaxima.pid");
198: print PIDSAVE "$$\n";
199: close(PIDSAVE);
200: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
201: &status('Starting');
202:
203:
204: # Install signal handlers.
205: $SIG{CHLD} = \&REAPER;
206: $SIG{INT} = $SIG{TERM} = \&HUNTSMAN;
207:
208: my $maximaport=$STARTPORT;
209: # Fork off our children.
210: for (1 .. $PREFORK) {
211: &make_new_child($server,$maximaport);
212: $maximaport++;
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)
219: for (my $i = $children; $i < $PREFORK; $i++) {
220: &status('Parent process, starting child');
221: my $newport;
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
228: }
229: }
230: }
231:
232: sub make_new_child {
233: my ($server,$maximaport) = @_;
234:
235: # block signal for fork
236: my $sigset = POSIX::SigSet->new(SIGINT);
237: sigprocmask(SIG_BLOCK, $sigset)
238: or die("Can't block SIGINT for fork: $!\n");
239:
240: die("fork: $!") unless defined(my $pid = fork);
241:
242: if ($pid) {
243: # Parent records the child's birth and returns.
244: sigprocmask(SIG_UNBLOCK, $sigset)
245: or die("Can't unblock SIGINT for fork: $!\n");
246: $children{$pid} = $maximaport;
247: $children++;
248: $usedmaximaports{$maximaport}=1;
249: return;
250: } else {
251: &logthis("Starting child on port $maximaport");
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)
257: or die("Can't unblock SIGINT for fork: $!\n");
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";
266: my $maximaselect=IO::Select->new($maximaserver);
267: sleep(1);
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");
272: $children{$maximapid} = "Maxima $maximapid port $maximaport";
273: my $prompt=<$cmd_out>;
274: &logthis("Maxima $maximapid: $prompt");
275:
276: # hopefully, MAXIMA calls us back
277: &status("Waiting $maximapid on $maximaport");
278: my $maximaclient=$maximaserver->accept();
279: $maximaclient->blocking(0);
280: $maximaselect->add($maximaclient);
281: &status("$maximapid on $maximaport connected.");
282: &logthis("Maxima $maximapid on port $maximaport connected.");
283: sleep(2);
284:
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);
292: &maximawrite($maximaselect,&unescape($cmd).";\n");
293: print $client &escape(&maximareply($maximaselect))."\n";
294: }
295: }
296:
297: # tidy up gracefully and finish
298:
299: if (ref($cmd_out)) { close($cmd_out); }
300: if (ref($cmd_err)) { close($cmd_err); }
301: if (ref($cmd_in)) { close($cmd_in); }
302:
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: }
309:
310: sub maximareply {
311: my ($maximaselect)=@_;
312: my $output='';
313:
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;
320: }
321:
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>