com.threerings.presents.server.net
Class PresentsConnectionManager

java.lang.Object
  extended by java.lang.Thread
      extended by com.samskivert.util.LoopingThread
          extended by com.threerings.nio.conman.ConnectionManager
              extended by com.threerings.presents.server.net.PresentsConnectionManager
All Implemented Interfaces:
Lifecycle.BaseComponent, Lifecycle.ShutdownComponent, ReportManager.Reporter, Runnable

public class PresentsConnectionManager
extends ConnectionManager
implements ReportManager.Reporter


Nested Class Summary
 
Nested classes/interfaces inherited from class com.threerings.nio.conman.ConnectionManager
ConnectionManager.OverflowQueue, ConnectionManager.PartialWriteHandler
 
Nested classes/interfaces inherited from class java.lang.Thread
Thread.State, Thread.UncaughtExceptionHandler
 
Field Summary
protected  Invoker _authInvoker
           
protected  Authenticator _author
          Handles client authentication.
protected  List<ChainedAuthenticator> _authors
           
protected  Queue<AuthingConnection> _authq
           
protected  ClientManager _clmgr
           
protected  Queue<Tuple<Connection,InetSocketAddress>> _connectq
           
protected  ByteBuffer _databuf
           
protected  Queue<Tuple<PresentsConnection,byte[]>> _dataq
           
protected  ByteArrayOutputStream _flattener
           
protected  FramingOutputStream _framer
           
protected  PresentsConMgrStats _lastStats
          A snapshot of our runtime stats as of our last report.
protected  PresentsDObjectMgr _omgr
           
protected  PrivateKey _privateKey
           
 
Fields inherited from class com.threerings.nio.conman.ConnectionManager
_acceptedq, _connections, _deathq, _handlers, _idleTime, _lastDebugStamp, _oflowHandler, _oflowqs, _onExit, _outbuf, _outq, _selectLoopTime, _selector, _selectorSelector, _stats, ASYNC_CLOSE_REQUEST, DEBUG_REPORT, DEBUG_REPORT_INTERVAL, LATENCY_GRACE
 
Fields inherited from class com.samskivert.util.LoopingThread
_running
 
Fields inherited from class java.lang.Thread
MAX_PRIORITY, MIN_PRIORITY, NORM_PRIORITY
 
Constructor Summary
PresentsConnectionManager(Lifecycle cycle, ReportManager repmgr)
           
 
Method Summary
 void addChainedAuthenticator(ChainedAuthenticator author)
          Adds an authenticator to the authentication chain.
 void appendReport(StringBuilder report, long now, long sinceLast, boolean reset)
          Requests that this reporter append its report to the supplied string buffer.
protected  void authenticateConnection(AuthingConnection conn)
          Performs the authentication process on the specified connection.
protected  void connectionClosed(Connection conn)
          Called by a connection when it discovers that it's closed.
protected  void connectionFailed(Connection conn, IOException ioe)
          Called by a connection if it experiences a network failure.
protected  DatagramSequencer createDatagramSequencer()
          Creates a datagram sequencer for use by a Connection.
 PrivateKey getPrivateKey()
          Returns the private key used in secure authentication.
 PresentsConMgrStats getStats()
          Returns our current runtime statistics.
protected  void handleAcceptedSocket(SocketChannel channel)
          Starts an accepted socket down the path to authorization.
protected  int handleDatagram(DatagramChannel listener, long when)
          Called when a datagram message is ready to be read off its channel.
protected  void handleIncoming(long iterStamp)
           
 boolean isRunning()
           
 void openOutgoingConnection(Connection conn, String hostname, int port)
          Opens an outgoing connection to the supplied address.
protected  boolean postDatagram(PresentsConnection conn, Message msg)
          Helper function for postMessage(com.threerings.presents.server.net.PresentsConnection, com.threerings.presents.net.Message); handles posting the message as a datagram.
protected  void postMessage(PresentsConnection conn, Message msg)
          Called by a connection when it has a downstream message that needs to be delivered.
