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