Annotation of loncom/loncnew, revision 1.32

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.32    ! albertel    5: # $Id: loncnew,v 1.31 2003/10/28 10:48:10 foxr Exp $
1.2       albertel    6: #
                      7: # Copyright Michigan State University Board of Trustees
                      8: #
                      9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
1.17      foxr       10: ## LON-CAPA is free software; you can redistribute it and/or modify
1.2       albertel   11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       foxr       28: #
1.15      foxr       29: # new lonc handles n request out bver m connections to londs.
1.1       foxr       30: # This module is based on the Event class.
                     31: #   Development iterations:
                     32: #    - Setup basic event loop.   (done)
                     33: #    - Add timer dispatch.       (done)
                     34: #    - Add ability to accept lonc UNIX domain sockets.  (done)
                     35: #    - Add ability to create/negotiate lond connections (done).
1.7       foxr       36: #    - Add general logic for dispatching requests and timeouts. (done).
                     37: #    - Add support for the lonc/lond requests.          (done).
1.1       foxr       38: #    - Add logging/status monitoring.
                     39: #    - Add Signal handling - HUP restarts. USR1 status report.
1.7       foxr       40: #    - Add Configuration file I/O                       (done).
1.1       foxr       41: #    - Add management/status request interface.
1.8       foxr       42: #    - Add deferred request capability.                  (done)
1.9       foxr       43: #    - Detect transmission timeouts.
1.7       foxr       44: #
                     45: 
1.23      foxr       46: use strict;
1.1       foxr       47: use lib "/home/httpd/lib/perl/";
                     48: use Event qw(:DEFAULT );
                     49: use POSIX qw(:signal_h);
1.12      foxr       50: use POSIX;
1.1       foxr       51: use IO::Socket;
                     52: use IO::Socket::INET;
                     53: use IO::Socket::UNIX;
1.9       foxr       54: use IO::File;
1.6       foxr       55: use IO::Handle;
1.1       foxr       56: use Socket;
                     57: use Crypt::IDEA;
                     58: use LONCAPA::Queue;
                     59: use LONCAPA::Stack;
                     60: use LONCAPA::LondConnection;
1.7       foxr       61: use LONCAPA::LondTransaction;
1.1       foxr       62: use LONCAPA::Configuration;
                     63: use LONCAPA::HashIterator;
                     64: 
                     65: 
                     66: #
                     67: #   Disable all signals we might receive from outside for now.
                     68: #
                     69: 
                     70: 
                     71: # Read the httpd configuration file to get perl variables
                     72: # normally set in apache modules:
                     73: 
                     74: my $perlvarref = LONCAPA::Configuration::read_conf('loncapa.conf');
                     75: my %perlvar    = %{$perlvarref};
                     76: 
                     77: #
                     78: #  parent and shared variables.
                     79: 
                     80: my %ChildHash;			# by pid -> host.
1.26      foxr       81: my %HostToPid;			# By host -> pid.
                     82: my %HostHash;			# by loncapaname -> IP.
1.1       foxr       83: 
                     84: 
1.9       foxr       85: my $MaxConnectionCount = 10;	# Will get from config later.
1.1       foxr       86: my $ClientConnection = 0;	# Uniquifier for client events.
                     87: 
1.9       foxr       88: my $DebugLevel = 0;
1.29      foxr       89: my $NextDebugLevel= 2;		# So Sigint can toggle this.
1.1       foxr       90: my $IdleTimeout= 3600;		# Wait an hour before pruning connections.
                     91: 
                     92: #
                     93: #  The variables below are only used by the child processes.
                     94: #
                     95: my $RemoteHost;			# Name of host child is talking to.
1.20      albertel   96: my $UnixSocketDir= $perlvar{'lonSockDir'};
1.1       foxr       97: my $IdleConnections = Stack->new(); # Set of idle connections
                     98: my %ActiveConnections;		# Connections to the remote lond.
1.7       foxr       99: my %ActiveTransactions;		# LondTransactions in flight.
1.1       foxr      100: my %ActiveClients;		# Serial numbers of active clients by socket.
                    101: my $WorkQueue       = Queue->new(); # Queue of pending transactions.
                    102: my $ConnectionCount = 0;
1.4       foxr      103: my $IdleSeconds     = 0;	# Number of seconds idle.
1.9       foxr      104: my $Status          = "";	# Current status string.
1.14      foxr      105: my $RecentLogEntry  = "";
1.30      foxr      106: my $ConnectionRetries=2;	# Number of connection retries allowed.
                    107: my $ConnectionRetriesLeft=2;	# Number of connection retries remaining.
1.1       foxr      108: 
                    109: #
1.9       foxr      110: #   The hash below gives the HTML format for log messages
                    111: #   given a severity.
                    112: #    
                    113: my %LogFormats;
                    114: 
                    115: $LogFormats{"CRITICAL"} = "<font color=red>CRITICAL: %s</font>";
                    116: $LogFormats{"SUCCESS"}  = "<font color=green>SUCCESS: %s</font>";
                    117: $LogFormats{"INFO"}     = "<font color=yellow>INFO: %s</font>";
                    118: $LogFormats{"WARNING"}  = "<font color=blue>WARNING: %s</font>";
                    119: $LogFormats{"DEFAULT"}  = " %s ";
                    120: 
1.10      foxr      121: 
                    122: 
                    123: =pod
                    124: 
                    125: =head2 LogPerm
                    126: 
                    127: Makes an entry into the permanent log file.
                    128: 
                    129: =cut
                    130: sub LogPerm {
                    131:     my $message=shift;
                    132:     my $execdir=$perlvar{'lonDaemons'};
                    133:     my $now=time;
                    134:     my $local=localtime($now);
                    135:     my $fh=IO::File->new(">>$execdir/logs/lonnet.perm.log");
                    136:     print $fh "$now:$message:$local\n";
                    137: }
1.9       foxr      138: 
                    139: =pod
                    140: 
                    141: =head2 Log
                    142: 
                    143: Logs a message to the log file.
                    144: Parameters:
                    145: 
                    146: =item severity
                    147: 
                    148: One of CRITICAL, WARNING, INFO, SUCCESS used to select the
                    149: format string used to format the message.  if the severity is
                    150: not a defined severity the Default format string is used.
                    151: 
                    152: =item message
                    153: 
                    154: The base message.  In addtion to the format string, the message
                    155: will be appended to a string containing the name of our remote
                    156: host and the time will be formatted into the message.
                    157: 
                    158: =cut
                    159: 
                    160: sub Log {
                    161:     my $severity = shift;
                    162:     my $message  = shift;
                    163:    
                    164:     if(!$LogFormats{$severity}) {
                    165: 	$severity = "DEFAULT";
                    166:     }
                    167: 
                    168:     my $format = $LogFormats{$severity};
                    169:     
                    170:     #  Put the window dressing in in front of the message format:
                    171: 
                    172:     my $now   = time;
                    173:     my $local = localtime($now);
                    174:     my $finalformat = "$local ($$) [$RemoteHost] [$Status] ";
                    175:     my $finalformat = $finalformat.$format."\n";
                    176: 
                    177:     # open the file and put the result.
                    178: 
                    179:     my $execdir = $perlvar{'lonDaemons'};
                    180:     my $fh      = IO::File->new(">>$execdir/logs/lonc.log");
                    181:     my $msg = sprintf($finalformat, $message);
1.14      foxr      182:     $RecentLogEntry = $msg;
1.9       foxr      183:     print $fh $msg;
                    184:     
1.10      foxr      185:     
1.9       foxr      186: }
1.6       foxr      187: 
1.3       albertel  188: 
1.1       foxr      189: =pod
1.3       albertel  190: 
                    191: =head2 GetPeerName
                    192: 
                    193: Returns the name of the host that a socket object is connected to.
                    194: 
1.1       foxr      195: =cut
                    196: 
                    197: sub GetPeername {
                    198:     my $connection = shift;
                    199:     my $AdrFamily  = shift;
                    200:     my $peer       = $connection->peername();
                    201:     my $peerport;
                    202:     my $peerip;
                    203:     if($AdrFamily == AF_INET) {
                    204: 	($peerport, $peerip) = sockaddr_in($peer);
1.23      foxr      205: 	my $peername    = gethostbyaddr($peerip, $AdrFamily);
1.1       foxr      206: 	return $peername;
                    207:     } elsif ($AdrFamily == AF_UNIX) {
                    208: 	my $peerfile;
                    209: 	($peerfile) = sockaddr_un($peer);
                    210: 	return $peerfile;
                    211:     }
                    212: }
                    213: #----------------------------- Timer management ------------------------
                    214: =pod
1.3       albertel  215: 
1.1       foxr      216: =head2 Debug
1.3       albertel  217: 
                    218: Invoked to issue a debug message.
                    219: 
1.1       foxr      220: =cut
1.3       albertel  221: 
1.1       foxr      222: sub Debug {
                    223:     my $level   = shift;
                    224:     my $message = shift;
                    225:     if ($level <= $DebugLevel) {
1.23      foxr      226: 	Log("INFO", "-Debug- $message host = $RemoteHost");
1.1       foxr      227:     }
                    228: }
                    229: 
                    230: sub SocketDump {
                    231:     my $level = shift;
                    232:     my $socket= shift;
                    233:     if($level <= $DebugLevel) {
                    234: 	$socket->Dump();
                    235:     }
                    236: }
1.3       albertel  237: 
1.1       foxr      238: =pod
1.3       albertel  239: 
1.5       foxr      240: =head2 ShowStatus
                    241: 
                    242:  Place some text as our pid status.
