Search in sources :

Example 1 with TimerProvider

use of org.keycloak.timer.TimerProvider in project keycloak by keycloak.

the class TestingResourceProvider method restorePeriodicTasks.

@POST
@Path("/restore-periodic-tasks")
@Produces(MediaType.APPLICATION_JSON)
public Response restorePeriodicTasks() {
    TimerProvider timer = session.getProvider(TimerProvider.class);
    for (Map.Entry<String, TimerProvider.TimerTaskContext> task : suspendedTimerTasks.entrySet()) {
        timer.schedule(task.getValue().getRunnable(), task.getValue().getIntervalMillis(), task.getKey());
    }
    suspendedTimerTasks.clear();
    return Response.noContent().build();
}
Also used : TimerProvider(org.keycloak.timer.TimerProvider) Map(java.util.Map) HashMap(java.util.HashMap) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Example 2 with TimerProvider

use of org.keycloak.timer.TimerProvider in project keycloak by keycloak.

the class KeycloakApplication method setupScheduledTasks.

public static void setupScheduledTasks(final KeycloakSessionFactory sessionFactory) {
    long interval = Config.scope("scheduled").getLong("interval", 900L) * 1000;
    KeycloakSession session = sessionFactory.create();
    try {
        TimerProvider timer = session.getProvider(TimerProvider.class);
        timer.schedule(new ClusterAwareScheduledTaskRunner(sessionFactory, new ClearExpiredEvents(), interval), interval, "ClearExpiredEvents");
        timer.schedule(new ClusterAwareScheduledTaskRunner(sessionFactory, new ClearExpiredClientInitialAccessTokens(), interval), interval, "ClearExpiredClientInitialAccessTokens");
        timer.schedule(new ScheduledTaskRunner(sessionFactory, new ClearExpiredUserSessions()), interval, ClearExpiredUserSessions.TASK_NAME);
        new UserStorageSyncManager().bootstrapPeriodic(sessionFactory, timer);
    } finally {
        session.close();
    }
}
Also used : UserStorageSyncManager(org.keycloak.services.managers.UserStorageSyncManager) ClusterAwareScheduledTaskRunner(org.keycloak.services.scheduled.ClusterAwareScheduledTaskRunner) ScheduledTaskRunner(org.keycloak.services.scheduled.ScheduledTaskRunner) KeycloakSession(org.keycloak.models.KeycloakSession) ClusterAwareScheduledTaskRunner(org.keycloak.services.scheduled.ClusterAwareScheduledTaskRunner) TimerProvider(org.keycloak.timer.TimerProvider) ClearExpiredEvents(org.keycloak.services.scheduled.ClearExpiredEvents) ClearExpiredClientInitialAccessTokens(org.keycloak.services.scheduled.ClearExpiredClientInitialAccessTokens) ClearExpiredUserSessions(org.keycloak.services.scheduled.ClearExpiredUserSessions)

Example 3 with TimerProvider

use of org.keycloak.timer.TimerProvider in project keycloak by keycloak.

the class DefaultJpaConnectionProviderFactory method startGlobalStats.

protected void startGlobalStats(KeycloakSession session, int globalStatsIntervalSecs) {
    logger.debugf("Started Hibernate statistics with the interval %s seconds", globalStatsIntervalSecs);
    TimerProvider timer = session.getProvider(TimerProvider.class);
    timer.scheduleTask(new HibernateStatsReporter(emf), globalStatsIntervalSecs * 1000, "ReportHibernateGlobalStats");
}
Also used : TimerProvider(org.keycloak.timer.TimerProvider)

Example 4 with TimerProvider

use of org.keycloak.timer.TimerProvider in project keycloak by keycloak.

the class UserSessionProviderOfflineModelTest method testExpired.

