Apache Tomcat 6.0.53

org.apache.catalina.ha.session
Class SimpleTcpReplicationManager

java.lang.Object
  extended by org.apache.catalina.session.ManagerBase
      extended by org.apache.catalina.session.StandardManager
          extended by org.apache.catalina.ha.session.SimpleTcpReplicationManager
All Implemented Interfaces:
java.beans.PropertyChangeListener, java.util.EventListener, javax.management.MBeanRegistration, ClusterManager, Lifecycle, Manager

public class SimpleTcpReplicationManager
extends StandardManager
implements ClusterManager

Title: Tomcat Session Replication for Tomcat 4.0
Description: A very simple straight forward implementation of session replication of servers in a cluster.
This session replication is implemented "live". By live I mean, when a session attribute is added into a session on Node A a message is broadcasted to other messages and setAttribute is called on the replicated sessions.
A full description of this implementation can be found under Filip's Tomcat Page
Copyright: See apache license
Company: www.filip.net
Description: The InMemoryReplicationManager is a session manager that replicated session information in memory.

The InMemoryReplicationManager extends the StandardManager hence it allows for us to inherit all the basic session management features like expiration, session listeners etc

To communicate with other nodes in the cluster, the InMemoryReplicationManager sends out 7 different type of multicast messages all defined in the SessionMessage class.
When a session is replicated (not an attribute added/removed) the session is serialized into a byte array using the StandardSession.readObjectData, StandardSession.writeObjectData methods.

Version:
1.0 for TC 4.0
Author:
Filip Hanik, Bela Ban (modifications for synchronous replication)

Nested Class Summary
 
Nested classes/interfaces inherited from class org.apache.catalina.session.ManagerBase
ManagerBase.SessionTiming
 
Field Summary
protected  CatalinaCluster cluster
           
protected  boolean defaultMode
           
protected  boolean distributable
           
protected  java.util.HashMap invalidatedSessions
           
static Log log
           
protected  java.lang.String mChannelConfig
           
protected  boolean mChannelStarted
           
protected  boolean mExpireSessionsOnShutdown
          Set to true if we don't want the sessions to expire on shutdown
protected  java.lang.String mGroupName
           
protected  boolean mManagerRunning
           
protected  boolean mPrintToScreen
           
protected  java.lang.String name
           
protected  boolean stateTransferred
          Flag to keep track if the state has been transferred or not Assumes false.
protected  boolean synchronousReplication
          Use synchronous rather than asynchronous replication.
protected  boolean useDirtyFlag
           
 
Fields inherited from class org.apache.catalina.session.StandardManager
info, lifecycle, maxActiveSessions, pathname, processingTime, rejectedSessions, started
 
Fields inherited from class org.apache.catalina.session.ManagerBase
algorithm, container, DEFAULT_ALGORITHM, devRandomSource, digest, domain, duplicates, entropy, expiredSessions, initialized, maxActive, maxInactiveInterval, mserver, oname, processExpiresFrequency, random, randomClass, randomIS, sessionAverageAliveTime, sessionCounter, sessionCreationTiming, sessionExpirationTiming, sessionIdLength, sessionMaxAliveTime, sessions, sm, support, TIMING_STATS_CACHE_SIZE
 
Fields inherited from interface org.apache.catalina.Lifecycle
AFTER_START_EVENT, AFTER_STOP_EVENT, BEFORE_START_EVENT, BEFORE_STOP_EVENT, DESTROY_EVENT, INIT_EVENT, PERIODIC_EVENT, START_EVENT, STOP_EVENT
 
Constructor Summary
SimpleTcpReplicationManager()
          Constructor, just calls super()
 
Method Summary
 ClusterManager cloneFromTemplate()
           
 Session createSession(java.lang.String sessionId)
          Construct and return a new session object, based on the default settings specified by this Manager's properties.
protected  Session createSession(java.lang.String sessionId, boolean notify, boolean setId)
          Creates a HTTP session.
 boolean doDomainReplication()
           
 CatalinaCluster getCluster()
           
 boolean getDistributable()
          Return the distributable flag for the sessions supported by this Manager.
 boolean getExpireSessionsOnShutdown()
           
 java.lang.String[] getInvalidatedSessions()
          When the manager expires session not tied to a request.
 java.lang.String getName()
          Return the descriptive short name of this Manager implementation.
 ReplicationStream getReplicationStream(byte[] data)
          Open Stream and use correct ClassLoader (Container) Switch ThreadClassLoader
 ReplicationStream getReplicationStream(byte[] data, int offset, int length)
           
 boolean isDefaultMode()
           
 boolean isManagerRunning()
           
 boolean isNotifyListenersOnReplication()
           
 boolean isStateTransferred()
           
 void messageDataReceived(ClusterMessage cmsg)
          A message was received from another node, this is the callback method to implement if you are interested in receiving replication messages.