1.10      foxr      243:  and as what we return in a SIGUSR1
1.5       foxr      244: 
                    245: =cut
                    246: sub ShowStatus {
1.10      foxr      247:     my $state = shift;
                    248:     my $now = time;
                    249:     my $local = localtime($now);
                    250:     $Status   = $local.": ".$state;
                    251:     $0='lonc: '.$state.' '.$local;
1.5       foxr      252: }
                    253: 
                    254: =pod
                    255: 
1.15      foxr      256: =head 2 SocketTimeout
                    257: 
                    258:     Called when an action on the socket times out.  The socket is 
                    259:    destroyed and any active transaction is failed.
                    260: 
                    261: 
                    262: =cut
                    263: sub SocketTimeout {
                    264:     my $Socket = shift;
                    265:     
1.22      foxr      266:     KillSocket($Socket);	# A transaction timeout also counts as
                    267:                                 # a connection failure:
                    268:     $ConnectionRetriesLeft--;
1.15      foxr      269: }
                    270: 
                    271: =pod
                    272: 
1.1       foxr      273: =head2 Tick
1.3       albertel  274: 
                    275: Invoked  each timer tick.
                    276: 
1.1       foxr      277: =cut
                    278: 
1.5       foxr      279: 
1.1       foxr      280: sub Tick {
                    281:     my $client;
1.22      foxr      282:     if($ConnectionRetriesLeft > 0) {
                    283: 	ShowStatus(GetServerHost()." Connection count: ".$ConnectionCount
                    284: 		   ." Retries remaining: ".$ConnectionRetriesLeft);
                    285:     } else {
                    286: 	ShowStatus(GetServerHost()." >> DEAD <<");
                    287:     }
1.4       foxr      288:     # Is it time to prune connection count:
                    289: 
                    290: 
                    291:     if($IdleConnections->Count()  && 
                    292:        ($WorkQueue->Count() == 0)) { # Idle connections and nothing to do?
                    293: 	$IdleSeconds++;
                    294: 	if($IdleSeconds > $IdleTimeout) { # Prune a connection...
1.23      foxr      295: 	    my $Socket = $IdleConnections->pop();
1.6       foxr      296: 	    KillSocket($Socket);
1.4       foxr      297: 	}
                    298:     } else {
                    299: 	$IdleSeconds = 0;	# Reset idle count if not idle.
                    300:     }
1.15      foxr      301:     #
                    302:     #  For each inflight transaction, tick down its timeout counter.
                    303:     #
1.23      foxr      304:     foreach my $item (keys %ActiveTransactions) {
1.15      foxr      305: 	my $Socket = $ActiveTransactions{$item}->getServer();
                    306: 	$Socket->Tick();
                    307:     }
1.5       foxr      308:     # Do we have work in the queue, but no connections to service them?
                    309:     # If so, try to make some new connections to get things going again.
                    310:     #
                    311:     
                    312:     my $Requests = $WorkQueue->Count();
1.10      foxr      313:     if (($ConnectionCount == 0)  && ($Requests > 0)) { 
                    314: 	if ($ConnectionRetriesLeft > 0) {
                    315: 	    my $Connections = ($Requests <= $MaxConnectionCount) ?
                    316: 		$Requests : $MaxConnectionCount;
1.29      foxr      317: 	    Debug(5,"Work but no connections, start ".$Connections." of them");
1.22      foxr      318: 	    my $successCount = 0;
1.23      foxr      319: 	    for (my $i =0; $i < $Connections; $i++) {
1.22      foxr      320: 		$successCount += MakeLondConnection();
                    321: 	    }
                    322: 	    if($successCount == 0) { # All connections failed:
1.29      foxr      323: 		Debug(5,"Work in queue failed to make any connectiouns\n");
1.22      foxr      324: 		EmptyQueue();	# Fail pending transactions with con_lost.
1.10      foxr      325: 	    }
                    326: 	} else {
1.22      foxr      327: 	    ShowStatus(GetServerHost()." >>> DEAD!!! <<<");
1.29      foxr      328: 	    Debug(5,"Work in queue, but gave up on connections..flushing\n");
1.10      foxr      329: 	    EmptyQueue();	# Connections can't be established.
1.5       foxr      330: 	}
                    331:        
                    332:     }
1.1       foxr      333: }
                    334: 
                    335: =pod
1.3       albertel  336: 
1.1       foxr      337: =head2 SetupTimer
                    338: 
1.3       albertel  339: Sets up a 1 per sec recurring timer event.  The event handler is used to:
1.1       foxr      340: 
1.3       albertel  341: =item
                    342: 
                    343: Trigger timeouts on communications along active sockets.
                    344: 
                    345: =item
                    346: 
                    347: Trigger disconnections of idle sockets.
1.1       foxr      348: 
                    349: =cut
                    350: 
                    351: sub SetupTimer {
                    352:     Debug(6, "SetupTimer");
                    353:     Event->timer(interval => 1, debug => 1, cb => \&Tick );
                    354: }
1.3       albertel  355: 
1.1       foxr      356: =pod
1.3       albertel  357: 
1.1       foxr      358: =head2 ServerToIdle
1.3       albertel  359: 
                    360: This function is called when a connection to the server is
                    361: ready for more work.
                    362: 
                    363: If there is work in the Work queue the top element is dequeued
1.1       foxr      364: and the connection will start to work on it.  If the work queue is
                    365: empty, the connection is pushed on the idle connection stack where
                    366: it will either get another work unit, or alternatively, if it sits there
                    367: long enough, it will be shut down and released.
                    368: 
1.3       albertel  369: =cut
1.1       foxr      370: 
                    371: sub ServerToIdle {
                    372:     my $Socket   = shift;	# Get the socket.
1.7       foxr      373:     delete($ActiveTransactions{$Socket}); # Server has no transaction
1.1       foxr      374: 
1.29      foxr      375:     &Debug(5, "Server to idle");
1.1       foxr      376: 
                    377:     #  If there's work to do, start the transaction:
                    378: 
1.23      foxr      379:     my $reqdata = $WorkQueue->dequeue(); # This is a LondTransaction
1.29      foxr      380:     if ($reqdata ne undef)  {
                    381: 	Debug(5, "Queue gave request data: ".$reqdata->getRequest());
1.7       foxr      382: 	&StartRequest($Socket,  $reqdata);
1.8       foxr      383: 
1.1       foxr      384:     } else {
                    385: 	
                    386:     #  There's no work waiting, so push the server to idle list.
1.29      foxr      387: 	&Debug(5, "No new work requests, server connection going idle");
1.1       foxr      388: 	$IdleConnections->push($Socket);
                    389:     }
                    390: }
1.3       albertel  391: 
1.1       foxr      392: =pod
1.3       albertel  393: 
1.1       foxr      394: =head2 ClientWritable
1.3       albertel  395: 
                    396: Event callback for when a client socket is writable.
                    397: 
                    398: This callback is established when a transaction reponse is
                    399: avaiable from lond.  The response is forwarded to the unix socket
                    400: as it becomes writable in this sub.
                    401: 
1.1       foxr      402: Parameters:
                    403: 
1.3       albertel  404: =item Event
                    405: 
                    406: The event that has been triggered. Event->w->data is
                    407: the data and Event->w->fd is the socket to write.
1.1       foxr      408: 
                    409: =cut
1.3       albertel  410: 
1.1       foxr      411: sub ClientWritable {
                    412:     my $Event    = shift;
                    413:     my $Watcher  = $Event->w;
                    414:     my $Data     = $Watcher->data;
                    415:     my $Socket   = $Watcher->fd;
                    416: 
                    417:     # Try to send the data:
                    418: 
                    419:     &Debug(6, "ClientWritable writing".$Data);
                    420:     &Debug(9, "Socket is: ".$Socket);
                    421: 
1.6       foxr      422:     if($Socket->connected) {
                    423: 	my $result = $Socket->send($Data, 0);
                    424: 	
                    425: 	# $result undefined: the write failed.
                    426: 	# otherwise $result is the number of bytes written.
                    427: 	# Remove that preceding string from the data.
                    428: 	# If the resulting data is empty, destroy the watcher
                    429: 	# and set up a read event handler to accept the next
                    430: 	# request.
                    431: 	
                    432: 	&Debug(9,"Send result is ".$result." Defined: ".defined($result));
1.29      foxr      433: 	if($result ne undef) {
1.6       foxr      434: 	    &Debug(9, "send result was defined");
                    435: 	    if($result == length($Data)) { # Entire string sent.
                    436: 		&Debug(9, "ClientWritable data all written");
                    437: 		$Watcher->cancel();
                    438: 		#
                    439: 		#  Set up to read next request from socket:
                    440: 		
                    441: 		my $descr     = sprintf("Connection to lonc client %d",
                    442: 					$ActiveClients{$Socket});
                    443: 		Event->io(cb    => \&ClientRequest,
                    444: 			  poll  => 'r',
                    445: 			  desc  => $descr,
                    446: 			  data  => "",
                    447: 			  fd    => $Socket);
                    448: 		
                    449: 	    } else {		# Partial string sent.
                    450: 		$Watcher->data(substr($Data, $result));
1.15      foxr      451: 		if($result == 0) {    # client hung up on us!!
                    452: 		    Log("INFO", "lonc pipe client hung up on us!");
                    453: 		    $Watcher->cancel;
                    454: 		    $Socket->shutdown(2);
                    455: 		    $Socket->close();
                    456: 		}
1.6       foxr      457: 	    }
                    458: 	    
                    459: 	} else {			# Error of some sort...
                    460: 	    
                    461: 	    # Some errnos are possible:
                    462: 	    my $errno = $!;
                    463: 	    if($errno == POSIX::EWOULDBLOCK   ||
                    464: 	       $errno == POSIX::EAGAIN        ||
                    465: 	       $errno == POSIX::EINTR) {
                    466: 		# No action taken?
                    467: 	    } else {		# Unanticipated errno.
                    468: 		&Debug(5,"ClientWritable error or peer shutdown".$RemoteHost);
                    469: 		$Watcher->cancel;	# Stop the watcher.
                    470: 		$Socket->shutdown(2); # Kill connection
                    471: 		$Socket->close();	# Close the socket.
                    472: 	    }
1.1       foxr      473: 	    
                    474: 	}
1.6       foxr      475:     } else {
                    476: 	$Watcher->cancel();	# A delayed request...just cancel.
1.1       foxr      477:     }
                    478: }
                    479: 
                    480: =pod
