File:  [LON-CAPA] / loncom / loncnew
Revision 1.37: download - view: text, annotated - select for diffs
Tue Dec 16 16:12:19 2003 UTC (20 years, 4 months ago) by albertel
Branches: MAIN
CVS tags: version_1_1_X, version_1_1_3, version_1_1_2, version_1_1_1, version_1_1_0, version_1_0_99_3, HEAD
- better fix for handling the connection Count issue

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

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