Search in sources :

Example 1 with ExecutorFilter

use of org.apache.mina.filter.executor.ExecutorFilter in project Openfire by igniterealtime.

the class StatCollector method run.

@Override
public void run() {
    try {
        // Collect content
        StringBuilder sb = new StringBuilder();
        // Add current timestamp
        sb.append(System.currentTimeMillis());
        sb.append(',');
        // Add info about the db connection pool
        sb.append(DbConnectionManager.getConnectionProvider().toString());
        sb.append(',');
        // Add info about the thread pool that process incoming requests
        ExecutorFilter executorFilter = (ExecutorFilter) socketAcceptor.getFilterChain().get(EXECUTOR_FILTER_NAME);
        ThreadPoolExecutor executor = (ThreadPoolExecutor) executorFilter.getExecutor();
        sb.append(executor.getCorePoolSize());
        sb.append(',');
        sb.append(executor.getActiveCount());
        sb.append(',');
        try {
            sb.append(executor.getQueue().size());
        } catch (UnsupportedOperationException e) {
            sb.append(-1);
        }
        sb.append(',');
        sb.append(executor.getCompletedTaskCount());
        // Add info about number of connected sessions
        sb.append(',');
        sb.append(SessionManager.getInstance().getConnectionsCount(false));
        // Add info about MINA statistics
        sb.append(',');
        sb.append(statCollector.getMsgRead());
        sb.append(',');
        sb.append(statCollector.getMsgWritten());
        sb.append(',');
        sb.append(statCollector.getQueuedEvents());
        sb.append(',');
        sb.append(statCollector.getScheduledWrites());
        // Add new line of content with current stats
        content.add(sb.toString());
        // Check if we need to print content to file (print content every minute)
        if (content.size() > (60f / frequency * 1000)) {
            try {
                File file = new File(JiveGlobals.getHomeDirectory() + File.separator + "logs", JiveGlobals.getProperty("statistic.filename", "stats.txt"));
                if (!file.exists()) {
                    file.createNewFile();
                }
                BufferedWriter out = new BufferedWriter(new FileWriter(file, true));
                if (!headerPrinter) {
                    out.write(new Date().toString());
                    out.write('\n');
                    out.write("Timestamp, DB min, DB max, DB current, DB used, Core Threads, Active Threads, Queue Tasks, Completed Tasks, Sessions, NIO Read, NIO Written, Queued NIO events, Queues NIO writes");
                    out.write('\n');
                    headerPrinter = true;
                }
                for (String line : content) {
                    out.write(line);
                    out.write('\n');
                }
                out.close();
            } catch (IOException e) {
                Log.error("Error creating statistics log file", e);
            }
            content.clear();
        }
    } catch (Exception e) {
        Log.error("Error collecting and logging server statistics", e);
    }
}
Also used : FileWriter(java.io.FileWriter) ExecutorFilter(org.apache.mina.filter.executor.ExecutorFilter) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) IOException(java.io.IOException) File(java.io.File) Date(java.util.Date) IOException(java.io.IOException) BufferedWriter(java.io.BufferedWriter)

Example 2 with ExecutorFilter

use of org.apache.mina.filter.executor.ExecutorFilter in project camel by apache.

the class MinaComponent method createDatagramEndpoint.

