Annotation of loncom/loncnew, revision 1.37

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

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