Search in sources :

Example 1 with Lifecycle

use of org.elasticsearch.common.component.Lifecycle in project crate by crate.

the class TcpTransport method bindToPort.

private InetSocketAddress bindToPort(final String name, final InetAddress hostAddress, String port) {
    PortsRange portsRange = new PortsRange(port);
    final AtomicReference<Exception> lastException = new AtomicReference<>();
    final AtomicReference<InetSocketAddress> boundSocket = new AtomicReference<>();
    closeLock.writeLock().lock();
    try {
        // No need for locking here since Lifecycle objects can't move from STARTED to INITIALIZED
        if (lifecycle.initialized() == false && lifecycle.started() == false) {
            throw new IllegalStateException("transport has been stopped");
        }
        boolean success = portsRange.iterate(portNumber -> {
            try {
                TcpServerChannel channel = bind(name, new InetSocketAddress(hostAddress, portNumber));
                serverChannels.computeIfAbsent(name, k -> new ArrayList<>()).add(channel);
                boundSocket.set(channel.getLocalAddress());
            } catch (Exception e) {
                lastException.set(e);
                return false;
            }
            return true;
        });
        if (!success) {
            throw new BindTransportException("Failed to bind to " + NetworkAddress.format(hostAddress, portsRange), lastException.get());
        }
    } finally {
        closeLock.writeLock().unlock();
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Bound profile [{}] to address {{}}", name, NetworkAddress.format(boundSocket.get()));
    }
    return boundSocket.get();
}
Also used : ElasticsearchException(org.elasticsearch.ElasticsearchException) Arrays(java.util.Arrays) BigArrays(org.elasticsearch.common.util.BigArrays) ConcurrentCollections(org.elasticsearch.common.util.concurrent.ConcurrentCollections) ConcurrentCollections.newConcurrentMap(org.elasticsearch.common.util.concurrent.ConcurrentCollections.newConcurrentMap) PortsRange(org.elasticsearch.common.transport.PortsRange) InetAddress(java.net.InetAddress) Settings(org.elasticsearch.common.settings.Settings) Matcher(java.util.regex.Matcher) Map(java.util.Map) CountDown(org.elasticsearch.common.util.concurrent.CountDown) ThreadPool(org.elasticsearch.threadpool.ThreadPool) ReadWriteLock(java.util.concurrent.locks.ReadWriteLock) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) StreamCorruptedException(java.io.StreamCorruptedException) Setting(org.elasticsearch.common.settings.Setting) EnumMap(java.util.EnumMap) Set(java.util.Set) PageCacheRecycler(org.elasticsearch.common.util.PageCacheRecycler) BytesReference(org.elasticsearch.common.bytes.BytesReference) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Objects(java.util.Objects) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Version(org.elasticsearch.Version) MeanMetric(org.elasticsearch.common.metrics.MeanMetric) TransportAddress(org.elasticsearch.common.transport.TransportAddress) RestStatus(org.elasticsearch.rest.RestStatus) TimeValue(io.crate.common.unit.TimeValue) Pattern(java.util.regex.Pattern) VisibleForTesting(io.crate.common.annotations.VisibleForTesting) NetworkAddress(org.elasticsearch.common.network.NetworkAddress) CancelledKeyException(java.nio.channels.CancelledKeyException) NetworkExceptionHelper.isCloseConnectionException(org.elasticsearch.common.transport.NetworkExceptionHelper.isCloseConnectionException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) BoundTransportAddress(org.elasticsearch.common.transport.BoundTransportAddress) BindException(java.net.BindException) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) AtomicReference(java.util.concurrent.atomic.AtomicReference) Supplier(java.util.function.Supplier) Strings(org.elasticsearch.common.Strings) CircuitBreakerService(org.elasticsearch.indices.breaker.CircuitBreakerService) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) BytesArray(org.elasticsearch.common.bytes.BytesArray) HashSet(java.util.HashSet) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) NetworkService(org.elasticsearch.common.network.NetworkService) NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) CircuitBreaker(org.elasticsearch.common.breaker.CircuitBreaker) Node(org.elasticsearch.node.Node) CloseableChannel(org.elasticsearch.common.network.CloseableChannel) JvmInfo(org.elasticsearch.monitor.jvm.JvmInfo) IntHashSet(com.carrotsearch.hppc.IntHashSet) IntSet(com.carrotsearch.hppc.IntSet) IOException(java.io.IOException) AbstractLifecycleComponent(org.elasticsearch.common.component.AbstractLifecycleComponent) UnknownHostException(java.net.UnknownHostException) Lifecycle(org.elasticsearch.common.component.Lifecycle) StreamInput(org.elasticsearch.common.io.stream.StreamInput) NetworkExceptionHelper.isConnectException(org.elasticsearch.common.transport.NetworkExceptionHelper.isConnectException) NetworkUtils(org.elasticsearch.common.network.NetworkUtils) Collections.unmodifiableMap(java.util.Collections.unmodifiableMap) ThreadedActionListener(org.elasticsearch.action.support.ThreadedActionListener) LogManager(org.apache.logging.log4j.LogManager) Collections(java.util.Collections) ActionListener(org.elasticsearch.action.ActionListener) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList) AtomicReference(java.util.concurrent.atomic.AtomicReference) PortsRange(org.elasticsearch.common.transport.PortsRange) ElasticsearchException(org.elasticsearch.ElasticsearchException) StreamCorruptedException(java.io.StreamCorruptedException) CancelledKeyException(java.nio.channels.CancelledKeyException) NetworkExceptionHelper.isCloseConnectionException(org.elasticsearch.common.transport.NetworkExceptionHelper.isCloseConnectionException) BindException(java.net.BindException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) NetworkExceptionHelper.isConnectException(org.elasticsearch.common.transport.NetworkExceptionHelper.isConnectException)

