Search in sources :

Example 11 with KeycloakSessionTask

use of org.keycloak.models.KeycloakSessionTask in project keycloak by keycloak.

the class UserStorageSyncManager method syncAllUsers.

public SynchronizationResult syncAllUsers(final KeycloakSessionFactory sessionFactory, final String realmId, final UserStorageProviderModel provider) {
    UserStorageProviderFactory factory = (UserStorageProviderFactory) sessionFactory.getProviderFactory(UserStorageProvider.class, provider.getProviderId());
    if (!(factory instanceof ImportSynchronization) || !provider.isImportEnabled() || !provider.isEnabled()) {
        return SynchronizationResult.ignored();
    }
    final Holder holder = new Holder();
    // Ensure not executed concurrently on this or any other cluster node
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            ClusterProvider clusterProvider = session.getProvider(ClusterProvider.class);
            // shared key for "full" and "changed" . Improve if needed
            String taskKey = provider.getId() + "::sync";
            // 30 seconds minimal timeout for now
            int timeout = Math.max(30, provider.getFullSyncPeriod());
            holder.result = clusterProvider.executeIfNotExecuted(taskKey, timeout, new Callable<SynchronizationResult>() {

                @Override
                public SynchronizationResult call() throws Exception {
                    updateLastSyncInterval(sessionFactory, provider, realmId);
                    return ((ImportSynchronization) factory).sync(sessionFactory, realmId, provider);
                }
            });
        }
    });
    if (holder.result == null || !holder.result.isExecuted()) {
        logger.debugf("syncAllUsers for federation provider %s was ignored as it's already in progress", provider.getName());
        return SynchronizationResult.ignored();
    } else {
        return holder.result.getResult();
    }
}
Also used : UserStorageProvider(org.keycloak.storage.UserStorageProvider) ClusterProvider(org.keycloak.cluster.ClusterProvider) KeycloakSessionTask(org.keycloak.models.KeycloakSessionTask) UserStorageProviderFactory(org.keycloak.storage.UserStorageProviderFactory) ImportSynchronization(org.keycloak.storage.user.ImportSynchronization) KeycloakSession(org.keycloak.models.KeycloakSession) SynchronizationResult(org.keycloak.storage.user.SynchronizationResult)

Example 12 with KeycloakSessionTask

use of org.keycloak.models.KeycloakSessionTask in project keycloak by keycloak.

the class BatchTaskRunner method runInBatches.

static void runInBatches(int first, int count, int batchCount, KeycloakSessionFactory sessionFactory, BatchTask batchTask) {
    final StateHolder state = new StateHolder();
    state.firstInThisBatch = first;
    state.remaining = count;
    state.countInThisBatch = Math.min(batchCount, state.remaining);
    while (state.remaining > 0) {
        KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

            @Override
            public void run(KeycloakSession session) {
                batchTask.run(session, state.firstInThisBatch, state.countInThisBatch);
            }
        });
        // update state
        state.firstInThisBatch = state.firstInThisBatch + state.countInThisBatch;
        state.remaining = state.remaining - state.countInThisBatch;
        state.countInThisBatch = Math.min(batchCount, state.remaining);
    }
}
Also used : KeycloakSessionTask(org.keycloak.models.KeycloakSessionTask) KeycloakSession(org.keycloak.models.KeycloakSession)

Example 13 with KeycloakSessionTask

use of org.keycloak.models.KeycloakSessionTask in project keycloak by keycloak.

the class PersistSessionsCommand method createSessionsBatch.

private void createSessionsBatch(final int countInThisBatch) {
    final List<String> userSessionIds = new LinkedList<>();
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            RealmModel realm = session.realms().getRealmByName("master");
            ClientModel testApp = realm.getClientByClientId("security-admin-console");
            UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
            for (int i = 0; i < countInThisBatch; i++) {
                String username = "john-" + userCounter.incrementAndGet();
                UserModel john = session.users().getUserByUsername(realm, username);
                if (john == null) {
                    john = session.users().addUser(realm, username);
                }
                UserSessionModel userSession = session.sessions().createUserSession(realm, john, username, "127.0.0.2", "form", true, null, null);
                AuthenticatedClientSessionModel clientSession = session.sessions().createClientSession(realm, testApp, userSession);
                clientSession.setRedirectUri("http://redirect");
                clientSession.setNote("foo", "bar-" + i);
                userSessionIds.add(userSession.getId());
            }
        }
    });
    log.infof("%d sessions created in infinispan storage", countInThisBatch);
    // Persist them now
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            RealmModel realm = session.realms().getRealmByName("master");
            ClientModel testApp = realm.getClientByClientId("security-admin-console");
            UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
            int counter = 0;
            for (String userSessionId : userSessionIds) {
                counter++;
                UserSessionModel userSession = session.sessions().getUserSession(realm, userSessionId);
                persister.createUserSession(userSession, true);
                AuthenticatedClientSessionModel clientSession = userSession.getAuthenticatedClientSessions().get(testApp.getId());
                persister.createClientSession(clientSession, true);
            }
            log.infof("%d user sessions persisted. Continue", counter);
        }
    });
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) ClientModel(org.keycloak.models.ClientModel) UserSessionModel(org.keycloak.models.UserSessionModel) UserSessionPersisterProvider(org.keycloak.models.session.UserSessionPersisterProvider) KeycloakSessionTask(org.keycloak.models.KeycloakSessionTask) KeycloakSession(org.keycloak.models.KeycloakSession) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) LinkedList(java.util.LinkedList)

