File:  [LON-CAPA] / loncom / loncnew
Revision 1.95: download - view: text, annotated - select for diffs
Mon Jan 24 11:02:32 2011 UTC (13 years, 3 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Add a 'ClientData' member to LondConnection and have loncnew use it to
properly keep track of which connection is which.
(Bug 6377 comment 43).

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

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