Search in sources :

Example 16 with ShutdownListener

use of org.forgerock.util.thread.listener.ShutdownListener in project OpenAM by OpenRock.

the class SessionPollerPool method initPollerPool.

/**
     * Configures the threadpool, and registers the threadpool with the shutdown manager so that it correctly
     * shuts down when the server is brought down.
     */
private synchronized void initPollerPool() {
    if (!pollerPoolInitialized) {
        if (pollingEnabled) {
            int poolSize = SystemProperties.getAsInt(Constants.POLLING_THREADPOOL_SIZE, DEFAULT_POOL_SIZE);
            int threshold = SystemProperties.getAsInt(Constants.POLLING_THREADPOOL_THRESHOLD, DEFAULT_THRESHOLD);
            final ShutdownManager shutdownMan = com.sun.identity.common.ShutdownManager.getInstance();
            threadPool = new ThreadPool("amSessionPoller", poolSize, threshold, true, debug);
            shutdownMan.addShutdownListener(new ShutdownListener() {

                public void shutdown() {
                    threadPool.shutdown();
                    threadPool = null;
                    pollerPoolInitialized = false;
                }
            });
            pollerPoolInitialized = true;
        } else {
            if (debug.messageEnabled()) {
                debug.message("Session Cache cleanup is set to " + sessionCleanupEnabled);
            }
        }
    }
}
Also used : ShutdownListener(org.forgerock.util.thread.listener.ShutdownListener) ThreadPool(com.iplanet.am.util.ThreadPool) ShutdownManager(org.forgerock.util.thread.listener.ShutdownManager)

Example 17 with ShutdownListener

use of org.forgerock.util.thread.listener.ShutdownListener in project OpenAM by OpenRock.

the class LDAPFilterCondition method setPolicyConfig.

/**
     * Sets the policy configuration parameters used by this condition.
     */
private synchronized void setPolicyConfig(Map configParams, String realmDn) throws PolicyException {
    if (System.currentTimeMillis() < policyConfigExpiresAt) {
        return;
    }
    if (debug.messageEnabled()) {
        debug.message("LDAPFilterCondition.setPolicyConfig():policy config expired, resetting");
    }
    if (configParams == null) {
        debug.error("LDAPFilterCondition.setPolicyConfig():configParams is null");
        throw new PolicyException(ResBundleUtils.rbName, "ldapfiltercondition_setpolicyconfig_null_policy_config", null, null);
    }
    String configuredLdapServer = (String) configParams.get(PolicyConfig.LDAP_SERVER);
    if (configuredLdapServer == null) {
        debug.error("LDAPFilterCondition.initialize(): failed to get LDAP " + "server name. If you enter more than one server name " + "in the policy config service's Primary LDAP Server " + "field, please make sure the ldap server name is preceded " + "with the local server name.");
        throw new PolicyException(ResBundleUtils.rbName, "invalid_ldap_server_host", null, null);
    }
    ldapServer = configuredLdapServer.toLowerCase();
    aliasEnabled = Boolean.valueOf((String) configParams.get(PolicyConfig.USER_ALIAS_ENABLED));
    authid = (String) configParams.get(PolicyConfig.LDAP_BIND_DN);
    authpw = (String) configParams.get(PolicyConfig.LDAP_BIND_PASSWORD);
    if (authpw != null) {
        authpw = PolicyUtils.decrypt(authpw);
    }
    baseDN = (String) configParams.get(PolicyConfig.LDAP_USERS_BASE_DN);
    userSearchFilter = (String) configParams.get(PolicyConfig.LDAP_USERS_SEARCH_FILTER);
    String scope = (String) configParams.get(PolicyConfig.LDAP_USERS_SEARCH_SCOPE);
    userSearchScope = LDAPUtils.getSearchScope(scope, SearchScope.WHOLE_SUBTREE);
    userRDNAttrName = (String) configParams.get(PolicyConfig.LDAP_USER_SEARCH_ATTRIBUTE);
    try {
        timeLimit = Integer.parseInt((String) configParams.get(PolicyConfig.LDAP_SEARCH_TIME_OUT));
        maxResults = Integer.parseInt((String) configParams.get(PolicyConfig.LDAP_SEARCH_LIMIT));
        minPoolSize = Integer.parseInt((String) configParams.get(PolicyConfig.LDAP_CONNECTION_POOL_MIN_SIZE));
        maxPoolSize = Integer.parseInt((String) configParams.get(PolicyConfig.LDAP_CONNECTION_POOL_MAX_SIZE));
    } catch (NumberFormatException nfe) {
        throw new PolicyException(nfe);
    }
    String ssl = (String) configParams.get(PolicyConfig.LDAP_SSL_ENABLED);
    if (ssl.equalsIgnoreCase("true")) {
        sslEnabled = true;
    } else {
        sslEnabled = false;
    }
    // get the organization name
    if (realmDn != null) {
        orgName = realmDn;
    }
    if (debug.messageEnabled()) {
        debug.message("LDAPFilterCondition.setPolicyConfig(): " + "getting params" + "\nldapServer: " + ldapServer + "\nauthid: " + authid + "\nbaseDN: " + baseDN + "\nuserSearchFilter: " + userSearchFilter + "\nuserRDNAttrName: " + userRDNAttrName + "\ntimeLimit: " + timeLimit + "\nmaxResults: " + maxResults + "\nminPoolSize: " + minPoolSize + "\nmaxPoolSize: " + maxPoolSize + "\nSSLEnabled: " + sslEnabled + "\nOrgName: " + orgName);
    }
    // initialize the connection pool for the ldap server
    Options options = Options.defaultOptions().set(CONNECT_TIMEOUT, new Duration((long) timeLimit, TimeUnit.MILLISECONDS));
    LDAPConnectionPools.initConnectionPool(ldapServer, authid, authpw, sslEnabled, minPoolSize, maxPoolSize, options);
    connPool = LDAPConnectionPools.getConnectionPool(ldapServer);
    ShutdownManager shutdownMan = com.sun.identity.common.ShutdownManager.getInstance();
    shutdownMan.addShutdownListener(new ShutdownListener() {

        public void shutdown() {
            if (connPool != null) {
                connPool.close();
            }
        }
    });
    policyConfigExpiresAt = System.currentTimeMillis() + PolicyConfig.getSubjectsResultTtl(configParams);
}
Also used : ShutdownListener(org.forgerock.util.thread.listener.ShutdownListener) Options(org.forgerock.util.Options) PolicyException(com.sun.identity.policy.PolicyException) ShutdownManager(com.sun.identity.common.ShutdownManager) Duration(org.forgerock.util.time.Duration)

