Annotation of loncom/loncnew, revision 1.61

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

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