File:  [LON-CAPA] / loncom / loncnew
Revision 1.71: download - view: text, annotated - select for diffs
Thu Jun 16 22:33:45 2005 UTC (18 years, 11 months ago) by albertel
Branches: MAIN
CVS tags: version_2_0_0, version_1_99_3, version_1_99_2, version_1_99_1, version_1_99_0, HEAD
- BUg#4128

    1: #!/usr/bin/perl
    2: # The LearningOnline Network with CAPA
    3: # lonc maintains the connections to remote computers
    4: #
    5: # $Id: loncnew,v 1.71 2005/06/16 22:33:45 albertel Exp $
    6: #
    7: # Copyright Michigan State University Board of Trustees
    8: #
    9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
   10: ## LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: #
   29: # new lonc handles n request out bver m connections to londs.
   30: # This module is based on the Event class.
   31: #   Development iterations:
   32: #    - Setup basic event loop.   (done)
   33: #    - Add timer dispatch.       (done)
   34: #    - Add ability to accept lonc UNIX domain sockets.  (done)
   35: #    - Add ability to create/negotiate lond connections (done).
   36: #    - Add general logic for dispatching requests and timeouts. (done).
   37: #    - Add support for the lonc/lond requests.          (done).
   38: #    - Add logging/status monitoring.                    (done)
   39: #    - Add Signal handling - HUP restarts. USR1 status report. (done)
   40: #    - Add Configuration file I/O                       (done).
   41: #    - Add management/status request interface.         (done)
   42: #    - Add deferred request capability.                  (done)
   43: #    - Detect transmission timeouts.                     (done)
   44: #
   45: 
   46: use strict;
   47: use lib "/home/httpd/lib/perl/";
   48: use Event qw(:DEFAULT );
   49: use POSIX qw(:signal_h);
   50: use POSIX;
   51: use IO::Socket;
   52: use IO::Socket::INET;
   53: use IO::Socket::UNIX;
   54: use IO::File;
   55: use IO::Handle;
   56: use Socket;
   57: use Crypt::IDEA;
   58: use LONCAPA::Queue;
   59: use LONCAPA::Stack;
   60: use LONCAPA::LondConnection;
   61: use LONCAPA::LondTransaction;
   62: use LONCAPA::Configuration;
   63: use LONCAPA::HashIterator;
   64: use Fcntl qw(:flock);
   65: 
   66: 
   67: # Read the httpd configuration file to get perl variables
   68: # normally set in apache modules:
   69: 
   70: my $perlvarref = LONCAPA::Configuration::read_conf('loncapa.conf');
   71: my %perlvar    = %{$perlvarref};
   72: 
   73: #
   74: #  parent and shared variables.
   75: 
   76: my %ChildHash;			# by pid -> host.
   77: my %HostToPid;			# By host -> pid.
   78: my %HostHash;			# by loncapaname -> IP.
   79: my %listening_to;		# Socket->host table for who the parent
   80:                                 # is listening to.
   81: my %parent_dispatchers;         # host-> listener watcher events. 
   82: 
   83: my %parent_handlers;		# Parent signal handlers...
   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= 600;		# Wait 10 minutes before pruning connections.
   91: 
   92: my $LogTransactions = 0;	# When True, all transactions/replies get logged.
   93: my $executable      = $0;	# Get the full path to me.
   94: 
   95: #
   96: #  The variables below are only used by the child processes.
   97: #
   98: my $RemoteHost;			# Name of host child is talking to.
   99: my $UnixSocketDir= $perlvar{'lonSockDir'};
  100: my $IdleConnections = Stack->new(); # Set of idle connections
  101: my %ActiveConnections;		# Connections to the remote lond.
  102: my %ActiveTransactions;		# LondTransactions in flight.
  103: my %ActiveClients;		# Serial numbers of active clients by socket.
  104: my $WorkQueue       = Queue->new(); # Queue of pending transactions.
  105: my $ConnectionCount = 0;
  106: my $IdleSeconds     = 0;	# Number of seconds idle.
  107: my $Status          = "";	# Current status string.
  108: my $RecentLogEntry  = "";
  109: my $ConnectionRetries=2;	# Number of connection retries allowed.
  110: my $ConnectionRetriesLeft=2;	# Number of connection retries remaining.
  111: my $LondVersion     = "unknown"; # Version of lond we talk with.
  112: my $KeyMode         = "";       # e.g. ssl, local, insecure from last connect.
  113: my $LondConnecting  = 0;       # True when a connection is being built.
  114: 
  115: 
  116: 
  117: my $DieWhenIdle     = 1;	# When true children die when trimmed -> 0.
  118: my $I_am_child      = 0;	# True if this is the child process.
  119: 
  120: #
  121: #   The hash below gives the HTML format for log messages
  122: #   given a severity.
  123: #    
  124: my %LogFormats;
  125: 
  126: $LogFormats{"CRITICAL"} = "<font color='red'>CRITICAL: %s</font>";
  127: $LogFormats{"SUCCESS"}  = "<font color='green'>SUCCESS: %s</font>";
  128: $LogFormats{"INFO"}     = "<font color='yellow'>INFO: %s</font>";
  129: $LogFormats{"WARNING"}  = "<font color='blue'>WARNING: %s</font>";
  130: $LogFormats{"DEFAULT"}  = " %s ";
  131: 
  132: 
  133: #  UpdateStatus;
  134: #    Update the idle status display to show how many connections
  135: #    are left, retries and other stuff.
  136: #
  137: sub UpdateStatus {
  138:     if ($ConnectionRetriesLeft > 0) {
  139: 	ShowStatus(GetServerHost()." Connection count: ".$ConnectionCount
  140: 		   ." Retries remaining: ".$ConnectionRetriesLeft
  141: 		   ." ($KeyMode)");
  142:     } else {
  143: 	ShowStatus(GetServerHost()." >> DEAD <<");
  144:     }
  145: }
  146: 
  147: 
  148: =pod
  149: 
  150: =head2 LogPerm
  151: 
  152: Makes an entry into the permanent log file.
  153: 
  154: =cut
  155: 
  156: sub LogPerm {
  157:     my $message=shift;
  158:     my $execdir=$perlvar{'lonDaemons'};
  159:     my $now=time;
  160:     my $local=localtime($now);
  161:     my $fh=IO::File->new(">>$execdir/logs/lonnet.perm.log");
  162:     print $fh "$now:$message:$local\n";
  163: }
  164: 
  165: =pod
  166: 
  167: =head2 Log
  168: 
  169: Logs a message to the log file.
  170: Parameters:
  171: 
  172: =item severity
  173: 
  174: One of CRITICAL, WARNING, INFO, SUCCESS used to select the
  175: format string used to format the message.  if the severity is
  176: not a defined severity the Default format string is used.
  177: 
  178: =item message
  179: 
  180: The base message.  In addtion to the format string, the message
  181: will be appended to a string containing the name of our remote
  182: host and the time will be formatted into the message.
  183: 
  184: =cut
  185: 
  186: sub Log {
  187: 
  188:     my ($severity, $message) = @_;
  189: 
  190:     if(!$LogFormats{$severity}) {
  191: 	$severity = "DEFAULT";
  192:     }
  193: 
  194:     my $format = $LogFormats{$severity};
  195:     
  196:     #  Put the window dressing in in front of the message format:
  197: 
  198:     my $now   = time;
  199:     my $local = localtime($now);
  200:     my $finalformat = "$local ($$) [$RemoteHost] [$Status] ";
  201:     my $finalformat = $finalformat.$format."\n";
  202: 
  203:     # open the file and put the result.
  204: 
  205:     my $execdir = $perlvar{'lonDaemons'};
  206:     my $fh      = IO::File->new(">>$execdir/logs/lonc.log");
  207:     my $msg = sprintf($finalformat, $message);
  208:     $RecentLogEntry = $msg;
  209:     print $fh $msg;
  210:     
  211:     
  212: }
  213: 
  214: 
  215: =pod
  216: 
  217: =head2 GetPeerName
  218: 
  219: Returns the name of the host that a socket object is connected to.
  220: 
  221: =cut
  222: 
  223: sub GetPeername {
  224: 
  225: 
  226:     my ($connection, $AdrFamily) = @_;
  227: 
  228:     my $peer       = $connection->peername();
  229:     my $peerport;
  230:     my $peerip;
  231:     if($AdrFamily == AF_INET) {
  232: 	($peerport, $peerip) = sockaddr_in($peer);
  233: 	my $peername    = gethostbyaddr($peerip, $AdrFamily);
  234: 	return $peername;
  235:     } elsif ($AdrFamily == AF_UNIX) {
  236: 	my $peerfile;
  237: 	($peerfile) = sockaddr_un($peer);
  238: 	return $peerfile;
  239:     }
  240: }
  241: =pod
  242: 
  243: =head2 Debug
  244: 
  245: Invoked to issue a debug message.
  246: 
  247: =cut
  248: 
  249: sub Debug {
  250: 
  251:     my ($level, $message) = @_;
  252: 
  253:     if ($level <= $DebugLevel) {
  254: 	Log("INFO", "-Debug- $message host = $RemoteHost");
  255:     }
  256: }
  257: 
  258: sub SocketDump {
  259: 
  260:     my ($level, $socket) = @_;
  261: 
  262:     if($level <= $DebugLevel) {
  263: 	$socket->Dump(-1);	# Ensure it will get dumped.
  264:     }
  265: }
  266: 
  267: =pod
  268: 
  269: =head2 ShowStatus
  270: 
  271:  Place some text as our pid status.
  272:  and as what we return in a SIGUSR1
  273: 
  274: =cut
  275: 
  276: sub ShowStatus {
  277:     my $state = shift;
  278:     my $now = time;
  279:     my $local = localtime($now);
  280:     $Status   = $local.": ".$state;
  281:     $0='lonc: '.$state.' '.$local;
  282: }
  283: 
  284: =pod
  285: 
  286: =head2 SocketTimeout
  287: 
  288:     Called when an action on the socket times out.  The socket is 
  289:    destroyed and any active transaction is failed.
  290: 
  291: 
  292: =cut
  293: 
  294: sub SocketTimeout {
  295:     my $Socket = shift;
  296:     Log("WARNING", "A socket timeout was detected");
  297:     Debug(5, " SocketTimeout called: ");
  298:     $Socket->Dump(0);
  299:     if(exists($ActiveTransactions{$Socket})) {
  300: 	FailTransaction($ActiveTransactions{$Socket});
  301:     }
  302:     KillSocket($Socket);	# A transaction timeout also counts as
  303:                                 # a connection failure:
  304:     $ConnectionRetriesLeft--;
  305:     if($ConnectionRetriesLeft <= 0) {
  306: 	Log("CRITICAL", "Host marked DEAD: ".GetServerHost());
  307: 	$LondConnecting = 0;
  308:     }
  309: 
  310: }
  311: #
  312: #   This function should be called by the child in all cases where it must
  313: #   exit.  If the child process is running with the DieWhenIdle turned on
  314: #   it must create a lock file for the AF_UNIX socket in order to prevent
  315: #   connection requests from lonnet in the time between process exit
  316: #   and the parent picking up the listen again.
  317: # Parameters:
  318: #     exit_code           - Exit status value, however see the next parameter.
  319: #     message             - If this optional parameter is supplied, the exit
  320: #                           is via a die with this message.
  321: #
  322: sub child_exit {
  323:     my ($exit_code, $message) = @_;
  324: 
  325:     # Regardless of how we exit, we may need to do the lock thing:
  326: 
  327:     if($DieWhenIdle) {
  328: 	#
  329: 	#  Create a lock file since there will be a time window
  330: 	#  between our exit and the parent's picking up the listen
  331: 	#  during which no listens will be done on the
  332: 	#  lonnet client socket.
  333: 	#
  334: 	my $lock_file = GetLoncSocketPath().".lock";
  335: 	open(LOCK,">$lock_file");
  336: 	print LOCK "Contents not important";
  337: 	close(LOCK);
  338: 	
  339: 	exit(0);
  340:     }
  341:     #  Now figure out how we exit:
  342: 
  343:     if($message) {
  344: 	die $message;
  345:     } else {
  346: 	exit($exit_code);
  347:     }
  348: }
  349: #----------------------------- Timer management ------------------------
  350: 
  351: =pod
  352: 
  353: =head2 Tick
  354: 
  355: Invoked  each timer tick.
  356: 
  357: =cut
  358: 
  359: 
  360: sub Tick {
  361:     my ($Event)       = @_;
  362:     my $clock_watcher = $Event->w;
  363: 
  364:     my $client;
  365:     UpdateStatus();
  366: 
  367:     # Is it time to prune connection count:
  368: 
  369: 
  370:     if($IdleConnections->Count()  && 
  371:        ($WorkQueue->Count() == 0)) { # Idle connections and nothing to do?
  372: 	$IdleSeconds++;
  373: 	if($IdleSeconds > $IdleTimeout) { # Prune a connection...
  374: 	    my $Socket = $IdleConnections->pop();
  375: 	    KillSocket($Socket);
  376: 	    $IdleSeconds = 0;	# Otherwise all connections get trimmed to fast.
  377: 	    UpdateStatus();
  378: 	    if(($ConnectionCount == 0) && $DieWhenIdle) {
  379: 		&child_exit(0);
  380: 
  381: 	    }
  382: 	}
  383:     } else {
  384: 	$IdleSeconds = 0;	# Reset idle count if not idle.
  385:     }
  386:     #
  387:     #  For each inflight transaction, tick down its timeout counter.
  388:     #
  389: 
  390:     foreach my $item (keys %ActiveConnections) {
  391: 	my $State = $ActiveConnections{$item}->data->GetState();
  392: 	if ($State ne 'Idle') {
  393: 	    Debug(5,"Ticking Socket $State $item");
  394: 	    $ActiveConnections{$item}->data->Tick();
  395: 	}
  396:     }
  397:     # Do we have work in the queue, but no connections to service them?
  398:     # If so, try to make some new connections to get things going again.
  399:     #
  400:     #   Note this code is dead now...
  401:     #
  402:     my $Requests = $WorkQueue->Count();
  403:     if (($ConnectionCount == 0)  && ($Requests > 0) && (!$LondConnecting)) { 
  404: 	if ($ConnectionRetriesLeft > 0) {
  405: 	    Debug(5,"Work but no connections, Make a new one");
  406: 	    my $success;
  407: 	    $success    = &MakeLondConnection;
  408: 	    if($success == 0) { # All connections failed:
  409: 		Debug(5,"Work in queue failed to make any connectiouns\n");
  410: 		EmptyQueue();	# Fail pending transactions with con_lost.
  411: 		CloseAllLondConnections(); # Should all be closed but....
  412: 	    }
  413: 	} else {
  414: 	    $LondConnecting = 0;
  415: 	    ShowStatus(GetServerHost()." >>> DEAD!!! <<<");
  416: 	    Debug(5,"Work in queue, but gave up on connections..flushing\n");
  417: 	    EmptyQueue();	# Connections can't be established.
  418: 	    CloseAllLondConnections(); # Should all already be closed but...
  419: 	}
  420:        
  421:     }
  422:     if ($ConnectionCount == 0) {
  423: 	$KeyMode = ""; 
  424: 	$clock_watcher->cancel();
  425:     }
  426:     &UpdateStatus();
  427: }
  428: 
  429: =pod
  430: 
  431: =head2 SetupTimer
  432: 
  433: Sets up a 1 per sec recurring timer event.  The event handler is used to:
  434: 
  435: =item
  436: 
  437: Trigger timeouts on communications along active sockets.
  438: 
  439: =item
  440: 
  441: Trigger disconnections of idle sockets.
  442: 
  443: =cut
  444: 
  445: sub SetupTimer {
  446:     Debug(6, "SetupTimer");
  447:     Event->timer(interval => 1, cb => \&Tick );
  448: }
  449: 
  450: =pod
  451: 
  452: =head2 ServerToIdle
  453: 
  454: This function is called when a connection to the server is
  455: ready for more work.
  456: 
  457: If there is work in the Work queue the top element is dequeued
  458: and the connection will start to work on it.  If the work queue is
  459: empty, the connection is pushed on the idle connection stack where
  460: it will either get another work unit, or alternatively, if it sits there
  461: long enough, it will be shut down and released.
  462: 
  463: =cut
  464: 
  465: sub ServerToIdle {
  466:     my $Socket   = shift;	# Get the socket.
  467:     $KeyMode = $Socket->{AuthenticationMode};
  468:     delete($ActiveTransactions{$Socket}); # Server has no transaction
  469: 
  470:     &Debug(5, "Server to idle");
  471: 
  472:     #  If there's work to do, start the transaction:
  473: 
  474:     my $reqdata = $WorkQueue->dequeue(); # This is a LondTransaction
  475:     if ($reqdata ne undef)  {
  476: 	Debug(5, "Queue gave request data: ".$reqdata->getRequest());
  477: 	&StartRequest($Socket,  $reqdata);
  478: 
  479:     } else {
  480: 	
  481:     #  There's no work waiting, so push the server to idle list.
  482: 	&Debug(5, "No new work requests, server connection going idle");
  483: 	$IdleConnections->push($Socket);
  484:     }
  485: }
  486: 
  487: =pod
  488: 
  489: =head2 ClientWritable
  490: 
  491: Event callback for when a client socket is writable.
  492: 
  493: This callback is established when a transaction reponse is
  494: avaiable from lond.  The response is forwarded to the unix socket
  495: as it becomes writable in this sub.
  496: 
  497: Parameters:
  498: 
  499: =item Event
  500: 
  501: The event that has been triggered. Event->w->data is
  502: the data and Event->w->fd is the socket to write.
  503: 
  504: =cut
  505: 
  506: sub ClientWritable {
  507:     my $Event    = shift;
  508:     my $Watcher  = $Event->w;
  509:     my $Data     = $Watcher->data;
  510:     my $Socket   = $Watcher->fd;
  511: 
  512:     # Try to send the data:
  513: 
  514:     &Debug(6, "ClientWritable writing".$Data);
  515:     &Debug(9, "Socket is: ".$Socket);
  516: 
  517:     if($Socket->connected) {
  518: 	my $result = $Socket->send($Data, 0);
  519: 	
  520: 	# $result undefined: the write failed.
  521: 	# otherwise $result is the number of bytes written.
  522: 	# Remove that preceding string from the data.
  523: 	# If the resulting data is empty, destroy the watcher
  524: 	# and set up a read event handler to accept the next
  525: 	# request.
  526: 	
  527: 	&Debug(9,"Send result is ".$result." Defined: ".defined($result));
  528: 	if($result ne undef) {
  529: 	    &Debug(9, "send result was defined");
  530: 	    if($result == length($Data)) { # Entire string sent.
  531: 		&Debug(9, "ClientWritable data all written");
  532: 		$Watcher->cancel();
  533: 		#
  534: 		#  Set up to read next request from socket:
  535: 		
  536: 		my $descr     = sprintf("Connection to lonc client %d",
  537: 					$ActiveClients{$Socket});
  538: 		Event->io(cb    => \&ClientRequest,
  539: 			  poll  => 'r',
  540: 			  desc  => $descr,
  541: 			  data  => "",
  542: 			  fd    => $Socket);
  543: 		
  544: 	    } else {		# Partial string sent.
  545: 		$Watcher->data(substr($Data, $result));
  546: 		if($result == 0) {    # client hung up on us!!
  547: 		    # Log("INFO", "lonc pipe client hung up on us!");
  548: 		    $Watcher->cancel;
  549: 		    $Socket->shutdown(2);
  550: 		    $Socket->close();
  551: 		}
  552: 	    }
  553: 	    
  554: 	} else {			# Error of some sort...
  555: 	    
  556: 	    # Some errnos are possible:
  557: 	    my $errno = $!;
  558: 	    if($errno == POSIX::EWOULDBLOCK   ||
  559: 	       $errno == POSIX::EAGAIN        ||
  560: 	       $errno == POSIX::EINTR) {
  561: 		# No action taken?
  562: 	    } else {		# Unanticipated errno.
  563: 		&Debug(5,"ClientWritable error or peer shutdown".$RemoteHost);
  564: 		$Watcher->cancel;	# Stop the watcher.
  565: 		$Socket->shutdown(2); # Kill connection
  566: 		$Socket->close();	# Close the socket.
  567: 	    }
  568: 	    
  569: 	}
  570:     } else {
  571: 	$Watcher->cancel();	# A delayed request...just cancel.
  572:     }
  573: }
  574: 
  575: =pod
  576: 
  577: =head2 CompleteTransaction
  578: 
  579: Called when the reply data has been received for a lond 
  580: transaction.   The reply data must now be sent to the
  581: ultimate client on the other end of the Unix socket.  This is
  582: done by setting up a writable event for the socket with the
  583: data the reply data.
  584: 
  585: Parameters:
  586: 
  587: =item Socket
  588: 
  589: Socket on which the lond transaction occured.  This is a
  590: LondConnection. The data received is in the TransactionReply member.
  591: 
  592: =item Transaction
  593: 
  594: The transaction that is being completed.
  595: 
  596: =cut
  597: 
  598: sub CompleteTransaction {
  599:     &Debug(5,"Complete transaction");
  600: 
  601:     my ($Socket, $Transaction) = @_;
  602: 
  603:     if (!$Transaction->isDeferred()) { # Normal transaction
  604: 	my $data   = $Socket->GetReply(); # Data to send.
  605: 	if($LogTransactions) {
  606: 	    Log("SUCCESS", "Reply from lond: '$data'");
  607: 	}
  608: 	StartClientReply($Transaction, $data);
  609:     } else {			# Delete deferred transaction file.
  610: 	Log("SUCCESS", "A delayed transaction was completed");
  611: 	LogPerm("S:$Transaction->getClient() :".$Transaction->getRequest());
  612: 	unlink $Transaction->getFile();
  613:     }
  614: }
  615: 
  616: =pod
  617: 
  618: =head1 StartClientReply
  619: 
  620:    Initiates a reply to a client where the reply data is a parameter.
  621: 
  622: =head2  parameters:
  623: 
  624: =item Transaction
  625: 
  626:     The transaction for which we are responding to the client.
  627: 
  628: =item data
  629: 
  630:     The data to send to apached client.
  631: 
  632: =cut
  633: 
  634: sub StartClientReply {
  635: 
  636:     my ($Transaction, $data) = @_;
  637: 
  638:     my $Client   = $Transaction->getClient();
  639: 
  640:     &Debug(8," Reply was: ".$data);
  641:     my $Serial         = $ActiveClients{$Client};
  642:     my $desc           = sprintf("Connection to lonc client %d",
  643: 				 $Serial);
  644:     Event->io(fd       => $Client,
  645: 	      poll     => "w",
  646: 	      desc     => $desc,
  647: 	      cb       => \&ClientWritable,
  648: 	      data     => $data);
  649: }
  650: 
  651: =pod
  652: 
  653: =head2 FailTransaction
  654: 
  655:   Finishes a transaction with failure because the associated lond socket
  656:   disconnected.  There are two possibilities:
  657:   - The transaction is deferred: in which case we just quietly
  658:     delete the transaction since there is no client connection.
  659:   - The transaction is 'live' in which case we initiate the sending
  660:     of "con_lost" to the client.
  661: 
  662: Deleting the transaction means killing it from the %ActiveTransactions hash.
  663: 
  664: Parameters:
  665: 
  666: =item client  
  667:  
  668:    The LondTransaction we are failing.
  669:  
  670: 
  671: =cut
  672: 
  673: sub FailTransaction {
  674:     my $transaction = shift;
  675:     
  676:     #  If the socket is dead, that's already logged.
  677: 
  678:     if ($ConnectionRetriesLeft > 0) {
  679: 	Log("WARNING", "Failing transaction "
  680: 	    .$transaction->getLoggableRequest());
  681:     }
  682:     Debug(1, "Failing transaction: ".$transaction->getLoggableRequest());
  683:     if (!$transaction->isDeferred()) { # If the transaction is deferred we'll get to it.
  684: 	my $client  = $transaction->getClient();
  685: 	Debug(1," Replying con_lost to ".$transaction->getRequest());
  686: 	StartClientReply($transaction, "con_lost\n");
  687:     }
  688: 
  689: }
  690: 
  691: =pod
  692: 
  693: =head1  EmptyQueue
  694: 
  695:   Fails all items in the work queue with con_lost.
  696:   Note that each item in the work queue is a transaction.
  697: 
  698: =cut
  699: 
  700: sub EmptyQueue {
  701:     $ConnectionRetriesLeft--;	# Counts as connection failure too.
  702:     while($WorkQueue->Count()) {
  703: 	my $request = $WorkQueue->dequeue(); # This is a transaction
  704: 	FailTransaction($request);
  705:     }
  706: }
  707: 
  708: =pod
  709: 
  710: =head2 CloseAllLondConnections
  711: 
  712: Close all connections open on lond prior to exit e.g.
  713: 
  714: =cut
  715: 
  716: sub CloseAllLondConnections {
  717:     foreach my $Socket (keys %ActiveConnections) {
  718:       if(exists($ActiveTransactions{$Socket})) {
  719: 	FailTransaction($ActiveTransactions{$Socket});
  720:       }
  721:       KillSocket($Socket);
  722:     }
  723: }
  724: 
  725: =pod
  726: 
  727: =head2 KillSocket
  728:  
  729: Destroys a socket.  This function can be called either when a socket
  730: has died of 'natural' causes or because a socket needs to be pruned due to
  731: idleness.  If the socket has died naturally, if there are no longer any 
  732: live connections a new connection is created (in case there are transactions
  733: in the queue).  If the socket has been pruned, it is never re-created.
  734: 
  735: Parameters:
  736: 
  737: =item Socket
  738:  
  739:   The socket to kill off.
  740: 
  741: =item Restart
  742: 
  743: nonzero if we are allowed to create a new connection.
  744: 
  745: =cut
  746: 
  747: sub KillSocket {
  748:     my $Socket = shift;
  749: 
  750:     Log("WARNING", "Shutting down a socket");
  751:     $Socket->Shutdown();
  752: 
  753:     #  If the socket came from the active connection set,
  754:     #  delete its transaction... note that FailTransaction should
  755:     #  already have been called!!!
  756:     #  otherwise it came from the idle set.
  757:     #  
  758:     
  759:     if(exists($ActiveTransactions{$Socket})) {
  760: 	delete ($ActiveTransactions{$Socket});
  761:     }
  762:     if(exists($ActiveConnections{$Socket})) {
  763: 	delete($ActiveConnections{$Socket});
  764: 	$ConnectionCount--;
  765: 	if ($ConnectionCount < 0) { $ConnectionCount = 0; }
  766:     }
  767:     #  If the connection count has gone to zero and there is work in the
  768:     #  work queue, the work all gets failed with con_lost.
  769:     #
  770:     if($ConnectionCount == 0) {
  771: 	EmptyQueue();
  772: 	CloseAllLondConnections; # Should all already be closed but...
  773:     }
  774: }
  775: 
  776: =pod
  777: 
  778: =head2 LondReadable
  779: 
  780: This function is called whenever a lond connection
  781: is readable.  The action is state dependent:
  782: 
  783: =head3 State=Initialized
  784: 
  785: We''re waiting for the challenge, this is a no-op until the
  786: state changes.
  787: 
  788: =head3 State=Challenged 
  789: 
  790: The challenge has arrived we need to transition to Writable.
  791: The connection must echo the challenge back.
  792: 
  793: =head3 State=ChallengeReplied
  794: 
  795: The challenge has been replied to.  The we are receiveing the 
  796: 'ok' from the partner.
  797: 
  798: =head3  State=ReadingVersionString
  799: 
  800: We have requested the lond version and are reading the
  801: version back.  Upon completion, we'll store the version away
  802: for future use(?).
  803: 
  804: =head3 State=HostSet
  805: 
  806: We have selected the domain name of our peer (multhomed hosts)
  807: and are getting the reply (presumably ok) back.
  808: 
  809: =head3 State=RequestingKey
  810: 
  811: The ok has been received and we need to send the request for
  812: an encryption key.  Transition to writable for that.
  813: 
  814: =head3 State=ReceivingKey
  815: 
  816: The the key has been requested, now we are reading the new key.
  817: 
  818: =head3 State=Idle 
  819: 
  820: The encryption key has been negotiated or we have finished 
  821: reading data from the a transaction.   If the callback data has
  822: a client as well as the socket iformation, then we are 
  823: doing a transaction and the data received is relayed to the client
  824: before the socket is put on the idle list.
  825: 
  826: =head3 State=SendingRequest
  827: 
  828: I do not think this state can be received here, but if it is,
  829: the appropriate thing to do is to transition to writable, and send
  830: the request.
  831: 
  832: =head3 State=ReceivingReply
  833: 
  834: We finished sending the request to the server and now transition
  835: to readable to receive the reply. 
  836: 
  837: The parameter to this function are:
  838: 
  839: The event. Implicit in this is the watcher and its data.  The data 
  840: contains at least the lond connection object and, if a 
  841: transaction is in progress, the socket attached to the local client.
  842: 
  843: =cut
  844: 
  845: sub LondReadable {
  846: 
  847:     my $Event      = shift;
  848:     my $Watcher    = $Event->w;
  849:     my $Socket     = $Watcher->data;
  850:     my $client     = undef;
  851: 
  852:     &Debug(6,"LondReadable called state = ".$Socket->GetState());
  853: 
  854: 
  855:     my $State = $Socket->GetState(); # All action depends on the state.
  856: 
  857:     SocketDump(6, $Socket);
  858:     my $status = $Socket->Readable();
  859: 
  860:     &Debug(2, "Socket->Readable returned: $status");
  861: 
  862:     if($status != 0) {
  863: 	# bad return from socket read. Currently this means that
  864: 	# The socket has become disconnected. We fail the transaction.
  865: 
  866: 	Log("WARNING",
  867: 	    "Lond connection lost.");
  868: 	if(exists($ActiveTransactions{$Socket})) {
  869: 	    FailTransaction($ActiveTransactions{$Socket});
  870: 	} else {
  871: 	    #  Socket is connecting and failed... need to mark
  872: 	    #  no longer connecting.
  873: 	   
  874: 	    $LondConnecting = 0;
  875: 	}
  876: 	$Watcher->cancel();
  877: 	KillSocket($Socket);
  878: 	$ConnectionRetriesLeft--;       # Counts as connection failure
  879: 	return;
  880:     }
  881:     SocketDump(6,$Socket);
  882: 
  883:     $State = $Socket->GetState(); # Update in case of transition.
  884:     &Debug(6, "After read, state is ".$State);
  885: 
  886:     if($State eq "Initialized") {
  887: 
  888: 
  889:     } elsif ($State eq "ChallengeReceived") {
  890: 	#  The challenge must be echoed back;  The state machine
  891: 	# in the connection takes care of setting that up.  Just
  892: 	# need to transition to writable:
  893: 	
  894: 	$Watcher->cb(\&LondWritable);
  895: 	$Watcher->poll("w");
  896: 
  897:     } elsif ($State eq "ChallengeReplied") {
  898: 
  899:     } elsif ($State eq "RequestingVersion") {
  900: 	# Need to ask for the version... that is writiability:
  901: 
  902: 	$Watcher->cb(\&LondWritable);
  903: 	$Watcher->poll("w");
  904: 
  905:     } elsif ($State eq "ReadingVersionString") {
  906: 	# Read the rest of the version string... 
  907:     } elsif ($State eq "SetHost") {
  908: 	# Need to request the actual domain get set...
  909: 
  910: 	$Watcher->cb(\&LondWritable);
  911: 	$Watcher->poll("w");
  912:     } elsif ($State eq "HostSet") {
  913: 	# Reading the 'ok' from the peer.
  914: 
  915:     } elsif ($State eq "RequestingKey") {
  916: 	#  The ok was received.  Now we need to request the key
  917: 	#  That requires us to be writable:
  918: 
  919: 	$Watcher->cb(\&LondWritable);
  920: 	$Watcher->poll("w");
  921: 
  922:     } elsif ($State eq "ReceivingKey") {
  923: 
  924:     } elsif ($State eq "Idle") {
  925:    
  926: 	# This is as good a spot as any to get the peer version
  927: 	# string:
  928:    
  929: 	if($LondVersion eq "unknown") {
  930: 	    $LondVersion = $Socket->PeerVersion();
  931: 	    Log("INFO", "Connected to lond version: $LondVersion");
  932: 	}
  933: 	# If necessary, complete a transaction and then go into the
  934: 	# idle queue.
  935: 	#  Note that a trasition to idle indicates a live lond
  936: 	# on the other end so reset the connection retries.
  937: 	#
  938: 	$ConnectionRetriesLeft = $ConnectionRetries; # success resets the count
  939: 	$Watcher->cancel();
  940: 	if(exists($ActiveTransactions{$Socket})) {
  941: 	    Debug(5,"Completing transaction!!");
  942: 	    CompleteTransaction($Socket, 
  943: 				$ActiveTransactions{$Socket});
  944: 	} else {
  945: 	    Log("SUCCESS", "Connection ".$ConnectionCount." to "
  946: 		.$RemoteHost." now ready for action");
  947: 	}
  948: 	ServerToIdle($Socket);	# Next work unit or idle.
  949: 
  950: 	#
  951: 	$LondConnecting = 0;	# Best spot I can think of for this.
  952: 	# 
  953: 	
  954:     } elsif ($State eq "SendingRequest") {
  955: 	#  We need to be writable for this and probably don't belong
  956: 	#  here inthe first place.
  957: 
  958: 	Deubg(6, "SendingRequest state encountered in readable");
  959: 	$Watcher->poll("w");
  960: 	$Watcher->cb(\&LondWritable);
  961: 
  962:     } elsif ($State eq "ReceivingReply") {
  963: 
  964: 
  965:     } else {
  966: 	# Invalid state.
  967: 	Debug(4, "Invalid state in LondReadable");
  968:     }
  969: }
  970: 
  971: =pod
  972: 
  973: =head2 LondWritable
  974: 
  975: This function is called whenever a lond connection
  976: becomes writable while there is a writeable monitoring
  977: event.  The action taken is very state dependent:
  978: 
  979: =head3 State = Connected 
  980: 
  981: The connection is in the process of sending the 'init' hailing to the
  982: lond on the remote end.  The connection object''s Writable member is
  983: called.  On error, ConnectionError is called to destroy the connection
  984: and remove it from the ActiveConnections hash
  985: 
  986: =head3 Initialized
  987: 
  988: 'init' has been sent, writability monitoring is removed and
  989: readability monitoring is started with LondReadable as the callback.
  990: 
  991: =head3 ChallengeReceived
  992: 
  993: The connection has received the who are you challenge from the remote
  994: system, and is in the process of sending the challenge
  995: response. Writable is called.
  996: 
  997: =head3 ChallengeReplied
  998: 
  999: The connection has replied to the initial challenge The we switch to
 1000: monitoring readability looking for the server to reply with 'ok'.
 1001: 
 1002: =head3 RequestingKey
 1003: 
 1004: The connection is in the process of requesting its encryption key.
 1005: Writable is called.
 1006: 
 1007: =head3 ReceivingKey
 1008: 
 1009: The connection has sent the request for a key.  Switch to readability
 1010: monitoring to accept the key
 1011: 
 1012: =head3 SendingRequest
 1013: 
 1014: The connection is in the process of sending a request to the server.
 1015: This request is part of a client transaction.  All the states until
 1016: now represent the client setup protocol. Writable is called.
 1017: 
 1018: =head3 ReceivingReply
 1019: 
 1020: The connection has sent a request.  Now it must receive a reply.
 1021: Readability monitoring is requested.
 1022: 
 1023: This function is an event handler and therefore receives as
 1024: a parameter the event that has fired.  The data for the watcher
 1025: of this event is a reference to a list of one or two elements,
 1026: depending on state. The first (and possibly only) element is the
 1027: socket.  The second (present only if a request is in progress)
 1028: is the socket on which to return a reply to the caller.
 1029: 
 1030: =cut
 1031: 
 1032: sub LondWritable {
 1033:     my $Event   = shift;
 1034:     my $Watcher = $Event->w;
 1035:     my $Socket  = $Watcher->data;
 1036:     my $State   = $Socket->GetState();
 1037: 
 1038:     Debug(6,"LondWritable State = ".$State."\n");
 1039: 
 1040:  
 1041:     #  Figure out what to do depending on the state of the socket:
 1042:     
 1043: 
 1044: 
 1045: 
 1046:     SocketDump(6,$Socket);
 1047: 
 1048:     #  If the socket is writable, we must always write.
 1049:     # Only by writing will we undergo state transitions.
 1050:     # Old logic wrote in state specific code below, however
 1051:     # That forces us at least through another invocation of
 1052:     # this function after writability is possible again.
 1053:     # This logic also factors out common code for handling
 1054:     # write failures... in all cases, write failures 
 1055:     # Kill the socket.
 1056:     #  This logic makes the branches of the >big< if below
 1057:     # so that the writing states are actually NO-OPs.
 1058: 
 1059:     if ($Socket->Writable() != 0) {
 1060: 	#  The write resulted in an error.
 1061: 	# We'll treat this as if the socket got disconnected:
 1062: 	Log("WARNING", "Connection to ".$RemoteHost.
 1063: 	    " has been disconnected");
 1064: 	if(exists($ActiveTransactions{$Socket})) {
 1065: 	    FailTransaction($ActiveTransactions{$Socket});
 1066: 	} else {
 1067: 	    #  In the process of conneting, so need to turn that off.
 1068: 	    
 1069: 	    $LondConnecting = 0;
 1070: 	}
 1071: 	$Watcher->cancel();
 1072: 	KillSocket($Socket);
 1073: 	return;
 1074:     }
 1075: 
 1076: 
 1077: 
 1078:     if      ($State eq "Connected")         {
 1079: 
 1080: 	#  "init" is being sent...
 1081:  
 1082:     } elsif ($State eq "Initialized")       {
 1083: 
 1084: 	# Now that init was sent, we switch 
 1085: 	# to watching for readability:
 1086: 
 1087: 	$Watcher->cb(\&LondReadable);
 1088: 	$Watcher->poll("r");
 1089: 	
 1090:     } elsif ($State eq "ChallengeReceived") {
 1091: 	# We received the challenge, now we 
 1092: 	# are echoing it back. This is a no-op,
 1093: 	# we're waiting for the state to change
 1094: 	
 1095:     } elsif ($State eq "ChallengeReplied")  {
 1096: 	# The echo was sent back, so we switch
 1097: 	# to watching readability.
 1098: 
 1099: 	$Watcher->cb(\&LondReadable);
 1100: 	$Watcher->poll("r");
 1101:     } elsif ($State eq "RequestingVersion") {
 1102: 	# Sending the peer a version request...
 1103: 
 1104:     } elsif ($State eq "ReadingVersionString") {
 1105: 	# Transition to read since we have sent the
 1106: 	# version command and now just need to read the
 1107: 	# version string from the peer:
 1108:       
 1109: 	$Watcher->cb(\&LondReadable);
 1110: 	$Watcher->poll("r");
 1111:       
 1112:     } elsif ($State eq "SetHost") {
 1113: 	#  Setting the remote domain...
 1114: 
 1115:     } elsif ($State eq "HostSet") {
 1116: 	# Back to readable to get the ok.
 1117:       
 1118: 	$Watcher->cb(\&LondReadable);
 1119: 	$Watcher->poll("r");
 1120:       
 1121: 
 1122:     } elsif ($State eq "RequestingKey")     {
 1123: 	# At this time we're requesting the key.
 1124: 	# again, this is essentially a no-op.
 1125: 
 1126:     } elsif ($State eq "ReceivingKey")      {
 1127: 	# Now we need to wait for the key
 1128: 	# to come back from the peer:
 1129: 
 1130: 	$Watcher->cb(\&LondReadable);
 1131: 	$Watcher->poll("r");
 1132: 
 1133:     } elsif ($State eq "SendingRequest")    {
 1134:  
 1135: 	# At this time we are sending a request to the
 1136: 	# peer... write the next chunk:
 1137: 
 1138: 
 1139:     } elsif ($State eq "ReceivingReply")    {
 1140: 	# The send has completed.  Wait for the
 1141: 	# data to come in for a reply.
 1142: 	Debug(8,"Writable sent request/receiving reply");
 1143: 	$Watcher->cb(\&LondReadable);
 1144: 	$Watcher->poll("r");
 1145: 
 1146:     } else {
 1147: 	#  Control only passes here on an error: 
 1148: 	#  the socket state does not match any
 1149: 	#  of the known states... so an error
 1150: 	#  must be logged.
 1151: 
 1152: 	&Debug(4, "Invalid socket state ".$State."\n");
 1153:     }
 1154:     
 1155: }
 1156: =pod
 1157:     
 1158: =cut
 1159: 
 1160: sub QueueDelayed {
 1161:     Debug(3,"QueueDelayed called");
 1162: 
 1163:     my $path = "$perlvar{'lonSockDir'}/delayed";
 1164: 
 1165:     Debug(4, "Delayed path: ".$path);
 1166:     opendir(DIRHANDLE, $path);
 1167:     
 1168:     my @alldelayed = grep /\.$RemoteHost$/, readdir DIRHANDLE;
 1169:     closedir(DIRHANDLE);
 1170:     my $dfname;
 1171:     my $reqfile;
 1172:     foreach $dfname (sort  @alldelayed) {
 1173: 	$reqfile = "$path/$dfname";
 1174: 	Debug(4, "queueing ".$reqfile);
 1175: 	my $Handle = IO::File->new($reqfile);
 1176: 	my $cmd    = <$Handle>;
 1177: 	chomp $cmd;		# There may or may not be a newline...
 1178: 	$cmd = $cmd."\n";	# now for sure there's exactly one newline.
 1179: 	my $Transaction = LondTransaction->new($cmd);
 1180: 	$Transaction->SetDeferred($reqfile);
 1181: 	QueueTransaction($Transaction);
 1182:     }
 1183:     
 1184: }
 1185: 
 1186: =pod
 1187: 
 1188: =head2 MakeLondConnection
 1189: 
 1190: Create a new lond connection object, and start it towards its initial
 1191: idleness.  Once idle, it becomes elligible to receive transactions
 1192: from the work queue.  If the work queue is not empty when the
 1193: connection is completed and becomes idle, it will dequeue an entry and
 1194: start off on it.
 1195: 
 1196: =cut
 1197: 
 1198: sub MakeLondConnection {     
 1199:     Debug(4,"MakeLondConnection to ".GetServerHost()." on port "
 1200: 	  .GetServerPort());
 1201: 
 1202:     my $Connection = LondConnection->new(&GetServerHost(),
 1203: 					 &GetServerPort());
 1204: 
 1205:     if($Connection eq undef) {	# Needs to be more robust later.
 1206: 	Log("CRITICAL","Failed to make a connection with lond.");
 1207: 	$ConnectionRetriesLeft--;
 1208: 	return 0;		# Failure.
 1209:     }  else {
 1210: 
 1211: 	# The connection needs to have writability 
 1212: 	# monitored in order to send the init sequence
 1213: 	# that starts the whole authentication/key
 1214: 	# exchange underway.
 1215: 	#
 1216: 	my $Socket = $Connection->GetSocket();
 1217: 	if($Socket eq undef) {
 1218: 	    &child_exit(-1, "did not get a socket from the connection");
 1219: 	} else {
 1220: 	    &Debug(9,"MakeLondConnection got socket: ".$Socket);
 1221: 	}
 1222: 	
 1223: 	$Connection->SetTimeoutCallback(\&SocketTimeout);
 1224: 
 1225: 	my $event = Event->io(fd       => $Socket,
 1226: 			   poll     => 'w',
 1227: 			   cb       => \&LondWritable,
 1228: 			   data     => $Connection,
 1229: 			   desc => 'Connection to lond server');
 1230: 	$ActiveConnections{$Connection} = $event;
 1231: 	if ($ConnectionCount == 0) {
 1232: 	    &SetupTimer;	# Need to handle timeouts with connections...
 1233: 	}
 1234: 	$ConnectionCount++;
 1235: 	Debug(4, "Connection count = ".$ConnectionCount);
 1236: 	if($ConnectionCount == 1) { # First Connection:
 1237: 	    QueueDelayed;
 1238: 	}
 1239: 	Log("SUCESS", "Created connection ".$ConnectionCount
 1240: 	    ." to host ".GetServerHost());
 1241: 	$LondConnecting = 1;	# Connection in progress.
 1242: 	return 1;		# Return success.
 1243:     }
 1244:     
 1245: }
 1246: 
 1247: =pod
 1248: 
 1249: =head2 StartRequest
 1250: 
 1251: Starts a lond request going on a specified lond connection.
 1252: parameters are:
 1253: 
 1254: =item $Lond
 1255: 
 1256: Connection to the lond that will send the transaction and receive the
 1257: reply.
 1258: 
 1259: =item $Client
 1260: 
 1261: Connection to the client that is making this request We got the
 1262: request from this socket, and when the request has been relayed to
 1263: lond and we get a reply back from lond it will get sent to this
 1264: socket.
 1265: 
 1266: =item $Request
 1267: 
 1268: The text of the request to send.
 1269: 
 1270: =cut
 1271: 
 1272: sub StartRequest {
 1273: 
 1274:     my ($Lond, $Request) = @_;
 1275:     
 1276:     Debug(6, "StartRequest: ".$Request->getRequest());
 1277: 
 1278:     my $Socket = $Lond->GetSocket();
 1279:     
 1280:     $Request->Activate($Lond);
 1281:     $ActiveTransactions{$Lond} = $Request;
 1282: 
 1283:     $Lond->InitiateTransaction($Request->getRequest());
 1284:     my $event = Event->io(fd      => $Socket,
 1285: 		       poll    => "w",
 1286: 		       cb      => \&LondWritable,
 1287: 		       data    => $Lond,
 1288: 		       desc    => "lond transaction connection");
 1289:     $ActiveConnections{$Lond} = $event;
 1290:     Debug(8," Start Request made watcher data with ".$event->data."\n");
 1291: }
 1292: 
 1293: =pod
 1294: 
 1295: =head2 QueueTransaction
 1296: 
 1297: If there is an idle lond connection, it is put to work doing this
 1298: transaction.  Otherwise, the transaction is placed in the work queue.
 1299: If placed in the work queue and the maximum number of connections has
 1300: not yet been created, a new connection will be started.  Our goal is
 1301: to eventually have a sufficient number of connections that the work
 1302: queue will typically be empty.  parameters are:
 1303: 
 1304: =item Socket
 1305: 
 1306: open on the lonc client.
 1307: 
 1308: =item Request
 1309: 
 1310: data to send to the lond.
 1311: 
 1312: =cut
 1313: 
 1314: sub QueueTransaction {
 1315: 
 1316:     my $requestData   = shift;	# This is a LondTransaction.
 1317:     my $cmd           = $requestData->getRequest();
 1318: 
 1319:     Debug(6,"QueueTransaction: ".$cmd);
 1320: 
 1321:     my $LondSocket    = $IdleConnections->pop();
 1322:     if(!defined $LondSocket) {	# Need to queue request.
 1323: 	Debug(5,"Must queue...");
 1324: 	$WorkQueue->enqueue($requestData);
 1325: 	Debug(5, "Queue Transaction startnew $ConnectionCount $LondConnecting");
 1326: 	if(($ConnectionCount < $MaxConnectionCount)   && (! $LondConnecting)) {
 1327: 
 1328: 	    if($ConnectionRetriesLeft > 0) {
 1329: 		Debug(5,"Starting additional lond connection");
 1330: 		if(&MakeLondConnection() == 0) {
 1331: 		    EmptyQueue();	# Fail transactions, can't make connection.
 1332: 		    CloseAllLondConnections; # Should all be closed but...
 1333: 		}
 1334: 	    } else {
 1335: 		ShowStatus(GetServerHost()." >>> DEAD !!!! <<<");
 1336: 		$LondConnecting = 0;
 1337: 		EmptyQueue();	# It's worse than that ... he's dead Jim.
 1338: 		CloseAllLondConnections; # Should all be closed but..
 1339: 	    }
 1340: 	}
 1341:     } else {			# Can start the request:
 1342: 	Debug(8,"Can start...");
 1343: 	StartRequest($LondSocket,  $requestData);
 1344:     }
 1345: }
 1346: 
 1347: #-------------------------- Lonc UNIX socket handling ---------------------
 1348: 
 1349: =pod
 1350: 
 1351: =head2 ClientRequest
 1352: Callback that is called when data can be read from the UNIX domain
 1353: socket connecting us with an apache server process.
 1354: 
 1355: =cut
 1356: 
 1357: sub ClientRequest {
 1358:     Debug(6, "ClientRequest");
 1359:     my $event   = shift;
 1360:     my $watcher = $event->w;
 1361:     my $socket  = $watcher->fd;
 1362:     my $data    = $watcher->data;
 1363:     my $thisread;
 1364: 
 1365:     Debug(9, "  Watcher named: ".$watcher->desc);
 1366: 
 1367:     my $rv = $socket->recv($thisread, POSIX::BUFSIZ, 0);
 1368:     Debug(8, "rcv:  data length = ".length($thisread)
 1369: 	  ." read =".$thisread);
 1370:     unless (defined $rv  && length($thisread)) {
 1371: 	 # Likely eof on socket.
 1372: 	Debug(5,"Client Socket closed on lonc for ".$RemoteHost);
 1373: 	close($socket);
 1374: 	$watcher->cancel();
 1375: 	delete($ActiveClients{$socket});
 1376: 	return;
 1377:     }
 1378:     Debug(8,"Data: ".$data." this read: ".$thisread);
 1379:     $data = $data.$thisread;	# Append new data.
 1380:     $watcher->data($data);
 1381:     if($data =~ /\n$/) {	# Request entirely read.
 1382: 	if($data eq "close_connection_exit\n") {
 1383: 	    Log("CRITICAL",
 1384: 		"Request Close Connection ... exiting");
 1385: 	    CloseAllLondConnections();
 1386: 	    exit;
 1387: 	}
 1388: 	Debug(8, "Complete transaction received: ".$data);
 1389: 	if($LogTransactions) {
 1390: 	    Log("SUCCESS", "Transaction: '$data'"); # Transaction has \n.
 1391: 	}
 1392: 	my $Transaction = LondTransaction->new($data);
 1393: 	$Transaction->SetClient($socket);
 1394: 	QueueTransaction($Transaction);
 1395: 	$watcher->cancel();	# Done looking for input data.
 1396:     }
 1397: 
 1398: }
 1399: 
 1400: #
 1401: #     Accept a connection request for a client (lonc child) and
 1402: #    start up an event watcher to keep an eye on input from that 
 1403: #    Event.  This can be called both from NewClient and from
 1404: #    ChildProcess if we are started in DieWhenIdle mode.
 1405: # Parameters:
 1406: #    $socket       - The listener socket.
 1407: # Returns:
 1408: #   NONE
 1409: # Side Effects:
 1410: #    An event is made to watch the accepted connection.
 1411: #    Active clients hash is updated to reflect the new connection.
 1412: #    The client connection count is incremented.
 1413: #
 1414: sub accept_client {
 1415:     my ($socket) = @_;
 1416: 
 1417:     Debug(8, "Entering accept for lonc UNIX socket\n");
 1418:     my $connection = $socket->accept();	# Accept the client connection.
 1419:     Debug(8,"Connection request accepted from "
 1420: 	  .GetPeername($connection, AF_UNIX));
 1421: 
 1422: 
 1423:     my $description = sprintf("Connection to lonc client %d",
 1424: 			      $ClientConnection);
 1425:     Debug(9, "Creating event named: ".$description);
 1426:     Event->io(cb      => \&ClientRequest,
 1427: 	      poll    => 'r',
 1428: 	      desc    => $description,
 1429: 	      data    => "",
 1430: 	      fd      => $connection);
 1431:     $ActiveClients{$connection} = $ClientConnection;
 1432:     $ClientConnection++;
 1433: }
 1434: 
 1435: =pod
 1436: 
 1437: =head2  NewClient
 1438: 
 1439: Callback that is called when a connection is received on the unix
 1440: socket for a new client of lonc.  The callback is parameterized by the
 1441: event.. which is a-priori assumed to be an io event, and therefore has
 1442: an fd member that is the Listener socket.  We Accept the connection
 1443: and register a new event on the readability of that socket:
 1444: 
 1445: =cut
 1446: 
 1447: sub NewClient {
 1448:     Debug(6, "NewClient");
 1449:     my $event      = shift;		# Get the event parameters.
 1450:     my $watcher    = $event->w; 
 1451:     my $socket     = $watcher->fd;	# Get the event' socket.
 1452: 
 1453:     &accept_client($socket);
 1454: }
 1455: 
 1456: =pod
 1457: 
 1458: =head2 GetLoncSocketPath
 1459: 
 1460: Returns the name of the UNIX socket on which to listen for client
 1461: connections.
 1462: 
 1463: =head2 Parameters:
 1464: 
 1465:     host (optional)  - Name of the host socket to return.. defaults to
 1466:                        the return from GetServerHost().
 1467: 
 1468: =cut
 1469: 
 1470: sub GetLoncSocketPath {
 1471: 
 1472:     my $host = GetServerHost();	# Default host.
 1473:     if (@_) {
 1474: 	($host)  = @_;		# Override if supplied.
 1475:     }
 1476:     return $UnixSocketDir."/".$host;
 1477: }
 1478: 
 1479: =pod
 1480: 
 1481: =head2 GetServerHost
 1482: 
 1483: Returns the host whose lond we talk with.
 1484: 
 1485: =cut
 1486: 
 1487: sub GetServerHost {
 1488:     return $RemoteHost;		# Setup by the fork.
 1489: }
 1490: 
 1491: =pod
 1492: 
 1493: =head2 GetServerPort
 1494: 
 1495: Returns the lond port number.
 1496: 
 1497: =cut
 1498: 
 1499: sub GetServerPort {
 1500:     return $perlvar{londPort};
 1501: }
 1502: 
 1503: =pod
 1504: 
 1505: =head2 SetupLoncListener
 1506: 
 1507: Setup a lonc listener event.  The event is called when the socket
 1508: becomes readable.. that corresponds to the receipt of a new
 1509: connection.  The event handler established will accept the connection
 1510: (creating a communcations channel), that int turn will establish
 1511: another event handler to subess requests.
 1512: 
 1513: =head2  Parameters:
 1514: 
 1515:    host (optional)   Name of the host to set up a unix socket to.
 1516: 
 1517: =cut
 1518: 
 1519: sub SetupLoncListener {
 1520: 
 1521:     my $host       = GetServerHost(); # Default host.
 1522:     if (@_) {
 1523: 	($host)    = @_		# Override host with parameter.
 1524:     }
 1525: 
 1526:     my $socket;
 1527:     my $SocketName = GetLoncSocketPath($host);
 1528:     unlink($SocketName);
 1529:     unless ($socket =IO::Socket::UNIX->new(Local  => $SocketName,
 1530: 					    Listen => 250, 
 1531: 					    Type   => SOCK_STREAM)) {
 1532: 	if($I_am_child) {
 1533: 	    &child_exit(-1, "Failed to create a lonc listener socket");
 1534: 	} else {
 1535: 	    die "Failed to create a lonc listner socket";
 1536: 	}
 1537:     }
 1538:     return $socket;
 1539: }
 1540: 
 1541: #
 1542: #   Toggle transaction logging.
 1543: #  Implicit inputs:  
 1544: #     LogTransactions
 1545: #  Implicit Outputs:
 1546: #     LogTransactions
 1547: sub ToggleTransactionLogging {
 1548:     print STDERR "Toggle transaction logging...\n";
 1549:     if(!$LogTransactions) {
 1550: 	$LogTransactions = 1;
 1551:     } else {
 1552: 	$LogTransactions = 0;
 1553:     }
 1554: 
 1555: 
 1556:     Log("SUCCESS", "Toggled transaction logging: $LogTransactions \n");
 1557: }
 1558: 
 1559: =pod 
 1560: 
 1561: =head2 ChildStatus
 1562:  
 1563: Child USR1 signal handler to report the most recent status
 1564: into the status file.
 1565: 
 1566: We also use this to reset the retries count in order to allow the
 1567: client to retry connections with a previously dead server.
 1568: 
 1569: =cut
 1570: 
 1571: sub ChildStatus {
 1572:     my $event = shift;
 1573:     my $watcher = $event->w;
 1574: 
 1575:     Debug(2, "Reporting child status because : ".$watcher->data);
 1576:     my $docdir = $perlvar{'lonDocRoot'};
 1577:     
 1578:     open(LOG,">>$docdir/lon-status/loncstatus.txt");
 1579:     flock(LOG,LOCK_EX);
 1580:     print LOG $$."\t".$RemoteHost."\t".$Status."\t".
 1581: 	$RecentLogEntry."\n";
 1582:     #
 1583:     #  Write out information about each of the connections:
 1584:     #
 1585:     if ($DebugLevel > 2) {
 1586: 	print LOG "Active connection statuses: \n";
 1587: 	my $i = 1;
 1588: 	print STDERR  "================================= Socket Status Dump:\n";
 1589: 	foreach my $item (keys %ActiveConnections) {
 1590: 	    my $Socket = $ActiveConnections{$item}->data;
 1591: 	    my $state  = $Socket->GetState();
 1592: 	    print LOG "Connection $i State: $state\n";
 1593: 	    print STDERR "---------------------- Connection $i \n";
 1594: 	    $Socket->Dump(-1);	# Ensure it gets dumped..
 1595: 	    $i++;	
 1596: 	}
 1597:     }
 1598:     flock(LOG,LOCK_UN);
 1599:     close(LOG);
 1600:     $ConnectionRetriesLeft = $ConnectionRetries;
 1601:     UpdateStatus();
 1602: }
 1603: 
 1604: =pod
 1605: 
 1606: =head2 SignalledToDeath
 1607: 
 1608: Called in response to a signal that causes a chid process to die.
 1609: 
 1610: =cut
 1611: 
 1612: 
 1613: sub SignalledToDeath {
 1614:     my $event  = shift;
 1615:     my $watcher= $event->w;
 1616: 
 1617:     Debug(2,"Signalled to death! via ".$watcher->data);
 1618:     my ($signal) = $watcher->data;
 1619:     chomp($signal);
 1620:     Log("CRITICAL", "Abnormal exit.  Child $$ for $RemoteHost "
 1621: 	."died through "."\"$signal\"");
 1622:     #LogPerm("F:lonc: $$ on $RemoteHost signalled to death: "
 1623: #	    ."\"$signal\"");
 1624:     exit 0;
 1625: 
 1626: }
 1627: 
 1628: =pod
 1629: 
 1630: =head2 ToggleDebug
 1631: 
 1632: This sub toggles trace debugging on and off.
 1633: 
 1634: =cut
 1635: 
 1636: sub ToggleDebug {
 1637:     my $Current    = $DebugLevel;
 1638:        $DebugLevel = $NextDebugLevel;
 1639:        $NextDebugLevel = $Current;
 1640: 
 1641:     Log("SUCCESS", "New debugging level for $RemoteHost now $DebugLevel");
 1642: 
 1643: }
 1644: 
 1645: =pod
 1646: 
 1647: =head2 ChildProcess
 1648: 
 1649: This sub implements a child process for a single lonc daemon.
 1650: Optional parameter:
 1651:    $socket  - if provided, this is a socket already open for listen
 1652:               on the client socket. Otherwise, a new listen is set up.
 1653: 
 1654: =cut
 1655: 
 1656: sub ChildProcess {
 1657:     #  If we are in DieWhenIdle mode, we've inherited all the
 1658:     #  events of our parent and those have to be cancelled or else
 1659:     #  all holy bloody chaos will result.. trust me, I already made
 1660:     #  >that< mistake.
 1661: 
 1662:     my $host = GetServerHost();
 1663:     foreach my $listener (keys %parent_dispatchers) {
 1664: 	my $watcher = $parent_dispatchers{$listener};
 1665: 	my $s       = $watcher->fd;
 1666: 	if ($listener ne $host) { # Close everyone but me.
 1667: 	    Debug(5, "Closing listen socket for $listener");
 1668: 	    $s->close();
 1669: 	}
 1670: 	Debug(5, "Killing watcher for $listener");
 1671: 
 1672: 	$watcher->cancel();
 1673: 	delete($parent_dispatchers{$listener});
 1674: 
 1675:     }
 1676: 
 1677:     #  kill off the parent's signal handlers too!  
 1678:     #
 1679: 
 1680:     for my $handler (keys %parent_handlers) {
 1681: 	my $watcher = $parent_handlers{$handler};
 1682: 	$watcher->cancel();
 1683: 	delete($parent_handlers{$handler});
 1684:     }
 1685: 
 1686:     $I_am_child    = 1;		# Seems like in spite of it all I may still getting
 1687:                                 # parent event dispatches.. flag I'm a child.
 1688: 
 1689: 
 1690:     #
 1691:     #  Signals must be handled by the Event framework...
 1692:     #
 1693: 
 1694:     Event->signal(signal   => "QUIT",
 1695: 		  cb       => \&SignalledToDeath,
 1696: 		  data     => "QUIT");
 1697:     Event->signal(signal   => "HUP",
 1698: 		  cb       => \&ChildStatus,
 1699: 		  data     => "HUP");
 1700:     Event->signal(signal   => "USR1",
 1701: 		  cb       => \&ChildStatus,
 1702: 		  data     => "USR1");
 1703:     Event->signal(signal   => "USR2",
 1704: 		  cb       => \&ToggleTransactionLogging);
 1705:     Event->signal(signal   => "INT",
 1706: 		  cb       => \&ToggleDebug,
 1707: 		  data     => "INT");
 1708: 
 1709:     #  Figure out if we got passed a socket or need to open one to listen for
 1710:     #  client requests.
 1711: 
 1712:     my ($socket) = @_;
 1713:     if (!$socket) {
 1714: 
 1715: 	$socket =  SetupLoncListener();
 1716:     }
 1717:     #  Establish an event to listen for client connection requests.
 1718: 
 1719: 
 1720:     Event->io(cb   => \&NewClient,
 1721: 	      poll => 'r',
 1722: 	      desc => 'Lonc Listener Unix Socket',
 1723: 	      fd   => $socket);
 1724:     
 1725:     $Event::Debuglevel = $DebugLevel;
 1726:     
 1727:     Debug(9, "Making initial lond connection for ".$RemoteHost);
 1728: 
 1729: # Setup the initial server connection:
 1730:     
 1731:      # &MakeLondConnection(); // let first work request do it.
 1732: 
 1733:     #  If We are in diwhenidle, need to accept the connection since the
 1734:     #  event may  not fire.
 1735: 
 1736:     if ($DieWhenIdle) {
 1737: 	&accept_client($socket);
 1738:     }
 1739: 
 1740:     Debug(9,"Entering event loop");
 1741:     my $ret = Event::loop();		#  Start the main event loop.
 1742:     
 1743:     
 1744:     &child_exit (-1,"Main event loop exited!!!");
 1745: }
 1746: 
 1747: #  Create a new child for host passed in:
 1748: 
 1749: sub CreateChild {
 1750:     my ($host, $socket) = @_;
 1751: 
 1752:     my $sigset = POSIX::SigSet->new(SIGINT);
 1753:     sigprocmask(SIG_BLOCK, $sigset);
 1754:     $RemoteHost = $host;
 1755:     Log("CRITICAL", "Forking server for ".$host);
 1756:     my $pid          = fork;
 1757:     if($pid) {			# Parent
 1758: 	$RemoteHost = "Parent";
 1759: 	$ChildHash{$pid} = $host;
 1760: 	$HostToPid{$host}= $pid;
 1761: 	sigprocmask(SIG_UNBLOCK, $sigset);
 1762: 
 1763:     } else {			# child.
 1764: 	ShowStatus("Connected to ".$RemoteHost);
 1765: 	$SIG{INT} = 'DEFAULT';
 1766: 	sigprocmask(SIG_UNBLOCK, $sigset);
 1767: 	if(defined $socket) {
 1768: 	    &ChildProcess($socket);
 1769: 	} else {
 1770: 	    ChildProcess;		# Does not return.
 1771: 	}
 1772:     }
 1773: }
 1774: 
 1775: # parent_client_connection:
 1776: #    Event handler that processes client connections for the parent process.
 1777: #    This sub is called when the parent is listening on a socket and
 1778: #    a connection request arrives.  We must:
 1779: #     Start a child process to accept the connection request.
 1780: #     Kill our listen on the socket.
 1781: # Parameter:
 1782: #    event       - The event object that was created to monitor this socket.
 1783: #                  event->w->fd is the socket.
 1784: # Returns:
 1785: #    NONE
 1786: #
 1787: sub parent_client_connection {
 1788:     if ($I_am_child) {
 1789: 	#  Should not get here, but seem to anyway:
 1790: 	&Debug(5," Child caught parent client connection event!!");
 1791: 	my ($event) = @_;
 1792: 	my $watcher = $event->w;
 1793: 	$watcher->cancel();	# Try to kill it off again!!
 1794:     } else {
 1795: 	&Debug(9, "parent_client_connection");
 1796: 	my ($event)   = @_;
 1797: 	my $watcher   = $event->w;
 1798: 	my $socket    = $watcher->fd;
 1799: 	
 1800: 	# Lookup the host associated with this socket:
 1801: 	
 1802: 	my $host = $listening_to{$socket};
 1803: 	
 1804: 	# Start the child:
 1805: 	
 1806: 	
 1807: 	
 1808: 	&Debug(9,"Creating child for $host (parent_client_connection)");
 1809: 	&CreateChild($host, $socket);
 1810: 	
 1811: 	# Clean up the listen since now the child takes over until it exits.
 1812: 	
 1813: 	$watcher->cancel();		# Nolonger listening to this event
 1814: 	delete($listening_to{$socket});
 1815: 	delete($parent_dispatchers{$host});
 1816: 	$socket->close();
 1817:     }
 1818: }
 1819: 
 1820: # parent_listen:
 1821: #    Opens a socket and starts a listen for the parent process on a client UNIX
 1822: #    domain socket.
 1823: #
 1824: #    This involves:
 1825: #       Creating a socket for listen.
 1826: #       Removing any socket lock file
 1827: #       Adding an event handler for this socket becoming readable
 1828: #         To the parent's event dispatcher.
 1829: # Parameters:
 1830: #    loncapa_host    - LonCAPA cluster name of the host represented by the client
 1831: #                      socket.
 1832: # Returns:
 1833: #    NONE
 1834: #
 1835: sub parent_listen {
 1836:     my ($loncapa_host) = @_;
 1837:     Debug(5, "parent_listen: $loncapa_host");
 1838: 
 1839:     my $socket    = &SetupLoncListener($loncapa_host);
 1840:     $listening_to{$socket} = $loncapa_host;
 1841:     if (!$socket) {
 1842: 	die "Unable to create a listen socket for $loncapa_host";
 1843:     }
 1844:     
 1845:     my $lock_file = &GetLoncSocketPath($loncapa_host).".lock";
 1846:     unlink($lock_file);		# No problem if it doesn't exist yet [startup e.g.]
 1847: 
 1848:     my $watcher = Event->io(cb    => \&parent_client_connection,
 1849: 	      poll  => 'r',
 1850: 	      desc  => "Parent listener unix socket ($loncapa_host)",
 1851: 	      fd    => $socket);
 1852:     $parent_dispatchers{$loncapa_host} = $watcher;
 1853: 
 1854: }
 1855: 
 1856: 
 1857: # listen_on_all_unix_sockets:
 1858: #    This sub initiates a listen on all unix domain lonc client sockets.
 1859: #    This will be called in the case where we are trimming idle processes.
 1860: #    When idle processes are trimmed, loncnew starts up with no children,
 1861: #    and only spawns off children when a connection request occurs on the
 1862: #    client unix socket.  The spawned child continues to run until it has
 1863: #    been idle a while at which point it eventually exits and once more
 1864: #    the parent picks up the listen.
 1865: #
 1866: #  Parameters:
 1867: #      NONE
 1868: #  Implicit Inputs:
 1869: #    The configuration file that has been read in by LondConnection.
 1870: #  Returns:
 1871: #     NONE
 1872: #
 1873: sub listen_on_all_unix_sockets {
 1874:     Debug(5, "listen_on_all_unix_sockets");
 1875:     my $host_iterator      =   &LondConnection::GetHostIterator();
 1876:     while (!$host_iterator->end()) {
 1877: 	my $host_entry_ref =   $host_iterator->get();
 1878: 	my $host_name      = $host_entry_ref->[0];
 1879: 	Debug(9, "Listen for $host_name");
 1880: 	&parent_listen($host_name);
 1881: 	$host_iterator->next();
 1882:     }
 1883: }
 1884: 
 1885: #   server_died is called whenever a child process exits.
 1886: #   Since this is dispatched via a signal, we must process all
 1887: #   dead children until there are no more left.  The action
 1888: #   is to:
 1889: #      - Remove the child from the bookeeping hashes
 1890: #      - Re-establish a listen on the unix domain socket associated
 1891: #        with that host.
 1892: # Parameters:
 1893: #    The event, but we don't actually care about it.
 1894: sub server_died {
 1895:     &Debug(9, "server_died called...");
 1896:     
 1897:     while(1) {			# Loop until waitpid nowait fails.
 1898: 	my $pid = waitpid(-1, WNOHANG);
 1899: 	if($pid <= 0) {
 1900: 	    return;		# Nothing left to wait for.
 1901: 	}
 1902: 	# need the host to restart:
 1903: 
 1904: 	my $host = $ChildHash{$pid};
 1905: 	if($host) {		# It's for real...
 1906: 	    &Debug(9, "Caught sigchild for $host");
 1907: 	    delete($ChildHash{$pid});
 1908: 	    delete($HostToPid{$host});
 1909: 	    &parent_listen($host);
 1910: 
 1911: 	} else {
 1912: 	    &Debug(5, "Caught sigchild for pid not in hosts hash: $pid");
 1913: 	}
 1914:     }
 1915: 
 1916: }
 1917: 
 1918: #
 1919: #  Parent process logic pass 1:
 1920: #   For each entry in the hosts table, we will
 1921: #  fork off an instance of ChildProcess to service the transactions
 1922: #  to that host.  Each pid will be entered in a global hash
 1923: #  with the value of the key, the host.
 1924: #  The parent will then enter a loop to wait for process exits.
 1925: #  Each exit gets logged and the child gets restarted.
 1926: #
 1927: 
 1928: #
 1929: #   Fork and start in new session so hang-up isn't going to 
 1930: #   happen without intent.
 1931: #
 1932: 
 1933: 
 1934: 
 1935: 
 1936: 
 1937: 
 1938: ShowStatus("Forming new session");
 1939: my $childpid = fork;
 1940: if ($childpid != 0) {
 1941:     sleep 4;			# Give child a chacne to break to
 1942:     exit 0;			# a new sesion.
 1943: }
 1944: #
 1945: #   Write my pid into the pid file so I can be located
 1946: #
 1947: 
 1948: ShowStatus("Parent writing pid file:");
 1949: my $execdir = $perlvar{'lonDaemons'};
 1950: open (PIDSAVE, ">$execdir/logs/lonc.pid");
 1951: print PIDSAVE "$$\n";
 1952: close(PIDSAVE);
 1953: 
 1954: 
 1955: 
 1956: if (POSIX::setsid() < 0) {
 1957:     print "Could not create new session\n";
 1958:     exit -1;
 1959: }
 1960: 
 1961: ShowStatus("Forking node servers");
 1962: 
 1963: Log("CRITICAL", "--------------- Starting children ---------------");
 1964: 
 1965: LondConnection::ReadConfig;               # Read standard config files.
 1966: my $HostIterator = LondConnection::GetHostIterator;
 1967: 
 1968: if ($DieWhenIdle) {
 1969:     $RemoteHost = "[parent]";
 1970:     &listen_on_all_unix_sockets();
 1971: } else {
 1972:     
 1973:     while (! $HostIterator->end()) {
 1974: 	
 1975: 	my $hostentryref = $HostIterator->get();
 1976: 	CreateChild($hostentryref->[0]);
 1977: 	$HostHash{$hostentryref->[0]} = $hostentryref->[4];
 1978: 	$HostIterator->next();
 1979:     }
 1980: }
 1981: 
 1982: $RemoteHost = "Parent Server";
 1983: 
 1984: # Maintain the population:
 1985: 
 1986: ShowStatus("Parent keeping the flock");
 1987: 
 1988: 
 1989: if ($DieWhenIdle) {
 1990:     # We need to setup a SIGChild event to handle the exit (natural or otherwise)
 1991:     # of the children.
 1992: 
 1993:     Event->signal(cb       => \&server_died,
 1994: 		   desc     => "Child exit handler",
 1995: 		   signal   => "CHLD");
 1996: 
 1997: 
 1998:     # Set up all the other signals we set up.  We'll vector them off to the
 1999:     # same subs as we would for DieWhenIdle false and, if necessary, conditionalize
 2000:     # the code there.
 2001: 
 2002:     $parent_handlers{INT} = Event->signal(cb       => \&Terminate,
 2003: 					  desc     => "Parent INT handler",
 2004: 					  signal   => "INT");
 2005:     $parent_handlers{TERM} = Event->signal(cb       => \&Terminate,
 2006: 					   desc     => "Parent TERM handler",
 2007: 					   signal   => "TERM");
 2008:     $parent_handlers{HUP}  = Event->signal(cb       => \&Restart,
 2009: 					   desc     => "Parent HUP handler.",
 2010: 					   signal   => "HUP");
 2011:     $parent_handlers{USR1} = Event->signal(cb       => \&CheckKids,
 2012: 					   desc     => "Parent USR1 handler",
 2013: 					   signal   => "USR1");
 2014:     $parent_handlers{USR2} = Event->signal(cb       => \&UpdateKids,
 2015: 					   desc     => "Parent USR2 handler.",
 2016: 					   signal   => "USR2");
 2017:     
 2018:     #  Start procdesing events.
 2019: 
 2020:     $Event::DebugLevel = $DebugLevel;
 2021:     Debug(9, "Parent entering event loop");
 2022:     my $ret = Event::loop();
 2023:     die "Main Event loop exited: $ret";
 2024: 
 2025: 
 2026: } else {
 2027:     #
 2028:     #   Set up parent signals:
 2029:     #
 2030:     
 2031:     $SIG{INT}  = \&Terminate;
 2032:     $SIG{TERM} = \&Terminate; 
 2033:     $SIG{HUP}  = \&Restart;
 2034:     $SIG{USR1} = \&CheckKids; 
 2035:     $SIG{USR2} = \&UpdateKids;	# LonManage update request.
 2036:     
 2037:     while(1) {
 2038: 	my $deadchild = wait();
 2039: 	if(exists $ChildHash{$deadchild}) {	# need to restart.
 2040: 	    my $deadhost = $ChildHash{$deadchild};
 2041: 	    delete($HostToPid{$deadhost});
 2042: 	    delete($ChildHash{$deadchild});
 2043: 	    Log("WARNING","Lost child pid= ".$deadchild.
 2044: 		"Connected to host ".$deadhost);
 2045: 	    Log("INFO", "Restarting child procesing ".$deadhost);
 2046: 	    CreateChild($deadhost);
 2047: 	}
 2048:     }
 2049: }
 2050: 
 2051: 
 2052: =pod
 2053: 
 2054: =head1 CheckKids
 2055: 
 2056:   Since kids do not die as easily in this implementation
 2057: as the previous one, there  is no need to restart the
 2058: dead ones (all dead kids get restarted when they die!!)
 2059: The only thing this function does is to pass USR1 to the
 2060: kids so that they report their status.
 2061: 
 2062: =cut
 2063: 
 2064: sub CheckKids {
 2065:     Debug(2, "Checking status of children");
 2066:     my $docdir = $perlvar{'lonDocRoot'};
 2067:     my $fh = IO::File->new(">$docdir/lon-status/loncstatus.txt");
 2068:     my $now=time;
 2069:     my $local=localtime($now);
 2070:     print $fh "LONC status $local - parent $$ \n\n";
 2071:     foreach my $host (keys %parent_dispatchers) {
 2072: 	print $fh "LONC Parent process listening for $host\n";
 2073:     }
 2074:     foreach my $pid (keys %ChildHash) {
 2075: 	Debug(2, "Sending USR1 -> $pid");
 2076: 	kill 'USR1' => $pid;	# Tell Child to report status.
 2077:     }
 2078: 
 2079: }
 2080: 
 2081: =pod
 2082: 
 2083: =head1  UpdateKids
 2084: 
 2085: parent's SIGUSR2 handler.  This handler:
 2086: 
 2087: =item
 2088: 
 2089: Rereads the hosts file.
 2090: 
 2091: =item
 2092:  
 2093: Kills off (via sigint) children for hosts that have disappeared.
 2094: 
 2095: =item
 2096: 
 2097: QUITs  children for hosts that already exist (this just forces a status display
 2098: and resets the connection retry count for that host.
 2099: 
 2100: =item
 2101: 
 2102: Starts new children for hosts that have been added to the hosts.tab file since
 2103: the start of the master program and maintains them.
 2104: 
 2105: =cut
 2106: 
 2107: sub UpdateKids {
 2108: 
 2109:     Log("INFO", "Updating connections via SIGUSR2");
 2110: 
 2111:     #  I'm not sure what I was thinking in the first implementation.
 2112:     # someone will have to work hard to convince me the effect is any
 2113:     # different than Restart, especially now that we don't start up 
 2114:     # per host servers automatically, may as well just restart.
 2115:     # The down side is transactions that are in flight will get timed out
 2116:     # (lost unless they are critical).
 2117: 
 2118:     &Restart();
 2119: 
 2120: }
 2121: 
 2122: 
 2123: =pod
 2124: 
 2125: =head1 Restart
 2126: 
 2127: Signal handler for HUP... all children are killed and
 2128: we self restart.  This is an el-cheapo way to re read
 2129: the config file.
 2130: 
 2131: =cut
 2132: 
 2133: sub Restart {
 2134:     &KillThemAll;		# First kill all the children.
 2135:     Log("CRITICAL", "Restarting");
 2136:     my $execdir = $perlvar{'lonDaemons'};
 2137:     unlink("$execdir/logs/lonc.pid");
 2138:     exec("$executable");
 2139: }
 2140: 
 2141: =pod
 2142: 
 2143: =head1 KillThemAll
 2144: 
 2145: Signal handler that kills all children by sending them a 
 2146: SIGHUP.  Responds to sigint and sigterm.
 2147: 
 2148: =cut
 2149: 
 2150: sub KillThemAll {
 2151:     Debug(2, "Kill them all!!");
 2152:     local($SIG{CHLD}) = 'IGNORE';      # Our children >will< die.
 2153:     foreach my $pid (keys %ChildHash) {
 2154: 	my $serving = $ChildHash{$pid};
 2155: 	ShowStatus("Nicely Killing lonc for $serving pid = $pid");
 2156: 	Log("CRITICAL", "Nicely Killing lonc for $serving pid = $pid");
 2157: 	kill 'QUIT' => $pid;
 2158:     }
 2159: 
 2160: 
 2161: }
 2162: 
 2163: 
 2164: #
 2165: #  Kill all children via KILL.  Just in case the
 2166: #  first shot didn't get them.
 2167: 
 2168: sub really_kill_them_all_dammit
 2169: {
 2170:     Debug(2, "Kill them all Dammit");
 2171:     local($SIG{CHLD} = 'IGNORE'); # In case some purist reenabled them.
 2172:     foreach my $pid (keys %ChildHash) {
 2173: 	my $serving = $ChildHash{$pid};
 2174: 	&ShowStatus("Nastily killing lonc for $serving pid = $pid");
 2175: 	Log("CRITICAL", "Nastily killing lonc for $serving pid = $pid");
 2176: 	kill 'KILL' => $pid;
 2177: 	delete($ChildHash{$pid});
 2178: 	my $execdir = $perlvar{'lonDaemons'};
 2179: 	unlink("$execdir/logs/lonc.pid");
 2180:     }
 2181: }
 2182: 
 2183: =pod
 2184: 
 2185: =head1 Terminate
 2186:  
 2187: Terminate the system.
 2188: 
 2189: =cut
 2190: 
 2191: sub Terminate {
 2192:     &Log("CRITICAL", "Asked to kill children.. first be nice...");
 2193:     &KillThemAll;
 2194:     #
 2195:     #  By now they really should all be dead.. but just in case 
 2196:     #  send them all SIGKILL's after a bit of waiting:
 2197: 
 2198:     sleep(4);
 2199:     &Log("CRITICAL", "Now kill children nasty");
 2200:     &really_kill_them_all_dammit;
 2201:     Log("CRITICAL","Master process exiting");
 2202:     exit 0;
 2203: 
 2204: }
 2205: =pod
 2206: 
 2207: =head1 Theory
 2208: 
 2209: The event class is used to build this as a single process with an
 2210: event driven model.  The following events are handled:
 2211: 
 2212: =item UNIX Socket connection Received
 2213: 
 2214: =item Request data arrives on UNIX data transfer socket.
 2215: 
 2216: =item lond connection becomes writable.
 2217: 
 2218: =item timer fires at 1 second intervals.
 2219: 
 2220: All sockets are run in non-blocking mode.  Timeouts managed by the timer
 2221: handler prevents hung connections.
 2222: 
 2223: Key data structures:
 2224: 
 2225: =item RequestQueue
 2226: 
 2227: A queue of requests received from UNIX sockets that are
 2228: waiting for a chance to be forwarded on a lond connection socket.
 2229: 
 2230: =item ActiveConnections
 2231: 
 2232: A hash of lond connections that have transactions in process that are
 2233: available to be timed out.
 2234: 
 2235: =item ActiveTransactions
 2236: 
 2237: A hash indexed by lond connections that contain the client reply
 2238: socket for each connection that has an active transaction on it.
 2239: 
 2240: =item IdleConnections
 2241: 
 2242: A hash of lond connections that have no work to do.  These connections
 2243: can be closed if they are idle for a long enough time.
 2244: 
 2245: =cut

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>
500 Internal Server Error

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator at root@localhost to inform them of the time this error occurred, and the actions you performed just before this error.

More information about this error may be available in the server error log.