Annotation of loncom/loncnew, revision 1.83

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

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