Search in sources :

Example 1 with MockServerSocket

use of org.elasticsearch.mocksocket.MockServerSocket 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 2 with MockServerSocket

use of org.elasticsearch.mocksocket.MockServerSocket in project elasticsearch by elastic.

the class RemoteClusterConnectionTests method testSlowNodeCanBeCanceled.

@SuppressForbidden(reason = "calls getLocalHost here but it's fine in this case")
public void testSlowNodeCanBeCanceled() throws IOException, InterruptedException {
    try (ServerSocket socket = new MockServerSocket()) {
        socket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0), 1);
        socket.setReuseAddress(true);
        DiscoveryNode seedNode = new DiscoveryNode("TEST", new TransportAddress(socket.getInetAddress(), socket.getLocalPort()), emptyMap(), emptySet(), Version.CURRENT);
        CountDownLatch acceptedLatch = new CountDownLatch(1);
        CountDownLatch closeRemote = new CountDownLatch(1);
        Thread t = new Thread() {

            @Override
            public void run() {
                try (Socket accept = socket.accept()) {
                    acceptedLatch.countDown();
                    closeRemote.await();
                } catch (IOException e) {
                // that's fine we might close
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        };
        t.start();
        try (MockTransportService service = MockTransportService.createNewService(Settings.EMPTY, Version.CURRENT, threadPool, null)) {
            service.start();
            service.acceptIncomingRequests();
            CountDownLatch listenerCalled = new CountDownLatch(1);
            AtomicReference<Exception> exceptionReference = new AtomicReference<>();
            try (RemoteClusterConnection connection = new RemoteClusterConnection(Settings.EMPTY, "test-cluster", Arrays.asList(seedNode), service, Integer.MAX_VALUE, n -> true)) {
                ActionListener<Void> listener = ActionListener.wrap(x -> {
                    listenerCalled.countDown();
                    fail("expected exception");
                }, x -> {
                    exceptionReference.set(x);
                    listenerCalled.countDown();
                });
                connection.updateSeedNodes(Arrays.asList(seedNode), listener);
                acceptedLatch.await();
                // now close it, this should trigger an interrupt on the socket and we can move on
                connection.close();
                assertTrue(connection.assertNoRunningConnections());
            }
            closeRemote.countDown();
            listenerCalled.await();
            assertNotNull(exceptionReference.get());
            expectThrows(CancellableThreads.ExecutionCancelledException.class, () -> {
                throw exceptionReference.get();
            });
        }
    }
}
Also used : DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) CancellableThreads(org.elasticsearch.common.util.CancellableThreads) MockTransportService(org.elasticsearch.test.transport.MockTransportService) InetSocketAddress(java.net.InetSocketAddress) TransportAddress(org.elasticsearch.common.transport.TransportAddress) MockServerSocket(org.elasticsearch.mocksocket.MockServerSocket) ServerSocket(java.net.ServerSocket) MockServerSocket(org.elasticsearch.mocksocket.MockServerSocket) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) CountDownLatch(java.util.concurrent.CountDownLatch) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) AlreadyConnectedException(java.nio.channels.AlreadyConnectedException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) UnknownHostException(java.net.UnknownHostException) UncheckedIOException(java.io.UncheckedIOException) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket) MockServerSocket(org.elasticsearch.mocksocket.MockServerSocket) SuppressForbidden(org.elasticsearch.common.SuppressForbidden)

Example 3 with MockServerSocket

use of org.elasticsearch.mocksocket.MockServerSocket in project elasticsearch by elastic.

the class AbstractSimpleTransportTestCase method testTimeoutPerConnection.