1.3       albertel  481: 
1.1       foxr      482: =head2 CompleteTransaction
1.3       albertel  483: 
                    484: Called when the reply data has been received for a lond 
1.1       foxr      485: transaction.   The reply data must now be sent to the
                    486: ultimate client on the other end of the Unix socket.  This is
                    487: done by setting up a writable event for the socket with the
                    488: data the reply data.
1.3       albertel  489: 
1.1       foxr      490: Parameters:
1.3       albertel  491: 
                    492: =item Socket
                    493: 
                    494: Socket on which the lond transaction occured.  This is a
                    495: LondConnection. The data received is in the TransactionReply member.
                    496: 
1.7       foxr      497: =item Transaction
1.3       albertel  498: 
1.7       foxr      499: The transaction that is being completed.
1.1       foxr      500: 
                    501: =cut
1.3       albertel  502: 
1.1       foxr      503: sub CompleteTransaction {
1.29      foxr      504:     &Debug(5,"Complete transaction");
1.1       foxr      505:     my $Socket = shift;
1.7       foxr      506:     my $Transaction = shift;
1.1       foxr      507: 
1.7       foxr      508:     if (!$Transaction->isDeferred()) { # Normal transaction
                    509: 	my $data   = $Socket->GetReply(); # Data to send.
                    510: 	StartClientReply($Transaction, $data);
                    511:     } else {			# Delete deferred transaction file.
1.9       foxr      512: 	Log("SUCCESS", "A delayed transaction was completed");
1.23      foxr      513: 	LogPerm("S:$Transaction->getClient() :".$Transaction->getRequest());
1.7       foxr      514: 	unlink $Transaction->getFile();
                    515:     }
1.6       foxr      516: }
                    517: =pod
                    518: =head1 StartClientReply
                    519: 
                    520:    Initiates a reply to a client where the reply data is a parameter.
                    521: 
1.7       foxr      522: =head2  parameters:
                    523: 
                    524: =item Transaction
                    525: 
                    526:     The transaction for which we are responding to the client.
                    527: 
                    528: =item data
                    529: 
                    530:     The data to send to apached client.
                    531: 
1.6       foxr      532: =cut
                    533: sub StartClientReply {
1.7       foxr      534:     my $Transaction   = shift;
1.6       foxr      535:     my $data     = shift;
1.1       foxr      536: 
1.12      foxr      537: 
1.7       foxr      538:     my $Client   = $Transaction->getClient();
                    539: 
1.1       foxr      540:     &Debug(8," Reply was: ".$data);
                    541:     my $Serial         = $ActiveClients{$Client};
                    542:     my $desc           = sprintf("Connection to lonc client %d",
                    543: 				 $Serial);
                    544:     Event->io(fd       => $Client,
                    545: 	      poll     => "w",
                    546: 	      desc     => $desc,
                    547: 	      cb       => \&ClientWritable,
                    548: 	      data     => $data);
                    549: }
1.4       foxr      550: =pod
                    551: =head2 FailTransaction
                    552: 
                    553:   Finishes a transaction with failure because the associated lond socket
1.7       foxr      554:   disconnected.  There are two possibilities:
                    555:   - The transaction is deferred: in which case we just quietly
                    556:     delete the transaction since there is no client connection.
                    557:   - The transaction is 'live' in which case we initiate the sending
                    558:     of "con_lost" to the client.
                    559: 
                    560: Deleting the transaction means killing it from the 
                    561: %ActiveTransactions hash.
1.4       foxr      562: 
                    563: Parameters:
                    564: 
                    565: =item client  
                    566:  
1.7       foxr      567:    The LondTransaction we are failing.
                    568:  
1.4       foxr      569: =cut
                    570: 
                    571: sub FailTransaction {
1.7       foxr      572:     my $transaction = shift;
1.17      foxr      573:     Log("WARNING", "Failing transaction ".$transaction->getRequest());
1.30      foxr      574:     Debug(1, "Failing transaction: ".$transaction->getRequest());
1.10      foxr      575:     if (!$transaction->isDeferred()) { # If the transaction is deferred we'll get to it.
1.11      foxr      576: 	my $client  = $transaction->getClient();
1.30      foxr      577: 	Debug(1," Replying con_lost to ".$transaction->getRequest());
1.11      foxr      578: 	StartClientReply($transaction, "con_lost\n");
1.7       foxr      579:     }
1.22      foxr      580:     if($ConnectionRetriesLeft <= 0) {
                    581: 	Log("CRITICAL", "Host marked dead: ".GetServerHost());
                    582:     }
1.4       foxr      583: 
                    584: }
                    585: 
                    586: =pod
1.6       foxr      587: =head1  EmptyQueue
1.7       foxr      588: 
1.6       foxr      589:   Fails all items in the work queue with con_lost.
1.7       foxr      590:   Note that each item in the work queue is a transaction.
                    591: 
1.6       foxr      592: =cut
                    593: sub EmptyQueue {
1.22      foxr      594:     $ConnectionRetriesLeft--;	# Counts as connection failure too.
1.6       foxr      595:     while($WorkQueue->Count()) {
1.10      foxr      596: 	my $request = $WorkQueue->dequeue(); # This is a transaction
1.7       foxr      597: 	FailTransaction($request);
1.6       foxr      598:     }
                    599: }
                    600: 
                    601: =pod
1.4       foxr      602: 
1.9       foxr      603: =head2 CloseAllLondConnections
                    604: 
                    605: Close all connections open on lond prior to exit e.g.
                    606: 
                    607: =cut
                    608: sub CloseAllLondConnections {
1.23      foxr      609:     foreach my $Socket (keys %ActiveConnections) {
1.9       foxr      610: 	KillSocket($Socket);
                    611:     }
                    612: }
                    613: =cut
                    614: 
                    615: =pod
                    616: 
1.4       foxr      617: =head2 KillSocket
                    618:  
                    619: Destroys a socket.  This function can be called either when a socket
                    620: has died of 'natural' causes or because a socket needs to be pruned due to
                    621: idleness.  If the socket has died naturally, if there are no longer any 
                    622: live connections a new connection is created (in case there are transactions
                    623: in the queue).  If the socket has been pruned, it is never re-created.
                    624: 
                    625: Parameters:
1.1       foxr      626: 
1.4       foxr      627: =item Socket
                    628:  
                    629:   The socket to kill off.
                    630: 
                    631: =item Restart
                    632: 
                    633: nonzero if we are allowed to create a new connection.
                    634: 
                    635: 
                    636: =cut
                    637: sub KillSocket {
                    638:     my $Socket = shift;
                    639: 
1.17      foxr      640:     Log("WARNING", "Shutting down a socket");
1.9       foxr      641:     $Socket->Shutdown();
                    642: 
1.7       foxr      643:     #  If the socket came from the active connection set,
                    644:     #  delete its transaction... note that FailTransaction should
                    645:     #  already have been called!!!
                    646:     #  otherwise it came from the idle set.
                    647:     #  
1.4       foxr      648:     
                    649:     if(exists($ActiveTransactions{$Socket})) {
                    650: 	delete ($ActiveTransactions{$Socket});
                    651:     }
                    652:     if(exists($ActiveConnections{$Socket})) {
                    653: 	delete($ActiveConnections{$Socket});
                    654:     }
                    655:     $ConnectionCount--;
1.6       foxr      656: 
                    657:     #  If the connection count has gone to zero and there is work in the
                    658:     #  work queue, the work all gets failed with con_lost.
                    659:     #
                    660:     if($ConnectionCount == 0) {
1.22      foxr      661: 	EmptyQueue();
1.4       foxr      662:     }
                    663: }
1.1       foxr      664: 
                    665: =pod
1.3       albertel  666: 
1.1       foxr      667: =head2 LondReadable
1.3       albertel  668: 
1.1       foxr      669: This function is called whenever a lond connection
                    670: is readable.  The action is state dependent:
                    671: 
1.3       albertel  672: =head3 State=Initialized
                    673: 
                    674: We''re waiting for the challenge, this is a no-op until the
1.1       foxr      675: state changes.
1.3       albertel  676: 
1.1       foxr      677: =head3 State=Challenged 
1.3       albertel  678: 
                    679: The challenge has arrived we need to transition to Writable.
1.1       foxr      680: The connection must echo the challenge back.
1.3       albertel  681: 
1.1       foxr      682: =head3 State=ChallengeReplied
1.3       albertel  683: 
                    684: The challenge has been replied to.  The we are receiveing the 
1.1       foxr      685: 'ok' from the partner.
1.3       albertel  686: 
1.1       foxr      687: =head3 State=RequestingKey
1.3       albertel  688: 
                    689: The ok has been received and we need to send the request for
1.1       foxr      690: an encryption key.  Transition to writable for that.
1.3       albertel  691: 
1.1       foxr      692: =head3 State=ReceivingKey
1.3       albertel  693: 
                    694: The the key has been requested, now we are reading the new key.
                    695: 
