org.infinispan.client.hotrod.exceptions.HotRodClientException Java Examples

The following examples show how to use org.infinispan.client.hotrod.exceptions.HotRodClientException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InfinispanCodeToTokenStoreProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public void put(UUID codeId, int lifespanSeconds, Map<String, String> codeData) {
    ActionTokenValueEntity tokenValue = new ActionTokenValueEntity(codeData);

    try {
        BasicCache<UUID, ActionTokenValueEntity> cache = codeCache.get();
        cache.put(codeId, tokenValue, lifespanSeconds, TimeUnit.SECONDS);
    } catch (HotRodClientException re) {
        // No need to retry. The hotrod (remoteCache) has some retries in itself in case of some random network error happened.
        if (logger.isDebugEnabled()) {
            logger.debugf(re, "Failed when adding code %s", codeId);
        }

        throw re;
    }
}
 
Example #2
Source File: InfinispanCodeToTokenStoreProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, String> remove(UUID codeId) {
    try {
        BasicCache<UUID, ActionTokenValueEntity> cache = codeCache.get();
        ActionTokenValueEntity existing = cache.remove(codeId);
        return existing == null ? null : existing.getNotes();
    } catch (HotRodClientException re) {
        // No need to retry. The hotrod (remoteCache) has some retries in itself in case of some random network error happened.
        // 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 removing code %s", codeId);
        }

        return null;
    }
}
 
Example #3
Source File: InfinispanSingleUseTokenStoreProvider.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public boolean putIfAbsent(String tokenId, int lifespanInSeconds) {
    ActionTokenValueEntity tokenValue = new ActionTokenValueEntity(null);

    // Rather keep the items in the cache for a bit longer
    lifespanInSeconds = lifespanInSeconds + 10;

    try {
        BasicCache<String, ActionTokenValueEntity> cache = tokenCache.get();
        ActionTokenValueEntity existing = cache.putIfAbsent(tokenId, tokenValue, lifespanInSeconds, TimeUnit.SECONDS);
        return existing == null;
    } catch (HotRodClientException re) {
        // No need to retry. The hotrod (remoteCache) has some retries in itself in case of some random network error happened.
        // In case of lock conflict, we don't want to retry anyway as there was likely an attempt to use the token from different place.
        logger.debugf(re, "Failed when adding token %s", tokenId);

        return false;
    }

}
 
Example #4
Source File: InfinispanClusterProviderFactory.java    From keycloak with Apache License 2.0 6 votes vote down vote up
static <V extends Serializable> V putIfAbsentWithRetries(CrossDCAwareCacheFactory crossDCAwareCacheFactory, String key, V value, int taskTimeoutInSeconds) {
    AtomicReference<V> resultRef = new AtomicReference<>();

    Retry.executeWithBackoff((int iteration) -> {

        try {
            V result;
            if (taskTimeoutInSeconds > 0) {
                result = (V) crossDCAwareCacheFactory.getCache().putIfAbsent(key, value);
            } else {
                result = (V) crossDCAwareCacheFactory.getCache().putIfAbsent(key, value, taskTimeoutInSeconds, TimeUnit.SECONDS);
            }
            resultRef.set(result);

        } catch (HotRodClientException re) {
            logger.warnf(re, "Failed to write key '%s' and value '%s' in iteration '%d' . Retrying", key, value, iteration);

            // Rethrow the exception. Retry will take care of handle the exception and eventually retry the operation.
            throw re;
        }

    }, 10, 10);

    return resultRef.get();
}
 
Example #5
Source File: InfinispanClientProcessor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private Properties loadFromStream(InputStream stream) {
    Properties properties = new Properties();
    try {
        properties.load(stream);
    } catch (IOException e) {
        throw new HotRodClientException("Issues configuring from client hotrod-client.properties", e);
    }
    return properties;
}
 
Example #6
Source File: InfinispanHotRodImpl.java    From khan-session with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * InputStream에서 properties 파일을 읽는다.
 *
 * @param stream
 * @return
 */
private Properties loadFromStream(InputStream stream) {
    Properties properties = new Properties();
    try {
        properties.load(stream);
    } catch (IOException e) {
        throw new HotRodClientException("Issues configuring from client hotrod-client.properties", e);
    }
    return properties;
}
 
