Annotation of loncom/loncnew, revision 1.28

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

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