protected  void processAuthedConnections(long iterStamp)
          Converts connections that have completed the authentication process into full running connections and notifies the client manager that new connections have been established.
protected  void sendOutgoingMessages(long iterStamp)
          Writes all queued overflow and normal messages to their respective sockets.
 boolean setPrivateKey(PrivateKey key)
          Sets the private key if the ciphers are supported.
 boolean setPrivateKey(String key)
          Sets the private key if the ciphers are supported.
protected  void startOutgoingConnection(Connection conn, InetSocketAddress addr)
          Starts the connection process for an outgoing connection.
protected  boolean writeDatagram(PresentsConnection conn, byte[] data)
          Sends a datagram to the specified connection.
 
Methods inherited from class com.threerings.nio.conman.ConnectionManager
closeConnection, didShutdown, handleAcceptedSocket, handleIterateFailure, iterate, noteWrite, postAsyncClose, processIncomingEvents, register, setShutdownAction, transferAcceptedSocket, willStart, writeMessage
 
Methods inherited from class com.samskivert.util.LoopingThread
kick, run, shutdown
 
Methods inherited from class java.lang.Thread
activeCount, checkAccess, countStackFrames, currentThread, destroy, dumpStack, enumerate, getAllStackTraces, getContextClassLoader, getDefaultUncaughtExceptionHandler, getId, getName, getPriority, getStackTrace, getState, getThreadGroup, getUncaughtExceptionHandler, holdsLock, interrupt, interrupted, isAlive, isDaemon, isInterrupted, join, join, join, resume, setContextClassLoader, setDaemon, setDefaultUncaughtExceptionHandler, setName, setPriority, setUncaughtExceptionHandler, sleep, sleep, start, stop, stop, suspend, toString, yield
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface com.samskivert.util.Lifecycle.ShutdownComponent
shutdown
 

Field Detail

_author

@Inject(optional=true)
protected Authenticator _author
Handles client authentication. The base authenticator is injected but optional services like the PeerManager may replace this authenticator with one that intercepts certain types of authentication and then passes normal authentications through.


_authors

protected List<ChainedAuthenticator> _authors

_privateKey

protected PrivateKey _privateKey

_authq

protected Queue<AuthingConnection> _authq

_connectq

protected Queue<Tuple<Connection,InetSocketAddress>> _connectq

_framer

protected FramingOutputStream _framer

_flattener

protected ByteArrayOutputStream _flattener

_authInvoker

@Inject
protected Invoker _authInvoker

_clmgr

@Inject
protected ClientManager _clmgr

_omgr

@Inject
protected PresentsDObjectMgr _omgr

_lastStats

protected PresentsConMgrStats _lastStats
A snapshot of our runtime stats as of our last report.


_dataq

protected Queue<Tuple<PresentsConnection,byte[]>> _dataq

_databuf

protected ByteBuffer _databuf
Constructor Detail

PresentsConnectionManager

@Inject
public PresentsConnectionManager(Lifecycle cycle,
                                        ReportManager repmgr)
                          throws IOException
Throws:
IOException
Method Detail

getStats

public PresentsConMgrStats getStats()
Description copied from class: ConnectionManager
Returns our current runtime statistics. Note: don't call this method too frequently as it is synchronized and will contend with the network I/O thread.

Overrides:
getStats in class ConnectionManager

appendReport

public void appendReport(StringBuilder report,
                         long now,
                         long sinceLast,
                         boolean reset)
Description copied from interface: ReportManager.Reporter
Requests that this reporter append its report to the supplied string buffer.

Specified by:
appendReport in interface ReportManager.Reporter
Parameters:
report - the string buffer to which the report text should be appended.
now - the time at which the report generation began, in epoch millis.
sinceLast - number of milliseconds since the last time we generated a report.
reset - if true, all accumulating stats should be reset, if false they should be allowed to continue to accumulate.

addChainedAuthenticator

public void addChainedAuthenticator(ChainedAuthenticator author)
Adds an authenticator to the authentication chain. This authenticator will be offered a chance to authenticate incoming connections before falling back to the main authenticator.