1.1       foxr      696: =head3 State=Idle 
1.3       albertel  697: 
                    698: The encryption key has been negotiated or we have finished 
1.1       foxr      699: reading data from the a transaction.   If the callback data has
                    700: a client as well as the socket iformation, then we are 
                    701: doing a transaction and the data received is relayed to the client
                    702: before the socket is put on the idle list.
1.3       albertel  703: 
1.1       foxr      704: =head3 State=SendingRequest
1.3       albertel  705: 
                    706: I do not think this state can be received here, but if it is,
1.1       foxr      707: the appropriate thing to do is to transition to writable, and send
                    708: the request.
1.3       albertel  709: 
1.1       foxr      710: =head3 State=ReceivingReply
1.3       albertel  711: 
                    712: We finished sending the request to the server and now transition
1.1       foxr      713: to readable to receive the reply. 
                    714: 
                    715: The parameter to this function are:
1.3       albertel  716: 
1.1       foxr      717: The event. Implicit in this is the watcher and its data.  The data 
                    718: contains at least the lond connection object and, if a 
                    719: transaction is in progress, the socket attached to the local client.
                    720: 
1.3       albertel  721: =cut
1.1       foxr      722: 
                    723: sub LondReadable {
1.8       foxr      724: 
1.1       foxr      725:     my $Event      = shift;
                    726:     my $Watcher    = $Event->w;
                    727:     my $Socket     = $Watcher->data;
                    728:     my $client     = undef;
                    729: 
1.23      foxr      730:     &Debug(6,"LondReadable called state = ".$Socket->GetState());
1.8       foxr      731: 
1.1       foxr      732: 
                    733:     my $State = $Socket->GetState(); # All action depends on the state.
                    734: 
                    735:     SocketDump(6, $Socket);
1.12      foxr      736:     my $status = $Socket->Readable();
1.17      foxr      737: 
1.12      foxr      738:     &Debug(2, "Socket->Readable returned: $status");
1.1       foxr      739: 
1.12      foxr      740:     if($status != 0) {
1.4       foxr      741: 	 # bad return from socket read. Currently this means that
                    742: 	# The socket has become disconnected. We fail the transaction.
                    743: 
1.17      foxr      744: 	Log("WARNING",
                    745: 	    "Lond connection lost.");
1.4       foxr      746: 	if(exists($ActiveTransactions{$Socket})) {
                    747: 	    FailTransaction($ActiveTransactions{$Socket});
                    748: 	}
                    749: 	$Watcher->cancel();
1.6       foxr      750: 	KillSocket($Socket);
1.22      foxr      751: 	$ConnectionRetriesLeft--;       # Counts as connection failure
1.4       foxr      752: 	return;
1.1       foxr      753:     }
                    754:     SocketDump(6,$Socket);
                    755: 
                    756:     $State = $Socket->GetState(); # Update in case of transition.
                    757:     &Debug(6, "After read, state is ".$State);
                    758: 
                    759:    if($State eq "Initialized") {
                    760: 
                    761: 
                    762:     } elsif ($State eq "ChallengeReceived") {
                    763: 	#  The challenge must be echoed back;  The state machine
                    764: 	# in the connection takes care of setting that up.  Just
                    765: 	# need to transition to writable:
                    766: 
1.8       foxr      767: 	$Watcher->cb(\&LondWritable);
1.1       foxr      768: 	$Watcher->poll("w");
                    769: 
                    770:     } elsif ($State eq "ChallengeReplied") {
                    771: 
                    772: 
                    773:     } elsif ($State eq "RequestingKey") {
                    774: 	#  The ok was received.  Now we need to request the key
                    775: 	#  That requires us to be writable:
                    776: 
1.8       foxr      777: 	$Watcher->cb(\&LondWritable);
1.1       foxr      778: 	$Watcher->poll("w");
                    779: 
                    780:     } elsif ($State eq "ReceivingKey") {
                    781: 
                    782:     } elsif ($State eq "Idle") {
                    783: 	# If necessary, complete a transaction and then go into the
                    784: 	# idle queue.
1.22      foxr      785: 	#  Note that a trasition to idle indicates a live lond
                    786: 	# on the other end so reset the connection retries.
                    787: 	#
                    788: 	$ConnectionRetriesLeft = $ConnectionRetries; # success resets the count
1.8       foxr      789: 	$Watcher->cancel();
1.1       foxr      790: 	if(exists($ActiveTransactions{$Socket})) {
1.29      foxr      791: 	    Debug(5,"Completing transaction!!");
1.1       foxr      792: 	    CompleteTransaction($Socket, 
                    793: 				$ActiveTransactions{$Socket});
1.9       foxr      794: 	} else {
                    795: 	    Log("SUCCESS", "Connection ".$ConnectionCount." to "
                    796: 		.$RemoteHost." now ready for action");
1.1       foxr      797: 	}
                    798: 	ServerToIdle($Socket);	# Next work unit or idle.
1.6       foxr      799: 	
1.1       foxr      800:     } elsif ($State eq "SendingRequest") {
                    801: 	#  We need to be writable for this and probably don't belong
                    802: 	#  here inthe first place.
                    803: 
                    804: 	Deubg(6, "SendingRequest state encountered in readable");
                    805: 	$Watcher->poll("w");
                    806: 	$Watcher->cb(\&LondWritable);
                    807: 
                    808:     } elsif ($State eq "ReceivingReply") {
                    809: 
                    810: 
                    811:     } else {
                    812: 	 # Invalid state.
                    813: 	Debug(4, "Invalid state in LondReadable");
                    814:     }
                    815: }
1.3       albertel  816: 
1.1       foxr      817: =pod
1.3       albertel  818: 
1.1       foxr      819: =head2 LondWritable
1.3       albertel  820: 
1.1       foxr      821: This function is called whenever a lond connection
                    822: becomes writable while there is a writeable monitoring
                    823: event.  The action taken is very state dependent:
1.3       albertel  824: 
1.1       foxr      825: =head3 State = Connected 
1.3       albertel  826: 
                    827: The connection is in the process of sending the 'init' hailing to the
                    828: lond on the remote end.  The connection object''s Writable member is
                    829: called.  On error, ConnectionError is called to destroy the connection
                    830: and remove it from the ActiveConnections hash
                    831: 
1.1       foxr      832: =head3 Initialized
1.3       albertel  833: 
                    834: 'init' has been sent, writability monitoring is removed and
                    835: readability monitoring is started with LondReadable as the callback.
                    836: 
1.1       foxr      837: =head3 ChallengeReceived
1.3       albertel  838: 
                    839: The connection has received the who are you challenge from the remote
                    840: system, and is in the process of sending the challenge
                    841: response. Writable is called.
                    842: 
1.1       foxr      843: =head3 ChallengeReplied
1.3       albertel  844: 
                    845: The connection has replied to the initial challenge The we switch to
                    846: monitoring readability looking for the server to reply with 'ok'.
                    847: 
1.1       foxr      848: =head3 RequestingKey
1.3       albertel  849: 
                    850: The connection is in the process of requesting its encryption key.
                    851: Writable is called.
                    852: 
1.1       foxr      853: =head3 ReceivingKey
1.3       albertel  854: 
                    855: The connection has sent the request for a key.  Switch to readability
                    856: monitoring to accept the key
                    857: 
1.1       foxr      858: =head3 SendingRequest
1.3       albertel  859: 
                    860: The connection is in the process of sending a request to the server.
                    861: This request is part of a client transaction.  All the states until
                    862: now represent the client setup protocol. Writable is called.
                    863: 
1.1       foxr      864: =head3 ReceivingReply
                    865: 
1.3       albertel  866: The connection has sent a request.  Now it must receive a reply.
                    867: Readability monitoring is requested.
                    868: 
                    869: This function is an event handler and therefore receives as
1.1       foxr      870: a parameter the event that has fired.  The data for the watcher
                    871: of this event is a reference to a list of one or two elements,
                    872: depending on state. The first (and possibly only) element is the
                    873: socket.  The second (present only if a request is in progress)
                    874: is the socket on which to return a reply to the caller.
                    875: 
                    876: =cut
