Package org.jboss.web.tomcat.service.session.distributedcache.impl.jbc

Source Code of org.jboss.web.tomcat.service.session.distributedcache.impl.jbc.AbstractJBossCacheService

/*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.web.tomcat.service.session.distributedcache.impl.jbc;

import java.io.IOException;
import java.io.Serializable;
import java.security.AccessController;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

import javax.transaction.TransactionManager;

import org.jboss.cache.Cache;
import org.jboss.cache.CacheException;
import org.jboss.cache.CacheManager;
import org.jboss.cache.CacheStatus;
import org.jboss.cache.Fqn;
import org.jboss.cache.Node;
import org.jboss.cache.Region;
import org.jboss.cache.buddyreplication.BuddyManager;
import org.jboss.cache.config.BuddyReplicationConfig;
import org.jboss.cache.config.CacheLoaderConfig;
import org.jboss.cache.pojo.impl.InternalConstant;
import org.jboss.cache.transaction.BatchModeTransactionManager;
import org.jboss.ha.framework.interfaces.CachableMarshalledValue;
import org.jboss.ha.framework.server.CacheManagerLocator;
import org.jboss.ha.framework.server.MarshalledValueHelper;
import org.jboss.ha.framework.server.SimpleCachableMarshalledValue;
import org.jboss.logging.Logger;
import org.jboss.util.loading.ContextClassLoaderSwitcher;
import org.jboss.web.tomcat.service.session.distributedcache.spi.BatchingManager;
import org.jboss.web.tomcat.service.session.distributedcache.spi.ClusteringNotSupportedException;
import org.jboss.web.tomcat.service.session.distributedcache.spi.DistributableSession;
import org.jboss.web.tomcat.service.session.distributedcache.spi.DistributableSessionData;
import org.jboss.web.tomcat.service.session.distributedcache.spi.DistributableSessionMetadata;
import org.jboss.web.tomcat.service.session.distributedcache.spi.DistributedCacheManager;
import org.jboss.web.tomcat.service.session.distributedcache.spi.LocalDistributableSessionManager;
import org.jboss.web.tomcat.service.session.distributedcache.spi.SessionSerializationFactory;

/**
* Abstract base implementation of {@link DistributedCacheManager}.
*/
public abstract class AbstractJBossCacheService implements DistributedCacheManager
{  
   public static final String BUDDY_BACKUP = BuddyManager.BUDDY_BACKUP_SUBTREE;
   public static final Fqn BUDDY_BACKUP_FQN = BuddyManager.BUDDY_BACKUP_SUBTREE_FQN;
   public static final String SESSION = "JSESSION";
  
   // Use Integers as JBC keys -- replication performant but won't be
   // confused with String attribute keys for ATTRIBUTE granularity sessions
   // Alternative is an enum, but then we replicate a long classname
   public static final Integer VERSION_KEY = Integer.valueOf(0);
   public static final Integer TIMESTAMP_KEY = Integer.valueOf(1);
   public static final Integer METADATA_KEY = Integer.valueOf(2);
   public static final Integer ATTRIBUTE_KEY = Integer.valueOf(3);
   protected static final Set<Integer> INTERNAL_KEYS = new HashSet<Integer>(Arrays.asList(VERSION_KEY, TIMESTAMP_KEY, METADATA_KEY, ATTRIBUTE_KEY));
   
   public static final String FQN_DELIMITER = "/";
  
   public static String getCombinedPath(String hostname, String contextPath)
   {
      return contextPath + "_" + hostname;
   }
  
   public static Fqn getSessionFqn(String contextHostPath, String sessionId)
   {
      Object[] objs = new Object[]{SESSION, contextHostPath, sessionId};
      return Fqn.fromList(Arrays.asList(objs), true);
   }
  
