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