1.3       albertel  877: 
1.1       foxr      878: sub LondWritable {
                    879:     my $Event   = shift;
                    880:     my $Watcher = $Event->w;
1.8       foxr      881:     my $Socket  = $Watcher->data;
                    882:     my $State   = $Socket->GetState();
1.1       foxr      883: 
1.8       foxr      884:     Debug(6,"LondWritable State = ".$State."\n");
1.1       foxr      885: 
1.8       foxr      886:  
1.1       foxr      887:     #  Figure out what to do depending on the state of the socket:
                    888:     
                    889: 
                    890: 
                    891: 
                    892:     SocketDump(6,$Socket);
                    893: 
                    894:     if      ($State eq "Connected")         {
                    895: 
                    896: 	if ($Socket->Writable() != 0) {
                    897: 	    #  The write resulted in an error.
1.4       foxr      898: 	    # We'll treat this as if the socket got disconnected:
1.9       foxr      899: 	    Log("WARNING", "Connection to ".$RemoteHost.
                    900: 		" has been disconnected");
1.18      foxr      901: 	    FailTransaction($ActiveTransactions{$Socket});
1.4       foxr      902: 	    $Watcher->cancel();
1.6       foxr      903: 	    KillSocket($Socket);
1.4       foxr      904: 	    return;
1.1       foxr      905: 	}
1.4       foxr      906: 	#  "init" is being sent...
                    907: 
1.1       foxr      908: 	
                    909:     } elsif ($State eq "Initialized")       {
                    910: 
                    911: 	# Now that init was sent, we switch 
                    912: 	# to watching for readability:
                    913: 
1.8       foxr      914: 	$Watcher->cb(\&LondReadable);
1.1       foxr      915: 	$Watcher->poll("r");
                    916: 
                    917:     } elsif ($State eq "ChallengeReceived") {
                    918: 	# We received the challenge, now we 
                    919: 	# are echoing it back. This is a no-op,
                    920: 	# we're waiting for the state to change
                    921: 	
                    922: 	if($Socket->Writable() != 0) {
1.5       foxr      923: 
                    924: 	    $Watcher->cancel();
1.6       foxr      925: 	    KillSocket($Socket);
1.5       foxr      926: 	    return;
1.1       foxr      927: 	}
                    928: 	
                    929:     } elsif ($State eq "ChallengeReplied")  {
                    930: 	# The echo was sent back, so we switch
                    931: 	# to watching readability.
                    932: 
1.8       foxr      933: 	$Watcher->cb(\&LondReadable);
1.1       foxr      934: 	$Watcher->poll("r");
                    935: 
                    936:     } elsif ($State eq "RequestingKey")     {
                    937: 	# At this time we're requesting the key.
                    938: 	# again, this is essentially a no-op.
                    939: 	# we'll write the next chunk until the
                    940: 	# state changes.
                    941: 
                    942: 	if($Socket->Writable() != 0) {
                    943: 	    # Write resulted in an error.
1.5       foxr      944: 
                    945: 	    $Watcher->cancel();
1.6       foxr      946: 	    KillSocket($Socket);
1.5       foxr      947: 	    return;
                    948: 
1.1       foxr      949: 	}
                    950:     } elsif ($State eq "ReceivingKey")      {
                    951: 	# Now we need to wait for the key
                    952: 	# to come back from the peer:
                    953: 
1.8       foxr      954: 	$Watcher->cb(\&LondReadable);
1.1       foxr      955: 	$Watcher->poll("r");
                    956: 
                    957:     } elsif ($State eq "SendingRequest")    {
                    958: 	# At this time we are sending a request to the
                    959: 	# peer... write the next chunk:
                    960: 
                    961: 	if($Socket->Writable() != 0) {
                    962: 
1.5       foxr      963: 	    if(exists($ActiveTransactions{$Socket})) {
                    964: 		Debug(3, "Lond connection lost, failing transactions");
                    965: 		FailTransaction($ActiveTransactions{$Socket});
                    966: 	    }
                    967: 	    $Watcher->cancel();
1.6       foxr      968: 	    KillSocket($Socket);
1.5       foxr      969: 	    return;
                    970: 	    
1.1       foxr      971: 	}
                    972: 
                    973:     } elsif ($State eq "ReceivingReply")    {
                    974: 	# The send has completed.  Wait for the
                    975: 	# data to come in for a reply.
                    976: 	Debug(8,"Writable sent request/receiving reply");
1.8       foxr      977: 	$Watcher->cb(\&LondReadable);
1.1       foxr      978: 	$Watcher->poll("r");
                    979: 
                    980:     } else {
                    981: 	#  Control only passes here on an error: 
                    982: 	#  the socket state does not match any
                    983: 	#  of the known states... so an error
                    984: 	#  must be logged.
                    985: 
                    986: 	&Debug(4, "Invalid socket state ".$State."\n");
                    987:     }
                    988:     
                    989: }
1.6       foxr      990: =pod
                    991:     
                    992: =cut
                    993: sub QueueDelayed {
1.8       foxr      994:     Debug(3,"QueueDelayed called");
                    995: 
1.6       foxr      996:     my $path = "$perlvar{'lonSockDir'}/delayed";
1.8       foxr      997: 
                    998:     Debug(4, "Delayed path: ".$path);
1.6       foxr      999:     opendir(DIRHANDLE, $path);
1.8       foxr     1000:     
1.23      foxr     1001:     my @alldelayed = grep /\.$RemoteHost$/, readdir DIRHANDLE;
1.6       foxr     1002:     closedir(DIRHANDLE);
                   1003:     my $dfname;
1.8       foxr     1004:     my $reqfile;
                   1005:     foreach $dfname (sort  @alldelayed) {
                   1006: 	$reqfile = "$path/$dfname";
                   1007: 	Debug(4, "queueing ".$reqfile);
1.6       foxr     1008: 	my $Handle = IO::File->new($reqfile);
                   1009: 	my $cmd    = <$Handle>;
1.8       foxr     1010: 	chomp $cmd;		# There may or may not be a newline...
1.12      foxr     1011: 	$cmd = $cmd."\n";	# now for sure there's exactly one newline.
1.7       foxr     1012: 	my $Transaction = LondTransaction->new($cmd);
                   1013: 	$Transaction->SetDeferred($reqfile);
                   1014: 	QueueTransaction($Transaction);
1.6       foxr     1015:     }
                   1016:     
                   1017: }
1.1       foxr     1018: 
                   1019: =pod
1.3       albertel 1020: 
1.1       foxr     1021: =head2 MakeLondConnection
1.3       albertel 1022: 
                   1023: Create a new lond connection object, and start it towards its initial
                   1024: idleness.  Once idle, it becomes elligible to receive transactions
                   1025: from the work queue.  If the work queue is not empty when the
                   1026: connection is completed and becomes idle, it will dequeue an entry and
                   1027: start off on it.
                   1028: 
1.1       foxr     1029: =cut
1.3       albertel 1030: 
1.1       foxr     1031: sub MakeLondConnection {     
                   1032:     Debug(4,"MakeLondConnection to ".GetServerHost()." on port "
                   1033: 	  .GetServerPort());
                   1034: 
                   1035:     my $Connection = LondConnection->new(&GetServerHost(),
                   1036: 					 &GetServerPort());
                   1037: 
1.30      foxr     1038:     if($Connection eq undef) {	# Needs to be more robust later.
1.9       foxr     1039: 	Log("CRITICAL","Failed to make a connection with lond.");
1.10      foxr     1040: 	$ConnectionRetriesLeft--;
                   1041: 	return 0;		# Failure.
1.5       foxr     1042:     }  else {
1.22      foxr     1043: 
1.5       foxr     1044: 	# The connection needs to have writability 
                   1045: 	# monitored in order to send the init sequence
                   1046: 	# that starts the whole authentication/key
                   1047: 	# exchange underway.
                   1048: 	#
                   1049: 	my $Socket = $Connection->GetSocket();
1.30      foxr     1050: 	if($Socket eq undef) {
1.5       foxr     1051: 	    die "did not get a socket from the connection";
                   1052: 	} else {
                   1053: 	    &Debug(9,"MakeLondConnection got socket: ".$Socket);
                   1054: 	}
1.1       foxr     1055: 	
1.21      foxr     1056: 	$Connection->SetTimeoutCallback(\&SocketTimeout);
                   1057: 
1.23      foxr     1058: 	my $event = Event->io(fd       => $Socket,
1.5       foxr     1059: 			   poll     => 'w',
                   1060: 			   cb       => \&LondWritable,
1.8       foxr     1061: 			   data     => $Connection,
1.5       foxr     1062: 			   desc => 'Connection to lond server');
                   1063: 	$ActiveConnections{$Connection} = $event;
                   1064: 	
                   1065: 	$ConnectionCount++;
1.8       foxr     1066: 	Debug(4, "Connection count = ".$ConnectionCount);
1.6       foxr     1067: 	if($ConnectionCount == 1) { # First Connection:
                   1068: 	    QueueDelayed;
                   1069: 	}
1.9       foxr     1070: 	Log("SUCESS", "Created connection ".$ConnectionCount
                   1071: 	    ." to host ".GetServerHost());
1.10      foxr     1072: 	return 1;		# Return success.
1.1       foxr     1073:     }
                   1074:     
                   1075: }
1.3       albertel 1076: 
1.1       foxr     1077: =pod
1.3       albertel 1078: 
1.1       foxr     1079: =head2 StartRequest
1.3       albertel 1080: 
                   1081: Starts a lond request going on a specified lond connection.
                   1082: parameters are:
                   1083: 
                   1084: =item $Lond
                   1085: 
                   1086: Connection to the lond that will send the transaction and receive the
                   1087: reply.
                   1088: 
                   1089: =item $Client
                   1090: 
                   1091: Connection to the client that is making this request We got the
                   1092: request from this socket, and when the request has been relayed to
                   1093: lond and we get a reply back from lond it will get sent to this
                   1094: socket.
                   1095: 
                   1096: =item $Request
                   1097: 
                   1098: The text of the request to send.
                   1099: 
1.1       foxr     1100: =cut
                   1101: 
                   1102: sub StartRequest {
                   1103:     my $Lond     = shift;
1.7       foxr     1104:     my $Request  = shift;	# This is a LondTransaction.
1.1       foxr     1105:     
1.7       foxr     1106:     Debug(6, "StartRequest: ".$Request->getRequest());
1.1       foxr     1107: 
                   1108:     my $Socket = $Lond->GetSocket();
                   1109:     
1.7       foxr     1110:     $Request->Activate($Lond);
                   1111:     $ActiveTransactions{$Lond} = $Request;
1.1       foxr     1112: 
1.7       foxr     1113:     $Lond->InitiateTransaction($Request->getRequest());
1.23      foxr     1114:     my $event = Event->io(fd      => $Socket,
1.1       foxr     1115: 		       poll    => "w",
                   1116: 		       cb      => \&LondWritable,
                   1117: 		       data    => $Lond,
                   1118: 		       desc    => "lond transaction connection");
                   1119:     $ActiveConnections{$Lond} = $event;
                   1120:     Debug(8," Start Request made watcher data with ".$event->data."\n");
                   1121: }
                   1122: 
                   1123: =pod
