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