Annotation of loncom/loncnew, revision 1.97

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.97    ! raeburn     5: # $Id: loncnew,v 1.96 2011/01/25 11:02:35 foxr Exp $
1.2       albertel    6: #
                      7: # Copyright Michigan State University Board of Trustees
                      8: #
                      9: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
1.17      foxr       10: ## LON-CAPA is free software; you can redistribute it and/or modify
1.2       albertel   11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       foxr       28: #
1.97    ! raeburn    29: # new lonc handles n request out over m connections to londs.
1.1       foxr       30: # This module is based on the Event class.
                     31: #   Development iterations:
                     32: #    - Setup basic event loop.   (done)
                     33: #    - Add timer dispatch.       (done)
                     34: #    - Add ability to accept lonc UNIX domain sockets.  (done)
                     35: #    - Add ability to create/negotiate lond connections (done).
1.7       foxr       36: #    - Add general logic for dispatching requests and timeouts. (done).
                     37: #    - Add support for the lonc/lond requests.          (done).
1.38      foxr       38: #    - Add logging/status monitoring.                    (done)
                     39: #    - Add Signal handling - HUP restarts. USR1 status report. (done)
1.7       foxr       40: #    - Add Configuration file I/O                       (done).
1.38      foxr       41: #    - Add management/status request interface.         (done)
1.8       foxr       42: #    - Add deferred request capability.                  (done)
1.38      foxr       43: #    - Detect transmission timeouts.                     (done)
1.7       foxr       44: #
                     45: 
1.23      foxr       46: use strict;
1.1       foxr       47: use lib "/home/httpd/lib/perl/";
                     48: use Event qw(:DEFAULT );
                     49: use POSIX qw(:signal_h);
1.12      foxr       50: use POSIX;
1.1       foxr       51: use IO::Socket;
                     52: use IO::Socket::INET;
                     53: use IO::Socket::UNIX;
1.9       foxr       54: use IO::File;
1.6       foxr       55: use IO::Handle;
1.1       foxr       56: use Socket;
                     57: use Crypt::IDEA;
                     58: use LONCAPA::Queue;
                     59: use LONCAPA::Stack;
                     60: use LONCAPA::LondConnection;
1.7       foxr       61: use LONCAPA::LondTransaction;
1.1       foxr       62: use LONCAPA::Configuration;
1.67      albertel   63: use Fcntl qw(:flock);
1.1       foxr       64: 
                     65: 
                     66: # Read the httpd configuration file to get perl variables
                     67: # normally set in apache modules:
                     68: 
                     69: my $perlvarref = LONCAPA::Configuration::read_conf('loncapa.conf');
                     70: my %perlvar    = %{$perlvarref};
                     71: 
                     72: #
                     73: #  parent and shared variables.
                     74: 
1.83      albertel   75: my %ChildPid;			# by pid -> host.
                     76: my %ChildHost;			# by host.
1.62      foxr       77: my %listening_to;		# Socket->host table for who the parent
                     78:                                 # is listening to.
                     79: my %parent_dispatchers;         # host-> listener watcher events. 
1.1       foxr       80: 
1.65      foxr       81: my %parent_handlers;		# Parent signal handlers...
                     82: 
1.9       foxr       83: my $MaxConnectionCount = 10;	# Will get from config later.
1.1       foxr       84: my $ClientConnection = 0;	# Uniquifier for client events.
                     85: 
1.9       foxr       86: my $DebugLevel = 0;
1.29      foxr       87: my $NextDebugLevel= 2;		# So Sigint can toggle this.
1.94      foxr       88: my $IdleTimeout= 5*60;		# Seconds to wait prior to pruning connections.
1.1       foxr       89: 
1.39      foxr       90: my $LogTransactions = 0;	# When True, all transactions/replies get logged.
1.65      foxr       91: my $executable      = $0;	# Get the full path to me.
1.39      foxr       92: 
1.1       foxr       93: #
                     94: #  The variables below are only used by the child processes.
                     95: #
                     96: my $RemoteHost;			# Name of host child is talking to.
1.81      albertel   97: my $RemoteHostId;		# default lonid of host child is talking to.
1.82      albertel   98: my @all_host_ids;
1.20      albertel   99: my $UnixSocketDir= $perlvar{'lonSockDir'};
1.1       foxr      100: my $IdleConnections = Stack->new(); # Set of idle connections
                    101: my %ActiveConnections;		# Connections to the remote lond.
1.7       foxr      102: my %ActiveTransactions;		# LondTransactions in flight.
1.1       foxr      103: my %ActiveClients;		# Serial numbers of active clients by socket.
                    104: my $WorkQueue       = Queue->new(); # Queue of pending transactions.
                    105: my $ConnectionCount = 0;
1.4       foxr      106: my $IdleSeconds     = 0;	# Number of seconds idle.
1.9       foxr      107: my $Status          = "";	# Current status string.
1.14      foxr      108: my $RecentLogEntry  = "";
1.72      albertel  109: my $ConnectionRetries=5;	# Number of connection retries allowed.
                    110: my $ConnectionRetriesLeft=5;	# Number of connection retries remaining.
1.40      foxr      111: my $LondVersion     = "unknown"; # Version of lond we talk with.
1.49      foxr      112: my $KeyMode         = "";       # e.g. ssl, local, insecure from last connect.
1.54      foxr      113: my $LondConnecting  = 0;       # True when a connection is being built.
1.1       foxr      114: 
1.60      foxr      115: 
                    116: 
1.62      foxr      117: my $I_am_child      = 0;	# True if this is the child process.
1.57      foxr      118: 
1.1       foxr      119: #
1.9       foxr      120: #   The hash below gives the HTML format for log messages
                    121: #   given a severity.
                    122: #    
                    123: my %LogFormats;
                    124: 
1.45      albertel  125: $LogFormats{"CRITICAL"} = "<font color='red'>CRITICAL: %s</font>";
                    126: $LogFormats{"SUCCESS"}  = "<font color='green'>SUCCESS: %s</font>";
                    127: $LogFormats{"INFO"}     = "<font color='yellow'>INFO: %s</font>";
                    128: $LogFormats{"WARNING"}  = "<font color='blue'>WARNING: %s</font>";
1.9       foxr      129: $LogFormats{"DEFAULT"}  = " %s ";
                    130: 
1.10      foxr      131: 
1.57      foxr      132: #  UpdateStatus;
                    133: #    Update the idle status display to show how many connections
                    134: #    are left, retries and other stuff.
                    135: #
                    136: sub UpdateStatus {
                    137:     if ($ConnectionRetriesLeft > 0) {
                    138: 	ShowStatus(GetServerHost()." Connection count: ".$ConnectionCount
                    139: 		   ." Retries remaining: ".$ConnectionRetriesLeft
                    140: 		   ." ($KeyMode)");
                    141:     } else {
                    142: 	ShowStatus(GetServerHost()." >> DEAD <<");
                    143:     }
                    144: }
                    145: 
1.10      foxr      146: 
                    147: =pod
                    148: 
                    149: =head2 LogPerm
                    150: 
                    151: Makes an entry into the permanent log file.
                    152: 
                    153: =cut
1.69      matthew   154: 
1.10      foxr      155: sub LogPerm {
                    156:     my $message=shift;
                    157:     my $execdir=$perlvar{'lonDaemons'};
                    158:     my $now=time;
                    159:     my $local=localtime($now);
                    160:     my $fh=IO::File->new(">>$execdir/logs/lonnet.perm.log");
1.86      albertel  161:     chomp($message);
1.10      foxr      162:     print $fh "$now:$message:$local\n";
                    163: }
1.9       foxr      164: 
                    165: =pod
                    166: 
                    167: =head2 Log
                    168: 
                    169: Logs a message to the log file.
                    170: Parameters:
                    171: 
                    172: =item severity
                    173: 
                    174: One of CRITICAL, WARNING, INFO, SUCCESS used to select the
                    175: format string used to format the message.  if the severity is
                    176: not a defined severity the Default format string is used.
                    177: 
                    178: =item message
                    179: 
                    180: The base message.  In addtion to the format string, the message
                    181: will be appended to a string containing the name of our remote
                    182: host and the time will be formatted into the message.
                    183: 
                    184: =cut
                    185: 
                    186: sub Log {
1.47      foxr      187: 
                    188:     my ($severity, $message) = @_;
                    189: 
1.9       foxr      190:     if(!$LogFormats{$severity}) {
                    191: 	$severity = "DEFAULT";
                    192:     }
                    193: 
                    194:     my $format = $LogFormats{$severity};
                    195:     
                    196:     #  Put the window dressing in in front of the message format:
                    197: 
                    198:     my $now   = time;
                    199:     my $local = localtime($now);
                    200:     my $finalformat = "$local ($$) [$RemoteHost] [$Status] ";
1.76      albertel  201:     $finalformat = $finalformat.$format."\n";
1.9       foxr      202: 
                    203:     # open the file and put the result.
                    204: 
                    205:     my $execdir = $perlvar{'lonDaemons'};
                    206:     my $fh      = IO::File->new(">>$execdir/logs/lonc.log");
                    207:     my $msg = sprintf($finalformat, $message);
1.14      foxr      208:     $RecentLogEntry = $msg;
1.9       foxr      209:     print $fh $msg;
                    210:     
1.10      foxr      211:     
1.9       foxr      212: }
1.6       foxr      213: 
1.3       albertel  214: 
1.1       foxr      215: =pod
1.3       albertel  216: 
                    217: =head2 GetPeerName
                    218: 
                    219: Returns the name of the host that a socket object is connected to.
                    220: 
1.1       foxr      221: =cut
                    222: 
                    223: sub GetPeername {
1.47      foxr      224: 
                    225: 
                    226:     my ($connection, $AdrFamily) = @_;
                    227: 
1.1       foxr      228:     my $peer       = $connection->peername();
                    229:     my $peerport;
                    230:     my $peerip;
                    231:     if($AdrFamily == AF_INET) {
                    232: 	($peerport, $peerip) = sockaddr_in($peer);
1.23      foxr      233: 	my $peername    = gethostbyaddr($peerip, $AdrFamily);
1.1       foxr      234: 	return $peername;
                    235:     } elsif ($AdrFamily == AF_UNIX) {
                    236: 	my $peerfile;
                    237: 	($peerfile) = sockaddr_un($peer);
                    238: 	return $peerfile;
                    239:     }
                    240: }
                    241: =pod
1.3       albertel  242: 
1.1       foxr      243: =head2 Debug
1.3       albertel  244: 
                    245: Invoked to issue a debug message.
                    246: 
1.1       foxr      247: =cut
1.3       albertel  248: 
1.1       foxr      249: sub Debug {
1.47      foxr      250: 
                    251:     my ($level, $message) = @_;
                    252: 
1.1       foxr      253:     if ($level <= $DebugLevel) {
1.23      foxr      254: 	Log("INFO", "-Debug- $message host = $RemoteHost");
1.1       foxr      255:     }
                    256: }
                    257: 
                    258: sub SocketDump {
1.47      foxr      259: 
                    260:     my ($level, $socket) = @_;
                    261: 
1.1       foxr      262:     if($level <= $DebugLevel) {
1.48      foxr      263: 	$socket->Dump(-1);	# Ensure it will get dumped.
1.1       foxr      264:     }
                    265: }
1.3       albertel  266: 
1.1       foxr      267: =pod
1.3       albertel  268: 
1.5       foxr      269: =head2 ShowStatus
                    270: 
                    271:  Place some text as our pid status.
1.10      foxr      272:  and as what we return in a SIGUSR1
1.5       foxr      273: 
                    274: =cut
1.69      matthew   275: 
1.5       foxr      276: sub ShowStatus {
1.10      foxr      277:     my $state = shift;
                    278:     my $now = time;
                    279:     my $local = localtime($now);
                    280:     $Status   = $local.": ".$state;
                    281:     $0='lonc: '.$state.' '.$local;
1.5       foxr      282: }
                    283: 
                    284: =pod
                    285: 
1.69      matthew   286: =head2 SocketTimeout
1.15      foxr      287: 
                    288:     Called when an action on the socket times out.  The socket is 
                    289:    destroyed and any active transaction is failed.
                    290: 
                    291: 
                    292: =cut
1.69      matthew   293: 
1.15      foxr      294: sub SocketTimeout {
                    295:     my $Socket = shift;
1.38      foxr      296:     Log("WARNING", "A socket timeout was detected");
1.52      foxr      297:     Debug(5, " SocketTimeout called: ");
1.48      foxr      298:     $Socket->Dump(0);
1.42      foxr      299:     if(exists($ActiveTransactions{$Socket})) {
1.43      albertel  300: 	FailTransaction($ActiveTransactions{$Socket});
1.42      foxr      301:     }
1.22      foxr      302:     KillSocket($Socket);	# A transaction timeout also counts as
                    303:                                 # a connection failure:
                    304:     $ConnectionRetriesLeft--;
1.42      foxr      305:     if($ConnectionRetriesLeft <= 0) {
1.52      foxr      306: 	Log("CRITICAL", "Host marked DEAD: ".GetServerHost());
1.56      foxr      307: 	$LondConnecting = 0;
1.42      foxr      308:     }
                    309: 
1.15      foxr      310: }
1.80      albertel  311: 
1.64      foxr      312: #
                    313: #   This function should be called by the child in all cases where it must
1.80      albertel  314: #   exit.  The child process must create a lock file for the AF_UNIX socket
                    315: #   in order to prevent connection requests from lonnet in the time between
                    316: #   process exit and the parent picking up the listen again.
                    317: #