protected  void messageReceived(SessionMessage msg, Member sender)
          This method is called by the received thread when a SessionMessage has been received from one of the other nodes in the cluster.
protected  Session readSession(byte[] data, java.lang.String sessionId)
          Reinstantiates a serialized session from the data passed in.
 ClusterMessage requestCompleted(java.lang.String sessionId)
          When the request has been completed, the replication valve will notify the manager, and the manager will decide whether any replication is needed or not.
 void sessionInvalidated(java.lang.String sessionId)
           
 void setCluster(CatalinaCluster cluster)
           
 void setDefaultMode(boolean defaultMode)
           
 void setDistributable(boolean dist)
          Set the distributable flag for the sessions supported by this Manager.
 void setDomainReplication(boolean sendClusterDomainOnly)
           
 void setExpireSessionsOnShutdown(boolean expireSessionsOnShutdown)
           
 void setName(java.lang.String name)
          Set the name of the manager, at host /context name and at engine hostname+/context
 void setNotifyListenersOnReplication(boolean notifyListenersOnReplication)
           
 void setPrintToScreen(boolean printtoscreen)
           
 void setSynchronousReplication(boolean flag)
           
 void setUseDirtyFlag(boolean usedirtyflag)
           
 void start()
          Prepare for the beginning of active use of the public methods of this component.
 void stop()
          Gracefully terminate the active use of the public methods of this component.
 void unload()
          Override persistence since they don't go hand in hand with replication for now.
protected  byte[] writeSession(Session session)
          Serialize a session into a byte array
This method simple calls the writeObjectData method on the session and returns the byte data from that call
 
Methods inherited from class org.apache.catalina.session.StandardManager
addLifecycleListener, doLoad, doUnload, file, findLifecycleListeners, getInfo, getMaxActiveSessions, getPathname, getRejectedSessions, load, propertyChange, removeLifecycleListener, setContainer, setMaxActiveSessions, setPathname, setRejectedSessions
 
Methods inherited from class org.apache.catalina.session.ManagerBase
add, addPropertyChangeListener, backgroundProcess, changeSessionId, createEmptySession, createSession, destroy, expireSession, findSession, findSessions, generateSessionId, getActiveSessions, getAlgorithm, getClassName, getContainer, getCreationTime, getCreationTimestamp, getDigest, getDomain, getDuplicates, getEngine, getEntropy, getExpiredSessions, getJvmRoute, getLastAccessedTime, getLastAccessedTimestamp, getMaxActive, getMaxInactiveInterval, getNewSession, getObjectName, getProcessExpiresFrequency, getProcessingTime, getRandom, getRandomBytes, getRandomClass, getRandomFile, getSession, getSessionAttribute, getSessionAttributeNameFilter, getSessionAttributeNamePattern, getSessionAttributeValueClassNameFilter, getSessionAttributeValueClassNamePattern, getSessionAverageAliveTime, getSessionCounter, getSessionCreateRate, getSessionExpireRate, getSessionIdLength, getSessionMaxAliveTime, getWarnOnSessionAttributeFilterFailure, init, listSessionIds, postDeregister, postRegister, preDeregister, preRegister, processExpires, remove, removePropertyChangeListener, setAlgorithm, setDuplicates, setEntropy, setExpiredSessions, setMaxActive, setMaxInactiveInterval, setProcessExpiresFrequency, setProcessingTime, setRandomClass, setRandomFile, setSessionAttributeNameFilter, setSessionAttributeValueClassNameFilter, setSessionAverageAliveTime, setSessionCounter, setSessionIdLength, setSessionMaxAliveTime, setWarnOnSessionAttributeFilterFailure, willAttributeDistribute
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 
Methods inherited from interface org.apache.catalina.Manager
add, addPropertyChangeListener, backgroundProcess, changeSessionId, createEmptySession, createSession, findSession, findSessions, getActiveSessions, getContainer, getExpiredSessions, getInfo, getMaxActive, getMaxInactiveInterval, getRejectedSessions, getSessionAverageAliveTime, getSessionCounter, getSessionIdLength, getSessionMaxAliveTime, load, remove, removePropertyChangeListener, setContainer, setExpiredSessions, setMaxActive, setMaxInactiveInterval, setRejectedSessions, setSessionAverageAliveTime, setSessionCounter, setSessionIdLength, setSessionMaxAliveTime, willAttributeDistribute
 

Field Detail

log

