File:  [LON-CAPA] / loncom / loncnew
Revision 1.32: download - view: text, annotated - select for diffs
Fri Nov 21 19:27:18 2003 UTC (20 years, 5 months ago) by albertel
Branches: MAIN
CVS tags: HEAD
- removing Debugging use lib
- removing change log

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

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