Search in sources :

Example 6 with InfinispanConnectionProvider

use of org.keycloak.connections.infinispan.InfinispanConnectionProvider in project keycloak by keycloak.

the class InfinispanUserSessionProviderFactory method checkRemoteCaches.

protected void checkRemoteCaches(KeycloakSession session) {
    this.remoteCacheInvoker = new RemoteCacheInvoker();
    InfinispanConnectionProvider ispn = session.getProvider(InfinispanConnectionProvider.class);
    Cache<String, SessionEntityWrapper<UserSessionEntity>> sessionsCache = ispn.getCache(InfinispanConnectionProvider.USER_SESSION_CACHE_NAME);
    RemoteCache sessionsRemoteCache = checkRemoteCache(session, sessionsCache, (RealmModel realm) -> {
        // We won't write to the remoteCache during token refresh, so the timeout needs to be longer.
        return Time.toMillis(realm.getSsoSessionMaxLifespan());
    }, SessionTimeouts::getUserSessionLifespanMs, SessionTimeouts::getUserSessionMaxIdleMs);
    if (sessionsRemoteCache != null) {
        lastSessionRefreshStore = new CrossDCLastSessionRefreshStoreFactory().createAndInit(session, sessionsCache, false);
    }
    Cache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> clientSessionsCache = ispn.getCache(InfinispanConnectionProvider.CLIENT_SESSION_CACHE_NAME);
    checkRemoteCache(session, clientSessionsCache, (RealmModel realm) -> {
        // We won't write to the remoteCache during token refresh, so the timeout needs to be longer.
        return Time.toMillis(realm.getSsoSessionMaxLifespan());
    }, SessionTimeouts::getClientSessionLifespanMs, SessionTimeouts::getClientSessionMaxIdleMs);
    Cache<String, SessionEntityWrapper<UserSessionEntity>> offlineSessionsCache = ispn.getCache(InfinispanConnectionProvider.OFFLINE_USER_SESSION_CACHE_NAME);
    RemoteCache offlineSessionsRemoteCache = checkRemoteCache(session, offlineSessionsCache, (RealmModel realm) -> {
        return Time.toMillis(realm.getOfflineSessionIdleTimeout());
    }, SessionTimeouts::getOfflineSessionLifespanMs, SessionTimeouts::getOfflineSessionMaxIdleMs);
    if (offlineSessionsRemoteCache != null) {
        offlineLastSessionRefreshStore = new CrossDCLastSessionRefreshStoreFactory().createAndInit(session, offlineSessionsCache, true);
    }
    Cache<UUID, SessionEntityWrapper<AuthenticatedClientSessionEntity>> offlineClientSessionsCache = ispn.getCache(InfinispanConnectionProvider.OFFLINE_CLIENT_SESSION_CACHE_NAME);
    checkRemoteCache(session, offlineClientSessionsCache, (RealmModel realm) -> {
        return Time.toMillis(realm.getOfflineSessionIdleTimeout());
    }, SessionTimeouts::getOfflineClientSessionLifespanMs, SessionTimeouts::getOfflineClientSessionMaxIdleMs);
}
Also used : RealmModel(org.keycloak.models.RealmModel) CrossDCLastSessionRefreshStoreFactory(org.keycloak.models.sessions.infinispan.changes.sessions.CrossDCLastSessionRefreshStoreFactory) RemoteCacheInvoker(org.keycloak.models.sessions.infinispan.remotestore.RemoteCacheInvoker) RemoteCache(org.infinispan.client.hotrod.RemoteCache) SessionTimeouts(org.keycloak.models.sessions.infinispan.util.SessionTimeouts) UUID(java.util.UUID) InfinispanConnectionProvider(org.keycloak.connections.infinispan.InfinispanConnectionProvider) SessionEntityWrapper(org.keycloak.models.sessions.infinispan.changes.SessionEntityWrapper)

Example 7 with InfinispanConnectionProvider

use of org.keycloak.connections.infinispan.InfinispanConnectionProvider in project keycloak by keycloak.

the class AbstractSessionCacheCommand method doRunCommand.

