Search in sources :

Example 6 with TransportAddress

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

the class AbstractSimpleTransportTestCase method testTcpHandshakeConnectionReset.

public void testTcpHandshakeConnectionReset() throws IOException, InterruptedException {
    try (ServerSocket socket = new MockServerSocket()) {
        socket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0), 1);
        socket.setReuseAddress(true);
        DiscoveryNode dummy = new DiscoveryNode("TEST", new TransportAddress(socket.getInetAddress(), socket.getLocalPort()), emptyMap(), emptySet(), version0);
        Thread t = new Thread() {

            @Override
            public void run() {
                try (Socket accept = socket.accept()) {
                    if (randomBoolean()) {
                        // sometimes wait until the other side sends the message
                        accept.getInputStream().read();
                    }
                } catch (IOException e) {
                    throw new UncheckedIOException(e);
                }
            }
        };
        t.start();
        ConnectionProfile.Builder builder = new ConnectionProfile.Builder();
        builder.addConnections(1, TransportRequestOptions.Type.BULK, TransportRequestOptions.Type.PING, TransportRequestOptions.Type.RECOVERY, TransportRequestOptions.Type.REG, TransportRequestOptions.Type.STATE);
        builder.setHandshakeTimeout(TimeValue.timeValueHours(1));
        ConnectTransportException ex = expectThrows(ConnectTransportException.class, () -> serviceA.connectToNode(dummy, builder.build()));
        assertEquals(ex.getMessage(), "[][" + dummy.getAddress() + "] general node connection failure");
        assertThat(ex.getCause().getMessage(), startsWith("handshake failed"));
        t.join();
    }
}
Also used : DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) InetSocketAddress(java.net.InetSocketAddress) TransportAddress(org.elasticsearch.common.transport.TransportAddress) MockServerSocket(org.elasticsearch.mocksocket.MockServerSocket) ServerSocket(java.net.ServerSocket) MockServerSocket(org.elasticsearch.mocksocket.MockServerSocket) UncheckedIOException(java.io.UncheckedIOException) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) ServerSocket(java.net.ServerSocket) Socket(java.net.Socket) MockServerSocket(org.elasticsearch.mocksocket.MockServerSocket)

Example 7 with TransportAddress

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

the class AbstractSimpleTransportTestCase method testHostOnMessages.

public void testHostOnMessages() throws InterruptedException {
    final CountDownLatch latch = new CountDownLatch(2);
    final AtomicReference<TransportAddress> addressA = new AtomicReference<>();
    final AtomicReference<TransportAddress> addressB = new AtomicReference<>();
    serviceB.registerRequestHandler("action1", TestRequest::new, ThreadPool.Names.SAME, new TransportRequestHandler<TestRequest>() {

        @Override
        public void messageReceived(TestRequest request, TransportChannel channel) throws Exception {
            addressA.set(request.remoteAddress());
            channel.sendResponse(new TestResponse());
            latch.countDown();
        }
    });
    serviceA.sendRequest(nodeB, "action1", new TestRequest(), new TransportResponseHandler<TestResponse>() {

        @Override
        public TestResponse newInstance() {
            return new TestResponse();
        }

        @Override
        public void handleResponse(TestResponse response) {
            addressB.set(response.remoteAddress());
            latch.countDown();
        }

        @Override
        public void handleException(TransportException exp) {
            latch.countDown();
        }

        @Override
        public String executor() {
            return ThreadPool.Names.SAME;
        }
    });
    if (!latch.await(10, TimeUnit.SECONDS)) {
        fail("message round trip did not complete within a sensible time frame");
    }
    assertTrue(nodeA.getAddress().getAddress().equals(addressA.get().getAddress()));
    assertTrue(nodeB.getAddress().getAddress().equals(addressB.get().getAddress()));
}
Also used : TransportAddress(org.elasticsearch.common.transport.TransportAddress) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ElasticsearchException(org.elasticsearch.ElasticsearchException) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) ExecutionException(java.util.concurrent.ExecutionException)

Example 8 with TransportAddress

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

the class DiscoveryNodeTests method testDiscoveryNodeSerializationKeepsHost.

public void testDiscoveryNodeSerializationKeepsHost() throws Exception {
    InetAddress inetAddress = InetAddress.getByAddress("name1", new byte[] { (byte) 192, (byte) 168, (byte) 0, (byte) 1 });
    TransportAddress transportAddress = new TransportAddress(inetAddress, randomIntBetween(0, 65535));
    DiscoveryNode node = new DiscoveryNode("name1", "id1", transportAddress, emptyMap(), emptySet(), Version.CURRENT);
    BytesStreamOutput streamOutput = new BytesStreamOutput();
    streamOutput.setVersion(Version.CURRENT);
    node.writeTo(streamOutput);
    StreamInput in = StreamInput.wrap(streamOutput.bytes().toBytesRef().bytes);
    DiscoveryNode serialized = new DiscoveryNode(in);
    assertEquals(transportAddress.address().getHostString(), serialized.getHostName());
    assertEquals(transportAddress.address().getHostString(), serialized.getAddress().address().getHostString());
    assertEquals(transportAddress.getAddress(), serialized.getHostAddress());
    assertEquals(transportAddress.getAddress(), serialized.getAddress().getAddress());
    assertEquals(transportAddress.getPort(), serialized.getAddress().getPort());
}
Also used : TransportAddress(org.elasticsearch.common.transport.TransportAddress) StreamInput(org.elasticsearch.common.io.stream.StreamInput) InetAddress(java.net.InetAddress) BytesStreamOutput(org.elasticsearch.common.io.stream.BytesStreamOutput)

