Annotation of loncom/loncnew, revision 1.34

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

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