File:  [LON-CAPA] / loncom / loncnew
Revision 1.27: download - view: text, annotated - select for diffs
Tue Oct 7 11:23:03 2003 UTC (20 years, 7 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Installed and tested code to process reinit in parent server.

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

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