@Override
protected void doRunCommand(KeycloakSession session) {
    InfinispanConnectionProvider provider = session.getProvider(InfinispanConnectionProvider.class);
    String cacheName = getArg(0);
    if (!SUPPORTED_CACHE_NAMES.contains(cacheName)) {
        log.errorf("Invalid cache name: '%s', Only cache names '%s' are supported", cacheName, SUPPORTED_CACHE_NAMES);
        throw new HandledException();
    }
    Cache<String, SessionEntityWrapper> ispnCache = provider.getCache(cacheName);
    doRunCacheCommand(session, ispnCache);
    ispnCache.entrySet().stream().skip(0).limit(10).collect(java.util.stream.Collectors.toMap(new java.util.function.Function() {

        public Object apply(Object entry) {
            return ((java.util.Map.Entry) entry).getKey();
        }
    }, new java.util.function.Function() {

        public Object apply(Object entry) {
            return ((java.util.Map.Entry) entry).getValue();
        }
    }));
}
Also used : InfinispanConnectionProvider(org.keycloak.connections.infinispan.InfinispanConnectionProvider) SessionEntityWrapper(org.keycloak.models.sessions.infinispan.changes.SessionEntityWrapper)

Example 8 with InfinispanConnectionProvider

use of org.keycloak.connections.infinispan.InfinispanConnectionProvider in project keycloak by keycloak.

the class InfinispanTestUtil method setTestingTimeService.

/**
 * Set Keycloak test TimeService to infinispan cacheManager. This will cause that infinispan will be aware of Keycloak Time offset, which is useful
 * for testing that infinispan entries are expired after moving Keycloak time forward with {@link org.keycloak.common.util.Time#setOffset} .
 */
public static void setTestingTimeService(KeycloakSession session) {
    // Testing timeService already set. This shouldn't happen if this utility is properly used
    if (origTimeService != null) {
        throw new IllegalStateException("Calling setTestingTimeService when testing TimeService was already set");
    }
    logger.info("Will set KeycloakIspnTimeService to the infinispan cacheManager");
    InfinispanConnectionProvider ispnProvider = session.getProvider(InfinispanConnectionProvider.class);
    EmbeddedCacheManager cacheManager = ispnProvider.getCache(InfinispanConnectionProvider.USER_SESSION_CACHE_NAME).getCacheManager();
    origTimeService = setTimeServiceToKeycloakTime(cacheManager);
}
Also used : EmbeddedCacheManager(org.infinispan.manager.EmbeddedCacheManager) InfinispanConnectionProvider(org.keycloak.connections.infinispan.InfinispanConnectionProvider)

Example 9 with InfinispanConnectionProvider

use of org.keycloak.connections.infinispan.InfinispanConnectionProvider in project keycloak by keycloak.

the class UserSessionProviderOfflineModelTest method testOfflineSessionLazyLoadingPropagationBetweenNodes.

@Test
public void testOfflineSessionLazyLoadingPropagationBetweenNodes() throws InterruptedException {
    AtomicReference<List<UserSessionModel>> offlineUserSessions = new AtomicReference<>(new LinkedList<>());
    AtomicReference<List<AuthenticatedClientSessionModel>> offlineClientSessions = new AtomicReference<>(new LinkedList<>());
    AtomicBoolean result = new AtomicBoolean(true);
    AtomicInteger index = new AtomicInteger();
    CountDownLatch latch = new CountDownLatch(4);
    CountDownLatch afterFirstNodeLatch = new CountDownLatch(1);
    inIndependentFactories(4, 300, () -> {
        if (index.incrementAndGet() == 1) {
            createOfflineSessions("user1", 10, offlineUserSessions, offlineClientSessions);
            afterFirstNodeLatch.countDown();
        }
        awaitLatch(afterFirstNodeLatch);
        log.debug("Joining the cluster");
        inComittedTransaction(session -> {
            InfinispanConnectionProvider provider = session.getProvider(InfinispanConnectionProvider.class);
            Cache<String, Object> cache = provider.getCache(InfinispanConnectionProvider.WORK_CACHE_NAME);
            do {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                    throw new RuntimeException(ex);
                }
            } while (!cache.getAdvancedCache().getDistributionManager().isJoinComplete());
            cache.keySet().forEach(s -> {
            });
        });
        log.debug("Cluster joined");
        withRealm(realmId, (session, realm) -> {
            final UserModel user = session.users().getUserByUsername(realm, "user1");
            result.set(result.get() && assertOfflineSession(offlineUserSessions, session.sessions().getOfflineUserSessionsStream(realm, user).collect(Collectors.toList())));
            return null;
        });
        latch.countDown();
        awaitLatch(latch);
    });
    Assert.assertTrue(result.get());
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) UserModel(org.keycloak.models.UserModel) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) LinkedList(java.util.LinkedList) List(java.util.List) InfinispanConnectionProvider(org.keycloak.connections.infinispan.InfinispanConnectionProvider) Test(org.junit.Test) KeycloakModelTest(org.keycloak.testsuite.model.KeycloakModelTest)

