Annotation of loncom/loncnew, revision 1.44

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

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