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