Annotation of loncom/loncnew, revision 1.64

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

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