use of org.keycloak.models.KeycloakSessionTask in project keycloak by keycloak.
the class InfinispanCacheInitializer method startLoading.
// Just coordinator will run this
@Override
protected void startLoading() {
InitializerState state = getStateFromCache();
SessionLoader.LoaderContext[] ctx = new SessionLoader.LoaderContext[1];
if (state == null) {
// Rather use separate transactions for update and counting
KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {
@Override
public void run(KeycloakSession session) {
sessionLoader.init(session);
}
});
KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {
@Override
public void run(KeycloakSession session) {
ctx[0] = sessionLoader.computeLoaderContext(session);
}
});
state = new InitializerState(ctx[0].getSegmentsCount());
} else {
KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {
@Override
public void run(KeycloakSession session) {
ctx[0] = sessionLoader.computeLoaderContext(session);
}
});
}
log.debugf("Start loading with loader: '%s', ctx: '%s' , state: %s", sessionLoader.toString(), ctx[0].toString(), state.toString());
startLoadingImpl(state, ctx[0]);
}
use of org.keycloak.models.KeycloakSessionTask in project keycloak by keycloak.
the class SessionInitializerWorker method apply.
@Override
public SessionLoader.WorkerResult apply(EmbeddedCacheManager embeddedCacheManager) {
Cache<Object, Object> workCache = embeddedCacheManager.getCache(cacheName);
if (log.isTraceEnabled()) {
log.tracef("Running computation for segment %s with worker %s", workerCtx.getSegment(), workerCtx.getWorkerId());
}
KeycloakSessionFactory sessionFactory = workCache.getAdvancedCache().getComponentRegistry().getComponent(KeycloakSessionFactory.class);
if (sessionFactory == null) {
log.debugf("KeycloakSessionFactory not yet set in cache. Worker skipped");
return sessionLoader.createFailedWorkerResult(loaderCtx, workerCtx);
}
SessionLoader.WorkerResult[] ref = new SessionLoader.WorkerResult[1];
KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {
@Override
public void run(KeycloakSession session) {
ref[0] = sessionLoader.loadSessions(session, loaderCtx, workerCtx);
}
});
return ref[0];
}
use of org.keycloak.models.KeycloakSessionTask in project keycloak by keycloak.
the class KeycloakApplication method bootstrap.
// Bootstrap master realm, import realms and create admin user.
protected ExportImportManager bootstrap() {
ExportImportManager[] exportImportManager = new ExportImportManager[1];
logger.debug("bootstrap");
KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {
@Override
public void run(KeycloakSession session) {
// TODO what is the purpose of following piece of code? Leaving it as is for now.
JtaTransactionManagerLookup lookup = (JtaTransactionManagerLookup) sessionFactory.getProviderFactory(JtaTransactionManagerLookup.class);
if (lookup != null) {
if (lookup.getTransactionManager() != null) {
try {
Transaction transaction = lookup.getTransactionManager().getTransaction();
logger.debugv("bootstrap current transaction? {0}", transaction != null);
if (transaction != null) {
logger.debugv("bootstrap current transaction status? {0}", transaction.getStatus());
}
} catch (SystemException e) {
throw new RuntimeException(e);
}
}
}
// TODO up here ^^
ApplianceBootstrap applianceBootstrap = new ApplianceBootstrap(session);
exportImportManager[0] = new ExportImportManager(session);
boolean createMasterRealm = applianceBootstrap.isNewInstall();
if (exportImportManager[0].isRunImport() && exportImportManager[0].isImportMasterIncluded()) {
createMasterRealm = false;
}
if (createMasterRealm) {
applianceBootstrap.createMasterRealm();
}
}
});
if (exportImportManager[0].isRunImport()) {
exportImportManager[0].runImport();
} else {
importRealms();
}
importAddUser();
return exportImportManager[0];
}
use of org.keycloak.models.KeycloakSessionTask in project keycloak by keycloak.
the class LDAPStorageProviderFactory method createQuery.
/**
* !! This function must be called from try-with-resources block, otherwise Vault secrets may be leaked !!
* @param sessionFactory
* @param realmId
* @param model
* @return
*/
private LDAPQuery createQuery(KeycloakSessionFactory sessionFactory, final String realmId, final ComponentModel model) {
class QueryHolder {
LDAPQuery query;
}
final QueryHolder queryHolder = new QueryHolder();
KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {
@Override
public void run(KeycloakSession session) {
session.getContext().setRealm(session.realms().getRealm(realmId));
LDAPStorageProvider ldapFedProvider = (LDAPStorageProvider) session.getProvider(UserStorageProvider.class, model);
RealmModel realm = session.realms().getRealm(realmId);
queryHolder.query = LDAPUtils.createQueryForUserSearch(ldapFedProvider, realm);
}
});
return queryHolder.query;
}
use of org.keycloak.models.KeycloakSessionTask in project keycloak by keycloak.
the class LDAPStorageProviderFactory method importLdapUsers.
protected SynchronizationResult importLdapUsers(KeycloakSessionFactory sessionFactory, final String realmId, final ComponentModel fedModel, List<LDAPObject> ldapUsers) {
final SynchronizationResult syncResult = new SynchronizationResult();
class BooleanHolder {
private boolean value = true;
}
final BooleanHolder exists = new BooleanHolder();
for (final LDAPObject ldapUser : ldapUsers) {
try {
// Process each user in it's own transaction to avoid global fail
KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {
@Override
public void run(KeycloakSession session) {
LDAPStorageProvider ldapFedProvider = (LDAPStorageProvider) session.getProvider(UserStorageProvider.class, fedModel);
RealmModel currentRealm = session.realms().getRealm(realmId);
session.getContext().setRealm(currentRealm);
String username = LDAPUtils.getUsername(ldapUser, ldapFedProvider.getLdapIdentityStore().getConfig());
exists.value = true;
LDAPUtils.checkUuid(ldapUser, ldapFedProvider.getLdapIdentityStore().getConfig());
UserModel currentUserLocal = session.userLocalStorage().getUserByUsername(currentRealm, username);
Optional<UserModel> userModelOptional = session.userLocalStorage().searchForUserByUserAttributeStream(currentRealm, LDAPConstants.LDAP_ID, ldapUser.getUuid()).findFirst();
if (!userModelOptional.isPresent() && currentUserLocal == null) {
// Add new user to Keycloak
exists.value = false;
ldapFedProvider.importUserFromLDAP(session, currentRealm, ldapUser);
syncResult.increaseAdded();
} else {
UserModel currentUser = userModelOptional.isPresent() ? userModelOptional.get() : currentUserLocal;
if ((fedModel.getId().equals(currentUser.getFederationLink())) && (ldapUser.getUuid().equals(currentUser.getFirstAttribute(LDAPConstants.LDAP_ID)))) {
// Update keycloak user
LDAPMappersComparator ldapMappersComparator = new LDAPMappersComparator(ldapFedProvider.getLdapIdentityStore().getConfig());
currentRealm.getComponentsStream(fedModel.getId(), LDAPStorageMapper.class.getName()).sorted(ldapMappersComparator.sortDesc()).forEachOrdered(mapperModel -> {
LDAPStorageMapper ldapMapper = ldapFedProvider.getMapperManager().getMapper(mapperModel);
ldapMapper.onImportUserFromLDAP(ldapUser, currentUser, currentRealm, false);
});
UserCache userCache = session.userCache();
if (userCache != null) {
userCache.evict(currentRealm, currentUser);
}
logger.debugf("Updated user from LDAP: %s", currentUser.getUsername());
syncResult.increaseUpdated();
} else {
logger.warnf("User with ID '%s' is not updated during sync as he already exists in Keycloak database but is not linked to federation provider '%s'", ldapUser.getUuid(), fedModel.getName());
syncResult.increaseFailed();
}
}
}
});
} catch (ModelException me) {
logger.error("Failed during import user from LDAP", me);
syncResult.increaseFailed();
// Remove user if we already added him during this transaction
if (!exists.value) {
KeycloakModelUtils.runJobInTransaction(sessionFactory, new KeycloakSessionTask() {
@Override
public void run(KeycloakSession session) {
LDAPStorageProvider ldapFedProvider = (LDAPStorageProvider) session.getProvider(UserStorageProvider.class, fedModel);
RealmModel currentRealm = session.realms().getRealm(realmId);
session.getContext().setRealm(currentRealm);
String username = null;
try {
username = LDAPUtils.getUsername(ldapUser, ldapFedProvider.getLdapIdentityStore().getConfig());
} catch (ModelException ignore) {
}
if (username != null) {
UserModel existing = session.userLocalStorage().getUserByUsername(currentRealm, username);
if (existing != null) {
UserCache userCache = session.userCache();
if (userCache != null) {
userCache.evict(currentRealm, existing);
}
session.userLocalStorage().removeUser(currentRealm, existing);
}
}
}
});
}
}
}
return syncResult;
}
Aggregations