Annotation of loncom/loncnew, revision 1.14
1.1 foxr 1: #!/usr/bin/perl
1.2 albertel 2: # The LearningOnline Network with CAPA
3: # lonc maintains the connections to remote computers
4: #
1.14 ! foxr 5: # $Id: loncnew,v 1.13 2003/07/02 01:31:55 foxr Exp $
1.2 albertel 6: #
7: # Copyright Michigan State University Board of Trustees
8: #
9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
10: #
11: # LON-CAPA is free software; you can redistribute it and/or modify
12: # it under the terms of the GNU General Public License as published by
13: # the Free Software Foundation; either version 2 of the License, or
14: # (at your option) any later version.
15: #
16: # LON-CAPA is distributed in the hope that it will be useful,
17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19: # GNU General Public License for more details.
20: #
21: # You should have received a copy of the GNU General Public License
22: # along with LON-CAPA; if not, write to the Free Software
23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24: #
25: # /home/httpd/html/adm/gpl.txt
26: #
27: # http://www.lon-capa.org/
28: #
1.1 foxr 29: #
30: # new lonc handles n requestors spread out bver m connections to londs.
31: # This module is based on the Event class.
32: # Development iterations:
33: # - Setup basic event loop. (done)
34: # - Add timer dispatch. (done)
35: # - Add ability to accept lonc UNIX domain sockets. (done)
36: # - Add ability to create/negotiate lond connections (done).
1.7 foxr 37: # - Add general logic for dispatching requests and timeouts. (done).
38: # - Add support for the lonc/lond requests. (done).
1.1 foxr 39: # - Add logging/status monitoring.
40: # - Add Signal handling - HUP restarts. USR1 status report.
1.7 foxr 41: # - Add Configuration file I/O (done).
1.1 foxr 42: # - Add management/status request interface.
1.8 foxr 43: # - Add deferred request capability. (done)
1.9 foxr 44: # - Detect transmission timeouts.
1.7 foxr 45: #
46:
47: # Change log:
1.8 foxr 48: # $Log: loncnew,v $
1.14 ! foxr 49: # Revision 1.13 2003/07/02 01:31:55 foxr
! 50: # Added kill -HUP logic (restart).
! 51: #
1.12 foxr 52: # Revision 1.11 2003/06/25 01:54:44 foxr
53: # Fix more problems with transaction failure.
54: #
1.11 foxr 55: # Revision 1.10 2003/06/24 02:46:04 foxr
56: # Put a limit on the number of times we'll retry a connection.
57: # Start getting the signal stuff put in as well...note that need to get signals
58: # going or else 6the client will permanently give up on dead servers.
59: #
1.10 foxr 60: # Revision 1.9 2003/06/13 02:38:43 foxr
61: # Add logging in 'expected format'
62: #
1.9 foxr 63: # Revision 1.8 2003/06/11 02:04:35 foxr
64: # Support delayed transactions... this is done uniformly by encapsulating
65: # transactions in an object ... a LondTransaction that is implemented by
66: # LondTransaction.pm
67: #
1.8 foxr 68: # Revision 1.7 2003/06/03 01:59:39 foxr
69: # complete coding to support deferred transactions.
70: #
1.7 foxr 71: #
1.1 foxr 72:
73: use lib "/home/httpd/lib/perl/";
74: use lib "/home/foxr/newloncapa/types";
75: use Event qw(:DEFAULT );
76: use POSIX qw(:signal_h);
1.12 foxr 77: use POSIX;
1.1 foxr 78: use IO::Socket;
79: use IO::Socket::INET;
80: use IO::Socket::UNIX;
1.9 foxr 81: use IO::File;
1.6 foxr 82: use IO::Handle;
1.1 foxr 83: use Socket;
84: use Crypt::IDEA;
85: use LONCAPA::Queue;
86: use LONCAPA::Stack;
87: use LONCAPA::LondConnection;
1.7 foxr 88: use LONCAPA::LondTransaction;
1.1 foxr 89: use LONCAPA::Configuration;
90: use LONCAPA::HashIterator;
91:
92:
93: #
94: # Disable all signals we might receive from outside for now.
95: #
1.14 ! foxr 96: #$SIG{QUIT} = IGNORE;
! 97: #$SIG{HUP} = IGNORE;
! 98: #$SIG{USR1} = IGNORE;
! 99: #$SIG{INT} = IGNORE;
! 100: #$SIG{CHLD} = IGNORE;
! 101: #$SIG{__DIE__} = IGNORE;
1.1 foxr 102:
103:
104: # Read the httpd configuration file to get perl variables
105: # normally set in apache modules:
106:
107: my $perlvarref = LONCAPA::Configuration::read_conf('loncapa.conf');
108: my %perlvar = %{$perlvarref};
109:
110: #
111: # parent and shared variables.
112:
113: my %ChildHash; # by pid -> host.
114:
115:
1.9 foxr 116: my $MaxConnectionCount = 10; # Will get from config later.
1.1 foxr 117: my $ClientConnection = 0; # Uniquifier for client events.
118:
1.9 foxr 119: my $DebugLevel = 0;
1.1 foxr 120: my $IdleTimeout= 3600; # Wait an hour before pruning connections.
121:
122: #
123: # The variables below are only used by the child processes.
124: #
125: my $RemoteHost; # Name of host child is talking to.
126: my $UnixSocketDir= "/home/httpd/sockets";
127: my $IdleConnections = Stack->new(); # Set of idle connections
128: my %ActiveConnections; # Connections to the remote lond.
1.7 foxr 129: my %ActiveTransactions; # LondTransactions in flight.
1.1 foxr 130: my %ActiveClients; # Serial numbers of active clients by socket.
131: my $WorkQueue = Queue->new(); # Queue of pending transactions.
132: my $ConnectionCount = 0;
1.4 foxr 133: my $IdleSeconds = 0; # Number of seconds idle.
1.9 foxr 134: my $Status = ""; # Current status string.
1.14 ! foxr 135: my $RecentLogEntry = "";
1.10 foxr 136: my $ConnectionRetries=5; # Number of connection retries allowed.
137: my $ConnectionRetriesLeft=5; # Number of connection retries remaining.
1.1 foxr 138:
139: #
1.9 foxr 140: # The hash below gives the HTML format for log messages
141: # given a severity.
142: #
143: my %LogFormats;
144:
145: $LogFormats{"CRITICAL"} = "<font color=red>CRITICAL: %s</font>";
146: $LogFormats{"SUCCESS"} = "<font color=green>SUCCESS: %s</font>";
147: $LogFormats{"INFO"} = "<font color=yellow>INFO: %s</font>";
148: $LogFormats{"WARNING"} = "<font color=blue>WARNING: %s</font>";
149: $LogFormats{"DEFAULT"} = " %s ";
150:
1.10 foxr 151:
152:
153: =pod
154:
155: =head2 LogPerm
156:
157: Makes an entry into the permanent log file.
158:
159: =cut
160: sub LogPerm {
161: my $message=shift;
162: my $execdir=$perlvar{'lonDaemons'};
163: my $now=time;
164: my $local=localtime($now);
165: my $fh=IO::File->new(">>$execdir/logs/lonnet.perm.log");
166: print $fh "$now:$message:$local\n";
167: }
1.9 foxr 168:
169: =pod
170:
171: =head2 Log
172:
173: Logs a message to the log file.
174: Parameters:
175:
176: =item severity
177:
178: One of CRITICAL, WARNING, INFO, SUCCESS used to select the
179: format string used to format the message. if the severity is
180: not a defined severity the Default format string is used.
181:
182: =item message
183:
184: The base message. In addtion to the format string, the message
185: will be appended to a string containing the name of our remote
186: host and the time will be formatted into the message.
187:
188: =cut
189:
190: sub Log {
191: my $severity = shift;
192: my $message = shift;
193:
194: if(!$LogFormats{$severity}) {
195: $severity = "DEFAULT";
196: }
197:
198: my $format = $LogFormats{$severity};
199:
200: # Put the window dressing in in front of the message format:
201:
202: my $now = time;
203: my $local = localtime($now);
204: my $finalformat = "$local ($$) [$RemoteHost] [$Status] ";
205: my $finalformat = $finalformat.$format."\n";
206:
207: # open the file and put the result.
208:
209: my $execdir = $perlvar{'lonDaemons'};
210: my $fh = IO::File->new(">>$execdir/logs/lonc.log");
211: my $msg = sprintf($finalformat, $message);
1.14 ! foxr 212: $RecentLogEntry = $msg;
1.9 foxr 213: print $fh $msg;
214:
1.10 foxr 215:
1.9 foxr 216: }
1.6 foxr 217:
1.3 albertel 218:
1.1 foxr 219: =pod
1.3 albertel 220:
221: =head2 GetPeerName
222:
223: Returns the name of the host that a socket object is connected to.
224:
1.1 foxr 225: =cut
226:
227: sub GetPeername {
228: my $connection = shift;
229: my $AdrFamily = shift;
230: my $peer = $connection->peername();
231: my $peerport;
232: my $peerip;
233: if($AdrFamily == AF_INET) {
234: ($peerport, $peerip) = sockaddr_in($peer);
235: my $peername = gethostbyaddr($iaddr, $AdrFamily);
236: return $peername;
237: } elsif ($AdrFamily == AF_UNIX) {
238: my $peerfile;
239: ($peerfile) = sockaddr_un($peer);
240: return $peerfile;
241: }
242: }
243: #----------------------------- Timer management ------------------------
244: =pod
1.3 albertel 245:
1.1 foxr 246: =head2 Debug
1.3 albertel 247:
248: Invoked to issue a debug message.
249:
1.1 foxr 250: =cut
1.3 albertel 251:
1.1 foxr 252: sub Debug {
253: my $level = shift;
254: my $message = shift;
255: if ($level <= $DebugLevel) {
256: print $message." host = ".$RemoteHost."\n";
257: }
258: }
259:
260: sub SocketDump {
261: my $level = shift;
262: my $socket= shift;
263: if($level <= $DebugLevel) {
264: $socket->Dump();
265: }
266: }
1.3 albertel 267:
1.1 foxr 268: =pod
1.3 albertel 269:
1.5 foxr 270: =head2 ShowStatus
271:
272: Place some text as our pid status.
1.10 foxr 273: and as what we return in a SIGUSR1
1.5 foxr 274:
275: =cut
276: sub ShowStatus {
1.10 foxr 277: my $state = shift;
278: my $now = time;
279: my $local = localtime($now);
280: $Status = $local.": ".$state;
281: $0='lonc: '.$state.' '.$local;
1.5 foxr 282: }
283:
284: =pod
285:
1.1 foxr 286: =head2 Tick
1.3 albertel 287:
288: Invoked each timer tick.
289:
1.1 foxr 290: =cut
291:
1.5 foxr 292:
1.1 foxr 293: sub Tick {
294: my $client;
1.5 foxr 295: ShowStatus(GetServerHost()." Connection count: ".$ConnectionCount);
1.12 foxr 296:
1.4 foxr 297: # Is it time to prune connection count:
298:
299:
300: if($IdleConnections->Count() &&
301: ($WorkQueue->Count() == 0)) { # Idle connections and nothing to do?
302: $IdleSeconds++;
303: if($IdleSeconds > $IdleTimeout) { # Prune a connection...
304: $Socket = $IdleConnections->pop();
1.6 foxr 305: KillSocket($Socket);
1.4 foxr 306: }
307: } else {
308: $IdleSeconds = 0; # Reset idle count if not idle.
309: }
1.5 foxr 310:
311: # Do we have work in the queue, but no connections to service them?
312: # If so, try to make some new connections to get things going again.
313: #
314:
315: my $Requests = $WorkQueue->Count();
1.10 foxr 316: if (($ConnectionCount == 0) && ($Requests > 0)) {
317: if ($ConnectionRetriesLeft > 0) {
318: my $Connections = ($Requests <= $MaxConnectionCount) ?
319: $Requests : $MaxConnectionCount;
320: Debug(1,"Work but no connections, start ".$Connections." of them");
321: for ($i =0; $i < $Connections; $i++) {
322: MakeLondConnection();
323: }
324: } else {
325: Debug(1,"Work in queue, but gave up on connections..flushing\n");
326: EmptyQueue(); # Connections can't be established.
1.5 foxr 327: }
328:
329: }
1.1 foxr 330: }
331:
332: =pod
1.3 albertel 333:
1.1 foxr 334: =head2 SetupTimer
335:
1.3 albertel 336: Sets up a 1 per sec recurring timer event. The event handler is used to:
1.1 foxr 337:
1.3 albertel 338: =item
339:
340: Trigger timeouts on communications along active sockets.
341:
342: =item
343:
344: Trigger disconnections of idle sockets.
1.1 foxr 345:
346: =cut
347:
348: sub SetupTimer {
349: Debug(6, "SetupTimer");
350: Event->timer(interval => 1, debug => 1, cb => \&Tick );
351: }
1.3 albertel 352:
1.1 foxr 353: =pod
1.3 albertel 354:
1.1 foxr 355: =head2 ServerToIdle
1.3 albertel 356:
357: This function is called when a connection to the server is
358: ready for more work.
359:
360: If there is work in the Work queue the top element is dequeued
1.1 foxr 361: and the connection will start to work on it. If the work queue is
362: empty, the connection is pushed on the idle connection stack where
363: it will either get another work unit, or alternatively, if it sits there
364: long enough, it will be shut down and released.
365:
1.3 albertel 366: =cut
1.1 foxr 367:
368: sub ServerToIdle {
369: my $Socket = shift; # Get the socket.
1.7 foxr 370: delete($ActiveTransactions{$Socket}); # Server has no transaction
1.1 foxr 371:
372: &Debug(6, "Server to idle");
373:
374: # If there's work to do, start the transaction:
375:
1.7 foxr 376: $reqdata = $WorkQueue->dequeue(); # This is a LondTransaction
1.1 foxr 377: unless($reqdata eq undef) {
1.7 foxr 378: Debug(9, "Queue gave request data: ".$reqdata->getRequest());
379: &StartRequest($Socket, $reqdata);
1.8 foxr 380:
1.1 foxr 381: } else {
382:
383: # There's no work waiting, so push the server to idle list.
384: &Debug(8, "No new work requests, server connection going idle");
385: $IdleConnections->push($Socket);
386: }
387: }
1.3 albertel 388:
1.1 foxr 389: =pod
1.3 albertel 390:
1.1 foxr 391: =head2 ClientWritable
1.3 albertel 392:
393: Event callback for when a client socket is writable.
394:
395: This callback is established when a transaction reponse is
396: avaiable from lond. The response is forwarded to the unix socket
397: as it becomes writable in this sub.
398:
1.1 foxr 399: Parameters:
400:
1.3 albertel 401: =item Event
402:
403: The event that has been triggered. Event->w->data is
404: the data and Event->w->fd is the socket to write.
1.1 foxr 405:
406: =cut
1.3 albertel 407:
1.1 foxr 408: sub ClientWritable {
409: my $Event = shift;
410: my $Watcher = $Event->w;
411: my $Data = $Watcher->data;
412: my $Socket = $Watcher->fd;
413:
414: # Try to send the data:
415:
416: &Debug(6, "ClientWritable writing".$Data);
417: &Debug(9, "Socket is: ".$Socket);
418:
1.6 foxr 419: if($Socket->connected) {
420: my $result = $Socket->send($Data, 0);
421:
422: # $result undefined: the write failed.
423: # otherwise $result is the number of bytes written.
424: # Remove that preceding string from the data.
425: # If the resulting data is empty, destroy the watcher
426: # and set up a read event handler to accept the next
427: # request.
428:
429: &Debug(9,"Send result is ".$result." Defined: ".defined($result));
430: if(defined($result)) {
431: &Debug(9, "send result was defined");
432: if($result == length($Data)) { # Entire string sent.
433: &Debug(9, "ClientWritable data all written");
434: $Watcher->cancel();
435: #
436: # Set up to read next request from socket:
437:
438: my $descr = sprintf("Connection to lonc client %d",
439: $ActiveClients{$Socket});
440: Event->io(cb => \&ClientRequest,
441: poll => 'r',
442: desc => $descr,
443: data => "",
444: fd => $Socket);
445:
446: } else { # Partial string sent.
447: $Watcher->data(substr($Data, $result));
448: }
449:
450: } else { # Error of some sort...
451:
452: # Some errnos are possible:
453: my $errno = $!;
454: if($errno == POSIX::EWOULDBLOCK ||
455: $errno == POSIX::EAGAIN ||
456: $errno == POSIX::EINTR) {
457: # No action taken?
458: } else { # Unanticipated errno.
459: &Debug(5,"ClientWritable error or peer shutdown".$RemoteHost);
460: $Watcher->cancel; # Stop the watcher.
461: $Socket->shutdown(2); # Kill connection
462: $Socket->close(); # Close the socket.
463: }
1.1 foxr 464:
465: }
1.6 foxr 466: } else {
467: $Watcher->cancel(); # A delayed request...just cancel.
1.1 foxr 468: }
469: }
470:
471: =pod
1.3 albertel 472:
1.1 foxr 473: =head2 CompleteTransaction
1.3 albertel 474:
475: Called when the reply data has been received for a lond
1.1 foxr 476: transaction. The reply data must now be sent to the
477: ultimate client on the other end of the Unix socket. This is
478: done by setting up a writable event for the socket with the
479: data the reply data.
1.3 albertel 480:
1.1 foxr 481: Parameters:
1.3 albertel 482:
483: =item Socket
484:
485: Socket on which the lond transaction occured. This is a
486: LondConnection. The data received is in the TransactionReply member.
487:
1.7 foxr 488: =item Transaction
1.3 albertel 489:
1.7 foxr 490: The transaction that is being completed.
1.1 foxr 491:
492: =cut
1.3 albertel 493:
1.1 foxr 494: sub CompleteTransaction {
495: &Debug(6,"Complete transaction");
496: my $Socket = shift;
1.7 foxr 497: my $Transaction = shift;
1.1 foxr 498:
1.7 foxr 499: if (!$Transaction->isDeferred()) { # Normal transaction
500: my $data = $Socket->GetReply(); # Data to send.
501: StartClientReply($Transaction, $data);
502: } else { # Delete deferred transaction file.
1.9 foxr 503: Log("SUCCESS", "A delayed transaction was completed");
1.10 foxr 504: LogPerm("S:$Client:".$Transaction->getRequest());
1.7 foxr 505: unlink $Transaction->getFile();
506: }
1.6 foxr 507: }
508: =pod
509: =head1 StartClientReply
510:
511: Initiates a reply to a client where the reply data is a parameter.
512:
1.7 foxr 513: =head2 parameters:
514:
515: =item Transaction
516:
517: The transaction for which we are responding to the client.
518:
519: =item data
520:
521: The data to send to apached client.
522:
1.6 foxr 523: =cut
524: sub StartClientReply {
1.7 foxr 525: my $Transaction = shift;
1.6 foxr 526: my $data = shift;
1.1 foxr 527:
1.12 foxr 528:
1.7 foxr 529: my $Client = $Transaction->getClient();
530:
1.1 foxr 531: &Debug(8," Reply was: ".$data);
532: my $Serial = $ActiveClients{$Client};
533: my $desc = sprintf("Connection to lonc client %d",
1.6 foxr 534:
1.1 foxr 535: $Serial);
536: Event->io(fd => $Client,
537: poll => "w",
538: desc => $desc,
539: cb => \&ClientWritable,
540: data => $data);
541: }
1.4 foxr 542: =pod
543: =head2 FailTransaction
544:
545: Finishes a transaction with failure because the associated lond socket
1.7 foxr 546: disconnected. There are two possibilities:
547: - The transaction is deferred: in which case we just quietly
548: delete the transaction since there is no client connection.
549: - The transaction is 'live' in which case we initiate the sending
550: of "con_lost" to the client.
551:
552: Deleting the transaction means killing it from the
553: %ActiveTransactions hash.
1.4 foxr 554:
555: Parameters:
556:
557: =item client
558:
1.7 foxr 559: The LondTransaction we are failing.
560:
1.4 foxr 561: =cut
562:
563: sub FailTransaction {
1.7 foxr 564: my $transaction = shift;
1.10 foxr 565: Debug(1, "Failing transaction: ".$transaction->getRequest());
566: if (!$transaction->isDeferred()) { # If the transaction is deferred we'll get to it.
1.11 foxr 567: my $client = $transaction->getClient();
1.10 foxr 568: Debug(1," Replying con_lost to ".$transaction->getRequest());
1.11 foxr 569: StartClientReply($transaction, "con_lost\n");
1.7 foxr 570: }
1.4 foxr 571:
572: }
573:
574: =pod
1.6 foxr 575: =head1 EmptyQueue
1.7 foxr 576:
1.6 foxr 577: Fails all items in the work queue with con_lost.
1.7 foxr 578: Note that each item in the work queue is a transaction.
579:
1.6 foxr 580: =cut
581: sub EmptyQueue {
582: while($WorkQueue->Count()) {
1.10 foxr 583: my $request = $WorkQueue->dequeue(); # This is a transaction
1.7 foxr 584: FailTransaction($request);
1.6 foxr 585: }
586: }
587:
588: =pod
1.4 foxr 589:
1.9 foxr 590: =head2 CloseAllLondConnections
591:
592: Close all connections open on lond prior to exit e.g.
593:
594: =cut
595: sub CloseAllLondConnections {
596: foreach $Socket (keys %ActiveConnections) {
597: KillSocket($Socket);
598: }
599: }
600: =cut
601:
602: =pod
603:
1.4 foxr 604: =head2 KillSocket
605:
606: Destroys a socket. This function can be called either when a socket
607: has died of 'natural' causes or because a socket needs to be pruned due to
608: idleness. If the socket has died naturally, if there are no longer any
609: live connections a new connection is created (in case there are transactions
610: in the queue). If the socket has been pruned, it is never re-created.
611:
612: Parameters:
1.1 foxr 613:
1.4 foxr 614: =item Socket
615:
616: The socket to kill off.
617:
618: =item Restart
619:
620: nonzero if we are allowed to create a new connection.
621:
622:
623: =cut
624: sub KillSocket {
625: my $Socket = shift;
626:
1.9 foxr 627: $Socket->Shutdown();
628:
1.7 foxr 629: # If the socket came from the active connection set,
630: # delete its transaction... note that FailTransaction should
631: # already have been called!!!
632: # otherwise it came from the idle set.
633: #
1.4 foxr 634:
635: if(exists($ActiveTransactions{$Socket})) {
636: delete ($ActiveTransactions{$Socket});
637: }
638: if(exists($ActiveConnections{$Socket})) {
639: delete($ActiveConnections{$Socket});
640: }
641: $ConnectionCount--;
1.6 foxr 642:
643: # If the connection count has gone to zero and there is work in the
644: # work queue, the work all gets failed with con_lost.
645: #
646: if($ConnectionCount == 0) {
647: EmptyQueue;
1.4 foxr 648: }
649: }
1.1 foxr 650:
651: =pod
1.3 albertel 652:
1.1 foxr 653: =head2 LondReadable
1.3 albertel 654:
1.1 foxr 655: This function is called whenever a lond connection
656: is readable. The action is state dependent:
657:
1.3 albertel 658: =head3 State=Initialized
659:
660: We''re waiting for the challenge, this is a no-op until the
1.1 foxr 661: state changes.
1.3 albertel 662:
1.1 foxr 663: =head3 State=Challenged
1.3 albertel 664:
665: The challenge has arrived we need to transition to Writable.
1.1 foxr 666: The connection must echo the challenge back.
1.3 albertel 667:
1.1 foxr 668: =head3 State=ChallengeReplied
1.3 albertel 669:
670: The challenge has been replied to. The we are receiveing the
1.1 foxr 671: 'ok' from the partner.
1.3 albertel 672:
1.1 foxr 673: =head3 State=RequestingKey
1.3 albertel 674:
675: The ok has been received and we need to send the request for
1.1 foxr 676: an encryption key. Transition to writable for that.
1.3 albertel 677:
1.1 foxr 678: =head3 State=ReceivingKey
1.3 albertel 679:
680: The the key has been requested, now we are reading the new key.
681:
1.1 foxr 682: =head3 State=Idle
1.3 albertel 683:
684: The encryption key has been negotiated or we have finished
1.1 foxr 685: reading data from the a transaction. If the callback data has
686: a client as well as the socket iformation, then we are
687: doing a transaction and the data received is relayed to the client
688: before the socket is put on the idle list.
1.3 albertel 689:
1.1 foxr 690: =head3 State=SendingRequest
1.3 albertel 691:
692: I do not think this state can be received here, but if it is,
1.1 foxr 693: the appropriate thing to do is to transition to writable, and send
694: the request.
1.3 albertel 695:
1.1 foxr 696: =head3 State=ReceivingReply
1.3 albertel 697:
698: We finished sending the request to the server and now transition
1.1 foxr 699: to readable to receive the reply.
700:
701: The parameter to this function are:
1.3 albertel 702:
1.1 foxr 703: The event. Implicit in this is the watcher and its data. The data
704: contains at least the lond connection object and, if a
705: transaction is in progress, the socket attached to the local client.
706:
1.3 albertel 707: =cut
1.1 foxr 708:
709: sub LondReadable {
1.8 foxr 710:
1.1 foxr 711: my $Event = shift;
712: my $Watcher = $Event->w;
713: my $Socket = $Watcher->data;
714: my $client = undef;
715:
1.8 foxr 716: &Debug(6,"LondReadable called state = ".$State);
717:
1.1 foxr 718:
719: my $State = $Socket->GetState(); # All action depends on the state.
720:
721: SocketDump(6, $Socket);
1.12 foxr 722: my $status = $Socket->Readable();
723: &Debug(2, "Socket->Readable returned: $status");
1.1 foxr 724:
1.12 foxr 725: if($status != 0) {
1.4 foxr 726: # bad return from socket read. Currently this means that
727: # The socket has become disconnected. We fail the transaction.
728:
729: if(exists($ActiveTransactions{$Socket})) {
730: Debug(3,"Lond connection lost failing transaction");
731: FailTransaction($ActiveTransactions{$Socket});
732: }
733: $Watcher->cancel();
1.6 foxr 734: KillSocket($Socket);
1.4 foxr 735: return;
1.1 foxr 736: }
737: SocketDump(6,$Socket);
738:
739: $State = $Socket->GetState(); # Update in case of transition.
740: &Debug(6, "After read, state is ".$State);
741:
742: if($State eq "Initialized") {
743:
744:
745: } elsif ($State eq "ChallengeReceived") {
746: # The challenge must be echoed back; The state machine
747: # in the connection takes care of setting that up. Just
748: # need to transition to writable:
749:
1.8 foxr 750: $Watcher->cb(\&LondWritable);
1.1 foxr 751: $Watcher->poll("w");
752:
753: } elsif ($State eq "ChallengeReplied") {
754:
755:
756: } elsif ($State eq "RequestingKey") {
757: # The ok was received. Now we need to request the key
758: # That requires us to be writable:
759:
1.8 foxr 760: $Watcher->cb(\&LondWritable);
1.1 foxr 761: $Watcher->poll("w");
762:
763: } elsif ($State eq "ReceivingKey") {
764:
765: } elsif ($State eq "Idle") {
766: # If necessary, complete a transaction and then go into the
767: # idle queue.
1.8 foxr 768: $Watcher->cancel();
1.1 foxr 769: if(exists($ActiveTransactions{$Socket})) {
770: Debug(8,"Completing transaction!!");
771: CompleteTransaction($Socket,
772: $ActiveTransactions{$Socket});
1.9 foxr 773: } else {
774: Log("SUCCESS", "Connection ".$ConnectionCount." to "
775: .$RemoteHost." now ready for action");
1.1 foxr 776: }
777: ServerToIdle($Socket); # Next work unit or idle.
1.6 foxr 778:
1.1 foxr 779: } elsif ($State eq "SendingRequest") {
780: # We need to be writable for this and probably don't belong
781: # here inthe first place.
782:
783: Deubg(6, "SendingRequest state encountered in readable");
784: $Watcher->poll("w");
785: $Watcher->cb(\&LondWritable);
786:
787: } elsif ($State eq "ReceivingReply") {
788:
789:
790: } else {
791: # Invalid state.
792: Debug(4, "Invalid state in LondReadable");
793: }
794: }
1.3 albertel 795:
1.1 foxr 796: =pod
1.3 albertel 797:
1.1 foxr 798: =head2 LondWritable
1.3 albertel 799:
1.1 foxr 800: This function is called whenever a lond connection
801: becomes writable while there is a writeable monitoring
802: event. The action taken is very state dependent:
1.3 albertel 803:
1.1 foxr 804: =head3 State = Connected
1.3 albertel 805:
806: The connection is in the process of sending the 'init' hailing to the
807: lond on the remote end. The connection object''s Writable member is
808: called. On error, ConnectionError is called to destroy the connection
809: and remove it from the ActiveConnections hash
810:
1.1 foxr 811: =head3 Initialized
1.3 albertel 812:
813: 'init' has been sent, writability monitoring is removed and
814: readability monitoring is started with LondReadable as the callback.
815:
1.1 foxr 816: =head3 ChallengeReceived
1.3 albertel 817:
818: The connection has received the who are you challenge from the remote
819: system, and is in the process of sending the challenge
820: response. Writable is called.
821:
1.1 foxr 822: =head3 ChallengeReplied
1.3 albertel 823:
824: The connection has replied to the initial challenge The we switch to
825: monitoring readability looking for the server to reply with 'ok'.
826:
1.1 foxr 827: =head3 RequestingKey
1.3 albertel 828:
829: The connection is in the process of requesting its encryption key.
830: Writable is called.
831:
1.1 foxr 832: =head3 ReceivingKey
1.3 albertel 833:
834: The connection has sent the request for a key. Switch to readability
835: monitoring to accept the key
836:
1.1 foxr 837: =head3 SendingRequest
1.3 albertel 838:
839: The connection is in the process of sending a request to the server.
840: This request is part of a client transaction. All the states until
841: now represent the client setup protocol. Writable is called.
842:
1.1 foxr 843: =head3 ReceivingReply
844:
1.3 albertel 845: The connection has sent a request. Now it must receive a reply.
846: Readability monitoring is requested.
847:
848: This function is an event handler and therefore receives as
1.1 foxr 849: a parameter the event that has fired. The data for the watcher
850: of this event is a reference to a list of one or two elements,
851: depending on state. The first (and possibly only) element is the
852: socket. The second (present only if a request is in progress)
853: is the socket on which to return a reply to the caller.
854:
855: =cut
1.3 albertel 856:
1.1 foxr 857: sub LondWritable {
858: my $Event = shift;
859: my $Watcher = $Event->w;
1.8 foxr 860: my $Socket = $Watcher->data;
861: my $State = $Socket->GetState();
1.1 foxr 862:
1.8 foxr 863: Debug(6,"LondWritable State = ".$State."\n");
1.1 foxr 864:
1.8 foxr 865:
1.1 foxr 866: # Figure out what to do depending on the state of the socket:
867:
868:
869:
870:
871: SocketDump(6,$Socket);
872:
873: if ($State eq "Connected") {
874:
875: if ($Socket->Writable() != 0) {
876: # The write resulted in an error.
1.4 foxr 877: # We'll treat this as if the socket got disconnected:
1.9 foxr 878: Log("WARNING", "Connection to ".$RemoteHost.
879: " has been disconnected");
1.4 foxr 880: $Watcher->cancel();
1.6 foxr 881: KillSocket($Socket);
1.4 foxr 882: return;
1.1 foxr 883: }
1.4 foxr 884: # "init" is being sent...
885:
1.1 foxr 886:
887: } elsif ($State eq "Initialized") {
888:
889: # Now that init was sent, we switch
890: # to watching for readability:
891:
1.8 foxr 892: $Watcher->cb(\&LondReadable);
1.1 foxr 893: $Watcher->poll("r");
894:
895: } elsif ($State eq "ChallengeReceived") {
896: # We received the challenge, now we
897: # are echoing it back. This is a no-op,
898: # we're waiting for the state to change
899:
900: if($Socket->Writable() != 0) {
1.5 foxr 901:
902: $Watcher->cancel();
1.6 foxr 903: KillSocket($Socket);
1.5 foxr 904: return;
1.1 foxr 905: }
906:
907: } elsif ($State eq "ChallengeReplied") {
908: # The echo was sent back, so we switch
909: # to watching readability.
910:
1.8 foxr 911: $Watcher->cb(\&LondReadable);
1.1 foxr 912: $Watcher->poll("r");
913:
914: } elsif ($State eq "RequestingKey") {
915: # At this time we're requesting the key.
916: # again, this is essentially a no-op.
917: # we'll write the next chunk until the
918: # state changes.
919:
920: if($Socket->Writable() != 0) {
921: # Write resulted in an error.
1.5 foxr 922:
923: $Watcher->cancel();
1.6 foxr 924: KillSocket($Socket);
1.5 foxr 925: return;
926:
1.1 foxr 927: }
928: } elsif ($State eq "ReceivingKey") {
929: # Now we need to wait for the key
930: # to come back from the peer:
931:
1.8 foxr 932: $Watcher->cb(\&LondReadable);
1.1 foxr 933: $Watcher->poll("r");
934:
935: } elsif ($State eq "SendingRequest") {
936: # At this time we are sending a request to the
937: # peer... write the next chunk:
938:
939: if($Socket->Writable() != 0) {
940:
1.5 foxr 941: if(exists($ActiveTransactions{$Socket})) {
942: Debug(3, "Lond connection lost, failing transactions");
943: FailTransaction($ActiveTransactions{$Socket});
944: }
945: $Watcher->cancel();
1.6 foxr 946: KillSocket($Socket);
1.5 foxr 947: return;
948:
1.1 foxr 949: }
950:
951: } elsif ($State eq "ReceivingReply") {
952: # The send has completed. Wait for the
953: # data to come in for a reply.
954: Debug(8,"Writable sent request/receiving reply");
1.8 foxr 955: $Watcher->cb(\&LondReadable);
1.1 foxr 956: $Watcher->poll("r");
957:
958: } else {
959: # Control only passes here on an error:
960: # the socket state does not match any
961: # of the known states... so an error
962: # must be logged.
963:
964: &Debug(4, "Invalid socket state ".$State."\n");
965: }
966:
967: }
1.6 foxr 968: =pod
969:
970: =cut
971: sub QueueDelayed {
1.8 foxr 972: Debug(3,"QueueDelayed called");
973:
1.6 foxr 974: my $path = "$perlvar{'lonSockDir'}/delayed";
1.8 foxr 975:
976: Debug(4, "Delayed path: ".$path);
1.6 foxr 977: opendir(DIRHANDLE, $path);
1.8 foxr 978:
1.6 foxr 979: @alldelayed = grep /\.$RemoteHost$/, readdir DIRHANDLE;
1.8 foxr 980: Debug(4, "Got ".$alldelayed." delayed files");
1.6 foxr 981: closedir(DIRHANDLE);
982: my $dfname;
1.8 foxr 983: my $reqfile;
984: foreach $dfname (sort @alldelayed) {
985: $reqfile = "$path/$dfname";
986: Debug(4, "queueing ".$reqfile);
1.6 foxr 987: my $Handle = IO::File->new($reqfile);
988: my $cmd = <$Handle>;
1.8 foxr 989: chomp $cmd; # There may or may not be a newline...
1.12 foxr 990: $cmd = $cmd."\n"; # now for sure there's exactly one newline.
1.7 foxr 991: my $Transaction = LondTransaction->new($cmd);
992: $Transaction->SetDeferred($reqfile);
993: QueueTransaction($Transaction);
1.6 foxr 994: }
995:
996: }
1.1 foxr 997:
998: =pod
1.3 albertel 999:
1.1 foxr 1000: =head2 MakeLondConnection
1.3 albertel 1001:
1002: Create a new lond connection object, and start it towards its initial
1003: idleness. Once idle, it becomes elligible to receive transactions
1004: from the work queue. If the work queue is not empty when the
1005: connection is completed and becomes idle, it will dequeue an entry and
1006: start off on it.
1007:
1.1 foxr 1008: =cut
1.3 albertel 1009:
1.1 foxr 1010: sub MakeLondConnection {
1011: Debug(4,"MakeLondConnection to ".GetServerHost()." on port "
1012: .GetServerPort());
1013:
1014: my $Connection = LondConnection->new(&GetServerHost(),
1015: &GetServerPort());
1016:
1017: if($Connection == undef) { # Needs to be more robust later.
1.9 foxr 1018: Log("CRITICAL","Failed to make a connection with lond.");
1.10 foxr 1019: $ConnectionRetriesLeft--;
1020: return 0; # Failure.
1.5 foxr 1021: } else {
1.10 foxr 1022: $ConnectionRetriesLeft = $ConnectionRetries; # success resets the count
1.5 foxr 1023: # The connection needs to have writability
1024: # monitored in order to send the init sequence
1025: # that starts the whole authentication/key
1026: # exchange underway.
1027: #
1028: my $Socket = $Connection->GetSocket();
1029: if($Socket == undef) {
1030: die "did not get a socket from the connection";
1031: } else {
1032: &Debug(9,"MakeLondConnection got socket: ".$Socket);
1033: }
1.1 foxr 1034:
1.5 foxr 1035:
1036: $event = Event->io(fd => $Socket,
1037: poll => 'w',
1038: cb => \&LondWritable,
1.8 foxr 1039: data => $Connection,
1.5 foxr 1040: desc => 'Connection to lond server');
1041: $ActiveConnections{$Connection} = $event;
1042:
1043: $ConnectionCount++;
1.8 foxr 1044: Debug(4, "Connection count = ".$ConnectionCount);
1.6 foxr 1045: if($ConnectionCount == 1) { # First Connection:
1046: QueueDelayed;
1047: }
1.9 foxr 1048: Log("SUCESS", "Created connection ".$ConnectionCount
1049: ." to host ".GetServerHost());
1.10 foxr 1050: return 1; # Return success.
1.1 foxr 1051: }
1052:
1053: }
1.3 albertel 1054:
1.1 foxr 1055: =pod
1.3 albertel 1056:
1.1 foxr 1057: =head2 StartRequest
1.3 albertel 1058:
1059: Starts a lond request going on a specified lond connection.
1060: parameters are:
1061:
1062: =item $Lond
1063:
1064: Connection to the lond that will send the transaction and receive the
1065: reply.
1066:
1067: =item $Client
1068:
1069: Connection to the client that is making this request We got the
1070: request from this socket, and when the request has been relayed to
1071: lond and we get a reply back from lond it will get sent to this
1072: socket.
1073:
1074: =item $Request
1075:
1076: The text of the request to send.
1077:
1.1 foxr 1078: =cut
1079:
1080: sub StartRequest {
1081: my $Lond = shift;
1.7 foxr 1082: my $Request = shift; # This is a LondTransaction.
1.1 foxr 1083:
1.7 foxr 1084: Debug(6, "StartRequest: ".$Request->getRequest());
1.1 foxr 1085:
1086: my $Socket = $Lond->GetSocket();
1087:
1.7 foxr 1088: $Request->Activate($Lond);
1089: $ActiveTransactions{$Lond} = $Request;
1.1 foxr 1090:
1.7 foxr 1091: $Lond->InitiateTransaction($Request->getRequest());
1.8 foxr 1092: $event = Event->io(fd => $Socket,
1.1 foxr 1093: poll => "w",
1094: cb => \&LondWritable,
1095: data => $Lond,
1096: desc => "lond transaction connection");
1097: $ActiveConnections{$Lond} = $event;
1098: Debug(8," Start Request made watcher data with ".$event->data."\n");
1099: }
1100:
1101: =pod
1.3 albertel 1102:
1.1 foxr 1103: =head2 QueueTransaction
1.3 albertel 1104:
1105: If there is an idle lond connection, it is put to work doing this
1106: transaction. Otherwise, the transaction is placed in the work queue.
1107: If placed in the work queue and the maximum number of connections has
1108: not yet been created, a new connection will be started. Our goal is
1109: to eventually have a sufficient number of connections that the work
1110: queue will typically be empty. parameters are:
1111:
1112: =item Socket
1113:
1114: open on the lonc client.
1115:
1116: =item Request
1117:
1118: data to send to the lond.
1.1 foxr 1119:
1120: =cut
1.3 albertel 1121:
1.1 foxr 1122: sub QueueTransaction {
1123:
1.7 foxr 1124: my $requestData = shift; # This is a LondTransaction.
1125: my $cmd = $requestData->getRequest();
1126:
1127: Debug(6,"QueueTransaction: ".$cmd);
1.1 foxr 1128:
1129: my $LondSocket = $IdleConnections->pop();
1130: if(!defined $LondSocket) { # Need to queue request.
1131: Debug(8,"Must queue...");
1132: $WorkQueue->enqueue($requestData);
1133: if($ConnectionCount < $MaxConnectionCount) {
1134: Debug(4,"Starting additional lond connection");
1135: MakeLondConnection();
1136: }
1137: } else { # Can start the request:
1138: Debug(8,"Can start...");
1.7 foxr 1139: StartRequest($LondSocket, $requestData);
1.1 foxr 1140: }
1141: }
1142:
1143: #-------------------------- Lonc UNIX socket handling ---------------------
1.3 albertel 1144:
1.1 foxr 1145: =pod
1.3 albertel 1146:
1.1 foxr 1147: =head2 ClientRequest
1.3 albertel 1148: Callback that is called when data can be read from the UNIX domain
1149: socket connecting us with an apache server process.
1.1 foxr 1150:
1151: =cut
1152:
1153: sub ClientRequest {
1154: Debug(6, "ClientRequest");
1155: my $event = shift;
1156: my $watcher = $event->w;
1157: my $socket = $watcher->fd;
1158: my $data = $watcher->data;
1159: my $thisread;
1160:
1161: Debug(9, " Watcher named: ".$watcher->desc);
1162:
1163: my $rv = $socket->recv($thisread, POSIX::BUFSIZ, 0);
1164: Debug(8, "rcv: data length = ".length($thisread)
1165: ." read =".$thisread);
1166: unless (defined $rv && length($thisread)) {
1167: # Likely eof on socket.
1168: Debug(5,"Client Socket closed on lonc for ".$RemoteHost);
1169: close($socket);
1170: $watcher->cancel();
1171: delete($ActiveClients{$socket});
1.10 foxr 1172: return;
1.1 foxr 1173: }
1174: Debug(8,"Data: ".$data." this read: ".$thisread);
1175: $data = $data.$thisread; # Append new data.
1176: $watcher->data($data);
1177: if($data =~ /(.*\n)/) { # Request entirely read.
1.10 foxr 1178: if($data eq "close_connection_exit\n") {
1.9 foxr 1179: Log("CRITICAL",
1180: "Request Close Connection ... exiting");
1181: CloseAllLondConnections();
1182: exit;
1183: }
1.1 foxr 1184: Debug(8, "Complete transaction received: ".$data);
1.8 foxr 1185: my $Transaction = LondTransaction->new($data);
1.7 foxr 1186: $Transaction->SetClient($socket);
1187: QueueTransaction($Transaction);
1.1 foxr 1188: $watcher->cancel(); # Done looking for input data.
1189: }
1190:
1191: }
1192:
1193:
1194: =pod
1.3 albertel 1195:
1.1 foxr 1196: =head2 NewClient
1.3 albertel 1197:
1198: Callback that is called when a connection is received on the unix
1199: socket for a new client of lonc. The callback is parameterized by the
1200: event.. which is a-priori assumed to be an io event, and therefore has
1201: an fd member that is the Listener socket. We Accept the connection
1202: and register a new event on the readability of that socket:
1203:
1.1 foxr 1204: =cut
1.3 albertel 1205:
1.1 foxr 1206: sub NewClient {
1207: Debug(6, "NewClient");
1208: my $event = shift; # Get the event parameters.
1209: my $watcher = $event->w;
1210: my $socket = $watcher->fd; # Get the event' socket.
1211: my $connection = $socket->accept(); # Accept the client connection.
1212: Debug(8,"Connection request accepted from "
1213: .GetPeername($connection, AF_UNIX));
1214:
1215:
1216: my $description = sprintf("Connection to lonc client %d",
1217: $ClientConnection);
1218: Debug(9, "Creating event named: ".$description);
1219: Event->io(cb => \&ClientRequest,
1220: poll => 'r',
1221: desc => $description,
1222: data => "",
1223: fd => $connection);
1224: $ActiveClients{$connection} = $ClientConnection;
1225: $ClientConnection++;
1226: }
1.3 albertel 1227:
1228: =pod
1229:
1230: =head2 GetLoncSocketPath
1231:
1232: Returns the name of the UNIX socket on which to listen for client
1233: connections.
1.1 foxr 1234:
1235: =cut
1.3 albertel 1236:
1.1 foxr 1237: sub GetLoncSocketPath {
1238: return $UnixSocketDir."/".GetServerHost();
1239: }
1240:
1.3 albertel 1241: =pod
1242:
1243: =head2 GetServerHost
1244:
1245: Returns the host whose lond we talk with.
1246:
1.1 foxr 1247: =cut
1.3 albertel 1248:
1.7 foxr 1249: sub GetServerHost {
1.1 foxr 1250: return $RemoteHost; # Setup by the fork.
1251: }
1.3 albertel 1252:
1253: =pod
1254:
1255: =head2 GetServerPort
1256:
1257: Returns the lond port number.
1258:
1.1 foxr 1259: =cut
1.3 albertel 1260:
1.7 foxr 1261: sub GetServerPort {
1.1 foxr 1262: return $perlvar{londPort};
1263: }
1.3 albertel 1264:
1265: =pod
1266:
1267: =head2 SetupLoncListener
1268:
1269: Setup a lonc listener event. The event is called when the socket
1270: becomes readable.. that corresponds to the receipt of a new
1271: connection. The event handler established will accept the connection
1272: (creating a communcations channel), that int turn will establish
1273: another event handler to subess requests.
1.1 foxr 1274:
1275: =cut
1.3 albertel 1276:
1.1 foxr 1277: sub SetupLoncListener {
1278:
1279: my $socket;
1280: my $SocketName = GetLoncSocketPath();
1281: unlink($SocketName);
1.7 foxr 1282: unless ($socket =IO::Socket::UNIX->new(Local => $SocketName,
1.1 foxr 1283: Listen => 10,
1284: Type => SOCK_STREAM)) {
1285: die "Failed to create a lonc listner socket";
1286: }
1287: Event->io(cb => \&NewClient,
1288: poll => 'r',
1289: desc => 'Lonc listener Unix Socket',
1290: fd => $socket);
1291: }
1292:
1.14 ! foxr 1293: =pod
! 1294:
! 1295: =head2 ChildStatus
! 1296:
! 1297: Child USR1 signal handler to report the most recent status
! 1298: into the status file.
! 1299:
! 1300: =cut
! 1301: sub ChildStatus {
! 1302: my $event = shift;
! 1303: my $watcher = $event->w;
! 1304:
! 1305: Debug(2, "Reporting child status because : ".$watcher->data);
! 1306: my $docdir = $perlvar{'lonDocRoot'};
! 1307: my $fh = IO::File->new(">>$docdir/lon-status/loncstatus.txt");
! 1308: print $fh $$."\t".$RemoteHost."\t".$Status."\t".
! 1309: $RecentLogEntry."\n";
! 1310: }
! 1311:
1.1 foxr 1312: =pod
1.3 albertel 1313:
1.10 foxr 1314: =head2 SignalledToDeath
1315:
1316: Called in response to a signal that causes a chid process to die.
1317:
1318: =cut
1319:
1320:
1321: sub SignalledToDeath {
1.14 ! foxr 1322: my $event = shift;
! 1323: my $watcher= $event->w;
! 1324:
! 1325: Debug(2,"Signalled to death! via ".$watcher->data);
1.10 foxr 1326: my ($signal) = @_;
1327: chomp($signal);
1328: Log("CRITICAL", "Abnormal exit. Child $$ for $RemoteHost "
1329: ."died through "."\"$signal\"");
1330: LogPerm("F:lonc: $$ on $RemoteHost signalled to death: "
1331: ."\"$signal\"");
1332: die("Signal abnormal end");
1.12 foxr 1333: exit 0;
1.10 foxr 1334:
1335: }
1.1 foxr 1336: =head2 ChildProcess
1337:
1338: This sub implements a child process for a single lonc daemon.
1339:
1340: =cut
1341:
1342: sub ChildProcess {
1343:
1344:
1.14 ! foxr 1345: #
! 1346: # Signals must be handled by the Event framework...
! 1347: #
! 1348: # $SIG{QUIT} = \&SignalledToDeath;
! 1349: # $SIG{HUP} = \&ChildStatus;
! 1350: # $SIG{USR1} = IGNORE;
! 1351: # $SIG{INT} = DEFAULT;
! 1352: # $SIG{CHLD} = IGNORE;
! 1353: # $SIG{__DIE__} = \&SignalledToDeath;
! 1354:
! 1355: Event->signal(signal => "QUIT",
! 1356: cb => \&SignalledToDeath,
! 1357: data => "QUIT");
! 1358: Event->signal(signal => "HUP",
! 1359: cb => \&ChildStatus,
! 1360: data => "HUP");
! 1361: Event->signal(signal => "USR1",
! 1362: cb => \&ChildStatus,
! 1363: data => "USR1");
1.1 foxr 1364:
1365: SetupTimer();
1366:
1367: SetupLoncListener();
1368:
1369: $Event::Debuglevel = $DebugLevel;
1370:
1371: Debug(9, "Making initial lond connection for ".$RemoteHost);
1372:
1373: # Setup the initial server connection:
1374:
1.14 ! foxr 1375: # &MakeLondConnection(); // let first work requirest do it.
1.10 foxr 1376:
1.5 foxr 1377:
1.1 foxr 1378: Debug(9,"Entering event loop");
1379: my $ret = Event::loop(); # Start the main event loop.
1380:
1381:
1382: die "Main event loop exited!!!";
1383: }
1384:
1385: # Create a new child for host passed in:
1386:
1387: sub CreateChild {
1.12 foxr 1388: my $sigset = POSIX::SigSet->new(SIGINT);
1389: sigprocmask(SIG_BLOCK, $sigset);
1.1 foxr 1390: my $host = shift;
1391: $RemoteHost = $host;
1.9 foxr 1392: Log("CRITICAL", "Forking server for ".$host);
1.1 foxr 1393: $pid = fork;
1394: if($pid) { # Parent
1395: $ChildHash{$pid} = $RemoteHost;
1.12 foxr 1396: sigprocmask(SIG_UNBLOCK, $sigset);
1397:
1.1 foxr 1398: } else { # child.
1.5 foxr 1399: ShowStatus("Connected to ".$RemoteHost);
1.12 foxr 1400: $SIG{INT} = DEFAULT;
1401: sigprocmask(SIG_UNBLOCK, $sigset);
1402: ChildProcess; # Does not return.
1.1 foxr 1403: }
1404:
1405: }
1406: #
1407: # Parent process logic pass 1:
1408: # For each entry in the hosts table, we will
1409: # fork off an instance of ChildProcess to service the transactions
1410: # to that host. Each pid will be entered in a global hash
1411: # with the value of the key, the host.
1412: # The parent will then enter a loop to wait for process exits.
1413: # Each exit gets logged and the child gets restarted.
1414: #
1415:
1.5 foxr 1416: #
1417: # Fork and start in new session so hang-up isn't going to
1418: # happen without intent.
1419: #
1420:
1421:
1.6 foxr 1422:
1423:
1.8 foxr 1424:
1.6 foxr 1425:
1426: ShowStatus("Forming new session");
1427: my $childpid = fork;
1428: if ($childpid != 0) {
1429: sleep 4; # Give child a chacne to break to
1430: exit 0; # a new sesion.
1431: }
1.8 foxr 1432: #
1433: # Write my pid into the pid file so I can be located
1434: #
1435:
1436: ShowStatus("Parent writing pid file:");
1437: $execdir = $perlvar{'lonDaemons'};
1438: open (PIDSAVE, ">$execdir/logs/lonc.pid");
1439: print PIDSAVE "$$\n";
1440: close(PIDSAVE);
1.6 foxr 1441:
1442: if (POSIX::setsid() < 0) {
1443: print "Could not create new session\n";
1444: exit -1;
1445: }
1.5 foxr 1446:
1447: ShowStatus("Forking node servers");
1448:
1.9 foxr 1449: Log("CRITICAL", "--------------- Starting children ---------------");
1450:
1.1 foxr 1451: my $HostIterator = LondConnection::GetHostIterator;
1452: while (! $HostIterator->end()) {
1453:
1454: $hostentryref = $HostIterator->get();
1455: CreateChild($hostentryref->[0]);
1456: $HostIterator->next();
1457: }
1.12 foxr 1458: $RemoteHost = "Parent Server";
1.1 foxr 1459:
1460: # Maintain the population:
1.5 foxr 1461:
1462: ShowStatus("Parent keeping the flock");
1.1 foxr 1463:
1.10 foxr 1464: #
1465: # Set up parent signals:
1466: #
1.12 foxr 1467:
1.14 ! foxr 1468: $SIG{INT} = \&Terminate;
! 1469: $SIG{TERM} = \&Terminate;
1.13 foxr 1470: $SIG{HUP} = \&Restart;
1.14 ! foxr 1471: $SIG{USR1} = \&CheckKids;
1.10 foxr 1472:
1.1 foxr 1473: while(1) {
1474: $deadchild = wait();
1475: if(exists $ChildHash{$deadchild}) { # need to restart.
1476: $deadhost = $ChildHash{$deadchild};
1477: delete($ChildHash{$deadchild});
1.9 foxr 1478: Log("WARNING","Lost child pid= ".$deadchild.
1.1 foxr 1479: "Connected to host ".$deadhost);
1.9 foxr 1480: Log("INFO", "Restarting child procesing ".$deadhost);
1.1 foxr 1481: CreateChild($deadhost);
1482: }
1.13 foxr 1483: }
1484:
1.14 ! foxr 1485:
! 1486:
! 1487: =pod
! 1488:
! 1489: =head1 CheckKids
! 1490:
! 1491: Since kids do not die as easily in this implementation
! 1492: as the previous one, there is no need to restart the
! 1493: dead ones (all dead kids get restarted when they die!!)
! 1494: The only thing this function does is to pass USR1 to the
! 1495: kids so that they report their status.
! 1496:
! 1497: =cut
! 1498:
! 1499: sub CheckKids {
! 1500: Debug(2, "Checking status of children");
! 1501: my $docdir = $perlvar{'lonDocRoot'};
! 1502: my $fh = IO::File->new(">$docdir/lon-status/loncstatus.txt");
! 1503: my $now=time;
! 1504: my $local=localtime($now);
! 1505: print $fh "LONC status $local - parent $$ \n\n";
! 1506: foreach $pid (keys %ChildHash) {
! 1507: Debug(2, "Sending USR1 -> $pid");
! 1508: kill 'USR1' => $pid; # Tell Child to report status.
! 1509: sleep 1; # Wait so file doesn't intermix.
! 1510: }
! 1511: }
! 1512:
1.13 foxr 1513: =pod
1514:
1515: =head1 Restart
1516:
1517: Signal handler for HUP... all children are killed and
1518: we self restart. This is an el-cheapo way to re read
1519: the config file.
1520:
1521: =cut
1522:
1523: sub Restart {
1524: KillThemAll; # First kill all the children.
1525: Log("CRITICAL", "Restarting");
1526: my $execdir = $perlvar{'lonDaemons'};
1527: unlink("$execdir/logs/lonc.pid");
1528: exec("$execdir/lonc");
1.10 foxr 1529: }
1.12 foxr 1530:
1531: =pod
1532:
1533: =head1 KillThemAll
1534:
1535: Signal handler that kills all children by sending them a
1536: SIGINT. Responds to sigint and sigterm.
1537:
1538: =cut
1539:
1.10 foxr 1540: sub KillThemAll {
1.12 foxr 1541: Debug(2, "Kill them all!!");
1542: local($SIG{CHLD}) = 'IGNORE'; # Our children >will< die.
1543: foreach $pid (keys %ChildHash) {
1544: my $serving = $ChildHash{$pid};
1545: Debug(2, "Killing lonc for $serving pid = $pid");
1546: ShowStatus("Killing lonc for $serving pid = $pid");
1547: Log("CRITICAL", "Killing lonc for $serving pid = $pid");
1548: kill('INT', $pid);
1.14 ! foxr 1549: delete($ChildeHash{$pid});
1.12 foxr 1550: }
1.14 ! foxr 1551: my $execdir = $perlvar{'lonDaemons'};
! 1552: unlink("$execdir/logs/lonc.pid");
! 1553: ShowStatus("Killing the master process");
1.12 foxr 1554: Log("CRITICAL", "Killing the master process.");
1.1 foxr 1555: }
1.12 foxr 1556:
1.14 ! foxr 1557: =pod
! 1558:
! 1559: =head1 Terminate
! 1560:
! 1561: Terminate the system.
! 1562:
! 1563: =cut
! 1564:
! 1565: sub Terminate {
! 1566: KillThemAll;
! 1567: exit;
! 1568:
! 1569: }
1.12 foxr 1570: =pod
1.1 foxr 1571:
1572: =head1 Theory
1.3 albertel 1573:
1574: The event class is used to build this as a single process with an
1575: event driven model. The following events are handled:
1.1 foxr 1576:
1577: =item UNIX Socket connection Received
1578:
1579: =item Request data arrives on UNIX data transfer socket.
1580:
1581: =item lond connection becomes writable.
1582:
1583: =item timer fires at 1 second intervals.
1584:
1585: All sockets are run in non-blocking mode. Timeouts managed by the timer
1586: handler prevents hung connections.
1587:
1588: Key data structures:
1589:
1.3 albertel 1590: =item RequestQueue
1591:
1592: A queue of requests received from UNIX sockets that are
1593: waiting for a chance to be forwarded on a lond connection socket.
1594:
1595: =item ActiveConnections
1596:
1597: A hash of lond connections that have transactions in process that are
1598: available to be timed out.
1599:
1600: =item ActiveTransactions
1601:
1602: A hash indexed by lond connections that contain the client reply
1603: socket for each connection that has an active transaction on it.
1604:
1605: =item IdleConnections
1606:
1607: A hash of lond connections that have no work to do. These connections
1608: can be closed if they are idle for a long enough time.
1.1 foxr 1609:
1610: =cut
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>