Example 10 with InfinispanConnectionProvider

use of org.keycloak.connections.infinispan.InfinispanConnectionProvider in project keycloak by keycloak.

the class InfinispanUserSessionProviderFactory method loadSessionsFromRemoteCache.

private void loadSessionsFromRemoteCache(final KeycloakSessionFactory sessionFactory, String cacheName, final int sessionsPerSegment, final int maxErrors) {
    log.debugf("Check pre-loading sessions from remote cache '%s'", cacheName);
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            InfinispanConnectionProvider connections = session.getProvider(InfinispanConnectionProvider.class);
            Cache<String, Serializable> workCache = connections.getCache(InfinispanConnectionProvider.WORK_CACHE_NAME);
            InfinispanCacheInitializer initializer = new InfinispanCacheInitializer(sessionFactory, workCache, new RemoteCacheSessionsLoader(cacheName, sessionsPerSegment), "remoteCacheLoad::" + cacheName, sessionsPerSegment, maxErrors);
            initializer.initCache();
            initializer.loadSessions();
        }
    });
    log.debugf("Pre-loading sessions from remote cache '%s' finished", cacheName);
}
Also used : KeycloakSessionTask(org.keycloak.models.KeycloakSessionTask) KeycloakSession(org.keycloak.models.KeycloakSession) InfinispanConnectionProvider(org.keycloak.connections.infinispan.InfinispanConnectionProvider) InfinispanCacheInitializer(org.keycloak.models.sessions.infinispan.initializer.InfinispanCacheInitializer) RemoteCacheSessionsLoader(org.keycloak.models.sessions.infinispan.remotestore.RemoteCacheSessionsLoader) Cache(org.infinispan.Cache) RemoteCache(org.infinispan.client.hotrod.RemoteCache)

Aggregations

InfinispanConnectionProvider (org.keycloak.connections.infinispan.InfinispanConnectionProvider)16 Cache (org.infinispan.Cache)5 SessionEntityWrapper (org.keycloak.models.sessions.infinispan.changes.SessionEntityWrapper)5 RemoteCache (org.infinispan.client.hotrod.RemoteCache)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)3 Test (org.junit.Test)3 KeycloakModelTest (org.keycloak.testsuite.model.KeycloakModelTest)3 LinkedList (java.util.LinkedList)2 List (java.util.List)2 UUID (java.util.UUID)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 KeycloakSession (org.keycloak.models.KeycloakSession)2 KeycloakSessionTask (org.keycloak.models.KeycloakSessionTask)2 RealmModel (org.keycloak.models.RealmModel)2 UserModel (org.keycloak.models.UserModel)2 LoginFailureKey (org.keycloak.models.sessions.infinispan.entities.LoginFailureKey)2 InfinispanCacheInitializer (org.keycloak.models.sessions.infinispan.initializer.InfinispanCacheInitializer)2 RemoteCacheSessionsLoader (org.keycloak.models.sessions.infinispan.remotestore.RemoteCacheSessionsLoader)2 SessionTimeouts (org.keycloak.models.sessions.infinispan.util.SessionTimeouts)2 RequireProvider (org.keycloak.testsuite.model.RequireProvider)2