File:  [LON-CAPA] / loncom / loncnew
Revision 1.85: download - view: text, annotated - select for diffs
Tue May 1 01:04:23 2007 UTC (17 years ago) by albertel
Branches: MAIN
CVS tags: version_2_4_0, version_2_3_99_0, HEAD
- when handling the reload need to clear out the children preccesses after they have exited

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

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