File:  [LON-CAPA] / loncom / loncnew
Revision 1.50: download - view: text, annotated - select for diffs
Fri Jul 2 09:28:14 2004 UTC (19 years, 9 months ago) by albertel
Branches: MAIN
CVS tags: version_1_2_0, version_1_1_99_5, version_1_1_99_4, version_1_1_99_3, version_1_1_99_2, version_1_1_99_1, HEAD

- many firewalls out there drop idle tcp connections that have been idl for 10 minutes or more.

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

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