1.3       albertel 1124: 
1.1       foxr     1125: =head2 QueueTransaction
1.3       albertel 1126: 
                   1127: If there is an idle lond connection, it is put to work doing this
                   1128: transaction.  Otherwise, the transaction is placed in the work queue.
                   1129: If placed in the work queue and the maximum number of connections has
                   1130: not yet been created, a new connection will be started.  Our goal is
                   1131: to eventually have a sufficient number of connections that the work
                   1132: queue will typically be empty.  parameters are:
                   1133: 
                   1134: =item Socket
                   1135: 
                   1136: open on the lonc client.
                   1137: 
                   1138: =item Request
                   1139: 
                   1140: data to send to the lond.
1.1       foxr     1141: 
                   1142: =cut
1.3       albertel 1143: 
1.1       foxr     1144: sub QueueTransaction {
                   1145: 
1.7       foxr     1146:     my $requestData   = shift;	# This is a LondTransaction.
                   1147:     my $cmd           = $requestData->getRequest();
                   1148: 
                   1149:     Debug(6,"QueueTransaction: ".$cmd);
1.1       foxr     1150: 
                   1151:     my $LondSocket    = $IdleConnections->pop();
                   1152:     if(!defined $LondSocket) {	# Need to queue request.
1.29      foxr     1153: 	Debug(5,"Must queue...");
1.1       foxr     1154: 	$WorkQueue->enqueue($requestData);
                   1155: 	if($ConnectionCount < $MaxConnectionCount) {
1.22      foxr     1156: 	    if($ConnectionRetriesLeft > 0) {
1.29      foxr     1157: 		Debug(5,"Starting additional lond connection");
1.22      foxr     1158: 		if(MakeLondConnection() == 0) {
                   1159: 		    EmptyQueue();	# Fail transactions, can't make connection.
                   1160: 		}
                   1161: 	    } else {
                   1162: 		ShowStatus(GetServerHost()." >>> DEAD !!!! <<<");
                   1163: 		EmptyQueue();	# It's worse than that ... he's dead Jim.
1.17      foxr     1164: 	    }
1.1       foxr     1165: 	}
                   1166:     } else {			# Can start the request:
                   1167: 	Debug(8,"Can start...");
1.7       foxr     1168: 	StartRequest($LondSocket,  $requestData);
1.1       foxr     1169:     }
                   1170: }
                   1171: 
                   1172: #-------------------------- Lonc UNIX socket handling ---------------------
1.3       albertel 1173: 
1.1       foxr     1174: =pod
1.3       albertel 1175: 
1.1       foxr     1176: =head2 ClientRequest
1.3       albertel 1177: Callback that is called when data can be read from the UNIX domain
                   1178: socket connecting us with an apache server process.
1.1       foxr     1179: 
                   1180: =cut
                   1181: 
                   1182: sub ClientRequest {
                   1183:     Debug(6, "ClientRequest");
                   1184:     my $event   = shift;
                   1185:     my $watcher = $event->w;
                   1186:     my $socket  = $watcher->fd;
                   1187:     my $data    = $watcher->data;
                   1188:     my $thisread;
                   1189: 
                   1190:     Debug(9, "  Watcher named: ".$watcher->desc);
                   1191: 
                   1192:     my $rv = $socket->recv($thisread, POSIX::BUFSIZ, 0);
                   1193:     Debug(8, "rcv:  data length = ".length($thisread)
                   1194: 	  ." read =".$thisread);
1.29      foxr     1195:     unless (defined $rv  && length($thisread)) {
1.1       foxr     1196: 	 # Likely eof on socket.
                   1197: 	Debug(5,"Client Socket closed on lonc for ".$RemoteHost);
                   1198: 	close($socket);
                   1199: 	$watcher->cancel();
                   1200: 	delete($ActiveClients{$socket});
1.10      foxr     1201: 	return;
1.1       foxr     1202:     }
                   1203:     Debug(8,"Data: ".$data." this read: ".$thisread);
                   1204:     $data = $data.$thisread;	# Append new data.
                   1205:     $watcher->data($data);
                   1206:     if($data =~ /(.*\n)/) {	# Request entirely read.
1.10      foxr     1207: 	if($data eq "close_connection_exit\n") {
1.9       foxr     1208: 	    Log("CRITICAL",
                   1209: 		"Request Close Connection ... exiting");
                   1210: 	    CloseAllLondConnections();
                   1211: 	    exit;
                   1212: 	}
1.1       foxr     1213: 	Debug(8, "Complete transaction received: ".$data);
1.8       foxr     1214: 	my $Transaction = LondTransaction->new($data);
1.7       foxr     1215: 	$Transaction->SetClient($socket);
                   1216: 	QueueTransaction($Transaction);
1.1       foxr     1217: 	$watcher->cancel();	# Done looking for input data.
                   1218:     }
                   1219: 
                   1220: }
                   1221: 
                   1222: 
                   1223: =pod
1.3       albertel 1224: 
1.1       foxr     1225: =head2  NewClient
1.3       albertel 1226: 
                   1227: Callback that is called when a connection is received on the unix
                   1228: socket for a new client of lonc.  The callback is parameterized by the
                   1229: event.. which is a-priori assumed to be an io event, and therefore has
                   1230: an fd member that is the Listener socket.  We Accept the connection
                   1231: and register a new event on the readability of that socket:
                   1232: 
1.1       foxr     1233: =cut
1.3       albertel 1234: 
1.1       foxr     1235: sub NewClient {
                   1236:     Debug(6, "NewClient");
                   1237:     my $event      = shift;		# Get the event parameters.
                   1238:     my $watcher    = $event->w; 
                   1239:     my $socket     = $watcher->fd;	# Get the event' socket.
                   1240:     my $connection = $socket->accept();	# Accept the client connection.
                   1241:     Debug(8,"Connection request accepted from "
                   1242: 	  .GetPeername($connection, AF_UNIX));
                   1243: 
                   1244: 
                   1245:     my $description = sprintf("Connection to lonc client %d",
                   1246: 			      $ClientConnection);
                   1247:     Debug(9, "Creating event named: ".$description);
                   1248:     Event->io(cb      => \&ClientRequest,
                   1249: 	      poll    => 'r',
                   1250: 	      desc    => $description,
                   1251: 	      data    => "",
                   1252: 	      fd      => $connection);
                   1253:     $ActiveClients{$connection} = $ClientConnection;
                   1254:     $ClientConnection++;
                   1255: }
1.3       albertel 1256: 
                   1257: =pod
                   1258: 
                   1259: =head2 GetLoncSocketPath
                   1260: 
                   1261: Returns the name of the UNIX socket on which to listen for client
                   1262: connections.
1.1       foxr     1263: 
                   1264: =cut
1.3       albertel 1265: 
1.1       foxr     1266: sub GetLoncSocketPath {
                   1267:     return $UnixSocketDir."/".GetServerHost();
                   1268: }
                   1269: 
1.3       albertel 1270: =pod
                   1271: 
                   1272: =head2 GetServerHost
                   1273: 
                   1274: Returns the host whose lond we talk with.
                   1275: 
1.1       foxr     1276: =cut
1.3       albertel 1277: 
1.7       foxr     1278: sub GetServerHost {
1.1       foxr     1279:     return $RemoteHost;		# Setup by the fork.
                   1280: }
1.3       albertel 1281: 
                   1282: =pod
                   1283: 
                   1284: =head2 GetServerPort
                   1285: 
                   1286: Returns the lond port number.
                   1287: 
1.1       foxr     1288: =cut
1.3       albertel 1289: 
1.7       foxr     1290: sub GetServerPort {
1.1       foxr     1291:     return $perlvar{londPort};
                   1292: }
1.3       albertel 1293: 
                   1294: =pod
                   1295: 
                   1296: =head2 SetupLoncListener
                   1297: 
                   1298: Setup a lonc listener event.  The event is called when the socket
                   1299: becomes readable.. that corresponds to the receipt of a new
                   1300: connection.  The event handler established will accept the connection
                   1301: (creating a communcations channel), that int turn will establish
                   1302: another event handler to subess requests.
1.1       foxr     1303: 
                   1304: =cut
1.3       albertel 1305: 
1.1       foxr     1306: sub SetupLoncListener {
                   1307: 
                   1308:     my $socket;
                   1309:     my $SocketName = GetLoncSocketPath();
                   1310:     unlink($SocketName);
1.7       foxr     1311:     unless ($socket =IO::Socket::UNIX->new(Local  => $SocketName,
1.1       foxr     1312: 					    Listen => 10, 
                   1313: 					    Type   => SOCK_STREAM)) {
                   1314: 	die "Failed to create a lonc listner socket";
                   1315:     }
                   1316:     Event->io(cb     => \&NewClient,
                   1317: 	      poll   => 'r',
                   1318: 	      desc   => 'Lonc listener Unix Socket',
                   1319: 	      fd     => $socket);
                   1320: }
                   1321: 
1.14      foxr     1322: =pod 
                   1323: 
                   1324: =head2 ChildStatus
                   1325:  
                   1326: Child USR1 signal handler to report the most recent status
                   1327: into the status file.
                   1328: 
1.22      foxr     1329: We also use this to reset the retries count in order to allow the
                   1330: client to retry connections with a previously dead server.
