File:  [LON-CAPA] / loncom / loncnew
Revision 1.43: download - view: text, annotated - select for diffs
Tue Feb 17 15:09:08 2004 UTC (20 years, 2 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- retabinate

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

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