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