File:  [LON-CAPA] / loncom / loncnew
Revision 1.67: download - view: text, annotated - select for diffs
Mon Jan 17 22:18:44 2005 UTC (19 years, 3 months ago) by albertel
Branches: MAIN
CVS tags: version_1_3_X, version_1_3_3, version_1_3_2, HEAD
- getting rid of the sleep 1, byy using locking instead

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

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