Example 9 with TransportAddress

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

the class DiscoveryNodeTests method testDiscoveryNodeSerializationToOldVersion.

public void testDiscoveryNodeSerializationToOldVersion() throws Exception {
    InetAddress inetAddress = InetAddress.getByAddress("name1", new byte[] { (byte) 192, (byte) 168, (byte) 0, (byte) 1 });
    TransportAddress transportAddress = new TransportAddress(inetAddress, randomIntBetween(0, 65535));
    DiscoveryNode node = new DiscoveryNode("name1", "id1", transportAddress, emptyMap(), emptySet(), Version.CURRENT);
    BytesStreamOutput streamOutput = new BytesStreamOutput();
    streamOutput.setVersion(Version.V_5_0_0);
    node.writeTo(streamOutput);
    StreamInput in = StreamInput.wrap(streamOutput.bytes().toBytesRef().bytes);
    in.setVersion(Version.V_5_0_0);
    DiscoveryNode serialized = new DiscoveryNode(in);
    assertEquals(transportAddress.address().getHostString(), serialized.getHostName());
    assertEquals(transportAddress.address().getHostString(), serialized.getAddress().address().getHostString());
    assertEquals(transportAddress.getAddress(), serialized.getHostAddress());
    assertEquals(transportAddress.getAddress(), serialized.getAddress().getAddress());
    assertEquals(transportAddress.getPort(), serialized.getAddress().getPort());
    assertFalse("if the minimum compatibility version moves past 5.0.3, remove the special casing in DiscoverNode(StreamInput) and " + "the TransportAddress(StreamInput, String) constructor", Version.CURRENT.minimumCompatibilityVersion().onOrAfter(Version.V_5_0_3_UNRELEASED));
}
Also used : TransportAddress(org.elasticsearch.common.transport.TransportAddress) StreamInput(org.elasticsearch.common.io.stream.StreamInput) InetAddress(java.net.InetAddress) BytesStreamOutput(org.elasticsearch.common.io.stream.BytesStreamOutput)

Example 10 with TransportAddress

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

the class BytesRestResponseTests method testErrorToAndFromXContent.

