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