Search in sources :

Example 1 with Cache

use of org.infinispan.Cache in project hibernate-orm by hibernate.

the class AbstractRegionAccessStrategyTest method evictOrRemoveAllTest.

protected void evictOrRemoveAllTest(final boolean evict) throws Exception {
    final Object KEY = generateNextKey();
    assertEquals(0, localRegion.getCache().size());
    assertEquals(0, remoteRegion.getCache().size());
    SharedSessionContractImplementor s1 = mockedSession();
    assertNull("local is clean", localAccessStrategy.get(s1, KEY, s1.getTimestamp()));
    SharedSessionContractImplementor s2 = mockedSession();
    assertNull("remote is clean", remoteAccessStrategy.get(s2, KEY, s2.getTimestamp()));
    CountDownLatch localPutFromLoadLatch = expectRemotePutFromLoad(remoteRegion.getCache(), localRegion.getCache());
    CountDownLatch remotePutFromLoadLatch = expectRemotePutFromLoad(localRegion.getCache(), remoteRegion.getCache());
    SharedSessionContractImplementor s3 = mockedSession();
    localAccessStrategy.putFromLoad(s3, KEY, VALUE1, s3.getTimestamp(), 1);
    SharedSessionContractImplementor s5 = mockedSession();
    remoteAccessStrategy.putFromLoad(s5, KEY, VALUE1, s5.getTimestamp(), 1);
    // putFromLoad is applied on local node synchronously, but if there's a concurrent update
    // from the other node it can silently fail when acquiring the loc . Then we could try to read
    // before the update is fully applied.
    assertTrue(localPutFromLoadLatch.await(1, TimeUnit.SECONDS));
    assertTrue(remotePutFromLoadLatch.await(1, TimeUnit.SECONDS));
    SharedSessionContractImplementor s4 = mockedSession();
    SharedSessionContractImplementor s6 = mockedSession();
    assertEquals(VALUE1, localAccessStrategy.get(s4, KEY, s4.getTimestamp()));
    assertEquals(VALUE1, remoteAccessStrategy.get(s6, KEY, s6.getTimestamp()));
    CountDownLatch endInvalidationLatch;
    if (invalidation && !evict) {
        // removeAll causes transactional remove commands which trigger EndInvalidationCommands on the remote side
        // if the cache is non-transactional, PutFromLoadValidator.registerRemoteInvalidations cannot find
        // current session nor register tx synchronization, so it falls back to simple InvalidationCommand.
        endInvalidationLatch = new CountDownLatch(1);
        if (transactional) {
            PutFromLoadValidator originalValidator = PutFromLoadValidator.removeFromCache(remoteRegion.getCache());
            assertEquals(PutFromLoadValidator.class, originalValidator.getClass());
            PutFromLoadValidator mockValidator = spy(originalValidator);
            doAnswer(invocation -> {
                try {
                    return invocation.callRealMethod();
                } finally {
                    endInvalidationLatch.countDown();
                }
            }).when(mockValidator).endInvalidatingKey(any(), any());
            PutFromLoadValidator.addToCache(remoteRegion.getCache(), mockValidator);
            cleanup.add(() -> {
                PutFromLoadValidator.removeFromCache(remoteRegion.getCache());
                PutFromLoadValidator.addToCache(remoteRegion.getCache(), originalValidator);
            });
        } else {
            ExpectingInterceptor.get(remoteRegion.getCache()).when((ctx, cmd) -> cmd instanceof InvalidateCommand).countDown(endInvalidationLatch);
            cleanup.add(() -> ExpectingInterceptor.cleanup(remoteRegion.getCache()));
        }
    } else {
        endInvalidationLatch = new CountDownLatch(0);
    }
    withTx(localEnvironment, mockedSession(), () -> {
        if (evict) {
            localAccessStrategy.evictAll();
        } else {
            SoftLock softLock = localAccessStrategy.lockRegion();
            localAccessStrategy.removeAll();
            localAccessStrategy.unlockRegion(softLock);
        }
        return null;
    });
    SharedSessionContractImplementor s7 = mockedSession();
    assertNull(localAccessStrategy.get(s7, KEY, s7.getTimestamp()));
    assertEquals(0, localRegion.getCache().size());
    SharedSessionContractImplementor s8 = mockedSession();
    assertNull(remoteAccessStrategy.get(s8, KEY, s8.getTimestamp()));
    assertEquals(0, remoteRegion.getCache().size());
    // Wait for async propagation of EndInvalidationCommand before executing naked put
    assertTrue(endInvalidationLatch.await(1, TimeUnit.SECONDS));
    TIME_SERVICE.advance(1);
    CountDownLatch lastPutFromLoadLatch = expectRemotePutFromLoad(remoteRegion.getCache(), localRegion.getCache());
    // Test whether the get above messes up the optimistic version
    SharedSessionContractImplementor s9 = mockedSession();
    assertTrue(remoteAccessStrategy.putFromLoad(s9, KEY, VALUE1, s9.getTimestamp(), 1));
    SharedSessionContractImplementor s10 = mockedSession();
    assertEquals(VALUE1, remoteAccessStrategy.get(s10, KEY, s10.getTimestamp()));
    assertEquals(1, remoteRegion.getCache().size());
    assertTrue(lastPutFromLoadLatch.await(1, TimeUnit.SECONDS));
    SharedSessionContractImplementor s11 = mockedSession();
    assertEquals((isUsingInvalidation() ? null : VALUE1), localAccessStrategy.get(s11, KEY, s11.getTimestamp()));
    SharedSessionContractImplementor s12 = mockedSession();
    assertEquals(VALUE1, remoteAccessStrategy.get(s12, KEY, s12.getTimestamp()));
}
Also used : Arrays(java.util.Arrays) Connection(java.sql.Connection) BatchModeJtaPlatform(org.hibernate.test.cache.infinispan.util.BatchModeJtaPlatform) Cache(org.infinispan.Cache) Transaction(org.hibernate.Transaction) AdvancedCache(org.infinispan.AdvancedCache) After(org.junit.After) Mockito.doAnswer(org.mockito.Mockito.doAnswer) CacheDataDescriptionImpl(org.hibernate.cache.internal.CacheDataDescriptionImpl) TestingUtil(org.infinispan.test.TestingUtil) AccessType(org.hibernate.cache.spi.access.AccessType) Predicate(java.util.function.Predicate) TombstoneUpdate(org.hibernate.cache.infinispan.util.TombstoneUpdate) JdbcResourceTransactionAccess(org.hibernate.resource.transaction.backend.jdbc.spi.JdbcResourceTransactionAccess) TestSynchronization(org.hibernate.test.cache.infinispan.util.TestSynchronization) Matchers.any(org.mockito.Matchers.any) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) SoftLock(org.hibernate.cache.spi.access.SoftLock) JdbcSessionOwner(org.hibernate.resource.jdbc.spi.JdbcSessionOwner) AfterClassOnce(org.hibernate.testing.AfterClassOnce) FutureUpdate(org.hibernate.cache.infinispan.util.FutureUpdate) PutKeyValueCommand(org.infinispan.commands.write.PutKeyValueCommand) TransactionImpl(org.hibernate.engine.transaction.internal.TransactionImpl) PutFromLoadValidator(org.hibernate.cache.infinispan.access.PutFromLoadValidator) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) Mockito.mock(org.mockito.Mockito.mock) JdbcConnectionAccess(org.hibernate.engine.jdbc.connections.spi.JdbcConnectionAccess) TestResourceTracker(org.infinispan.test.fwk.TestResourceTracker) Logger(org.jboss.logging.Logger) TransactionCoordinator(org.hibernate.resource.transaction.spi.TransactionCoordinator) Session(org.hibernate.Session) Caches(org.hibernate.cache.infinispan.util.Caches) StandardServiceRegistryBuilder(org.hibernate.boot.registry.StandardServiceRegistryBuilder) Mockito.spy(org.mockito.Mockito.spy) ArrayList(java.util.ArrayList) RegionAccessStrategy(org.hibernate.cache.spi.access.RegionAccessStrategy) SQLException(java.sql.SQLException) TestTimeService(org.hibernate.test.cache.infinispan.util.TestTimeService) RollbackException(javax.transaction.RollbackException) TransactionCoordinatorOwner(org.hibernate.resource.transaction.spi.TransactionCoordinatorOwner) ExpectingInterceptor(org.hibernate.test.cache.infinispan.util.ExpectingInterceptor) ComparableComparator(org.hibernate.internal.util.compare.ComparableComparator) BatchModeTransactionCoordinator(org.hibernate.test.cache.infinispan.util.BatchModeTransactionCoordinator) JdbcResourceTransactionMock(org.hibernate.test.cache.infinispan.util.JdbcResourceTransactionMock) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) AssertionFailedError(junit.framework.AssertionFailedError) JdbcServices(org.hibernate.engine.jdbc.spi.JdbcServices) JdbcSessionContext(org.hibernate.resource.jdbc.spi.JdbcSessionContext) TestInfinispanRegionFactory(org.hibernate.test.cache.infinispan.util.TestInfinispanRegionFactory) Mockito.when(org.mockito.Mockito.when) BaseRegion(org.hibernate.cache.infinispan.impl.BaseRegion) ServiceRegistry(org.hibernate.service.ServiceRegistry) TimeUnit(java.util.concurrent.TimeUnit) CacheDataDescription(org.hibernate.cache.spi.CacheDataDescription) InvalidateCommand(org.infinispan.commands.write.InvalidateCommand) Assert.assertNull(org.junit.Assert.assertNull) SystemException(javax.transaction.SystemException) JdbcResourceLocalTransactionCoordinatorBuilderImpl(org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorBuilderImpl) SqlExceptionHelper(org.hibernate.engine.jdbc.spi.SqlExceptionHelper) BeforeClassOnce(org.hibernate.testing.BeforeClassOnce) Assert.assertEquals(org.junit.Assert.assertEquals) PutFromLoadValidator(org.hibernate.cache.infinispan.access.PutFromLoadValidator) SharedSessionContractImplementor(org.hibernate.engine.spi.SharedSessionContractImplementor) CountDownLatch(java.util.concurrent.CountDownLatch) InvalidateCommand(org.infinispan.commands.write.InvalidateCommand) SoftLock(org.hibernate.cache.spi.access.SoftLock)