1.64      foxr      318: # Parameters:
                    319: #     exit_code           - Exit status value, however see the next parameter.
                    320: #     message             - If this optional parameter is supplied, the exit
                    321: #                           is via a die with this message.
                    322: #
                    323: sub child_exit {
                    324:     my ($exit_code, $message) = @_;
                    325: 
                    326:     # Regardless of how we exit, we may need to do the lock thing:
                    327: 
1.80      albertel  328:     #
                    329:     #  Create a lock file since there will be a time window
                    330:     #  between our exit and the parent's picking up the listen
                    331:     #  during which no listens will be done on the
                    332:     #  lonnet client socket.
                    333:     #
                    334:     my $lock_file = &GetLoncSocketPath().".lock";
                    335:     open(LOCK,">$lock_file");
                    336:     print LOCK "Contents not important";
                    337:     close(LOCK);
1.81      albertel  338:     unlink(&GetLoncSocketPath());
1.64      foxr      339: 
1.80      albertel  340:     if ($message) {
                    341: 	die($message);
1.64      foxr      342:     } else {
                    343: 	exit($exit_code);
                    344:     }
                    345: }
1.35      foxr      346: #----------------------------- Timer management ------------------------
1.15      foxr      347: 
                    348: =pod
                    349: 
1.1       foxr      350: =head2 Tick
1.3       albertel  351: 
1.97    ! raeburn   352: Invoked each timer tick.
1.3       albertel  353: 
1.1       foxr      354: =cut
                    355: 
1.5       foxr      356: 
1.1       foxr      357: sub Tick {
1.52      foxr      358:     my ($Event)       = @_;
                    359:     my $clock_watcher = $Event->w;
                    360: 
1.1       foxr      361:     my $client;
1.57      foxr      362:     UpdateStatus();
                    363: 
1.4       foxr      364:     # Is it time to prune connection count:
                    365: 
                    366: 
                    367:     if($IdleConnections->Count()  && 
                    368:        ($WorkQueue->Count() == 0)) { # Idle connections and nothing to do?
1.52      foxr      369: 	$IdleSeconds++;
1.4       foxr      370: 	if($IdleSeconds > $IdleTimeout) { # Prune a connection...
1.23      foxr      371: 	    my $Socket = $IdleConnections->pop();
1.6       foxr      372: 	    KillSocket($Socket);
1.54      foxr      373: 	    $IdleSeconds = 0;	# Otherwise all connections get trimmed to fast.
1.57      foxr      374: 	    UpdateStatus();
1.80      albertel  375: 	    if(($ConnectionCount == 0)) {
1.64      foxr      376: 		&child_exit(0);
                    377: 
1.57      foxr      378: 	    }
1.4       foxr      379: 	}
                    380:     } else {
                    381: 	$IdleSeconds = 0;	# Reset idle count if not idle.
                    382:     }
1.15      foxr      383:     #
                    384:     #  For each inflight transaction, tick down its timeout counter.
                    385:     #
1.35      foxr      386: 
1.34      albertel  387:     foreach my $item (keys %ActiveConnections) {
                    388: 	my $State = $ActiveConnections{$item}->data->GetState();
1.35      foxr      389: 	if ($State ne 'Idle') {
1.34      albertel  390: 	    Debug(5,"Ticking Socket $State $item");
                    391: 	    $ActiveConnections{$item}->data->Tick();
                    392: 	}
1.15      foxr      393:     }
1.5       foxr      394:     # Do we have work in the queue, but no connections to service them?
                    395:     # If so, try to make some new connections to get things going again.
                    396:     #
1.57      foxr      397:     #   Note this code is dead now...
                    398:     #
1.5       foxr      399:     my $Requests = $WorkQueue->Count();
1.56      foxr      400:     if (($ConnectionCount == 0)  && ($Requests > 0) && (!$LondConnecting)) { 
1.10      foxr      401: 	if ($ConnectionRetriesLeft > 0) {
1.56      foxr      402: 	    Debug(5,"Work but no connections, Make a new one");
                    403: 	    my $success;
                    404: 	    $success    = &MakeLondConnection;
                    405: 	    if($success == 0) { # All connections failed:
1.29      foxr      406: 		Debug(5,"Work in queue failed to make any connectiouns\n");
1.22      foxr      407: 		EmptyQueue();	# Fail pending transactions with con_lost.
1.42      foxr      408: 		CloseAllLondConnections(); # Should all be closed but....
1.10      foxr      409: 	    }
                    410: 	} else {
1.56      foxr      411: 	    $LondConnecting = 0;
1.22      foxr      412: 	    ShowStatus(GetServerHost()." >>> DEAD!!! <<<");
1.29      foxr      413: 	    Debug(5,"Work in queue, but gave up on connections..flushing\n");
1.10      foxr      414: 	    EmptyQueue();	# Connections can't be established.
1.42      foxr      415: 	    CloseAllLondConnections(); # Should all already be closed but...
1.5       foxr      416: 	}
                    417:        
                    418:     }
1.49      foxr      419:     if ($ConnectionCount == 0) {
                    420: 	$KeyMode = ""; 
1.52      foxr      421: 	$clock_watcher->cancel();
1.49      foxr      422:     }
1.66      albertel  423:     &UpdateStatus();
1.1       foxr      424: }
                    425: 
                    426: =pod
1.3       albertel  427: 
1.1       foxr      428: =head2 SetupTimer
                    429: 
1.3       albertel  430: Sets up a 1 per sec recurring timer event.  The event handler is used to:
1.1       foxr      431: 
1.3       albertel  432: =item
                    433: 
                    434: Trigger timeouts on communications along active sockets.
                    435: 
                    436: =item
                    437: 
                    438: Trigger disconnections of idle sockets.
1.1       foxr      439: 
                    440: =cut
                    441: 
                    442: sub SetupTimer {
1.52      foxr      443:     Debug(6, "SetupTimer");
1.92      foxr      444:     Event->timer(interval => 1, cb => \&Tick,
                    445: 	hard => 1);
1.1       foxr      446: }
1.3       albertel  447: 
1.1       foxr      448: =pod
1.3       albertel  449: 
1.1       foxr      450: =head2 ServerToIdle
1.3       albertel  451: 
                    452: This function is called when a connection to the server is
                    453: ready for more work.
                    454: 
                    455: If there is work in the Work queue the top element is dequeued
1.1       foxr      456: and the connection will start to work on it.  If the work queue is
                    457: empty, the connection is pushed on the idle connection stack where
                    458: it will either get another work unit, or alternatively, if it sits there
                    459: long enough, it will be shut down and released.
                    460: 
1.3       albertel  461: =cut
1.1       foxr      462: 
                    463: sub ServerToIdle {
                    464:     my $Socket   = shift;	# Get the socket.
1.49      foxr      465:     $KeyMode = $Socket->{AuthenticationMode};
1.7       foxr      466:     delete($ActiveTransactions{$Socket}); # Server has no transaction
1.1       foxr      467: 
1.29      foxr      468:     &Debug(5, "Server to idle");
1.1       foxr      469: 
                    470:     #  If there's work to do, start the transaction:
                    471: 
1.23      foxr      472:     my $reqdata = $WorkQueue->dequeue(); # This is a LondTransaction
1.29      foxr      473:     if ($reqdata ne undef)  {
                    474: 	Debug(5, "Queue gave request data: ".$reqdata->getRequest());
1.7       foxr      475: 	&StartRequest($Socket,  $reqdata);
1.8       foxr      476: 
1.1       foxr      477:     } else {
                    478: 	
                    479:     #  There's no work waiting, so push the server to idle list.
1.29      foxr      480: 	&Debug(5, "No new work requests, server connection going idle");
1.1       foxr      481: 	$IdleConnections->push($Socket);
                    482:     }
                    483: }
1.3       albertel  484: 
1.1       foxr      485: =pod
1.3       albertel  486: 
1.1       foxr      487: =head2 ClientWritable
1.3       albertel  488: 
                    489: Event callback for when a client socket is writable.
                    490: 
1.97    ! raeburn   491: This callback is established when a transaction response is
        !           492: available from lond.  The response is forwarded to the unix socket
1.3       albertel  493: as it becomes writable in this sub.
                    494: 
1.1       foxr      495: Parameters:
                    496: 
1.3       albertel  497: =item Event
                    498: 
                    499: The event that has been triggered. Event->w->data is
                    500: the data and Event->w->fd is the socket to write.
1.1       foxr      501: 
                    502: =cut
1.3       albertel  503: 
1.1       foxr      504: sub ClientWritable {
                    505:     my $Event    = shift;
                    506:     my $Watcher  = $Event->w;
1.84      albertel  507:     if (!defined($Watcher)) {
                    508: 	&child_exit(-1,'No watcher for event in ClientWritable');
                    509:     }
1.1       foxr      510:     my $Data     = $Watcher->data;
                    511:     my $Socket   = $Watcher->fd;
                    512: 
                    513:     # Try to send the data:
                    514: 
                    515:     &Debug(6, "ClientWritable writing".$Data);
                    516:     &Debug(9, "Socket is: ".$Socket);
                    517: 
1.6       foxr      518:     if($Socket->connected) {
                    519: 	my $result = $Socket->send($Data, 0);
                    520: 	
                    521: 	# $result undefined: the write failed.
                    522: 	# otherwise $result is the number of bytes written.
                    523: 	# Remove that preceding string from the data.
                    524: 	# If the resulting data is empty, destroy the watcher
                    525: 	# and set up a read event handler to accept the next
                    526: 	# request.
                    527: 	
                    528: 	&Debug(9,"Send result is ".$result." Defined: ".defined($result));
1.29      foxr      529: 	if($result ne undef) {
1.6       foxr      530: 	    &Debug(9, "send result was defined");
                    531: 	    if($result == length($Data)) { # Entire string sent.
                    532: 		&Debug(9, "ClientWritable data all written");
                    533: 		$Watcher->cancel();
                    534: 		#
                    535: 		#  Set up to read next request from socket:
                    536: 		
                    537: 		my $descr     = sprintf("Connection to lonc client %d",
                    538: 					$ActiveClients{$Socket});
                    539: 		Event->io(cb    => \&ClientRequest,
                    540: 			  poll  => 'r',
                    541: 			  desc  => $descr,
                    542: 			  data  => "",
                    543: 			  fd    => $Socket);
                    544: 		
                    545: 	    } else {		# Partial string sent.
                    546: 		$Watcher->data(substr($Data, $result));
1.15      foxr      547: 		if($result == 0) {    # client hung up on us!!
1.52      foxr      548: 		    # Log("INFO", "lonc pipe client hung up on us!");
1.15      foxr      549: 		    $Watcher->cancel;
                    550: 		    $Socket->shutdown(2);
                    551: 		    $Socket->close();
                    552: 		}
1.6       foxr      553: 	    }
                    554: 	    
                    555: 	} else {			# Error of some sort...
                    556: 	    
                    557: 	    # Some errnos are possible:
                    558: 	    my $errno = $!;
                    559: 	    if($errno == POSIX::EWOULDBLOCK   ||
                    560: 	       $errno == POSIX::EAGAIN        ||
                    561: 	       $errno == POSIX::EINTR) {
1.96      foxr      562: 		# No action taken...the socket will be writable firing the event again
                    563: 		# which will result in a retry of the write.
1.6       foxr      564: 	    } else {		# Unanticipated errno.
                    565: 		&Debug(5,"ClientWritable error or peer shutdown".$RemoteHost);
                    566: 		$Watcher->cancel;	# Stop the watcher.
                    567: 		$Socket->shutdown(2); # Kill connection
                    568: 		$Socket->close();	# Close the socket.
                    569: 	    }
1.1       foxr      570: 	    
                    571: 	}
1.6       foxr      572:     } else {
                    573: 	$Watcher->cancel();	# A delayed request...just cancel.
1.84      albertel  574: 	return;
1.1       foxr      575:     }
                    576: }
                    577: 
                    578: =pod
1.3       albertel  579: 
1.1       foxr      580: =head2 CompleteTransaction
1.3       albertel  581: 
                    582: Called when the reply data has been received for a lond 
1.1       foxr      583: transaction.   The reply data must now be sent to the
                    584: ultimate client on the other end of the Unix socket.  This is
                    585: done by setting up a writable event for the socket with the
                    586: data the reply data.
1.3       albertel  587: 
1.1       foxr      588: Parameters:
1.3       albertel  589: 
                    590: =item Socket
                    591: 
1.97    ! raeburn   592: Socket on which the lond transaction occurred.  This is a
        !           593: LondConnection. The data received are in the TransactionReply member.
1.3       albertel  594: 
1.7       foxr      595: =item Transaction
1.3       albertel  596: 
1.7       foxr      597: The transaction that is being completed.
1.1       foxr      598: 
                    599: =cut
1.3       albertel  600: 
1.1       foxr      601: sub CompleteTransaction {
1.29      foxr      602:     &Debug(5,"Complete transaction");
1.47      foxr      603: 
                    604:     my ($Socket, $Transaction) = @_;
1.1       foxr      605: 
1.7       foxr      606:     if (!$Transaction->isDeferred()) { # Normal transaction
                    607: 	my $data   = $Socket->GetReply(); # Data to send.
1.39      foxr      608: 	if($LogTransactions) {
                    609: 	    Log("SUCCESS", "Reply from lond: '$data'");
                    610: 	}
1.7       foxr      611: 	StartClientReply($Transaction, $data);
                    612:     } else {			# Delete deferred transaction file.
1.9       foxr      613: 	Log("SUCCESS", "A delayed transaction was completed");
1.86      albertel  614: 	LogPerm("S:".$Transaction->getClient().":".$Transaction->getRequest());
                    615: 	unlink($Transaction->getFile());
1.7       foxr      616:     }
1.6       foxr      617: }
1.42      foxr      618: 
1.6       foxr      619: =pod
1.42      foxr      620: 
1.6       foxr      621: =head1 StartClientReply
                    622: 
                    623:    Initiates a reply to a client where the reply data is a parameter.
                    624: 
1.7       foxr      625: =head2  parameters:
                    626: 
                    627: =item Transaction
                    628: 
                    629:     The transaction for which we are responding to the client.
                    630: 
                    631: =item data
                    632: 
