Search in sources :

Example 21 with UserSessionEntity

use of org.keycloak.models.sessions.infinispan.entities.UserSessionEntity in project keycloak by keycloak.

the class ConcurrencyJDGRemoveSessionTest method createSessionEntity.

private static SessionEntityWrapper<UserSessionEntity> createSessionEntity(String sessionId) {
    // Create 100 initial sessions
    UserSessionEntity session = new UserSessionEntity();
    session.setId(sessionId);
    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(UUID.randomUUID());
    clientSession.setAuthMethod("saml");
    clientSession.setAction("something");
    clientSession.setTimestamp(1234);
    session.getAuthenticatedClientSessions().put(CLIENT_1_UUID.toString(), clientSession.getId());
    SessionEntityWrapper<UserSessionEntity> wrappedSession = new SessionEntityWrapper<>(session);
    return wrappedSession;
}
Also used : AuthenticatedClientSessionEntity(org.keycloak.models.sessions.infinispan.entities.AuthenticatedClientSessionEntity) SessionEntityWrapper(org.keycloak.models.sessions.infinispan.changes.SessionEntityWrapper) UserSessionEntity(org.keycloak.models.sessions.infinispan.entities.UserSessionEntity)

Example 22 with UserSessionEntity

use of org.keycloak.models.sessions.infinispan.entities.UserSessionEntity in project keycloak by keycloak.

the class RemoteCacheSessionsLoaderTest method testRemoteCache.

@Test
@Ignore
public void testRemoteCache() throws Exception {
    String cacheName = InfinispanConnectionProvider.USER_SESSION_CACHE_NAME;
    Cache cache1 = createManager(1, cacheName).getCache(cacheName);
    Cache cache2 = cache1.getCacheManager().getCache("local");
    RemoteCache remoteCache = InfinispanUtil.getRemoteCache(cache1);
    cache1.clear();
    cache2.clear();
    remoteCache.clear();
    try {
        for (int i = 0; i < COUNT; i++) {
            // Create initial item
            UserSessionEntity session = new UserSessionEntity();
            session.setId("loader-key-" + i);
            session.setRealmId("master");
            session.setBrokerSessionId("!23123123");
            session.setBrokerUserId(null);
            session.setUser("admin");
            session.setLoginUsername("admin");
            session.setIpAddress("123.44.143.178");
            session.setStarted(Time.currentTime());
            session.setLastSessionRefresh(Time.currentTime());
            SessionEntityWrapper<UserSessionEntity> wrappedSession = new SessionEntityWrapper<>(session);
            // Create caches, listeners and finally worker threads
            remoteCache.put("loader-key-" + i, wrappedSession);
            Assert.assertFalse(cache2.containsKey("loader-key-" + i));
            if (i % 1000 == 0) {
                logger.infof("%d sessions added", i);
            }
        }
        // RemoteCacheSessionsLoader loader = new RemoteCacheSessionsLoader(InfinispanConnectionProvider.USER_SESSION_CACHE_NAME, 64) {
        // 
        // @Override
        // protected Cache getCache(KeycloakSession session) {
        // return cache2;
        // }
        // 
        // @Override
        // protected RemoteCache getRemoteCache(KeycloakSession session) {
        // return remoteCache;
        // }
        // 
        // };
        // Just to be able to test serializability
        RemoteCacheSessionsLoader loader = new CustomLoader(cacheName, 64, cache2, remoteCache);
        loader.init(null);
        RemoteCacheSessionsLoaderContext ctx = loader.computeLoaderContext(null);
        Assert.assertEquals(ctx.getSessionsTotal(), COUNT);
        Assert.assertEquals(ctx.getIspnSegmentsCount(), 256);
        // Assert.assertEquals(ctx.getSegmentsCount(), 16);
        Assert.assertEquals(ctx.getSessionsPerSegment(), 64);
        int totalCount = 0;
        logger.infof("segmentsCount: %d", ctx.getSegmentsCount());
        Set<String> visitedKeys = new HashSet<>();
        for (int currentSegment = 0; currentSegment < ctx.getSegmentsCount(); currentSegment++) {
            logger.infof("Loading segment %d", currentSegment);
            loader.loadSessions(null, ctx, new SessionLoader.WorkerContext(currentSegment, currentSegment));
            logger.infof("Loaded %d keys for segment %d", cache2.keySet().size(), currentSegment);
            totalCount = totalCount + cache2.keySet().size();
            visitedKeys.addAll(cache2.keySet());
            cache2.clear();
        }
        Assert.assertEquals(totalCount, COUNT);
        Assert.assertEquals(visitedKeys.size(), COUNT);
        logger.infof("SUCCESS: Loaded %d sessions", totalCount);
    } finally {
        // Finish JVM
        cache1.getCacheManager().stop();
    }
}
Also used : RemoteCacheSessionsLoaderContext(org.keycloak.models.sessions.infinispan.remotestore.RemoteCacheSessionsLoaderContext) SessionEntityWrapper(org.keycloak.models.sessions.infinispan.changes.SessionEntityWrapper) SessionLoader(org.keycloak.models.sessions.infinispan.initializer.SessionLoader) RemoteCache(org.infinispan.client.hotrod.RemoteCache) RemoteCacheSessionsLoader(org.keycloak.models.sessions.infinispan.remotestore.RemoteCacheSessionsLoader) Cache(org.infinispan.Cache) RemoteCache(org.infinispan.client.hotrod.RemoteCache) UserSessionEntity(org.keycloak.models.sessions.infinispan.entities.UserSessionEntity) HashSet(java.util.HashSet) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 23 with UserSessionEntity

