Annotation of loncom/loncnew, revision 1.39

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

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