Example 2 with Lifecycle

use of org.elasticsearch.common.component.Lifecycle in project crate by crate.

the class TcpTransportTests method testExceptionHandling.

private void testExceptionHandling(boolean startTransport, Exception exception, boolean expectClosed, MockLogAppender.LoggingExpectation... expectations) throws IllegalAccessException {
    final TestThreadPool testThreadPool = new TestThreadPool("test");
    MockLogAppender appender = new MockLogAppender();
    try {
        appender.start();
        Loggers.addAppender(LogManager.getLogger(TcpTransport.class), appender);
        for (MockLogAppender.LoggingExpectation expectation : expectations) {
            appender.addExpectation(expectation);
        }
        final Lifecycle lifecycle = new Lifecycle();
        if (startTransport) {
            lifecycle.moveToStarted();
        }
        final FakeTcpChannel channel = new FakeTcpChannel();
        final PlainActionFuture<Void> listener = new PlainActionFuture<>();
        channel.addCloseListener(listener);
        var logger = Loggers.getLogger(TcpTransport.class);
        TcpTransport.handleException(logger, channel, exception, lifecycle, new OutboundHandler(randomAlphaOfLength(10), Version.CURRENT, new StatsTracker(), testThreadPool, BigArrays.NON_RECYCLING_INSTANCE));
        if (expectClosed) {
            assertTrue(listener.isDone());
            assertThat(listener.actionGet(), nullValue());
        } else {
            assertFalse(listener.isDone());
        }
        appender.assertAllExpectationsMatched();
    } finally {
        Loggers.removeAppender(LogManager.getLogger(TcpTransport.class), appender);
        appender.stop();
        ThreadPool.terminate(testThreadPool, 30, TimeUnit.SECONDS);
    }
}
Also used : MockLogAppender(org.elasticsearch.test.MockLogAppender) PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture) Lifecycle(org.elasticsearch.common.component.Lifecycle) TestThreadPool(org.elasticsearch.threadpool.TestThreadPool)

Aggregations

IntHashSet (com.carrotsearch.hppc.IntHashSet)1 IntSet (com.carrotsearch.hppc.IntSet)1 VisibleForTesting (io.crate.common.annotations.VisibleForTesting)1 TimeValue (io.crate.common.unit.TimeValue)1 IOException (java.io.IOException)1 StreamCorruptedException (java.io.StreamCorruptedException)1 BindException (java.net.BindException)1 InetAddress (java.net.InetAddress)1 InetSocketAddress (java.net.InetSocketAddress)1 UnknownHostException (java.net.UnknownHostException)1 CancelledKeyException (java.nio.channels.CancelledKeyException)1 StandardCharsets (java.nio.charset.StandardCharsets)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 Collections (java.util.Collections)1 Collections.unmodifiableMap (java.util.Collections.unmodifiableMap)1 EnumMap (java.util.EnumMap)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 List (java.util.List)1