use of org.keycloak.models.sessions.infinispan.entities.UserSessionEntity in project keycloak by keycloak.

the class ConcurrencyDistributedRemoveSessionTest method main.

public static void main(String[] args) throws Exception {
    Cache<String, SessionEntityWrapper<UserSessionEntity>> cache1 = DistributedCacheConcurrentWritesTest.createManager("node1").getCache(InfinispanConnectionProvider.USER_SESSION_CACHE_NAME);
    Cache<String, SessionEntityWrapper<UserSessionEntity>> cache2 = DistributedCacheConcurrentWritesTest.createManager("node2").getCache(InfinispanConnectionProvider.USER_SESSION_CACHE_NAME);
    // Create caches, listeners and finally worker threads
    Thread worker1 = createWorker(cache1, 1);
    Thread worker2 = createWorker(cache2, 2);
    Thread worker3 = createWorker(cache1, 1);
    Thread worker4 = createWorker(cache2, 2);
    // Create 100 initial sessions
    for (int i = 0; i < ITERATIONS; i++) {
        String sessionId = String.valueOf(i);
        SessionEntityWrapper<UserSessionEntity> wrappedSession = createSessionEntity(sessionId);
        cache1.put(sessionId, wrappedSession);
        removalCounts.put(sessionId, new AtomicInteger(0));
    }
    logger.info("SESSIONS CREATED");
    // Create 100 initial sessions
    for (int i = 0; i < ITERATIONS; i++) {
        String sessionId = String.valueOf(i);
        SessionEntityWrapper loadedWrapper = cache2.get(sessionId);
        Assert.assertNotNull("Loaded wrapper for key " + sessionId, loadedWrapper);
    }
    logger.info("SESSIONS AVAILABLE ON DC2");
    long start = System.currentTimeMillis();
    try {
        worker1.start();
        worker2.start();
        worker3.start();
        worker4.start();
        worker1.join();
        worker2.join();
        worker3.join();
        worker4.join();
        logger.info("SESSIONS REMOVED");
        Map<Integer, Integer> histogram = new HashMap<>();
        for (Map.Entry<String, AtomicInteger> entry : removalCounts.entrySet()) {
            int count = entry.getValue().get();
            int current = histogram.get(count) == null ? 0 : histogram.get(count);
            current++;
            histogram.put(count, current);
        }
        logger.infof("Histogram: %s", histogram.toString());
        logger.infof("Errors: %d", errorsCounter.get());
        long took = System.currentTimeMillis() - start;
        logger.infof("took %d ms", took);
    } finally {
        Thread.sleep(2000);
        // Finish JVM
        cache1.getCacheManager().stop();
        cache2.getCacheManager().stop();
    }
}
Also used : ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) SessionEntityWrapper(org.keycloak.models.sessions.infinispan.changes.SessionEntityWrapper) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Map(java.util.Map) UserSessionEntity(org.keycloak.models.sessions.infinispan.entities.UserSessionEntity)

Example 24 with UserSessionEntity

use of org.keycloak.models.sessions.infinispan.entities.UserSessionEntity in project keycloak by keycloak.

the class InfinispanUserSessionProvider method importUserSession.

