Annotation of loncom/loncnew, revision 1.82

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

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