File:  [LON-CAPA] / loncom / loncnew
Revision 1.8: download - view: text, annotated - select for diffs
Wed Jun 11 02:04:35 2003 UTC (20 years, 11 months ago) by foxr
Branches: MAIN
CVS tags: HEAD
Support delayed transactions... this is done uniformly by encapsulating
transactions in an object ... a LondTransaction that is implemented by
LondTransaction.pm

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

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