File:  [LON-CAPA] / loncom / loncnew
Revision 1.79: download - view: text, annotated - select for diffs
Wed Mar 28 00:14:15 2007 UTC (17 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: HEAD
- switch on the dynamic hosts.tab support in loncnew by default

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

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