File:  [LON-CAPA] / loncom / loncnew
Revision 1.61: download - view: text, annotated - select for diffs
Wed Sep 29 10:37:35 2004 UTC (19 years, 7 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Start adding logic for parent listen.  All this is still conditionalized on
the DieWhenIdle variable, and is incomplete.  Do not set DieWhenIdle to true
as the current effect is DieBeforeStarting. (RF).

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

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