// Imports just userSession without it's clientSessions
protected UserSessionAdapter importUserSession(UserSessionModel userSession, boolean offline) {
    UserSessionEntity entity = createUserSessionEntityInstance(userSession);
    InfinispanChangelogBasedTransaction<String, UserSessionEntity> userSessionUpdateTx = getTransaction(offline);
    InfinispanChangelogBasedTransaction<UUID, AuthenticatedClientSessionEntity> clientSessionUpdateTx = getClientSessionTransaction(offline);
    SessionUpdateTask<UserSessionEntity> importTask = Tasks.addIfAbsentSync();
    userSessionUpdateTx.addTask(userSession.getId(), importTask, entity, UserSessionModel.SessionPersistenceState.PERSISTENT);
    UserSessionAdapter importedSession = wrap(userSession.getRealm(), entity, offline);
    return importedSession;
}
Also used : AuthenticatedClientSessionEntity(org.keycloak.models.sessions.infinispan.entities.AuthenticatedClientSessionEntity) UUID(java.util.UUID) UserSessionEntity(org.keycloak.models.sessions.infinispan.entities.UserSessionEntity)

Example 25 with UserSessionEntity

use of org.keycloak.models.sessions.infinispan.entities.UserSessionEntity in project keycloak by keycloak.

the class InfinispanUserSessionProvider method createUserSessionEntityInstance.

private UserSessionEntity createUserSessionEntityInstance(UserSessionModel userSession) {
    UserSessionEntity entity = new UserSessionEntity();
    entity.setId(userSession.getId());
    entity.setRealmId(userSession.getRealm().getId());
    entity.setAuthMethod(userSession.getAuthMethod());
    entity.setBrokerSessionId(userSession.getBrokerSessionId());
    entity.setBrokerUserId(userSession.getBrokerUserId());
    entity.setIpAddress(userSession.getIpAddress());
    entity.setNotes(userSession.getNotes() == null ? new ConcurrentHashMap<>() : userSession.getNotes());
    entity.setAuthenticatedClientSessions(new AuthenticatedClientSessionStore());
    entity.setRememberMe(userSession.isRememberMe());
    entity.setState(userSession.getState());
    if (userSession instanceof OfflineUserSessionModel) {
        // this is a hack so that UserModel doesn't have to be available when offline token is imported.
        // see related JIRA - KEYCLOAK-5350 and corresponding test
        OfflineUserSessionModel oline = (OfflineUserSessionModel) userSession;
        entity.setUser(oline.getUserId());
    // NOTE: Hack
    // We skip calling entity.setLoginUsername(userSession.getLoginUsername())
    } else {
        entity.setLoginUsername(userSession.getLoginUsername());
        entity.setUser(userSession.getUser().getId());
    }
    entity.setStarted(userSession.getStarted());
    entity.setLastSessionRefresh(userSession.getLastSessionRefresh());
    return entity;
}
Also used : OfflineUserSessionModel(org.keycloak.models.OfflineUserSessionModel) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) AuthenticatedClientSessionStore(org.keycloak.models.sessions.infinispan.entities.AuthenticatedClientSessionStore) UserSessionEntity(org.keycloak.models.sessions.infinispan.entities.UserSessionEntity)

Aggregations

UserSessionEntity (org.keycloak.models.sessions.infinispan.entities.UserSessionEntity)27 SessionEntityWrapper (org.keycloak.models.sessions.infinispan.changes.SessionEntityWrapper)13 AuthenticatedClientSessionEntity (org.keycloak.models.sessions.infinispan.entities.AuthenticatedClientSessionEntity)9 UserSessionUpdateTask (org.keycloak.models.sessions.infinispan.changes.UserSessionUpdateTask)6 UUID (java.util.UUID)5 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)5 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)5 OfflineUserSessionModel (org.keycloak.models.OfflineUserSessionModel)5 HashMap (java.util.HashMap)4 Map (java.util.Map)4 RemoteCache (org.infinispan.client.hotrod.RemoteCache)4 Cache (org.infinispan.Cache)3 HotRodClientException (org.infinispan.client.hotrod.exceptions.HotRodClientException)3 UserSessionModel (org.keycloak.models.UserSessionModel)3 Serializable (java.io.Serializable)2 Collection (java.util.Collection)2 Collections (java.util.Collections)2 Iterator (java.util.Iterator)2 Objects (java.util.Objects)2 Set (java.util.Set)2