   public static Fqn getBuddyBackupSessionFqn(String dataOwner, String contextHostPath, String sessionId)
   {
      Object[] objs = new Object[]{BUDDY_BACKUP, dataOwner, SESSION, contextHostPath, sessionId};
      return Fqn.fromList(Arrays.asList(objs), true);
   }  
  
   private static ContextClassLoaderSwitcher getContextClassLoaderSwitcher()
   {
      return (ContextClassLoaderSwitcher) AccessController.doPrivileged(ContextClassLoaderSwitcher.INSTANTIATOR);
   }
  
   protected Logger log_ = Logger.getLogger(getClass());
  
   private Cache plainCache_;
  
   /** Context path for webapp + hostName; this + session id is a unique combo. */
   protected String combinedPath_;
   protected BatchingManager batchingManager;

   private LocalDistributableSessionManager manager_;
   private ClassLoader webAppClassLoader_;
   private CacheListener cacheListener_;
   protected JBossCacheWrapper cacheWrapper_;
  
   /** Do we have to marshall attributes ourself or can we let JBC do it? */
   private boolean useTreeCacheMarshalling_ = false;
  
   /** Are we configured for passivation? */
   private boolean usePassivation_ = false;
   private PassivationListener passivationListener_;
  
   /** Is cache configured for buddy replication? */
   private boolean useBuddyReplication_ = false;
  
   protected String cacheConfigName_;
  
   protected AbstractJBossCacheService(LocalDistributableSessionManager localManager) throws ClusteringNotSupportedException
   {
      this(localManager, Util.findPlainCache(Util.getCacheConfigName(localManager)));
     
      this.cacheConfigName_ = Util.getCacheConfigName(localManager);
   }
  
   protected AbstractJBossCacheService(LocalDistributableSessionManager localManager, Cache cache)
   {
      this.manager_    = localManager;
      this.plainCache_ = cache;
     
      this.cacheWrapper_ = new JBossCacheWrapper(plainCache_);
     
      this.useTreeCacheMarshalling_ = plainCache_.getConfiguration().isUseRegionBasedMarshalling();
      CacheLoaderConfig clc = plainCache_.getConfiguration().getCacheLoaderConfig();
      if(clc != null)
      {
         usePassivation_ = (clc.isPassivation() && !clc.isShared());
      }
   }
  
   protected LocalDistributableSessionManager getManager()
   {
      return manager_;
   }
  
   protected Cache getCache()
   {
      return plainCache_;
   }
  
   protected void setCache(Cache cache)
   {
      this.plainCache_ = cache;
   }
  
   protected abstract boolean getStoreAttributesInSingleKey();
   protected abstract boolean isFieldBased();