1.14      foxr     1331: =cut
                   1332: sub ChildStatus {
                   1333:     my $event = shift;
                   1334:     my $watcher = $event->w;
                   1335: 
                   1336:     Debug(2, "Reporting child status because : ".$watcher->data);
                   1337:     my $docdir = $perlvar{'lonDocRoot'};
                   1338:     my $fh = IO::File->new(">>$docdir/lon-status/loncstatus.txt");
                   1339:     print $fh $$."\t".$RemoteHost."\t".$Status."\t".
                   1340: 	$RecentLogEntry."\n";
1.22      foxr     1341:     $ConnectionRetriesLeft = $ConnectionRetries;
1.14      foxr     1342: }
                   1343: 
1.1       foxr     1344: =pod
1.3       albertel 1345: 
1.10      foxr     1346: =head2 SignalledToDeath
                   1347: 
                   1348: Called in response to a signal that causes a chid process to die.
                   1349: 
                   1350: =cut
                   1351: 
                   1352: 
                   1353: sub SignalledToDeath {
1.14      foxr     1354:     my $event  = shift;
                   1355:     my $watcher= $event->w;
                   1356: 
                   1357:     Debug(2,"Signalled to death! via ".$watcher->data);
1.17      foxr     1358:     my ($signal) = $watcher->data;
1.10      foxr     1359:     chomp($signal);
                   1360:     Log("CRITICAL", "Abnormal exit.  Child $$ for $RemoteHost "
                   1361: 	."died through "."\"$signal\"");
                   1362:     LogPerm("F:lonc: $$ on $RemoteHost signalled to death: "
                   1363: 	    ."\"$signal\"");
1.12      foxr     1364:     exit 0;
1.10      foxr     1365: 
                   1366: }
1.16      foxr     1367: 
                   1368: =head2 ToggleDebug
                   1369: 
                   1370: This sub toggles trace debugging on and off.
                   1371: 
                   1372: =cut
                   1373: 
                   1374: sub ToggleDebug {
                   1375:     my $Current    = $DebugLevel;
                   1376:        $DebugLevel = $NextDebugLevel;
                   1377:        $NextDebugLevel = $Current;
                   1378: 
                   1379:     Log("SUCCESS", "New debugging level for $RemoteHost now $DebugLevel");
                   1380: 
                   1381: }
                   1382: 
1.1       foxr     1383: =head2 ChildProcess
                   1384: 
                   1385: This sub implements a child process for a single lonc daemon.
                   1386: 
                   1387: =cut
                   1388: 
                   1389: sub ChildProcess {
                   1390: 
                   1391: 
1.14      foxr     1392:     #
                   1393:     #  Signals must be handled by the Event framework...
                   1394: #
                   1395: 
                   1396:     Event->signal(signal   => "QUIT",
                   1397: 		  cb       => \&SignalledToDeath,
                   1398: 		  data     => "QUIT");
                   1399:     Event->signal(signal   => "HUP",
                   1400: 		  cb       => \&ChildStatus,
                   1401: 		  data     => "HUP");
                   1402:     Event->signal(signal   => "USR1",
                   1403: 		  cb       => \&ChildStatus,
                   1404: 		  data     => "USR1");
1.16      foxr     1405:     Event->signal(signal   => "INT",
                   1406: 		  cb       => \&ToggleDebug,
                   1407: 		  data     => "INT");
1.1       foxr     1408: 
                   1409:     SetupTimer();
                   1410:     
                   1411:     SetupLoncListener();
                   1412:     
                   1413:     $Event::Debuglevel = $DebugLevel;
                   1414:     
                   1415:     Debug(9, "Making initial lond connection for ".$RemoteHost);
                   1416: 
                   1417: # Setup the initial server connection:
                   1418:     
1.14      foxr     1419:      # &MakeLondConnection(); // let first work requirest do it.
1.10      foxr     1420: 
1.5       foxr     1421: 
1.1       foxr     1422:     Debug(9,"Entering event loop");
                   1423:     my $ret = Event::loop();		#  Start the main event loop.
                   1424:     
                   1425:     
                   1426:     die "Main event loop exited!!!";
                   1427: }
                   1428: 
                   1429: #  Create a new child for host passed in:
                   1430: 
                   1431: sub CreateChild {
1.12      foxr     1432:     my $sigset = POSIX::SigSet->new(SIGINT);
                   1433:     sigprocmask(SIG_BLOCK, $sigset);
1.1       foxr     1434:     my $host = shift;
                   1435:     $RemoteHost = $host;
1.9       foxr     1436:     Log("CRITICAL", "Forking server for ".$host);
1.23      foxr     1437:     my $pid          = fork;
1.1       foxr     1438:     if($pid) {			# Parent
1.17      foxr     1439: 	$RemoteHost = "Parent";
1.27      foxr     1440: 	$ChildHash{$pid} = $host;
1.26      foxr     1441: 	$HostToPid{$host}= $pid;
1.12      foxr     1442: 	sigprocmask(SIG_UNBLOCK, $sigset);
                   1443: 
1.1       foxr     1444:     } else {			# child.
1.5       foxr     1445: 	ShowStatus("Connected to ".$RemoteHost);
1.23      foxr     1446: 	$SIG{INT} = 'DEFAULT';
1.12      foxr     1447: 	sigprocmask(SIG_UNBLOCK, $sigset);
                   1448: 	ChildProcess;		# Does not return.
1.1       foxr     1449:     }
                   1450: 
                   1451: }
                   1452: #
                   1453: #  Parent process logic pass 1:
                   1454: #   For each entry in the hosts table, we will
                   1455: #  fork off an instance of ChildProcess to service the transactions
                   1456: #  to that host.  Each pid will be entered in a global hash
                   1457: #  with the value of the key, the host.
                   1458: #  The parent will then enter a loop to wait for process exits.
                   1459: #  Each exit gets logged and the child gets restarted.
                   1460: #
                   1461: 
1.5       foxr     1462: #
                   1463: #   Fork and start in new session so hang-up isn't going to 
                   1464: #   happen without intent.
                   1465: #
                   1466: 
                   1467: 
1.6       foxr     1468: 
                   1469: 
1.8       foxr     1470: 
1.6       foxr     1471: 
                   1472: ShowStatus("Forming new session");
                   1473: my $childpid = fork;
                   1474: if ($childpid != 0) {
                   1475:     sleep 4;			# Give child a chacne to break to
                   1476:     exit 0;			# a new sesion.
                   1477: }
1.8       foxr     1478: #
                   1479: #   Write my pid into the pid file so I can be located
                   1480: #
                   1481: 
                   1482: ShowStatus("Parent writing pid file:");
1.23      foxr     1483: my $execdir = $perlvar{'lonDaemons'};
1.8       foxr     1484: open (PIDSAVE, ">$execdir/logs/lonc.pid");
                   1485: print PIDSAVE "$$\n";
                   1486: close(PIDSAVE);
1.6       foxr     1487: 
1.17      foxr     1488: 
                   1489: 
1.6       foxr     1490: if (POSIX::setsid() < 0) {
                   1491:     print "Could not create new session\n";
                   1492:     exit -1;
                   1493: }
1.5       foxr     1494: 
                   1495: ShowStatus("Forking node servers");
                   1496: 
1.9       foxr     1497: Log("CRITICAL", "--------------- Starting children ---------------");
                   1498: 
1.31      foxr     1499: LondConnection::ReadConfig;               # Read standard config files.
1.1       foxr     1500: my $HostIterator = LondConnection::GetHostIterator;
                   1501: while (! $HostIterator->end()) {
                   1502: 
1.23      foxr     1503:     my $hostentryref = $HostIterator->get();
1.1       foxr     1504:     CreateChild($hostentryref->[0]);
1.26      foxr     1505:     $HostHash{$hostentryref->[0]} = $hostentryref->[4];
1.1       foxr     1506:     $HostIterator->next();
                   1507: }
1.12      foxr     1508: $RemoteHost = "Parent Server";
1.1       foxr     1509: 
                   1510: # Maintain the population:
1.5       foxr     1511: 
                   1512: ShowStatus("Parent keeping the flock");
1.1       foxr     1513: 
1.10      foxr     1514: #
                   1515: #   Set up parent signals:
                   1516: #
1.12      foxr     1517: 
1.14      foxr     1518: $SIG{INT}  = \&Terminate;
                   1519: $SIG{TERM} = \&Terminate; 
1.13      foxr     1520: $SIG{HUP}  = \&Restart;
1.14      foxr     1521: $SIG{USR1} = \&CheckKids; 
1.24      foxr     1522: $SIG{USR2} = \&UpdateKids;	# LonManage update request.
1.10      foxr     1523: 
1.1       foxr     1524: while(1) {
1.23      foxr     1525:     my $deadchild = wait();
1.1       foxr     1526:     if(exists $ChildHash{$deadchild}) {	# need to restart.
1.23      foxr     1527: 	my $deadhost = $ChildHash{$deadchild};
1.26      foxr     1528: 	delete($HostToPid{$deadhost});
1.1       foxr     1529: 	delete($ChildHash{$deadchild});
1.9       foxr     1530: 	Log("WARNING","Lost child pid= ".$deadchild.
1.1       foxr     1531: 	      "Connected to host ".$deadhost);
1.9       foxr     1532: 	Log("INFO", "Restarting child procesing ".$deadhost);
1.1       foxr     1533: 	CreateChild($deadhost);
                   1534:     }
1.13      foxr     1535: }
                   1536: 