Example 2 with Cache

use of org.infinispan.Cache in project hibernate-orm by hibernate.

the class JndiRegionFactoryTest method testRedeployment.

@Test
public void testRedeployment() throws Exception {
    addEntityCheckCache(sessionFactory());
    bindToJndi = false;
    rebuildSessionFactory();
    addEntityCheckCache(sessionFactory());
    JndiInfinispanRegionFactory regionFactory = (JndiInfinispanRegionFactory) sessionFactory().getSettings().getRegionFactory();
    Cache cache = regionFactory.getCacheManager().getCache(Item.class.getName());
    assertEquals(ComponentStatus.RUNNING, cache.getStatus());
}
Also used : Item(org.hibernate.test.cache.infinispan.functional.entities.Item) JndiInfinispanRegionFactory(org.hibernate.cache.infinispan.JndiInfinispanRegionFactory) Cache(org.infinispan.Cache) Test(org.junit.Test)

Example 3 with Cache

use of org.infinispan.Cache in project wildfly by wildfly.

the class CacheRegistry method topologyChanged.

@TopologyChanged
public void topologyChanged(TopologyChangedEvent<Node, Map.Entry<K, V>> event) {
    if (event.isPre())
        return;
    ConsistentHash previousHash = event.getConsistentHashAtStart();
    List<Address> previousMembers = previousHash.getMembers();
    ConsistentHash hash = event.getConsistentHashAtEnd();
    List<Address> members = hash.getMembers();
    Address localAddress = event.getCache().getCacheManager().getAddress();
    // Determine which nodes have left the cache view
    Set<Address> addresses = new HashSet<>(previousMembers);
    addresses.removeAll(members);
    try {
        this.topologyChangeExecutor.submit(() -> {
            if (!addresses.isEmpty()) {
                // We're only interested in the entries for which we are the primary owner
                List<Node> nodes = addresses.stream().filter(address -> hash.locatePrimaryOwner(address).equals(localAddress)).map(address -> this.factory.createNode(address)).collect(Collectors.toList());
                if (!nodes.isEmpty()) {
                    Cache<Node, Map.Entry<K, V>> cache = this.cache.getAdvancedCache().withFlags(Flag.FORCE_SYNCHRONOUS);
                    Map<K, V> removed = new HashMap<>();
                    try (Batch batch = this.batcher.createBatch()) {
                        for (Node node : nodes) {
                            Map.Entry<K, V> old = cache.remove(node);
                            if (old != null) {
                                removed.put(old.getKey(), old.getValue());
                            }
                        }
                    } catch (CacheException e) {
                        ClusteringServerLogger.ROOT_LOGGER.registryPurgeFailed(e, this.cache.getCacheManager().toString(), this.cache.getName(), nodes);
                    }
                    // Invoke listeners outside above tx context
                    if (!removed.isEmpty()) {
                        this.notifyListeners(Event.Type.CACHE_ENTRY_REMOVED, removed);
                    }
                }
            } else {
                // This is a merge after cluster split: re-populate the cache registry with lost registry entries
                if (!previousMembers.contains(localAddress)) {
                    // If this node is not a member at merge start, its mapping is lost and needs to be recreated and listeners notified
                    try {
                        this.populateRegistry();
                        // Local cache events do not trigger notifications
                        this.notifyListeners(Event.Type.CACHE_ENTRY_CREATED, this.entry);
                    } catch (CacheException e) {
                        ClusteringServerLogger.ROOT_LOGGER.failedToRestoreLocalRegistryEntry(e, this.cache.getCacheManager().toString(), this.cache.getName());
                    }
                }
            }
        });
    } catch (RejectedExecutionException e) {
    // Executor was shutdown
    }
}
Also used : CacheEntryRemoved(org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved) TopologyChanged(org.infinispan.notifications.cachelistener.annotation.TopologyChanged) ClusteringLogger(org.jboss.as.clustering.logging.ClusteringLogger) HashMap(java.util.HashMap) Cache(org.infinispan.Cache) HashSet(java.util.HashSet) ClassLoaderThreadFactory(org.wildfly.clustering.service.concurrent.ClassLoaderThreadFactory) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) Map(java.util.Map) CacheEntryModified(org.infinispan.notifications.cachelistener.annotation.CacheEntryModified) CacheEntryRemovedEvent(org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent) ThreadFactory(java.util.concurrent.ThreadFactory) NodeFactory(org.wildfly.clustering.group.NodeFactory) ExecutorService(java.util.concurrent.ExecutorService) Address(org.infinispan.remoting.transport.Address) JBossThreadFactory(org.jboss.threads.JBossThreadFactory) CacheException(org.infinispan.commons.CacheException) ConsistentHash(org.infinispan.distribution.ch.ConsistentHash) Batcher(org.wildfly.clustering.ee.Batcher) Registry(org.wildfly.clustering.registry.Registry) Group(org.wildfly.clustering.group.Group) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) PrivilegedAction(java.security.PrivilegedAction) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) TopologyChangedEvent(org.infinispan.notifications.cachelistener.event.TopologyChangedEvent) TimeUnit(java.util.concurrent.TimeUnit) CacheEntryCreated(org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated) AbstractMap(java.util.AbstractMap) List(java.util.List) WildFlySecurityManager(org.wildfly.security.manager.WildFlySecurityManager) Flag(org.infinispan.context.Flag) KeyFilter(org.infinispan.filter.KeyFilter) CacheEntryEvent(org.infinispan.notifications.cachelistener.event.CacheEntryEvent) Batch(org.wildfly.clustering.ee.Batch) Event(org.infinispan.notifications.cachelistener.event.Event) Node(org.wildfly.clustering.group.Node) ClusteringServerLogger(org.wildfly.clustering.server.logging.ClusteringServerLogger) Collections(java.util.Collections) ConsistentHash(org.infinispan.distribution.ch.ConsistentHash) Address(org.infinispan.remoting.transport.Address) HashMap(java.util.HashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) CacheException(org.infinispan.commons.CacheException) Node(org.wildfly.clustering.group.Node) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) Batch(org.wildfly.clustering.ee.Batch) HashMap(java.util.HashMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) AbstractMap(java.util.AbstractMap) HashSet(java.util.HashSet) TopologyChanged(org.infinispan.notifications.cachelistener.annotation.TopologyChanged)

