Annotation of loncom/loncnew, revision 1.26

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

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