File:  [LON-CAPA] / loncom / loncnew
Revision 1.83: download - view: text, annotated - select for diffs
Wed Apr 11 00:10:45 2007 UTC (17 years ago) by albertel
Branches: MAIN
CVS tags: HEAD
- when there is a race to create a connection make sure only one child gets forked off

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

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