Annotation of loncom/loncnew, revision 1.65

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

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