Search in sources :

Example 76 with TransportAddress

use of org.elasticsearch.common.transport.TransportAddress in project elasticsearch by elastic.

the class Netty4HttpServerTransport method bindAddress.

private TransportAddress bindAddress(final InetAddress hostAddress) {
    final AtomicReference<Exception> lastException = new AtomicReference<>();
    final AtomicReference<InetSocketAddress> boundSocket = new AtomicReference<>();
    boolean success = port.iterate(portNumber -> {
        try {
            synchronized (serverChannels) {
                ChannelFuture future = serverBootstrap.bind(new InetSocketAddress(hostAddress, portNumber)).sync();
                serverChannels.add(future.channel());
                boundSocket.set((InetSocketAddress) future.channel().localAddress());
            }
        } catch (Exception e) {
            lastException.set(e);
            return false;
        }
        return true;
    });
    if (!success) {
        throw new BindHttpException("Failed to bind to [" + port.getPortRangeString() + "]", lastException.get());
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Bound http to address {{}}", NetworkAddress.format(boundSocket.get()));
    }
    return new TransportAddress(boundSocket.get());
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) InetSocketAddress(java.net.InetSocketAddress) TransportAddress(org.elasticsearch.common.transport.TransportAddress) BoundTransportAddress(org.elasticsearch.common.transport.BoundTransportAddress) AtomicReference(java.util.concurrent.atomic.AtomicReference) BindHttpException(org.elasticsearch.http.BindHttpException) BindHttpException(org.elasticsearch.http.BindHttpException) BindTransportException(org.elasticsearch.transport.BindTransportException) ReadTimeoutException(io.netty.handler.timeout.ReadTimeoutException) IOException(java.io.IOException)

Example 77 with TransportAddress

use of org.elasticsearch.common.transport.TransportAddress in project elasticsearch by elastic.

the class Netty4HttpRequestSizeLimitIT method testDoesNotLimitExcludedRequests.

public void testDoesNotLimitExcludedRequests() throws Exception {
    ensureGreen();
    @SuppressWarnings("unchecked") Tuple<String, CharSequence>[] requestUris = new Tuple[1500];
    for (int i = 0; i < requestUris.length; i++) {
        requestUris[i] = Tuple.tuple("/_cluster/settings", "{ \"transient\": {\"search.default_search_timeout\": \"40s\" } }");
    }
    HttpServerTransport httpServerTransport = internalCluster().getInstance(HttpServerTransport.class);
    TransportAddress transportAddress = (TransportAddress) randomFrom(httpServerTransport.boundAddress().boundAddresses());
    try (Netty4HttpClient nettyHttpClient = new Netty4HttpClient()) {
        Collection<FullHttpResponse> responses = nettyHttpClient.put(transportAddress.address(), requestUris);
        assertThat(responses, hasSize(requestUris.length));
        assertAllInExpectedStatus(responses, HttpResponseStatus.OK);
    }
}
Also used : TransportAddress(org.elasticsearch.common.transport.TransportAddress) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) HttpServerTransport(org.elasticsearch.http.HttpServerTransport) Tuple(org.elasticsearch.common.collect.Tuple)

Example 78 with TransportAddress

use of org.elasticsearch.common.transport.TransportAddress in project elasticsearch by elastic.

the class Netty4HttpServerPipeliningTests method testThatHttpPipeliningCanBeDisabled.

