Annotation of loncom/loncnew, revision 1.29

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

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