1.14      foxr     1537: 
                   1538: 
                   1539: =pod
                   1540: 
                   1541: =head1 CheckKids
                   1542: 
                   1543:   Since kids do not die as easily in this implementation
                   1544: as the previous one, there  is no need to restart the
                   1545: dead ones (all dead kids get restarted when they die!!)
                   1546: The only thing this function does is to pass USR1 to the
                   1547: kids so that they report their status.
                   1548: 
                   1549: =cut
                   1550: 
                   1551: sub CheckKids {
                   1552:     Debug(2, "Checking status of children");
                   1553:     my $docdir = $perlvar{'lonDocRoot'};
                   1554:     my $fh = IO::File->new(">$docdir/lon-status/loncstatus.txt");
                   1555:     my $now=time;
                   1556:     my $local=localtime($now);
                   1557:     print $fh "LONC status $local - parent $$ \n\n";
1.23      foxr     1558:     foreach my $pid (keys %ChildHash) {
1.14      foxr     1559: 	Debug(2, "Sending USR1 -> $pid");
                   1560: 	kill 'USR1' => $pid;	# Tell Child to report status.
                   1561: 	sleep 1;		# Wait so file doesn't intermix.
                   1562:     }
                   1563: }
1.24      foxr     1564: 
                   1565: =pod
                   1566: 
                   1567: =head1  UpdateKids
                   1568: 
1.25      foxr     1569: parent's SIGUSR2 handler.  This handler:
1.24      foxr     1570: 
                   1571: =item
                   1572: 
                   1573: Rereads the hosts file.
                   1574: 
                   1575: =item
                   1576:  
                   1577: Kills off (via sigint) children for hosts that have disappeared.
                   1578: 
                   1579: =item
                   1580: 
1.27      foxr     1581: QUITs  children for hosts that already exist (this just forces a status display
1.24      foxr     1582: and resets the connection retry count for that host.
                   1583: 
                   1584: =item
                   1585: 
                   1586: Starts new children for hosts that have been added to the hosts.tab file since
                   1587: the start of the master program and maintains them.
                   1588: 
                   1589: =cut
                   1590: 
                   1591: sub UpdateKids {
1.27      foxr     1592: 
1.25      foxr     1593:     Log("INFO", "Updating connections via SIGUSR2");
1.27      foxr     1594: 
                   1595:     #  Just in case we need to kill our own lonc, we wait a few seconds to
                   1596:     #  give it a chance to receive and relay lond's response to the 
                   1597:     #  re-init command.
                   1598:     #
                   1599: 
                   1600:     sleep(2);			# Wait a couple of seconds.
                   1601: 
                   1602:     my %hosts;                   # Indexed by loncapa hostname, value=ip.
                   1603:     
                   1604:     # Need to re-read  the host table:
                   1605:     
                   1606:     
                   1607:     LondConnection::ReadConfig();
                   1608:     my $I = LondConnection::GetHostIterator;
                   1609:     while (! $I->end()) {
                   1610: 	my $item = $I->get();
                   1611: 	$hosts{$item->[0]} = $item->[4];
                   1612: 	$I->next();
                   1613:     }
                   1614: 
                   1615:     #  The logic below is written for clarity not for efficiency.
                   1616:     #  Since I anticipate that this function is only rarely called, that's
                   1617:     #  appropriate.  There are certainly ways to combine the loops below,
                   1618:     #  and anyone wishing to obscure the logic is welcome to go for it.
                   1619:     #  Note that we don't re-direct sigchild.  Instead we do what's needed
                   1620:     #  to the data structures that keep track of children to ensure that
                   1621:     #  when sigchild is honored, no new child is born.
                   1622:     #
                   1623: 
                   1624:     #  For each existing child; if it's host doesn't exist, kill the child.
                   1625: 
                   1626:     foreach my $child (keys %ChildHash) {
                   1627: 	my $oldhost = $ChildHash{$child};
                   1628: 	if (!(exists $hosts{$oldhost})) {
                   1629: 	    Log("CRITICAL", "Killing child for $oldhost  host no longer exists");
                   1630: 	    delete $ChildHash{$child};
                   1631: 	    delete $HostToPid{$oldhost};
                   1632: 	    kill 'QUIT' => $child;
                   1633: 	}
                   1634:     }
                   1635:     # For each remaining existing child; if it's host's ip has changed,
                   1636:     # Restart the child on the new IP.
                   1637: 
                   1638:     foreach my $child (keys %ChildHash) {
                   1639: 	my $oldhost = $ChildHash{$child};
                   1640: 	my $oldip   = $HostHash{$oldhost};
                   1641: 	if ($hosts{$oldhost} ne $oldip) {
                   1642: 
                   1643: 	    # kill the old child.
                   1644: 
                   1645: 	    Log("CRITICAL", "Killing child for $oldhost host ip has changed...");
                   1646: 	    delete $ChildHash{$child};
                   1647: 	    delete $HostToPid{$oldhost};
                   1648: 	    kill 'QUIT' => $child;
                   1649: 
                   1650: 	    # Do the book-keeping needed to start a new child on the
                   1651: 	    # new ip.
                   1652: 
                   1653: 	    $HostHash{$oldhost} = $hosts{$oldhost};
                   1654: 	    CreateChild($oldhost);
                   1655: 	}
                   1656:     }
                   1657:     # Finally, for each new host, not in the host hash, create a
                   1658:     # enter the host and create a new child.
                   1659:     # Force a status display of any existing process.
                   1660: 
                   1661:     foreach my $host (keys %hosts) {
                   1662: 	if(!(exists $HostHash{$host})) {
                   1663: 	    Log("INFO", "New host $host discovered in hosts.tab...");
                   1664: 	    $HostHash{$host} = $hosts{$host};
                   1665: 	    CreateChild($host);
                   1666: 	} else {
                   1667: 	    kill 'HUP' => $HostToPid{$host};    # status display.
                   1668: 	}
                   1669:     }
1.24      foxr     1670: }
                   1671: 
1.14      foxr     1672: 
1.13      foxr     1673: =pod
                   1674: 
                   1675: =head1 Restart
                   1676: 
                   1677: Signal handler for HUP... all children are killed and
                   1678: we self restart.  This is an el-cheapo way to re read
                   1679: the config file.
                   1680: 
                   1681: =cut
                   1682: 
                   1683: sub Restart {
1.23      foxr     1684:     &KillThemAll;		# First kill all the children.
1.13      foxr     1685:     Log("CRITICAL", "Restarting");
                   1686:     my $execdir = $perlvar{'lonDaemons'};
                   1687:     unlink("$execdir/logs/lonc.pid");
1.28      albertel 1688:     exec("$execdir/loncnew");
1.10      foxr     1689: }
1.12      foxr     1690: 
                   1691: =pod
                   1692: 
                   1693: =head1 KillThemAll
                   1694: 
                   1695: Signal handler that kills all children by sending them a 
1.17      foxr     1696: SIGHUP.  Responds to sigint and sigterm.
1.12      foxr     1697: 
                   1698: =cut
                   1699: 
1.10      foxr     1700: sub KillThemAll {
1.12      foxr     1701:     Debug(2, "Kill them all!!");
                   1702:     local($SIG{CHLD}) = 'IGNORE';      # Our children >will< die.
1.23      foxr     1703:     foreach my $pid (keys %ChildHash) {
1.12      foxr     1704: 	my $serving = $ChildHash{$pid};
                   1705: 	Debug(2, "Killing lonc for $serving pid = $pid");
                   1706: 	ShowStatus("Killing lonc for $serving pid = $pid");
                   1707: 	Log("CRITICAL", "Killing lonc for $serving pid = $pid");
1.17      foxr     1708: 	kill 'QUIT' => $pid;
                   1709: 	delete($ChildHash{$pid});
1.12      foxr     1710:     }
1.14      foxr     1711:     my $execdir = $perlvar{'lonDaemons'};
                   1712:     unlink("$execdir/logs/lonc.pid");
1.17      foxr     1713: 
1.1       foxr     1714: }
1.12      foxr     1715: 
1.14      foxr     1716: =pod
                   1717: 
                   1718: =head1 Terminate
                   1719:  
                   1720: Terminate the system.
                   1721: 
                   1722: =cut
                   1723: 
                   1724: sub Terminate {
                   1725:     KillThemAll;
1.17      foxr     1726:     Log("CRITICAL","Master process exiting");
                   1727:     exit 0;
1.14      foxr     1728: 
                   1729: }
1.12      foxr     1730: =pod
1.1       foxr     1731: 
                   1732: =head1 Theory
1.3       albertel 1733: 
                   1734: The event class is used to build this as a single process with an
                   1735: event driven model.  The following events are handled:
1.1       foxr     1736: 
                   1737: =item UNIX Socket connection Received
                   1738: 
                   1739: =item Request data arrives on UNIX data transfer socket.
                   1740: 
                   1741: =item lond connection becomes writable.
                   1742: 
                   1743: =item timer fires at 1 second intervals.
                   1744: 
                   1745: All sockets are run in non-blocking mode.  Timeouts managed by the timer
                   1746: handler prevents hung connections.
                   1747: 
                   1748: Key data structures:
                   1749: 
1.3       albertel 1750: =item RequestQueue
                   1751: 
                   1752: A queue of requests received from UNIX sockets that are
                   1753: waiting for a chance to be forwarded on a lond connection socket.
                   1754: 
                   1755: =item ActiveConnections
                   1756: 
                   1757: A hash of lond connections that have transactions in process that are
                   1758: available to be timed out.
                   1759: 
                   1760: =item ActiveTransactions
                   1761: 
                   1762: A hash indexed by lond connections that contain the client reply
                   1763: socket for each connection that has an active transaction on it.
                   1764: 
                   1765: =item IdleConnections
                   1766: 
                   1767: A hash of lond connections that have no work to do.  These connections
                   1768: can be closed if they are idle for a long enough time.
1.1       foxr     1769: 
                   1770: =cut

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