Example 18 with ShutdownListener

use of org.forgerock.util.thread.listener.ShutdownListener in project OpenAM by OpenRock.

the class EmbeddedOpenDS method startServer.

/**
     * Starts the embedded <code>OpenDJ</code> instance.
     *
     * @param odsRoot File system directory where <code>OpenDJ</code>
     *                is installed.
     * @throws Exception upon encountering errors.
     */
public static void startServer(String odsRoot) throws Exception {
    if (isStarted()) {
        return;
    }
    Debug debug = Debug.getInstance(SetupConstants.DEBUG_NAME);
    debug.message("EmbeddedOpenDS.startServer(" + odsRoot + ")");
    DirectoryEnvironmentConfig config = new DirectoryEnvironmentConfig();
    config.setServerRoot(new File(odsRoot));
    config.setForceDaemonThreads(true);
    config.setConfigClass(ConfigFileHandler.class);
    config.setConfigFile(new File(odsRoot + "/config", "config.ldif"));
    debug.message("EmbeddedOpenDS.startServer:starting DS Server...");
    EmbeddedUtils.startServer(config);
    debug.message("...EmbeddedOpenDS.startServer:DS Server started.");
    int sleepcount = 0;
    while (!EmbeddedUtils.isRunning() && (sleepcount < 60)) {
        sleepcount++;
        SetupProgress.reportStart("emb.waitingforstarted", null);
        Thread.sleep(1000);
    }
    if (EmbeddedUtils.isRunning()) {
        SetupProgress.reportEnd("emb.success", null);
    } else {
        SetupProgress.reportEnd("emb.failed", null);
    }
    serverStarted = true;
    ShutdownManager shutdownMan = com.sun.identity.common.ShutdownManager.getInstance();
    shutdownMan.addShutdownListener(new ShutdownListener() {

        public void shutdown() {
            try {
                shutdownServer("Graceful Shutdown");
            } catch (Exception ex) {
                Debug debug = Debug.getInstance(SetupConstants.DEBUG_NAME);
                debug.error("EmbeddedOpenDS:shutdown hook failed", ex);
            }
        }
    }, ShutdownPriority.LOWEST);
}
Also used : ShutdownListener(org.forgerock.util.thread.listener.ShutdownListener) ShutdownManager(com.sun.identity.common.ShutdownManager) DirectoryEnvironmentConfig(org.opends.server.types.DirectoryEnvironmentConfig) ZipFile(java.util.zip.ZipFile) File(java.io.File) Debug(com.sun.identity.shared.debug.Debug) FileNotFoundException(java.io.FileNotFoundException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) LdapException(org.forgerock.opendj.ldap.LdapException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IOException(java.io.IOException)

Example 19 with ShutdownListener

use of org.forgerock.util.thread.listener.ShutdownListener in project OpenAM by OpenRock.

the class SMSThreadPool method initialize.

static synchronized void initialize(boolean reinit) {
    // Check if already initialized
    if (reinit) {
        initialized = false;
    }
    if (initialized) {
        return;
    }
    int newPoolSize = DEFAULT_POOL_SIZE;
    try {
        if (SystemProperties.isServerMode()) {
            newPoolSize = Integer.parseInt(SystemProperties.get(Constants.SM_THREADPOOL_SIZE));
        } else {
            // For clients and CLIs, it is hardcoded to 3
            newPoolSize = 2;
        }
    } catch (Exception e) {
        newPoolSize = DEFAULT_POOL_SIZE;
    }
    if (newPoolSize == poolSize) {
        // No change in the pool size, return
        return;
    } else {
        poolSize = newPoolSize;
    }
    if (debug.messageEnabled()) {
        debug.message("SMSThreadPool: poolSize=" + poolSize);
    }
    ShutdownManager shutdownMan = com.sun.identity.common.ShutdownManager.getInstance();
    if (thrdPool != null) {
        // Create a new thread pool
        thrdPool = new ThreadPool("smIdmThreadPool", poolSize, DEFAULT_TRESHOLD, false, debug);
        // Create the shutdown hook
        ShutdownListener newShutdownListener = new ShutdownListener() {

            public void shutdown() {
                thrdPool.shutdown();
            }
        };
        // Register to shutdown hook
        shutdownMan.replaceShutdownListener(shutdownListener, newShutdownListener, null);
    } else {
        // Create a new thread pool
        thrdPool = new ThreadPool("smIdmThreadPool", poolSize, DEFAULT_TRESHOLD, false, debug);
        // Create the shutdown hook
        shutdownListener = new ShutdownListener() {

            public void shutdown() {
                thrdPool.shutdown();
            }
        };
        // Register to shutdown hook
        shutdownMan.addShutdownListener(shutdownListener);
    }
    initialized = true;
}
Also used : ShutdownListener(org.forgerock.util.thread.listener.ShutdownListener) ThreadPool(com.iplanet.am.util.ThreadPool) ShutdownManager(org.forgerock.util.thread.listener.ShutdownManager) ThreadPoolException(com.iplanet.am.util.ThreadPoolException)

Example 20 with ShutdownListener

use of org.forgerock.util.thread.listener.ShutdownListener in project OpenAM by OpenRock.

the class LDAPAuthUtils method createConnectionPool.

private ConnectionFactory createConnectionPool(Map<String, ConnectionFactory> connectionPools, String bindingUser, char[] bindingPwd) throws LdapException, LDAPUtilException {
    ConnectionFactory connPool;
    try {
        String configName = servers.toString() + ":" + bindingUser;
        connPool = connectionPools.get(configName);
        if (connPool == null) {
            synchronized (connectionPools) {
                connPool = connectionPools.get(configName);
                Options options = Options.defaultOptions().set(REQUEST_TIMEOUT, new Duration((long) operationsTimeout, TimeUnit.MILLISECONDS));
                if (connPool == null) {
                    if (debug.messageEnabled()) {
                        debug.message("Create ConnectionPool for servers:\n" + servers);
                    }
                    // Since connection pool for search and authentication
                    // are different, each gets half the configured size
                    int min = minDefaultPoolSize / 2 + 1;
                    int max = maxDefaultPoolSize / 2;
                    if (min >= max) {
                        min = max - 1;
                    }
                    Set<LDAPURL> primaryUrls = convertToLDAPURLs(primaryServers);
                    Set<LDAPURL> secondaryUrls = convertToLDAPURLs(secondaryServers);
                    if (poolSize != null && !poolSize.isEmpty()) {
                        String tmpmin = null;
                        String tmpmax = null;
                        for (String val : poolSize) {
                            // host:port:min:max
                            StringTokenizer stz = new StringTokenizer(val, ":");
                            if (stz.countTokens() == 4) {
                                LDAPURL url = LDAPURL.valueOf(stz.nextToken() + ":" + stz.nextToken());
                                if (primaryUrls.contains(url) || secondaryUrls.contains(url)) {
                                    tmpmin = stz.nextToken();
                                    tmpmax = stz.nextToken();
                                    break;
                                }
                            }
                        }
                        if (tmpmin != null) {
                            try {
                                min = Integer.parseInt(tmpmin);
                                max = Integer.parseInt(tmpmax);
                                if (max < min) {
                                    debug.error("ldap connection pool max size is less than min size");
                                    min = minDefaultPoolSize;
                                    max = maxDefaultPoolSize;
                                }
                            } catch (NumberFormatException ex) {
                                debug.error("Invalid ldap connection pool size", ex);
                                min = minDefaultPoolSize;
                                max = maxDefaultPoolSize;
                            }
                        }
                    }
                    if (debug.messageEnabled()) {
                        debug.message("LDAPAuthUtils.LDAPAuthUtils: min=" + min + ", max=" + max);
                    }
                    if (isSecure) {
                        SSLContextBuilder builder = new SSLContextBuilder();
                        if (trustAll) {
                            builder.setTrustManager(TrustManagers.trustAll());
                        }
                        SSLContext sslContext = builder.getSSLContext();
                        options.set(SSL_CONTEXT, sslContext);
                        if (useStartTLS) {
                            options.set(SSL_USE_STARTTLS, true);
                        }
                    }
                    final ConnectionFactory connFactory;
                    ConnectionFactory primaryCf = newFailoverConnectionPool(primaryUrls, bindingUser, bindingPwd, max, heartBeatInterval, heartBeatTimeUnit, options);
                    if (secondaryServers.isEmpty()) {
                        connFactory = primaryCf;
                    } else {
                        ConnectionFactory secondaryCf = newFailoverConnectionPool(secondaryUrls, bindingUser, bindingPwd, max, heartBeatInterval, heartBeatTimeUnit, options);
                        connFactory = Connections.newFailoverLoadBalancer(asList(primaryCf, secondaryCf), options);
                    }
                    ShutdownManager shutdownMan = com.sun.identity.common.ShutdownManager.getInstance();
                    shutdownMan.addShutdownListener(new ShutdownListener() {

                        public void shutdown() {
                            connFactory.close();
                        }
                    });
                    connPool = connFactory;
                    connectionPools.put(configName, connPool);
                }
            }
        }
    } catch (GeneralSecurityException gse) {
        debug.error("Unable to create connection pool", gse);
        throw new LDAPUtilException(gse);
    }
    return connPool;
}
Also used : Options(org.forgerock.util.Options) DecodeOptions(org.forgerock.opendj.ldap.DecodeOptions) GeneralSecurityException(java.security.GeneralSecurityException) ShutdownManager(com.sun.identity.common.ShutdownManager) Duration(org.forgerock.util.time.Duration) ByteString(org.forgerock.opendj.ldap.ByteString) SSLContext(javax.net.ssl.SSLContext) ShutdownListener(org.forgerock.util.thread.listener.ShutdownListener) ConnectionFactory(org.forgerock.opendj.ldap.ConnectionFactory) LDAPConnectionFactory(org.forgerock.opendj.ldap.LDAPConnectionFactory) StringTokenizer(java.util.StringTokenizer) SSLContextBuilder(org.forgerock.opendj.ldap.SSLContextBuilder)

Aggregations

ShutdownListener (org.forgerock.util.thread.listener.ShutdownListener)22 ShutdownManager (org.forgerock.util.thread.listener.ShutdownManager)10 LDAPConnectionFactory (org.forgerock.opendj.ldap.LDAPConnectionFactory)6 Options (org.forgerock.util.Options)4 Duration (org.forgerock.util.time.Duration)4 ShutdownManager (com.sun.identity.common.ShutdownManager)3 ConnectionFactory (org.forgerock.opendj.ldap.ConnectionFactory)3 SSLContextBuilder (org.forgerock.opendj.ldap.SSLContextBuilder)3 ThreadPool (com.iplanet.am.util.ThreadPool)2 DSConfigMgr (com.iplanet.services.ldap.DSConfigMgr)2 LDAPServiceException (com.iplanet.services.ldap.LDAPServiceException)2 ServerInstance (com.iplanet.services.ldap.ServerInstance)2 PolicyException (com.sun.identity.policy.PolicyException)2 IOException (java.io.IOException)2 ByteString (org.forgerock.opendj.ldap.ByteString)2 LdapException (org.forgerock.opendj.ldap.LdapException)2 InvocationOnMock (org.mockito.invocation.InvocationOnMock)2 Answer (org.mockito.stubbing.Answer)2 Test (org.testng.annotations.Test)2 ThreadPoolException (com.iplanet.am.util.ThreadPoolException)1