public void testErrorToAndFromXContent() throws IOException {
    final boolean detailed = randomBoolean();
    Exception original;
    ElasticsearchException cause = null;
    String reason;
    String type = "exception";
    RestStatus status = RestStatus.INTERNAL_SERVER_ERROR;
    boolean addHeadersOrMetadata = false;
    switch(randomIntBetween(0, 5)) {
        case 0:
            original = new ElasticsearchException("ElasticsearchException without cause");
            if (detailed) {
                addHeadersOrMetadata = randomBoolean();
                reason = "ElasticsearchException without cause";
            } else {
                reason = "ElasticsearchException[ElasticsearchException without cause]";
            }
            break;
        case 1:
            original = new ElasticsearchException("ElasticsearchException with a cause", new FileNotFoundException("missing"));
            if (detailed) {
                addHeadersOrMetadata = randomBoolean();
                type = "exception";
                reason = "ElasticsearchException with a cause";
                cause = new ElasticsearchException("Elasticsearch exception [type=file_not_found_exception, reason=missing]");
            } else {
                reason = "ElasticsearchException[ElasticsearchException with a cause]";
            }
            break;
        case 2:
            original = new ResourceNotFoundException("ElasticsearchException with custom status");
            status = RestStatus.NOT_FOUND;
            if (detailed) {
                addHeadersOrMetadata = randomBoolean();
                type = "resource_not_found_exception";
                reason = "ElasticsearchException with custom status";
            } else {
                reason = "ResourceNotFoundException[ElasticsearchException with custom status]";
            }
            break;
        case 3:
            TransportAddress address = buildNewFakeTransportAddress();
            original = new RemoteTransportException("remote", address, "action", new ResourceAlreadyExistsException("ElasticsearchWrapperException with a cause that has a custom status"));
            status = RestStatus.BAD_REQUEST;
            if (detailed) {
                type = "resource_already_exists_exception";
                reason = "ElasticsearchWrapperException with a cause that has a custom status";
            } else {
                reason = "RemoteTransportException[[remote][" + address.toString() + "][action]]";
            }
            break;
        case 4:
            original = new RemoteTransportException("ElasticsearchWrapperException with a cause that has a special treatment", new IllegalArgumentException("wrong"));
            status = RestStatus.BAD_REQUEST;
            if (detailed) {
                type = "illegal_argument_exception";
                reason = "wrong";
            } else {
                reason = "RemoteTransportException[[ElasticsearchWrapperException with a cause that has a special treatment]]";
            }
            break;
        case 5:
            status = randomFrom(RestStatus.values());
            original = new ElasticsearchStatusException("ElasticsearchStatusException with random status", status);
            if (detailed) {
                addHeadersOrMetadata = randomBoolean();
                type = "status_exception";
                reason = "ElasticsearchStatusException with random status";
            } else {
                reason = "ElasticsearchStatusException[ElasticsearchStatusException with random status]";
            }
            break;
        default:
            throw new UnsupportedOperationException("Failed to generate random exception");
    }
    String message = "Elasticsearch exception [type=" + type + ", reason=" + reason + "]";
    ElasticsearchStatusException expected = new ElasticsearchStatusException(message, status, cause);
    if (addHeadersOrMetadata) {
        ElasticsearchException originalException = ((ElasticsearchException) original);
        if (randomBoolean()) {
            originalException.addHeader("foo", "bar", "baz");
            expected.addHeader("foo", "bar", "baz");
        }
        if (randomBoolean()) {
            originalException.addMetadata("es.metadata_0", "0");
            expected.addMetadata("es.metadata_0", "0");
        }
        if (randomBoolean()) {
            String resourceType = randomAsciiOfLength(5);
            String resourceId = randomAsciiOfLength(5);
            originalException.setResources(resourceType, resourceId);
            expected.setResources(resourceType, resourceId);
        }
        if (randomBoolean()) {
            originalException.setIndex("_index");
            expected.setIndex("_index");
        }
    }
    final XContentType xContentType = randomFrom(XContentType.values());
    Map<String, String> params = Collections.singletonMap("format", xContentType.mediaType());
    RestRequest request = new FakeRestRequest.Builder(xContentRegistry()).withParams(params).build();
    RestChannel channel = detailed ? new DetailedExceptionRestChannel(request) : new SimpleExceptionRestChannel(request);
    BytesRestResponse response = new BytesRestResponse(channel, original);
    ElasticsearchException parsedError;
    try (XContentParser parser = createParser(xContentType.xContent(), response.content())) {
        parsedError = BytesRestResponse.errorFromXContent(parser);
        assertNull(parser.nextToken());
    }
    assertEquals(expected.status(), parsedError.status());
    assertDeepEquals(expected, parsedError);
}
Also used : RemoteTransportException(org.elasticsearch.transport.RemoteTransportException) TransportAddress(org.elasticsearch.common.transport.TransportAddress) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) FileNotFoundException(java.io.FileNotFoundException) ResourceAlreadyExistsException(org.elasticsearch.ResourceAlreadyExistsException) ElasticsearchException(org.elasticsearch.ElasticsearchException) Matchers.containsString(org.hamcrest.Matchers.containsString) ElasticsearchException(org.elasticsearch.ElasticsearchException) ParsingException(org.elasticsearch.common.ParsingException) ResourceAlreadyExistsException(org.elasticsearch.ResourceAlreadyExistsException) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException) ResourceNotFoundException(org.elasticsearch.ResourceNotFoundException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) SearchPhaseExecutionException(org.elasticsearch.action.search.SearchPhaseExecutionException) RemoteTransportException(org.elasticsearch.transport.RemoteTransportException) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException) XContentType(org.elasticsearch.common.xcontent.XContentType) FakeRestRequest(org.elasticsearch.test.rest.FakeRestRequest) ResourceNotFoundException(org.elasticsearch.ResourceNotFoundException) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Aggregations

TransportAddress (org.elasticsearch.common.transport.TransportAddress)89 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)32 Settings (org.elasticsearch.common.settings.Settings)29 ArrayList (java.util.ArrayList)24 BoundTransportAddress (org.elasticsearch.common.transport.BoundTransportAddress)24 IOException (java.io.IOException)21 InetSocketAddress (java.net.InetSocketAddress)20 InetAddress (java.net.InetAddress)19 UnknownHostException (java.net.UnknownHostException)12 NamedWriteableRegistry (org.elasticsearch.common.io.stream.NamedWriteableRegistry)12 TransportService (org.elasticsearch.transport.TransportService)12 HashSet (java.util.HashSet)11 TransportClient (org.elasticsearch.client.transport.TransportClient)11 NetworkService (org.elasticsearch.common.network.NetworkService)11 MockTransportService (org.elasticsearch.test.transport.MockTransportService)11 NoneCircuitBreakerService (org.elasticsearch.indices.breaker.NoneCircuitBreakerService)10 HashMap (java.util.HashMap)9 List (java.util.List)9 Logger (org.apache.logging.log4j.Logger)9 MockTcpTransport (org.elasticsearch.transport.MockTcpTransport)9