public void testTimeoutPerConnection() throws IOException {
    assumeTrue("Works only on BSD network stacks and apparently windows", Constants.MAC_OS_X || Constants.FREE_BSD || Constants.WINDOWS);
    try (ServerSocket socket = new MockServerSocket()) {
        // note - this test uses backlog=1 which is implementation specific ie. it might not work on some TCP/IP stacks
        // on linux (at least newer ones) the listen(addr, backlog=1) should just ignore new connections if the queue is full which
        // means that once we received an ACK from the client we just drop the packet on the floor (which is what we want) and we run
        // into a connection timeout quickly. Yet other implementations can for instance can terminate the connection within the 3 way
        // handshake which I haven't tested yet.
        socket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0), 1);
        socket.setReuseAddress(true);
        DiscoveryNode first = new DiscoveryNode("TEST", new TransportAddress(socket.getInetAddress(), socket.getLocalPort()), emptyMap(), emptySet(), version0);
        DiscoveryNode second = new DiscoveryNode("TEST", new TransportAddress(socket.getInetAddress(), socket.getLocalPort()), emptyMap(), emptySet(), version0);
        ConnectionProfile.Builder builder = new ConnectionProfile.Builder();
        builder.addConnections(1, TransportRequestOptions.Type.BULK, TransportRequestOptions.Type.PING, TransportRequestOptions.Type.RECOVERY, TransportRequestOptions.Type.REG, TransportRequestOptions.Type.STATE);
        // connection with one connection and a large timeout -- should consume the one spot in the backlog queue
        try (TransportService service = buildService("TS_TPC", Version.CURRENT, null, Settings.EMPTY, true, false)) {
            IOUtils.close(service.openConnection(first, builder.build()));
            builder.setConnectTimeout(TimeValue.timeValueMillis(1));
            final ConnectionProfile profile = builder.build();
            // now with the 1ms timeout we got and test that is it's applied
            long startTime = System.nanoTime();
            ConnectTransportException ex = expectThrows(ConnectTransportException.class, () -> service.openConnection(second, profile));
            final long now = System.nanoTime();
            final long timeTaken = TimeValue.nsecToMSec(now - startTime);
            assertTrue("test didn't timeout quick enough, time taken: [" + timeTaken + "]", timeTaken < TimeValue.timeValueSeconds(5).millis());
            assertEquals(ex.getMessage(), "[][" + second.getAddress() + "] connect_timeout[1ms]");
        }
    }
}
Also used : DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) MockTransportService(org.elasticsearch.test.transport.MockTransportService) InetSocketAddress(java.net.InetSocketAddress) TransportAddress(org.elasticsearch.common.transport.TransportAddress) MockServerSocket(org.elasticsearch.mocksocket.MockServerSocket) ServerSocket(java.net.ServerSocket) MockServerSocket(org.elasticsearch.mocksocket.MockServerSocket)

Example 4 with MockServerSocket

use of org.elasticsearch.mocksocket.MockServerSocket in project elasticsearch by elastic.

the class AbstractSimpleTransportTestCase method testTcpHandshakeTimeout.

public void testTcpHandshakeTimeout() throws IOException {
    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);
        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.timeValueMillis(1));
        ConnectTransportException ex = expectThrows(ConnectTransportException.class, () -> serviceA.connectToNode(dummy, builder.build()));
        assertEquals("[][" + dummy.getAddress() + "] handshake_timeout[1ms]", ex.getMessage());
    }
}
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)

Example 5 with MockServerSocket

use of org.elasticsearch.mocksocket.MockServerSocket in project elasticsearch by elastic.

the class MockTcpTransport method bind.

@Override
protected MockChannel bind(final String name, InetSocketAddress address) throws IOException {
    MockServerSocket socket = new MockServerSocket();
    socket.bind(address);
    socket.setReuseAddress(TCP_REUSE_ADDRESS.get(settings));
    ByteSizeValue tcpReceiveBufferSize = TCP_RECEIVE_BUFFER_SIZE.get(settings);
    if (tcpReceiveBufferSize.getBytes() > 0) {
        socket.setReceiveBufferSize(tcpReceiveBufferSize.bytesAsInt());
    }
    MockChannel serverMockChannel = new MockChannel(socket, name);
    CountDownLatch started = new CountDownLatch(1);
    executor.execute(new AbstractRunnable() {

        @Override
        public void onFailure(Exception e) {
            try {
                onException(serverMockChannel, e);
            } catch (IOException ex) {
                logger.warn("failed on handling exception", ex);
            }
        }

        @Override
        protected void doRun() throws Exception {
            started.countDown();
            serverMockChannel.accept(executor);
        }
    });
    try {
        started.await();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
    return serverMockChannel;
}
Also used : AbstractRunnable(org.elasticsearch.common.util.concurrent.AbstractRunnable) MockServerSocket(org.elasticsearch.mocksocket.MockServerSocket) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) SocketException(java.net.SocketException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException)

Aggregations

MockServerSocket (org.elasticsearch.mocksocket.MockServerSocket)5 InetSocketAddress (java.net.InetSocketAddress)4 ServerSocket (java.net.ServerSocket)4 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)4 TransportAddress (org.elasticsearch.common.transport.TransportAddress)4 IOException (java.io.IOException)3 UncheckedIOException (java.io.UncheckedIOException)2 Socket (java.net.Socket)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)2 MockTransportService (org.elasticsearch.test.transport.MockTransportService)2 SocketException (java.net.SocketException)1 SocketTimeoutException (java.net.SocketTimeoutException)1 UnknownHostException (java.net.UnknownHostException)1 AlreadyConnectedException (java.nio.channels.AlreadyConnectedException)1 BrokenBarrierException (java.util.concurrent.BrokenBarrierException)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 AlreadyClosedException (org.apache.lucene.store.AlreadyClosedException)1 SuppressForbidden (org.elasticsearch.common.SuppressForbidden)1 ByteSizeValue (org.elasticsearch.common.unit.ByteSizeValue)1