Annotation of loncom/loncnew, revision 1.106

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

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