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