Search in sources :

Example 31 with Cache

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

the class CacheExpirationTest method testCacheExpiration.

@Test
public void testCacheExpiration() throws Exception {
    log.debug("Put two events to the main cache");
    inComittedTransaction(session -> {
        InfinispanConnectionProvider provider = session.getProvider(InfinispanConnectionProvider.class);
        Cache<String, Object> cache = provider.getCache(InfinispanConnectionProvider.WORK_CACHE_NAME);
        cache.entrySet().stream().filter(me -> me.getValue() instanceof AuthenticationSessionAuthNoteUpdateEvent).forEach((c, me) -> c.remove(me.getKey()));
        cache.put("1-2", AuthenticationSessionAuthNoteUpdateEvent.create("g1", "p1", "r1", Collections.emptyMap()), 20000, TimeUnit.MILLISECONDS);
        cache.put("1-2-3", AuthenticationSessionAuthNoteUpdateEvent.create("g2", "p2", "r2", Collections.emptyMap()), 20000, TimeUnit.MILLISECONDS);
    });
    assumeThat("jmap output format unsupported", getNumberOfInstancesOfClass(AuthenticationSessionAuthNoteUpdateEvent.class), notNullValue());
    // Ensure that instance counting works as expected, there should be at least two instances in memory now.
    // Infinispan server is decoding the client request before processing the request at the cache level,
    // therefore there are sometimes three instances of AuthenticationSessionAuthNoteUpdateEvent class in the memory
    assertThat(getNumberOfInstancesOfClass(AuthenticationSessionAuthNoteUpdateEvent.class), greaterThanOrEqualTo(2));
    log.debug("Starting other nodes and see that they join, receive the data and have their data expired");
    AtomicInteger completedTests = new AtomicInteger(0);
    inIndependentFactories(NUM_EXTRA_FACTORIES, 5 * 60, () -> {
        log.debug("Joining the cluster");
        inComittedTransaction(session -> {
            InfinispanConnectionProvider provider = session.getProvider(InfinispanConnectionProvider.class);
            Cache<String, Object> cache = provider.getCache(InfinispanConnectionProvider.WORK_CACHE_NAME);
            log.debug("Waiting for caches to join the cluster");
            do {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException(ex);
                }
            } while (!cache.getAdvancedCache().getDistributionManager().isJoinComplete());
            String site = CONFIG.scope("connectionsInfinispan", "default").get("siteName");
            log.debug("Cluster joined " + site);
            log.debug("Waiting for cache to receive the two elements within the cluster");
            do {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException(ex);
                }
            } while (cache.entrySet().stream().filter(me -> me.getValue() instanceof AuthenticationSessionAuthNoteUpdateEvent).count() != 2);
            // access the items in the local cache in the different site (site-2) in order to fetch them from the remote cache
            assertThat(cache.get("1-2"), notNullValue());
            assertThat(cache.get("1-2-3"), notNullValue());
            // this is testing for a situation where an expiration lifespan configuration was missing in a replicated cache;
            // the elements were no longer seen in the cache, still they weren't garbage collected.
            // we must not look into the cache as that would trigger expiration explicitly.
            // original issue: https://issues.redhat.com/browse/KEYCLOAK-18518
            log.debug("Waiting for garbage collection to collect the entries across all caches in JVM");
            do {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException(ex);
                }
            } while (getNumberOfInstancesOfClass(AuthenticationSessionAuthNoteUpdateEvent.class) != 0);
            completedTests.incrementAndGet();
            log.debug("Test completed");
        });
    });
    assertThat(completedTests.get(), is(NUM_EXTRA_FACTORIES));
}
Also used : InfinispanConnectionProvider(org.keycloak.connections.infinispan.InfinispanConnectionProvider) Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) Assume.assumeThat(org.junit.Assume.assumeThat) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) Test(org.junit.Test) KeycloakModelTest(org.keycloak.testsuite.model.KeycloakModelTest) IOException(java.io.IOException) Cache(org.infinispan.Cache) InputStreamReader(java.io.InputStreamReader) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) Matcher(java.util.regex.Matcher) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Assume(org.junit.Assume) AuthenticationSessionAuthNoteUpdateEvent(org.keycloak.models.cache.infinispan.events.AuthenticationSessionAuthNoteUpdateEvent) RequireProvider(org.keycloak.testsuite.model.RequireProvider) Matchers.is(org.hamcrest.Matchers.is) BufferedReader(java.io.BufferedReader) ManagementFactory(java.lang.management.ManagementFactory) Pattern(java.util.regex.Pattern) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Collections(java.util.Collections) AuthenticationSessionAuthNoteUpdateEvent(org.keycloak.models.cache.infinispan.events.AuthenticationSessionAuthNoteUpdateEvent) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) InfinispanConnectionProvider(org.keycloak.connections.infinispan.InfinispanConnectionProvider) Test(org.junit.Test) KeycloakModelTest(org.keycloak.testsuite.model.KeycloakModelTest)