@Test
public void testExpired() {
    // Suspend periodic tasks to avoid race-conditions, which may cause missing updates of lastSessionRefresh times to UserSessionPersisterProvider
    TimerProvider timer = kcSession.getProvider(TimerProvider.class);
    TimerProvider.TimerTaskContext timerTaskCtx = null;
    if (timer != null) {
        timerTaskCtx = timer.cancelTask(PersisterLastSessionRefreshStoreFactory.DB_LSR_PERIODIC_TASK_NAME);
        log.info("Cancelled periodic task " + PersisterLastSessionRefreshStoreFactory.DB_LSR_PERIODIC_TASK_NAME);
    }
    InfinispanTestUtil.setTestingTimeService(kcSession);
    try {
        // Key is userSessionId, value is set of client UUIDS
        Map<String, Set<String>> offlineSessions = new HashMap<>();
        ClientModel[] testApp = new ClientModel[1];
        UserSessionModel[] origSessions = inComittedTransaction(session -> {
            // Create some online sessions in infinispan
            return UserSessionPersisterProviderTest.createSessions(session, realmId);
        });
        inComittedTransaction(session -> {
            RealmModel realm = session.realms().getRealm(realmId);
            sessionManager = new UserSessionManager(session);
            persister = session.getProvider(UserSessionPersisterProvider.class);
            // Persist 3 created userSessions and clientSessions as offline
            testApp[0] = realm.getClientByClientId("test-app");
            session.sessions().getUserSessionsStream(realm, testApp[0]).collect(Collectors.toList()).forEach(userSession -> offlineSessions.put(userSession.getId(), createOfflineSessionIncludeClientSessions(session, userSession)));
            // Assert all previously saved offline sessions found
            for (Map.Entry<String, Set<String>> entry : offlineSessions.entrySet()) {
                UserSessionModel foundSession = sessionManager.findOfflineUserSession(realm, entry.getKey());
                Assert.assertEquals(foundSession.getAuthenticatedClientSessions().keySet(), entry.getValue());
            }
        });
        log.info("Persisted 3 sessions to UserSessionPersisterProvider");
        inComittedTransaction(session -> {
            RealmModel realm = session.realms().getRealm(realmId);
            persister = session.getProvider(UserSessionPersisterProvider.class);
            UserSessionModel session0 = session.sessions().getOfflineUserSession(realm, origSessions[0].getId());
            Assert.assertNotNull(session0);
            // sessions are in persister too
            Assert.assertEquals(3, persister.getUserSessionsCount(true));
            Time.setOffset(300);
            log.infof("Set time offset to 300. Time is: %d", Time.currentTime());
            // Set lastSessionRefresh to currentSession[0] to 0
            session0.setLastSessionRefresh(Time.currentTime());
        });
        // Increase timeOffset and update LSR of the session two times - first to 20 days and then to 21 days. At least one of updates
        // will propagate to PersisterLastSessionRefreshStore and update DB (Single update is not 100% sure as there is still a
        // chance of delayed periodic task to be run in the meantime and causing race-condition, which would mean LSR not updated in the DB)
        IntStream.range(0, 2).sequential().forEach(index -> inComittedTransaction(index, (session, i) -> {
            int timeOffset = 1728000 + (i * 86400);
            RealmModel realm = session.realms().getRealm(realmId);
            Time.setOffset(timeOffset);
            log.infof("Set time offset to %d. Time is: %d", timeOffset, Time.currentTime());
            UserSessionModel session0 = session.sessions().getOfflineUserSession(realm, origSessions[0].getId());
            session0.setLastSessionRefresh(Time.currentTime());
            return null;
        }));
        inComittedTransaction(session -> {
            RealmModel realm = session.realms().getRealm(realmId);
            persister = session.getProvider(UserSessionPersisterProvider.class);
            // Increase timeOffset - 40 days
            Time.setOffset(3456000);
            log.infof("Set time offset to 3456000. Time is: %d", Time.currentTime());
            // Expire and ensure that all sessions despite session0 were removed
            persister.removeExpired(realm);
        });
        inComittedTransaction(session -> {
            RealmModel realm = session.realms().getRealm(realmId);
            persister = session.getProvider(UserSessionPersisterProvider.class);
            // assert session0 is the only session found
            Assert.assertNotNull(session.sessions().getOfflineUserSession(realm, origSessions[0].getId()));
            Assert.assertNull(session.sessions().getOfflineUserSession(realm, origSessions[1].getId()));
            Assert.assertNull(session.sessions().getOfflineUserSession(realm, origSessions[2].getId()));
            Assert.assertEquals(1, persister.getUserSessionsCount(true));
            // Expire everything and assert nothing found
            Time.setOffset(7000000);
            persister.removeExpired(realm);
        });
        inComittedTransaction(session -> {
            RealmModel realm = session.realms().getRealm(realmId);
            sessionManager = new UserSessionManager(session);
            persister = session.getProvider(UserSessionPersisterProvider.class);
            for (String userSessionId : offlineSessions.keySet()) {
                Assert.assertNull(sessionManager.findOfflineUserSession(realm, userSessionId));
            }
            Assert.assertEquals(0, persister.getUserSessionsCount(true));
        });
    } finally {
        Time.setOffset(0);
        kcSession.getKeycloakSessionFactory().publish(new ResetTimeOffsetEvent());
        if (timer != null) {
            timer.schedule(timerTaskCtx.getRunnable(), timerTaskCtx.getIntervalMillis(), PersisterLastSessionRefreshStoreFactory.DB_LSR_PERIODIC_TASK_NAME);
        }
        InfinispanTestUtil.revertTimeService();
    }
}
Also used : ClientModel(org.keycloak.models.ClientModel) IntStream(java.util.stream.IntStream) UserSessionProvider(org.keycloak.models.UserSessionProvider) Constants(org.keycloak.models.Constants) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) Cache(org.infinispan.Cache) AtomicReference(java.util.concurrent.atomic.AtomicReference) HashSet(java.util.HashSet) UserModel(org.keycloak.models.UserModel) RealmProvider(org.keycloak.models.RealmProvider) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AuthenticatedClientSessionModel(org.keycloak.models.AuthenticatedClientSessionModel) Map(java.util.Map) RequireProvider(org.keycloak.testsuite.model.RequireProvider) LinkedList(java.util.LinkedList) TimerProvider(org.keycloak.timer.TimerProvider) Time(org.keycloak.common.util.Time) InfinispanConnectionProvider(org.keycloak.connections.infinispan.InfinispanConnectionProvider) InfinispanTestUtil(org.keycloak.testsuite.model.infinispan.InfinispanTestUtil) UserManager(org.keycloak.models.UserManager) RealmModel(org.keycloak.models.RealmModel) UserSessionPersisterProvider(org.keycloak.models.session.UserSessionPersisterProvider) KeycloakSession(org.keycloak.models.KeycloakSession) Set(java.util.Set) Test(org.junit.Test) PersisterLastSessionRefreshStoreFactory(org.keycloak.models.sessions.infinispan.changes.sessions.PersisterLastSessionRefreshStoreFactory) KeycloakModelTest(org.keycloak.testsuite.model.KeycloakModelTest) UserSessionModel(org.keycloak.models.UserSessionModel) Collectors(java.util.stream.Collectors) UserProvider(org.keycloak.models.UserProvider) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) UserSessionManager(org.keycloak.services.managers.UserSessionManager) ResetTimeOffsetEvent(org.keycloak.models.utils.ResetTimeOffsetEvent) Assert(org.junit.Assert) UserSessionModel(org.keycloak.models.UserSessionModel) HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) RealmModel(org.keycloak.models.RealmModel) UserSessionManager(org.keycloak.services.managers.UserSessionManager) ClientModel(org.keycloak.models.ClientModel) UserSessionPersisterProvider(org.keycloak.models.session.UserSessionPersisterProvider) ResetTimeOffsetEvent(org.keycloak.models.utils.ResetTimeOffsetEvent) TimerProvider(org.keycloak.timer.TimerProvider) HashMap(java.util.HashMap) Map(java.util.Map) Test(org.junit.Test) KeycloakModelTest(org.keycloak.testsuite.model.KeycloakModelTest)