   public void start()
   {
      this.webAppClassLoader_ = this.manager_.getApplicationClassLoader();
     
      String webAppPath;
      String path = manager_.getContextName();
      if( path.length() == 0 || path.equals("/")) {
         // If this is root.
         webAppPath = "ROOT";
      } else if ( path.startsWith("/") ) {
         webAppPath = path.substring(1);
      } else {
         webAppPath = path;
      }
      // JBAS-3941 -- context path can be multi-level, but we don't
      // want that turning into a multilevel Fqn, so escape it
      // Use '-' which is legal in a filesystem path
      webAppPath = webAppPath.replace('/', '_');
      log_.debug("Old and new web app path are: " +path + ", " +webAppPath);
     
      String hostName;     
      String host = manager_.getHostName();
      if( host == null || host.length() == 0) {
         hostName = "localhost";
      }else {
         hostName = host;
      }
      log_.debug("Old and new virtual host name are: " + host + ", " + hostName);

      this.combinedPath_ = getCombinedPath(hostName, webAppPath);
     
      if (plainCache_.getCacheStatus() != CacheStatus.STARTED)
      {
         plainCache_.start();
      }

      // We require the cache batchingManager to be BatchModeTransactionManager now.
      TransactionManager tm = plainCache_.getConfiguration().getRuntimeConfig().getTransactionManager();
      if( ! (tm instanceof BatchModeTransactionManager) )
      {
         throw new RuntimeException("start(): JBoss Cache transaction manager " +
                                    "is not of type BatchModeTransactionManager. " +
                                    "It is " + (tm == null ? "null" : tm.getClass().getName()));
      }
      this.batchingManager = new BatchingManagerImpl(tm);
     
      Object[] objs = new Object[]{SESSION, combinedPath_};
      Fqn pathFqn = Fqn.fromList(Arrays.asList(objs), true);
     
      BuddyReplicationConfig brc = plainCache_.getConfiguration().getBuddyReplicationConfig();
      this.useBuddyReplication_ = brc != null && brc.isEnabled();
      if (useTreeCacheMarshalling_ || this.useBuddyReplication_)
      {
         // JBAS-5628/JBAS-5629 -- clean out persistent store
         cleanWebappRegion(pathFqn);
      }

      // Listen for cache changes
      cacheListener_ = new CacheListener(cacheWrapper_, manager_, combinedPath_,
                                         Util.getReplicationGranularity(manager_));
      plainCache_.addCacheListener(cacheListener_);
     
      if(useTreeCacheMarshalling_)
      {
         // register the tcl and bring over the state for the webapp
         try
         {
           
            log_.debug("UseMarshalling is true. We will register the fqn: " +
                        pathFqn + " with class loader" +webAppClassLoader_ +
                        " and activate the webapp's Region");
            Node root = plainCache_.getRoot();
            if (root.hasChild(pathFqn) == false)
            {
               plainCache_.getInvocationContext().getOptionOverrides().setCacheModeLocal(true);
               root.addChild(pathFqn);
            }
            Region region = plainCache_.getRegion(pathFqn, true);
            region.registerContextClassLoader(webAppClassLoader_);
            region.activate();
         }
         catch (Exception ex)
         {
            throw new RuntimeException("Can't register class loader", ex);
         }
      }
     
      if(manager_.isPassivationEnabled())
      {
         log_.debug("Passivation is enabled");
         passivationListener_ = new PassivationListener(manager_, combinedPath_);
         plainCache_.addCacheListener(passivationListener_);
      }
      else
      {
         log_.debug("Passivation is disabled");
      }
   }

   public void stop()
   {
      plainCache_.removeCacheListener(cacheListener_);     
      if (passivationListener_ != null)
         plainCache_.removeCacheListener(passivationListener_);
     
      // Construct the fqn
      Object[] objs = new Object[]{SESSION, combinedPath_};
      Fqn pathFqn = Fqn.fromList(Arrays.asList(objs), true);

      if(useTreeCacheMarshalling_)
      {
         log_.debug("UseMarshalling is true. We will inactivate the fqn: " +
                    pathFqn + " and un-register its classloader");
           
         try {
            Region region = plainCache_.getRegion(pathFqn, false);
            if (region != null)
            {
               region.deactivate();
               region.unregisterContextClassLoader();
            }
         }
         catch (Exception e)
         {
            log_.error("Exception during inactivation of webapp region " + pathFqn +
                       " or un-registration of its class loader", e);
         }
      }
      BuddyReplicationConfig brc = plainCache_.getConfiguration().getBuddyReplicationConfig();
      this.useBuddyReplication_ = brc != null && brc.isEnabled();
      if (useTreeCacheMarshalling_ || this.useBuddyReplication_)
      {
         // JBAS-5628/JBAS-5629 -- clean out persistent store
         cleanWebappRegion(pathFqn);
      }
      // remove session data
      // BES 2007/08/18 Can't do this as it will
      // 1) blow away passivated sessions
      // 2) leave the cache in an inconsistent state if the war
      //    is restarted
//      cacheWrapper_.removeLocalSubtree(pathFqn);
     
      this.webAppClassLoader_ = null;
     
      if (cacheConfigName_ != null)
      {
         releaseCacheToManager(cacheConfigName_);
      }
   }

