File:  [LON-CAPA] / loncom / loncnew
Revision 1.65: download - view: text, annotated - select for diffs
Tue Oct 5 11:16:57 2004 UTC (19 years, 6 months ago) by foxr
Branches: MAIN
CVS tags: version_1_3_1, version_1_3_0, version_1_2_99_1, version_1_2_99_0, HEAD
Full signal handling in loncnew.  I believe this now works so I have set
DieWhenIdle to true.   If there are problems in an emergency, set DieWhenIdle
to 0 and old style behavior (no process trimming) will occur.

    1: #!/usr/bin/perl
    2: # The LearningOnline Network with CAPA
    3: # lonc maintains the connections to remote computers
    4: #
    5: # $Id: loncnew,v 1.65 2004/10/05 11:16:57 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.                    (done)
   39: #    - Add Signal handling - HUP restarts. USR1 status report. (done)
   40: #    - Add Configuration file I/O                       (done).
   41: #    - Add management/status request interface.         (done)
   42: #    - Add deferred request capability.                  (done)
   43: #    - Detect transmission timeouts.                     (done)
   44: #
   45: 
   46: use strict;
   47: use lib "/home/httpd/lib/perl/";
   48: use Event qw(:DEFAULT );
   49: use POSIX qw(:signal_h);
   50: use POSIX;
   51: use IO::Socket;
   52: use IO::Socket::INET;
   53: use IO::Socket::UNIX;
   54: use IO::File;
   55: use IO::Handle;
   56: use Socket;
   57: use Crypt::IDEA;
   58: use LONCAPA::Queue;
   59: use LONCAPA::Stack;
   60: use LONCAPA::LondConnection;
   61: use LONCAPA::LondTransaction;
   62: use LONCAPA::Configuration;
   63: use LONCAPA::HashIterator;
   64: 
   65: 
   66: # Read the httpd configuration file to get perl variables
   67: # normally set in apache modules:
   68: 
   69: my $perlvarref = LONCAPA::Configuration::read_conf('loncapa.conf');
   70: my %perlvar    = %{$perlvarref};
   71: 
   72: #
   73: #  parent and shared variables.
   74: 
   75: my %ChildHash;			# by pid -> host.
   76: my %HostToPid;			# By host -> pid.
   77: my %HostHash;			# by loncapaname -> IP.
   78: my %listening_to;		# Socket->host table for who the parent
   79:                                 # is listening to.
   80: my %parent_dispatchers;         # host-> listener watcher events. 
   81: 
   82: my %parent_handlers;		# Parent signal handlers...
   83: 
   84: my $MaxConnectionCount = 10;	# Will get from config later.
   85: my $ClientConnection = 0;	# Uniquifier for client events.
   86: 
   87: my $DebugLevel = 0;
   88: my $NextDebugLevel= 2;		# So Sigint can toggle this.
   89: my $IdleTimeout= 600;		# Wait 10 minutes before pruning connections.
   90: 
   91: my $LogTransactions = 0;	# When True, all transactions/replies get logged.
   92: my $executable      = $0;	# Get the full path to me.
   93: 
   94: #
   95: #  The variables below are only used by the child processes.
   96: #
   97: my $RemoteHost;			# Name of host child is talking to.
   98: my $UnixSocketDir= $perlvar{'lonSockDir'};
   99: my $IdleConnections = Stack->new(); # Set of idle connections
  100: my %ActiveConnections;		# Connections to the remote lond.
  101: my %ActiveTransactions;		# LondTransactions in flight.
  102: my %ActiveClients;		# Serial numbers of active clients by socket.
  103: my $WorkQueue       = Queue->new(); # Queue of pending transactions.
  104: my $ConnectionCount = 0;
  105: my $IdleSeconds     = 0;	# Number of seconds idle.
  106: my $Status          = "";	# Current status string.
  107: my $RecentLogEntry  = "";
  108: my $ConnectionRetries=2;	# Number of connection retries allowed.
  109: my $ConnectionRetriesLeft=2;	# Number of connection retries remaining.
  110: my $LondVersion     = "unknown"; # Version of lond we talk with.
  111: my $KeyMode         = "";       # e.g. ssl, local, insecure from last connect.
  112: my $LondConnecting  = 0;       # True when a connection is being built.
  113: 
  114: 
  115: 
  116: my $DieWhenIdle     = 1;	# When true children die when trimmed -> 0.
  117: my $I_am_child      = 0;	# True if this is the child process.
  118: 
  119: #
  120: #   The hash below gives the HTML format for log messages
  121: #   given a severity.
  122: #    
  123: my %LogFormats;
  124: 
  125: $LogFormats{"CRITICAL"} = "<font color='red'>CRITICAL: %s</font>";
  126: $LogFormats{"SUCCESS"}  = "<font color='green'>SUCCESS: %s</font>";
  127: $LogFormats{"INFO"}     = "<font color='yellow'>INFO: %s</font>";
  128: $LogFormats{"WARNING"}  = "<font color='blue'>WARNING: %s</font>";
  129: $LogFormats{"DEFAULT"}  = " %s ";
  130: 
  131: 
  132: #  UpdateStatus;
  133: #    Update the idle status display to show how many connections
  134: #    are left, retries and other stuff.
  135: #
  136: sub UpdateStatus {
  137:     if ($ConnectionRetriesLeft > 0) {
  138: 	ShowStatus(GetServerHost()." Connection count: ".$ConnectionCount
  139: 		   ." Retries remaining: ".$ConnectionRetriesLeft
  140: 		   ." ($KeyMode)");
  141:     } else {
  142: 	ShowStatus(GetServerHost()." >> DEAD <<");
  143:     }
  144: }
  145: 
  146: 
  147: =pod
  148: 
  149: =head2 LogPerm
  150: 
  151: Makes an entry into the permanent log file.
  152: 
  153: =cut
  154: sub LogPerm {
  155:     my $message=shift;
  156:     my $execdir=$perlvar{'lonDaemons'};
  157:     my $now=time;
  158:     my $local=localtime($now);
  159:     my $fh=IO::File->new(">>$execdir/logs/lonnet.perm.log");
  160:     print $fh "$now:$message:$local\n";
  161: }
  162: 
  163: =pod
  164: 
  165: =head2 Log
  166: 
  167: Logs a message to the log file.
  168: Parameters:
  169: 
  170: =item severity
  171: 
  172: One of CRITICAL, WARNING, INFO, SUCCESS used to select the
  173: format string used to format the message.  if the severity is
  174: not a defined severity the Default format string is used.
  175: 
  176: =item message
  177: 
  178: The base message.  In addtion to the format string, the message
  179: will be appended to a string containing the name of our remote
  180: host and the time will be formatted into the message.
  181: 
  182: =cut
  183: 
  184: sub Log {
  185: 
  186:     my ($severity, $message) = @_;
  187: 
  188:     if(!$LogFormats{$severity}) {
  189: 	$severity = "DEFAULT";
  190:     }
  191: 
  192:     my $format = $LogFormats{$severity};
  193:     
  194:     #  Put the window dressing in in front of the message format:
  195: 
  196:     my $now   = time;
  197:     my $local = localtime($now);
  198:     my $finalformat = "$local ($$) [$RemoteHost] [$Status] ";
  199:     my $finalformat = $finalformat.$format."\n";
  200: 
  201:     # open the file and put the result.
  202: 
  203:     my $execdir = $perlvar{'lonDaemons'};
  204:     my $fh      = IO::File->new(">>$execdir/logs/lonc.log");
  205:     my $msg = sprintf($finalformat, $message);
  206:     $RecentLogEntry = $msg;
  207:     print $fh $msg;
  208:     
  209:     
  210: }
  211: 
  212: 
  213: =pod
  214: 
  215: =head2 GetPeerName
  216: 
  217: Returns the name of the host that a socket object is connected to.
  218: 
  219: =cut
  220: 
  221: sub GetPeername {
  222: 
  223: 
  224:     my ($connection, $AdrFamily) = @_;
  225: 
  226:     my $peer       = $connection->peername();
  227:     my $peerport;
  228:     my $peerip;
  229:     if($AdrFamily == AF_INET) {
  230: 	($peerport, $peerip) = sockaddr_in($peer);
  231: 	my $peername    = gethostbyaddr($peerip, $AdrFamily);
  232: 	return $peername;
  233:     } elsif ($AdrFamily == AF_UNIX) {
  234: 	my $peerfile;
  235: 	($peerfile) = sockaddr_un($peer);
  236: 	return $peerfile;
  237:     }
  238: }
  239: =pod
  240: 
  241: =head2 Debug
  242: 
  243: Invoked to issue a debug message.
  244: 
  245: =cut
  246: 
  247: sub Debug {
  248: 
  249:     my ($level, $message) = @_;
  250: 
  251:     if ($level <= $DebugLevel) {
  252: 	Log("INFO", "-Debug- $message host = $RemoteHost");
  253:     }
  254: }
  255: 
  256: sub SocketDump {
  257: 
  258:     my ($level, $socket) = @_;
  259: 
  260:     if($level <= $DebugLevel) {
  261: 	$socket->Dump(-1);	# Ensure it will get dumped.
  262:     }
  263: }
  264: 
  265: =pod
  266: 
  267: =head2 ShowStatus
  268: 
  269:  Place some text as our pid status.
  270:  and as what we return in a SIGUSR1
  271: 
  272: =cut
  273: sub ShowStatus {
  274:     my $state = shift;
  275:     my $now = time;
  276:     my $local = localtime($now);
  277:     $Status   = $local.": ".$state;
  278:     $0='lonc: '.$state.' '.$local;
  279: }
  280: 
  281: =pod
  282: 
  283: =head 2 SocketTimeout
  284: 
  285:     Called when an action on the socket times out.  The socket is 
  286:    destroyed and any active transaction is failed.
  287: 
  288: 
  289: =cut
  290: sub SocketTimeout {
  291:     my $Socket = shift;
  292:     Log("WARNING", "A socket timeout was detected");
  293:     Debug(5, " SocketTimeout called: ");
  294:     $Socket->Dump(0);
  295:     if(exists($ActiveTransactions{$Socket})) {
  296: 	FailTransaction($ActiveTransactions{$Socket});
  297:     }
  298:     KillSocket($Socket);	# A transaction timeout also counts as
  299:                                 # a connection failure:
  300:     $ConnectionRetriesLeft--;
  301:     if($ConnectionRetriesLeft <= 0) {
  302: 	Log("CRITICAL", "Host marked DEAD: ".GetServerHost());
  303: 	$LondConnecting = 0;
  304:     }
  305: 
  306: }
  307: #
  308: #   This function should be called by the child in all cases where it must
  309: #   exit.  If the child process is running with the DieWhenIdle turned on
  310: #   it must create a lock file for the AF_UNIX socket in order to prevent
  311: #   connection requests from lonnet in the time between process exit
  312: #   and the parent picking up the listen again.
  313: # Parameters:
  314: #     exit_code           - Exit status value, however see the next parameter.
  315: #     message             - If this optional parameter is supplied, the exit
  316: #                           is via a die with this message.
  317: #
  318: sub child_exit {
  319:     my ($exit_code, $message) = @_;
  320: 
  321:     # Regardless of how we exit, we may need to do the lock thing:
  322: 
  323:     if($DieWhenIdle) {
  324: 	#
  325: 	#  Create a lock file since there will be a time window
  326: 	#  between our exit and the parent's picking up the listen
  327: 	#  during which no listens will be done on the
  328: 	#  lonnet client socket.
  329: 	#
  330: 	my $lock_file = GetLoncSocketPath().".lock";
  331: 	open(LOCK,">$lock_file");
  332: 	print LOCK "Contents not important";
  333: 	close(LOCK);
  334: 	
  335: 	exit(0);
  336:     }
  337:     #  Now figure out how we exit:
  338: 
  339:     if($message) {
  340: 	die $message;
  341:     } else {
  342: 	exit($exit_code);
  343:     }
  344: }
  345: #----------------------------- Timer management ------------------------
  346: 
  347: =pod
  348: 
  349: =head2 Tick
  350: 
  351: Invoked  each timer tick.
  352: 
  353: =cut
  354: 
  355: 
  356: sub Tick {
  357:     my ($Event)       = @_;
  358:     my $clock_watcher = $Event->w;
  359: 
  360:     my $client;
  361:     UpdateStatus();
  362: 
  363:     # Is it time to prune connection count:
  364: 
  365: 
  366:     if($IdleConnections->Count()  && 
  367:        ($WorkQueue->Count() == 0)) { # Idle connections and nothing to do?
  368: 	$IdleSeconds++;
  369: 	if($IdleSeconds > $IdleTimeout) { # Prune a connection...
  370: 	    my $Socket = $IdleConnections->pop();
  371: 	    KillSocket($Socket);
  372: 	    $IdleSeconds = 0;	# Otherwise all connections get trimmed to fast.
  373: 	    UpdateStatus();
  374: 	    if(($ConnectionCount == 0) && $DieWhenIdle) {
  375: 		&child_exit(0);
  376: 
  377: 	    }
  378: 	}
  379:     } else {
  380: 	$IdleSeconds = 0;	# Reset idle count if not idle.
  381:     }
  382:     #
  383:     #  For each inflight transaction, tick down its timeout counter.
  384:     #
  385: 
  386:     foreach my $item (keys %ActiveConnections) {
  387: 	my $State = $ActiveConnections{$item}->data->GetState();
  388: 	if ($State ne 'Idle') {
  389: 	    Debug(5,"Ticking Socket $State $item");
  390: 	    $ActiveConnections{$item}->data->Tick();
  391: 	}
  392:     }
  393:     # Do we have work in the queue, but no connections to service them?
  394:     # If so, try to make some new connections to get things going again.
  395:     #
  396:     #   Note this code is dead now...
  397:     #
  398:     my $Requests = $WorkQueue->Count();
  399:     if (($ConnectionCount == 0)  && ($Requests > 0) && (!$LondConnecting)) { 
  400: 	if ($ConnectionRetriesLeft > 0) {
  401: 	    Debug(5,"Work but no connections, Make a new one");
  402: 	    my $success;
  403: 	    $success    = &MakeLondConnection;
  404: 	    if($success == 0) { # All connections failed:
  405: 		Debug(5,"Work in queue failed to make any connectiouns\n");
  406: 		EmptyQueue();	# Fail pending transactions with con_lost.
  407: 		CloseAllLondConnections(); # Should all be closed but....
  408: 	    }
  409: 	} else {
  410: 	    $LondConnecting = 0;
  411: 	    ShowStatus(GetServerHost()." >>> DEAD!!! <<<");
  412: 	    Debug(5,"Work in queue, but gave up on connections..flushing\n");
  413: 	    EmptyQueue();	# Connections can't be established.
  414: 	    CloseAllLondConnections(); # Should all already be closed but...
  415: 	}
  416:        
  417:     }
  418:     if ($ConnectionCount == 0) {
  419: 	$KeyMode = ""; 
  420: 	$clock_watcher->cancel();
  421:     }
  422: }
  423: 
  424: =pod
  425: 
  426: =head2 SetupTimer
  427: 
  428: Sets up a 1 per sec recurring timer event.  The event handler is used to:
  429: 
  430: =item
  431: 
  432: Trigger timeouts on communications along active sockets.
  433: 
  434: =item
  435: 
  436: Trigger disconnections of idle sockets.
  437: 
  438: =cut
  439: 
  440: sub SetupTimer {
  441:     Debug(6, "SetupTimer");
  442:     Event->timer(interval => 1, cb => \&Tick );
  443: }
  444: 
  445: =pod
  446: 
  447: =head2 ServerToIdle
  448: 
  449: This function is called when a connection to the server is
  450: ready for more work.
  451: 
  452: If there is work in the Work queue the top element is dequeued
  453: and the connection will start to work on it.  If the work queue is
  454: empty, the connection is pushed on the idle connection stack where
  455: it will either get another work unit, or alternatively, if it sits there
  456: long enough, it will be shut down and released.
  457: 
  458: =cut
  459: 
  460: sub ServerToIdle {
  461:     my $Socket   = shift;	# Get the socket.
  462:     $KeyMode = $Socket->{AuthenticationMode};
  463:     delete($ActiveTransactions{$Socket}); # Server has no transaction
  464: 
  465:     &Debug(5, "Server to idle");
  466: 
  467:     #  If there's work to do, start the transaction:
  468: 
  469:     my $reqdata = $WorkQueue->dequeue(); # This is a LondTransaction
  470:     if ($reqdata ne undef)  {
  471: 	Debug(5, "Queue gave request data: ".$reqdata->getRequest());
  472: 	&StartRequest($Socket,  $reqdata);
  473: 
  474:     } else {
  475: 	
  476:     #  There's no work waiting, so push the server to idle list.
  477: 	&Debug(5, "No new work requests, server connection going idle");
  478: 	$IdleConnections->push($Socket);
  479:     }
  480: }
  481: 
  482: =pod
  483: 
  484: =head2 ClientWritable
  485: 
  486: Event callback for when a client socket is writable.
  487: 
  488: This callback is established when a transaction reponse is
  489: avaiable from lond.  The response is forwarded to the unix socket
  490: as it becomes writable in this sub.
  491: 
  492: Parameters:
  493: 
  494: =item Event
  495: 
  496: The event that has been triggered. Event->w->data is
  497: the data and Event->w->fd is the socket to write.
  498: 
  499: =cut
  500: 
  501: sub ClientWritable {
  502:     my $Event    = shift;
  503:     my $Watcher  = $Event->w;
  504:     my $Data     = $Watcher->data;
  505:     my $Socket   = $Watcher->fd;
  506: 
  507:     # Try to send the data:
  508: 
  509:     &Debug(6, "ClientWritable writing".$Data);
  510:     &Debug(9, "Socket is: ".$Socket);
  511: 
  512:     if($Socket->connected) {
  513: 	my $result = $Socket->send($Data, 0);
  514: 	
  515: 	# $result undefined: the write failed.
  516: 	# otherwise $result is the number of bytes written.
  517: 	# Remove that preceding string from the data.
  518: 	# If the resulting data is empty, destroy the watcher
  519: 	# and set up a read event handler to accept the next
  520: 	# request.
  521: 	
  522: 	&Debug(9,"Send result is ".$result." Defined: ".defined($result));
  523: 	if($result ne undef) {
  524: 	    &Debug(9, "send result was defined");
  525: 	    if($result == length($Data)) { # Entire string sent.
  526: 		&Debug(9, "ClientWritable data all written");
  527: 		$Watcher->cancel();
  528: 		#
  529: 		#  Set up to read next request from socket:
  530: 		
  531: 		my $descr     = sprintf("Connection to lonc client %d",
  532: 					$ActiveClients{$Socket});
  533: 		Event->io(cb    => \&ClientRequest,
  534: 			  poll  => 'r',
  535: 			  desc  => $descr,
  536: 			  data  => "",
  537: 			  fd    => $Socket);
  538: 		
  539: 	    } else {		# Partial string sent.
  540: 		$Watcher->data(substr($Data, $result));
  541: 		if($result == 0) {    # client hung up on us!!
  542: 		    # Log("INFO", "lonc pipe client hung up on us!");
  543: 		    $Watcher->cancel;
  544: 		    $Socket->shutdown(2);
  545: 		    $Socket->close();
  546: 		}
  547: 	    }
  548: 	    
  549: 	} else {			# Error of some sort...
  550: 	    
  551: 	    # Some errnos are possible:
  552: 	    my $errno = $!;
  553: 	    if($errno == POSIX::EWOULDBLOCK   ||
  554: 	       $errno == POSIX::EAGAIN        ||
  555: 	       $errno == POSIX::EINTR) {
  556: 		# No action taken?
  557: 	    } else {		# Unanticipated errno.
  558: 		&Debug(5,"ClientWritable error or peer shutdown".$RemoteHost);
  559: 		$Watcher->cancel;	# Stop the watcher.
  560: 		$Socket->shutdown(2); # Kill connection
  561: 		$Socket->close();	# Close the socket.
  562: 	    }
  563: 	    
  564: 	}
  565:     } else {
  566: 	$Watcher->cancel();	# A delayed request...just cancel.
  567:     }
  568: }
  569: 
  570: =pod
  571: 
  572: =head2 CompleteTransaction
  573: 
  574: Called when the reply data has been received for a lond 
  575: transaction.   The reply data must now be sent to the
  576: ultimate client on the other end of the Unix socket.  This is
  577: done by setting up a writable event for the socket with the
  578: data the reply data.
  579: 
  580: Parameters:
  581: 
  582: =item Socket
  583: 
  584: Socket on which the lond transaction occured.  This is a
  585: LondConnection. The data received is in the TransactionReply member.
  586: 
  587: =item Transaction
  588: 
  589: The transaction that is being completed.
  590: 
  591: =cut
  592: 
  593: sub CompleteTransaction {
  594:     &Debug(5,"Complete transaction");
  595: 
  596:     my ($Socket, $Transaction) = @_;
  597: 
  598:     if (!$Transaction->isDeferred()) { # Normal transaction
  599: 	my $data   = $Socket->GetReply(); # Data to send.
  600: 	if($LogTransactions) {
  601: 	    Log("SUCCESS", "Reply from lond: '$data'");
  602: 	}
  603: 	StartClientReply($Transaction, $data);
  604:     } else {			# Delete deferred transaction file.
  605: 	Log("SUCCESS", "A delayed transaction was completed");
  606: 	LogPerm("S:$Transaction->getClient() :".$Transaction->getRequest());
  607: 	unlink $Transaction->getFile();
  608:     }
  609: }
  610: 
  611: =pod
  612: 
  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: 
  629: sub StartClientReply {
  630: 
  631:     my ($Transaction, $data) = @_;
  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: 				 $Serial);
  639:     Event->io(fd       => $Client,
  640: 	      poll     => "w",
  641: 	      desc     => $desc,
  642: 	      cb       => \&ClientWritable,
  643: 	      data     => $data);
  644: }
  645: 
  646: =pod
  647: 
  648: =head2 FailTransaction
  649: 
  650:   Finishes a transaction with failure because the associated lond socket
  651:   disconnected.  There are two possibilities:
  652:   - The transaction is deferred: in which case we just quietly
  653:     delete the transaction since there is no client connection.
  654:   - The transaction is 'live' in which case we initiate the sending
  655:     of "con_lost" to the client.
  656: 
  657: Deleting the transaction means killing it from the %ActiveTransactions hash.
  658: 
  659: Parameters:
  660: 
  661: =item client  
  662:  
  663:    The LondTransaction we are failing.
  664:  
  665: 
  666: =cut
  667: 
  668: sub FailTransaction {
  669:     my $transaction = shift;
  670:     
  671:     #  If the socket is dead, that's already logged.
  672: 
  673:     if ($ConnectionRetriesLeft > 0) {
  674: 	Log("WARNING", "Failing transaction "
  675: 	    .$transaction->getRequest());
  676:     }
  677:     Debug(1, "Failing transaction: ".$transaction->getRequest());
  678:     if (!$transaction->isDeferred()) { # If the transaction is deferred we'll get to it.
  679: 	my $client  = $transaction->getClient();
  680: 	Debug(1," Replying con_lost to ".$transaction->getRequest());
  681: 	StartClientReply($transaction, "con_lost\n");
  682:     }
  683: 
  684: }
  685: 
  686: =pod
  687: =head1  EmptyQueue
  688: 
  689:   Fails all items in the work queue with con_lost.
  690:   Note that each item in the work queue is a transaction.
  691: 
  692: =cut
  693: sub EmptyQueue {
  694:     $ConnectionRetriesLeft--;	# Counts as connection failure too.
  695:     while($WorkQueue->Count()) {
  696: 	my $request = $WorkQueue->dequeue(); # This is a transaction
  697: 	FailTransaction($request);
  698:     }
  699: }
  700: 
  701: =pod
  702: 
  703: =head2 CloseAllLondConnections
  704: 
  705: Close all connections open on lond prior to exit e.g.
  706: 
  707: =cut
  708: sub CloseAllLondConnections {
  709:     foreach my $Socket (keys %ActiveConnections) {
  710:       if(exists($ActiveTransactions{$Socket})) {
  711: 	FailTransaction($ActiveTransactions{$Socket});
  712:       }
  713:       KillSocket($Socket);
  714:     }
  715: }
  716: =cut
  717: 
  718: =pod
  719: 
  720: =head2 KillSocket
  721:  
  722: Destroys a socket.  This function can be called either when a socket
  723: has died of 'natural' causes or because a socket needs to be pruned due to
  724: idleness.  If the socket has died naturally, if there are no longer any 
  725: live connections a new connection is created (in case there are transactions
  726: in the queue).  If the socket has been pruned, it is never re-created.
  727: 
  728: Parameters:
  729: 
  730: =item Socket
  731:  
  732:   The socket to kill off.
  733: 
  734: =item Restart
  735: 
  736: nonzero if we are allowed to create a new connection.
  737: 
  738: 
  739: =cut
  740: sub KillSocket {
  741:     my $Socket = shift;
  742: 
  743:     Log("WARNING", "Shutting down a socket");
  744:     $Socket->Shutdown();
  745: 
  746:     #  If the socket came from the active connection set,
  747:     #  delete its transaction... note that FailTransaction should
  748:     #  already have been called!!!
  749:     #  otherwise it came from the idle set.
  750:     #  
  751:     
  752:     if(exists($ActiveTransactions{$Socket})) {
  753: 	delete ($ActiveTransactions{$Socket});
  754:     }
  755:     if(exists($ActiveConnections{$Socket})) {
  756: 	delete($ActiveConnections{$Socket});
  757: 	$ConnectionCount--;
  758: 	if ($ConnectionCount < 0) { $ConnectionCount = 0; }
  759:     }
  760:     #  If the connection count has gone to zero and there is work in the
  761:     #  work queue, the work all gets failed with con_lost.
  762:     #
  763:     if($ConnectionCount == 0) {
  764: 	EmptyQueue();
  765: 	CloseAllLondConnections; # Should all already be closed but...
  766:     }
  767: }
  768: 
  769: =pod
  770: 
  771: =head2 LondReadable
  772: 
  773: This function is called whenever a lond connection
  774: is readable.  The action is state dependent:
  775: 
  776: =head3 State=Initialized
  777: 
  778: We''re waiting for the challenge, this is a no-op until the
  779: state changes.
  780: 
  781: =head3 State=Challenged 
  782: 
  783: The challenge has arrived we need to transition to Writable.
  784: The connection must echo the challenge back.
  785: 
  786: =head3 State=ChallengeReplied
  787: 
  788: The challenge has been replied to.  The we are receiveing the 
  789: 'ok' from the partner.
  790: 
  791: =head3  State=ReadingVersionString
  792: 
  793: We have requested the lond version and are reading the
  794: version back.  Upon completion, we'll store the version away
  795: for future use(?).
  796: 
  797: =head3 State=HostSet
  798: 
  799: We have selected the domain name of our peer (multhomed hosts)
  800: and are getting the reply (presumably ok) back.
  801: 
  802: =head3 State=RequestingKey
  803: 
  804: The ok has been received and we need to send the request for
  805: an encryption key.  Transition to writable for that.
  806: 
  807: =head3 State=ReceivingKey
  808: 
  809: The the key has been requested, now we are reading the new key.
  810: 
  811: =head3 State=Idle 
  812: 
  813: The encryption key has been negotiated or we have finished 
  814: reading data from the a transaction.   If the callback data has
  815: a client as well as the socket iformation, then we are 
  816: doing a transaction and the data received is relayed to the client
  817: before the socket is put on the idle list.
  818: 
  819: =head3 State=SendingRequest
  820: 
  821: I do not think this state can be received here, but if it is,
  822: the appropriate thing to do is to transition to writable, and send
  823: the request.
  824: 
  825: =head3 State=ReceivingReply
  826: 
  827: We finished sending the request to the server and now transition
  828: to readable to receive the reply. 
  829: 
  830: The parameter to this function are:
  831: 
  832: The event. Implicit in this is the watcher and its data.  The data 
  833: contains at least the lond connection object and, if a 
  834: transaction is in progress, the socket attached to the local client.
  835: 
  836: =cut
  837: 
  838: sub LondReadable {
  839: 
  840:     my $Event      = shift;
  841:     my $Watcher    = $Event->w;
  842:     my $Socket     = $Watcher->data;
  843:     my $client     = undef;
  844: 
  845:     &Debug(6,"LondReadable called state = ".$Socket->GetState());
  846: 
  847: 
  848:     my $State = $Socket->GetState(); # All action depends on the state.
  849: 
  850:     SocketDump(6, $Socket);
  851:     my $status = $Socket->Readable();
  852: 
  853:     &Debug(2, "Socket->Readable returned: $status");
  854: 
  855:     if($status != 0) {
  856: 	# bad return from socket read. Currently this means that
  857: 	# The socket has become disconnected. We fail the transaction.
  858: 
  859: 	Log("WARNING",
  860: 	    "Lond connection lost.");
  861: 	if(exists($ActiveTransactions{$Socket})) {
  862: 	    FailTransaction($ActiveTransactions{$Socket});
  863: 	} else {
  864: 	    #  Socket is connecting and failed... need to mark
  865: 	    #  no longer connecting.
  866: 	   
  867: 	    $LondConnecting = 0;
  868: 	}
  869: 	$Watcher->cancel();
  870: 	KillSocket($Socket);
  871: 	$ConnectionRetriesLeft--;       # Counts as connection failure
  872: 	return;
  873:     }
  874:     SocketDump(6,$Socket);
  875: 
  876:     $State = $Socket->GetState(); # Update in case of transition.
  877:     &Debug(6, "After read, state is ".$State);
  878: 
  879:     if($State eq "Initialized") {
  880: 
  881: 
  882:     } elsif ($State eq "ChallengeReceived") {
  883: 	#  The challenge must be echoed back;  The state machine
  884: 	# in the connection takes care of setting that up.  Just
  885: 	# need to transition to writable:
  886: 	
  887: 	$Watcher->cb(\&LondWritable);
  888: 	$Watcher->poll("w");
  889: 
  890:     } elsif ($State eq "ChallengeReplied") {
  891: 
  892:     } elsif ($State eq "RequestingVersion") {
  893: 	# Need to ask for the version... that is writiability:
  894: 
  895: 	$Watcher->cb(\&LondWritable);
  896: 	$Watcher->poll("w");
  897: 
  898:     } elsif ($State eq "ReadingVersionString") {
  899: 	# Read the rest of the version string... 
  900:     } elsif ($State eq "SetHost") {
  901: 	# Need to request the actual domain get set...
  902: 
  903: 	$Watcher->cb(\&LondWritable);
  904: 	$Watcher->poll("w");
  905:     } elsif ($State eq "HostSet") {
  906: 	# Reading the 'ok' from the peer.
  907: 
  908:     } elsif ($State eq "RequestingKey") {
  909: 	#  The ok was received.  Now we need to request the key
  910: 	#  That requires us to be writable:
  911: 
  912: 	$Watcher->cb(\&LondWritable);
  913: 	$Watcher->poll("w");
  914: 
  915:     } elsif ($State eq "ReceivingKey") {
  916: 
  917:     } elsif ($State eq "Idle") {
  918:    
  919: 	# This is as good a spot as any to get the peer version
  920: 	# string:
  921:    
  922: 	if($LondVersion eq "unknown") {
  923: 	    $LondVersion = $Socket->PeerVersion();
  924: 	    Log("INFO", "Connected to lond version: $LondVersion");
  925: 	}
  926: 	# If necessary, complete a transaction and then go into the
  927: 	# idle queue.
  928: 	#  Note that a trasition to idle indicates a live lond
  929: 	# on the other end so reset the connection retries.
  930: 	#
  931: 	$ConnectionRetriesLeft = $ConnectionRetries; # success resets the count
  932: 	$Watcher->cancel();
  933: 	if(exists($ActiveTransactions{$Socket})) {
  934: 	    Debug(5,"Completing transaction!!");
  935: 	    CompleteTransaction($Socket, 
  936: 				$ActiveTransactions{$Socket});
  937: 	} else {
  938: 	    Log("SUCCESS", "Connection ".$ConnectionCount." to "
  939: 		.$RemoteHost." now ready for action");
  940: 	}
  941: 	ServerToIdle($Socket);	# Next work unit or idle.
  942: 
  943: 	#
  944: 	$LondConnecting = 0;	# Best spot I can think of for this.
  945: 	# 
  946: 	
  947:     } elsif ($State eq "SendingRequest") {
  948: 	#  We need to be writable for this and probably don't belong
  949: 	#  here inthe first place.
  950: 
  951: 	Deubg(6, "SendingRequest state encountered in readable");
  952: 	$Watcher->poll("w");
  953: 	$Watcher->cb(\&LondWritable);
  954: 
  955:     } elsif ($State eq "ReceivingReply") {
  956: 
  957: 
  958:     } else {
  959: 	# Invalid state.
  960: 	Debug(4, "Invalid state in LondReadable");
  961:     }
  962: }
  963: 
  964: =pod
  965: 
  966: =head2 LondWritable
  967: 
  968: This function is called whenever a lond connection
  969: becomes writable while there is a writeable monitoring
  970: event.  The action taken is very state dependent:
  971: 
  972: =head3 State = Connected 
  973: 
  974: The connection is in the process of sending the 'init' hailing to the
  975: lond on the remote end.  The connection object''s Writable member is
  976: called.  On error, ConnectionError is called to destroy the connection
  977: and remove it from the ActiveConnections hash
  978: 
  979: =head3 Initialized
  980: 
  981: 'init' has been sent, writability monitoring is removed and
  982: readability monitoring is started with LondReadable as the callback.
  983: 
  984: =head3 ChallengeReceived
  985: 
  986: The connection has received the who are you challenge from the remote
  987: system, and is in the process of sending the challenge
  988: response. Writable is called.
  989: 
  990: =head3 ChallengeReplied
  991: 
  992: The connection has replied to the initial challenge The we switch to
  993: monitoring readability looking for the server to reply with 'ok'.
  994: 
  995: =head3 RequestingKey
  996: 
  997: The connection is in the process of requesting its encryption key.
  998: Writable is called.
  999: 
 1000: =head3 ReceivingKey
 1001: 
 1002: The connection has sent the request for a key.  Switch to readability
 1003: monitoring to accept the key
 1004: 
 1005: =head3 SendingRequest
 1006: 
 1007: The connection is in the process of sending a request to the server.
 1008: This request is part of a client transaction.  All the states until
 1009: now represent the client setup protocol. Writable is called.
 1010: 
 1011: =head3 ReceivingReply
 1012: 
 1013: The connection has sent a request.  Now it must receive a reply.
 1014: Readability monitoring is requested.
 1015: 
 1016: This function is an event handler and therefore receives as
 1017: a parameter the event that has fired.  The data for the watcher
 1018: of this event is a reference to a list of one or two elements,
 1019: depending on state. The first (and possibly only) element is the
 1020: socket.  The second (present only if a request is in progress)
 1021: is the socket on which to return a reply to the caller.
 1022: 
 1023: =cut
 1024: 
 1025: sub LondWritable {
 1026:     my $Event   = shift;
 1027:     my $Watcher = $Event->w;
 1028:     my $Socket  = $Watcher->data;
 1029:     my $State   = $Socket->GetState();
 1030: 
 1031:     Debug(6,"LondWritable State = ".$State."\n");
 1032: 
 1033:  
 1034:     #  Figure out what to do depending on the state of the socket:
 1035:     
 1036: 
 1037: 
 1038: 
 1039:     SocketDump(6,$Socket);
 1040: 
 1041:     #  If the socket is writable, we must always write.
 1042:     # Only by writing will we undergo state transitions.
 1043:     # Old logic wrote in state specific code below, however
 1044:     # That forces us at least through another invocation of
 1045:     # this function after writability is possible again.
 1046:     # This logic also factors out common code for handling
 1047:     # write failures... in all cases, write failures 
 1048:     # Kill the socket.
 1049:     #  This logic makes the branches of the >big< if below
 1050:     # so that the writing states are actually NO-OPs.
 1051: 
 1052:     if ($Socket->Writable() != 0) {
 1053: 	#  The write resulted in an error.
 1054: 	# We'll treat this as if the socket got disconnected:
 1055: 	Log("WARNING", "Connection to ".$RemoteHost.
 1056: 	    " has been disconnected");
 1057: 	if(exists($ActiveTransactions{$Socket})) {
 1058: 	    FailTransaction($ActiveTransactions{$Socket});
 1059: 	} else {
 1060: 	    #  In the process of conneting, so need to turn that off.
 1061: 	    
 1062: 	    $LondConnecting = 0;
 1063: 	}
 1064: 	$Watcher->cancel();
 1065: 	KillSocket($Socket);
 1066: 	return;
 1067:     }
 1068: 
 1069: 
 1070: 
 1071:     if      ($State eq "Connected")         {
 1072: 
 1073: 	#  "init" is being sent...
 1074:  
 1075:     } elsif ($State eq "Initialized")       {
 1076: 
 1077: 	# Now that init was sent, we switch 
 1078: 	# to watching for readability:
 1079: 
 1080: 	$Watcher->cb(\&LondReadable);
 1081: 	$Watcher->poll("r");
 1082: 	
 1083:     } elsif ($State eq "ChallengeReceived") {
 1084: 	# We received the challenge, now we 
 1085: 	# are echoing it back. This is a no-op,
 1086: 	# we're waiting for the state to change
 1087: 	
 1088:     } elsif ($State eq "ChallengeReplied")  {
 1089: 	# The echo was sent back, so we switch
 1090: 	# to watching readability.
 1091: 
 1092: 	$Watcher->cb(\&LondReadable);
 1093: 	$Watcher->poll("r");
 1094:     } elsif ($State eq "RequestingVersion") {
 1095: 	# Sending the peer a version request...
 1096: 
 1097:     } elsif ($State eq "ReadingVersionString") {
 1098: 	# Transition to read since we have sent the
 1099: 	# version command and now just need to read the
 1100: 	# version string from the peer:
 1101:       
 1102: 	$Watcher->cb(\&LondReadable);
 1103: 	$Watcher->poll("r");
 1104:       
 1105:     } elsif ($State eq "SetHost") {
 1106: 	#  Setting the remote domain...
 1107: 
 1108:     } elsif ($State eq "HostSet") {
 1109: 	# Back to readable to get the ok.
 1110:       
 1111: 	$Watcher->cb(\&LondReadable);
 1112: 	$Watcher->poll("r");
 1113:       
 1114: 
 1115:     } elsif ($State eq "RequestingKey")     {
 1116: 	# At this time we're requesting the key.
 1117: 	# again, this is essentially a no-op.
 1118: 
 1119:     } elsif ($State eq "ReceivingKey")      {
 1120: 	# Now we need to wait for the key
 1121: 	# to come back from the peer:
 1122: 
 1123: 	$Watcher->cb(\&LondReadable);
 1124: 	$Watcher->poll("r");
 1125: 
 1126:     } elsif ($State eq "SendingRequest")    {
 1127:  
 1128: 	# At this time we are sending a request to the
 1129: 	# peer... write the next chunk:
 1130: 
 1131: 
 1132:     } elsif ($State eq "ReceivingReply")    {
 1133: 	# The send has completed.  Wait for the
 1134: 	# data to come in for a reply.
 1135: 	Debug(8,"Writable sent request/receiving reply");
 1136: 	$Watcher->cb(\&LondReadable);
 1137: 	$Watcher->poll("r");
 1138: 
 1139:     } else {
 1140: 	#  Control only passes here on an error: 
 1141: 	#  the socket state does not match any
 1142: 	#  of the known states... so an error
 1143: 	#  must be logged.
 1144: 
 1145: 	&Debug(4, "Invalid socket state ".$State."\n");
 1146:     }
 1147:     
 1148: }
 1149: =pod
 1150:     
 1151: =cut
 1152: sub QueueDelayed {
 1153:     Debug(3,"QueueDelayed called");
 1154: 
 1155:     my $path = "$perlvar{'lonSockDir'}/delayed";
 1156: 
 1157:     Debug(4, "Delayed path: ".$path);
 1158:     opendir(DIRHANDLE, $path);
 1159:     
 1160:     my @alldelayed = grep /\.$RemoteHost$/, readdir DIRHANDLE;
 1161:     closedir(DIRHANDLE);
 1162:     my $dfname;
 1163:     my $reqfile;
 1164:     foreach $dfname (sort  @alldelayed) {
 1165: 	$reqfile = "$path/$dfname";
 1166: 	Debug(4, "queueing ".$reqfile);
 1167: 	my $Handle = IO::File->new($reqfile);
 1168: 	my $cmd    = <$Handle>;
 1169: 	chomp $cmd;		# There may or may not be a newline...
 1170: 	$cmd = $cmd."\n";	# now for sure there's exactly one newline.
 1171: 	my $Transaction = LondTransaction->new($cmd);
 1172: 	$Transaction->SetDeferred($reqfile);
 1173: 	QueueTransaction($Transaction);
 1174:     }
 1175:     
 1176: }
 1177: 
 1178: =pod
 1179: 
 1180: =head2 MakeLondConnection
 1181: 
 1182: Create a new lond connection object, and start it towards its initial
 1183: idleness.  Once idle, it becomes elligible to receive transactions
 1184: from the work queue.  If the work queue is not empty when the
 1185: connection is completed and becomes idle, it will dequeue an entry and
 1186: start off on it.
 1187: 
 1188: =cut
 1189: 
 1190: sub MakeLondConnection {     
 1191:     Debug(4,"MakeLondConnection to ".GetServerHost()." on port "
 1192: 	  .GetServerPort());
 1193: 
 1194:     my $Connection = LondConnection->new(&GetServerHost(),
 1195: 					 &GetServerPort());
 1196: 
 1197:     if($Connection eq undef) {	# Needs to be more robust later.
 1198: 	Log("CRITICAL","Failed to make a connection with lond.");
 1199: 	$ConnectionRetriesLeft--;
 1200: 	return 0;		# Failure.
 1201:     }  else {
 1202: 
 1203: 	# The connection needs to have writability 
 1204: 	# monitored in order to send the init sequence
 1205: 	# that starts the whole authentication/key
 1206: 	# exchange underway.
 1207: 	#
 1208: 	my $Socket = $Connection->GetSocket();
 1209: 	if($Socket eq undef) {
 1210: 	    &child_exit(-1, "did not get a socket from the connection");
 1211: 	} else {
 1212: 	    &Debug(9,"MakeLondConnection got socket: ".$Socket);
 1213: 	}
 1214: 	
 1215: 	$Connection->SetTimeoutCallback(\&SocketTimeout);
 1216: 
 1217: 	my $event = Event->io(fd       => $Socket,
 1218: 			   poll     => 'w',
 1219: 			   cb       => \&LondWritable,
 1220: 			   data     => $Connection,
 1221: 			   desc => 'Connection to lond server');
 1222: 	$ActiveConnections{$Connection} = $event;
 1223: 	if ($ConnectionCount == 0) {
 1224: 	    &SetupTimer;	# Need to handle timeouts with connections...
 1225: 	}
 1226: 	$ConnectionCount++;
 1227: 	Debug(4, "Connection count = ".$ConnectionCount);
 1228: 	if($ConnectionCount == 1) { # First Connection:
 1229: 	    QueueDelayed;
 1230: 	}
 1231: 	Log("SUCESS", "Created connection ".$ConnectionCount
 1232: 	    ." to host ".GetServerHost());
 1233: 	$LondConnecting = 1;	# Connection in progress.
 1234: 	return 1;		# Return success.
 1235:     }
 1236:     
 1237: }
 1238: 
 1239: =pod
 1240: 
 1241: =head2 StartRequest
 1242: 
 1243: Starts a lond request going on a specified lond connection.
 1244: parameters are:
 1245: 
 1246: =item $Lond
 1247: 
 1248: Connection to the lond that will send the transaction and receive the
 1249: reply.
 1250: 
 1251: =item $Client
 1252: 
 1253: Connection to the client that is making this request We got the
 1254: request from this socket, and when the request has been relayed to
 1255: lond and we get a reply back from lond it will get sent to this
 1256: socket.
 1257: 
 1258: =item $Request
 1259: 
 1260: The text of the request to send.
 1261: 
 1262: =cut
 1263: 
 1264: sub StartRequest {
 1265: 
 1266:     my ($Lond, $Request) = @_;
 1267:     
 1268:     Debug(6, "StartRequest: ".$Request->getRequest());
 1269: 
 1270:     my $Socket = $Lond->GetSocket();
 1271:     
 1272:     $Request->Activate($Lond);
 1273:     $ActiveTransactions{$Lond} = $Request;
 1274: 
 1275:     $Lond->InitiateTransaction($Request->getRequest());
 1276:     my $event = Event->io(fd      => $Socket,
 1277: 		       poll    => "w",
 1278: 		       cb      => \&LondWritable,
 1279: 		       data    => $Lond,
 1280: 		       desc    => "lond transaction connection");
 1281:     $ActiveConnections{$Lond} = $event;
 1282:     Debug(8," Start Request made watcher data with ".$event->data."\n");
 1283: }
 1284: 
 1285: =pod
 1286: 
 1287: =head2 QueueTransaction
 1288: 
 1289: If there is an idle lond connection, it is put to work doing this
 1290: transaction.  Otherwise, the transaction is placed in the work queue.
 1291: If placed in the work queue and the maximum number of connections has
 1292: not yet been created, a new connection will be started.  Our goal is
 1293: to eventually have a sufficient number of connections that the work
 1294: queue will typically be empty.  parameters are:
 1295: 
 1296: =item Socket
 1297: 
 1298: open on the lonc client.
 1299: 
 1300: =item Request
 1301: 
 1302: data to send to the lond.
 1303: 
 1304: =cut
 1305: 
 1306: sub QueueTransaction {
 1307: 
 1308:     my $requestData   = shift;	# This is a LondTransaction.
 1309:     my $cmd           = $requestData->getRequest();
 1310: 
 1311:     Debug(6,"QueueTransaction: ".$cmd);
 1312: 
 1313:     my $LondSocket    = $IdleConnections->pop();
 1314:     if(!defined $LondSocket) {	# Need to queue request.
 1315: 	Debug(5,"Must queue...");
 1316: 	$WorkQueue->enqueue($requestData);
 1317: 	Debug(5, "Queue Transaction startnew $ConnectionCount $LondConnecting");
 1318: 	if(($ConnectionCount < $MaxConnectionCount)   && (! $LondConnecting)) {
 1319: 
 1320: 	    if($ConnectionRetriesLeft > 0) {
 1321: 		Debug(5,"Starting additional lond connection");
 1322: 		if(&MakeLondConnection() == 0) {
 1323: 		    EmptyQueue();	# Fail transactions, can't make connection.
 1324: 		    CloseAllLondConnections; # Should all be closed but...
 1325: 		}
 1326: 	    } else {
 1327: 		ShowStatus(GetServerHost()." >>> DEAD !!!! <<<");
 1328: 		$LondConnecting = 0;
 1329: 		EmptyQueue();	# It's worse than that ... he's dead Jim.
 1330: 		CloseAllLondConnections; # Should all be closed but..
 1331: 	    }
 1332: 	}
 1333:     } else {			# Can start the request:
 1334: 	Debug(8,"Can start...");
 1335: 	StartRequest($LondSocket,  $requestData);
 1336:     }
 1337: }
 1338: 
 1339: #-------------------------- Lonc UNIX socket handling ---------------------
 1340: 
 1341: =pod
 1342: 
 1343: =head2 ClientRequest
 1344: Callback that is called when data can be read from the UNIX domain
 1345: socket connecting us with an apache server process.
 1346: 
 1347: =cut
 1348: 
 1349: sub ClientRequest {
 1350:     Debug(6, "ClientRequest");
 1351:     my $event   = shift;
 1352:     my $watcher = $event->w;
 1353:     my $socket  = $watcher->fd;
 1354:     my $data    = $watcher->data;
 1355:     my $thisread;
 1356: 
 1357:     Debug(9, "  Watcher named: ".$watcher->desc);
 1358: 
 1359:     my $rv = $socket->recv($thisread, POSIX::BUFSIZ, 0);
 1360:     Debug(8, "rcv:  data length = ".length($thisread)
 1361: 	  ." read =".$thisread);
 1362:     unless (defined $rv  && length($thisread)) {
 1363: 	 # Likely eof on socket.
 1364: 	Debug(5,"Client Socket closed on lonc for ".$RemoteHost);
 1365: 	close($socket);
 1366: 	$watcher->cancel();
 1367: 	delete($ActiveClients{$socket});
 1368: 	return;
 1369:     }
 1370:     Debug(8,"Data: ".$data." this read: ".$thisread);
 1371:     $data = $data.$thisread;	# Append new data.
 1372:     $watcher->data($data);
 1373:     if($data =~ /\n$/) {	# Request entirely read.
 1374: 	if($data eq "close_connection_exit\n") {
 1375: 	    Log("CRITICAL",
 1376: 		"Request Close Connection ... exiting");
 1377: 	    CloseAllLondConnections();
 1378: 	    exit;
 1379: 	}
 1380: 	Debug(8, "Complete transaction received: ".$data);
 1381: 	if($LogTransactions) {
 1382: 	    Log("SUCCESS", "Transaction: '$data'"); # Transaction has \n.
 1383: 	}
 1384: 	my $Transaction = LondTransaction->new($data);
 1385: 	$Transaction->SetClient($socket);
 1386: 	QueueTransaction($Transaction);
 1387: 	$watcher->cancel();	# Done looking for input data.
 1388:     }
 1389: 
 1390: }
 1391: 
 1392: #
 1393: #     Accept a connection request for a client (lonc child) and
 1394: #    start up an event watcher to keep an eye on input from that 
 1395: #    Event.  This can be called both from NewClient and from
 1396: #    ChildProcess if we are started in DieWhenIdle mode.
 1397: # Parameters:
 1398: #    $socket       - The listener socket.
 1399: # Returns:
 1400: #   NONE
 1401: # Side Effects:
 1402: #    An event is made to watch the accepted connection.
 1403: #    Active clients hash is updated to reflect the new connection.
 1404: #    The client connection count is incremented.
 1405: #
 1406: sub accept_client {
 1407:     my ($socket) = @_;
 1408: 
 1409:     Debug(8, "Entering accept for lonc UNIX socket\n");
 1410:     my $connection = $socket->accept();	# Accept the client connection.
 1411:     Debug(8,"Connection request accepted from "
 1412: 	  .GetPeername($connection, AF_UNIX));
 1413: 
 1414: 
 1415:     my $description = sprintf("Connection to lonc client %d",
 1416: 			      $ClientConnection);
 1417:     Debug(9, "Creating event named: ".$description);
 1418:     Event->io(cb      => \&ClientRequest,
 1419: 	      poll    => 'r',
 1420: 	      desc    => $description,
 1421: 	      data    => "",
 1422: 	      fd      => $connection);
 1423:     $ActiveClients{$connection} = $ClientConnection;
 1424:     $ClientConnection++;
 1425: }
 1426: 
 1427: =pod
 1428: 
 1429: =head2  NewClient
 1430: 
 1431: Callback that is called when a connection is received on the unix
 1432: socket for a new client of lonc.  The callback is parameterized by the
 1433: event.. which is a-priori assumed to be an io event, and therefore has
 1434: an fd member that is the Listener socket.  We Accept the connection
 1435: and register a new event on the readability of that socket:
 1436: 
 1437: =cut
 1438: 
 1439: sub NewClient {
 1440:     Debug(6, "NewClient");
 1441:     my $event      = shift;		# Get the event parameters.
 1442:     my $watcher    = $event->w; 
 1443:     my $socket     = $watcher->fd;	# Get the event' socket.
 1444: 
 1445:     &accept_client($socket);
 1446: }
 1447: 
 1448: =pod
 1449: 
 1450: =head2 GetLoncSocketPath
 1451: 
 1452: Returns the name of the UNIX socket on which to listen for client
 1453: connections.
 1454: 
 1455: =head2 Parameters:
 1456: 
 1457:     host (optional)  - Name of the host socket to return.. defaults to
 1458:                        the return from GetServerHost().
 1459: 
 1460: =cut
 1461: 
 1462: sub GetLoncSocketPath {
 1463: 
 1464:     my $host = GetServerHost();	# Default host.
 1465:     if (@_) {
 1466: 	($host)  = @_;		# Override if supplied.
 1467:     }
 1468:     return $UnixSocketDir."/".$host;
 1469: }
 1470: 
 1471: =pod
 1472: 
 1473: =head2 GetServerHost
 1474: 
 1475: Returns the host whose lond we talk with.
 1476: 
 1477: =cut
 1478: 
 1479: sub GetServerHost {
 1480:     return $RemoteHost;		# Setup by the fork.
 1481: }
 1482: 
 1483: =pod
 1484: 
 1485: =head2 GetServerPort
 1486: 
 1487: Returns the lond port number.
 1488: 
 1489: =cut
 1490: 
 1491: sub GetServerPort {
 1492:     return $perlvar{londPort};
 1493: }
 1494: 
 1495: =pod
 1496: 
 1497: =head2 SetupLoncListener
 1498: 
 1499: Setup a lonc listener event.  The event is called when the socket
 1500: becomes readable.. that corresponds to the receipt of a new
 1501: connection.  The event handler established will accept the connection
 1502: (creating a communcations channel), that int turn will establish
 1503: another event handler to subess requests.
 1504: 
 1505: =head2  Parameters:
 1506: 
 1507:    host (optional)   Name of the host to set up a unix socket to.
 1508: 
 1509: =cut
 1510: 
 1511: sub SetupLoncListener {
 1512: 
 1513:     my $host       = GetServerHost(); # Default host.
 1514:     if (@_) {
 1515: 	($host)    = @_		# Override host with parameter.
 1516:     }
 1517: 
 1518:     my $socket;
 1519:     my $SocketName = GetLoncSocketPath($host);
 1520:     unlink($SocketName);
 1521:     unless ($socket =IO::Socket::UNIX->new(Local  => $SocketName,
 1522: 					    Listen => 250, 
 1523: 					    Type   => SOCK_STREAM)) {
 1524: 	if($I_am_child) {
 1525: 	    &child_exit(-1, "Failed to create a lonc listener socket");
 1526: 	} else {
 1527: 	    die "Failed to create a lonc listner socket";
 1528: 	}
 1529:     }
 1530:     return $socket;
 1531: }
 1532: 
 1533: #
 1534: #   Toggle transaction logging.
 1535: #  Implicit inputs:  
 1536: #     LogTransactions
 1537: #  Implicit Outputs:
 1538: #     LogTransactions
 1539: sub ToggleTransactionLogging {
 1540:     print STDERR "Toggle transaction logging...\n";
 1541:     if(!$LogTransactions) {
 1542: 	$LogTransactions = 1;
 1543:     } else {
 1544: 	$LogTransactions = 0;
 1545:     }
 1546: 
 1547: 
 1548:     Log("SUCCESS", "Toggled transaction logging: $LogTransactions \n");
 1549: }
 1550: 
 1551: =pod 
 1552: 
 1553: =head2 ChildStatus
 1554:  
 1555: Child USR1 signal handler to report the most recent status
 1556: into the status file.
 1557: 
 1558: We also use this to reset the retries count in order to allow the
 1559: client to retry connections with a previously dead server.
 1560: =cut
 1561: 
 1562: sub ChildStatus {
 1563:     my $event = shift;
 1564:     my $watcher = $event->w;
 1565: 
 1566:     Debug(2, "Reporting child status because : ".$watcher->data);
 1567:     my $docdir = $perlvar{'lonDocRoot'};
 1568:     my $fh = IO::File->new(">>$docdir/lon-status/loncstatus.txt");
 1569:     print $fh $$."\t".$RemoteHost."\t".$Status."\t".
 1570: 	$RecentLogEntry."\n";
 1571:     #
 1572:     #  Write out information about each of the connections:
 1573:     #
 1574:     if ($DebugLevel > 2) {
 1575: 	print $fh "Active connection statuses: \n";
 1576: 	my $i = 1;
 1577: 	print STDERR  "================================= Socket Status Dump:\n";
 1578: 	foreach my $item (keys %ActiveConnections) {
 1579: 	    my $Socket = $ActiveConnections{$item}->data;
 1580: 	    my $state  = $Socket->GetState();
 1581: 	    print $fh "Connection $i State: $state\n";
 1582: 	    print STDERR "---------------------- Connection $i \n";
 1583: 	    $Socket->Dump(-1);	# Ensure it gets dumped..
 1584: 	    $i++;	
 1585: 	}
 1586:     }
 1587:     $ConnectionRetriesLeft = $ConnectionRetries;
 1588: }
 1589: 
 1590: =pod
 1591: 
 1592: =head2 SignalledToDeath
 1593: 
 1594: Called in response to a signal that causes a chid process to die.
 1595: 
 1596: =cut
 1597: 
 1598: 
 1599: sub SignalledToDeath {
 1600:     my $event  = shift;
 1601:     my $watcher= $event->w;
 1602: 
 1603:     Debug(2,"Signalled to death! via ".$watcher->data);
 1604:     my ($signal) = $watcher->data;
 1605:     chomp($signal);
 1606:     Log("CRITICAL", "Abnormal exit.  Child $$ for $RemoteHost "
 1607: 	."died through "."\"$signal\"");
 1608:     LogPerm("F:lonc: $$ on $RemoteHost signalled to death: "
 1609: 	    ."\"$signal\"");
 1610:     exit 0;
 1611: 
 1612: }
 1613: 
 1614: =head2 ToggleDebug
 1615: 
 1616: This sub toggles trace debugging on and off.
 1617: 
 1618: =cut
 1619: 
 1620: sub ToggleDebug {
 1621:     my $Current    = $DebugLevel;
 1622:        $DebugLevel = $NextDebugLevel;
 1623:        $NextDebugLevel = $Current;
 1624: 
 1625:     Log("SUCCESS", "New debugging level for $RemoteHost now $DebugLevel");
 1626: 
 1627: }
 1628: 
 1629: =head2 ChildProcess
 1630: 
 1631: This sub implements a child process for a single lonc daemon.
 1632: Optional parameter:
 1633:    $socket  - if provided, this is a socket already open for listen
 1634:               on the client socket. Otherwise, a new listen is set up.
 1635: 
 1636: =cut
 1637: 
 1638: sub ChildProcess {
 1639:     #  If we are in DieWhenIdle mode, we've inherited all the
 1640:     #  events of our parent and those have to be cancelled or else
 1641:     #  all holy bloody chaos will result.. trust me, I already made
 1642:     #  >that< mistake.
 1643: 
 1644:     my $host = GetServerHost();
 1645:     foreach my $listener (keys %parent_dispatchers) {
 1646: 	my $watcher = $parent_dispatchers{$listener};
 1647: 	my $s       = $watcher->fd;
 1648: 	if ($listener ne $host) { # Close everyone but me.
 1649: 	    Debug(5, "Closing listen socket for $listener");
 1650: 	    $s->close();
 1651: 	}
 1652: 	Debug(5, "Killing watcher for $listener");
 1653: 
 1654: 	$watcher->cancel();
 1655: 	delete($parent_dispatchers{$listener});
 1656: 
 1657:     }
 1658: 
 1659:     #  kill off the parent's signal handlers too!  
 1660:     #
 1661: 
 1662:     for my $handler (keys %parent_handlers) {
 1663: 	my $watcher = $parent_handlers{$handler};
 1664: 	$watcher->cancel();
 1665: 	delete($parent_handlers{$handler});
 1666:     }
 1667: 
 1668:     $I_am_child    = 1;		# Seems like in spite of it all I may still getting
 1669:                                 # parent event dispatches.. flag I'm a child.
 1670: 
 1671: 
 1672:     #
 1673:     #  Signals must be handled by the Event framework...
 1674:     #
 1675: 
 1676:     Event->signal(signal   => "QUIT",
 1677: 		  cb       => \&SignalledToDeath,
 1678: 		  data     => "QUIT");
 1679:     Event->signal(signal   => "HUP",
 1680: 		  cb       => \&ChildStatus,
 1681: 		  data     => "HUP");
 1682:     Event->signal(signal   => "USR1",
 1683: 		  cb       => \&ChildStatus,
 1684: 		  data     => "USR1");
 1685:     Event->signal(signal   => "USR2",
 1686: 		  cb       => \&ToggleTransactionLogging);
 1687:     Event->signal(signal   => "INT",
 1688: 		  cb       => \&ToggleDebug,
 1689: 		  data     => "INT");
 1690: 
 1691:     #  Figure out if we got passed a socket or need to open one to listen for
 1692:     #  client requests.
 1693: 
 1694:     my ($socket) = @_;
 1695:     if (!$socket) {
 1696: 
 1697: 	$socket =  SetupLoncListener();
 1698:     }
 1699:     #  Establish an event to listen for client connection requests.
 1700: 
 1701: 
 1702:     Event->io(cb   => \&NewClient,
 1703: 	      poll => 'r',
 1704: 	      desc => 'Lonc Listener Unix Socket',
 1705: 	      fd   => $socket);
 1706:     
 1707:     $Event::Debuglevel = $DebugLevel;
 1708:     
 1709:     Debug(9, "Making initial lond connection for ".$RemoteHost);
 1710: 
 1711: # Setup the initial server connection:
 1712:     
 1713:      # &MakeLondConnection(); // let first work request do it.
 1714: 
 1715:     #  If We are in diwhenidle, need to accept the connection since the
 1716:     #  event may  not fire.
 1717: 
 1718:     if ($DieWhenIdle) {
 1719: 	&accept_client($socket);
 1720:     }
 1721: 
 1722:     Debug(9,"Entering event loop");
 1723:     my $ret = Event::loop();		#  Start the main event loop.
 1724:     
 1725:     
 1726:     &child_exit (-1,"Main event loop exited!!!");
 1727: }
 1728: 
 1729: #  Create a new child for host passed in:
 1730: 
 1731: sub CreateChild {
 1732:     my ($host, $socket) = @_;
 1733: 
 1734:     my $sigset = POSIX::SigSet->new(SIGINT);
 1735:     sigprocmask(SIG_BLOCK, $sigset);
 1736:     $RemoteHost = $host;
 1737:     Log("CRITICAL", "Forking server for ".$host);
 1738:     my $pid          = fork;
 1739:     if($pid) {			# Parent
 1740: 	$RemoteHost = "Parent";
 1741: 	$ChildHash{$pid} = $host;
 1742: 	$HostToPid{$host}= $pid;
 1743: 	sigprocmask(SIG_UNBLOCK, $sigset);
 1744: 
 1745:     } else {			# child.
 1746: 	ShowStatus("Connected to ".$RemoteHost);
 1747: 	$SIG{INT} = 'DEFAULT';
 1748: 	sigprocmask(SIG_UNBLOCK, $sigset);
 1749: 	if(defined $socket) {
 1750: 	    &ChildProcess($socket);
 1751: 	} else {
 1752: 	    ChildProcess;		# Does not return.
 1753: 	}
 1754:     }
 1755: }
 1756: 
 1757: # parent_client_connection:
 1758: #    Event handler that processes client connections for the parent process.
 1759: #    This sub is called when the parent is listening on a socket and
 1760: #    a connection request arrives.  We must:
 1761: #     Start a child process to accept the connection request.
 1762: #     Kill our listen on the socket.
 1763: # Parameter:
 1764: #    event       - The event object that was created to monitor this socket.
 1765: #                  event->w->fd is the socket.
 1766: # Returns:
 1767: #    NONE
 1768: #
 1769: sub parent_client_connection {
 1770:     if ($I_am_child) {
 1771: 	#  Should not get here, but seem to anyway:
 1772: 	&Debug(5," Child caught parent client connection event!!");
 1773: 	my ($event) = @_;
 1774: 	my $watcher = $event->w;
 1775: 	$watcher->cancel();	# Try to kill it off again!!
 1776:     } else {
 1777: 	&Debug(9, "parent_client_connection");
 1778: 	my ($event)   = @_;
 1779: 	my $watcher   = $event->w;
 1780: 	my $socket    = $watcher->fd;
 1781: 	
 1782: 	# Lookup the host associated with this socket:
 1783: 	
 1784: 	my $host = $listening_to{$socket};
 1785: 	
 1786: 	# Start the child:
 1787: 	
 1788: 	
 1789: 	
 1790: 	&Debug(9,"Creating child for $host (parent_client_connection)");
 1791: 	&CreateChild($host, $socket);
 1792: 	
 1793: 	# Clean up the listen since now the child takes over until it exits.
 1794: 	
 1795: 	$watcher->cancel();		# Nolonger listening to this event
 1796: 	delete($listening_to{$socket});
 1797: 	delete($parent_dispatchers{$host});
 1798: 	$socket->close();
 1799:     }
 1800: }
 1801: 
 1802: # parent_listen:
 1803: #    Opens a socket and starts a listen for the parent process on a client UNIX
 1804: #    domain socket.
 1805: #
 1806: #    This involves:
 1807: #       Creating a socket for listen.
 1808: #       Removing any socket lock file
 1809: #       Adding an event handler for this socket becoming readable
 1810: #         To the parent's event dispatcher.
 1811: # Parameters:
 1812: #    loncapa_host    - LonCAPA cluster name of the host represented by the client
 1813: #                      socket.
 1814: # Returns:
 1815: #    NONE
 1816: #
 1817: sub parent_listen {
 1818:     my ($loncapa_host) = @_;
 1819:     Debug(5, "parent_listen: $loncapa_host");
 1820: 
 1821:     my $socket    = &SetupLoncListener($loncapa_host);
 1822:     $listening_to{$socket} = $loncapa_host;
 1823:     if (!$socket) {
 1824: 	die "Unable to create a listen socket for $loncapa_host";
 1825:     }
 1826:     
 1827:     my $lock_file = &GetLoncSocketPath($loncapa_host).".lock";
 1828:     unlink($lock_file);		# No problem if it doesn't exist yet [startup e.g.]
 1829: 
 1830:     my $watcher = Event->io(cb    => \&parent_client_connection,
 1831: 	      poll  => 'r',
 1832: 	      desc  => "Parent listener unix socket ($loncapa_host)",
 1833: 	      fd    => $socket);
 1834:     $parent_dispatchers{$loncapa_host} = $watcher;
 1835: 
 1836: }
 1837: 
 1838: 
 1839: # listen_on_all_unix_sockets:
 1840: #    This sub initiates a listen on all unix domain lonc client sockets.
 1841: #    This will be called in the case where we are trimming idle processes.
 1842: #    When idle processes are trimmed, loncnew starts up with no children,
 1843: #    and only spawns off children when a connection request occurs on the
 1844: #    client unix socket.  The spawned child continues to run until it has
 1845: #    been idle a while at which point it eventually exits and once more
 1846: #    the parent picks up the listen.
 1847: #
 1848: #  Parameters:
 1849: #      NONE
 1850: #  Implicit Inputs:
 1851: #    The configuration file that has been read in by LondConnection.
 1852: #  Returns:
 1853: #     NONE
 1854: #
 1855: sub listen_on_all_unix_sockets {
 1856:     Debug(5, "listen_on_all_unix_sockets");
 1857:     my $host_iterator      =   &LondConnection::GetHostIterator();
 1858:     while (!$host_iterator->end()) {
 1859: 	my $host_entry_ref =   $host_iterator->get();
 1860: 	my $host_name      = $host_entry_ref->[0];
 1861: 	Debug(9, "Listen for $host_name");
 1862: 	&parent_listen($host_name);
 1863: 	$host_iterator->next();
 1864:     }
 1865: }
 1866: 
 1867: #   server_died is called whenever a child process exits.
 1868: #   Since this is dispatched via a signal, we must process all
 1869: #   dead children until there are no more left.  The action
 1870: #   is to:
 1871: #      - Remove the child from the bookeeping hashes
 1872: #      - Re-establish a listen on the unix domain socket associated
 1873: #        with that host.
 1874: # Parameters:
 1875: #    The event, but we don't actually care about it.
 1876: sub server_died {
 1877:     &Debug(9, "server_died called...");
 1878:     
 1879:     while(1) {			# Loop until waitpid nowait fails.
 1880: 	my $pid = waitpid(-1, WNOHANG);
 1881: 	if($pid <= 0) {
 1882: 	    return;		# Nothing left to wait for.
 1883: 	}
 1884: 	# need the host to restart:
 1885: 
 1886: 	my $host = $ChildHash{$pid};
 1887: 	if($host) {		# It's for real...
 1888: 	    &Debug(9, "Caught sigchild for $host");
 1889: 	    delete($ChildHash{$pid});
 1890: 	    delete($HostToPid{$host});
 1891: 	    &parent_listen($host);
 1892: 
 1893: 	} else {
 1894: 	    &Debug(5, "Caught sigchild for pid not in hosts hash: $pid");
 1895: 	}
 1896:     }
 1897: 
 1898: }
 1899: 
 1900: #
 1901: #  Parent process logic pass 1:
 1902: #   For each entry in the hosts table, we will
 1903: #  fork off an instance of ChildProcess to service the transactions
 1904: #  to that host.  Each pid will be entered in a global hash
 1905: #  with the value of the key, the host.
 1906: #  The parent will then enter a loop to wait for process exits.
 1907: #  Each exit gets logged and the child gets restarted.
 1908: #
 1909: 
 1910: #
 1911: #   Fork and start in new session so hang-up isn't going to 
 1912: #   happen without intent.
 1913: #
 1914: 
 1915: 
 1916: 
 1917: 
 1918: 
 1919: 
 1920: ShowStatus("Forming new session");
 1921: my $childpid = fork;
 1922: if ($childpid != 0) {
 1923:     sleep 4;			# Give child a chacne to break to
 1924:     exit 0;			# a new sesion.
 1925: }
 1926: #
 1927: #   Write my pid into the pid file so I can be located
 1928: #
 1929: 
 1930: ShowStatus("Parent writing pid file:");
 1931: my $execdir = $perlvar{'lonDaemons'};
 1932: open (PIDSAVE, ">$execdir/logs/lonc.pid");
 1933: print PIDSAVE "$$\n";
 1934: close(PIDSAVE);
 1935: 
 1936: 
 1937: 
 1938: if (POSIX::setsid() < 0) {
 1939:     print "Could not create new session\n";
 1940:     exit -1;
 1941: }
 1942: 
 1943: ShowStatus("Forking node servers");
 1944: 
 1945: Log("CRITICAL", "--------------- Starting children ---------------");
 1946: 
 1947: LondConnection::ReadConfig;               # Read standard config files.
 1948: my $HostIterator = LondConnection::GetHostIterator;
 1949: 
 1950: if ($DieWhenIdle) {
 1951:     $RemoteHost = "[parent]";
 1952:     &listen_on_all_unix_sockets();
 1953: } else {
 1954:     
 1955:     while (! $HostIterator->end()) {
 1956: 	
 1957: 	my $hostentryref = $HostIterator->get();
 1958: 	CreateChild($hostentryref->[0]);
 1959: 	$HostHash{$hostentryref->[0]} = $hostentryref->[4];
 1960: 	$HostIterator->next();
 1961:     }
 1962: }
 1963: 
 1964: $RemoteHost = "Parent Server";
 1965: 
 1966: # Maintain the population:
 1967: 
 1968: ShowStatus("Parent keeping the flock");
 1969: 
 1970: 
 1971: if ($DieWhenIdle) {
 1972:     # We need to setup a SIGChild event to handle the exit (natural or otherwise)
 1973:     # of the children.
 1974: 
 1975:     Event->signal(cb       => \&server_died,
 1976: 		   desc     => "Child exit handler",
 1977: 		   signal   => "CHLD");
 1978: 
 1979: 
 1980:     # Set up all the other signals we set up.  We'll vector them off to the
 1981:     # same subs as we would for DieWhenIdle false and, if necessary, conditionalize
 1982:     # the code there.
 1983: 
 1984:     $parent_handlers{INT} = Event->signal(cb       => \&Terminate,
 1985: 					  desc     => "Parent INT handler",
 1986: 					  signal   => "INT");
 1987:     $parent_handlers{TERM} = Event->signal(cb       => \&Terminate,
 1988: 					   desc     => "Parent TERM handler",
 1989: 					   signal   => "TERM");
 1990:     $parent_handlers{HUP}  = Event->signal(cb       => \&Restart,
 1991: 					   desc     => "Parent HUP handler.",
 1992: 					   signal   => "HUP");
 1993:     $parent_handlers{USR1} = Event->signal(cb       => \&CheckKids,
 1994: 					   desc     => "Parent USR1 handler",
 1995: 					   signal   => "USR1");
 1996:     $parent_handlers{USR2} = Event->signal(cb       => \&UpdateKids,
 1997: 					   desc     => "Parent USR2 handler.",
 1998: 					   signal   => "USR2");
 1999:     
 2000:     #  Start procdesing events.
 2001: 
 2002:     $Event::DebugLevel = $DebugLevel;
 2003:     Debug(9, "Parent entering event loop");
 2004:     my $ret = Event::loop();
 2005:     die "Main Event loop exited: $ret";
 2006: 
 2007: 
 2008: } else {
 2009:     #
 2010:     #   Set up parent signals:
 2011:     #
 2012:     
 2013:     $SIG{INT}  = \&Terminate;
 2014:     $SIG{TERM} = \&Terminate; 
 2015:     $SIG{HUP}  = \&Restart;
 2016:     $SIG{USR1} = \&CheckKids; 
 2017:     $SIG{USR2} = \&UpdateKids;	# LonManage update request.
 2018:     
 2019:     while(1) {
 2020: 	my $deadchild = wait();
 2021: 	if(exists $ChildHash{$deadchild}) {	# need to restart.
 2022: 	    my $deadhost = $ChildHash{$deadchild};
 2023: 	    delete($HostToPid{$deadhost});
 2024: 	    delete($ChildHash{$deadchild});
 2025: 	    Log("WARNING","Lost child pid= ".$deadchild.
 2026: 		"Connected to host ".$deadhost);
 2027: 	    Log("INFO", "Restarting child procesing ".$deadhost);
 2028: 	    CreateChild($deadhost);
 2029: 	}
 2030:     }
 2031: }
 2032: 
 2033: 
 2034: =pod
 2035: 
 2036: =head1 CheckKids
 2037: 
 2038:   Since kids do not die as easily in this implementation
 2039: as the previous one, there  is no need to restart the
 2040: dead ones (all dead kids get restarted when they die!!)
 2041: The only thing this function does is to pass USR1 to the
 2042: kids so that they report their status.
 2043: 
 2044: =cut
 2045: 
 2046: sub CheckKids {
 2047:     Debug(2, "Checking status of children");
 2048:     my $docdir = $perlvar{'lonDocRoot'};
 2049:     my $fh = IO::File->new(">$docdir/lon-status/loncstatus.txt");
 2050:     my $now=time;
 2051:     my $local=localtime($now);
 2052:     print $fh "LONC status $local - parent $$ \n\n";
 2053:     foreach my $host (keys %parent_dispatchers) {
 2054: 	print $fh "LONC Parent process listening for $host\n";
 2055:     }
 2056:     foreach my $pid (keys %ChildHash) {
 2057: 	Debug(2, "Sending USR1 -> $pid");
 2058: 	kill 'USR1' => $pid;	# Tell Child to report status.
 2059: 	sleep 1;		# Wait so file doesn't intermix.
 2060:     }
 2061: 
 2062: }
 2063: 
 2064: =pod
 2065: 
 2066: =head1  UpdateKids
 2067: 
 2068: parent's SIGUSR2 handler.  This handler:
 2069: 
 2070: =item
 2071: 
 2072: Rereads the hosts file.
 2073: 
 2074: =item
 2075:  
 2076: Kills off (via sigint) children for hosts that have disappeared.
 2077: 
 2078: =item
 2079: 
 2080: QUITs  children for hosts that already exist (this just forces a status display
 2081: and resets the connection retry count for that host.
 2082: 
 2083: =item
 2084: 
 2085: Starts new children for hosts that have been added to the hosts.tab file since
 2086: the start of the master program and maintains them.
 2087: 
 2088: =cut
 2089: 
 2090: sub UpdateKids {
 2091: 
 2092:     Log("INFO", "Updating connections via SIGUSR2");
 2093: 
 2094:     #  I'm not sure what I was thinking in the first implementation.
 2095:     # someone will have to work hard to convince me the effect is any
 2096:     # different than Restart, especially now that we don't start up 
 2097:     # per host servers automatically, may as well just restart.
 2098:     # The down side is transactions that are in flight will get timed out
 2099:     # (lost unless they are critical).
 2100: 
 2101:     &Restart();
 2102: 
 2103: }
 2104: 
 2105: 
 2106: =pod
 2107: 
 2108: =head1 Restart
 2109: 
 2110: Signal handler for HUP... all children are killed and
 2111: we self restart.  This is an el-cheapo way to re read
 2112: the config file.
 2113: 
 2114: =cut
 2115: 
 2116: sub Restart {
 2117:     &KillThemAll;		# First kill all the children.
 2118:     Log("CRITICAL", "Restarting");
 2119:     my $execdir = $perlvar{'lonDaemons'};
 2120:     unlink("$execdir/logs/lonc.pid");
 2121:     exec("$executable");
 2122: }
 2123: 
 2124: =pod
 2125: 
 2126: =head1 KillThemAll
 2127: 
 2128: Signal handler that kills all children by sending them a 
 2129: SIGHUP.  Responds to sigint and sigterm.
 2130: 
 2131: =cut
 2132: 
 2133: sub KillThemAll {
 2134:     Debug(2, "Kill them all!!");
 2135:     local($SIG{CHLD}) = 'IGNORE';      # Our children >will< die.
 2136:     foreach my $pid (keys %ChildHash) {
 2137: 	my $serving = $ChildHash{$pid};
 2138: 	ShowStatus("Nicely Killing lonc for $serving pid = $pid");
 2139: 	Log("CRITICAL", "Nicely Killing lonc for $serving pid = $pid");
 2140: 	kill 'QUIT' => $pid;
 2141:     }
 2142: 
 2143: 
 2144: }
 2145: 
 2146: 
 2147: #
 2148: #  Kill all children via KILL.  Just in case the
 2149: #  first shot didn't get them.
 2150: 
 2151: sub really_kill_them_all_dammit
 2152: {
 2153:     Debug(2, "Kill them all Dammit");
 2154:     local($SIG{CHLD} = 'IGNORE'); # In case some purist reenabled them.
 2155:     foreach my $pid (keys %ChildHash) {
 2156: 	my $serving = $ChildHash{$pid};
 2157: 	&ShowStatus("Nastily killing lonc for $serving pid = $pid");
 2158: 	Log("CRITICAL", "Nastily killing lonc for $serving pid = $pid");
 2159: 	kill 'KILL' => $pid;
 2160: 	delete($ChildHash{$pid});
 2161: 	my $execdir = $perlvar{'lonDaemons'};
 2162: 	unlink("$execdir/logs/lonc.pid");
 2163:     }
 2164: }
 2165: =pod
 2166: 
 2167: =head1 Terminate
 2168:  
 2169: Terminate the system.
 2170: 
 2171: =cut
 2172: 
 2173: sub Terminate {
 2174:     &Log("CRITICAL", "Asked to kill children.. first be nice...");
 2175:     &KillThemAll;
 2176:     #
 2177:     #  By now they really should all be dead.. but just in case 
 2178:     #  send them all SIGKILL's after a bit of waiting:
 2179: 
 2180:     sleep(4);
 2181:     &Log("CRITICAL", "Now kill children nasty");
 2182:     &really_kill_them_all_dammit;
 2183:     Log("CRITICAL","Master process exiting");
 2184:     exit 0;
 2185: 
 2186: }
 2187: =pod
 2188: 
 2189: =head1 Theory
 2190: 
 2191: The event class is used to build this as a single process with an
 2192: event driven model.  The following events are handled:
 2193: 
 2194: =item UNIX Socket connection Received
 2195: 
 2196: =item Request data arrives on UNIX data transfer socket.
 2197: 
 2198: =item lond connection becomes writable.
 2199: 
 2200: =item timer fires at 1 second intervals.
 2201: 
 2202: All sockets are run in non-blocking mode.  Timeouts managed by the timer
 2203: handler prevents hung connections.
 2204: 
 2205: Key data structures:
 2206: 
 2207: =item RequestQueue
 2208: 
 2209: A queue of requests received from UNIX sockets that are
 2210: waiting for a chance to be forwarded on a lond connection socket.
 2211: 
 2212: =item ActiveConnections
 2213: 
 2214: A hash of lond connections that have transactions in process that are
 2215: available to be timed out.
 2216: 
 2217: =item ActiveTransactions
 2218: 
 2219: A hash indexed by lond connections that contain the client reply
 2220: socket for each connection that has an active transaction on it.
 2221: 
 2222: =item IdleConnections
 2223: 
 2224: A hash of lond connections that have no work to do.  These connections
 2225: can be closed if they are idle for a long enough time.
 2226: 
 2227: =cut

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