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