public void testThatHttpPipeliningCanBeDisabled() throws Exception {
    final Settings settings = Settings.builder().put("http.pipelining", false).put("http.port", "0").build();
    try (HttpServerTransport httpServerTransport = new CustomNettyHttpServerTransport(settings)) {
        httpServerTransport.start();
        final TransportAddress transportAddress = randomFrom(httpServerTransport.boundAddress().boundAddresses());
        final int numberOfRequests = randomIntBetween(4, 16);
        final Set<Integer> slowIds = new HashSet<>();
        final List<String> requests = new ArrayList<>(numberOfRequests);
        for (int i = 0; i < numberOfRequests; i++) {
            if (rarely()) {
                requests.add("/slow/" + i);
                slowIds.add(i);
            } else {
                requests.add("/" + i);
            }
        }
        try (Netty4HttpClient nettyHttpClient = new Netty4HttpClient()) {
            Collection<FullHttpResponse> responses = nettyHttpClient.get(transportAddress.address(), requests.toArray(new String[] {}));
            List<String> responseBodies = new ArrayList<>(Netty4HttpClient.returnHttpResponseBodies(responses));
            // we can not be sure about the order of the responses, but the slow ones should come last
            assertThat(responseBodies, hasSize(numberOfRequests));
            for (int i = 0; i < numberOfRequests - slowIds.size(); i++) {
                assertThat(responseBodies.get(i), matches("/\\d+"));
            }
            final Set<Integer> ids = new HashSet<>();
            for (int i = 0; i < slowIds.size(); i++) {
                final String response = responseBodies.get(numberOfRequests - slowIds.size() + i);
                assertThat(response, matches("/slow/\\d+"));
                assertTrue(ids.add(Integer.parseInt(response.split("/")[2])));
            }
            assertThat(slowIds, equalTo(ids));
        }
    }
}
Also used : TransportAddress(org.elasticsearch.common.transport.TransportAddress) ArrayList(java.util.ArrayList) HttpServerTransport(org.elasticsearch.http.HttpServerTransport) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) Settings(org.elasticsearch.common.settings.Settings) HashSet(java.util.HashSet)

Example 79 with TransportAddress

use of org.elasticsearch.common.transport.TransportAddress in project elasticsearch by elastic.

the class Netty4HttpServerTransportTests method runExpectHeaderTest.

private void runExpectHeaderTest(final Settings settings, final String expectation, final int contentLength, final HttpResponseStatus expectedStatus) throws InterruptedException {
    final HttpServerTransport.Dispatcher dispatcher = new HttpServerTransport.Dispatcher() {

        @Override
        public void dispatchRequest(RestRequest request, RestChannel channel, ThreadContext threadContext) {
            channel.sendResponse(new BytesRestResponse(OK, BytesRestResponse.TEXT_CONTENT_TYPE, new BytesArray("done")));
        }

        @Override
        public void dispatchBadRequest(RestRequest request, RestChannel channel, ThreadContext threadContext, Throwable cause) {
            throw new AssertionError();
        }
    };
    try (Netty4HttpServerTransport transport = new Netty4HttpServerTransport(settings, networkService, bigArrays, threadPool, xContentRegistry(), dispatcher)) {
        transport.start();
        final TransportAddress remoteAddress = randomFrom(transport.boundAddress().boundAddresses());
        try (Netty4HttpClient client = new Netty4HttpClient()) {
            final FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/");
            request.headers().set(HttpHeaderNames.EXPECT, expectation);
            HttpUtil.setContentLength(request, contentLength);
            final FullHttpResponse response = client.post(remoteAddress.address(), request);
            assertThat(response.status(), equalTo(expectedStatus));
            if (expectedStatus.equals(HttpResponseStatus.CONTINUE)) {
                final FullHttpRequest continuationRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/", Unpooled.EMPTY_BUFFER);
                final FullHttpResponse continuationResponse = client.post(remoteAddress.address(), continuationRequest);
                assertThat(continuationResponse.status(), is(HttpResponseStatus.OK));
                assertThat(new String(ByteBufUtil.getBytes(continuationResponse.content()), StandardCharsets.UTF_8), is("done"));
            }
        }
    }
}
Also used : BytesArray(org.elasticsearch.common.bytes.BytesArray) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) FullHttpRequest(io.netty.handler.codec.http.FullHttpRequest) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) TransportAddress(org.elasticsearch.common.transport.TransportAddress) ThreadContext(org.elasticsearch.common.util.concurrent.ThreadContext) RestChannel(org.elasticsearch.rest.RestChannel) Matchers.containsString(org.hamcrest.Matchers.containsString) Strings.collectionToDelimitedString(org.elasticsearch.common.Strings.collectionToDelimitedString) NullDispatcher(org.elasticsearch.http.NullDispatcher) HttpServerTransport(org.elasticsearch.http.HttpServerTransport) RestRequest(org.elasticsearch.rest.RestRequest) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse)

