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