Example 5 with TimerProvider

use of org.keycloak.timer.TimerProvider in project keycloak by keycloak.

the class UserSessionProviderOfflineModelTest method testLoadUserSessionsWithNotDeletedOfflineClientSessions.

@Test
public void testLoadUserSessionsWithNotDeletedOfflineClientSessions() {
    // Suspend periodic tasks to avoid race-conditions, which may cause missing updates of lastSessionRefresh times to UserSessionPersisterProvider
    TimerProvider timer = kcSession.getProvider(TimerProvider.class);
    TimerProvider.TimerTaskContext timerTaskCtx = null;
    if (timer != null) {
        timerTaskCtx = timer.cancelTask(PersisterLastSessionRefreshStoreFactory.DB_LSR_PERIODIC_TASK_NAME);
        log.info("Cancelled periodic task " + PersisterLastSessionRefreshStoreFactory.DB_LSR_PERIODIC_TASK_NAME);
    }
    InfinispanTestUtil.setTestingTimeService(kcSession);
    try {
        UserSessionModel[] origSessions = inComittedTransaction(session -> {
            // Create some online sessions in infinispan
            return UserSessionPersisterProviderTest.createSessions(session, realmId);
        });
        inComittedTransaction(session -> {
            RealmModel realm = session.realms().getRealm(realmId);
            sessionManager = new UserSessionManager(session);
            persister = session.getProvider(UserSessionPersisterProvider.class);
            session.sessions().getUserSessionsStream(realm, realm.getClientByClientId("test-app")).collect(Collectors.toList()).forEach(userSession -> createOfflineSessionIncludeClientSessions(session, userSession));
        });
        log.info("Persisted 3 sessions to UserSessionPersisterProvider");
        inComittedTransaction(session -> {
            persister = session.getProvider(UserSessionPersisterProvider.class);
            Assert.assertEquals(3, persister.getUserSessionsCount(true));
        });
        inComittedTransaction(session -> {
            RealmModel realm = session.realms().getRealm(realmId);
            persister = session.getProvider(UserSessionPersisterProvider.class);
            // Expire everything except offline client sessions
            Time.setOffset(7000000);
            persister.removeExpired(realm);
        });
        inComittedTransaction(session -> {
            RealmModel realm = session.realms().getRealm(realmId);
            sessionManager = new UserSessionManager(session);
            persister = session.getProvider(UserSessionPersisterProvider.class);
            Assert.assertEquals(0, persister.getUserSessionsCount(true));
            // create two offline user sessions
            UserSessionModel userSession = session.sessions().createUserSession(realm, session.users().getUserByUsername(realm, "user1"), "user1", "ip1", null, false, null, null);
            session.sessions().createOfflineUserSession(userSession);
            session.sessions().createOfflineUserSession(origSessions[0]);
            // try to load user session from persister
            Assert.assertEquals(2, persister.loadUserSessionsStream(0, 10, true, "00000000-0000-0000-0000-000000000000").count());
        });
    } finally {
        Time.setOffset(0);
        kcSession.getKeycloakSessionFactory().publish(new ResetTimeOffsetEvent());
        if (timer != null) {
            timer.schedule(timerTaskCtx.getRunnable(), timerTaskCtx.getIntervalMillis(), PersisterLastSessionRefreshStoreFactory.DB_LSR_PERIODIC_TASK_NAME);
        }
        InfinispanTestUtil.revertTimeService();
    }
}
Also used : RealmModel(org.keycloak.models.RealmModel) UserSessionManager(org.keycloak.services.managers.UserSessionManager) UserSessionModel(org.keycloak.models.UserSessionModel) UserSessionPersisterProvider(org.keycloak.models.session.UserSessionPersisterProvider) ResetTimeOffsetEvent(org.keycloak.models.utils.ResetTimeOffsetEvent) TimerProvider(org.keycloak.timer.TimerProvider) Test(org.junit.Test) KeycloakModelTest(org.keycloak.testsuite.model.KeycloakModelTest)

Aggregations

TimerProvider (org.keycloak.timer.TimerProvider)7 Test (org.junit.Test)3 KeycloakSession (org.keycloak.models.KeycloakSession)3 RealmModel (org.keycloak.models.RealmModel)3 UserSessionModel (org.keycloak.models.UserSessionModel)3 ResetTimeOffsetEvent (org.keycloak.models.utils.ResetTimeOffsetEvent)3 KeycloakModelTest (org.keycloak.testsuite.model.KeycloakModelTest)3 HashMap (java.util.HashMap)2 List (java.util.List)2 Map (java.util.Map)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 AuthenticatedClientSessionModel (org.keycloak.models.AuthenticatedClientSessionModel)2 UserSessionProvider (org.keycloak.models.UserSessionProvider)2 UserSessionPersisterProvider (org.keycloak.models.session.UserSessionPersisterProvider)2 UserSessionManager (org.keycloak.services.managers.UserSessionManager)2 HashSet (java.util.HashSet)1 LinkedList (java.util.LinkedList)1 Set (java.util.Set)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)1