Annotation of loncom/loncnew, revision 1.54

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

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