Annotation of loncom/loncnew, revision 1.38

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

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