Example 32 with Cache

use of org.infinispan.Cache in project partyline by Commonjava.

the class InfinispanJFS method getMetadata.

FileMeta getMetadata(final File target, final LocalLockOwner owner) throws IOException {
    String path = target.getAbsolutePath();
    return lockManager.lockAnd(path, (key, opLock) -> {
        FileMeta meta = null;
        TransactionManager transactionManager = metadataCache.getAdvancedCache().getTransactionManager();
        try {
            transactionManager.begin();
            meta = metadataCache.computeIfAbsent(path, (p) -> new FileMeta(p, target.isDirectory(), this.blockSize));
            LockLevel currentLockLevel = meta.getLockLevel(this.nodeKey);
            // Only update the cache if the lock level changed
            if (currentLockLevel == null || currentLockLevel != owner.getLockLevel()) {
                meta.setLock(this.nodeKey, owner.getLockLevel());
                metadataCache.put(path, meta);
            }
            transactionManager.commit();
        } catch (Exception e) {
            logger.error("Failed to execute in transaction. Rolling back. Path: " + path, e);
            try {
                transactionManager.rollback();
            } catch (SystemException e1) {
                logger.error("SystemException during transaction rollback involving path: " + path, e1);
            }
        }
        return meta;
    });
}
Also used : SignallingLocker(org.commonjava.cdi.util.weft.SignallingLocker) JoinableFilesystem(org.commonjava.util.partyline.spi.JoinableFilesystem) LockLevel(org.commonjava.util.partyline.lock.LockLevel) LoggerFactory(org.slf4j.LoggerFactory) StreamCallbacks(org.commonjava.util.partyline.callback.StreamCallbacks) Cache(org.infinispan.Cache) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) FileMeta(org.commonjava.util.partyline.impl.infinispan.model.FileMeta) RollbackException(javax.transaction.RollbackException) LocalLockOwner(org.commonjava.util.partyline.lock.local.LocalLockOwner) CacheEntryModified(org.infinispan.notifications.cachelistener.annotation.CacheEntryModified) JoinableFile(org.commonjava.util.partyline.spi.JoinableFile) UnlockStatus(org.commonjava.util.partyline.lock.UnlockStatus) Listener(org.infinispan.notifications.Listener) Logger(org.slf4j.Logger) HeuristicRollbackException(javax.transaction.HeuristicRollbackException) PartylineException(org.commonjava.util.partyline.PartylineException) IOException(java.io.IOException) File(java.io.File) SignallingLock(org.commonjava.cdi.util.weft.SignallingLock) NotSupportedException(javax.transaction.NotSupportedException) CacheEntryCreated(org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated) List(java.util.List) CacheEntryEvent(org.infinispan.notifications.cachelistener.event.CacheEntryEvent) SystemException(javax.transaction.SystemException) FileBlock(org.commonjava.util.partyline.impl.infinispan.model.FileBlock) HeuristicMixedException(javax.transaction.HeuristicMixedException) TransactionManager(javax.transaction.TransactionManager) Collections(java.util.Collections) SystemException(javax.transaction.SystemException) TransactionManager(javax.transaction.TransactionManager) LockLevel(org.commonjava.util.partyline.lock.LockLevel) FileMeta(org.commonjava.util.partyline.impl.infinispan.model.FileMeta) RollbackException(javax.transaction.RollbackException) HeuristicRollbackException(javax.transaction.HeuristicRollbackException) PartylineException(org.commonjava.util.partyline.PartylineException) IOException(java.io.IOException) NotSupportedException(javax.transaction.NotSupportedException) SystemException(javax.transaction.SystemException) HeuristicMixedException(javax.transaction.HeuristicMixedException)

Aggregations

Cache (org.infinispan.Cache)32 RemoteCache (org.infinispan.client.hotrod.RemoteCache)10 Test (org.junit.Test)8 Map (java.util.Map)7 Collections (java.util.Collections)6 TimeUnit (java.util.concurrent.TimeUnit)6 InfinispanConnectionProvider (org.keycloak.connections.infinispan.InfinispanConnectionProvider)6 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 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 List (java.util.List)3 ExecutorService (java.util.concurrent.ExecutorService)3