1.97    ! raeburn   633:     The data to send to apache client.
1.7       foxr      634: 
1.6       foxr      635: =cut
1.42      foxr      636: 
1.6       foxr      637: sub StartClientReply {
1.1       foxr      638: 
1.47      foxr      639:     my ($Transaction, $data) = @_;
1.12      foxr      640: 
1.7       foxr      641:     my $Client   = $Transaction->getClient();
                    642: 
1.1       foxr      643:     &Debug(8," Reply was: ".$data);
                    644:     my $Serial         = $ActiveClients{$Client};
                    645:     my $desc           = sprintf("Connection to lonc client %d",
                    646: 				 $Serial);
                    647:     Event->io(fd       => $Client,
                    648: 	      poll     => "w",
                    649: 	      desc     => $desc,
                    650: 	      cb       => \&ClientWritable,
                    651: 	      data     => $data);
                    652: }
1.42      foxr      653: 
1.4       foxr      654: =pod
1.42      foxr      655: 
1.4       foxr      656: =head2 FailTransaction
                    657: 
                    658:   Finishes a transaction with failure because the associated lond socket
1.7       foxr      659:   disconnected.  There are two possibilities:
                    660:   - The transaction is deferred: in which case we just quietly
                    661:     delete the transaction since there is no client connection.
                    662:   - The transaction is 'live' in which case we initiate the sending
                    663:     of "con_lost" to the client.
                    664: 
1.42      foxr      665: Deleting the transaction means killing it from the %ActiveTransactions hash.
1.4       foxr      666: 
                    667: Parameters:
                    668: 
                    669: =item client  
                    670:  
1.7       foxr      671:    The LondTransaction we are failing.
                    672:  
1.42      foxr      673: 
1.4       foxr      674: =cut
                    675: 
                    676: sub FailTransaction {
1.7       foxr      677:     my $transaction = shift;
1.52      foxr      678:     
                    679:     #  If the socket is dead, that's already logged.
                    680: 
                    681:     if ($ConnectionRetriesLeft > 0) {
                    682: 	Log("WARNING", "Failing transaction "
1.71      albertel  683: 	    .$transaction->getLoggableRequest());
1.52      foxr      684:     }
1.71      albertel  685:     Debug(1, "Failing transaction: ".$transaction->getLoggableRequest());
1.10      foxr      686:     if (!$transaction->isDeferred()) { # If the transaction is deferred we'll get to it.
1.11      foxr      687: 	my $client  = $transaction->getClient();
1.30      foxr      688: 	Debug(1," Replying con_lost to ".$transaction->getRequest());
1.11      foxr      689: 	StartClientReply($transaction, "con_lost\n");
1.7       foxr      690:     }
1.4       foxr      691: 
                    692: }
                    693: 
                    694: =pod
1.69      matthew   695: 
1.6       foxr      696: =head1  EmptyQueue
1.7       foxr      697: 
1.6       foxr      698:   Fails all items in the work queue with con_lost.
1.7       foxr      699:   Note that each item in the work queue is a transaction.
                    700: 
1.6       foxr      701: =cut
1.69      matthew   702: 
1.6       foxr      703: sub EmptyQueue {
1.22      foxr      704:     $ConnectionRetriesLeft--;	# Counts as connection failure too.
1.6       foxr      705:     while($WorkQueue->Count()) {
1.10      foxr      706: 	my $request = $WorkQueue->dequeue(); # This is a transaction
1.7       foxr      707: 	FailTransaction($request);
1.6       foxr      708:     }
                    709: }
                    710: 
                    711: =pod
1.4       foxr      712: 
1.9       foxr      713: =head2 CloseAllLondConnections
                    714: 
                    715: Close all connections open on lond prior to exit e.g.
                    716: 
                    717: =cut
1.69      matthew   718: 
1.9       foxr      719: sub CloseAllLondConnections {
1.23      foxr      720:     foreach my $Socket (keys %ActiveConnections) {
1.42      foxr      721:       if(exists($ActiveTransactions{$Socket})) {
                    722: 	FailTransaction($ActiveTransactions{$Socket});
                    723:       }
                    724:       KillSocket($Socket);
1.9       foxr      725:     }
                    726: }
                    727: 
                    728: =pod
                    729: 
1.4       foxr      730: =head2 KillSocket
                    731:  
                    732: Destroys a socket.  This function can be called either when a socket
                    733: has died of 'natural' causes or because a socket needs to be pruned due to
                    734: idleness.  If the socket has died naturally, if there are no longer any 
                    735: live connections a new connection is created (in case there are transactions
                    736: in the queue).  If the socket has been pruned, it is never re-created.
                    737: 
                    738: Parameters:
1.1       foxr      739: 
1.4       foxr      740: =item Socket
                    741:  
                    742:   The socket to kill off.
                    743: 
                    744: =item Restart
                    745: 
1.97    ! raeburn   746: non-zero if we are allowed to create a new connection.
1.4       foxr      747: 
1.69      matthew   748: =cut
1.4       foxr      749: 
                    750: sub KillSocket {
                    751:     my $Socket = shift;
                    752: 
1.17      foxr      753:     Log("WARNING", "Shutting down a socket");
1.9       foxr      754:     $Socket->Shutdown();
                    755: 
1.7       foxr      756:     #  If the socket came from the active connection set,
                    757:     #  delete its transaction... note that FailTransaction should
                    758:     #  already have been called!!!
                    759:     #  otherwise it came from the idle set.
                    760:     #  
1.4       foxr      761:     
                    762:     if(exists($ActiveTransactions{$Socket})) {
                    763: 	delete ($ActiveTransactions{$Socket});
                    764:     }
                    765:     if(exists($ActiveConnections{$Socket})) {
1.90      foxr      766: 	$ActiveConnections{$Socket}->cancel;
1.4       foxr      767: 	delete($ActiveConnections{$Socket});
1.37      albertel  768: 	$ConnectionCount--;
                    769: 	if ($ConnectionCount < 0) { $ConnectionCount = 0; }
1.4       foxr      770:     }
1.6       foxr      771:     #  If the connection count has gone to zero and there is work in the
                    772:     #  work queue, the work all gets failed with con_lost.
                    773:     #
                    774:     if($ConnectionCount == 0) {
1.22      foxr      775: 	EmptyQueue();
1.42      foxr      776: 	CloseAllLondConnections; # Should all already be closed but...
1.4       foxr      777:     }
1.90      foxr      778:     UpdateStatus();
1.4       foxr      779: }
1.1       foxr      780: 
                    781: =pod
1.3       albertel  782: 
1.1       foxr      783: =head2 LondReadable
1.3       albertel  784: 
1.1       foxr      785: This function is called whenever a lond connection
                    786: is readable.  The action is state dependent:
                    787: 
1.3       albertel  788: =head3 State=Initialized
                    789: 
1.97    ! raeburn   790: We're waiting for the challenge, this is a no-op until the
1.1       foxr      791: state changes.
1.3       albertel  792: 
1.1       foxr      793: =head3 State=Challenged 
1.3       albertel  794: 
                    795: The challenge has arrived we need to transition to Writable.
1.1       foxr      796: The connection must echo the challenge back.
1.3       albertel  797: 
1.1       foxr      798: =head3 State=ChallengeReplied
1.3       albertel  799: 
1.97    ! raeburn   800: The challenge has been replied to.  Then we are receiving the 
1.1       foxr      801: 'ok' from the partner.
1.3       albertel  802: 
1.40      foxr      803: =head3  State=ReadingVersionString
                    804: 
                    805: We have requested the lond version and are reading the
                    806: version back.  Upon completion, we'll store the version away
                    807: for future use(?).
                    808: 
                    809: =head3 State=HostSet
                    810: 
                    811: We have selected the domain name of our peer (multhomed hosts)
                    812: and are getting the reply (presumably ok) back.
                    813: 
1.1       foxr      814: =head3 State=RequestingKey
1.3       albertel  815: 
                    816: The ok has been received and we need to send the request for
1.1       foxr      817: an encryption key.  Transition to writable for that.
1.3       albertel  818: 
1.1       foxr      819: =head3 State=ReceivingKey
1.3       albertel  820: 
                    821: The the key has been requested, now we are reading the new key.
                    822: 
1.1       foxr      823: =head3 State=Idle 
1.3       albertel  824: 
                    825: The encryption key has been negotiated or we have finished 
1.97    ! raeburn   826: reading data from the a transaction.   If the callback data have
        !           827: a client as well as the socket nformation, then we are 
        !           828: doing a transaction and the data received are relayed to the client
1.1       foxr      829: before the socket is put on the idle list.
1.3       albertel  830: 
1.1       foxr      831: =head3 State=SendingRequest
1.3       albertel  832: 
                    833: I do not think this state can be received here, but if it is,
1.1       foxr      834: the appropriate thing to do is to transition to writable, and send
                    835: the request.
1.3       albertel  836: 
1.1       foxr      837: =head3 State=ReceivingReply
1.3       albertel  838: 
                    839: We finished sending the request to the server and now transition
1.1       foxr      840: to readable to receive the reply. 
                    841: 
                    842: The parameter to this function are:
1.3       albertel  843: 
1.1       foxr      844: The event. Implicit in this is the watcher and its data.  The data 
1.97    ! raeburn   845: contain at least the lond connection object and, if a 
1.1       foxr      846: transaction is in progress, the socket attached to the local client.
                    847: 
1.3       albertel  848: =cut
1.1       foxr      849: 
                    850: sub LondReadable {
1.8       foxr      851: 
1.41      albertel  852:     my $Event      = shift;
                    853:     my $Watcher    = $Event->w;
                    854:     my $Socket     = $Watcher->data;
                    855:     my $client     = undef;
1.40      foxr      856: 
1.41      albertel  857:     &Debug(6,"LondReadable called state = ".$Socket->GetState());
1.40      foxr      858: 
                    859: 
1.41      albertel  860:     my $State = $Socket->GetState(); # All action depends on the state.
1.40      foxr      861: 
1.41      albertel  862:     SocketDump(6, $Socket);
                    863:     my $status = $Socket->Readable();
1.40      foxr      864: 
1.41      albertel  865:     &Debug(2, "Socket->Readable returned: $status");
1.40      foxr      866: 
1.41      albertel  867:     if($status != 0) {
                    868: 	# bad return from socket read. Currently this means that
                    869: 	# The socket has become disconnected. We fail the transaction.
1.40      foxr      870: 
1.41      albertel  871: 	Log("WARNING",
                    872: 	    "Lond connection lost.");
                    873: 	if(exists($ActiveTransactions{$Socket})) {
                    874: 	    FailTransaction($ActiveTransactions{$Socket});
1.56      foxr      875: 	} else {
                    876: 	    #  Socket is connecting and failed... need to mark
                    877: 	    #  no longer connecting.
                    878: 	   
                    879: 	    $LondConnecting = 0;
1.41      albertel  880: 	}
                    881: 	$Watcher->cancel();
                    882: 	KillSocket($Socket);
                    883: 	$ConnectionRetriesLeft--;       # Counts as connection failure
                    884: 	return;
                    885:     }
                    886:     SocketDump(6,$Socket);
1.17      foxr      887: 
1.41      albertel  888:     $State = $Socket->GetState(); # Update in case of transition.
                    889:     &Debug(6, "After read, state is ".$State);
1.1       foxr      890: 
1.41      albertel  891:     if($State eq "Initialized") {
1.1       foxr      892: 
                    893: 
1.41      albertel  894:     } elsif ($State eq "ChallengeReceived") {
1.1       foxr      895: 	#  The challenge must be echoed back;  The state machine
                    896: 	# in the connection takes care of setting that up.  Just
                    897: 	# need to transition to writable:
1.41      albertel  898: 	
                    899: 	$Watcher->cb(\&LondWritable);
                    900: 	$Watcher->poll("w");
1.1       foxr      901: 
1.41      albertel  902:     } elsif ($State eq "ChallengeReplied") {
1.1       foxr      903: 
1.41      albertel  904:     } elsif ($State eq "RequestingVersion") {
                    905: 	# Need to ask for the version... that is writiability:
1.1       foxr      906: 
1.41      albertel  907: 	$Watcher->cb(\&LondWritable);
                    908: 	$Watcher->poll("w");
                    909: 
                    910:     } elsif ($State eq "ReadingVersionString") {
                    911: 	# Read the rest of the version string... 
                    912:     } elsif ($State eq "SetHost") {
                    913: 	# Need to request the actual domain get set...
                    914: 
                    915: 	$Watcher->cb(\&LondWritable);
                    916: 	$Watcher->poll("w");
                    917:     } elsif ($State eq "HostSet") {
                    918: 	# Reading the 'ok' from the peer.
                    919: 
                    920:     } elsif ($State eq "RequestingKey") {
1.1       foxr      921: 	#  The ok was received.  Now we need to request the key
                    922: 	#  That requires us to be writable:
                    923: 
1.41      albertel  924: 	$Watcher->cb(\&LondWritable);
                    925: 	$Watcher->poll("w");
1.1       foxr      926: 
1.41      albertel  927:     } elsif ($State eq "ReceivingKey") {
1.1       foxr      928: 
1.41      albertel  929:     } elsif ($State eq "Idle") {
1.40      foxr      930:    
1.41      albertel  931: 	# This is as good a spot as any to get the peer version
                    932: 	# string:
1.40      foxr      933:    
1.41      albertel  934: 	if($LondVersion eq "unknown") {
                    935: 	    $LondVersion = $Socket->PeerVersion();
                    936: 	    Log("INFO", "Connected to lond version: $LondVersion");
                    937: 	}
1.1       foxr      938: 	# If necessary, complete a transaction and then go into the
                    939: 	# idle queue.
1.22      foxr      940: 	#  Note that a trasition to idle indicates a live lond
                    941: 	# on the other end so reset the connection retries.
                    942: 	#
1.41      albertel  943: 	$ConnectionRetriesLeft = $ConnectionRetries; # success resets the count
                    944: 	$Watcher->cancel();
                    945: 	if(exists($ActiveTransactions{$Socket})) {
                    946: 	    Debug(5,"Completing transaction!!");
                    947: 	    CompleteTransaction($Socket, 
                    948: 				$ActiveTransactions{$Socket});
                    949: 	} else {
1.95      foxr      950: 	    my $count = $Socket->GetClientData();
                    951: 	    Log("SUCCESS", "Connection ".$count." to "
1.41      albertel  952: 		.$RemoteHost." now ready for action");
                    953: 	}
                    954: 	ServerToIdle($Socket);	# Next work unit or idle.
1.54      foxr      955: 
                    956: 	#
                    957: 	$LondConnecting = 0;	# Best spot I can think of for this.
                    958: 	# 
1.6       foxr      959: 	
1.41      albertel  960:     } elsif ($State eq "SendingRequest") {
1.1       foxr      961: 	#  We need to be writable for this and probably don't belong
                    962: 	#  here inthe first place.
                    963: 
1.73      albertel  964: 	Debug(6, "SendingRequest state encountered in readable");
1.41      albertel  965: 	$Watcher->poll("w");
                    966: 	$Watcher->cb(\&LondWritable);
1.1       foxr      967: 
1.41      albertel  968:     } elsif ($State eq "ReceivingReply") {
1.1       foxr      969: 
                    970: 
1.41      albertel  971:     } else {
                    972: 	# Invalid state.
                    973: 	Debug(4, "Invalid state in LondReadable");
                    974:     }
1.1       foxr      975: }
1.3       albertel  976: 
1.1       foxr      977: =pod
1.3       albertel  978: 
1.1       foxr      979: =head2 LondWritable
1.3       albertel  980: 
1.1       foxr      981: This function is called whenever a lond connection
                    982: becomes writable while there is a writeable monitoring
                    983: event.  The action taken is very state dependent:
