File:  [LON-CAPA] / loncom / loncnew
Revision 1.62: download - view: text, annotated - select for diffs
Mon Oct 4 10:30:50 2004 UTC (19 years, 7 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Get the subprocess forking to work.  A lot of stuff still to do (Handling
child exit for one, signals etc. for another), so pleases still leave
DieWhenIdle false.

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

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