setPrivateKey

public boolean setPrivateKey(PrivateKey key)
Sets the private key if the ciphers are supported.

Returns:
true if the key is set

setPrivateKey

public boolean setPrivateKey(String key)
Sets the private key if the ciphers are supported.

Returns:
true if the key is set

getPrivateKey

public PrivateKey getPrivateKey()
Returns the private key used in secure authentication.


handleDatagram

protected int handleDatagram(DatagramChannel listener,
                             long when)
Called when a datagram message is ready to be read off its channel.


postMessage

protected void postMessage(PresentsConnection conn,
                           Message msg)
Called by a connection when it has a downstream message that needs to be delivered. Note: this method is called as a result of a call to PresentsConnection.postMessage(com.threerings.presents.net.Message) which happens when forwarding an event to a client and at the completion of authentication, both of which must happen only on the distributed object thread.


postDatagram

protected boolean postDatagram(PresentsConnection conn,
                               Message msg)
                        throws Exception
Helper function for postMessage(com.threerings.presents.server.net.PresentsConnection, com.threerings.presents.net.Message); handles posting the message as a datagram.

Returns:
true if the datagram was successfully posted, false if it was too big.
Throws:
Exception

createDatagramSequencer

protected DatagramSequencer createDatagramSequencer()
Creates a datagram sequencer for use by a Connection.


openOutgoingConnection

public void openOutgoingConnection(Connection conn,
                                   String hostname,
                                   int port)
                            throws IOException
Opens an outgoing connection to the supplied address. The connection will be opened in a non-blocking manner and added to the connection manager's select set. Messages posted to the connection prior to it being actually connected to its destination will remain in the queue. If the connection fails those messages will be dropped.

Parameters:
conn - the connection to be initialized and opened. Callers may want to provide a Connection derived class so that they may intercept calldown methods.
hostname - the hostname of the server to which to connect.
port - the port on which to connect to the server.
Throws:
IOException - thrown if an error occurs creating our socket. Everything else happens asynchronously. If the connection attempt fails, the Connection will be notified via Connection.networkFailure(java.io.IOException).

startOutgoingConnection

protected void startOutgoingConnection(Connection conn,
                                       InetSocketAddress addr)
Starts the connection process for an outgoing connection. This is called as part of the conmgr tick for any pending outgoing connections.


isRunning

public boolean isRunning()
Overrides:
isRunning in class LoopingThread

handleIncoming

protected void handleIncoming(long iterStamp)
Overrides:
handleIncoming in class ConnectionManager

connectionFailed

protected void connectionFailed(Connection conn,
                                IOException ioe)
Description copied from class: ConnectionManager
Called by a connection if it experiences a network failure.

Overrides:
connectionFailed in class ConnectionManager

connectionClosed

protected void connectionClosed(Connection conn)
Description copied from class: ConnectionManager
Called by a connection when it discovers that it's closed.

Overrides:
connectionClosed in class ConnectionManager

authenticateConnection

protected void authenticateConnection(AuthingConnection conn)
Performs the authentication process on the specified connection. This is called by AuthingConnection itself once it receives its auth request.


handleAcceptedSocket

protected void handleAcceptedSocket(SocketChannel channel)
Starts an accepted socket down the path to authorization.

Specified by:
handleAcceptedSocket in class ConnectionManager

processAuthedConnections

protected void processAuthedConnections(long iterStamp)
Converts connections that have completed the authentication process into full running connections and notifies the client manager that new connections have been established.


sendOutgoingMessages

protected void sendOutgoingMessages(long iterStamp)
Description copied from class: ConnectionManager
Writes all queued overflow and normal messages to their respective sockets. Connections that already have established overflow queues will have their messages appended to their overflow queue instead so that they are delivered in the proper order.

Overrides:
sendOutgoingMessages in class ConnectionManager

writeDatagram

protected boolean writeDatagram(PresentsConnection conn,
                                byte[] data)
Sends a datagram to the specified connection.

Returns:
true if the datagram was sent, false if we failed to send for any reason.