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