1.3       albertel  984: 
1.1       foxr      985: =head3 State = Connected 
1.3       albertel  986: 
                    987: The connection is in the process of sending the 'init' hailing to the
1.97    ! raeburn   988: lond on the remote end.  The connection object's Writable member is
1.3       albertel  989: called.  On error, ConnectionError is called to destroy the connection
                    990: and remove it from the ActiveConnections hash
                    991: 
1.1       foxr      992: =head3 Initialized
1.3       albertel  993: 
                    994: 'init' has been sent, writability monitoring is removed and
                    995: readability monitoring is started with LondReadable as the callback.
                    996: 
1.1       foxr      997: =head3 ChallengeReceived
1.3       albertel  998: 
                    999: The connection has received the who are you challenge from the remote
                   1000: system, and is in the process of sending the challenge
                   1001: response. Writable is called.
                   1002: 
1.1       foxr     1003: =head3 ChallengeReplied
1.3       albertel 1004: 
                   1005: The connection has replied to the initial challenge The we switch to
                   1006: monitoring readability looking for the server to reply with 'ok'.
                   1007: 
1.1       foxr     1008: =head3 RequestingKey
1.3       albertel 1009: 
                   1010: The connection is in the process of requesting its encryption key.
                   1011: Writable is called.
                   1012: 
1.1       foxr     1013: =head3 ReceivingKey
1.3       albertel 1014: 
                   1015: The connection has sent the request for a key.  Switch to readability
                   1016: monitoring to accept the key
                   1017: 
1.1       foxr     1018: =head3 SendingRequest
1.3       albertel 1019: 
                   1020: The connection is in the process of sending a request to the server.
                   1021: This request is part of a client transaction.  All the states until
                   1022: now represent the client setup protocol. Writable is called.
                   1023: 
1.1       foxr     1024: =head3 ReceivingReply
                   1025: 
1.3       albertel 1026: The connection has sent a request.  Now it must receive a reply.
                   1027: Readability monitoring is requested.
                   1028: 
                   1029: This function is an event handler and therefore receives as
1.1       foxr     1030: a parameter the event that has fired.  The data for the watcher
                   1031: of this event is a reference to a list of one or two elements,
                   1032: depending on state. The first (and possibly only) element is the
                   1033: socket.  The second (present only if a request is in progress)
                   1034: is the socket on which to return a reply to the caller.
                   1035: 
                   1036: =cut
1.3       albertel 1037: 
1.1       foxr     1038: sub LondWritable {
                   1039:     my $Event   = shift;
                   1040:     my $Watcher = $Event->w;
1.8       foxr     1041:     my $Socket  = $Watcher->data;
                   1042:     my $State   = $Socket->GetState();
1.1       foxr     1043: 
1.8       foxr     1044:     Debug(6,"LondWritable State = ".$State."\n");
1.1       foxr     1045: 
1.8       foxr     1046:  
1.1       foxr     1047:     #  Figure out what to do depending on the state of the socket:
                   1048:     
                   1049: 
                   1050: 
                   1051: 
                   1052:     SocketDump(6,$Socket);
                   1053: 
1.42      foxr     1054:     #  If the socket is writable, we must always write.
                   1055:     # Only by writing will we undergo state transitions.
                   1056:     # Old logic wrote in state specific code below, however
                   1057:     # That forces us at least through another invocation of
                   1058:     # this function after writability is possible again.
                   1059:     # This logic also factors out common code for handling
                   1060:     # write failures... in all cases, write failures 
                   1061:     # Kill the socket.
                   1062:     #  This logic makes the branches of the >big< if below
                   1063:     # so that the writing states are actually NO-OPs.
                   1064: 
                   1065:     if ($Socket->Writable() != 0) {
1.43      albertel 1066: 	#  The write resulted in an error.
                   1067: 	# We'll treat this as if the socket got disconnected:
                   1068: 	Log("WARNING", "Connection to ".$RemoteHost.
                   1069: 	    " has been disconnected");
                   1070: 	if(exists($ActiveTransactions{$Socket})) {
                   1071: 	    FailTransaction($ActiveTransactions{$Socket});
1.56      foxr     1072: 	} else {
                   1073: 	    #  In the process of conneting, so need to turn that off.
                   1074: 	    
                   1075: 	    $LondConnecting = 0;
1.43      albertel 1076: 	}
                   1077: 	$Watcher->cancel();
                   1078: 	KillSocket($Socket);
                   1079: 	return;
1.42      foxr     1080:     }
                   1081: 
                   1082: 
                   1083: 
1.41      albertel 1084:     if      ($State eq "Connected")         {
1.1       foxr     1085: 
1.41      albertel 1086: 	#  "init" is being sent...
1.42      foxr     1087:  
1.41      albertel 1088:     } elsif ($State eq "Initialized")       {
1.4       foxr     1089: 
1.41      albertel 1090: 	# Now that init was sent, we switch 
                   1091: 	# to watching for readability:
1.1       foxr     1092: 
1.41      albertel 1093: 	$Watcher->cb(\&LondReadable);
                   1094: 	$Watcher->poll("r");
                   1095: 	
                   1096:     } elsif ($State eq "ChallengeReceived") {
                   1097: 	# We received the challenge, now we 
                   1098: 	# are echoing it back. This is a no-op,
                   1099: 	# we're waiting for the state to change
1.1       foxr     1100: 	
1.41      albertel 1101:     } elsif ($State eq "ChallengeReplied")  {
                   1102: 	# The echo was sent back, so we switch
                   1103: 	# to watching readability.
                   1104: 
                   1105: 	$Watcher->cb(\&LondReadable);
                   1106: 	$Watcher->poll("r");
                   1107:     } elsif ($State eq "RequestingVersion") {
                   1108: 	# Sending the peer a version request...
1.42      foxr     1109: 
1.41      albertel 1110:     } elsif ($State eq "ReadingVersionString") {
                   1111: 	# Transition to read since we have sent the
                   1112: 	# version command and now just need to read the
                   1113: 	# version string from the peer:
1.40      foxr     1114:       
1.41      albertel 1115: 	$Watcher->cb(\&LondReadable);
                   1116: 	$Watcher->poll("r");
1.40      foxr     1117:       
1.41      albertel 1118:     } elsif ($State eq "SetHost") {
                   1119: 	#  Setting the remote domain...
1.42      foxr     1120: 
1.41      albertel 1121:     } elsif ($State eq "HostSet") {
                   1122: 	# Back to readable to get the ok.
1.40      foxr     1123:       
1.41      albertel 1124: 	$Watcher->cb(\&LondReadable);
                   1125: 	$Watcher->poll("r");
1.40      foxr     1126:       
                   1127: 
1.41      albertel 1128:     } elsif ($State eq "RequestingKey")     {
                   1129: 	# At this time we're requesting the key.
                   1130: 	# again, this is essentially a no-op.
                   1131: 
                   1132:     } elsif ($State eq "ReceivingKey")      {
                   1133: 	# Now we need to wait for the key
                   1134: 	# to come back from the peer:
                   1135: 
                   1136: 	$Watcher->cb(\&LondReadable);
                   1137: 	$Watcher->poll("r");
                   1138: 
                   1139:     } elsif ($State eq "SendingRequest")    {
1.40      foxr     1140:  
1.41      albertel 1141: 	# At this time we are sending a request to the
1.1       foxr     1142: 	# peer... write the next chunk:
                   1143: 
1.41      albertel 1144: 
                   1145:     } elsif ($State eq "ReceivingReply")    {
                   1146: 	# The send has completed.  Wait for the
                   1147: 	# data to come in for a reply.
                   1148: 	Debug(8,"Writable sent request/receiving reply");
                   1149: 	$Watcher->cb(\&LondReadable);
                   1150: 	$Watcher->poll("r");
1.1       foxr     1151: 
1.41      albertel 1152:     } else {
                   1153: 	#  Control only passes here on an error: 
                   1154: 	#  the socket state does not match any
                   1155: 	#  of the known states... so an error
                   1156: 	#  must be logged.
1.1       foxr     1157: 
1.41      albertel 1158: 	&Debug(4, "Invalid socket state ".$State."\n");
                   1159:     }
1.1       foxr     1160:     
                   1161: }
1.81      albertel 1162: 
1.6       foxr     1163: =pod
                   1164:     
                   1165: =cut
1.69      matthew  1166: 
1.81      albertel 1167: 
1.6       foxr     1168: sub QueueDelayed {
1.8       foxr     1169:     Debug(3,"QueueDelayed called");
                   1170: 
1.6       foxr     1171:     my $path = "$perlvar{'lonSockDir'}/delayed";
1.8       foxr     1172: 
                   1173:     Debug(4, "Delayed path: ".$path);
1.6       foxr     1174:     opendir(DIRHANDLE, $path);
1.75      albertel 1175: 
1.82      albertel 1176:     my $host_id_re = '(?:'.join('|',map {quotemeta($_)} (@all_host_ids)).')';
1.75      albertel 1177:     my @alldelayed = grep(/\.$host_id_re$/, readdir(DIRHANDLE));
1.6       foxr     1178:     closedir(DIRHANDLE);
1.75      albertel 1179:     foreach my $dfname (sort(@alldelayed)) {
                   1180: 	my $reqfile = "$path/$dfname";
                   1181: 	my ($host_id) = ($dfname =~ /\.([^.]*)$/);
                   1182: 	Debug(4, "queueing ".$reqfile." for $host_id");
1.6       foxr     1183: 	my $Handle = IO::File->new($reqfile);
                   1184: 	my $cmd    = <$Handle>;
1.8       foxr     1185: 	chomp $cmd;		# There may or may not be a newline...
1.12      foxr     1186: 	$cmd = $cmd."\n";	# now for sure there's exactly one newline.
1.75      albertel 1187: 	my $Transaction = LondTransaction->new("sethost:$host_id:$cmd");
1.7       foxr     1188: 	$Transaction->SetDeferred($reqfile);
                   1189: 	QueueTransaction($Transaction);
1.6       foxr     1190:     }
                   1191:     
                   1192: }
1.1       foxr     1193: 
                   1194: =pod
1.3       albertel 1195: 
1.1       foxr     1196: =head2 MakeLondConnection
1.3       albertel 1197: 
                   1198: Create a new lond connection object, and start it towards its initial
1.97    ! raeburn  1199: idleness.  Once idle, it becomes eligible to receive transactions
1.3       albertel 1200: from the work queue.  If the work queue is not empty when the
                   1201: connection is completed and becomes idle, it will dequeue an entry and
                   1202: start off on it.
                   1203: 
1.1       foxr     1204: =cut
1.3       albertel 1205: 
1.1       foxr     1206: sub MakeLondConnection {     
                   1207:     Debug(4,"MakeLondConnection to ".GetServerHost()." on port "
                   1208: 	  .GetServerPort());
                   1209: 
                   1210:     my $Connection = LondConnection->new(&GetServerHost(),
1.81      albertel 1211: 					 &GetServerPort(),
                   1212: 					 &GetHostId());
1.1       foxr     1213: 
1.90      foxr     1214:     if($Connection eq undef) {	
1.9       foxr     1215: 	Log("CRITICAL","Failed to make a connection with lond.");
1.10      foxr     1216: 	$ConnectionRetriesLeft--;
                   1217: 	return 0;		# Failure.
1.5       foxr     1218:     }  else {
1.22      foxr     1219: 
1.82      albertel 1220: 	$LondConnecting = 1;	# Connection in progress.
1.5       foxr     1221: 	# The connection needs to have writability 
                   1222: 	# monitored in order to send the init sequence
                   1223: 	# that starts the whole authentication/key
                   1224: 	# exchange underway.
                   1225: 	#
                   1226: 	my $Socket = $Connection->GetSocket();
1.30      foxr     1227: 	if($Socket eq undef) {
1.64      foxr     1228: 	    &child_exit(-1, "did not get a socket from the connection");
1.5       foxr     1229: 	} else {
                   1230: 	    &Debug(9,"MakeLondConnection got socket: ".$Socket);
                   1231: 	}
1.1       foxr     1232: 	
1.21      foxr     1233: 	$Connection->SetTimeoutCallback(\&SocketTimeout);
                   1234: 
1.23      foxr     1235: 	my $event = Event->io(fd       => $Socket,
1.5       foxr     1236: 			   poll     => 'w',
                   1237: 			   cb       => \&LondWritable,
1.8       foxr     1238: 			   data     => $Connection,
1.5       foxr     1239: 			   desc => 'Connection to lond server');
                   1240: 	$ActiveConnections{$Connection} = $event;
1.52      foxr     1241: 	if ($ConnectionCount == 0) {
                   1242: 	    &SetupTimer;	# Need to handle timeouts with connections...
                   1243: 	}
1.5       foxr     1244: 	$ConnectionCount++;
1.95      foxr     1245: 	$Connection->SetClientData($ConnectionCount);
1.8       foxr     1246: 	Debug(4, "Connection count = ".$ConnectionCount);
1.6       foxr     1247: 	if($ConnectionCount == 1) { # First Connection:
                   1248: 	    QueueDelayed;
                   1249: 	}
1.97    ! raeburn  1250: 	Log("SUCCESS", "Created connection ".$ConnectionCount
1.9       foxr     1251: 	    ." to host ".GetServerHost());
1.10      foxr     1252: 	return 1;		# Return success.
1.1       foxr     1253:     }
                   1254:     
                   1255: }