Example #7
Source File: RemoteCacheProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected synchronized RemoteCache loadRemoteCache(String cacheName) {
    RemoteCache remoteCache = InfinispanUtil.getRemoteCache(cacheManager.getCache(cacheName));

    Boolean remoteStoreSecurity = config.getBoolean("remoteStoreSecurityEnabled");
    if (remoteStoreSecurity == null) {
        try {
            logger.debugf("Detecting remote security settings of HotRod server, cache %s. Disable by explicitly setting \"remoteStoreSecurityEnabled\" property in spi=connectionsInfinispan/provider=default", cacheName);
            remoteStoreSecurity = false;
            final RemoteCache<Object, Object> scriptCache = remoteCache.getRemoteCacheManager().getCache(SCRIPT_CACHE_NAME);
            if (scriptCache == null) {
                logger.debug("Cannot detect remote security settings of HotRod server, disabling.");
            } else {
                scriptCache.containsKey("");
            }
        } catch (HotRodClientException ex) {
            logger.debug("Seems that HotRod server requires authentication, enabling.");
            remoteStoreSecurity = true;
        }
    }

    if (remoteStoreSecurity) {
        logger.infof("Remote store security for cache %s is enabled. Disable by setting \"remoteStoreSecurityEnabled\" property to \"false\" in spi=connectionsInfinispan/provider=default", cacheName);
        RemoteCacheManager securedMgr = getOrCreateSecuredRemoteCacheManager(config, cacheName, remoteCache.getRemoteCacheManager());
        return securedMgr.getCache(remoteCache.getName());
    } else {
        logger.infof("Remote store security for cache %s is disabled. If server fails to connect to remote JDG server, enable it.", cacheName);
        return remoteCache;
    }
}
 
Example #8
Source File: OfflinePersistentUserSessionLoader.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public void afterAllSessionsLoaded(BaseCacheInitializer initializer) {
    Cache<String, Serializable> workCache = initializer.getWorkCache();

    // Will retry few times for the case when backup site not available in cross-dc environment.
    // The site might be taken offline automatically if "take-offline" properly configured
    Retry.executeWithBackoff((int iteration) -> {

        try {
            // Cross-DC aware flag
            workCache
                    .getAdvancedCache().withFlags(Flag.SKIP_REMOTE_LOOKUP)
                    .put(PERSISTENT_SESSIONS_LOADED, true);

        } catch (HotRodClientException re) {
            log.warnf(re, "Failed to write flag PERSISTENT_SESSIONS_LOADED in iteration '%d' . Retrying", iteration);

            // Rethrow the exception. Retry will take care of handle the exception and eventually retry the operation.
            throw re;
        }

    }, 10, 10);

    // Just local-DC aware flag
    workCache
            .getAdvancedCache().withFlags(Flag.SKIP_REMOTE_LOOKUP, Flag.SKIP_CACHE_LOAD, Flag.SKIP_CACHE_STORE)
            .put(PERSISTENT_SESSIONS_LOADED_IN_CURRENT_DC, true);


    log.debugf("Persistent sessions loaded successfully!");
}
 
Example #9
Source File: InfinispanNotificationsManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
void notify(String taskKey, ClusterEvent event, boolean ignoreSender, ClusterProvider.DCNotify dcNotify) {
    WrapperClusterEvent wrappedEvent = new WrapperClusterEvent();
    wrappedEvent.setEventKey(taskKey);
    wrappedEvent.setDelegateEvent(event);
    wrappedEvent.setIgnoreSender(ignoreSender);
    wrappedEvent.setIgnoreSenderSite(dcNotify == ClusterProvider.DCNotify.ALL_BUT_LOCAL_DC);
    wrappedEvent.setSender(myAddress);
    wrappedEvent.setSenderSite(mySite);

    String eventKey = UUID.randomUUID().toString();

    if (logger.isTraceEnabled()) {
        logger.tracef("Sending event with key %s: %s", eventKey, event);
    }

    if (dcNotify == ClusterProvider.DCNotify.LOCAL_DC_ONLY || workRemoteCache == null) {
        // Just put it to workCache, but skip notifying remoteCache
        workCache.getAdvancedCache().withFlags(Flag.IGNORE_RETURN_VALUES, Flag.SKIP_CACHE_STORE)
                .put(eventKey, wrappedEvent, 120, TimeUnit.SECONDS);
    } else {
        // Add directly to remoteCache. Will notify remote listeners on all nodes in all DCs
        Retry.executeWithBackoff((int iteration) -> {
            try {
                workRemoteCache.put(eventKey, wrappedEvent, 120, TimeUnit.SECONDS);
            } catch (HotRodClientException re) {
            if (logger.isDebugEnabled()) {
                logger.debugf(re, "Failed sending notification to remote cache '%s'. Key: '%s', iteration '%s'. Will try to retry the task",
                        workRemoteCache.getName(), eventKey, iteration);
            }

            // Rethrow the exception. Retry will take care of handle the exception and eventually retry the operation.
            throw re;
        }

    }, 10, 10);

    }
}
 