public static Log log

mChannelConfig

protected java.lang.String mChannelConfig

mGroupName

protected java.lang.String mGroupName

mChannelStarted

protected boolean mChannelStarted

mPrintToScreen

protected boolean mPrintToScreen

defaultMode

protected boolean defaultMode

mManagerRunning

protected boolean mManagerRunning

synchronousReplication

protected boolean synchronousReplication
Use synchronous rather than asynchronous replication. Every session modification (creation, change, removal etc) will be sent to all members. The call will then wait for max milliseconds, or forever (if timeout is 0) for all responses.


mExpireSessionsOnShutdown

protected boolean mExpireSessionsOnShutdown
Set to true if we don't want the sessions to expire on shutdown


useDirtyFlag

protected boolean useDirtyFlag

name

protected java.lang.String name

distributable

protected boolean distributable

cluster

protected CatalinaCluster cluster

invalidatedSessions

protected java.util.HashMap invalidatedSessions

stateTransferred

protected boolean stateTransferred
Flag to keep track if the state has been transferred or not Assumes false.

Constructor Detail

SimpleTcpReplicationManager

public SimpleTcpReplicationManager()
Constructor, just calls super()

Method Detail

doDomainReplication

public boolean doDomainReplication()
Specified by:
doDomainReplication in interface ClusterManager
Returns:
Manager send only to same cluster domain.

setDomainReplication

public void setDomainReplication(boolean sendClusterDomainOnly)
Specified by:
setDomainReplication in interface ClusterManager
Parameters:
sendClusterDomainOnly - The sendClusterDomainOnly to set.

isDefaultMode

public boolean isDefaultMode()
Specified by:
isDefaultMode in interface ClusterManager
Returns:
Returns the defaultMode.

setDefaultMode

public void setDefaultMode(boolean defaultMode)
Specified by:
setDefaultMode in interface ClusterManager
Parameters:
defaultMode - The defaultMode to set.

isManagerRunning

public boolean isManagerRunning()

setUseDirtyFlag

public void setUseDirtyFlag(boolean usedirtyflag)

setExpireSessionsOnShutdown

public void setExpireSessionsOnShutdown(boolean expireSessionsOnShutdown)

setCluster

public void setCluster(CatalinaCluster cluster)
Specified by:
setCluster in interface ClusterManager

getExpireSessionsOnShutdown

public boolean getExpireSessionsOnShutdown()

setPrintToScreen

public void setPrintToScreen(boolean printtoscreen)

setSynchronousReplication

public void setSynchronousReplication(boolean flag)

unload

public void unload()
            throws java.io.IOException
Override persistence since they don't go hand in hand with replication for now.

Specified by:
unload in interface Manager
Overrides:
unload in class StandardManager
Throws:
java.io.IOException - if an input/output error occurs

createSession

protected Session createSession(java.lang.String sessionId,
                                boolean notify,
                                boolean setId)
Creates a HTTP session. Most of the code in here is copied from the StandardManager. This is not pretty, yeah I know, but it was necessary since the StandardManager had hard coded the session instantiation to the a StandardSession, when we actually want to instantiate a ReplicatedSession
If the call comes from the Tomcat servlet engine, a SessionMessage goes out to the other nodes in the cluster that this session has been created.

Parameters:
notify - - if set to true the other nodes in the cluster will be notified. This flag is needed so that we can create a session before we deserialize a replicated one
See Also:
ReplicatedSession

createSession

public Session createSession(java.lang.String sessionId)
Construct and return a new session object, based on the default settings specified by this Manager's properties. The session id will be assigned by this method, and available via the getId() method of the returned session. If a new session cannot be created for any reason, return null.

Specified by:
createSession in interface Manager
Overrides:
createSession in class StandardManager
Parameters:
sessionId - The session id which should be used to create the new session; if null, a new session id will be generated
Throws:
java.lang.IllegalStateException - if a new session cannot be instantiated for any reason

sessionInvalidated

public void sessionInvalidated(java.lang.String sessionId)

getInvalidatedSessions

public java.lang.String[] getInvalidatedSessions()
Description copied from interface: ClusterManager
When the manager expires session not tied to a request. The cluster will periodically ask for a list of sessions that should expire and that should be sent across the wire.

Specified by:
getInvalidatedSessions in interface ClusterManager
Returns:
String[] The invalidated sessions

requestCompleted

public ClusterMessage requestCompleted(java.lang.String sessionId)
Description copied from interface: ClusterManager
When the request has been completed, the replication valve will notify the manager, and the manager will decide whether any replication is needed or not. If there is a need for replication, the manager will create a session message and that will be replicated. The cluster determines where it gets sent.

