Annotation of loncom/loncnew, revision 1.30

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

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