File:  [LON-CAPA] / loncom / loncnew
Revision 1.80: download - view: text, annotated - select for diffs
Wed Mar 28 00:23:46 2007 UTC (17 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: HEAD
- eliminate the non-DIeWhenIdle option

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

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