1.3       albertel 1256: 
1.1       foxr     1257: =pod
1.3       albertel 1258: 
1.1       foxr     1259: =head2 StartRequest
1.3       albertel 1260: 
                   1261: Starts a lond request going on a specified lond connection.
                   1262: parameters are:
                   1263: 
                   1264: =item $Lond
                   1265: 
                   1266: Connection to the lond that will send the transaction and receive the
                   1267: reply.
                   1268: 
                   1269: =item $Client
                   1270: 
1.97    ! raeburn  1271: Connection to the client that is making this request. We got the
1.3       albertel 1272: request from this socket, and when the request has been relayed to
                   1273: lond and we get a reply back from lond it will get sent to this
                   1274: socket.
                   1275: 
                   1276: =item $Request
                   1277: 
                   1278: The text of the request to send.
                   1279: 
1.1       foxr     1280: =cut
                   1281: 
                   1282: sub StartRequest {
1.47      foxr     1283: 
                   1284:     my ($Lond, $Request) = @_;
1.1       foxr     1285:     
1.7       foxr     1286:     Debug(6, "StartRequest: ".$Request->getRequest());
1.1       foxr     1287: 
                   1288:     my $Socket = $Lond->GetSocket();
                   1289:     
1.7       foxr     1290:     $Request->Activate($Lond);
                   1291:     $ActiveTransactions{$Lond} = $Request;
1.1       foxr     1292: 
1.7       foxr     1293:     $Lond->InitiateTransaction($Request->getRequest());
1.23      foxr     1294:     my $event = Event->io(fd      => $Socket,
1.1       foxr     1295: 		       poll    => "w",
                   1296: 		       cb      => \&LondWritable,
                   1297: 		       data    => $Lond,
                   1298: 		       desc    => "lond transaction connection");
                   1299:     $ActiveConnections{$Lond} = $event;
                   1300:     Debug(8," Start Request made watcher data with ".$event->data."\n");
                   1301: }
                   1302: 
                   1303: =pod
1.3       albertel 1304: 
1.1       foxr     1305: =head2 QueueTransaction
1.3       albertel 1306: 
                   1307: If there is an idle lond connection, it is put to work doing this
                   1308: transaction.  Otherwise, the transaction is placed in the work queue.
                   1309: If placed in the work queue and the maximum number of connections has
                   1310: not yet been created, a new connection will be started.  Our goal is
                   1311: to eventually have a sufficient number of connections that the work
                   1312: queue will typically be empty.  parameters are:
                   1313: 
                   1314: =item Socket
                   1315: 
                   1316: open on the lonc client.
                   1317: 
                   1318: =item Request
                   1319: 
                   1320: data to send to the lond.
1.1       foxr     1321: 
                   1322: =cut
1.3       albertel 1323: 
1.1       foxr     1324: sub QueueTransaction {
                   1325: 
1.7       foxr     1326:     my $requestData   = shift;	# This is a LondTransaction.
                   1327:     my $cmd           = $requestData->getRequest();
                   1328: 
                   1329:     Debug(6,"QueueTransaction: ".$cmd);
1.1       foxr     1330: 
                   1331:     my $LondSocket    = $IdleConnections->pop();
                   1332:     if(!defined $LondSocket) {	# Need to queue request.
1.29      foxr     1333: 	Debug(5,"Must queue...");
1.1       foxr     1334: 	$WorkQueue->enqueue($requestData);
1.56      foxr     1335: 	Debug(5, "Queue Transaction startnew $ConnectionCount $LondConnecting");
                   1336: 	if(($ConnectionCount < $MaxConnectionCount)   && (! $LondConnecting)) {
                   1337: 
1.22      foxr     1338: 	    if($ConnectionRetriesLeft > 0) {
1.29      foxr     1339: 		Debug(5,"Starting additional lond connection");
1.56      foxr     1340: 		if(&MakeLondConnection() == 0) {
1.22      foxr     1341: 		    EmptyQueue();	# Fail transactions, can't make connection.
1.42      foxr     1342: 		    CloseAllLondConnections; # Should all be closed but...
1.22      foxr     1343: 		}
                   1344: 	    } else {
                   1345: 		ShowStatus(GetServerHost()." >>> DEAD !!!! <<<");
1.56      foxr     1346: 		$LondConnecting = 0;
1.22      foxr     1347: 		EmptyQueue();	# It's worse than that ... he's dead Jim.
1.42      foxr     1348: 		CloseAllLondConnections; # Should all be closed but..
1.17      foxr     1349: 	    }
1.1       foxr     1350: 	}
                   1351:     } else {			# Can start the request:
                   1352: 	Debug(8,"Can start...");
1.7       foxr     1353: 	StartRequest($LondSocket,  $requestData);
1.1       foxr     1354:     }
                   1355: }
                   1356: 
1.95      foxr     1357: #-------------------------- Lonc UNIX socket handling -------------------
1.1       foxr     1358: =pod
1.3       albertel 1359: 
1.1       foxr     1360: =head2 ClientRequest
1.97    ! raeburn  1361: 
1.3       albertel 1362: Callback that is called when data can be read from the UNIX domain
                   1363: socket connecting us with an apache server process.
1.1       foxr     1364: 
                   1365: =cut
                   1366: 
                   1367: sub ClientRequest {
                   1368:     Debug(6, "ClientRequest");
                   1369:     my $event   = shift;
                   1370:     my $watcher = $event->w;
                   1371:     my $socket  = $watcher->fd;
                   1372:     my $data    = $watcher->data;
                   1373:     my $thisread;
                   1374: 
                   1375:     Debug(9, "  Watcher named: ".$watcher->desc);
                   1376: 
                   1377:     my $rv = $socket->recv($thisread, POSIX::BUFSIZ, 0);
                   1378:     Debug(8, "rcv:  data length = ".length($thisread)
                   1379: 	  ." read =".$thisread);
1.29      foxr     1380:     unless (defined $rv  && length($thisread)) {
1.1       foxr     1381: 	 # Likely eof on socket.
                   1382: 	Debug(5,"Client Socket closed on lonc for ".$RemoteHost);
                   1383: 	close($socket);
                   1384: 	$watcher->cancel();
                   1385: 	delete($ActiveClients{$socket});
1.10      foxr     1386: 	return;
1.1       foxr     1387:     }
                   1388:     Debug(8,"Data: ".$data." this read: ".$thisread);
                   1389:     $data = $data.$thisread;	# Append new data.
                   1390:     $watcher->data($data);
1.44      albertel 1391:     if($data =~ /\n$/) {	# Request entirely read.
1.87      albertel 1392: 	if ($data eq "close_connection_exit\n") {
1.9       foxr     1393: 	    Log("CRITICAL",
                   1394: 		"Request Close Connection ... exiting");
                   1395: 	    CloseAllLondConnections();
                   1396: 	    exit;
1.87      albertel 1397: 	} elsif ($data eq "reset_retries\n") {
                   1398: 	    Log("INFO", "Resetting Connection Retries.");
                   1399: 	    $ConnectionRetriesLeft = $ConnectionRetries;
                   1400: 	    &UpdateStatus();
                   1401: 	    my $Transaction = LondTransaction->new($data);
                   1402: 	    $Transaction->SetClient($socket);
                   1403: 	    StartClientReply($Transaction, "ok\n");
                   1404: 	    $watcher->cancel();
                   1405: 	    return;
1.9       foxr     1406: 	}
1.1       foxr     1407: 	Debug(8, "Complete transaction received: ".$data);
1.87      albertel 1408: 	if ($LogTransactions) {
1.39      foxr     1409: 	    Log("SUCCESS", "Transaction: '$data'"); # Transaction has \n.
                   1410: 	}
1.8       foxr     1411: 	my $Transaction = LondTransaction->new($data);
1.7       foxr     1412: 	$Transaction->SetClient($socket);
                   1413: 	QueueTransaction($Transaction);
1.1       foxr     1414: 	$watcher->cancel();	# Done looking for input data.
                   1415:     }
                   1416: 
                   1417: }
                   1418: 
1.62      foxr     1419: #
                   1420: #     Accept a connection request for a client (lonc child) and
                   1421: #    start up an event watcher to keep an eye on input from that 
                   1422: #    Event.  This can be called both from NewClient and from
1.80      albertel 1423: #    ChildProcess.
1.62      foxr     1424: # Parameters:
                   1425: #    $socket       - The listener socket.
                   1426: # Returns:
                   1427: #   NONE
                   1428: # Side Effects:
                   1429: #    An event is made to watch the accepted connection.
                   1430: #    Active clients hash is updated to reflect the new connection.
                   1431: #    The client connection count is incremented.
                   1432: #
                   1433: sub accept_client {
                   1434:     my ($socket) = @_;
                   1435: 
                   1436:     Debug(8, "Entering accept for lonc UNIX socket\n");
                   1437:     my $connection = $socket->accept();	# Accept the client connection.
                   1438:     Debug(8,"Connection request accepted from "
                   1439: 	  .GetPeername($connection, AF_UNIX));
                   1440: 
                   1441: 
                   1442:     my $description = sprintf("Connection to lonc client %d",
                   1443: 			      $ClientConnection);
                   1444:     Debug(9, "Creating event named: ".$description);
                   1445:     Event->io(cb      => \&ClientRequest,
                   1446: 	      poll    => 'r',
                   1447: 	      desc    => $description,
                   1448: 	      data    => "",
                   1449: 	      fd      => $connection);
                   1450:     $ActiveClients{$connection} = $ClientConnection;
                   1451:     $ClientConnection++;
                   1452: }
1.1       foxr     1453: 
                   1454: =pod
1.3       albertel 1455: 
1.1       foxr     1456: =head2  NewClient
1.3       albertel 1457: 
                   1458: Callback that is called when a connection is received on the unix
                   1459: socket for a new client of lonc.  The callback is parameterized by the
                   1460: event.. which is a-priori assumed to be an io event, and therefore has
1.97    ! raeburn  1461: an fd member that is the Listener socket.  We accept the connection
1.3       albertel 1462: and register a new event on the readability of that socket:
                   1463: 
1.1       foxr     1464: =cut
1.3       albertel 1465: 
1.1       foxr     1466: sub NewClient {
                   1467:     Debug(6, "NewClient");
                   1468:     my $event      = shift;		# Get the event parameters.
                   1469:     my $watcher    = $event->w; 
                   1470:     my $socket     = $watcher->fd;	# Get the event' socket.
                   1471: 
1.62      foxr     1472:     &accept_client($socket);
1.1       foxr     1473: }
1.3       albertel 1474: 
                   1475: =pod
                   1476: 
                   1477: =head2 GetLoncSocketPath
                   1478: 
                   1479: Returns the name of the UNIX socket on which to listen for client
                   1480: connections.
1.1       foxr     1481: 
1.58      foxr     1482: =head2 Parameters:
                   1483: 
                   1484:     host (optional)  - Name of the host socket to return.. defaults to
                   1485:                        the return from GetServerHost().
                   1486: 
1.1       foxr     1487: =cut
1.3       albertel 1488: 
1.1       foxr     1489: sub GetLoncSocketPath {
1.58      foxr     1490: 
                   1491:     my $host = GetServerHost();	# Default host.
                   1492:     if (@_) {
                   1493: 	($host)  = @_;		# Override if supplied.
                   1494:     }
                   1495:     return $UnixSocketDir."/".$host;
1.1       foxr     1496: }
                   1497: 
1.3       albertel 1498: =pod
                   1499: 
                   1500: =head2 GetServerHost
                   1501: 
                   1502: Returns the host whose lond we talk with.
                   1503: 
1.1       foxr     1504: =cut
1.3       albertel 1505: 
1.7       foxr     1506: sub GetServerHost {
1.1       foxr     1507:     return $RemoteHost;		# Setup by the fork.
                   1508: }
1.3       albertel 1509: 
                   1510: =pod
                   1511: 
1.81      albertel 1512: =head2 GetServerId
                   1513: 
                   1514: Returns the hostid whose lond we talk with.
                   1515: 
                   1516: =cut
                   1517: 
                   1518: sub GetHostId {
                   1519:     return $RemoteHostId;		# Setup by the fork.
                   1520: }
                   1521: 
                   1522: =pod
                   1523: 
1.3       albertel 1524: =head2 GetServerPort
                   1525: 
                   1526: Returns the lond port number.
                   1527: 
1.1       foxr     1528: =cut
1.3       albertel 1529: 
1.7       foxr     1530: sub GetServerPort {
1.1       foxr     1531:     return $perlvar{londPort};
                   1532: }
1.3       albertel 1533: 
                   1534: =pod
                   1535: 
                   1536: =head2 SetupLoncListener
                   1537: 
                   1538: Setup a lonc listener event.  The event is called when the socket
                   1539: becomes readable.. that corresponds to the receipt of a new
                   1540: connection.  The event handler established will accept the connection