Example 4 with Cache

use of org.infinispan.Cache in project wildfly by wildfly.

the class KeyAffinityServiceFactoryBuilder method build.

@Override
public ServiceBuilder<KeyAffinityServiceFactory> build(ServiceTarget target) {
    int bufferSize = this.bufferSize;
    Function<ExecutorService, KeyAffinityServiceFactory> mapper = executor -> new KeyAffinityServiceFactory() {

        @Override
        public <K> KeyAffinityService<K> createService(Cache<K, ?> cache, KeyGenerator<K> generator) {
            CacheMode mode = cache.getCacheConfiguration().clustering().cacheMode();
            return mode.isDistributed() || mode.isReplicated() ? new KeyAffinityServiceImpl<>(executor, cache, generator, bufferSize, Collections.singleton(cache.getCacheManager().getAddress()), false) : new SimpleKeyAffinityService<>(generator);
        }
    };
    Supplier<ExecutorService> supplier = () -> {
        ThreadGroup threadGroup = new ThreadGroup("KeyAffinityService ThreadGroup");
        String namePattern = "KeyAffinityService Thread Pool -- %t";
        PrivilegedAction<ThreadFactory> action = () -> new JBossThreadFactory(threadGroup, Boolean.FALSE, null, namePattern, null, null);
        return Executors.newCachedThreadPool(doPrivileged(action));
    };
    Service<KeyAffinityServiceFactory> service = new SuppliedValueService<>(mapper, supplier, ExecutorService::shutdown);
    return new AsynchronousServiceBuilder<>(this.getServiceName(), service).startSynchronously().build(target).setInitialMode(ServiceController.Mode.ON_DEMAND);
}
Also used : Service(org.jboss.msc.service.Service) AccessController.doPrivileged(java.security.AccessController.doPrivileged) Cache(org.infinispan.Cache) Function(java.util.function.Function) Supplier(java.util.function.Supplier) KeyGenerator(org.infinispan.affinity.KeyGenerator) SuppliedValueService(org.wildfly.clustering.service.SuppliedValueService) KeyAffinityService(org.infinispan.affinity.KeyAffinityService) KeyAffinityServiceFactory(org.wildfly.clustering.infinispan.spi.affinity.KeyAffinityServiceFactory) ServiceTarget(org.jboss.msc.service.ServiceTarget) ThreadFactory(java.util.concurrent.ThreadFactory) ExecutorService(java.util.concurrent.ExecutorService) Address(org.infinispan.remoting.transport.Address) JBossThreadFactory(org.jboss.threads.JBossThreadFactory) PathAddress(org.jboss.as.controller.PathAddress) ServiceBuilder(org.jboss.msc.service.ServiceBuilder) AsynchronousServiceBuilder(org.wildfly.clustering.service.AsynchronousServiceBuilder) PrivilegedAction(java.security.PrivilegedAction) Executors(java.util.concurrent.Executors) KeyAffinityServiceImpl(org.infinispan.affinity.impl.KeyAffinityServiceImpl) ServiceController(org.jboss.msc.service.ServiceController) CacheMode(org.infinispan.configuration.cache.CacheMode) ServiceName(org.jboss.msc.service.ServiceName) Collections(java.util.Collections) Builder(org.wildfly.clustering.service.Builder) JBossThreadFactory(org.jboss.threads.JBossThreadFactory) CacheMode(org.infinispan.configuration.cache.CacheMode) KeyAffinityServiceFactory(org.wildfly.clustering.infinispan.spi.affinity.KeyAffinityServiceFactory) PrivilegedAction(java.security.PrivilegedAction) ExecutorService(java.util.concurrent.ExecutorService) KeyGenerator(org.infinispan.affinity.KeyGenerator) Cache(org.infinispan.Cache) SuppliedValueService(org.wildfly.clustering.service.SuppliedValueService)

