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