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