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