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