Example 5 with Cache

use of org.infinispan.Cache in project keycloak by keycloak.

the class InfinispanStickySessionEncoderProvider method getRoute.

private String getRoute(String sessionId) {
    InfinispanConnectionProvider ispnProvider = session.getProvider(InfinispanConnectionProvider.class);
    Cache cache = ispnProvider.getCache(InfinispanConnectionProvider.AUTHENTICATION_SESSIONS_CACHE_NAME);
    return InfinispanUtil.getTopologyInfo(session).getRouteName(cache, sessionId);
}
Also used : InfinispanConnectionProvider(org.keycloak.connections.infinispan.InfinispanConnectionProvider) Cache(org.infinispan.Cache)

Aggregations

Cache (org.infinispan.Cache)31 RemoteCache (org.infinispan.client.hotrod.RemoteCache)10 Test (org.junit.Test)8 Map (java.util.Map)7 TimeUnit (java.util.concurrent.TimeUnit)6 InfinispanConnectionProvider (org.keycloak.connections.infinispan.InfinispanConnectionProvider)6 Collections (java.util.Collections)5 HashMap (java.util.HashMap)5 ServiceName (org.jboss.msc.service.ServiceName)5 KeycloakSession (org.keycloak.models.KeycloakSession)5 Set (java.util.Set)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 ExecutorService (java.util.concurrent.ExecutorService)4 Function (java.util.function.Function)4 BasicCache (org.infinispan.commons.api.BasicCache)4 SessionEntityWrapper (org.keycloak.models.sessions.infinispan.changes.SessionEntityWrapper)4 Serializable (java.io.Serializable)3 AbstractMap (java.util.AbstractMap)3 Iterator (java.util.Iterator)3 Flag (org.infinispan.context.Flag)3