protected MinaEndpoint createDatagramEndpoint(String uri, MinaConfiguration configuration) {
    boolean minaLogger = configuration.isMinaLogger();
    long timeout = configuration.getTimeout();
    boolean transferExchange = configuration.isTransferExchange();
    boolean sync = configuration.isSync();
    List<IoFilter> filters = configuration.getFilters();
    ExecutorService acceptorPool = getCamelContext().getExecutorServiceManager().newCachedThreadPool(this, "MinaDatagramAcceptor");
    ExecutorService connectorPool = getCamelContext().getExecutorServiceManager().newCachedThreadPool(this, "MinaDatagramConnector");
    ExecutorService workerPool = getCamelContext().getExecutorServiceManager().newCachedThreadPool(this, "MinaThreadPool");
    IoAcceptor acceptor = new DatagramAcceptor(acceptorPool);
    IoConnector connector = new DatagramConnector(connectorPool);
    SocketAddress address = new InetSocketAddress(configuration.getHost(), configuration.getPort());
    if (transferExchange) {
        throw new IllegalArgumentException("transferExchange=true is not supported for datagram protocol");
    }
    DatagramConnectorConfig connectorConfig = new DatagramConnectorConfig();
    // must use manual thread model according to Mina documentation
    connectorConfig.setThreadModel(ThreadModel.MANUAL);
    configureDataGramCodecFactory("MinaProducer", connectorConfig, configuration);
    connectorConfig.getFilterChain().addLast("threadPool", new ExecutorFilter(workerPool));
    if (minaLogger) {
        connectorConfig.getFilterChain().addLast("logger", new LoggingFilter());
    }
    appendIoFiltersToChain(filters, connectorConfig.getFilterChain());
    // set connect timeout to mina in seconds
    connectorConfig.setConnectTimeout((int) (timeout / 1000));
    DatagramAcceptorConfig acceptorConfig = new DatagramAcceptorConfig();
    // must use manual thread model according to Mina documentation
    acceptorConfig.setThreadModel(ThreadModel.MANUAL);
    configureDataGramCodecFactory("MinaConsumer", acceptorConfig, configuration);
    acceptorConfig.setDisconnectOnUnbind(true);
    // reuse address is default true for datagram
    acceptorConfig.getFilterChain().addLast("threadPool", new ExecutorFilter(workerPool));
    if (minaLogger) {
        acceptorConfig.getFilterChain().addLast("logger", new LoggingFilter());
    }
    appendIoFiltersToChain(filters, acceptorConfig.getFilterChain());
    MinaEndpoint endpoint = new MinaEndpoint(uri, this);
    endpoint.setAddress(address);
    endpoint.setAcceptor(acceptor);
    endpoint.setAcceptorConfig(acceptorConfig);
    endpoint.setConnector(connector);
    endpoint.setConnectorConfig(connectorConfig);
    endpoint.setConfiguration(configuration);
    // enlist threads pools in use on endpoint
    endpoint.addThreadPool(acceptorPool);
    endpoint.addThreadPool(connectorPool);
    endpoint.addThreadPool(workerPool);
    // set sync or async mode after endpoint is created
    if (sync) {
        endpoint.setExchangePattern(ExchangePattern.InOut);
    } else {
        endpoint.setExchangePattern(ExchangePattern.InOnly);
    }
    return endpoint;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) ExecutorFilter(org.apache.mina.filter.executor.ExecutorFilter) LoggingFilter(org.apache.mina.filter.LoggingFilter) IoFilter(org.apache.mina.common.IoFilter) DatagramConnector(org.apache.mina.transport.socket.nio.DatagramConnector) DatagramConnectorConfig(org.apache.mina.transport.socket.nio.DatagramConnectorConfig) DatagramAcceptorConfig(org.apache.mina.transport.socket.nio.DatagramAcceptorConfig) DatagramAcceptor(org.apache.mina.transport.socket.nio.DatagramAcceptor) IoAcceptor(org.apache.mina.common.IoAcceptor) ExecutorService(java.util.concurrent.ExecutorService) IoConnector(org.apache.mina.common.IoConnector) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Example 3 with ExecutorFilter

use of org.apache.mina.filter.executor.ExecutorFilter in project camel by apache.

the class Mina2Consumer method setupDatagramProtocol.

protected void setupDatagramProtocol(String uri, Mina2Configuration configuration) {
    boolean minaLogger = configuration.isMinaLogger();
    List<IoFilter> filters = configuration.getFilters();
    address = new InetSocketAddress(configuration.getHost(), configuration.getPort());
    acceptor = new NioDatagramAcceptor();
    // acceptor connectorConfig
    configureDataGramCodecFactory("Mina2Consumer", acceptor, configuration);
    acceptor.setCloseOnDeactivation(true);
    // reuse address is default true for datagram
    if (configuration.isOrderedThreadPoolExecutor()) {
        workerPool = new OrderedThreadPoolExecutor(configuration.getMaximumPoolSize());
    } else {
        workerPool = new UnorderedThreadPoolExecutor(configuration.getMaximumPoolSize());
    }
    acceptor.getFilterChain().addLast("threadPool", new ExecutorFilter(workerPool));
    if (minaLogger) {
        acceptor.getFilterChain().addLast("logger", new LoggingFilter());
    }
    appendIoFiltersToChain(filters, acceptor.getFilterChain());
    if (configuration.getSslContextParameters() != null) {
        LOG.warn("Using datagram protocol, " + configuration.getProtocol() + ", but an SSLContextParameters instance was provided.  SSLContextParameters is only supported on the TCP protocol.");
    }
}
Also used : UnorderedThreadPoolExecutor(org.apache.mina.filter.executor.UnorderedThreadPoolExecutor) OrderedThreadPoolExecutor(org.apache.mina.filter.executor.OrderedThreadPoolExecutor) InetSocketAddress(java.net.InetSocketAddress) ExecutorFilter(org.apache.mina.filter.executor.ExecutorFilter) LoggingFilter(org.apache.mina.filter.logging.LoggingFilter) IoFilter(org.apache.mina.core.filterchain.IoFilter) NioDatagramAcceptor(org.apache.mina.transport.socket.nio.NioDatagramAcceptor)

