File:  [LON-CAPA] / loncom / loncnew
Revision 1.106: download - view: text, annotated - select for diffs
Thu Dec 6 13:52:28 2018 UTC (5 years, 4 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Remove unused assignment added in rev. 1.105

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

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