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