File:  [LON-CAPA] / loncom / loncnew
Revision 1.81: download - view: text, annotated - select for diffs
Wed Mar 28 20:28:29 2007 UTC (17 years, 1 month ago) by albertel
Branches: MAIN
CVS tags: HEAD
- eliminate any reading of hosts.tab from loncnew
- launch of lonc connection requires passing the lonid through the common
  launch socket
- dealyed messages getting sent again (requires loncnew using lonnet....)

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