File:  [LON-CAPA] / loncom / loncnew
Revision 1.47: download - view: text, annotated - select for diffs
Tue Jun 1 10:02:13 2004 UTC (19 years, 11 months ago) by foxr
Branches: MAIN
CVS tags: version_1_1_99_0, HEAD
Make parameter passing meet standard using @_ not multiple shifts
or English @ARG.

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

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