1.97    ! raeburn  1541: (creating a communcations channel), that in turn will establish
1.3       albertel 1542: another event handler to subess requests.
1.1       foxr     1543: 
1.58      foxr     1544: =head2  Parameters:
                   1545: 
                   1546:    host (optional)   Name of the host to set up a unix socket to.
                   1547: 
1.1       foxr     1548: =cut
1.3       albertel 1549: 
1.1       foxr     1550: sub SetupLoncListener {
1.78      albertel 1551:     my ($host,$SocketName) = @_;
                   1552:     if (!$host) { $host = &GetServerHost(); }
                   1553:     if (!$SocketName) { $SocketName = &GetLoncSocketPath($host); }
1.1       foxr     1554: 
1.78      albertel 1555: 
                   1556:     unlink($SocketName);
1.58      foxr     1557: 
1.1       foxr     1558:     my $socket;
1.7       foxr     1559:     unless ($socket =IO::Socket::UNIX->new(Local  => $SocketName,
1.55      albertel 1560: 					    Listen => 250, 
1.1       foxr     1561: 					    Type   => SOCK_STREAM)) {
1.64      foxr     1562: 	if($I_am_child) {
                   1563: 	    &child_exit(-1, "Failed to create a lonc listener socket");
                   1564: 	} else {
                   1565: 	    die "Failed to create a lonc listner socket";
                   1566: 	}
1.1       foxr     1567:     }
1.59      foxr     1568:     return $socket;
1.1       foxr     1569: }
                   1570: 
1.39      foxr     1571: #
                   1572: #   Toggle transaction logging.
                   1573: #  Implicit inputs:  
                   1574: #     LogTransactions
                   1575: #  Implicit Outputs:
                   1576: #     LogTransactions
                   1577: sub ToggleTransactionLogging {
                   1578:     print STDERR "Toggle transaction logging...\n";
                   1579:     if(!$LogTransactions) {
                   1580: 	$LogTransactions = 1;
                   1581:     } else {
                   1582: 	$LogTransactions = 0;
                   1583:     }
                   1584: 
                   1585: 
                   1586:     Log("SUCCESS", "Toggled transaction logging: $LogTransactions \n");
                   1587: }
                   1588: 
1.14      foxr     1589: =pod 
                   1590: 
                   1591: =head2 ChildStatus
                   1592:  
                   1593: Child USR1 signal handler to report the most recent status
                   1594: into the status file.
                   1595: 
1.22      foxr     1596: We also use this to reset the retries count in order to allow the
                   1597: client to retry connections with a previously dead server.
1.69      matthew  1598: 
1.14      foxr     1599: =cut
1.46      albertel 1600: 
1.14      foxr     1601: sub ChildStatus {
                   1602:     my $event = shift;
                   1603:     my $watcher = $event->w;
                   1604: 
                   1605:     Debug(2, "Reporting child status because : ".$watcher->data);
                   1606:     my $docdir = $perlvar{'lonDocRoot'};
1.67      albertel 1607:     
                   1608:     open(LOG,">>$docdir/lon-status/loncstatus.txt");
                   1609:     flock(LOG,LOCK_EX);
                   1610:     print LOG $$."\t".$RemoteHost."\t".$Status."\t".
1.14      foxr     1611: 	$RecentLogEntry."\n";
1.38      foxr     1612:     #
                   1613:     #  Write out information about each of the connections:
                   1614:     #
1.46      albertel 1615:     if ($DebugLevel > 2) {
1.67      albertel 1616: 	print LOG "Active connection statuses: \n";
1.46      albertel 1617: 	my $i = 1;
                   1618: 	print STDERR  "================================= Socket Status Dump:\n";
                   1619: 	foreach my $item (keys %ActiveConnections) {
                   1620: 	    my $Socket = $ActiveConnections{$item}->data;
                   1621: 	    my $state  = $Socket->GetState();
1.67      albertel 1622: 	    print LOG "Connection $i State: $state\n";
1.46      albertel 1623: 	    print STDERR "---------------------- Connection $i \n";
1.48      foxr     1624: 	    $Socket->Dump(-1);	# Ensure it gets dumped..
1.46      albertel 1625: 	    $i++;	
                   1626: 	}
1.38      foxr     1627:     }
1.67      albertel 1628:     flock(LOG,LOCK_UN);
                   1629:     close(LOG);
1.22      foxr     1630:     $ConnectionRetriesLeft = $ConnectionRetries;
1.70      albertel 1631:     UpdateStatus();
1.14      foxr     1632: }
                   1633: 
1.1       foxr     1634: =pod
1.3       albertel 1635: 
1.10      foxr     1636: =head2 SignalledToDeath
                   1637: 
                   1638: Called in response to a signal that causes a chid process to die.
                   1639: 
                   1640: =cut
                   1641: 
                   1642: 
                   1643: sub SignalledToDeath {
1.14      foxr     1644:     my $event  = shift;
                   1645:     my $watcher= $event->w;
                   1646: 
                   1647:     Debug(2,"Signalled to death! via ".$watcher->data);
1.17      foxr     1648:     my ($signal) = $watcher->data;
1.10      foxr     1649:     chomp($signal);
                   1650:     Log("CRITICAL", "Abnormal exit.  Child $$ for $RemoteHost "
                   1651: 	."died through "."\"$signal\"");
1.68      albertel 1652:     #LogPerm("F:lonc: $$ on $RemoteHost signalled to death: "
                   1653: #	    ."\"$signal\"");
1.12      foxr     1654:     exit 0;
1.10      foxr     1655: 
                   1656: }
1.16      foxr     1657: 
1.69      matthew  1658: =pod
                   1659: 
1.16      foxr     1660: =head2 ToggleDebug
                   1661: 
                   1662: This sub toggles trace debugging on and off.
                   1663: 
                   1664: =cut
                   1665: 
                   1666: sub ToggleDebug {
                   1667:     my $Current    = $DebugLevel;
                   1668:        $DebugLevel = $NextDebugLevel;
                   1669:        $NextDebugLevel = $Current;
                   1670: 
                   1671:     Log("SUCCESS", "New debugging level for $RemoteHost now $DebugLevel");
                   1672: 
                   1673: }
                   1674: 
1.69      matthew  1675: =pod
                   1676: 
1.1       foxr     1677: =head2 ChildProcess
                   1678: 
                   1679: This sub implements a child process for a single lonc daemon.
1.61      foxr     1680: Optional parameter:
1.97    ! raeburn  1681:    $socket  - if provided, this is a socket already open for listening
        !          1682:               on the client socket. Otherwise, a new listener is set up.
1.1       foxr     1683: 
                   1684: =cut
                   1685: 
                   1686: sub ChildProcess {
1.80      albertel 1687:     #  We've inherited all the
1.62      foxr     1688:     #  events of our parent and those have to be cancelled or else
                   1689:     #  all holy bloody chaos will result.. trust me, I already made
                   1690:     #  >that< mistake.
                   1691: 
                   1692:     my $host = GetServerHost();
                   1693:     foreach my $listener (keys %parent_dispatchers) {
                   1694: 	my $watcher = $parent_dispatchers{$listener};
                   1695: 	my $s       = $watcher->fd;
                   1696: 	if ($listener ne $host) { # Close everyone but me.
                   1697: 	    Debug(5, "Closing listen socket for $listener");
                   1698: 	    $s->close();
                   1699: 	}
                   1700: 	Debug(5, "Killing watcher for $listener");
                   1701: 
                   1702: 	$watcher->cancel();
1.65      foxr     1703: 	delete($parent_dispatchers{$listener});
1.62      foxr     1704: 
                   1705:     }
1.65      foxr     1706: 
                   1707:     #  kill off the parent's signal handlers too!  
                   1708:     #
                   1709: 
                   1710:     for my $handler (keys %parent_handlers) {
                   1711: 	my $watcher = $parent_handlers{$handler};
                   1712: 	$watcher->cancel();
                   1713: 	delete($parent_handlers{$handler});
                   1714:     }
                   1715: 
1.64      foxr     1716:     $I_am_child    = 1;		# Seems like in spite of it all I may still getting
                   1717:                                 # parent event dispatches.. flag I'm a child.
1.1       foxr     1718: 
                   1719: 
1.14      foxr     1720:     #
                   1721:     #  Signals must be handled by the Event framework...
1.61      foxr     1722:     #
1.14      foxr     1723: 
                   1724:     Event->signal(signal   => "QUIT",
                   1725: 		  cb       => \&SignalledToDeath,
                   1726: 		  data     => "QUIT");
                   1727:     Event->signal(signal   => "HUP",
                   1728: 		  cb       => \&ChildStatus,
                   1729: 		  data     => "HUP");
                   1730:     Event->signal(signal   => "USR1",
                   1731: 		  cb       => \&ChildStatus,
                   1732: 		  data     => "USR1");
1.39      foxr     1733:     Event->signal(signal   => "USR2",
                   1734: 		  cb       => \&ToggleTransactionLogging);
1.16      foxr     1735:     Event->signal(signal   => "INT",
                   1736: 		  cb       => \&ToggleDebug,
                   1737: 		  data     => "INT");
1.1       foxr     1738: 
1.93      foxr     1739:     # Block the pipe signal we'll get when the socket disconnects.  We detect 
                   1740:     # socket disconnection via send/receive failures. On disconnect, the
                   1741:     # socket becomes readable .. which will force the disconnect detection.
                   1742: 
                   1743:     my $set = POSIX::SigSet->new(SIGPIPE);
                   1744:     sigprocmask(SIG_BLOCK, $set);
                   1745: 
1.62      foxr     1746:     #  Figure out if we got passed a socket or need to open one to listen for
                   1747:     #  client requests.
                   1748: 
1.61      foxr     1749:     my ($socket) = @_;
                   1750:     if (!$socket) {
                   1751: 
                   1752: 	$socket =  SetupLoncListener();
                   1753:     }
1.62      foxr     1754:     #  Establish an event to listen for client connection requests.
                   1755: 
                   1756: 
1.59      foxr     1757:     Event->io(cb   => \&NewClient,
                   1758: 	      poll => 'r',
                   1759: 	      desc => 'Lonc Listener Unix Socket',
                   1760: 	      fd   => $socket);
1.1       foxr     1761:     
1.76      albertel 1762:     $Event::DebugLevel = $DebugLevel;
1.1       foxr     1763:     
                   1764:     Debug(9, "Making initial lond connection for ".$RemoteHost);
                   1765: 
                   1766: # Setup the initial server connection:
                   1767:     
1.62      foxr     1768:      # &MakeLondConnection(); // let first work request do it.
1.10      foxr     1769: 
1.80      albertel 1770:     #  need to accept the connection since the event may  not fire.
1.62      foxr     1771: 
1.80      albertel 1772:     &accept_client($socket);
1.5       foxr     1773: 
1.1       foxr     1774:     Debug(9,"Entering event loop");
                   1775:     my $ret = Event::loop();		#  Start the main event loop.
                   1776:     
                   1777:     
1.64      foxr     1778:     &child_exit (-1,"Main event loop exited!!!");
1.1       foxr     1779: }
                   1780: 
                   1781: #  Create a new child for host passed in:
                   1782: 
                   1783: sub CreateChild {
1.81      albertel 1784:     my ($host, $hostid) = @_;
1.52      foxr     1785: 
1.12      foxr     1786:     my $sigset = POSIX::SigSet->new(SIGINT);
                   1787:     sigprocmask(SIG_BLOCK, $sigset);
1.1       foxr     1788:     $RemoteHost = $host;
1.91      foxr     1789:     ShowStatus('Parent keeping the flock'); # Update time in status message.
1.9       foxr     1790:     Log("CRITICAL", "Forking server for ".$host);
1.23      foxr     1791:     my $pid          = fork;
1.1       foxr     1792:     if($pid) {			# Parent
1.17      foxr     1793: 	$RemoteHost = "Parent";
1.83      albertel 1794: 	$ChildPid{$pid} = $host;
1.12      foxr     1795: 	sigprocmask(SIG_UNBLOCK, $sigset);
1.82      albertel 1796: 	undef(@all_host_ids);
1.1       foxr     1797:     } else {			# child.
1.81      albertel 1798: 	$RemoteHostId = $hostid;
1.5       foxr     1799: 	ShowStatus("Connected to ".$RemoteHost);
1.23      foxr     1800: 	$SIG{INT} = 'DEFAULT';
1.12      foxr     1801: 	sigprocmask(SIG_UNBLOCK, $sigset);
1.81      albertel 1802: 	&ChildProcess();		# Does not return.
1.1       foxr     1803:     }
1.61      foxr     1804: }
1.1       foxr     1805: 
1.61      foxr     1806: # parent_client_connection:
                   1807: #    Event handler that processes client connections for the parent process.
                   1808: #    This sub is called when the parent is listening on a socket and
                   1809: #    a connection request arrives.  We must:
                   1810: #     Start a child process to accept the connection request.
                   1811: #     Kill our listen on the socket.
                   1812: # Parameter:
                   1813: #    event       - The event object that was created to monitor this socket.
                   1814: #                  event->w->fd is the socket.
                   1815: # Returns:
                   1816: #    NONE
                   1817: #
                   1818: sub parent_client_connection {
1.62      foxr     1819:     if ($I_am_child) {
                   1820: 	#  Should not get here, but seem to anyway:
                   1821: 	&Debug(5," Child caught parent client connection event!!");
                   1822: 	my ($event) = @_;
                   1823: 	my $watcher = $event->w;
                   1824: 	$watcher->cancel();	# Try to kill it off again!!
                   1825:     } else {
                   1826: 	&Debug(9, "parent_client_connection");
                   1827: 	my ($event)   = @_;
                   1828: 	my $watcher   = $event->w;
                   1829: 	my $socket    = $watcher->fd;
1.81      albertel 1830: 	my $connection = $socket->accept();	# Accept the client connection.
                   1831: 	Event->io(cb      => \&get_remote_hostname,
                   1832: 		  poll    => 'r',
                   1833: 		  data    => "",
                   1834: 		  fd      => $connection);
1.77      albertel 1835:     }
                   1836: }
                   1837: 
                   1838: sub get_remote_hostname {
1.82      albertel 1839:     my ($event)   = @_;
                   1840:     my $watcher   = $event->w;
                   1841:     my $socket    = $watcher->fd;
                   1842: 
                   1843:     my $thisread;
                   1844:     my $rv = $socket->recv($thisread, POSIX::BUFSIZ, 0);
                   1845:     Debug(8, "rcv:  data length = ".length($thisread)." read =".$thisread);
                   1846:     if (!defined($rv) || length($thisread) == 0) {
                   1847: 	# Likely eof on socket.
                   1848: 	Debug(5,"Client Socket closed on lonc for p_c_c");
                   1849: 	close($socket);
                   1850: 	$watcher->cancel();
                   1851: 	return;
                   1852:     }
                   1853: 
                   1854:     my $data    = $watcher->data().$thisread;
                   1855:     $watcher->data($data);
                   1856:     if($data =~ /\n$/) {	# Request entirely read.
                   1857: 	chomp($data);
                   1858:     } else {
                   1859: 	return;
                   1860:     }
1.77      albertel 1861: 
1.82      albertel 1862:     &Debug(5,"Creating child for $data (parent_client_connection)");
                   1863:     (my $hostname,my $lonid,@all_host_ids) = split(':',$data);
1.83      albertel 1864:     $ChildHost{$hostname}++;
                   1865:     if ($ChildHost{$hostname} == 1) {
                   1866: 	&CreateChild($hostname,$lonid);
                   1867:     } else {
                   1868: 	&Log('WARNING',"Request for a second child on $hostname");
                   1869:     }
1.82      albertel 1870:     # Clean up the listen since now the child takes over until it exits.
                   1871:     $watcher->cancel();		# Nolonger listening to this event
                   1872:     $socket->send("done\n");
                   1873:     $socket->close();
1.61      foxr     1874: }
                   1875: 
                   1876: # parent_listen:
                   1877: #    Opens a socket and starts a listen for the parent process on a client UNIX
                   1878: #    domain socket.
                   1879: #
                   1880: #    This involves:
                   1881: #       Creating a socket for listen.
                   1882: #       Removing any socket lock file
                   1883: #       Adding an event handler for this socket becoming readable
                   1884: #         To the parent's event dispatcher.
                   1885: # Parameters:
                   1886: #    loncapa_host    - LonCAPA cluster name of the host represented by the client
                   1887: #                      socket.
                   1888: # Returns:
                   1889: #    NONE
                   1890: #
                   1891: sub parent_listen {
                   1892:     my ($loncapa_host) = @_;
                   1893:     Debug(5, "parent_listen: $loncapa_host");
                   1894: 
1.78      albertel 1895:     my ($socket,$file);
                   1896:     if (!$loncapa_host) {
                   1897: 	$loncapa_host = 'common_parent';
                   1898: 	$file         = $perlvar{'lonSockCreate'};
                   1899:     } else {
                   1900: 	$file         = &GetLoncSocketPath($loncapa_host);
                   1901:     }
                   1902:     $socket = &SetupLoncListener($loncapa_host,$file);
                   1903: 
1.62      foxr     1904:     $listening_to{$socket} = $loncapa_host;
1.61      foxr     1905:     if (!$socket) {
                   1906: 	die "Unable to create a listen socket for $loncapa_host";
                   1907:     }
                   1908:     
1.78      albertel 1909:     my $lock_file = $file.".lock";
1.61      foxr     1910:     unlink($lock_file);		# No problem if it doesn't exist yet [startup e.g.]
                   1911: 
1.77      albertel 1912:     my $watcher = 
                   1913: 	Event->io(cb    => \&parent_client_connection,
                   1914: 		  poll  => 'r',
                   1915: 		  desc  => "Parent listener unix socket ($loncapa_host)",
                   1916: 		  data => "",
                   1917: 		  fd    => $socket);
1.62      foxr     1918:     $parent_dispatchers{$loncapa_host} = $watcher;
1.61      foxr     1919: 
                   1920: }
                   1921: 