Example 80 with TransportAddress

use of org.elasticsearch.common.transport.TransportAddress in project elasticsearch by elastic.

the class UnicastZenPingTests method testInvalidHosts.

public void testInvalidHosts() throws InterruptedException {
    final Logger logger = mock(Logger.class);
    final NetworkService networkService = new NetworkService(Settings.EMPTY, Collections.emptyList());
    final Transport transport = new MockTcpTransport(Settings.EMPTY, threadPool, BigArrays.NON_RECYCLING_INSTANCE, new NoneCircuitBreakerService(), new NamedWriteableRegistry(Collections.emptyList()), networkService, Version.CURRENT) {

        @Override
        public BoundTransportAddress boundAddress() {
            return new BoundTransportAddress(new TransportAddress[] { new TransportAddress(InetAddress.getLoopbackAddress(), 9300) }, new TransportAddress(InetAddress.getLoopbackAddress(), 9300));
        }
    };
    closeables.push(transport);
    final TransportService transportService = new TransportService(Settings.EMPTY, transport, threadPool, TransportService.NOOP_TRANSPORT_INTERCEPTOR, x -> null, null);
    closeables.push(transportService);
    final List<DiscoveryNode> discoveryNodes = TestUnicastZenPing.resolveHostsLists(executorService, logger, Arrays.asList("127.0.0.1:9300:9300", "127.0.0.1:9301"), 1, transportService, "test_", TimeValue.timeValueSeconds(1));
    // only one of the two is valid and will be used
    assertThat(discoveryNodes, hasSize(1));
    assertThat(discoveryNodes.get(0).getAddress().getAddress(), equalTo("127.0.0.1"));
    assertThat(discoveryNodes.get(0).getAddress().getPort(), equalTo(9301));
    verify(logger).warn(eq("failed to resolve host [127.0.0.1:9300:9300]"), Matchers.any(ExecutionException.class));
}
Also used : NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) MockTransportService(org.elasticsearch.test.transport.MockTransportService) TransportService(org.elasticsearch.transport.TransportService) TransportAddress(org.elasticsearch.common.transport.TransportAddress) BoundTransportAddress(org.elasticsearch.common.transport.BoundTransportAddress) BoundTransportAddress(org.elasticsearch.common.transport.BoundTransportAddress) NetworkService(org.elasticsearch.common.network.NetworkService) Logger(org.apache.logging.log4j.Logger) Transport(org.elasticsearch.transport.Transport) MockTcpTransport(org.elasticsearch.transport.MockTcpTransport) ExecutionException(java.util.concurrent.ExecutionException) MockTcpTransport(org.elasticsearch.transport.MockTcpTransport) NoneCircuitBreakerService(org.elasticsearch.indices.breaker.NoneCircuitBreakerService)

Aggregations

TransportAddress (org.elasticsearch.common.transport.TransportAddress)129 Settings (org.elasticsearch.common.settings.Settings)46 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)45 BoundTransportAddress (org.elasticsearch.common.transport.BoundTransportAddress)33 ArrayList (java.util.ArrayList)31 IOException (java.io.IOException)30 InetSocketAddress (java.net.InetSocketAddress)28 InetAddress (java.net.InetAddress)22 PreBuiltTransportClient (org.elasticsearch.transport.client.PreBuiltTransportClient)20 HashSet (java.util.HashSet)16 UnknownHostException (java.net.UnknownHostException)15 TransportClient (org.elasticsearch.client.transport.TransportClient)15 TransportService (org.elasticsearch.transport.TransportService)14 NamedWriteableRegistry (org.elasticsearch.common.io.stream.NamedWriteableRegistry)13 AtomicReference (java.util.concurrent.atomic.AtomicReference)12 ClusterState (org.elasticsearch.cluster.ClusterState)12 NetworkService (org.elasticsearch.common.network.NetworkService)12 ThreadPool (org.elasticsearch.threadpool.ThreadPool)12 HashMap (java.util.HashMap)11 List (java.util.List)11