Example #10
Source File: ConcurrencyJDGCachePutTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static int getClusterStartupTime(Cache<String, Integer> cache, String cacheKey, EntryInfo wrapper, int myThreadId) {
        Integer startupTime = myThreadId==1 ? Integer.parseInt(cacheKey.substring(4)) : Integer.parseInt(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;
        }
    }
 
Example #11
Source File: ConcurrencyJDGRemoveSessionTest.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
        public void run() {

            for (int i=0 ; i<ITERATIONS ; i++) {
                String sessionId = String.valueOf(i);

                try {
                    Object o = remoteCache
                            .withFlags(org.infinispan.client.hotrod.Flag.FORCE_RETURN_VALUE)
                            .remove(sessionId);

                    if (o != null) {
                        removalCounts.get(sessionId).incrementAndGet();
                    }
                } catch (HotRodClientException hrce) {
                    errorsCounter.incrementAndGet();
                }
//
//
//                logger.infof("Session %s removed on DC1", sessionId);
//
//                // Check if it's immediately seen that session is removed on 2nd DC
//                RemoteCache secondDCRemoteCache = myThreadId == 1 ? remoteCache2 : remoteCache1;
//                SessionEntityWrapper thatSession = (SessionEntityWrapper) secondDCRemoteCache.get(sessionId);
//                Assert.assertNull("Session with ID " + sessionId + " not removed on the other DC. ThreadID: " + myThreadId, thatSession);
//
//                // Also check that it's immediatelly removed on my DC
//                SessionEntityWrapper mySession = (SessionEntityWrapper) remoteCache.get(sessionId);
//                Assert.assertNull("Session with ID " + sessionId + " not removed on the other DC. ThreadID: " + myThreadId, mySession);
            }

        }
 
Example #12
Source File: RemoteCacheInvoker.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public <K, V extends SessionEntity> void runTask(KeycloakSession kcSession, RealmModel realm, String cacheName, K key, SessionUpdateTask<V> task, SessionEntityWrapper<V> sessionWrapper) {
    RemoteCacheContext context = remoteCaches.get(cacheName);
    if (context == null) {
        return;
    }

    V session = sessionWrapper.getEntity();

    SessionUpdateTask.CacheOperation operation = task.getOperation(session);
    SessionUpdateTask.CrossDCMessageStatus status = task.getCrossDCMessageStatus(sessionWrapper);

    if (status == SessionUpdateTask.CrossDCMessageStatus.NOT_NEEDED) {
        if (logger.isTraceEnabled()) {
            logger.tracef("Skip writing to remoteCache for entity '%s' of cache '%s' and operation '%s'", key, cacheName, operation);
        }
        return;
    }

    long loadedMaxIdleTimeMs = context.maxIdleTimeLoader.getMaxIdleTimeMs(realm);

    // Increase the timeout to ensure that entry won't expire on remoteCache in case that write of some entities to remoteCache is postponed (eg. userSession.lastSessionRefresh)
    final long maxIdleTimeMs = loadedMaxIdleTimeMs + 1800000;

    if (logger.isTraceEnabled()) {
        logger.tracef("Running task '%s' on remote cache '%s' . Key is '%s'", operation, cacheName, key);
    }

    TopologyInfo topology = InfinispanUtil.getTopologyInfo(kcSession);

    Retry.executeWithBackoff((int iteration) -> {

        try {
            runOnRemoteCache(topology, context.remoteCache, maxIdleTimeMs, key, task, sessionWrapper);
        } catch (HotRodClientException re) {
            if (logger.isDebugEnabled()) {
                logger.debugf(re, "Failed running task '%s' on remote cache '%s' . Key: '%s', iteration '%s'. Will try to retry the task",
                        operation, cacheName, key, iteration);
            }

            // Rethrow the exception. Retry will take care of handle the exception and eventually retry the operation.
            throw re;
        }

    }, 10, 10);
}
 
Example #13
Source File: ConcurrencyJDGOfflineBackupsTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
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(Flag.CACHE_MODE_LOCAL) // will still invoke remoteStore . Just doesn't propagate to cluster
                            .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();
        }

    }