1.77      albertel 1922: sub parent_clean_up {
                   1923:     my ($loncapa_host) = @_;
1.87      albertel 1924:     Debug(1, "parent_clean_up: $loncapa_host");
1.77      albertel 1925: 
                   1926:     my $socket_file = &GetLoncSocketPath($loncapa_host);
                   1927:     unlink($socket_file);	# No problem if it doesn't exist yet [startup e.g.]
                   1928:     my $lock_file   = $socket_file.".lock";
                   1929:     unlink($lock_file);		# No problem if it doesn't exist yet [startup e.g.]
                   1930: }
                   1931: 
1.61      foxr     1932: 
1.83      albertel 1933: 
                   1934: #    This sub initiates a listen on the common unix domain lonc client socket.
                   1935: #    loncnew starts up with no children, and only spawns off children when a
                   1936: #    connection request occurs on the common client unix socket.  The spawned
                   1937: #    child continues to run until it has been idle a while at which point it
                   1938: #    eventually exits and once more the parent picks up the listen.
1.61      foxr     1939: #
                   1940: #  Parameters:
                   1941: #      NONE
                   1942: #  Implicit Inputs:
                   1943: #    The configuration file that has been read in by LondConnection.
                   1944: #  Returns:
                   1945: #     NONE
                   1946: #
1.77      albertel 1947: sub listen_on_common_socket {
                   1948:     Debug(5, "listen_on_common_socket");
1.78      albertel 1949:     &parent_listen();
1.77      albertel 1950: }
                   1951: 
1.63      foxr     1952: #   server_died is called whenever a child process exits.
                   1953: #   Since this is dispatched via a signal, we must process all
                   1954: #   dead children until there are no more left.  The action
                   1955: #   is to:
                   1956: #      - Remove the child from the bookeeping hashes
                   1957: #      - Re-establish a listen on the unix domain socket associated
                   1958: #        with that host.
                   1959: # Parameters:
                   1960: #    The event, but we don't actually care about it.
                   1961: sub server_died {
                   1962:     &Debug(9, "server_died called...");
                   1963:     
                   1964:     while(1) {			# Loop until waitpid nowait fails.
                   1965: 	my $pid = waitpid(-1, WNOHANG);
                   1966: 	if($pid <= 0) {
                   1967: 	    return;		# Nothing left to wait for.
                   1968: 	}
                   1969: 	# need the host to restart:
                   1970: 
1.83      albertel 1971: 	my $host = $ChildPid{$pid};
1.63      foxr     1972: 	if($host) {		# It's for real...
                   1973: 	    &Debug(9, "Caught sigchild for $host");
1.83      albertel 1974: 	    delete($ChildPid{$pid});
                   1975: 	    delete($ChildHost{$host});
1.81      albertel 1976: 	    &parent_clean_up($host);
                   1977: 
1.63      foxr     1978: 	} else {
                   1979: 	    &Debug(5, "Caught sigchild for pid not in hosts hash: $pid");
                   1980: 	}
                   1981:     }
                   1982: 
                   1983: }
                   1984: 
1.1       foxr     1985: #
                   1986: #  Parent process logic pass 1:
                   1987: #   For each entry in the hosts table, we will
                   1988: #  fork off an instance of ChildProcess to service the transactions
                   1989: #  to that host.  Each pid will be entered in a global hash
                   1990: #  with the value of the key, the host.
                   1991: #  The parent will then enter a loop to wait for process exits.
                   1992: #  Each exit gets logged and the child gets restarted.
                   1993: #
                   1994: 
1.5       foxr     1995: #
                   1996: #   Fork and start in new session so hang-up isn't going to 
                   1997: #   happen without intent.
                   1998: #
                   1999: 
                   2000: 
1.6       foxr     2001: 
                   2002: 
1.8       foxr     2003: 
1.6       foxr     2004: 
                   2005: ShowStatus("Forming new session");
                   2006: my $childpid = fork;
                   2007: if ($childpid != 0) {
                   2008:     sleep 4;			# Give child a chacne to break to
                   2009:     exit 0;			# a new sesion.
                   2010: }
1.8       foxr     2011: #
                   2012: #   Write my pid into the pid file so I can be located
                   2013: #
                   2014: 
                   2015: ShowStatus("Parent writing pid file:");
1.23      foxr     2016: my $execdir = $perlvar{'lonDaemons'};
1.8       foxr     2017: open (PIDSAVE, ">$execdir/logs/lonc.pid");
                   2018: print PIDSAVE "$$\n";
                   2019: close(PIDSAVE);
1.6       foxr     2020: 
1.17      foxr     2021: 
                   2022: 
1.6       foxr     2023: if (POSIX::setsid() < 0) {
                   2024:     print "Could not create new session\n";
                   2025:     exit -1;
                   2026: }
1.5       foxr     2027: 
                   2028: ShowStatus("Forking node servers");
                   2029: 
1.9       foxr     2030: Log("CRITICAL", "--------------- Starting children ---------------");
                   2031: 
1.31      foxr     2032: LondConnection::ReadConfig;               # Read standard config files.
1.1       foxr     2033: 
1.80      albertel 2034: $RemoteHost = "[parent]";
1.81      albertel 2035: &listen_on_common_socket();
1.60      foxr     2036: 
1.12      foxr     2037: $RemoteHost = "Parent Server";
1.1       foxr     2038: 
                   2039: # Maintain the population:
1.5       foxr     2040: 
                   2041: ShowStatus("Parent keeping the flock");
1.1       foxr     2042: 
1.12      foxr     2043: 
1.80      albertel 2044: # We need to setup a SIGChild event to handle the exit (natural or otherwise)
                   2045: # of the children.
1.61      foxr     2046: 
1.80      albertel 2047: Event->signal(cb       => \&server_died,
                   2048: 	      desc     => "Child exit handler",
                   2049: 	      signal   => "CHLD");
                   2050: 
                   2051: 
                   2052: # Set up all the other signals we set up.
                   2053: 
                   2054: $parent_handlers{INT} = Event->signal(cb       => \&Terminate,
                   2055: 				      desc     => "Parent INT handler",
                   2056: 				      signal   => "INT");
                   2057: $parent_handlers{TERM} = Event->signal(cb       => \&Terminate,
                   2058: 				       desc     => "Parent TERM handler",
                   2059: 				       signal   => "TERM");
1.81      albertel 2060: $parent_handlers{HUP}  = Event->signal(cb       => \&KillThemAll,
                   2061: 				       desc     => "Parent HUP handler.",
                   2062: 				       signal   => "HUP");
1.80      albertel 2063: $parent_handlers{USR1} = Event->signal(cb       => \&CheckKids,
                   2064: 				       desc     => "Parent USR1 handler",
                   2065: 				       signal   => "USR1");
                   2066: $parent_handlers{USR2} = Event->signal(cb       => \&UpdateKids,
                   2067: 				       desc     => "Parent USR2 handler.",
                   2068: 				       signal   => "USR2");
                   2069: 
                   2070: #  Start procdesing events.
                   2071: 
                   2072: $Event::DebugLevel = $DebugLevel;
                   2073: Debug(9, "Parent entering event loop");
                   2074: my $ret = Event::loop();
                   2075: die "Main Event loop exited: $ret";
1.14      foxr     2076: 
                   2077: =pod
                   2078: 
                   2079: =head1 CheckKids
                   2080: 
                   2081:   Since kids do not die as easily in this implementation
1.97    ! raeburn  2082: as the previous one, there is no need to restart the
1.14      foxr     2083: dead ones (all dead kids get restarted when they die!!)
                   2084: The only thing this function does is to pass USR1 to the
                   2085: kids so that they report their status.
                   2086: 
                   2087: =cut
                   2088: 
                   2089: sub CheckKids {
                   2090:     Debug(2, "Checking status of children");
                   2091:     my $docdir = $perlvar{'lonDocRoot'};
                   2092:     my $fh = IO::File->new(">$docdir/lon-status/loncstatus.txt");
                   2093:     my $now=time;
                   2094:     my $local=localtime($now);
                   2095:     print $fh "LONC status $local - parent $$ \n\n";
1.65      foxr     2096:     foreach my $host (keys %parent_dispatchers) {
                   2097: 	print $fh "LONC Parent process listening for $host\n";
                   2098:     }
1.83      albertel 2099:     foreach my $pid (keys %ChildPid) {
1.14      foxr     2100: 	Debug(2, "Sending USR1 -> $pid");
                   2101: 	kill 'USR1' => $pid;	# Tell Child to report status.
                   2102:     }
1.65      foxr     2103: 
1.14      foxr     2104: }
1.24      foxr     2105: 
                   2106: =pod
                   2107: 
                   2108: =head1  UpdateKids
                   2109: 
1.25      foxr     2110: parent's SIGUSR2 handler.  This handler:
1.24      foxr     2111: 
                   2112: =item
                   2113: 
                   2114: Rereads the hosts file.
                   2115: 
                   2116: =item
                   2117:  
                   2118: Kills off (via sigint) children for hosts that have disappeared.
                   2119: 
                   2120: =item
                   2121: 
