File:  [LON-CAPA] / loncom / loncnew
Revision 1.13: download - view: text, annotated - select for diffs
Wed Jul 2 01:31:55 2003 UTC (20 years, 10 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Added kill -HUP logic (restart).

    1: #!/usr/bin/perl
    2: # The LearningOnline Network with CAPA
    3: # lonc maintains the connections to remote computers
    4: #
    5: # $Id: loncnew,v 1.13 2003/07/02 01:31:55 foxr Exp $
    6: #
    7: # Copyright Michigan State University Board of Trustees
    8: #
    9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
   10: #
   11: # LON-CAPA is free software; you can redistribute it and/or modify
   12: # it under the terms of the GNU General Public License as published by
   13: # the Free Software Foundation; either version 2 of the License, or
   14: # (at your option) any later version.
   15: #
   16: # LON-CAPA is distributed in the hope that it will be useful,
   17: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   18: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   19: # GNU General Public License for more details.
   20: #
   21: # You should have received a copy of the GNU General Public License
   22: # along with LON-CAPA; if not, write to the Free Software
   23: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   24: #
   25: # /home/httpd/html/adm/gpl.txt
   26: #
   27: # http://www.lon-capa.org/
   28: #
   29: #
   30: # new lonc handles n requestors spread out bver m connections to londs.
   31: # This module is based on the Event class.
   32: #   Development iterations:
   33: #    - Setup basic event loop.   (done)
   34: #    - Add timer dispatch.       (done)
   35: #    - Add ability to accept lonc UNIX domain sockets.  (done)
   36: #    - Add ability to create/negotiate lond connections (done).
   37: #    - Add general logic for dispatching requests and timeouts. (done).
   38: #    - Add support for the lonc/lond requests.          (done).
   39: #    - Add logging/status monitoring.
   40: #    - Add Signal handling - HUP restarts. USR1 status report.
   41: #    - Add Configuration file I/O                       (done).
   42: #    - Add management/status request interface.
   43: #    - Add deferred request capability.                  (done)
   44: #    - Detect transmission timeouts.
   45: #
   46: 
   47: # Change log:
   48: #    $Log: loncnew,v $
   49: #    Revision 1.13  2003/07/02 01:31:55  foxr
   50: #    Added kill -HUP logic (restart).
   51: #
   52: #    Revision 1.11  2003/06/25 01:54:44  foxr
   53: #    Fix more problems with transaction failure.
   54: #
   55: #    Revision 1.10  2003/06/24 02:46:04  foxr
   56: #    Put a limit on  the number of times we'll retry a connection.
   57: #    Start getting the signal stuff put in as well...note that need to get signals
   58: #    going or else 6the client will permanently give up on dead servers.
   59: #
   60: #    Revision 1.9  2003/06/13 02:38:43  foxr
   61: #    Add logging in 'expected format'
   62: #
   63: #    Revision 1.8  2003/06/11 02:04:35  foxr
   64: #    Support delayed transactions... this is done uniformly by encapsulating
   65: #    transactions in an object ... a LondTransaction that is implemented by
   66: #    LondTransaction.pm
   67: #
   68: #    Revision 1.7  2003/06/03 01:59:39  foxr
   69: #    complete coding to support deferred transactions.
   70: #
   71: #
   72: 
   73: use lib "/home/httpd/lib/perl/";
   74: use lib "/home/foxr/newloncapa/types";
   75: use Event qw(:DEFAULT );
   76: use POSIX qw(:signal_h);
   77: use POSIX;
   78: use IO::Socket;
   79: use IO::Socket::INET;
   80: use IO::Socket::UNIX;
   81: use IO::File;
   82: use IO::Handle;
   83: use Socket;
   84: use Crypt::IDEA;
   85: use LONCAPA::Queue;
   86: use LONCAPA::Stack;
   87: use LONCAPA::LondConnection;
   88: use LONCAPA::LondTransaction;
   89: use LONCAPA::Configuration;
   90: use LONCAPA::HashIterator;
   91: 
   92: 
   93: #
   94: #   Disable all signals we might receive from outside for now.
   95: #
   96: $SIG{QUIT}  = IGNORE;
   97: $SIG{HUP}   = IGNORE;
   98: $SIG{USR1}  = IGNORE;
   99: $SIG{INT}   = IGNORE;
  100: $SIG{CHLD}  = IGNORE;
  101: $SIG{__DIE__}  = IGNORE;
  102: 
  103: 
  104: # Read the httpd configuration file to get perl variables
  105: # normally set in apache modules:
  106: 
  107: my $perlvarref = LONCAPA::Configuration::read_conf('loncapa.conf');
  108: my %perlvar    = %{$perlvarref};
  109: 
  110: #
  111: #  parent and shared variables.
  112: 
  113: my %ChildHash;			# by pid -> host.
  114: 
  115: 
  116: my $MaxConnectionCount = 10;	# Will get from config later.
  117: my $ClientConnection = 0;	# Uniquifier for client events.
  118: 
  119: my $DebugLevel = 0;
  120: my $IdleTimeout= 3600;		# Wait an hour before pruning connections.
  121: 
  122: #
  123: #  The variables below are only used by the child processes.
  124: #
  125: my $RemoteHost;			# Name of host child is talking to.
  126: my $UnixSocketDir= "/home/httpd/sockets"; 
  127: my $IdleConnections = Stack->new(); # Set of idle connections
  128: my %ActiveConnections;		# Connections to the remote lond.
  129: my %ActiveTransactions;		# LondTransactions in flight.
  130: my %ActiveClients;		# Serial numbers of active clients by socket.
  131: my $WorkQueue       = Queue->new(); # Queue of pending transactions.
  132: my $ConnectionCount = 0;
  133: my $IdleSeconds     = 0;	# Number of seconds idle.
  134: my $Status          = "";	# Current status string.
  135: my $ConnectionRetries=5;	# Number of connection retries allowed.
  136: my $ConnectionRetriesLeft=5;	# Number of connection retries remaining.
  137: 
  138: #
  139: #   The hash below gives the HTML format for log messages
  140: #   given a severity.
  141: #    
  142: my %LogFormats;
  143: 
  144: $LogFormats{"CRITICAL"} = "<font color=red>CRITICAL: %s</font>";
  145: $LogFormats{"SUCCESS"}  = "<font color=green>SUCCESS: %s</font>";
  146: $LogFormats{"INFO"}     = "<font color=yellow>INFO: %s</font>";
  147: $LogFormats{"WARNING"}  = "<font color=blue>WARNING: %s</font>";
  148: $LogFormats{"DEFAULT"}  = " %s ";
  149: 
  150: 
  151: 
  152: =pod
  153: 
  154: =head2 LogPerm
  155: 
  156: Makes an entry into the permanent log file.
  157: 
  158: =cut
  159: sub LogPerm {
  160:     my $message=shift;
  161:     my $execdir=$perlvar{'lonDaemons'};
  162:     my $now=time;
  163:     my $local=localtime($now);
  164:     my $fh=IO::File->new(">>$execdir/logs/lonnet.perm.log");
  165:     print $fh "$now:$message:$local\n";
  166: }
  167: 
  168: =pod
  169: 
  170: =head2 Log
  171: 
  172: Logs a message to the log file.
  173: Parameters:
  174: 
  175: =item severity
  176: 
  177: One of CRITICAL, WARNING, INFO, SUCCESS used to select the
  178: format string used to format the message.  if the severity is
  179: not a defined severity the Default format string is used.
  180: 
  181: =item message
  182: 
  183: The base message.  In addtion to the format string, the message
  184: will be appended to a string containing the name of our remote
  185: host and the time will be formatted into the message.
  186: 
  187: =cut
  188: 
  189: sub Log {
  190:     my $severity = shift;
  191:     my $message  = shift;
  192:    
  193:     if(!$LogFormats{$severity}) {
  194: 	$severity = "DEFAULT";
  195:     }
  196: 
  197:     my $format = $LogFormats{$severity};
  198:     
  199:     #  Put the window dressing in in front of the message format:
  200: 
  201:     my $now   = time;
  202:     my $local = localtime($now);
  203:     my $finalformat = "$local ($$) [$RemoteHost] [$Status] ";
  204:     my $finalformat = $finalformat.$format."\n";
  205: 
  206:     # open the file and put the result.
  207: 
  208:     my $execdir = $perlvar{'lonDaemons'};
  209:     my $fh      = IO::File->new(">>$execdir/logs/lonc.log");
  210:     my $msg = sprintf($finalformat, $message);
  211:     print $fh $msg;
  212:     
  213:     
  214: }
  215: 
  216: 
  217: =pod
  218: 
  219: =head2 GetPeerName
  220: 
  221: Returns the name of the host that a socket object is connected to.
  222: 
  223: =cut
  224: 
  225: sub GetPeername {
  226:     my $connection = shift;
  227:     my $AdrFamily  = shift;
  228:     my $peer       = $connection->peername();
  229:     my $peerport;
  230:     my $peerip;
  231:     if($AdrFamily == AF_INET) {
  232: 	($peerport, $peerip) = sockaddr_in($peer);
  233: 	my $peername    = gethostbyaddr($iaddr, $AdrFamily);
  234: 	return $peername;
  235:     } elsif ($AdrFamily == AF_UNIX) {
  236: 	my $peerfile;
  237: 	($peerfile) = sockaddr_un($peer);
  238: 	return $peerfile;
  239:     }
  240: }
  241: #----------------------------- Timer management ------------------------
  242: =pod
  243: 
  244: =head2 Debug
  245: 
  246: Invoked to issue a debug message.
  247: 
  248: =cut
  249: 
  250: sub Debug {
  251:     my $level   = shift;
  252:     my $message = shift;
  253:     if ($level <= $DebugLevel) {
  254: 	print $message." host = ".$RemoteHost."\n";
  255:     }
  256: }
  257: 
  258: sub SocketDump {
  259:     my $level = shift;
  260:     my $socket= shift;
  261:     if($level <= $DebugLevel) {
  262: 	$socket->Dump();
  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: sub ShowStatus {
  275:     my $state = shift;
  276:     my $now = time;
  277:     my $local = localtime($now);
  278:     $Status   = $local.": ".$state;
  279:     $0='lonc: '.$state.' '.$local;
  280: }
  281: 
  282: =pod
  283: 
  284: =head2 Tick
  285: 
  286: Invoked  each timer tick.
  287: 
  288: =cut
  289: 
  290: 
  291: sub Tick {
  292:     my $client;
  293:     ShowStatus(GetServerHost()." Connection count: ".$ConnectionCount);
  294: 
  295:     # Is it time to prune connection count:
  296: 
  297: 
  298:     if($IdleConnections->Count()  && 
  299:        ($WorkQueue->Count() == 0)) { # Idle connections and nothing to do?
  300: 	$IdleSeconds++;
  301: 	if($IdleSeconds > $IdleTimeout) { # Prune a connection...
  302: 	    $Socket = $IdleConnections->pop();
  303: 	    KillSocket($Socket);
  304: 	}
  305:     } else {
  306: 	$IdleSeconds = 0;	# Reset idle count if not idle.
  307:     }
  308: 
  309:     # Do we have work in the queue, but no connections to service them?
  310:     # If so, try to make some new connections to get things going again.
  311:     #
  312:     
  313:     my $Requests = $WorkQueue->Count();
  314:     if (($ConnectionCount == 0)  && ($Requests > 0)) { 
  315: 	if ($ConnectionRetriesLeft > 0) {
  316: 	    my $Connections = ($Requests <= $MaxConnectionCount) ?
  317: 		$Requests : $MaxConnectionCount;
  318: 	    Debug(1,"Work but no connections, start ".$Connections." of them");
  319: 	    for ($i =0; $i < $Connections; $i++) {
  320: 		MakeLondConnection();
  321: 	    }
  322: 	} else {
  323: 	    Debug(1,"Work in queue, but gave up on connections..flushing\n");
  324: 	    EmptyQueue();	# Connections can't be established.
  325: 	}
  326:        
  327:     }
  328: }
  329: 
  330: =pod
  331: 
  332: =head2 SetupTimer
  333: 
  334: Sets up a 1 per sec recurring timer event.  The event handler is used to:
  335: 
  336: =item
  337: 
  338: Trigger timeouts on communications along active sockets.
  339: 
  340: =item
  341: 
  342: Trigger disconnections of idle sockets.
  343: 
  344: =cut
  345: 
  346: sub SetupTimer {
  347:     Debug(6, "SetupTimer");
  348:     Event->timer(interval => 1, debug => 1, cb => \&Tick );
  349: }
  350: 
  351: =pod
  352: 
  353: =head2 ServerToIdle
  354: 
  355: This function is called when a connection to the server is
  356: ready for more work.
  357: 
  358: If there is work in the Work queue the top element is dequeued
  359: and the connection will start to work on it.  If the work queue is
  360: empty, the connection is pushed on the idle connection stack where
  361: it will either get another work unit, or alternatively, if it sits there
  362: long enough, it will be shut down and released.
  363: 
  364: =cut
  365: 
  366: sub ServerToIdle {
  367:     my $Socket   = shift;	# Get the socket.
  368:     delete($ActiveTransactions{$Socket}); # Server has no transaction
  369: 
  370:     &Debug(6, "Server to idle");
  371: 
  372:     #  If there's work to do, start the transaction:
  373: 
  374:     $reqdata = $WorkQueue->dequeue(); # This is a LondTransaction
  375:     unless($reqdata eq undef)  {
  376: 	Debug(9, "Queue gave request data: ".$reqdata->getRequest());
  377: 	&StartRequest($Socket,  $reqdata);
  378: 
  379:     } else {
  380: 	
  381:     #  There's no work waiting, so push the server to idle list.
  382: 	&Debug(8, "No new work requests, server connection going idle");
  383: 	$IdleConnections->push($Socket);
  384:     }
  385: }
  386: 
  387: =pod
  388: 
  389: =head2 ClientWritable
  390: 
  391: Event callback for when a client socket is writable.
  392: 
  393: This callback is established when a transaction reponse is
  394: avaiable from lond.  The response is forwarded to the unix socket
  395: as it becomes writable in this sub.
  396: 
  397: Parameters:
  398: 
  399: =item Event
  400: 
  401: The event that has been triggered. Event->w->data is
  402: the data and Event->w->fd is the socket to write.
  403: 
  404: =cut
  405: 
  406: sub ClientWritable {
  407:     my $Event    = shift;
  408:     my $Watcher  = $Event->w;
  409:     my $Data     = $Watcher->data;
  410:     my $Socket   = $Watcher->fd;
  411: 
  412:     # Try to send the data:
  413: 
  414:     &Debug(6, "ClientWritable writing".$Data);
  415:     &Debug(9, "Socket is: ".$Socket);
  416: 
  417:     if($Socket->connected) {
  418: 	my $result = $Socket->send($Data, 0);
  419: 	
  420: 	# $result undefined: the write failed.
  421: 	# otherwise $result is the number of bytes written.
  422: 	# Remove that preceding string from the data.
  423: 	# If the resulting data is empty, destroy the watcher
  424: 	# and set up a read event handler to accept the next
  425: 	# request.
  426: 	
  427: 	&Debug(9,"Send result is ".$result." Defined: ".defined($result));
  428: 	if(defined($result)) {
  429: 	    &Debug(9, "send result was defined");
  430: 	    if($result == length($Data)) { # Entire string sent.
  431: 		&Debug(9, "ClientWritable data all written");
  432: 		$Watcher->cancel();
  433: 		#
  434: 		#  Set up to read next request from socket:
  435: 		
  436: 		my $descr     = sprintf("Connection to lonc client %d",
  437: 					$ActiveClients{$Socket});
  438: 		Event->io(cb    => \&ClientRequest,
  439: 			  poll  => 'r',
  440: 			  desc  => $descr,
  441: 			  data  => "",
  442: 			  fd    => $Socket);
  443: 		
  444: 	    } else {		# Partial string sent.
  445: 		$Watcher->data(substr($Data, $result));
  446: 	    }
  447: 	    
  448: 	} else {			# Error of some sort...
  449: 	    
  450: 	    # Some errnos are possible:
  451: 	    my $errno = $!;
  452: 	    if($errno == POSIX::EWOULDBLOCK   ||
  453: 	       $errno == POSIX::EAGAIN        ||
  454: 	       $errno == POSIX::EINTR) {
  455: 		# No action taken?
  456: 	    } else {		# Unanticipated errno.
  457: 		&Debug(5,"ClientWritable error or peer shutdown".$RemoteHost);
  458: 		$Watcher->cancel;	# Stop the watcher.
  459: 		$Socket->shutdown(2); # Kill connection
  460: 		$Socket->close();	# Close the socket.
  461: 	    }
  462: 	    
  463: 	}
  464:     } else {
  465: 	$Watcher->cancel();	# A delayed request...just cancel.
  466:     }
  467: }
  468: 
  469: =pod
  470: 
  471: =head2 CompleteTransaction
  472: 
  473: Called when the reply data has been received for a lond 
  474: transaction.   The reply data must now be sent to the
  475: ultimate client on the other end of the Unix socket.  This is
  476: done by setting up a writable event for the socket with the
  477: data the reply data.
  478: 
  479: Parameters:
  480: 
  481: =item Socket
  482: 
  483: Socket on which the lond transaction occured.  This is a
  484: LondConnection. The data received is in the TransactionReply member.
  485: 
  486: =item Transaction
  487: 
  488: The transaction that is being completed.
  489: 
  490: =cut
  491: 
  492: sub CompleteTransaction {
  493:     &Debug(6,"Complete transaction");
  494:     my $Socket = shift;
  495:     my $Transaction = shift;
  496: 
  497:     if (!$Transaction->isDeferred()) { # Normal transaction
  498: 	my $data   = $Socket->GetReply(); # Data to send.
  499: 	StartClientReply($Transaction, $data);
  500:     } else {			# Delete deferred transaction file.
  501: 	Log("SUCCESS", "A delayed transaction was completed");
  502: 	LogPerm("S:$Client:".$Transaction->getRequest());
  503: 	unlink $Transaction->getFile();
  504:     }
  505: }
  506: =pod
  507: =head1 StartClientReply
  508: 
  509:    Initiates a reply to a client where the reply data is a parameter.
  510: 
  511: =head2  parameters:
  512: 
  513: =item Transaction
  514: 
  515:     The transaction for which we are responding to the client.
  516: 
  517: =item data
  518: 
  519:     The data to send to apached client.
  520: 
  521: =cut
  522: sub StartClientReply {
  523:     my $Transaction   = shift;
  524:     my $data     = shift;
  525: 
  526: 
  527:     my $Client   = $Transaction->getClient();
  528: 
  529:     &Debug(8," Reply was: ".$data);
  530:     my $Serial         = $ActiveClients{$Client};
  531:     my $desc           = sprintf("Connection to lonc client %d",
  532: 
  533: 				 $Serial);
  534:     Event->io(fd       => $Client,
  535: 	      poll     => "w",
  536: 	      desc     => $desc,
  537: 	      cb       => \&ClientWritable,
  538: 	      data     => $data);
  539: }
  540: =pod
  541: =head2 FailTransaction
  542: 
  543:   Finishes a transaction with failure because the associated lond socket
  544:   disconnected.  There are two possibilities:
  545:   - The transaction is deferred: in which case we just quietly
  546:     delete the transaction since there is no client connection.
  547:   - The transaction is 'live' in which case we initiate the sending
  548:     of "con_lost" to the client.
  549: 
  550: Deleting the transaction means killing it from the 
  551: %ActiveTransactions hash.
  552: 
  553: Parameters:
  554: 
  555: =item client  
  556:  
  557:    The LondTransaction we are failing.
  558:  
  559: =cut
  560: 
  561: sub FailTransaction {
  562:     my $transaction = shift;
  563:     Debug(1, "Failing transaction: ".$transaction->getRequest());
  564:     if (!$transaction->isDeferred()) { # If the transaction is deferred we'll get to it.
  565: 	my $client  = $transaction->getClient();
  566: 	Debug(1," Replying con_lost to ".$transaction->getRequest());
  567: 	StartClientReply($transaction, "con_lost\n");
  568:     }
  569: 
  570: }
  571: 
  572: =pod
  573: =head1  EmptyQueue
  574: 
  575:   Fails all items in the work queue with con_lost.
  576:   Note that each item in the work queue is a transaction.
  577: 
  578: =cut
  579: sub EmptyQueue {
  580:     while($WorkQueue->Count()) {
  581: 	my $request = $WorkQueue->dequeue(); # This is a transaction
  582: 	FailTransaction($request);
  583:     }
  584: }
  585: 
  586: =pod
  587: 
  588: =head2 CloseAllLondConnections
  589: 
  590: Close all connections open on lond prior to exit e.g.
  591: 
  592: =cut
  593: sub CloseAllLondConnections {
  594:     foreach $Socket (keys %ActiveConnections) {
  595: 	KillSocket($Socket);
  596:     }
  597: }
  598: =cut
  599: 
  600: =pod
  601: 
  602: =head2 KillSocket
  603:  
  604: Destroys a socket.  This function can be called either when a socket
  605: has died of 'natural' causes or because a socket needs to be pruned due to
  606: idleness.  If the socket has died naturally, if there are no longer any 
  607: live connections a new connection is created (in case there are transactions
  608: in the queue).  If the socket has been pruned, it is never re-created.
  609: 
  610: Parameters:
  611: 
  612: =item Socket
  613:  
  614:   The socket to kill off.
  615: 
  616: =item Restart
  617: 
  618: nonzero if we are allowed to create a new connection.
  619: 
  620: 
  621: =cut
  622: sub KillSocket {
  623:     my $Socket = shift;
  624: 
  625:     $Socket->Shutdown();
  626: 
  627:     #  If the socket came from the active connection set,
  628:     #  delete its transaction... note that FailTransaction should
  629:     #  already have been called!!!
  630:     #  otherwise it came from the idle set.
  631:     #  
  632:     
  633:     if(exists($ActiveTransactions{$Socket})) {
  634: 	delete ($ActiveTransactions{$Socket});
  635:     }
  636:     if(exists($ActiveConnections{$Socket})) {
  637: 	delete($ActiveConnections{$Socket});
  638:     }
  639:     $ConnectionCount--;
  640: 
  641:     #  If the connection count has gone to zero and there is work in the
  642:     #  work queue, the work all gets failed with con_lost.
  643:     #
  644:     if($ConnectionCount == 0) {
  645: 	EmptyQueue;
  646:     }
  647: }
  648: 
  649: =pod
  650: 
  651: =head2 LondReadable
  652: 
  653: This function is called whenever a lond connection
  654: is readable.  The action is state dependent:
  655: 
  656: =head3 State=Initialized
  657: 
  658: We''re waiting for the challenge, this is a no-op until the
  659: state changes.
  660: 
  661: =head3 State=Challenged 
  662: 
  663: The challenge has arrived we need to transition to Writable.
  664: The connection must echo the challenge back.
  665: 
  666: =head3 State=ChallengeReplied
  667: 
  668: The challenge has been replied to.  The we are receiveing the 
  669: 'ok' from the partner.
  670: 
  671: =head3 State=RequestingKey
  672: 
  673: The ok has been received and we need to send the request for
  674: an encryption key.  Transition to writable for that.
  675: 
  676: =head3 State=ReceivingKey
  677: 
  678: The the key has been requested, now we are reading the new key.
  679: 
  680: =head3 State=Idle 
  681: 
  682: The encryption key has been negotiated or we have finished 
  683: reading data from the a transaction.   If the callback data has
  684: a client as well as the socket iformation, then we are 
  685: doing a transaction and the data received is relayed to the client
  686: before the socket is put on the idle list.
  687: 
  688: =head3 State=SendingRequest
  689: 
  690: I do not think this state can be received here, but if it is,
  691: the appropriate thing to do is to transition to writable, and send
  692: the request.
  693: 
  694: =head3 State=ReceivingReply
  695: 
  696: We finished sending the request to the server and now transition
  697: to readable to receive the reply. 
  698: 
  699: The parameter to this function are:
  700: 
  701: The event. Implicit in this is the watcher and its data.  The data 
  702: contains at least the lond connection object and, if a 
  703: transaction is in progress, the socket attached to the local client.
  704: 
  705: =cut
  706: 
  707: sub LondReadable {
  708: 
  709:     my $Event      = shift;
  710:     my $Watcher    = $Event->w;
  711:     my $Socket     = $Watcher->data;
  712:     my $client     = undef;
  713: 
  714:     &Debug(6,"LondReadable called state = ".$State);
  715: 
  716: 
  717:     my $State = $Socket->GetState(); # All action depends on the state.
  718: 
  719:     SocketDump(6, $Socket);
  720:     my $status = $Socket->Readable();
  721:     &Debug(2, "Socket->Readable returned: $status");
  722: 
  723:     if($status != 0) {
  724: 	 # bad return from socket read. Currently this means that
  725: 	# The socket has become disconnected. We fail the transaction.
  726: 
  727: 	if(exists($ActiveTransactions{$Socket})) {
  728: 	    Debug(3,"Lond connection lost failing transaction");
  729: 	    FailTransaction($ActiveTransactions{$Socket});
  730: 	}
  731: 	$Watcher->cancel();
  732: 	KillSocket($Socket);
  733: 	return;
  734:     }
  735:     SocketDump(6,$Socket);
  736: 
  737:     $State = $Socket->GetState(); # Update in case of transition.
  738:     &Debug(6, "After read, state is ".$State);
  739: 
  740:    if($State eq "Initialized") {
  741: 
  742: 
  743:     } elsif ($State eq "ChallengeReceived") {
  744: 	#  The challenge must be echoed back;  The state machine
  745: 	# in the connection takes care of setting that up.  Just
  746: 	# need to transition to writable:
  747: 
  748: 	$Watcher->cb(\&LondWritable);
  749: 	$Watcher->poll("w");
  750: 
  751:     } elsif ($State eq "ChallengeReplied") {
  752: 
  753: 
  754:     } elsif ($State eq "RequestingKey") {
  755: 	#  The ok was received.  Now we need to request the key
  756: 	#  That requires us to be writable:
  757: 
  758: 	$Watcher->cb(\&LondWritable);
  759: 	$Watcher->poll("w");
  760: 
  761:     } elsif ($State eq "ReceivingKey") {
  762: 
  763:     } elsif ($State eq "Idle") {
  764: 	# If necessary, complete a transaction and then go into the
  765: 	# idle queue.
  766: 	$Watcher->cancel();
  767: 	if(exists($ActiveTransactions{$Socket})) {
  768: 	    Debug(8,"Completing transaction!!");
  769: 	    CompleteTransaction($Socket, 
  770: 				$ActiveTransactions{$Socket});
  771: 	} else {
  772: 	    Log("SUCCESS", "Connection ".$ConnectionCount." to "
  773: 		.$RemoteHost." now ready for action");
  774: 	}
  775: 	ServerToIdle($Socket);	# Next work unit or idle.
  776: 	
  777:     } elsif ($State eq "SendingRequest") {
  778: 	#  We need to be writable for this and probably don't belong
  779: 	#  here inthe first place.
  780: 
  781: 	Deubg(6, "SendingRequest state encountered in readable");
  782: 	$Watcher->poll("w");
  783: 	$Watcher->cb(\&LondWritable);
  784: 
  785:     } elsif ($State eq "ReceivingReply") {
  786: 
  787: 
  788:     } else {
  789: 	 # Invalid state.
  790: 	Debug(4, "Invalid state in LondReadable");
  791:     }
  792: }
  793: 
  794: =pod
  795: 
  796: =head2 LondWritable
  797: 
  798: This function is called whenever a lond connection
  799: becomes writable while there is a writeable monitoring
  800: event.  The action taken is very state dependent:
  801: 
  802: =head3 State = Connected 
  803: 
  804: The connection is in the process of sending the 'init' hailing to the
  805: lond on the remote end.  The connection object''s Writable member is
  806: called.  On error, ConnectionError is called to destroy the connection
  807: and remove it from the ActiveConnections hash
  808: 
  809: =head3 Initialized
  810: 
  811: 'init' has been sent, writability monitoring is removed and
  812: readability monitoring is started with LondReadable as the callback.
  813: 
  814: =head3 ChallengeReceived
  815: 
  816: The connection has received the who are you challenge from the remote
  817: system, and is in the process of sending the challenge
  818: response. Writable is called.
  819: 
  820: =head3 ChallengeReplied
  821: 
  822: The connection has replied to the initial challenge The we switch to
  823: monitoring readability looking for the server to reply with 'ok'.
  824: 
  825: =head3 RequestingKey
  826: 
  827: The connection is in the process of requesting its encryption key.
  828: Writable is called.
  829: 
  830: =head3 ReceivingKey
  831: 
  832: The connection has sent the request for a key.  Switch to readability
  833: monitoring to accept the key
  834: 
  835: =head3 SendingRequest
  836: 
  837: The connection is in the process of sending a request to the server.
  838: This request is part of a client transaction.  All the states until
  839: now represent the client setup protocol. Writable is called.
  840: 
  841: =head3 ReceivingReply
  842: 
  843: The connection has sent a request.  Now it must receive a reply.
  844: Readability monitoring is requested.
  845: 
  846: This function is an event handler and therefore receives as
  847: a parameter the event that has fired.  The data for the watcher
  848: of this event is a reference to a list of one or two elements,
  849: depending on state. The first (and possibly only) element is the
  850: socket.  The second (present only if a request is in progress)
  851: is the socket on which to return a reply to the caller.
  852: 
  853: =cut
  854: 
  855: sub LondWritable {
  856:     my $Event   = shift;
  857:     my $Watcher = $Event->w;
  858:     my $Socket  = $Watcher->data;
  859:     my $State   = $Socket->GetState();
  860: 
  861:     Debug(6,"LondWritable State = ".$State."\n");
  862: 
  863:  
  864:     #  Figure out what to do depending on the state of the socket:
  865:     
  866: 
  867: 
  868: 
  869:     SocketDump(6,$Socket);
  870: 
  871:     if      ($State eq "Connected")         {
  872: 
  873: 	if ($Socket->Writable() != 0) {
  874: 	    #  The write resulted in an error.
  875: 	    # We'll treat this as if the socket got disconnected:
  876: 	    Log("WARNING", "Connection to ".$RemoteHost.
  877: 		" has been disconnected");
  878: 	    $Watcher->cancel();
  879: 	    KillSocket($Socket);
  880: 	    return;
  881: 	}
  882: 	#  "init" is being sent...
  883: 
  884: 	
  885:     } elsif ($State eq "Initialized")       {
  886: 
  887: 	# Now that init was sent, we switch 
  888: 	# to watching for readability:
  889: 
  890: 	$Watcher->cb(\&LondReadable);
  891: 	$Watcher->poll("r");
  892: 
  893:     } elsif ($State eq "ChallengeReceived") {
  894: 	# We received the challenge, now we 
  895: 	# are echoing it back. This is a no-op,
  896: 	# we're waiting for the state to change
  897: 	
  898: 	if($Socket->Writable() != 0) {
  899: 
  900: 	    $Watcher->cancel();
  901: 	    KillSocket($Socket);
  902: 	    return;
  903: 	}
  904: 	
  905:     } elsif ($State eq "ChallengeReplied")  {
  906: 	# The echo was sent back, so we switch
  907: 	# to watching readability.
  908: 
  909: 	$Watcher->cb(\&LondReadable);
  910: 	$Watcher->poll("r");
  911: 
  912:     } elsif ($State eq "RequestingKey")     {
  913: 	# At this time we're requesting the key.
  914: 	# again, this is essentially a no-op.
  915: 	# we'll write the next chunk until the
  916: 	# state changes.
  917: 
  918: 	if($Socket->Writable() != 0) {
  919: 	    # Write resulted in an error.
  920: 
  921: 	    $Watcher->cancel();
  922: 	    KillSocket($Socket);
  923: 	    return;
  924: 
  925: 	}
  926:     } elsif ($State eq "ReceivingKey")      {
  927: 	# Now we need to wait for the key
  928: 	# to come back from the peer:
  929: 
  930: 	$Watcher->cb(\&LondReadable);
  931: 	$Watcher->poll("r");
  932: 
  933:     } elsif ($State eq "SendingRequest")    {
  934: 	# At this time we are sending a request to the
  935: 	# peer... write the next chunk:
  936: 
  937: 	if($Socket->Writable() != 0) {
  938: 
  939: 	    if(exists($ActiveTransactions{$Socket})) {
  940: 		Debug(3, "Lond connection lost, failing transactions");
  941: 		FailTransaction($ActiveTransactions{$Socket});
  942: 	    }
  943: 	    $Watcher->cancel();
  944: 	    KillSocket($Socket);
  945: 	    return;
  946: 	    
  947: 	}
  948: 
  949:     } elsif ($State eq "ReceivingReply")    {
  950: 	# The send has completed.  Wait for the
  951: 	# data to come in for a reply.
  952: 	Debug(8,"Writable sent request/receiving reply");
  953: 	$Watcher->cb(\&LondReadable);
  954: 	$Watcher->poll("r");
  955: 
  956:     } else {
  957: 	#  Control only passes here on an error: 
  958: 	#  the socket state does not match any
  959: 	#  of the known states... so an error
  960: 	#  must be logged.
  961: 
  962: 	&Debug(4, "Invalid socket state ".$State."\n");
  963:     }
  964:     
  965: }
  966: =pod
  967:     
  968: =cut
  969: sub QueueDelayed {
  970:     Debug(3,"QueueDelayed called");
  971: 
  972:     my $path = "$perlvar{'lonSockDir'}/delayed";
  973: 
  974:     Debug(4, "Delayed path: ".$path);
  975:     opendir(DIRHANDLE, $path);
  976:     
  977:     @alldelayed = grep /\.$RemoteHost$/, readdir DIRHANDLE;
  978:     Debug(4, "Got ".$alldelayed." delayed files");
  979:     closedir(DIRHANDLE);
  980:     my $dfname;
  981:     my $reqfile;
  982:     foreach $dfname (sort  @alldelayed) {
  983: 	$reqfile = "$path/$dfname";
  984: 	Debug(4, "queueing ".$reqfile);
  985: 	my $Handle = IO::File->new($reqfile);
  986: 	my $cmd    = <$Handle>;
  987: 	chomp $cmd;		# There may or may not be a newline...
  988: 	$cmd = $cmd."\n";	# now for sure there's exactly one newline.
  989: 	my $Transaction = LondTransaction->new($cmd);
  990: 	$Transaction->SetDeferred($reqfile);
  991: 	QueueTransaction($Transaction);
  992:     }
  993:     
  994: }
  995: 
  996: =pod
  997: 
  998: =head2 MakeLondConnection
  999: 
 1000: Create a new lond connection object, and start it towards its initial
 1001: idleness.  Once idle, it becomes elligible to receive transactions
 1002: from the work queue.  If the work queue is not empty when the
 1003: connection is completed and becomes idle, it will dequeue an entry and
 1004: start off on it.
 1005: 
 1006: =cut
 1007: 
 1008: sub MakeLondConnection {     
 1009:     Debug(4,"MakeLondConnection to ".GetServerHost()." on port "
 1010: 	  .GetServerPort());
 1011: 
 1012:     my $Connection = LondConnection->new(&GetServerHost(),
 1013: 					 &GetServerPort());
 1014: 
 1015:     if($Connection == undef) {	# Needs to be more robust later.
 1016: 	Log("CRITICAL","Failed to make a connection with lond.");
 1017: 	$ConnectionRetriesLeft--;
 1018: 	return 0;		# Failure.
 1019:     }  else {
 1020: 	$ConnectionRetriesLeft = $ConnectionRetries; # success resets the count
 1021: 	# The connection needs to have writability 
 1022: 	# monitored in order to send the init sequence
 1023: 	# that starts the whole authentication/key
 1024: 	# exchange underway.
 1025: 	#
 1026: 	my $Socket = $Connection->GetSocket();
 1027: 	if($Socket == undef) {
 1028: 	    die "did not get a socket from the connection";
 1029: 	} else {
 1030: 	    &Debug(9,"MakeLondConnection got socket: ".$Socket);
 1031: 	}
 1032: 	
 1033: 	
 1034: 	$event = Event->io(fd       => $Socket,
 1035: 			   poll     => 'w',
 1036: 			   cb       => \&LondWritable,
 1037: 			   data     => $Connection,
 1038: 			   desc => 'Connection to lond server');
 1039: 	$ActiveConnections{$Connection} = $event;
 1040: 	
 1041: 	$ConnectionCount++;
 1042: 	Debug(4, "Connection count = ".$ConnectionCount);
 1043: 	if($ConnectionCount == 1) { # First Connection:
 1044: 	    QueueDelayed;
 1045: 	}
 1046: 	Log("SUCESS", "Created connection ".$ConnectionCount
 1047: 	    ." to host ".GetServerHost());
 1048: 	return 1;		# Return success.
 1049:     }
 1050:     
 1051: }
 1052: 
 1053: =pod
 1054: 
 1055: =head2 StartRequest
 1056: 
 1057: Starts a lond request going on a specified lond connection.
 1058: parameters are:
 1059: 
 1060: =item $Lond
 1061: 
 1062: Connection to the lond that will send the transaction and receive the
 1063: reply.
 1064: 
 1065: =item $Client
 1066: 
 1067: Connection to the client that is making this request We got the
 1068: request from this socket, and when the request has been relayed to
 1069: lond and we get a reply back from lond it will get sent to this
 1070: socket.
 1071: 
 1072: =item $Request
 1073: 
 1074: The text of the request to send.
 1075: 
 1076: =cut
 1077: 
 1078: sub StartRequest {
 1079:     my $Lond     = shift;
 1080:     my $Request  = shift;	# This is a LondTransaction.
 1081:     
 1082:     Debug(6, "StartRequest: ".$Request->getRequest());
 1083: 
 1084:     my $Socket = $Lond->GetSocket();
 1085:     
 1086:     $Request->Activate($Lond);
 1087:     $ActiveTransactions{$Lond} = $Request;
 1088: 
 1089:     $Lond->InitiateTransaction($Request->getRequest());
 1090:     $event = Event->io(fd      => $Socket,
 1091: 		       poll    => "w",
 1092: 		       cb      => \&LondWritable,
 1093: 		       data    => $Lond,
 1094: 		       desc    => "lond transaction connection");
 1095:     $ActiveConnections{$Lond} = $event;
 1096:     Debug(8," Start Request made watcher data with ".$event->data."\n");
 1097: }
 1098: 
 1099: =pod
 1100: 
 1101: =head2 QueueTransaction
 1102: 
 1103: If there is an idle lond connection, it is put to work doing this
 1104: transaction.  Otherwise, the transaction is placed in the work queue.
 1105: If placed in the work queue and the maximum number of connections has
 1106: not yet been created, a new connection will be started.  Our goal is
 1107: to eventually have a sufficient number of connections that the work
 1108: queue will typically be empty.  parameters are:
 1109: 
 1110: =item Socket
 1111: 
 1112: open on the lonc client.
 1113: 
 1114: =item Request
 1115: 
 1116: data to send to the lond.
 1117: 
 1118: =cut
 1119: 
 1120: sub QueueTransaction {
 1121: 
 1122:     my $requestData   = shift;	# This is a LondTransaction.
 1123:     my $cmd           = $requestData->getRequest();
 1124: 
 1125:     Debug(6,"QueueTransaction: ".$cmd);
 1126: 
 1127:     my $LondSocket    = $IdleConnections->pop();
 1128:     if(!defined $LondSocket) {	# Need to queue request.
 1129: 	Debug(8,"Must queue...");
 1130: 	$WorkQueue->enqueue($requestData);
 1131: 	if($ConnectionCount < $MaxConnectionCount) {
 1132: 	    Debug(4,"Starting additional lond connection");
 1133: 	    MakeLondConnection();
 1134: 	}
 1135:     } else {			# Can start the request:
 1136: 	Debug(8,"Can start...");
 1137: 	StartRequest($LondSocket,  $requestData);
 1138:     }
 1139: }
 1140: 
 1141: #-------------------------- Lonc UNIX socket handling ---------------------
 1142: 
 1143: =pod
 1144: 
 1145: =head2 ClientRequest
 1146: Callback that is called when data can be read from the UNIX domain
 1147: socket connecting us with an apache server process.
 1148: 
 1149: =cut
 1150: 
 1151: sub ClientRequest {
 1152:     Debug(6, "ClientRequest");
 1153:     my $event   = shift;
 1154:     my $watcher = $event->w;
 1155:     my $socket  = $watcher->fd;
 1156:     my $data    = $watcher->data;
 1157:     my $thisread;
 1158: 
 1159:     Debug(9, "  Watcher named: ".$watcher->desc);
 1160: 
 1161:     my $rv = $socket->recv($thisread, POSIX::BUFSIZ, 0);
 1162:     Debug(8, "rcv:  data length = ".length($thisread)
 1163: 	  ." read =".$thisread);
 1164:     unless (defined $rv && length($thisread)) {
 1165: 	 # Likely eof on socket.
 1166: 	Debug(5,"Client Socket closed on lonc for ".$RemoteHost);
 1167: 	close($socket);
 1168: 	$watcher->cancel();
 1169: 	delete($ActiveClients{$socket});
 1170: 	return;
 1171:     }
 1172:     Debug(8,"Data: ".$data." this read: ".$thisread);
 1173:     $data = $data.$thisread;	# Append new data.
 1174:     $watcher->data($data);
 1175:     if($data =~ /(.*\n)/) {	# Request entirely read.
 1176: 	if($data eq "close_connection_exit\n") {
 1177: 	    Log("CRITICAL",
 1178: 		"Request Close Connection ... exiting");
 1179: 	    CloseAllLondConnections();
 1180: 	    exit;
 1181: 	}
 1182: 	Debug(8, "Complete transaction received: ".$data);
 1183: 	my $Transaction = LondTransaction->new($data);
 1184: 	$Transaction->SetClient($socket);
 1185: 	QueueTransaction($Transaction);
 1186: 	$watcher->cancel();	# Done looking for input data.
 1187:     }
 1188: 
 1189: }
 1190: 
 1191: 
 1192: =pod
 1193: 
 1194: =head2  NewClient
 1195: 
 1196: Callback that is called when a connection is received on the unix
 1197: socket for a new client of lonc.  The callback is parameterized by the
 1198: event.. which is a-priori assumed to be an io event, and therefore has
 1199: an fd member that is the Listener socket.  We Accept the connection
 1200: and register a new event on the readability of that socket:
 1201: 
 1202: =cut
 1203: 
 1204: sub NewClient {
 1205:     Debug(6, "NewClient");
 1206:     my $event      = shift;		# Get the event parameters.
 1207:     my $watcher    = $event->w; 
 1208:     my $socket     = $watcher->fd;	# Get the event' socket.
 1209:     my $connection = $socket->accept();	# Accept the client connection.
 1210:     Debug(8,"Connection request accepted from "
 1211: 	  .GetPeername($connection, AF_UNIX));
 1212: 
 1213: 
 1214:     my $description = sprintf("Connection to lonc client %d",
 1215: 			      $ClientConnection);
 1216:     Debug(9, "Creating event named: ".$description);
 1217:     Event->io(cb      => \&ClientRequest,
 1218: 	      poll    => 'r',
 1219: 	      desc    => $description,
 1220: 	      data    => "",
 1221: 	      fd      => $connection);
 1222:     $ActiveClients{$connection} = $ClientConnection;
 1223:     $ClientConnection++;
 1224: }
 1225: 
 1226: =pod
 1227: 
 1228: =head2 GetLoncSocketPath
 1229: 
 1230: Returns the name of the UNIX socket on which to listen for client
 1231: connections.
 1232: 
 1233: =cut
 1234: 
 1235: sub GetLoncSocketPath {
 1236:     return $UnixSocketDir."/".GetServerHost();
 1237: }
 1238: 
 1239: =pod
 1240: 
 1241: =head2 GetServerHost
 1242: 
 1243: Returns the host whose lond we talk with.
 1244: 
 1245: =cut
 1246: 
 1247: sub GetServerHost {
 1248:     return $RemoteHost;		# Setup by the fork.
 1249: }
 1250: 
 1251: =pod
 1252: 
 1253: =head2 GetServerPort
 1254: 
 1255: Returns the lond port number.
 1256: 
 1257: =cut
 1258: 
 1259: sub GetServerPort {
 1260:     return $perlvar{londPort};
 1261: }
 1262: 
 1263: =pod
 1264: 
 1265: =head2 SetupLoncListener
 1266: 
 1267: Setup a lonc listener event.  The event is called when the socket
 1268: becomes readable.. that corresponds to the receipt of a new
 1269: connection.  The event handler established will accept the connection
 1270: (creating a communcations channel), that int turn will establish
 1271: another event handler to subess requests.
 1272: 
 1273: =cut
 1274: 
 1275: sub SetupLoncListener {
 1276: 
 1277:     my $socket;
 1278:     my $SocketName = GetLoncSocketPath();
 1279:     unlink($SocketName);
 1280:     unless ($socket =IO::Socket::UNIX->new(Local  => $SocketName,
 1281: 					    Listen => 10, 
 1282: 					    Type   => SOCK_STREAM)) {
 1283: 	die "Failed to create a lonc listner socket";
 1284:     }
 1285:     Event->io(cb     => \&NewClient,
 1286: 	      poll   => 'r',
 1287: 	      desc   => 'Lonc listener Unix Socket',
 1288: 	      fd     => $socket);
 1289: }
 1290: 
 1291: =pod
 1292: 
 1293: =head2 SignalledToDeath
 1294: 
 1295: Called in response to a signal that causes a chid process to die.
 1296: 
 1297: =cut
 1298: 
 1299: 
 1300: sub SignalledToDeath {
 1301:     Debug(2,"Signalled to death!");
 1302:     my ($signal) = @_;
 1303:     chomp($signal);
 1304:     Log("CRITICAL", "Abnormal exit.  Child $$ for $RemoteHost "
 1305: 	."died through "."\"$signal\"");
 1306:     LogPerm("F:lonc: $$ on $RemoteHost signalled to death: "
 1307: 	    ."\"$signal\"");
 1308:     die("Signal abnormal end");
 1309:     exit 0;
 1310: 
 1311: }
 1312: =head2 ChildProcess
 1313: 
 1314: This sub implements a child process for a single lonc daemon.
 1315: 
 1316: =cut
 1317: 
 1318: sub ChildProcess {
 1319: 
 1320: 
 1321:     # For now turn off signals.
 1322:     
 1323:     $SIG{QUIT}  = \&SignalledToDeath;
 1324:     $SIG{HUP}   = IGNORE;
 1325:     $SIG{USR1}  = IGNORE;
 1326:     $SIG{INT}   = DEFAULT;
 1327:     $SIG{CHLD}  = IGNORE;
 1328:     $SIG{__DIE__}  = \&SignalledToDeath;
 1329: 
 1330:     SetupTimer();
 1331:     
 1332:     SetupLoncListener();
 1333:     
 1334:     $Event::Debuglevel = $DebugLevel;
 1335:     
 1336:     Debug(9, "Making initial lond connection for ".$RemoteHost);
 1337: 
 1338: # Setup the initial server connection:
 1339:     
 1340:      # &MakeLondConnection(); // let first work requirest do it.
 1341: 
 1342: 
 1343:     Debug(9,"Entering event loop");
 1344:     my $ret = Event::loop();		#  Start the main event loop.
 1345:     
 1346:     
 1347:     die "Main event loop exited!!!";
 1348: }
 1349: 
 1350: #  Create a new child for host passed in:
 1351: 
 1352: sub CreateChild {
 1353:     my $sigset = POSIX::SigSet->new(SIGINT);
 1354:     sigprocmask(SIG_BLOCK, $sigset);
 1355:     my $host = shift;
 1356:     $RemoteHost = $host;
 1357:     Log("CRITICAL", "Forking server for ".$host);
 1358:     $pid          = fork;
 1359:     if($pid) {			# Parent
 1360: 	$ChildHash{$pid} = $RemoteHost;
 1361: 	sigprocmask(SIG_UNBLOCK, $sigset);
 1362: 
 1363:     } else {			# child.
 1364: 	ShowStatus("Connected to ".$RemoteHost);
 1365: 	$SIG{INT} = DEFAULT;
 1366: 	sigprocmask(SIG_UNBLOCK, $sigset);
 1367: 	ChildProcess;		# Does not return.
 1368:     }
 1369: 
 1370: }
 1371: #
 1372: #  Parent process logic pass 1:
 1373: #   For each entry in the hosts table, we will
 1374: #  fork off an instance of ChildProcess to service the transactions
 1375: #  to that host.  Each pid will be entered in a global hash
 1376: #  with the value of the key, the host.
 1377: #  The parent will then enter a loop to wait for process exits.
 1378: #  Each exit gets logged and the child gets restarted.
 1379: #
 1380: 
 1381: #
 1382: #   Fork and start in new session so hang-up isn't going to 
 1383: #   happen without intent.
 1384: #
 1385: 
 1386: 
 1387: 
 1388: 
 1389: 
 1390: 
 1391: ShowStatus("Forming new session");
 1392: my $childpid = fork;
 1393: if ($childpid != 0) {
 1394:     sleep 4;			# Give child a chacne to break to
 1395:     exit 0;			# a new sesion.
 1396: }
 1397: #
 1398: #   Write my pid into the pid file so I can be located
 1399: #
 1400: 
 1401: ShowStatus("Parent writing pid file:");
 1402: $execdir = $perlvar{'lonDaemons'};
 1403: open (PIDSAVE, ">$execdir/logs/lonc.pid");
 1404: print PIDSAVE "$$\n";
 1405: close(PIDSAVE);
 1406: 
 1407: if (POSIX::setsid() < 0) {
 1408:     print "Could not create new session\n";
 1409:     exit -1;
 1410: }
 1411: 
 1412: ShowStatus("Forking node servers");
 1413: 
 1414: Log("CRITICAL", "--------------- Starting children ---------------");
 1415: 
 1416: my $HostIterator = LondConnection::GetHostIterator;
 1417: while (! $HostIterator->end()) {
 1418: 
 1419:     $hostentryref = $HostIterator->get();
 1420:     CreateChild($hostentryref->[0]);
 1421:     $HostIterator->next();
 1422: }
 1423: $RemoteHost = "Parent Server";
 1424: 
 1425: # Maintain the population:
 1426: 
 1427: ShowStatus("Parent keeping the flock");
 1428: 
 1429: #
 1430: #   Set up parent signals:
 1431: #
 1432: 
 1433: $SIG{INT}  = \&KillThemAll;
 1434: $SIG{TERM} = \&KillThemAll; 
 1435: $SIG{HUP}  = \&Restart;
 1436: 
 1437: while(1) {
 1438:     $deadchild = wait();
 1439:     if(exists $ChildHash{$deadchild}) {	# need to restart.
 1440: 	$deadhost = $ChildHash{$deadchild};
 1441: 	delete($ChildHash{$deadchild});
 1442: 	Log("WARNING","Lost child pid= ".$deadchild.
 1443: 	      "Connected to host ".$deadhost);
 1444: 	Log("INFO", "Restarting child procesing ".$deadhost);
 1445: 	CreateChild($deadhost);
 1446:     }
 1447: }
 1448: 
 1449: =pod
 1450: 
 1451: =head1 Restart
 1452: 
 1453: Signal handler for HUP... all children are killed and
 1454: we self restart.  This is an el-cheapo way to re read
 1455: the config file.
 1456: 
 1457: =cut
 1458: 
 1459: sub Restart {
 1460:     KillThemAll;		# First kill all the children.
 1461:     Log("CRITICAL", "Restarting");
 1462:     my $execdir = $perlvar{'lonDaemons'};
 1463:     unlink("$execdir/logs/lonc.pid");
 1464:     exec("$execdir/lonc");
 1465: }
 1466: 
 1467: =pod
 1468: 
 1469: =head1 KillThemAll
 1470: 
 1471: Signal handler that kills all children by sending them a 
 1472: SIGINT.  Responds to sigint and sigterm.
 1473: 
 1474: =cut
 1475: 
 1476: sub KillThemAll {
 1477:     Debug(2, "Kill them all!!");
 1478:     local($SIG{CHLD}) = 'IGNORE';      # Our children >will< die.
 1479:     foreach $pid (keys %ChildHash) {
 1480: 	my $serving = $ChildHash{$pid};
 1481: 	Debug(2, "Killing lonc for $serving pid = $pid");
 1482: 	ShowStatus("Killing lonc for $serving pid = $pid");
 1483: 	Log("CRITICAL", "Killing lonc for $serving pid = $pid");
 1484: 	kill('INT', $pid);
 1485:     }
 1486:     Log("CRITICAL", "Killing the master process.");
 1487:     exit
 1488: }
 1489: 
 1490: =pod
 1491: 
 1492: =head1 Theory
 1493: 
 1494: The event class is used to build this as a single process with an
 1495: event driven model.  The following events are handled:
 1496: 
 1497: =item UNIX Socket connection Received
 1498: 
 1499: =item Request data arrives on UNIX data transfer socket.
 1500: 
 1501: =item lond connection becomes writable.
 1502: 
 1503: =item timer fires at 1 second intervals.
 1504: 
 1505: All sockets are run in non-blocking mode.  Timeouts managed by the timer
 1506: handler prevents hung connections.
 1507: 
 1508: Key data structures:
 1509: 
 1510: =item RequestQueue
 1511: 
 1512: A queue of requests received from UNIX sockets that are
 1513: waiting for a chance to be forwarded on a lond connection socket.
 1514: 
 1515: =item ActiveConnections
 1516: 
 1517: A hash of lond connections that have transactions in process that are
 1518: available to be timed out.
 1519: 
 1520: =item ActiveTransactions
 1521: 
 1522: A hash indexed by lond connections that contain the client reply
 1523: socket for each connection that has an active transaction on it.
 1524: 
 1525: =item IdleConnections
 1526: 
 1527: A hash of lond connections that have no work to do.  These connections
 1528: can be closed if they are idle for a long enough time.
 1529: 
 1530: =cut

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