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