1.27      foxr     2122: QUITs  children for hosts that already exist (this just forces a status display
1.24      foxr     2123: and resets the connection retry count for that host.
                   2124: 
                   2125: =item
                   2126: 
                   2127: Starts new children for hosts that have been added to the hosts.tab file since
                   2128: the start of the master program and maintains them.
                   2129: 
                   2130: =cut
                   2131: 
                   2132: sub UpdateKids {
1.27      foxr     2133: 
1.25      foxr     2134:     Log("INFO", "Updating connections via SIGUSR2");
1.27      foxr     2135: 
1.65      foxr     2136:     #  I'm not sure what I was thinking in the first implementation.
                   2137:     # someone will have to work hard to convince me the effect is any
                   2138:     # different than Restart, especially now that we don't start up 
                   2139:     # per host servers automatically, may as well just restart.
                   2140:     # The down side is transactions that are in flight will get timed out
                   2141:     # (lost unless they are critical).
1.27      foxr     2142: 
1.81      albertel 2143:     &KillThemAll();
1.24      foxr     2144: }
                   2145: 
1.14      foxr     2146: 
1.13      foxr     2147: =pod
                   2148: 
                   2149: =head1 Restart
                   2150: 
                   2151: Signal handler for HUP... all children are killed and
1.97    ! raeburn  2152: we self restart.  This is an el-cheapo way to re-read
1.13      foxr     2153: the config file.
                   2154: 
                   2155: =cut
                   2156: 
                   2157: sub Restart {
1.23      foxr     2158:     &KillThemAll;		# First kill all the children.
1.13      foxr     2159:     Log("CRITICAL", "Restarting");
                   2160:     my $execdir = $perlvar{'lonDaemons'};
                   2161:     unlink("$execdir/logs/lonc.pid");
1.65      foxr     2162:     exec("$executable");
1.10      foxr     2163: }
1.12      foxr     2164: 
                   2165: =pod
                   2166: 
                   2167: =head1 KillThemAll
                   2168: 
                   2169: Signal handler that kills all children by sending them a 
1.17      foxr     2170: SIGHUP.  Responds to sigint and sigterm.
1.12      foxr     2171: 
                   2172: =cut
                   2173: 
1.10      foxr     2174: sub KillThemAll {
1.12      foxr     2175:     Debug(2, "Kill them all!!");
1.85      albertel 2176:     
                   2177:     #local($SIG{CHLD}) = 'IGNORE';
                   2178:     # Our children >will< die.
                   2179:     # but we need to catch their death and cleanup after them in case this is 
                   2180:     # a restart set of kills
                   2181:     my @allpids = keys(%ChildPid);
                   2182:     foreach my $pid (@allpids) {
1.83      albertel 2183: 	my $serving = $ChildPid{$pid};
1.52      foxr     2184: 	ShowStatus("Nicely Killing lonc for $serving pid = $pid");
                   2185: 	Log("CRITICAL", "Nicely Killing lonc for $serving pid = $pid");
1.17      foxr     2186: 	kill 'QUIT' => $pid;
1.12      foxr     2187:     }
1.85      albertel 2188:     ShowStatus("Finished killing child processes off.");
1.1       foxr     2189: }
1.12      foxr     2190: 
1.52      foxr     2191: 
                   2192: #
                   2193: #  Kill all children via KILL.  Just in case the
                   2194: #  first shot didn't get them.
                   2195: 
                   2196: sub really_kill_them_all_dammit
                   2197: {
                   2198:     Debug(2, "Kill them all Dammit");
                   2199:     local($SIG{CHLD} = 'IGNORE'); # In case some purist reenabled them.
1.83      albertel 2200:     foreach my $pid (keys %ChildPid) {
                   2201: 	my $serving = $ChildPid{$pid};
1.52      foxr     2202: 	&ShowStatus("Nastily killing lonc for $serving pid = $pid");
                   2203: 	Log("CRITICAL", "Nastily killing lonc for $serving pid = $pid");
                   2204: 	kill 'KILL' => $pid;
1.83      albertel 2205: 	delete($ChildPid{$pid});
1.52      foxr     2206: 	my $execdir = $perlvar{'lonDaemons'};
                   2207: 	unlink("$execdir/logs/lonc.pid");
                   2208:     }
                   2209: }
1.69      matthew  2210: 
1.14      foxr     2211: =pod
                   2212: 
                   2213: =head1 Terminate
                   2214:  
                   2215: Terminate the system.
                   2216: 
                   2217: =cut
                   2218: 
                   2219: sub Terminate {
1.52      foxr     2220:     &Log("CRITICAL", "Asked to kill children.. first be nice...");
                   2221:     &KillThemAll;
                   2222:     #
                   2223:     #  By now they really should all be dead.. but just in case 
                   2224:     #  send them all SIGKILL's after a bit of waiting:
                   2225: 
                   2226:     sleep(4);
                   2227:     &Log("CRITICAL", "Now kill children nasty");
                   2228:     &really_kill_them_all_dammit;
1.17      foxr     2229:     Log("CRITICAL","Master process exiting");
                   2230:     exit 0;
1.14      foxr     2231: 
                   2232: }
1.81      albertel 2233: 
                   2234: sub my_hostname {
                   2235:     use Sys::Hostname;
                   2236:     my $name = &hostname();
                   2237:     &Debug(9,"Name is $name");
                   2238:     return $name;
                   2239: }
                   2240: 
1.12      foxr     2241: =pod
1.1       foxr     2242: 
                   2243: =head1 Theory
1.3       albertel 2244: 
                   2245: The event class is used to build this as a single process with an
                   2246: event driven model.  The following events are handled:
1.1       foxr     2247: 
                   2248: =item UNIX Socket connection Received
                   2249: 
                   2250: =item Request data arrives on UNIX data transfer socket.
                   2251: 
                   2252: =item lond connection becomes writable.
                   2253: 
                   2254: =item timer fires at 1 second intervals.
                   2255: 
                   2256: All sockets are run in non-blocking mode.  Timeouts managed by the timer
                   2257: handler prevents hung connections.
                   2258: 
                   2259: Key data structures:
                   2260: 
1.3       albertel 2261: =item RequestQueue
                   2262: 
                   2263: A queue of requests received from UNIX sockets that are
                   2264: waiting for a chance to be forwarded on a lond connection socket.
                   2265: 
                   2266: =item ActiveConnections
                   2267: 
                   2268: A hash of lond connections that have transactions in process that are
                   2269: available to be timed out.
                   2270: 
                   2271: =item ActiveTransactions
                   2272: 
                   2273: A hash indexed by lond connections that contain the client reply
                   2274: socket for each connection that has an active transaction on it.
                   2275: 
                   2276: =item IdleConnections
                   2277: 
                   2278: A hash of lond connections that have no work to do.  These connections
                   2279: can be closed if they are idle for a long enough time.
1.1       foxr     2280: 
                   2281: =cut
1.88      foxr     2282: 
                   2283: =pod
                   2284: 
                   2285: =head1 Log messages
                   2286: 
                   2287: The following is a list of log messages that can appear in the 
                   2288: lonc.log file.  Each log file has a severity and a message.
                   2289: 
                   2290: =over 2
                   2291: 
                   2292: =item Warning  A socket timeout was detected
                   2293: 
                   2294: If there are pending transactions in the socket's queue,
                   2295: they are failed (saved if critical).  If the connection
                   2296: retry count gets exceeded by this, the
                   2297: remote host is marked as dead.
1.97    ! raeburn  2298: Called when timeouts occurred during the connection and
1.88      foxr     2299: connection dialog with a remote host.
                   2300: 
                   2301: =item Critical Host makred DEAD <hostname>   
                   2302: 
                   2303: The numer of retry counts for contacting a host was
                   2304: exceeded. The host is marked dead an no 
                   2305: further attempts will be made by that child.
                   2306: 
                   2307: =item Info lonc pipe client hung up on us     
                   2308: 
                   2309: Write to the client pipe indicated no data transferred
                   2310: Socket to remote host is shut down.  Reply to the client 
                   2311: is discarded.  Note: This is commented out in &ClientWriteable
                   2312: 
                   2313: =item Success  Reply from lond: <data>   
                   2314: 
                   2315: Can be enabled for debugging by setting LogTransactions to nonzero.
                   2316: Indicates a successful transaction with lond, <data> is the data received
                   2317: from the remote lond.
                   2318: 
                   2319: =item Success A delayed transaction was completed  
                   2320: 
                   2321: A transaction that must be reliable was executed and completed
                   2322: as lonc restarted.  This is followed by a mesage of the form
                   2323: 
                   2324:   S: client-name : request
                   2325: 
                   2326: =item WARNING  Failing transaction <cmd>:<subcmd>  
                   2327: 
                   2328: Transaction failed on a socket, but the failure retry count for the remote
                   2329: node has not yet been exhausted (the node is not yet marked dead).
                   2330: cmd is the command, subcmd is the subcommand.  This results from a con_lost
                   2331: when communicating with lond.
                   2332: 
                   2333: =item WARNING Shutting down a socket     
                   2334: 
                   2335: Called when a socket is being closed to lond.  This is emitted both when 
                   2336: idle pruning is being done and when the socket has been disconnected by the remote.
                   2337: 
                   2338: =item WARNING Lond connection lost.
                   2339: 
                   2340: Called when a read from lond's socket failed indicating lond has closed the 
                   2341: connection or died.  This should be followed by one or more
                   2342: 
                   2343:  "WARNING Failing transaction..." msgs for each in-flight or queued transaction.
                   2344: 
                   2345: =item INFO Connected to lond version:  <version> 
                   2346: 
                   2347: When connection negotiation is complete, the lond version is requested and logged here.
                   2348: 
                   2349: =item SUCCESS Connection n to host now ready for action
                   2350: 
                   2351: Emitted when connection has been completed with lond. n is then number of 
                   2352: concurrent connections and host, the host to which the connection has just
                   2353: been established.
                   2354: 
                   2355: =item WARNING Connection to host has been disconnected
                   2356: 
                   2357: Write to a lond resulted in failure status.  Connection to lond is dropped.
                   2358: 
                   2359: =item SUCCESS Created connection n to host host 
                   2360: 
                   2361: Initial connection request to host..(before negotiation).
                   2362: 
                   2363: =item CRITICAL Request Close Connection ... exiting
                   2364: 
                   2365: Client has sent "close_connection_exit"   The loncnew server is exiting.
                   2366: 
                   2367: =item INFO Resetting Connection Retries 
                   2368: 
                   2369: Client has sent "reset_retries" The lond connection retries are reset to zero for the
                   2370: corresponding lond.
                   2371: 
                   2372: =item SUCCESS Transaction <data>
                   2373: 
                   2374: Only emitted if the global variable $LogTransactions was set to true.
                   2375: A client has requested a lond transaction <data> is the contents of the request.
                   2376: 
                   2377: =item SUCCESS Toggled transaction logging <LogTransactions>
                   2378:                                     
                   2379: The state of the $LogTransactions global has been toggled, and its current value
                   2380: (after being toggled) is displayed.  When non zero additional logging of transactions
                   2381: is enabled for debugging purposes.  Transaction logging is toggled on receipt of a USR2
                   2382: signal.
                   2383: 
                   2384: =item CRITICAL Abnormal exit. Child <pid> for <host> died thorugh signal.
                   2385: 
                   2386: QUIT signal received.  lonc child process is exiting.
                   2387: 
                   2388: =item SUCCESS New debugging level for <RemoteHost> now <DebugLevel>
                   2389:                                     
                   2390: Debugging toggled for the host loncnew is talking with.
                   2391: Currently debugging is a level based scheme with higher number 
                   2392: conveying more information.  The daemon starts out at
                   2393: DebugLevel 0 and can toggle back and forth between that and
                   2394: DebugLevel 2  These are controlled by
                   2395: the global variables $DebugLevel and $NextDebugLevel
                   2396: The debug level can go up to 9.
                   2397: SIGINT toggles the debug level.  The higher the debug level the 
                   2398: more debugging information is spewed.  See the Debug
                   2399: sub in loncnew.
                   2400: 
                   2401: =item CRITICAL Forking server for host  
                   2402: 
                   2403: A child is being created to service requests for the specified host.
                   2404: 
                   2405: 
                   2406: =item WARNING Request for a second child on hostname
                   2407:                                     
                   2408: Somehow loncnew was asked to start a second child on a host that already had a child
                   2409: servicing it.  This request is not honored, but themessage is emitted.  This could happen
                   2410: due to a race condition.  When a client attempts to contact loncnew for a new host, a child
                   2411: is forked off to handle the requests for that server.  The parent then backs off the Unix
                   2412: domain socket leaving it for the child to service all requests.  If in the time between
                   2413: creating the child, and backing off, a new connection request comes in to the unix domain
                   2414: socket, this could trigger (unlikely but remotely possible),.
                   2415: 
                   2416: =item CRITICAL ------ Starting Children ----
                   2417: 
                   2418: This message should probably be changed to "Entering event loop"  as the loncnew only starts
                   2419: children as needed.  This message is emitted as new events are established and
                   2420: the event processing loop is entered.
                   2421: 
                   2422: =item INFO Updating connections via SIGUSR2
                   2423:                                     
                   2424: SIGUSR2 received. The original code would kill all clients, re-read the host file,
1.97    ! raeburn  2425: then restart children for each host.  Now that children are started on demand, this
1.88      foxr     2426: just kills all child processes and lets requests start them as needed again.
                   2427: 
                   2428: 
                   2429: =item CRITICAL Restarting
                   2430: 
                   2431: SigHUP received.  all the children are killed and the script exec's itself to start again.
                   2432: 
                   2433: =item CRITICAL Nicely killing lonc for host pid = <pid>
                   2434: 
                   2435: Attempting to kill the child that is serving the specified host (pid given) cleanly via
1.97    ! raeburn  2436: SIGQUIT.  The child should handle that, clean up nicely and exit.
1.88      foxr     2437: 
                   2438: =item CRITICAL Nastily killing lonc for host pid = <pid>
                   2439: 
                   2440: The child specified did not die when requested via SIGQUIT.  Therefore it is killed
                   2441: via SIGKILL.
                   2442: 
                   2443: =item CRITICAL Asked to kill children.. first be nice..
                   2444: 
                   2445: In the parent's INT handler.  INT kills the child processes.  This inidicate loncnew
                   2446: is about to attempt to kill all known children via SIGQUIT.  This message should be followed 
                   2447: by one "Nicely killing" message for each extant child.
                   2448: 
                   2449: =item CRITICAL Now kill children nasty 
                   2450: 
                   2451: In the parent's INT handler. remaining children are about to be killed via
                   2452: SIGKILL. Should be followed by a Nastily killing... for each lonc child that 
                   2453: refused to die.
                   2454: 
                   2455: =item CRITICAL Master process exiting
                   2456: 
                   2457: In the parent's INT handler. just prior to the exit 0 call.
                   2458: 
                   2459: =back
                   2460: 
                   2461: =cut

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