Annotation of loncom/loncnew, revision 1.56

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

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