   /**
    * Get specfically the BatchModeTransactionManager.
    */
   public BatchingManager getBatchingManager()
   {
      return batchingManager;
   }
  
   /**
    * Gets whether TreeCache-based marshalling is available
    */
   public boolean isMarshallingAvailable()
   {
      return useTreeCacheMarshalling_;
   }
  
  

   public void sessionCreated(DistributableSession session)
   {
      if (session.needRegionForSession())
      {
         Fqn fqn = getSessionFqn(combinedPath_, session.getRealId());
         setupSessionRegion(session, fqn);
      }     
   }

   /**
    * Loads any serialized data in the cache into the given session
    * using its <code>readExternal</code> method.
    *
    * @return the session passed as <code>toLoad</code>, or
    *         <code>null</code> if the cache had no data stored
    *         under the given session id.
    */
   public <T extends DistributableSession> T loadSession(String realId, T toLoad)
   {
      Fqn fqn = getSessionFqn(combinedPath_, realId);
      Map sessionData =  cacheWrapper_.getData(fqn, true);
     
      if (sessionData == null) {
         // Requested session is no longer in the cache; return null
         return null;
      }
     
      if (toLoad.needRegionForSession())
      {
         setupSessionRegion(toLoad, fqn);
      }
     
      DistributableSessionData dsd = getDistributableSessionData(realId, sessionData, true);
      toLoad.update(dsd);
     
      return toLoad;
   }

   public void putSession(DistributableSession session)
   {
      String realId = session.getRealId();
     
      if (log_.isTraceEnabled())
      {
         log_.trace("putSession(): putting session " + realId);
      }    
     
      Fqn fqn = getSessionFqn(combinedPath_, realId);
     
      Map map = new HashMap();
      map.put(VERSION_KEY, session.getVersion());
     
      boolean replicateTimestamp = false;
     
      if (session.isSessionMetadataDirty())
      {  
         map.put(METADATA_KEY, session.getSessionMetadata());
         replicateTimestamp = true;
      }
    
      if (session.isSessionAttributeMapDirty())
      {
         if (getStoreAttributesInSingleKey())
         {
            Map attrs = session.getSessionAttributeMap();
            map.put(ATTRIBUTE_KEY, getMarshalledValue(attrs));
         }
         // Whether or not we stored the attributes above, we need
         // to replicate timestamp
         replicateTimestamp = true;
      }
     
      if (replicateTimestamp || session.getMustReplicateTimestamp())
      {
         map.put(TIMESTAMP_KEY, session.getSessionTimestamp());
      }
     
      cacheWrapper_.put(fqn, map);
   }

   /**
    * Extension point to allow subclasses to add per-session JBC regions.
    *
    * @param session the session
    * @param fqn the fqn for the session
    */
   protected void setupSessionRegion(DistributableSession session, Fqn fqn)
   {     
   }

   /**
    * Extension point to allow subclasses to remove per-session JBC regions.
    *
    * @param session the session
    * @param fqn the fqn for the session
    */
   protected void removeSessionRegion(String realId, Fqn fqn)
   {     
   }

   public void removeSession(String realId)
   {
      Fqn fqn = getSessionFqn(combinedPath_, realId);
      if (log_.isTraceEnabled())
      {
         log_.trace("Remove session from distributed store. Fqn: " + fqn);
      }

      cacheWrapper_.remove(fqn);
     
      removeSessionRegion(realId, fqn);
   }

   public void removeSessionLocal(String realId)
   {
      Fqn fqn = getSessionFqn(combinedPath_, realId);
      if (log_.isTraceEnabled())
      {
         log_.trace("Remove session from my own distributed store only. Fqn: " + fqn);
      }
     
      cacheWrapper_.removeLocal(fqn);
     
      removeSessionRegion(realId, fqn);
   }

