PageRenderTime 49ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/jboss-as-7.1.1.Final/clustering/ejb3-infinispan/src/main/java/org/jboss/as/clustering/ejb3/cache/backing/infinispan/InfinispanBackingCacheEntryStore.java

#
Java | 343 lines | 281 code | 35 blank | 27 comment | 26 complexity | 5c27310d7072dfa79bc2053fd2f45977 MD5 | raw file
Possible License(s): LGPL-2.1, Apache-2.0
  1. /*
  2. * JBoss, Home of Professional Open Source.
  3. * Copyright 2011, Red Hat Middleware LLC, and individual contributors
  4. * as indicated by the @author tags. See the copyright.txt file in the
  5. * distribution for a full listing of individual contributors.
  6. *
  7. * This is free software; you can redistribute it and/or modify it
  8. * under the terms of the GNU Lesser General Public License as
  9. * published by the Free Software Foundation; either version 2.1 of
  10. * the License, or (at your option) any later version.
  11. *
  12. * This software is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with this software; if not, write to the Free
  19. * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  20. * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
  21. */
  22. package org.jboss.as.clustering.ejb3.cache.backing.infinispan;
  23. import java.io.IOException;
  24. import java.io.Serializable;
  25. import java.util.Collections;
  26. import java.util.List;
  27. import java.util.Map;
  28. import java.util.Random;
  29. import java.util.Set;
  30. import org.infinispan.Cache;
  31. import org.infinispan.context.Flag;
  32. import org.infinispan.distribution.DataLocality;
  33. import org.infinispan.distribution.DistributionManager;
  34. import org.infinispan.notifications.Listener;
  35. import org.infinispan.notifications.cachelistener.annotation.CacheEntryActivated;
  36. import org.infinispan.notifications.cachelistener.annotation.CacheEntryPassivated;
  37. import org.infinispan.notifications.cachelistener.event.CacheEntryActivatedEvent;
  38. import org.infinispan.notifications.cachelistener.event.CacheEntryPassivatedEvent;
  39. import org.infinispan.remoting.transport.Address;
  40. import org.jboss.as.clustering.MarshalledValue;
  41. import org.jboss.as.clustering.MarshalledValueFactory;
  42. import org.jboss.as.clustering.infinispan.invoker.BatchOperation;
  43. import org.jboss.as.clustering.infinispan.invoker.CacheInvoker;
  44. import org.jboss.as.clustering.lock.SharedLocalYieldingClusterLockManager;
  45. import org.jboss.as.clustering.lock.SharedLocalYieldingClusterLockManager.LockResult;
  46. import org.jboss.as.clustering.lock.TimeoutException;
  47. import org.jboss.as.clustering.registry.Registry;
  48. import org.jboss.as.ejb3.cache.Cacheable;
  49. import org.jboss.as.ejb3.cache.PassivationManager;
  50. import org.jboss.as.ejb3.cache.impl.backing.clustering.ClusteredBackingCacheEntryStoreConfig;
  51. import org.jboss.as.ejb3.cache.spi.BackingCacheEntry;
  52. import org.jboss.as.ejb3.cache.spi.GroupCompatibilityChecker;
  53. import org.jboss.as.ejb3.cache.spi.impl.AbstractBackingCacheEntryStore;
  54. import org.jboss.as.ejb3.component.stateful.StatefulTimeoutInfo;
  55. import org.jboss.ejb.client.Affinity;
  56. import org.jboss.ejb.client.ClusterAffinity;
  57. import org.jboss.ejb.client.NodeAffinity;
  58. import org.jboss.logging.Logger;
  59. /**
  60. * Infinispan-based backing cache entry store.
  61. * @author Paul Ferraro
  62. */
  63. @Listener
  64. public class InfinispanBackingCacheEntryStore<K extends Serializable, V extends Cacheable<K>, E extends BackingCacheEntry<K, V>, C> extends AbstractBackingCacheEntryStore<K, V, E>{
  65. private final Logger log = Logger.getLogger(getClass());
  66. private final SharedLocalYieldingClusterLockManager lockManager;
  67. private final LockKeyFactory<K, C> lockKeyFactory;
  68. private final MarshalledValueFactory<C> keyFactory;
  69. private final MarshalledValueFactory<C> valueFactory;
  70. private final C context;
  71. private final boolean controlCacheLifecycle;
  72. private final Cache<MarshalledValue<K, C>, MarshalledValue<E, C>> cache;
  73. private final CacheInvoker invoker;
  74. private final PassivationManager<K, E> passivationManager;
  75. private final boolean clustered;
  76. private final Random random = new Random(System.currentTimeMillis());
  77. private final Registry<String, ?> registry;
  78. public InfinispanBackingCacheEntryStore(Cache<MarshalledValue<K, C>, MarshalledValue<E, C>> cache, CacheInvoker invoker, PassivationManager<K, E> passivationManager, StatefulTimeoutInfo timeout, ClusteredBackingCacheEntryStoreConfig config, boolean controlCacheLifecycle, MarshalledValueFactory<C> keyFactory, MarshalledValueFactory<C> valueFactory, C context, SharedLocalYieldingClusterLockManager lockManager, LockKeyFactory<K, C> lockKeyFactory, Registry<String, ?> registry) {
  79. super(timeout, config);
  80. this.cache = cache;
  81. this.invoker = invoker;
  82. this.passivationManager = passivationManager;
  83. this.controlCacheLifecycle = controlCacheLifecycle;
  84. this.clustered = cache.getCacheConfiguration().clustering().cacheMode().isClustered();
  85. this.keyFactory = keyFactory;
  86. this.valueFactory = valueFactory;
  87. this.context = context;
  88. this.lockManager = this.clustered ? lockManager : null;
  89. this.lockKeyFactory = lockKeyFactory;
  90. this.registry = registry;
  91. }
  92. @Override
  93. public void start() {
  94. if (this.controlCacheLifecycle) {
  95. this.cache.start();
  96. }
  97. }
  98. @Override
  99. public void stop() {
  100. if (this.controlCacheLifecycle) {
  101. this.cache.stop();
  102. }
  103. }
  104. @Override
  105. public boolean hasAffinity(K key) {
  106. DistributionManager dist = this.cache.getAdvancedCache().getDistributionManager();
  107. if (dist != null) {
  108. DataLocality locality = dist.getLocality(key);
  109. return locality.isLocal() || locality.isUncertain();
  110. }
  111. return true;
  112. }
  113. @Override
  114. public Affinity getStrictAffinity() {
  115. return new ClusterAffinity(this.cache.getCacheManager().getClusterName());
  116. }
  117. @Override
  118. public Affinity getWeakAffinity(K key) {
  119. if (!this.hasAffinity(key)) {
  120. // Locate nodes on which the cache entry will reside
  121. List<Address> addresses = this.cache.getAdvancedCache().getDistributionManager().locate(key);
  122. if (!addresses.contains(this.cache.getCacheManager().getAddress())) {
  123. // Otherwise choose random node from hash targets
  124. Map.Entry<String, ?> entry = this.registry.getRemoteEntry(addresses.get(random.nextInt(addresses.size())));
  125. if (entry != null) {
  126. return new NodeAffinity(entry.getKey());
  127. }
  128. }
  129. }
  130. return new NodeAffinity(this.registry.getLocalEntry().getKey());
  131. }
  132. @Override
  133. public Set<K> insert(E entry) {
  134. K id = entry.getId();
  135. this.trace("insert(%s)", id);
  136. final MarshalledValue<K, C> key = this.marshalKey(id);
  137. this.acquireSessionOwnership(key, true);
  138. try {
  139. final MarshalledValue<E, C> value = this.marshalEntry(entry);
  140. Operation<Void> operation = new Operation<Void>() {
  141. @Override
  142. public Void invoke(Cache<MarshalledValue<K, C>, MarshalledValue<E, C>> cache) {
  143. cache.getAdvancedCache().withFlags(Flag.SKIP_REMOTE_LOOKUP).put(key, value);
  144. return null;
  145. }
  146. };
  147. this.invoke(operation);
  148. } finally {
  149. this.releaseSessionOwnership(key, false);
  150. }
  151. return Collections.emptySet();
  152. }
  153. @Override
  154. public E get(K id, boolean lock) {
  155. this.trace("get(%s. %s)", id, lock);
  156. final MarshalledValue<K, C> key = this.marshalKey(id);
  157. if (lock) {
  158. this.acquireSessionOwnership(key, false);
  159. }
  160. Operation<MarshalledValue<E, C>> operation = new Operation<MarshalledValue<E, C>>() {
  161. @Override
  162. public MarshalledValue<E, C> invoke(Cache<MarshalledValue<K, C>, MarshalledValue<E, C>> cache) {
  163. return cache.get(key);
  164. }
  165. };
  166. return this.unmarshalEntry(id, this.invoke(operation));
  167. }
  168. @Override
  169. public void update(E entry, boolean modified) {
  170. K id = entry.getId();
  171. this.trace("update(%s, %s)", id, modified);
  172. final MarshalledValue<K, C> key = this.marshalKey(id);
  173. try {
  174. if (modified) {
  175. final MarshalledValue<E, C> value = this.marshalEntry(entry);
  176. Operation<Void> operation = new Operation<Void>() {
  177. @Override
  178. public Void invoke(Cache<MarshalledValue<K, C>, MarshalledValue<E, C>> cache) {
  179. cache.getAdvancedCache().withFlags(Flag.SKIP_REMOTE_LOOKUP).put(key, value);
  180. return null;
  181. }
  182. };
  183. this.invoke(operation);
  184. }
  185. } finally {
  186. this.releaseSessionOwnership(key, false);
  187. }
  188. }
  189. @Override
  190. public E remove(K id) {
  191. this.trace("remove(%s)", id);
  192. final MarshalledValue<K, C> key = this.marshalKey(id);
  193. Operation<MarshalledValue<E, C>> operation = new Operation<MarshalledValue<E, C>>() {
  194. @Override
  195. public MarshalledValue<E, C> invoke(Cache<MarshalledValue<K, C>, MarshalledValue<E, C>> cache) {
  196. return cache.remove(key);
  197. }
  198. };
  199. try {
  200. return this.unmarshalEntry(id, this.invoke(operation));
  201. } finally {
  202. this.releaseSessionOwnership(key, true);
  203. }
  204. }
  205. private <R> R invoke(Operation<R> operation) {
  206. return this.invoker.invoke(this.cache, new BatchOperation<MarshalledValue<K, C>, MarshalledValue<E, C>, R>(operation));
  207. }
  208. private MarshalledValue<K, C> marshalKey(K key) {
  209. try {
  210. return this.keyFactory.createMarshalledValue(key);
  211. } catch (IOException e) {
  212. throw InfinispanEjbMessages.MESSAGES.serializationFailure(e, key);
  213. }
  214. }
  215. private K unmarshalKey(MarshalledValue<K, C> key) {
  216. try {
  217. return key.get(this.context);
  218. } catch (Exception e) {
  219. throw InfinispanEjbMessages.MESSAGES.deserializationFailure(e, key);
  220. }
  221. }
  222. private MarshalledValue<E, C> marshalEntry(E value) {
  223. try {
  224. return this.valueFactory.createMarshalledValue(value);
  225. } catch (IOException e) {
  226. throw InfinispanEjbMessages.MESSAGES.serializationFailure(e, value.getId());
  227. }
  228. }
  229. private E unmarshalEntry(K id, MarshalledValue<E, C> value) {
  230. if (value == null) return null;
  231. try {
  232. return value.get(this.context);
  233. } catch (Exception e) {
  234. throw InfinispanEjbMessages.MESSAGES.deserializationFailure(e, id);
  235. }
  236. }
  237. private LockResult acquireSessionOwnership(MarshalledValue<K, C> key, boolean newLock) {
  238. if (this.lockManager == null) return null;
  239. Serializable lockKey = this.lockKeyFactory.createLockKey(key);
  240. this.trace("Acquiring %slock on %s", newLock ? "new " : "", lockKey);
  241. long timeout = this.cache.getCacheConfiguration().locking().lockAcquisitionTimeout();
  242. try {
  243. LockResult result = this.lockManager.lock(lockKey, timeout, newLock);
  244. this.trace("Lock acquired (%s) on %s", result, lockKey);
  245. return result;
  246. } catch (TimeoutException e) {
  247. throw InfinispanEjbMessages.MESSAGES.lockAcquisitionTimeout(lockKey, timeout);
  248. } catch (InterruptedException e) {
  249. Thread.currentThread().interrupt();
  250. throw InfinispanEjbMessages.MESSAGES.lockAcquisitionInterruption(e, lockKey);
  251. }
  252. }
  253. private void releaseSessionOwnership(MarshalledValue<K, C> key, boolean remove) {
  254. if (this.lockManager != null) {
  255. Serializable lockKey = this.lockKeyFactory.createLockKey(key);
  256. this.trace("Releasing %slock on %s", remove ? "and removing " : "", lockKey);
  257. this.lockManager.unlock(lockKey, remove);
  258. this.trace("Released %slock on %s", remove ? "and removed " : "", lockKey);
  259. }
  260. }
  261. @Override
  262. public void passivate(E entry) {
  263. final MarshalledValue<K, C> key = this.marshalKey(entry.getId());
  264. Operation<Void> operation = new Operation<Void>() {
  265. @Override
  266. public Void invoke(Cache<MarshalledValue<K, C>, MarshalledValue<E, C>> cache) {
  267. cache.evict(key);
  268. return null;
  269. }
  270. };
  271. this.invoker.invoke(this.cache, operation);
  272. }
  273. @Override
  274. public boolean isClustered() {
  275. return this.clustered;
  276. }
  277. @Override
  278. public boolean isCompatibleWith(GroupCompatibilityChecker other) {
  279. if (other instanceof InfinispanBackingCacheEntryStore) {
  280. InfinispanBackingCacheEntryStore<?, ?, ?, ?> store = (InfinispanBackingCacheEntryStore<?, ?, ?, ?>) other;
  281. return this.cache.getCacheManager() == store.cache.getCacheManager();
  282. }
  283. return false;
  284. }
  285. @CacheEntryActivated
  286. public void activated(CacheEntryActivatedEvent<MarshalledValue<K, C>, MarshalledValue<E, C>> event) {
  287. if ((this.passivationManager != null) && !event.isPre()){
  288. K key = this.unmarshalKey(event.getKey());
  289. this.trace("activated(%s)", key);
  290. this.passivationManager.postActivate(this.unmarshalEntry(key, event.getValue()));
  291. }
  292. }
  293. @CacheEntryPassivated
  294. public void passivated(CacheEntryPassivatedEvent<MarshalledValue<K, C>, MarshalledValue<E, C>> event) {
  295. if ((this.passivationManager != null) && event.isPre()) {
  296. K key = this.unmarshalKey(event.getKey());
  297. this.trace("passivated(%s)", key);
  298. this.passivationManager.prePassivate(this.unmarshalEntry(key, event.getValue()));
  299. }
  300. }
  301. abstract class Operation<R> implements CacheInvoker.Operation<MarshalledValue<K, C>, MarshalledValue<E, C>, R> {
  302. }
  303. private void trace(String message, Object... args) {
  304. if (this.log.isTraceEnabled()) {
  305. this.log.tracef(message, args);
  306. }
  307. }
  308. }