Example 14 with KeycloakSessionTask

use of org.keycloak.models.KeycloakSessionTask in project keycloak by keycloak.

the class PersistSessionsCommand method doRunCommand.

@Override
public void doRunCommand(KeycloakSession sess) {
    final int count = getIntArg(0);
    final int batchCount = getIntArg(1);
    int remaining = count;
    while (remaining > 0) {
        int createInThisBatch = Math.min(batchCount, remaining);
        createSessionsBatch(createInThisBatch);
        remaining = remaining - createInThisBatch;
    }
    // Write some summary
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            UserSessionPersisterProvider persister = session.getProvider(UserSessionPersisterProvider.class);
            log.info("Command finished. Total number of sessions in persister: " + persister.getUserSessionsCount(true));
        }
    });
}
Also used : UserSessionPersisterProvider(org.keycloak.models.session.UserSessionPersisterProvider) KeycloakSessionTask(org.keycloak.models.KeycloakSessionTask) KeycloakSession(org.keycloak.models.KeycloakSession)

Example 15 with KeycloakSessionTask

use of org.keycloak.models.KeycloakSessionTask in project keycloak by keycloak.

the class SyncDummyUserFederationProviderFactory method syncSince.

@Override
public SynchronizationResult syncSince(Date lastSync, KeycloakSessionFactory sessionFactory, String realmId, UserStorageProviderModel model) {
    KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {

        @Override
        public void run(KeycloakSession session) {
            int waitTime = Integer.parseInt(model.getConfig().getFirst(WAIT_TIME));
            logger.infof("Starting sync of changed users. Wait time is: %s", waitTime);
            RealmModel realm = session.realms().getRealm(realmId);
            // KEYCLOAK-2412 : Just remove and add some users for testing purposes
            for (int i = 0; i < 10; i++) {
                String username = "dummyuser-" + i;
                UserModel user = session.userLocalStorage().getUserByUsername(realm, username);
                if (user != null) {
                    session.userLocalStorage().removeUser(realm, user);
                }
                user = session.userLocalStorage().addUser(realm, username);
            }
            logger.infof("Finished sync of changed users. Waiting now for %d seconds", waitTime);
            try {
                latch1.await(waitTime * 1000, TimeUnit.MILLISECONDS);
            } catch (InterruptedException ie) {
                Thread.currentThread().interrupt();
                throw new RuntimeException("Interrupted!", ie);
            }
            logger.infof("Finished waiting");
        }
    });
    // countDown, so the SyncFederationTest can continue
    latch2.countDown();
    return new SynchronizationResult();
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserModel(org.keycloak.models.UserModel) KeycloakSessionTask(org.keycloak.models.KeycloakSessionTask) KeycloakSession(org.keycloak.models.KeycloakSession) SynchronizationResult(org.keycloak.storage.user.SynchronizationResult)

Aggregations

KeycloakSession (org.keycloak.models.KeycloakSession)15 KeycloakSessionTask (org.keycloak.models.KeycloakSessionTask)15 RealmModel (org.keycloak.models.RealmModel)5 SynchronizationResult (org.keycloak.storage.user.SynchronizationResult)4 UserModel (org.keycloak.models.UserModel)3 UserStorageProvider (org.keycloak.storage.UserStorageProvider)3 UserStorageProviderFactory (org.keycloak.storage.UserStorageProviderFactory)3 ImportSynchronization (org.keycloak.storage.user.ImportSynchronization)3 List (java.util.List)2 Cache (org.infinispan.Cache)2 RemoteCache (org.infinispan.client.hotrod.RemoteCache)2 ClusterProvider (org.keycloak.cluster.ClusterProvider)2 InfinispanConnectionProvider (org.keycloak.connections.infinispan.InfinispanConnectionProvider)2 ExportImportManager (org.keycloak.exportimport.ExportImportManager)2 KeycloakSessionFactory (org.keycloak.models.KeycloakSessionFactory)2 UserSessionPersisterProvider (org.keycloak.models.session.UserSessionPersisterProvider)2 InfinispanCacheInitializer (org.keycloak.models.sessions.infinispan.initializer.InfinispanCacheInitializer)2 RemoteCacheSessionsLoader (org.keycloak.models.sessions.infinispan.remotestore.RemoteCacheSessionsLoader)2 LDAPQuery (org.keycloak.storage.ldap.idm.query.internal.LDAPQuery)2 Date (java.util.Date)1