File:  [LON-CAPA] / loncom / loncnew
Revision 1.34: download - view: text, annotated - select for diffs
Thu Dec 11 23:18:37 2003 UTC (20 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- connections could get frozen in the connectiong state if the remote end accepted the connection but never got back to us on any of our commands BUG#2488

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

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