Search in sources :

Example 6 with HotRodClientException

use of org.infinispan.client.hotrod.exceptions.HotRodClientException in project keycloak by keycloak.

the class ConcurrencyJDGCachePutTest method getClusterStartupTime.

public static int getClusterStartupTime(Cache<String, Integer> cache, String cacheKey, EntryInfo wrapper, int myThreadId) {
    Integer startupTime = myThreadId == 1 ? Integer.valueOf(cacheKey.substring(4)) : Integer.valueOf(cacheKey.substring(4)) * 2;
    // Concurrency doesn't work correctly with this
    // Integer existingClusterStartTime = (Integer) cache.putIfAbsent(cacheKey, startupTime);
    // Concurrency works fine with this
    RemoteCache remoteCache = cache.getAdvancedCache().getComponentRegistry().getComponent(PersistenceManager.class).getStores(RemoteStore.class).iterator().next().getRemoteCache();
    Integer existingClusterStartTime = null;
    for (int i = 0; i < 10; i++) {
        try {
            existingClusterStartTime = (Integer) remoteCache.withFlags(Flag.FORCE_RETURN_VALUE).putIfAbsent(cacheKey, startupTime);
            break;
        } catch (HotRodClientException ce) {
            if (i == 9) {
                throw ce;
            // break;
            } else {
                wrapper.exceptions.incrementAndGet();
                System.err.println("Exception: i=" + i + " for key: " + cacheKey + " and myThreadId: " + myThreadId);
            }
        }
    }
    if (existingClusterStartTime == null) // || startupTime.equals(remoteCache.get(cacheKey))
    {
        wrapper.successfulInitializations.incrementAndGet();
        return startupTime;
    } else {
        wrapper.failedInitializations.incrementAndGet();
        return existingClusterStartTime;
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) RemoteCache(org.infinispan.client.hotrod.RemoteCache) HotRodClientException(org.infinispan.client.hotrod.exceptions.HotRodClientException) RemoteStore(org.infinispan.persistence.remote.RemoteStore)

Example 7 with HotRodClientException

use of org.infinispan.client.hotrod.exceptions.HotRodClientException in project keycloak by keycloak.

the class ConcurrencyJDGOfflineBackupsTest method main.

public static void main(String[] args) throws Exception {
    Cache<String, SessionEntityWrapper<UserSessionEntity>> cache1 = createManager(1).getCache(InfinispanConnectionProvider.USER_SESSION_CACHE_NAME);
    try {
        // Create initial item
        UserSessionEntity session = new UserSessionEntity();
        session.setId("123");
        session.setRealmId("foo");
        session.setBrokerSessionId("!23123123");
        session.setBrokerUserId(null);
        session.setUser("foo");
        session.setLoginUsername("foo");
        session.setIpAddress("123.44.143.178");
        session.setStarted(Time.currentTime());
        session.setLastSessionRefresh(Time.currentTime());
        // AuthenticatedClientSessionEntity clientSession = new AuthenticatedClientSessionEntity();
        // clientSession.setAuthMethod("saml");
        // clientSession.setAction("something");
        // clientSession.setTimestamp(1234);
        // clientSession.setProtocolMappers(new HashSet<>(Arrays.asList("mapper1", "mapper2")));
        // clientSession.setRoles(new HashSet<>(Arrays.asList("role1", "role2")));
        // session.getAuthenticatedClientSessions().put(CLIENT_1_UUID.toString(), clientSession.getId());
        SessionEntityWrapper<UserSessionEntity> wrappedSession = new SessionEntityWrapper<>(session);
        // Some dummy testing of remoteStore behaviour
        logger.info("Before put");
        AtomicInteger successCount = new AtomicInteger(0);
        AtomicInteger errorsCount = new AtomicInteger(0);
        for (int i = 0; i < 100; i++) {
            try {
                cache1.getAdvancedCache().withFlags(// will still invoke remoteStore . Just doesn't propagate to cluster
                Flag.CACHE_MODE_LOCAL).put("123", wrappedSession);
                successCount.incrementAndGet();
                Thread.sleep(1000);
                logger.infof("Success in the iteration: %d", i);
            } catch (HotRodClientException hrce) {
                logger.errorf("Failed to put the item in the iteration: %d ", i);
                errorsCount.incrementAndGet();
            }
        }
        logger.infof("SuccessCount: %d, ErrorsCount: %d", successCount.get(), errorsCount.get());
    // logger.info("After put");
    // 
    // cache1.replace("123", wrappedSession);
    // 
    // logger.info("After replace");
    // 
    // cache1.get("123");
    // 
    // logger.info("After cache1.get");
    // cache2.get("123");
    // 
    // logger.info("After cache2.get");
    } finally {
        // Finish JVM
        cache1.getCacheManager().stop();
    }
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HotRodClientException(org.infinispan.client.hotrod.exceptions.HotRodClientException) SessionEntityWrapper(org.keycloak.models.sessions.infinispan.changes.SessionEntityWrapper) UserSessionEntity(org.keycloak.models.sessions.infinispan.entities.UserSessionEntity)

Example 8 with HotRodClientException

use of org.infinispan.client.hotrod.exceptions.HotRodClientException in project keycloak by keycloak.

the class InfinispanUserSessionProvider method importSessionsWithExpiration.

private <T extends SessionEntity> void importSessionsWithExpiration(Map<? extends Object, SessionEntityWrapper<T>> sessionsById, BasicCache cache, BiFunction<RealmModel, T, Long> lifespanMsCalculator, BiFunction<RealmModel, T, Long> maxIdleTimeMsCalculator) {
    sessionsById.forEach((id, sessionEntityWrapper) -> {
        T sessionEntity = sessionEntityWrapper.getEntity();
        RealmModel currentRealm = session.realms().getRealm(sessionEntity.getRealmId());
        long lifespan = lifespanMsCalculator.apply(currentRealm, sessionEntity);
        long maxIdle = maxIdleTimeMsCalculator.apply(currentRealm, sessionEntity);
        if (lifespan != SessionTimeouts.ENTRY_EXPIRED_FLAG && maxIdle != SessionTimeouts.ENTRY_EXPIRED_FLAG) {
            if (cache instanceof RemoteCache) {
                Retry.executeWithBackoff((int iteration) -> {
                    try {
                        cache.put(id, sessionEntityWrapper, lifespan, TimeUnit.MILLISECONDS, maxIdle, TimeUnit.MILLISECONDS);
                    } catch (HotRodClientException re) {
                        if (log.isDebugEnabled()) {
                            log.debugf(re, "Failed to put import %d sessions to remoteCache. Iteration '%s'. Will try to retry the task", sessionsById.size(), iteration);
                        }
                        // Rethrow the exception. Retry will take care of handle the exception and eventually retry the operation.
                        throw re;
                    }
                }, 10, 10);
            } else {
                cache.put(id, sessionEntityWrapper, lifespan, TimeUnit.MILLISECONDS, maxIdle, TimeUnit.MILLISECONDS);
            }
        }
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) RemoteCache(org.infinispan.client.hotrod.RemoteCache) HotRodClientException(org.infinispan.client.hotrod.exceptions.HotRodClientException)

Example 9 with HotRodClientException

use of org.infinispan.client.hotrod.exceptions.HotRodClientException in project wildfly by wildfly.

the class HotRodStore method start.

@Override
public CompletionStage<Void> start(InitializationContext context) {
    this.blockingManager = context.getBlockingManager();
    HotRodStoreConfiguration configuration = context.getConfiguration();
    RemoteCacheContainer container = configuration.remoteCacheContainer();
    String cacheConfiguration = configuration.cacheConfiguration();
    String cacheName = context.getCache().getName();
    this.batchSize = configuration.maxBatchSize();
    this.marshaller = context.getPersistenceMarshaller();
    this.entryFactory = context.getMarshallableEntryFactory();
    String templateName = (cacheConfiguration != null) ? cacheConfiguration : DefaultTemplate.DIST_SYNC.getTemplateName();
    Consumer<RemoteCacheConfigurationBuilder> configurator = new Consumer<RemoteCacheConfigurationBuilder>() {

        @Override
        public void accept(RemoteCacheConfigurationBuilder builder) {
            builder.forceReturnValues(false).transactionMode(TransactionMode.NONE).nearCacheMode(NearCacheMode.DISABLED).templateName(templateName);
        }
    };
    container.getConfiguration().addRemoteCache(cacheName, configurator);
    Runnable task = new Runnable() {

        @Override
        public void run() {
            try {
                HotRodStore.this.setRemoteCache(container, cacheName);
            } catch (HotRodClientException ex) {
                throw new PersistenceException(ex);
            }
        }
    };
    return this.blockingManager.runBlocking(task, "hotrod-store-start");
}
Also used : RemoteCacheContainer(org.wildfly.clustering.infinispan.client.RemoteCacheContainer) Consumer(java.util.function.Consumer) PersistenceException(org.infinispan.persistence.spi.PersistenceException) RemoteCacheConfigurationBuilder(org.infinispan.client.hotrod.configuration.RemoteCacheConfigurationBuilder) HotRodClientException(org.infinispan.client.hotrod.exceptions.HotRodClientException)

Example 10 with HotRodClientException

use of org.infinispan.client.hotrod.exceptions.HotRodClientException in project keycloak by keycloak.

the class InfinispanOAuth2DeviceTokenStoreProvider method isPollingAllowed.

@Override
public boolean isPollingAllowed(OAuth2DeviceCodeModel deviceCode) {
    try {
        BasicCache<String, ActionTokenValueEntity> cache = codeCache.get();
        String key = deviceCode.serializePollingKey();
        ActionTokenValueEntity value = new ActionTokenValueEntity(null);
        ActionTokenValueEntity existing = cache.putIfAbsent(key, value, deviceCode.getPollingInterval(), TimeUnit.SECONDS);
        return existing == null;
    } catch (HotRodClientException re) {
        // In case of lock conflict, we don't want to retry anyway as there was likely an attempt to remove the code from different place.
        if (logger.isDebugEnabled()) {
            logger.debugf(re, "Failed when putting polling key for device code %s", deviceCode.getDeviceCode());
        }
        return false;
    }
}
Also used : ActionTokenValueEntity(org.keycloak.models.sessions.infinispan.entities.ActionTokenValueEntity) HotRodClientException(org.infinispan.client.hotrod.exceptions.HotRodClientException)

Aggregations

HotRodClientException (org.infinispan.client.hotrod.exceptions.HotRodClientException)21 ActionTokenValueEntity (org.keycloak.models.sessions.infinispan.entities.ActionTokenValueEntity)14 UUID (java.util.UUID)5 RemoteCache (org.infinispan.client.hotrod.RemoteCache)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)3 Consumer (java.util.function.Consumer)2 OAuth2DeviceCodeModel (org.keycloak.models.OAuth2DeviceCodeModel)2 SessionUpdateTask (org.keycloak.models.sessions.infinispan.changes.SessionUpdateTask)2 Serializable (java.io.Serializable)1 Collection (java.util.Collection)1 Collections (java.util.Collections)1 HashMap (java.util.HashMap)1 Iterator (java.util.Iterator)1 Map (java.util.Map)1 Objects (java.util.Objects)1 Set (java.util.Set)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 Future (java.util.concurrent.Future)1 TimeUnit (java.util.concurrent.TimeUnit)1 BiFunction (java.util.function.BiFunction)1