Example 4 with ExecutorFilter

use of org.apache.mina.filter.executor.ExecutorFilter in project Openfire by igniterealtime.

the class MINAConnectionAcceptor method reconfigure.

@Override
public synchronized void reconfigure(ConnectionConfiguration configuration) {
    this.configuration = configuration;
    if (socketAcceptor == null) {
        // reconfig will occur when acceptor is started.
        return;
    }
    final DefaultIoFilterChainBuilder filterChain = socketAcceptor.getFilterChain();
    if (filterChain.contains(ConnectionManagerImpl.EXECUTOR_FILTER_NAME)) {
        final ExecutorFilter executorFilter = (ExecutorFilter) filterChain.get(ConnectionManagerImpl.EXECUTOR_FILTER_NAME);
        ((ThreadPoolExecutor) executorFilter.getExecutor()).setCorePoolSize((configuration.getMaxThreadPoolSize() / 4) + 1);
        ((ThreadPoolExecutor) executorFilter.getExecutor()).setMaximumPoolSize((configuration.getMaxThreadPoolSize()));
    }
    if (configuration.getTlsPolicy() == Connection.TLSPolicy.legacyMode) {
        // add or replace TLS filter (that's used only for 'direct-TLS')
        try {
            final SslFilter sslFilter = encryptionArtifactFactory.createServerModeSslFilter();
            if (filterChain.contains(ConnectionManagerImpl.TLS_FILTER_NAME)) {
                filterChain.replace(ConnectionManagerImpl.TLS_FILTER_NAME, sslFilter);
            } else {
                filterChain.addAfter(ConnectionManagerImpl.EXECUTOR_FILTER_NAME, ConnectionManagerImpl.TLS_FILTER_NAME, sslFilter);
            }
        } catch (KeyManagementException | NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException e) {
            Log.error("An exception occurred while reloading the TLS configuration.", e);
        }
    } else {
        // The acceptor is in 'startTLS' mode. Remove TLS filter (that's used only for 'direct-TLS')
        if (filterChain.contains(ConnectionManagerImpl.TLS_FILTER_NAME)) {
            filterChain.remove(ConnectionManagerImpl.TLS_FILTER_NAME);
        }
    }
    if (configuration.getMaxBufferSize() > 0) {
        socketAcceptor.getSessionConfig().setMaxReadBufferSize(configuration.getMaxBufferSize());
        Log.debug("Throttling read buffer for connections to max={} bytes", configuration.getMaxBufferSize());
    }
}
Also used : SslFilter(org.apache.mina.filter.ssl.SslFilter) UnrecoverableKeyException(java.security.UnrecoverableKeyException) ExecutorFilter(org.apache.mina.filter.executor.ExecutorFilter) DefaultIoFilterChainBuilder(org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) KeyManagementException(java.security.KeyManagementException)

Example 5 with ExecutorFilter

use of org.apache.mina.filter.executor.ExecutorFilter in project Openfire by igniterealtime.

the class MINAConnectionAcceptor method start.

/**
 * Starts this acceptor by binding the socket acceptor. When the acceptor is already started, a warning will be
 * logged and the method invocation is otherwise ignored.
 */
