Annotation of loncom/lonmaxima, revision 1.6
1.1 www 1: #!/usr/bin/perl
2: #
3: # The LearningOnline Network with CAPA
4: # Connect to MAXIMA CAS
5: #
1.6 ! albertel 6: # $Id: lonmaxima,v 1.5 2006/03/03 23:41:38 albertel 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.1 www 33:
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
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
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.3 albertel 55:
56: use vars qw($PREFORK $MAX_CLIENTS_PER_CHILD %children $children $status
1.5 albertel 57: $pidfile $port %perlvar $lastlog);
1.2 www 58:
1.1 www 59: sub maximareply {
1.4 albertel 60: my ($cmd) = @_;
1.1 www 61: my $reply='';
62: my $error='';
63: my $exitstatus='';
64:
65: unless ($cmd=~/\;\n$/) { $cmd.=";\n"; }
1.5 albertel 66:
67: my ($cmd_in, $cmd_out, $cmd_err);
1.1 www 68: my $pid = open3($cmd_in, $cmd_out, $cmd_err, 'maxima');
1.2 www 69: $children{$pid} = 1;
1.1 www 70:
71: print $cmd_in $cmd;
1.5 albertel 72: close($cmd_in);
1.1 www 73:
1.2 www 74: &status("Command sent");
75:
76: my $selector = IO::Select->new();
1.1 www 77: $selector->add($cmd_err, $cmd_out);
78:
1.6 ! albertel 79: while (my @ready = $selector->can_read()) {
1.1 www 80: foreach my $fh (@ready) {
81: if (fileno($fh) == fileno($cmd_err)) {
82: $error.=<$cmd_err>;
83: } else {
1.6 ! albertel 84: my $line = scalar(<$cmd_out>);
1.1 www 85: if ($line=~/^(\(\%o|\s)/) {
1.5 albertel 86: $line=~s/^\(.*\)/ /;
87: $reply.=$line;
88: }
1.1 www 89: }
90: $selector->remove($fh) if eof($fh);
91: }
92: }
1.5 albertel 93: close($cmd_out);
94: close($cmd_err);
1.2 www 95: &status("Command processed");
1.1 www 96: return ($reply,$error,$exitstatus);
97: }
1.2 www 98:
99: # ------------------------------------------------------------ Service routines
100: sub REAPER { # takes care of dead children
101: # and MAXIMA processes
102: $SIG{CHLD} = \&REAPER;
103: my $pid = wait;
1.6 ! albertel 104: $children--;
! 105: delete($children{$pid});
1.2 www 106: }
107:
108: sub HUNTSMAN { # signal handler for SIGINT
109: local($SIG{CHLD}) = 'IGNORE'; # we're going to kill our children
1.6 ! albertel 110: kill('INT' => keys(%children));
1.2 www 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 {
1.4 albertel 122: my ($message)=@_;
1.2 www 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 {
1.4 albertel 134: my ($what)=@_;
1.2 www 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 {
1.4 albertel 144: my ($str)=@_;
1.2 www 145: $str =~ s/(\W)/"%".unpack('H2',$1)/eg;
146: return $str;
147: }
148:
149: # ----------------------------------------------------- Un-Escape Special Chars
150:
151: sub unescape {
1.4 albertel 152: my ($str)=@_;
1.2 www 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);
1.5 albertel 163: &logthis("<font color=\"red\">CRITICAL: "
164: ."ABNORMAL EXIT. Child $$ died through "
165: ."\"$signal\"</font>");
1.2 www 166: die("Signal abend");
167: }
1.5 albertel 168:
1.2 www 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");
1.3 albertel 180: %perlvar=%{&LONCAPA::Configuration::read_conf('loncapa.conf')};
1.2 www 181:
182: # ----------------------------- Make sure this process is running from user=www
183: my $wwwid=getpwnam('www');
184: if ($wwwid!=$<) {
1.5 albertel 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.' |\
1.2 www 188: mailto $emailto -s '$subj' > /dev/null");
1.5 albertel 189: exit 1;
1.2 www 190: }
191:
192: # --------------------------------------------- Check if other instance running
193:
194: $pidfile="$perlvar{'lonDaemons'}/logs/lonmaxima.pid";
195:
196: if (-e $pidfile) {
1.5 albertel 197: my $lfh=IO::File->new("$pidfile");
198: my $pide=<$lfh>;
199: chomp($pide);
1.6 ! albertel 200: if (kill(0 => $pide)) { die "already running"; }
1.2 www 201: }
1.5 albertel 202:
1.2 www 203: # ------------------------------------------------------- Listen to UNIX socket
204: &status("Opening socket");
205:
206: $port = "$perlvar{'lonSockDir'}/maximasock";
207:
208: unlink($port);
209:
210:
1.6 ! albertel 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: }
1.2 www 223:
224:
225: # ---------------------------------------------------- Fork once and dissociate
226:
227: my $fpid=fork;
228: exit if $fpid;
1.6 ! albertel 229: die("Couldn't fork: $!") unless defined($fpid);
1.2 www 230:
231: POSIX::setsid() or die "Can't start new session: $!";
232:
233: # ------------------------------------------------------- Write our PID on disk
234:
235: my $execdir=$perlvar{'lonDaemons'};
1.5 albertel 236: open(PIDSAVE,">$execdir/logs/lonmaxima.pid");
1.2 www 237: print PIDSAVE "$$\n";
238: close(PIDSAVE);
239: &logthis("<font color='red'>CRITICAL: ---------- Starting ----------</font>");
240: &status('Starting');
1.6 ! albertel 241:
1.2 www 242:
243:
244: # Fork off our children.
245: for (1 .. $PREFORK) {
1.5 albertel 246: &make_new_child($server);
1.2 www 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)
1.3 albertel 257: for (my $i = $children; $i < $PREFORK; $i++) {
1.2 www 258: &status('Parent process, starting child');
1.5 albertel 259: &make_new_child($server); # top up the child pool
1.2 www 260: }
261: }
262:
263: sub make_new_child {
1.5 albertel 264: my ($server) = @_;
1.4 albertel 265:
1.2 www 266: # block signal for fork
1.4 albertel 267: my $sigset = POSIX::SigSet->new(SIGINT);
1.2 www 268: sigprocmask(SIG_BLOCK, $sigset)
1.6 ! albertel 269: or die("Can't block SIGINT for fork: $!\n");
1.2 www 270:
1.6 ! albertel 271: die("fork: $!") unless defined(my $pid = fork);
1.2 www 272:
273: if ($pid) {
274: # Parent records the child's birth and returns.
275: sigprocmask(SIG_UNBLOCK, $sigset)
1.6 ! albertel 276: or die("Can't unblock SIGINT for fork: $!\n");
1.2 www 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)
1.6 ! albertel 286: or die("Can't unblock SIGINT for fork: $!\n");
1.4 albertel 287:
1.5 albertel 288: &process_requests($server);
1.4 albertel 289:
1.2 www 290: # tidy up gracefully and finish
1.1 www 291:
1.2 www 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: }
1.4 albertel 298:
299: sub process_requests {
1.5 albertel 300: my ($server) = @_;
1.4 albertel 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');
1.5 albertel 304: my $client = $server->accept() or last;
305: while (my $cmd=<$client>) {
1.4 albertel 306: &status('Processing command');
307: print $client &escape((&maximareply(&unescape($cmd)))[0])."\n";
308: }
309: }
310: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>