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