@Override
public synchronized void start() {
    if (socketAcceptor != null) {
        Log.warn("Unable to start acceptor (it is already started!)");
        return;
    }
    try {
        // Configure the thread pool that is to be used.
        final int initialSize = (configuration.getMaxThreadPoolSize() / 4) + 1;
        final ExecutorFilter executorFilter = new ExecutorFilter(initialSize, configuration.getMaxThreadPoolSize(), 60, TimeUnit.SECONDS);
        final ThreadPoolExecutor eventExecutor = (ThreadPoolExecutor) executorFilter.getExecutor();
        final ThreadFactory threadFactory = new NamedThreadFactory(name + "-thread-", eventExecutor.getThreadFactory(), true, null);
        eventExecutor.setThreadFactory(threadFactory);
        // Construct a new socket acceptor, and configure it.
        socketAcceptor = buildSocketAcceptor();
        if (JMXManager.isEnabled()) {
        // configureJMX( socketAcceptor, name );
        }
        final DefaultIoFilterChainBuilder filterChain = socketAcceptor.getFilterChain();
        filterChain.addFirst(ConnectionManagerImpl.EXECUTOR_FILTER_NAME, executorFilter);
        // Add the XMPP codec filter
        filterChain.addAfter(ConnectionManagerImpl.EXECUTOR_FILTER_NAME, ConnectionManagerImpl.XMPP_CODEC_FILTER_NAME, new ProtocolCodecFilter(new XMPPCodecFactory()));
        // Kill sessions whose outgoing queues keep growing and fail to send traffic
        filterChain.addAfter(ConnectionManagerImpl.XMPP_CODEC_FILTER_NAME, ConnectionManagerImpl.CAPACITY_FILTER_NAME, new StalledSessionsFilter());
        // Ports can be configured to start connections in SSL (as opposed to upgrade a non-encrypted socket to an encrypted one, typically using StartTLS)
        if (configuration.getTlsPolicy() == Connection.TLSPolicy.legacyMode) {
            final SslFilter sslFilter = encryptionArtifactFactory.createServerModeSslFilter();
            filterChain.addAfter(ConnectionManagerImpl.EXECUTOR_FILTER_NAME, ConnectionManagerImpl.TLS_FILTER_NAME, sslFilter);
        }
        // Throttle sessions who send data too fast
        if (configuration.getMaxBufferSize() > 0) {
            socketAcceptor.getSessionConfig().setMaxReadBufferSize(configuration.getMaxBufferSize());
            Log.debug("Throttling read buffer for connections to max={} bytes", configuration.getMaxBufferSize());
        }
        // Start accepting connections
        socketAcceptor.setHandler(connectionHandler);
        socketAcceptor.bind(new InetSocketAddress(configuration.getBindAddress(), configuration.getPort()));
    } catch (Exception e) {
        System.err.println("Error starting " + configuration.getPort() + ": " + e.getMessage());
        Log.error("Error starting: " + configuration.getPort(), e);
        // Reset for future use.
        if (socketAcceptor != null) {
            try {
                socketAcceptor.unbind();
            } finally {
                socketAcceptor = null;
            }
        }
    }
}
Also used : ThreadFactory(java.util.concurrent.ThreadFactory) NamedThreadFactory(org.jivesoftware.util.NamedThreadFactory) SslFilter(org.apache.mina.filter.ssl.SslFilter) NamedThreadFactory(org.jivesoftware.util.NamedThreadFactory) InetSocketAddress(java.net.InetSocketAddress) ExecutorFilter(org.apache.mina.filter.executor.ExecutorFilter) DefaultIoFilterChainBuilder(org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder) StalledSessionsFilter(org.jivesoftware.openfire.net.StalledSessionsFilter) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) ProtocolCodecFilter(org.apache.mina.filter.codec.ProtocolCodecFilter) KeyStoreException(java.security.KeyStoreException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) KeyManagementException(java.security.KeyManagementException) MalformedObjectNameException(javax.management.MalformedObjectNameException) JMException(javax.management.JMException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Aggregations

ExecutorFilter (org.apache.mina.filter.executor.ExecutorFilter)11 InetSocketAddress (java.net.InetSocketAddress)9 SslFilter (org.apache.mina.filter.ssl.SslFilter)6 IoFilter (org.apache.mina.core.filterchain.IoFilter)5 OrderedThreadPoolExecutor (org.apache.mina.filter.executor.OrderedThreadPoolExecutor)5 UnorderedThreadPoolExecutor (org.apache.mina.filter.executor.UnorderedThreadPoolExecutor)5 LoggingFilter (org.apache.mina.filter.logging.LoggingFilter)5 ThreadPoolExecutor (java.util.concurrent.ThreadPoolExecutor)3 IOException (java.io.IOException)2 SocketAddress (java.net.SocketAddress)2 KeyManagementException (java.security.KeyManagementException)2 KeyStoreException (java.security.KeyStoreException)2 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)2 UnrecoverableKeyException (java.security.UnrecoverableKeyException)2 ExecutorService (java.util.concurrent.ExecutorService)2 IoAcceptor (org.apache.mina.common.IoAcceptor)2 IoConnector (org.apache.mina.common.IoConnector)2 IoFilter (org.apache.mina.common.IoFilter)2 DefaultIoFilterChainBuilder (org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder)2 LoggingFilter (org.apache.mina.filter.LoggingFilter)2