File:  [LON-CAPA] / loncom / loncnew
Revision 1.23: download - view: text, annotated - select for diffs
Mon Sep 15 09:24:49 2003 UTC (20 years, 8 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Add use strict and fix all the fallout from that.

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

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>