   public void removeSessionLocal(String realId, String dataOwner)
   {
      if (dataOwner == null)
      {
         removeSessionLocal(realId);
      }
      else
      {        
         Fqn fqn = getBuddyBackupSessionFqn(dataOwner, combinedPath_, realId);
         if (log_.isTraceEnabled())
         {
            log_.trace("Remove session from my own distributed store only. Fqn: " + fqn);
         }
         cacheWrapper_.removeLocal(fqn);
      }
   }  
     
   public void evictSession(String realId)
   {
      evictSession(realId, null);     
   }  
     
   public void evictSession(String realId, String dataOwner)
   {   
      Fqn fqn = dataOwner == null ? getSessionFqn(combinedPath_, realId) : getBuddyBackupSessionFqn(dataOwner, combinedPath_, realId);
      if(log_.isTraceEnabled())
      {
         log_.trace("evictSession(): evicting session from my distributed store. Fqn: " + fqn);
      }
      cacheWrapper_.evictSubtree(fqn);     
   }
  
   public DistributableSessionData getSessionData(String realId, String dataOwner, boolean includeAttributes)
   {
      Fqn fqn = dataOwner == null ? getSessionFqn(combinedPath_, realId) : getBuddyBackupSessionFqn(dataOwner, combinedPath_, realId);
      Map<Object, Object> distributedCacheData = cacheWrapper_.getData(fqn, false);
      return getDistributableSessionData(realId, distributedCacheData, includeAttributes);
   }

   /**
    * Gets the ids of all sessions in the underlying cache.
    *
    * @return Map<String, String> containing all of the session ids of sessions in the cache
    *         (with any jvmRoute removed) as keys, and the identifier of the data owner for
    *         the session as value (or a <code>null</code>  value if buddy
    *         replication is not enabled.) Will not return <code>null</code>.
    */
   public Map<String, String> getSessionIds()
   {
      Map<String, String> result = new HashMap<String, String>();
     
      Fqn webappFqn = getWebappFqn();
     
      Node bbRoot = plainCache_.getRoot().getChild(BUDDY_BACKUP_FQN);
      if (bbRoot != null)
      {
         Set<Node> owners = bbRoot.getChildren();
         if (owners != null)
         {
            for (Node owner : owners)
            {
               Node webRoot = owner.getChild(webappFqn);
               if (webRoot != null)
               {
                  Set<String> ids = webRoot.getChildrenNames();
                  storeSessionOwners(ids, (String) owner.getFqn().getLastElement(), result);
               }
            }
         }
      }
     
      storeSessionOwners(getChildrenNames(webappFqn), null, result);

      return result;
   }
  
   protected Set getChildrenNames(Fqn fqn)
   {
      Node node = plainCache_.getRoot().getChild(fqn);
      return (node == null ? Collections.EMPTY_SET : node.getChildrenNames());
   }

   private void storeSessionOwners(Set<String> ids, String owner, Map<String, String> map)
   {
      if (ids != null)
      {
         for (String id : ids)
         {           
            if (!InternalConstant.JBOSS_INTERNAL_STRING.equals(id))
            {
               map.put(id, owner);
            }
         }
      }
   }
   public boolean isPassivationEnabled()
   {
      return usePassivation_;     
   }

   protected Fqn getWebappFqn()
   {
      // /SESSION/webAppPath_hostName
      Object[] objs = new Object[]{SESSION, combinedPath_};
      return Fqn.fromList(Arrays.asList(objs), true);
   }
  
   /**
    * Extracts the contents of <code>distributedCacheData</code>.
    *
    * <strong>Note:</strong> This operation may alter the contents of the
    * passed in map. If this is unacceptable, pass in a defensive copy.
    */
   protected DistributableSessionData getDistributableSessionData(String realId,
                                       Map<Object, Object> distributedCacheData,
                                       boolean includeAttributes)
   {
      AtomicInteger version = (AtomicInteger) distributedCacheData.get(VERSION_KEY);
      AtomicLong timestamp = (AtomicLong) distributedCacheData.get(TIMESTAMP_KEY);
      DistributableSessionMetadata metadata = (DistributableSessionMetadata) distributedCacheData.get(METADATA_KEY);
      Map<String, Object> attrs = includeAttributes ? getSessionAttributes(realId, distributedCacheData) : null;     
      return new DistributableSessionDataImpl(version, timestamp, metadata, attrs);
   }
  
