File:  [LON-CAPA] / loncom / loncnew
Revision 1.91: download - view: text, annotated - select for diffs
Mon Dec 20 11:31:52 2010 UTC (13 years, 4 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Ensure that time on flock keeping messages (forking server) in logs are
updated...note that this will make the ps axuww message include the time
of the last fork if I'm reading the code correctly..rather than the
start time.

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

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