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