com.threerings.nio.conman
Class ConnectionManager

java.lang.Object
  extended by java.lang.Thread
      extended by com.samskivert.util.LoopingThread
          extended by com.threerings.nio.conman.ConnectionManager
All Implemented Interfaces:
Lifecycle.BaseComponent, Lifecycle.ShutdownComponent, Runnable
Direct Known Subclasses:
PolicyServer, PresentsConnectionManager

public abstract class ConnectionManager
extends LoopingThread
implements Lifecycle.ShutdownComponent

Manages socket connections. It creates connection objects for each socket connection, but those connection objects interact closely with the connection manager because network I/O is done via a poll()-like mechanism rather than via threads.

ConnectionManager doesn't directly accept TCP connections; it expects ServerSocketChannelAcceptor or an external entity to do so and call its handleAcceptedSocket(java.nio.channels.SocketChannel) method


Nested Class Summary
protected  class ConnectionManager.OverflowQueue
          Used to handle messages for a client whose network buffer has filled up because their outgoing network buffer has filled up.
protected static interface ConnectionManager.PartialWriteHandler
          Used to handle partial writes in writeMessage(com.threerings.nio.conman.Connection, byte[], com.threerings.nio.conman.ConnectionManager.PartialWriteHandler).
 
Nested classes/interfaces inherited from class java.lang.Thread
Thread.State, Thread.UncaughtExceptionHandler
 
Field Summary
protected  Queue<SocketChannel> _acceptedq
           
protected  IntMap<Connection> _connections
          Connections mapped by identifier.
protected  Queue<Connection> _deathq
           
protected  Map<SelectionKey,NetEventHandler> _handlers
          Maps selection keys to network event handlers.
protected  long _idleTime
           
protected  long _lastDebugStamp
          Used to periodically report connection manager activity when in debug mode.
protected  ConnectionManager.PartialWriteHandler _oflowHandler
          Used to create an overflow queue on the first partial write.
protected  Map<Connection,ConnectionManager.OverflowQueue> _oflowqs
           
protected  Runnable _onExit
          A runnable to execute when the connection manager thread exits.
protected  ByteBuffer _outbuf
           
protected  Queue<Tuple<Connection,byte[]>> _outq
           
protected  int _selectLoopTime
          Duration in milliseconds for which we wait for network events before checking our running flag to see if we should still be running.
protected  Selector _selector
           
protected  SelectorIterable _selectorSelector
           
protected  ConMgrStats _stats
          Our current runtime stats.
protected static byte[] ASYNC_CLOSE_REQUEST
          Used to denote asynchronous close requests.
protected static boolean DEBUG_REPORT
          Whether or not debug reporting is activated .
protected static long DEBUG_REPORT_INTERVAL
          Report our activity every 30 seconds.
protected static long LATENCY_GRACE
          The number of milliseconds beyond the ping interval that we allow a client's network connection to be idle before we forcibly disconnect them.
 
Fields inherited from class com.samskivert.util.LoopingThread
_running
 
Fields inherited from class java.lang.Thread
MAX_PRIORITY, MIN_PRIORITY, NORM_PRIORITY
 
Constructor Summary
ConnectionManager(Lifecycle cycle, long idleTime)
          Creates a connection manager instance.
 
Method Summary
 void closeConnection(Connection conn)
          Queues a connection up to be closed on the conmgr thread.
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  void didShutdown()
           
 ConMgrStats getStats()
          Returns our current runtime statistics.
protected abstract  void handleAcceptedSocket(SocketChannel channel)
          Adds a connection for the given socket to the managed set.
protected  void handleAcceptedSocket(SocketChannel channel, Connection conn)
           
protected  void handleIncoming(long iterStamp)
           
protected  void handleIterateFailure(Exception e)
           
protected  void iterate()
           
protected  void noteWrite(int msgs, int bytes)
          Called by writeMessage(com.threerings.nio.conman.Connection, byte[], com.threerings.nio.conman.ConnectionManager.PartialWriteHandler) and friends when they write data over the network.
protected  void postAsyncClose(Connection conn)
          Posts a fake message to this connection's outgoing message queue that will cause the connection to be closed when this message is reached.
protected  void processIncomingEvents(long iterStamp)
          Checks for any network events on our set of sockets and passes those events down to their associated NetEventHandlers for processing.
 SelectionKey register(SelectableChannel chan, int ops, NetEventHandler netEventHandler)
          Registers ops on chan on this manager's selector and hooks netEventHandler up to receive events whenever the selection occurs.
protected  void sendOutgoingMessages(long iterStamp)
          Writes all queued overflow and normal messages to their respective sockets.
 void setShutdownAction(Runnable onExit)
          Instructs us to execute the specified runnable when the connection manager thread exits.
 void transferAcceptedSocket(SocketChannel channel)
          Introduces a new active socket into Presents from off the ConnectionManager thread.
protected  void willStart()
           
protected  boolean writeMessage(Connection conn, byte[] data, ConnectionManager.PartialWriteHandler pwh)
          Writes a message out to a connection, passing the buck to the partial write handler if the entire message could not be written.
 
Methods inherited from class com.samskivert.util.LoopingThread
isRunning, 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

_oflowHandler

protected ConnectionManager.PartialWriteHandler _oflowHandler
Used to create an overflow queue on the first partial write.


