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