#!/usr/bin/perl # # new lonc handles n requestors spread out bver m connections to londs. # This module is based on the Event class. # Development iterations: # - Setup basic event loop. (done) # - Add timer dispatch. (done) # - Add ability to accept lonc UNIX domain sockets. (done) # - Add ability to create/negotiate lond connections (done). # - Add general logic for dispatching requests and timeouts. # - Add support for the lonc/lond requests. # - Add logging/status monitoring. # - Add Signal handling - HUP restarts. USR1 status report. # - Add Configuration file I/O # - Add Pending request processing on startup. # - Add management/status request interface. use lib "/home/httpd/lib/perl/"; use lib "/home/foxr/newloncapa/types"; use Event qw(:DEFAULT ); use POSIX qw(:signal_h); use IO::Socket; use IO::Socket::INET; use IO::Socket::UNIX; use Socket; use Crypt::IDEA; use LONCAPA::Queue; use LONCAPA::Stack; use LONCAPA::LondConnection; use LONCAPA::Configuration; use LONCAPA::HashIterator; print "Loncnew starting\n"; # # Disable all signals we might receive from outside for now. # $SIG{QUIT} = IGNORE; $SIG{HUP} = IGNORE; $SIG{USR1} = IGNORE; $SIG{INT} = IGNORE; $SIG{CHLD} = IGNORE; $SIG{__DIE__} = IGNORE; # Read the httpd configuration file to get perl variables # normally set in apache modules: my $perlvarref = LONCAPA::Configuration::read_conf('loncapa.conf'); my %perlvar = %{$perlvarref}; # # parent and shared variables. my %ChildHash; # by pid -> host. my $MaxConnectionCount = 5; # Will get from config later. my $ClientConnection = 0; # Uniquifier for client events. my $DebugLevel = 5; my $IdleTimeout= 3600; # Wait an hour before pruning connections. # # The variables below are only used by the child processes. # my $RemoteHost; # Name of host child is talking to. my $UnixSocketDir= "/home/httpd/sockets"; my $IdleConnections = Stack->new(); # Set of idle connections my %ActiveConnections; # Connections to the remote lond. my %ActiveTransactions; # Transactions in flight. my %ActiveClients; # Serial numbers of active clients by socket. my $WorkQueue = Queue->new(); # Queue of pending transactions. my $ClientQueue = Queue->new(); # Queue of clients causing xactinos. my $ConnectionCount = 0; # =pod =head 2 GetPeerName Returns the name of the host that a socket object is connected to. =cut sub GetPeername { my $connection = shift; my $AdrFamily = shift; my $peer = $connection->peername(); my $peerport; my $peerip; if($AdrFamily == AF_INET) { ($peerport, $peerip) = sockaddr_in($peer); my $peername = gethostbyaddr($iaddr, $AdrFamily); return $peername; } elsif ($AdrFamily == AF_UNIX) { my $peerfile; ($peerfile) = sockaddr_un($peer); return $peerfile; } } #----------------------------- Timer management ------------------------ =pod =head2 Debug Invoked to issue a debug message. =cut sub Debug { my $level = shift; my $message = shift; if ($level <= $DebugLevel) { print $message." host = ".$RemoteHost."\n"; } } sub SocketDump { my $level = shift; my $socket= shift; if($level <= $DebugLevel) { $socket->Dump(); } } =pod =head2 Tick Invoked each timer tick. =cut sub Tick { my $client; Debug(6, "Tick"); Debug(6, " Current connection count: ".$ConnectionCount); foreach $client (keys %ActiveClients) { Debug(7, " Have client: with id: ".$ActiveClients{$client}); } } =pod =head2 SetupTimer Sets up a 1 per sec recurring timer event. The event handler is used to: =item Trigger timeouts on communications along active sockets. =item Trigger disconnections of idle sockets. =cut sub SetupTimer { Debug(6, "SetupTimer"); Event->timer(interval => 1, debug => 1, cb => \&Tick ); } =pod =head2 ServerToIdle This function is called when a connection to the server is ready for more work. If there is work in the Work queue the top element is dequeued and the connection will start to work on it. If the work queue is empty, the connection is pushed on the idle connection stack where it will either get another work unit, or alternatively, if it sits there long enough, it will be shut down and released. =cut sub ServerToIdle { my $Socket = shift; # Get the socket. &Debug(6, "Server to idle"); # If there's work to do, start the transaction: $reqdata = $WorkQueue->dequeue(); Debug(9, "Queue gave request data: ".$reqdata); unless($reqdata eq undef) { my $unixSocket = $ClientQueue->dequeue(); &Debug(6, "Starting new work request"); &Debug(7, "Request: ".$reqdata); &StartRequest($Socket, $unixSocket, $reqdata); } else { # There's no work waiting, so push the server to idle list. &Debug(8, "No new work requests, server connection going idle"); delete($ActiveTransactions{$Socket}); $IdleConnections->push($Socket); } } =pod =head2 ClientWritable Event callback for when a client socket is writable. This callback is established when a transaction reponse is avaiable from lond. The response is forwarded to the unix socket as it becomes writable in this sub. Parameters: =item Event - The event that has been triggered. Event->w->data is the data and Event->w->fd is the socket to write. =cut sub ClientWritable { my $Event = shift; my $Watcher = $Event->w; my $Data = $Watcher->data; my $Socket = $Watcher->fd; # Try to send the data: &Debug(6, "ClientWritable writing".$Data); &Debug(9, "Socket is: ".$Socket); my $result = $Socket->send($Data, 0); # $result undefined: the write failed. # otherwise $result is the number of bytes written. # Remove that preceding string from the data. # If the resulting data is empty, destroy the watcher # and set up a read event handler to accept the next # request. &Debug(9,"Send result is ".$result." Defined: ".defined($result)); if(defined($result)) { &Debug(9, "send result was defined"); if($result == length($Data)) { # Entire string sent. &Debug(9, "ClientWritable data all written"); $Watcher->cancel(); # # Set up to read next request from socket: my $descr = sprintf("Connection to lonc client %d", $ActiveClients{$Socket}); Event->io(cb => \&ClientRequest, poll => 'r', desc => $descr, data => "", fd => $Socket); } else { # Partial string sent. $Watcher->data(substr($Data, $result)); } } else { # Error of some sort... # Some errnos are possible: my $errno = $!; if($errno == POSIX::EWOULDBLOCK || $errno == POSIX::EAGAIN || $errno == POSIX::EINTR) { # No action taken? } else { # Unanticipated errno. &Debug(5,"ClientWritable error or peer shutdown".$RemoteHost); $Watcher->cancel; # Stop the watcher. $Socket->shutdown(2); # Kill connection $Socket->close(); # Close the socket. } } } =pod =head2 CompleteTransaction Called when the reply data has been received for a lond transaction. The reply data must now be sent to the ultimate client on the other end of the Unix socket. This is done by setting up a writable event for the socket with the data the reply data. Parameters: =item Socket - Socket on which the lond transaction occured. This is a LondConnection. The data received is in the TransactionReply member. =item Client - Unix domain socket open on the ultimate client. =cut sub CompleteTransaction { &Debug(6,"Complete transaction"); my $Socket = shift; my $Client = shift; my $data = $Socket->GetReply(); # Data to send. &Debug(8," Reply was: ".$data); my $Serial = $ActiveClients{$Client}; my $desc = sprintf("Connection to lonc client %d", $Serial); Event->io(fd => $Client, poll => "w", desc => $desc, cb => \&ClientWritable, data => $data); } =pod =head2 LondReadable This function is called whenever a lond connection is readable. The action is state dependent: =head3 State = Initialized We''re waiting for the challenge, this is a no-op until the state changes. =head3 State=Challenged The challenge has arrived we need to transition to Writable. The connection must echo the challenge back. =head3 State=ChallengeReplied The challenge has been replied to. The we are receiveing the 'ok' from the partner. =head3 State=RequestingKey The ok has been received and we need to send the request for an encryption key. Transition to writable for that. =head3 State=ReceivingKey The the key has been requested, now we are reading the new key. =head3 State=Idle The encryption key has been negotiated or we have finished reading data from the a transaction. If the callback data has a client as well as the socket iformation, then we are doing a transaction and the data received is relayed to the client before the socket is put on the idle list. =head3 State=SendingRequest I do not think this state can be received here, but if it is, the appropriate thing to do is to transition to writable, and send the request. =head3 State=ReceivingReply We finished sending the request to the server and now transition to readable to receive the reply. The parameter to this function are: The event. Implicit in this is the watcher and its data. The data contains at least the lond connection object and, if a transaction is in progress, the socket attached to the local client. =cut sub LondReadable { my $Event = shift; my $Watcher = $Event->w; my $Socket = $Watcher->data; my $client = undef; my $State = $Socket->GetState(); # All action depends on the state. &Debug(6,"LondReadable called state = ".$State); SocketDump(6, $Socket); if($Socket->Readable() != 0) { # bad return from socket read. } SocketDump(6,$Socket); $State = $Socket->GetState(); # Update in case of transition. &Debug(6, "After read, state is ".$State); if($State eq "Initialized") { } elsif ($State eq "ChallengeReceived") { # The challenge must be echoed back; The state machine # in the connection takes care of setting that up. Just # need to transition to writable: $Watcher->poll("w"); $Watcher->cb(\&LondWritable); } elsif ($State eq "ChallengeReplied") { } elsif ($State eq "RequestingKey") { # The ok was received. Now we need to request the key # That requires us to be writable: $Watcher->poll("w"); $Watcher->cb(\&LondWritable); } elsif ($State eq "ReceivingKey") { } elsif ($State eq "Idle") { # If necessary, complete a transaction and then go into the # idle queue. if(exists($ActiveTransactions{$Socket})) { Debug(8,"Completing transaction!!"); CompleteTransaction($Socket, $ActiveTransactions{$Socket}); } $Watcher->cancel(); ServerToIdle($Socket); # Next work unit or idle. } elsif ($State eq "SendingRequest") { # We need to be writable for this and probably don't belong # here inthe first place. Deubg(6, "SendingRequest state encountered in readable"); $Watcher->poll("w"); $Watcher->cb(\&LondWritable); } elsif ($State eq "ReceivingReply") { } else { # Invalid state. Debug(4, "Invalid state in LondReadable"); } } =pod =head2 LondWritable This function is called whenever a lond connection becomes writable while there is a writeable monitoring event. The action taken is very state dependent: =head3 State = Connected The connection is in the process of sending the 'init' hailing to the lond on the remote end. The connection object''s Writable member is called. On error, ConnectionError is called to destroy the connection and remove it from the ActiveConnections hash =head3 Initialized 'init' has been sent, writability monitoring is removed and readability monitoring is started with LondReadable as the callback. =head3 ChallengeReceived The connection has received the who are you challenge from the remote system, and is in the process of sending the challenge response. Writable is called. =head3 ChallengeReplied The connection has replied to the initial challenge The we switch to monitoring readability looking for the server to reply with 'ok'. =head3 RequestingKey The connection is in the process of requesting its encryption key. Writable is called. =head3 ReceivingKey The connection has sent the request for a key. Switch to readability monitoring to accept the key =head3 SendingRequest The connection is in the process of sending a request to the server. This request is part of a client transaction. All the states until now represent the client setup protocol. Writable is called. =head3 ReceivingReply The connection has sent a request. Now it must receive a reply. Readability monitoring is requested. This function is an event handler and therefore receives as a parameter the event that has fired. The data for the watcher of this event is a reference to a list of one or two elements, depending on state. The first (and possibly only) element is the socket. The second (present only if a request is in progress) is the socket on which to return a reply to the caller. =cut sub LondWritable { my $Event = shift; my $Watcher = $Event->w; my @data = $Watcher->data; Debug(6,"LondWritable State = ".$State." data has ".@data." elts.\n"); my $Socket = $data[0]; # I know there's at least a socket. # Figure out what to do depending on the state of the socket: my $State = $Socket->GetState(); SocketDump(6,$Socket); if ($State eq "Connected") { # "init" is being sent... if ($Socket->Writable() != 0) { # The write resulted in an error. } } elsif ($State eq "Initialized") { # Now that init was sent, we switch # to watching for readability: $Watcher->poll("r"); $Watcher->cb(\&LondReadable); } elsif ($State eq "ChallengeReceived") { # We received the challenge, now we # are echoing it back. This is a no-op, # we're waiting for the state to change if($Socket->Writable() != 0) { # Write of the next chunk resulted in an error. } } elsif ($State eq "ChallengeReplied") { # The echo was sent back, so we switch # to watching readability. $Watcher->poll("r"); $Watcher->cb(\&LondReadable); } elsif ($State eq "RequestingKey") { # At this time we're requesting the key. # again, this is essentially a no-op. # we'll write the next chunk until the # state changes. if($Socket->Writable() != 0) { # Write resulted in an error. } } elsif ($State eq "ReceivingKey") { # Now we need to wait for the key # to come back from the peer: $Watcher->poll("r"); $Watcher->cb(\&LondReadable); } elsif ($State eq "SendingRequest") { # At this time we are sending a request to the # peer... write the next chunk: if($Socket->Writable() != 0) { # Write resulted in an error. } } elsif ($State eq "ReceivingReply") { # The send has completed. Wait for the # data to come in for a reply. Debug(8,"Writable sent request/receiving reply"); $Watcher->poll("r"); $Watcher->cb(\&LondReadable); } else { # Control only passes here on an error: # the socket state does not match any # of the known states... so an error # must be logged. &Debug(4, "Invalid socket state ".$State."\n"); } } =pod =head2 MakeLondConnection Create a new lond connection object, and start it towards its initial idleness. Once idle, it becomes elligible to receive transactions from the work queue. If the work queue is not empty when the connection is completed and becomes idle, it will dequeue an entry and start off on it. =cut sub MakeLondConnection { Debug(4,"MakeLondConnection to ".GetServerHost()." on port " .GetServerPort()); my $Connection = LondConnection->new(&GetServerHost(), &GetServerPort()); if($Connection == undef) { # Needs to be more robust later. die "Failed to make a connection!!".$!."\n"; } # The connection needs to have writability # monitored in order to send the init sequence # that starts the whole authentication/key # exchange underway. # my $Socket = $Connection->GetSocket(); if($Socket == undef) { die "did not get a socket from the connection"; } else { &Debug(9,"MakeLondConnection got socket: ".$Socket); } $event = Event->io(fd => $Socket, poll => 'w', cb => \&LondWritable, data => ($Connection, undef), desc => 'Connection to lond server'); $ActiveConnections{$Lond} = $event; $ConnectionCount++; } =pod =head2 StartRequest Starts a lond request going on a specified lond connection. parameters are: =item $Lond - Connection to the lond that will send the transaction and receive the reply. =item $Client - Connection to the client that is making this request We got the request from this socket, and when the request has been relayed to lond and we get a reply back from lond it will get sent to this socket. =item $Request - The text of the request to send. =cut sub StartRequest { my $Lond = shift; my $Client = shift; my $Request = shift; Debug(6, "StartRequest: ".$Request); my $Socket = $Lond->GetSocket(); $ActiveTransactions{$Lond} = $Client; # Socket to relay to client. $Lond->InitiateTransaction($Request); $event = Event->io(fd => $Lond->GetSocket(), poll => "w", cb => \&LondWritable, data => $Lond, desc => "lond transaction connection"); $ActiveConnections{$Lond} = $event; Debug(8," Start Request made watcher data with ".$event->data."\n"); } =pod =head2 QueueTransaction - If there is an idle lond connection, it is put to work doing this transaction. Otherwise, the transaction is placed in the work queue. If placed in the work queue and the maximum number of connections has not yet been created, a new connection will be started. Our goal is to eventually have a sufficient number of connections that the work queue will typically be empty. parameters are: =item Socket open on the lonc client. =item Request data to send to the lond. =cut sub QueueTransaction { my $requestSocket = shift; my $requestData = shift; Debug(6,"QueueTransaction: ".$requestData); my $LondSocket = $IdleConnections->pop(); if(!defined $LondSocket) { # Need to queue request. Debug(8,"Must queue..."); $ClientQueue->enqueue($requestSocket); $WorkQueue->enqueue($requestData); if($ConnectionCount < $MaxConnectionCount) { Debug(4,"Starting additional lond connection"); MakeLondConnection(); } } else { # Can start the request: Debug(8,"Can start..."); StartRequest($LondSocket, $requestSocket, $requestData); } } #-------------------------- Lonc UNIX socket handling --------------------- =pod =head2 ClientRequest Callback that is called when data can be read from the UNIX domain socket connecting us with an apache server process. =cut sub ClientRequest { Debug(6, "ClientRequest"); my $event = shift; my $watcher = $event->w; my $socket = $watcher->fd; my $data = $watcher->data; my $thisread; Debug(9, " Watcher named: ".$watcher->desc); my $rv = $socket->recv($thisread, POSIX::BUFSIZ, 0); Debug(8, "rcv: data length = ".length($thisread) ." read =".$thisread); unless (defined $rv && length($thisread)) { # Likely eof on socket. Debug(5,"Client Socket closed on lonc for ".$RemoteHost); close($socket); $watcher->cancel(); delete($ActiveClients{$socket}); } Debug(8,"Data: ".$data." this read: ".$thisread); $data = $data.$thisread; # Append new data. $watcher->data($data); if($data =~ /(.*\n)/) { # Request entirely read. Debug(8, "Complete transaction received: ".$data); QueueTransaction($socket, $data); $watcher->cancel(); # Done looking for input data. } } =pod =head2 NewClient Callback that is called when a connection is received on the unix socket for a new client of lonc. The callback is parameterized by the event.. which is a-priori assumed to be an io event, and therefore has an fd member that is the Listener socket. We Accept the connection and register a new event on the readability of that socket: =cut sub NewClient { Debug(6, "NewClient"); my $event = shift; # Get the event parameters. my $watcher = $event->w; my $socket = $watcher->fd; # Get the event' socket. my $connection = $socket->accept(); # Accept the client connection. Debug(8,"Connection request accepted from " .GetPeername($connection, AF_UNIX)); my $description = sprintf("Connection to lonc client %d", $ClientConnection); Debug(9, "Creating event named: ".$description); Event->io(cb => \&ClientRequest, poll => 'r', desc => $description, data => "", fd => $connection); $ActiveClients{$connection} = $ClientConnection; $ClientConnection++; } =pod GetLoncSocketPath Returns the name of the UNIX socket on which to listen for client connections. =cut sub GetLoncSocketPath { return $UnixSocketDir."/".GetServerHost(); } =pod GetServerHost Returns the host whose lond we talk with. =cut sub GetServerHost { # Stub - get this from config. return $RemoteHost; # Setup by the fork. } =pod GetServerPort Returns the lond port number. =cut sub GetServerPort { # Stub - get this from config. return $perlvar{londPort}; } =pod SetupLoncListener Setup a lonc listener event. The event is called when the socket becomes readable.. that corresponds to the receipt of a new connection. The event handler established will accept the connection (creating a communcations channel), that int turn will establish another event handler to subess requests. =cut sub SetupLoncListener { my $socket; my $SocketName = GetLoncSocketPath(); unlink($SocketName); unless ($socket = IO::Socket::UNIX->new(Local => $SocketName, Listen => 10, Type => SOCK_STREAM)) { die "Failed to create a lonc listner socket"; } Event->io(cb => \&NewClient, poll => 'r', desc => 'Lonc listener Unix Socket', fd => $socket); } =pod =head2 ChildProcess This sub implements a child process for a single lonc daemon. =cut sub ChildProcess { print "Loncnew\n"; # For now turn off signals. $SIG{QUIT} = IGNORE; $SIG{HUP} = IGNORE; $SIG{USR1} = IGNORE; $SIG{INT} = IGNORE; $SIG{CHLD} = IGNORE; $SIG{__DIE__} = IGNORE; SetupTimer(); SetupLoncListener(); $Event::Debuglevel = $DebugLevel; Debug(9, "Making initial lond connection for ".$RemoteHost); # Setup the initial server connection: &MakeLondConnection(); Debug(9,"Entering event loop"); my $ret = Event::loop(); # Start the main event loop. die "Main event loop exited!!!"; } # Create a new child for host passed in: sub CreateChild { my $host = shift; $RemoteHost = $host; Debug(3, "Forking off child for ".$RemoteHost); sleep(5); $pid = fork; if($pid) { # Parent $ChildHash{$pid} = $RemoteHost; } else { # child. ChildProcess; } } # # Parent process logic pass 1: # For each entry in the hosts table, we will # fork off an instance of ChildProcess to service the transactions # to that host. Each pid will be entered in a global hash # with the value of the key, the host. # The parent will then enter a loop to wait for process exits. # Each exit gets logged and the child gets restarted. # my $HostIterator = LondConnection::GetHostIterator; while (! $HostIterator->end()) { $hostentryref = $HostIterator->get(); CreateChild($hostentryref->[0]); $HostIterator->next(); } # Maintain the population: while(1) { $deadchild = wait(); if(exists $ChildHash{$deadchild}) { # need to restart. $deadhost = $ChildHash{$deadchild}; delete($ChildHash{$deadchild}); Debug(4,"Lost child pid= ".$deadchild. "Connected to host ".$deadhost); CreateChild($deadhost); } } =head1 Theory The event class is used to build this as a single process with an event driven model. The following events are handled: =item UNIX Socket connection Received =item Request data arrives on UNIX data transfer socket. =item lond connection becomes writable. =item timer fires at 1 second intervals. All sockets are run in non-blocking mode. Timeouts managed by the timer handler prevents hung connections. Key data structures: =item RequestQueue - A queue of requests received from UNIX sockets that are waiting for a chance to be forwarded on a lond connection socket. =item ActiveConnections - A hash of lond connections that have transactions in process that are available to be timed out. =item ActiveTransactions - A hash indexed by lond connections that contain the client reply socket for each connection that has an active transaction on it. =item IdleConnections - A hash of lond connections that have no work to do. These connections can be closed if they are idle for a long enough time. =cut