_selector

protected Selector _selector

_selectorSelector

protected SelectorIterable _selectorSelector

_handlers

protected Map<SelectionKey,NetEventHandler> _handlers
Maps selection keys to network event handlers.


_connections

protected IntMap<Connection> _connections
Connections mapped by identifier.


_deathq

protected Queue<Connection> _deathq

_acceptedq

protected Queue<SocketChannel> _acceptedq

_outq

protected Queue<Tuple<Connection,byte[]>> _outq

_outbuf

protected ByteBuffer _outbuf

_oflowqs

protected Map<Connection,ConnectionManager.OverflowQueue> _oflowqs

_stats

protected ConMgrStats _stats
Our current runtime stats.


_lastDebugStamp

protected long _lastDebugStamp
Used to periodically report connection manager activity when in debug mode.


_onExit

protected volatile Runnable _onExit
A runnable to execute when the connection manager thread exits.


_selectLoopTime

@Inject(optional=true)
protected int _selectLoopTime
Duration in milliseconds for which we wait for network events before checking our running flag to see if we should still be running. We don't want to loop too tightly, but we need to make sure we don't sit around listening for incoming network events too long when there are outgoing messages in the queue.


_idleTime

protected final long _idleTime

ASYNC_CLOSE_REQUEST

protected static final byte[] ASYNC_CLOSE_REQUEST
Used to denote asynchronous close requests.


DEBUG_REPORT

protected static final boolean DEBUG_REPORT
Whether or not debug reporting is activated .

See Also:
Constant Field Values

DEBUG_REPORT_INTERVAL

protected static final long DEBUG_REPORT_INTERVAL
Report our activity every 30 seconds.

See Also:
Constant Field Values

LATENCY_GRACE

protected static final long LATENCY_GRACE
The number of milliseconds beyond the ping interval that we allow a client's network connection to be idle before we forcibly disconnect them.

See Also:
Constant Field Values
Constructor Detail

ConnectionManager

public ConnectionManager(Lifecycle cycle,
                         long idleTime)
                  throws IOException
Creates a connection manager instance.

Throws:
IOException
Method Detail

setShutdownAction

public void setShutdownAction(Runnable onExit)
Instructs us to execute the specified runnable when the connection manager thread exits. Note: this will be executed on the connection manager thread, so don't do anything dangerous. Only one action may be specified and it may be cleared by calling this method with null.


getStats

public ConMgrStats getStats()
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.


register

public SelectionKey register(SelectableChannel chan,
                             int ops,
                             NetEventHandler netEventHandler)
                      throws IOException
Registers ops on chan on this manager's selector and hooks netEventHandler up to receive events whenever the selection occurs.

Throws:
IOException

transferAcceptedSocket

public void transferAcceptedSocket(SocketChannel channel)
Introduces a new active socket into Presents from off the ConnectionManager thread. If Presents is embedded in another framework that handles socket acceptance, this will be called by its socket acceptor to get the socket into Presents to start authorization.


closeConnection

public void closeConnection(Connection conn)
Queues a connection up to be closed on the conmgr thread.


willStart

protected void willStart()
Overrides:
willStart in class LoopingThread

iterate

protected void iterate()
Overrides:
iterate in class LoopingThread

handleIncoming

protected void handleIncoming(long iterStamp)

handleAcceptedSocket

protected abstract void handleAcceptedSocket(SocketChannel channel)
Adds a connection for the given socket to the managed set.


handleAcceptedSocket

protected void handleAcceptedSocket(SocketChannel channel,
                                    Connection conn)

processIncomingEvents

protected void processIncomingEvents(long iterStamp)
Checks for any network events on our set of sockets and passes those events down to their associated NetEventHandlers for processing.


sendOutgoingMessages

protected void sendOutgoingMessages(long iterStamp)
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.


writeMessage

protected boolean writeMessage(Connection conn,
                               byte[] data,
                               ConnectionManager.PartialWriteHandler pwh)
Writes a message out to a connection, passing the buck to the partial write handler if the entire message could not be written.

Returns:
true if the message was fully written, false if it was partially written (in which case the partial message handler will have been invoked).

noteWrite

protected void noteWrite(int msgs,
                         int bytes)
Called by writeMessage(com.threerings.nio.conman.Connection, byte[], com.threerings.nio.conman.ConnectionManager.PartialWriteHandler) and friends when they write data over the network.


postAsyncClose

protected void postAsyncClose(Connection conn)
Posts a fake message to this connection's outgoing message queue that will cause the connection to be closed when this message is reached. This is only used by outgoing connections to ensure that they finish sending their queued outgoing messages before closing their connection. Incoming connections tend only to be closed at the request of the client or in case of delinquincy. In neither circumstance do we need to flush the client's outgoing queue before closing.


connectionFailed

protected void connectionFailed(Connection conn,
                                IOException ioe)
Called by a connection if it experiences a network failure.


connectionClosed

protected void connectionClosed(Connection conn)
Called by a connection when it discovers that it's closed.


handleIterateFailure

protected void handleIterateFailure(Exception e)
Overrides:
handleIterateFailure in class LoopingThread

didShutdown

protected void didShutdown()
Overrides:
didShutdown in class LoopingThread