Specified by:
requestCompleted in interface ClusterManager
Parameters:
sessionId - - the sessionId that just completed.
Returns:
a SessionMessage to be sent.

writeSession

protected byte[] writeSession(Session session)
Serialize a session into a byte array
This method simple calls the writeObjectData method on the session and returns the byte data from that call

Parameters:
session - - the session to be serialized
Returns:
a byte array containing the session data, null if the serialization failed

getReplicationStream

public ReplicationStream getReplicationStream(byte[] data)
                                       throws java.io.IOException
Open Stream and use correct ClassLoader (Container) Switch ThreadClassLoader

Specified by:
getReplicationStream in interface ClusterManager
Parameters:
data -
Returns:
The object input stream
Throws:
java.io.IOException

getReplicationStream

public ReplicationStream getReplicationStream(byte[] data,
                                              int offset,
                                              int length)
                                       throws java.io.IOException
Specified by:
getReplicationStream in interface ClusterManager
Throws:
java.io.IOException

readSession

protected Session readSession(byte[] data,
                              java.lang.String sessionId)
Reinstantiates a serialized session from the data passed in. This will first call createSession() so that we get a fresh instance with all the managers set and all the transient fields validated. Then it calls Session.readObjectData(byte[]) to deserialize the object

Parameters:
data - - a byte array containing session data
Returns:
a valid Session object, null if an error occurs

getName

public java.lang.String getName()
Description copied from class: StandardManager
Return the descriptive short name of this Manager implementation.

Specified by:
getName in interface ClusterManager
Overrides:
getName in class StandardManager
Returns:
The descriptive short name of this Manager implementation.

start

public void start()
           throws LifecycleException
Prepare for the beginning of active use of the public methods of this component. This method should be called after configure(), and before any of the public methods of the component are utilized.
Starts the cluster communication channel, this will connect with the other nodes in the cluster, and request the current session state to be transferred to this node.

Specified by:
start in interface Lifecycle
Overrides:
start in class StandardManager
Throws:
java.lang.IllegalStateException - if this component has already been started
LifecycleException - if this component detects a fatal error that prevents this component from being used

stop

public void stop()
          throws LifecycleException
Gracefully terminate the active use of the public methods of this component. This method should be the last one called on a given instance of this component.
This will disconnect the cluster communication channel and stop the listener thread.

Specified by:
stop in interface Lifecycle
Overrides:
stop in class StandardManager
Throws:
java.lang.IllegalStateException - if this component has not been started
LifecycleException - if this component detects a fatal error that needs to be reported

setDistributable

public void setDistributable(boolean dist)
Description copied from interface: Manager
Set the distributable flag for the sessions supported by this Manager. If this flag is set, all user data objects added to sessions associated with this manager must implement Serializable.

Specified by:
setDistributable in interface Manager
Overrides:
setDistributable in class ManagerBase
Parameters:
dist - The new distributable flag

getDistributable

public boolean getDistributable()
Description copied from class: ManagerBase
Return the distributable flag for the sessions supported by this Manager.

Specified by:
getDistributable in interface Manager
Overrides:
getDistributable in class ManagerBase

messageReceived

protected void messageReceived(SessionMessage msg,
                               Member sender)
This method is called by the received thread when a SessionMessage has been received from one of the other nodes in the cluster.

Parameters:
msg - - the message received
sender - - the sender of the message, this is used if we receive a EVT_GET_ALL_SESSION message, so that we only reply to the requesting node

messageDataReceived

public void messageDataReceived(ClusterMessage cmsg)
Description copied from interface: ClusterManager
A message was received from another node, this is the callback method to implement if you are interested in receiving replication messages.

Specified by:
messageDataReceived in interface ClusterManager
Parameters:
cmsg - - the message received.

isStateTransferred

public boolean isStateTransferred()

setName

public void setName(java.lang.String name)
Description copied from interface: ClusterManager
Set the name of the manager, at host /context name and at engine hostname+/context

Specified by:
setName in interface ClusterManager

isNotifyListenersOnReplication

public boolean isNotifyListenersOnReplication()
Specified by:
isNotifyListenersOnReplication in interface ClusterManager

setNotifyListenersOnReplication

public void setNotifyListenersOnReplication(boolean notifyListenersOnReplication)

getCluster

public CatalinaCluster getCluster()
Specified by:
getCluster in interface ClusterManager

cloneFromTemplate

public ClusterManager cloneFromTemplate()
Specified by:
cloneFromTemplate in interface ClusterManager

Apache Tomcat 6.0.53

Copyright © 2000-2017 Apache Software Foundation. All Rights Reserved.