   /**
    * Returns the session attributes, possibly using the passed in
    * <code>distributedCacheData</code> as a source.
    *
    * <strong>Note:</strong> This operation may alter the contents of the
    * passed in map. If this is unacceptable, pass in a defensive copy.
    */
   protected abstract Map<String, Object> getSessionAttributes(String realId, Map<Object, Object> distributedCacheData);
  
   protected void releaseCacheToManager(String cacheConfigName)
   {     
      try
      {
         CacheManager cm = CacheManagerLocator.getCacheManagerLocator().getCacheManager(null);
         cm.releaseCache(cacheConfigName);
      }
      catch (Exception e)
      {
         log_.error("Problem releasing cache to CacheManager -- config is " + cacheConfigName, e);
      }
   }

   protected Object getMarshalledValue(Object value)
   {
      // JBAS-2920.  For now, continue using MarshalledValue, as
      // it allows lazy deserialization of the attribute on remote nodes
      // For Branch_4_0 this is what we have to do anyway for backwards
      // compatibility. For HEAD we'll follow suit for now.
      // TODO consider only using MV for complex objects (i.e. not primitives)
      // and Strings longer than X.
     
//      if (useTreeCacheMarshalling_)
//      {
//         return value;
//      }
//      else
//      {
        
         // JBAS-2921 - replaced MarshalledValue calls with SessionSerializationFactory calls
         // to allow for switching between JBossSerialization and JavaSerialization using
         // system property -D=session.serialization.jboss=true / false
         // MarshalledValue mv = new MarshalledValue(value);
         if  (MarshalledValueHelper.isTypeExcluded(value.getClass()))
         {
            return value;              
         }
         else
         {
            try
            {
               CachableMarshalledValue mv = SessionSerializationFactory.createMarshalledValue((Serializable) value);
               return mv;
            }
            catch (ClassCastException e)
            {
               throw new IllegalArgumentException(value + " does not implement java.io.Serializable");
            }
         }
//      }
   }

   protected Object getUnMarshalledValue(Object obj)
   {
      if (!(obj instanceof SimpleCachableMarshalledValue))
            return obj;
        
      // Swap in/out the tcl for this web app. Needed only for un marshalling.
      ContextClassLoaderSwitcher.SwitchContext switcher = null;
      try
      {
         switcher = getContextClassLoaderSwitcher().getSwitchContext();
         switcher.setClassLoader(webAppClassLoader_);
        
         SimpleCachableMarshalledValue mv = (SimpleCachableMarshalledValue) obj;
         mv.setObjectStreamSource(SessionSerializationFactory.getObjectStreamSource());
         return mv.get();
      }
      catch (IOException e)
      {
         log_.error("IOException occurred unmarshalling value ", e);
         return null;
      }
      catch (ClassNotFoundException e)
      {
         log_.error("ClassNotFoundException occurred unmarshalling value ", e);
         return null;
      }
      finally
      {
         if (switcher != null)
         {
            switcher.reset();
         }
      }
   }

   private void cleanWebappRegion(Fqn regionFqn)
   {
      try {
         // Remove locally.
         plainCache_.getInvocationContext().getOptionOverrides().setCacheModeLocal(true);
         plainCache_.removeNode(regionFqn);
      }
      catch (CacheException e)
      {
         log_.error("can't clean content from the underlying distributed cache");
      }
   }

}
TOP

Related Classes of org.jboss.web.tomcat.service.session.distributedcache.impl.jbc.AbstractJBossCacheService

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.