Annotation of loncom/loncnew, revision 1.17

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

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