Search in sources :

Example 21 with MockTransportService

use of org.elasticsearch.test.transport.MockTransportService 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 22 with MockTransportService

use of org.elasticsearch.test.transport.MockTransportService in project elasticsearch by elastic.

the class RemoteClusterServiceTests method testGroupClusterIndices.

public void testGroupClusterIndices() throws IOException {
    List<DiscoveryNode> knownNodes = new CopyOnWriteArrayList<>();
    try (MockTransportService seedTransport = startTransport("cluster_1_node", knownNodes, Version.CURRENT);
        MockTransportService otherSeedTransport = startTransport("cluster_2_node", knownNodes, Version.CURRENT)) {
        DiscoveryNode seedNode = seedTransport.getLocalDiscoNode();
        DiscoveryNode otherSeedNode = otherSeedTransport.getLocalDiscoNode();
        knownNodes.add(seedTransport.getLocalDiscoNode());
        knownNodes.add(otherSeedTransport.getLocalDiscoNode());
        Collections.shuffle(knownNodes, random());
        try (MockTransportService transportService = MockTransportService.createNewService(Settings.EMPTY, Version.CURRENT, threadPool, null)) {
            transportService.start();
            transportService.acceptIncomingRequests();
            Settings.Builder builder = Settings.builder();
            builder.putArray("search.remote.cluster_1.seeds", seedNode.getAddress().toString());
            builder.putArray("search.remote.cluster_2.seeds", otherSeedNode.getAddress().toString());
            try (RemoteClusterService service = new RemoteClusterService(builder.build(), transportService)) {
                assertFalse(service.isCrossClusterSearchEnabled());
                service.initializeRemoteClusters();
                assertTrue(service.isCrossClusterSearchEnabled());
                assertTrue(service.isRemoteClusterRegistered("cluster_1"));
                assertTrue(service.isRemoteClusterRegistered("cluster_2"));
                assertFalse(service.isRemoteClusterRegistered("foo"));
                Map<String, List<String>> perClusterIndices = service.groupClusterIndices(new String[] { "foo:bar", "cluster_1:bar", "cluster_2:foo:bar", "cluster_1:test", "cluster_2:foo*", "foo" }, i -> false);
                String[] localIndices = perClusterIndices.computeIfAbsent(RemoteClusterService.LOCAL_CLUSTER_GROUP_KEY, k -> Collections.emptyList()).toArray(new String[0]);
                assertNotNull(perClusterIndices.remove(RemoteClusterService.LOCAL_CLUSTER_GROUP_KEY));
                assertArrayEquals(new String[] { "foo:bar", "foo" }, localIndices);
                assertEquals(2, perClusterIndices.size());
                assertEquals(Arrays.asList("bar", "test"), perClusterIndices.get("cluster_1"));
                assertEquals(Arrays.asList("foo:bar", "foo*"), perClusterIndices.get("cluster_2"));
                IllegalArgumentException iae = expectThrows(IllegalArgumentException.class, () -> service.groupClusterIndices(new String[] { "foo:bar", "cluster_1:bar", "cluster_2:foo:bar", "cluster_1:test", "cluster_2:foo*", "foo" }, i -> "cluster_1:bar".equals(i)));
                assertEquals("Can not filter indices; index cluster_1:bar exists but there is also a remote cluster named:" + " cluster_1", iae.getMessage());
            }
        }
    }
}
Also used : ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) ShardId(org.elasticsearch.index.shard.ShardId) Arrays(java.util.Arrays) ShardIterator(org.elasticsearch.cluster.routing.ShardIterator) TermsQueryBuilder(org.elasticsearch.index.query.TermsQueryBuilder) HashMap(java.util.HashMap) ShardRoutingState(org.elasticsearch.cluster.routing.ShardRoutingState) Strings(org.elasticsearch.common.Strings) ArrayList(java.util.ArrayList) InetAddress(java.net.InetAddress) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) Settings(org.elasticsearch.common.settings.Settings) Map(java.util.Map) ThreadPool(org.elasticsearch.threadpool.ThreadPool) ESTestCase(org.elasticsearch.test.ESTestCase) MockTransportService(org.elasticsearch.test.transport.MockTransportService) ClusterSearchShardsGroup(org.elasticsearch.action.admin.cluster.shards.ClusterSearchShardsGroup) TestThreadPool(org.elasticsearch.threadpool.TestThreadPool) IOException(java.io.IOException) InetSocketAddress(java.net.InetSocketAddress) ClusterSearchShardsResponse(org.elasticsearch.action.admin.cluster.shards.ClusterSearchShardsResponse) TimeUnit(java.util.concurrent.TimeUnit) AliasFilter(org.elasticsearch.search.internal.AliasFilter) ClusterSettings(org.elasticsearch.common.settings.ClusterSettings) List(java.util.List) Version(org.elasticsearch.Version) TransportAddress(org.elasticsearch.common.transport.TransportAddress) MatchAllQueryBuilder(org.elasticsearch.index.query.MatchAllQueryBuilder) Collections(java.util.Collections) TestShardRouting(org.elasticsearch.cluster.routing.TestShardRouting) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) MockTransportService(org.elasticsearch.test.transport.MockTransportService) ArrayList(java.util.ArrayList) List(java.util.List) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) Settings(org.elasticsearch.common.settings.Settings) ClusterSettings(org.elasticsearch.common.settings.ClusterSettings) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 23 with MockTransportService

use of org.elasticsearch.test.transport.MockTransportService in project elasticsearch by elastic.

the class RemoteClusterServiceTests method testIncrementallyAddClusters.

public void testIncrementallyAddClusters() throws IOException {
    List<DiscoveryNode> knownNodes = new CopyOnWriteArrayList<>();
    try (MockTransportService seedTransport = startTransport("cluster_1_node", knownNodes, Version.CURRENT);
        MockTransportService otherSeedTransport = startTransport("cluster_2_node", knownNodes, Version.CURRENT)) {
        DiscoveryNode seedNode = seedTransport.getLocalDiscoNode();
        DiscoveryNode otherSeedNode = otherSeedTransport.getLocalDiscoNode();
        knownNodes.add(seedTransport.getLocalDiscoNode());
        knownNodes.add(otherSeedTransport.getLocalDiscoNode());
        Collections.shuffle(knownNodes, random());
        try (MockTransportService transportService = MockTransportService.createNewService(Settings.EMPTY, Version.CURRENT, threadPool, null)) {
            transportService.start();
            transportService.acceptIncomingRequests();
            Settings.Builder builder = Settings.builder();
            builder.putArray("search.remote.cluster_1.seeds", seedNode.getAddress().toString());
            builder.putArray("search.remote.cluster_2.seeds", otherSeedNode.getAddress().toString());
            try (RemoteClusterService service = new RemoteClusterService(Settings.EMPTY, transportService)) {
                assertFalse(service.isCrossClusterSearchEnabled());
                service.initializeRemoteClusters();
                assertFalse(service.isCrossClusterSearchEnabled());
                service.updateRemoteCluster("cluster_1", Collections.singletonList(seedNode.getAddress().address()));
                assertTrue(service.isCrossClusterSearchEnabled());
                assertTrue(service.isRemoteClusterRegistered("cluster_1"));
                service.updateRemoteCluster("cluster_2", Collections.singletonList(otherSeedNode.getAddress().address()));
                assertTrue(service.isCrossClusterSearchEnabled());
                assertTrue(service.isRemoteClusterRegistered("cluster_1"));
                assertTrue(service.isRemoteClusterRegistered("cluster_2"));
                service.updateRemoteCluster("cluster_2", Collections.emptyList());
                assertFalse(service.isRemoteClusterRegistered("cluster_2"));
                IllegalArgumentException iae = expectThrows(IllegalArgumentException.class, () -> service.updateRemoteCluster(RemoteClusterService.LOCAL_CLUSTER_GROUP_KEY, Collections.emptyList()));
                assertEquals("remote clusters must not have the empty string as its key", iae.getMessage());
            }
        }
    }
}
Also used : DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) MockTransportService(org.elasticsearch.test.transport.MockTransportService) Settings(org.elasticsearch.common.settings.Settings) ClusterSettings(org.elasticsearch.common.settings.ClusterSettings) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 24 with MockTransportService

use of org.elasticsearch.test.transport.MockTransportService in project elasticsearch by elastic.

the class RelocationIT method testCancellationCleansTempFiles.

public void testCancellationCleansTempFiles() throws Exception {
    final String indexName = "test";
    final String p_node = internalCluster().startNode();
    prepareCreate(indexName, Settings.builder().put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1, IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0)).get();
    internalCluster().startNode();
    internalCluster().startNode();
    List<IndexRequestBuilder> requests = new ArrayList<>();
    int numDocs = scaledRandomIntBetween(25, 250);
    for (int i = 0; i < numDocs; i++) {
        requests.add(client().prepareIndex(indexName, "type").setSource("{}", XContentType.JSON));
    }
    indexRandom(true, requests);
    assertFalse(client().admin().cluster().prepareHealth().setWaitForNodes("3").setWaitForGreenStatus().get().isTimedOut());
    flush();
    int allowedFailures = randomIntBetween(3, 10);
    logger.info("--> blocking recoveries from primary (allowed failures: [{}])", allowedFailures);
    CountDownLatch corruptionCount = new CountDownLatch(allowedFailures);
    ClusterService clusterService = internalCluster().getInstance(ClusterService.class, p_node);
    MockTransportService mockTransportService = (MockTransportService) internalCluster().getInstance(TransportService.class, p_node);
    for (DiscoveryNode node : clusterService.state().nodes()) {
        if (!node.equals(clusterService.localNode())) {
            mockTransportService.addDelegate(internalCluster().getInstance(TransportService.class, node.getName()), new RecoveryCorruption(mockTransportService.original(), corruptionCount));
        }
    }
    client().admin().indices().prepareUpdateSettings(indexName).setSettings(Settings.builder().put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 1)).get();
    corruptionCount.await();
    logger.info("--> stopping replica assignment");
    assertAcked(client().admin().cluster().prepareUpdateSettings().setTransientSettings(Settings.builder().put(EnableAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ENABLE_SETTING.getKey(), "none")));
    logger.info("--> wait for all replica shards to be removed, on all nodes");
    assertBusy(() -> {
        for (String node : internalCluster().getNodeNames()) {
            if (node.equals(p_node)) {
                continue;
            }
            ClusterState state = client(node).admin().cluster().prepareState().setLocal(true).get().getState();
            assertThat(node + " indicates assigned replicas", state.getRoutingTable().index(indexName).shardsWithState(ShardRoutingState.UNASSIGNED).size(), equalTo(1));
        }
    });
    logger.info("--> verifying no temporary recoveries are left");
    for (String node : internalCluster().getNodeNames()) {
        NodeEnvironment nodeEnvironment = internalCluster().getInstance(NodeEnvironment.class, node);
        for (final Path shardLoc : nodeEnvironment.availableShardPaths(new ShardId(indexName, "_na_", 0))) {
            if (Files.exists(shardLoc)) {
                assertBusy(() -> {
                    try {
                        Files.walkFileTree(shardLoc, new SimpleFileVisitor<Path>() {

                            @Override
                            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                                assertThat("found a temporary recovery file: " + file, file.getFileName().toString(), not(startsWith("recovery.")));
                                return FileVisitResult.CONTINUE;
                            }
                        });
                    } catch (IOException e) {
                        throw new AssertionError("failed to walk file tree starting at [" + shardLoc + "]", e);
                    }
                });
            }
        }
    }
}
Also used : Path(java.nio.file.Path) ClusterState(org.elasticsearch.cluster.ClusterState) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) MockTransportService(org.elasticsearch.test.transport.MockTransportService) NodeEnvironment(org.elasticsearch.env.NodeEnvironment) ArrayList(java.util.ArrayList) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) IndexRequestBuilder(org.elasticsearch.action.index.IndexRequestBuilder) ShardId(org.elasticsearch.index.shard.ShardId) ClusterService(org.elasticsearch.cluster.service.ClusterService) MockTransportService(org.elasticsearch.test.transport.MockTransportService) TransportService(org.elasticsearch.transport.TransportService) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes)

Example 25 with MockTransportService

use of org.elasticsearch.test.transport.MockTransportService in project elasticsearch by elastic.

the class Netty4ScheduledPingTests method testScheduledPing.

public void testScheduledPing() throws Exception {
    ThreadPool threadPool = new TestThreadPool(getClass().getName());
    Settings settings = Settings.builder().put(TcpTransport.PING_SCHEDULE.getKey(), "5ms").put(TransportSettings.PORT.getKey(), 0).put("cluster.name", "test").build();
    CircuitBreakerService circuitBreakerService = new NoneCircuitBreakerService();
    NamedWriteableRegistry registry = new NamedWriteableRegistry(Collections.emptyList());
    final Netty4Transport nettyA = new Netty4Transport(settings, threadPool, new NetworkService(settings, Collections.emptyList()), BigArrays.NON_RECYCLING_INSTANCE, registry, circuitBreakerService);
    MockTransportService serviceA = new MockTransportService(settings, nettyA, threadPool, TransportService.NOOP_TRANSPORT_INTERCEPTOR, null);
    serviceA.start();
    serviceA.acceptIncomingRequests();
    final Netty4Transport nettyB = new Netty4Transport(settings, threadPool, new NetworkService(settings, Collections.emptyList()), BigArrays.NON_RECYCLING_INSTANCE, registry, circuitBreakerService);
    MockTransportService serviceB = new MockTransportService(settings, nettyB, threadPool, TransportService.NOOP_TRANSPORT_INTERCEPTOR, null);
    serviceB.start();
    serviceB.acceptIncomingRequests();
    DiscoveryNode nodeA = serviceA.getLocalDiscoNode();
    DiscoveryNode nodeB = serviceB.getLocalDiscoNode();
    serviceA.connectToNode(nodeB);
    serviceB.connectToNode(nodeA);
    assertBusy(new Runnable() {

        @Override
        public void run() {
            assertThat(nettyA.getPing().getSuccessfulPings(), greaterThan(100L));
            assertThat(nettyB.getPing().getSuccessfulPings(), greaterThan(100L));
        }
    });
    assertThat(nettyA.getPing().getFailedPings(), equalTo(0L));
    assertThat(nettyB.getPing().getFailedPings(), equalTo(0L));
    serviceA.registerRequestHandler("sayHello", TransportRequest.Empty::new, ThreadPool.Names.GENERIC, new TransportRequestHandler<TransportRequest.Empty>() {

        @Override
        public void messageReceived(TransportRequest.Empty request, TransportChannel channel) {
            try {
                channel.sendResponse(TransportResponse.Empty.INSTANCE, TransportResponseOptions.EMPTY);
            } catch (IOException e) {
                logger.error("Unexpected failure", e);
                fail(e.getMessage());
            }
        }
    });
    int rounds = scaledRandomIntBetween(100, 5000);
    for (int i = 0; i < rounds; i++) {
        serviceB.submitRequest(nodeA, "sayHello", TransportRequest.Empty.INSTANCE, TransportRequestOptions.builder().withCompress(randomBoolean()).build(), new TransportResponseHandler<TransportResponse.Empty>() {

            @Override
            public TransportResponse.Empty newInstance() {
                return TransportResponse.Empty.INSTANCE;
            }

            @Override
            public String executor() {
                return ThreadPool.Names.GENERIC;
            }

            @Override
            public void handleResponse(TransportResponse.Empty response) {
            }

            @Override
            public void handleException(TransportException exp) {
                logger.error("Unexpected failure", exp);
                fail("got exception instead of a response: " + exp.getMessage());
            }
        }).txGet();
    }
    assertBusy(() -> {
        assertThat(nettyA.getPing().getSuccessfulPings(), greaterThan(200L));
        assertThat(nettyB.getPing().getSuccessfulPings(), greaterThan(200L));
    });
    assertThat(nettyA.getPing().getFailedPings(), equalTo(0L));
    assertThat(nettyB.getPing().getFailedPings(), equalTo(0L));
    Releasables.close(serviceA, serviceB);
    terminate(threadPool);
}
Also used : NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) TransportRequest(org.elasticsearch.transport.TransportRequest) MockTransportService(org.elasticsearch.test.transport.MockTransportService) ThreadPool(org.elasticsearch.threadpool.ThreadPool) TestThreadPool(org.elasticsearch.threadpool.TestThreadPool) TransportResponseHandler(org.elasticsearch.transport.TransportResponseHandler) IOException(java.io.IOException) TestThreadPool(org.elasticsearch.threadpool.TestThreadPool) TransportResponse(org.elasticsearch.transport.TransportResponse) TransportException(org.elasticsearch.transport.TransportException) NetworkService(org.elasticsearch.common.network.NetworkService) TransportChannel(org.elasticsearch.transport.TransportChannel) CircuitBreakerService(org.elasticsearch.indices.breaker.CircuitBreakerService) NoneCircuitBreakerService(org.elasticsearch.indices.breaker.NoneCircuitBreakerService) Settings(org.elasticsearch.common.settings.Settings) TransportSettings(org.elasticsearch.transport.TransportSettings) NoneCircuitBreakerService(org.elasticsearch.indices.breaker.NoneCircuitBreakerService)

Aggregations

MockTransportService (org.elasticsearch.test.transport.MockTransportService)42 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)25 IOException (java.io.IOException)19 Settings (org.elasticsearch.common.settings.Settings)17 CountDownLatch (java.util.concurrent.CountDownLatch)16 TransportService (org.elasticsearch.transport.TransportService)15 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)12 ArrayList (java.util.ArrayList)10 TransportRequest (org.elasticsearch.transport.TransportRequest)10 TransportRequestOptions (org.elasticsearch.transport.TransportRequestOptions)10 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)9 NamedWriteableRegistry (org.elasticsearch.common.io.stream.NamedWriteableRegistry)9 NetworkService (org.elasticsearch.common.network.NetworkService)9 NoneCircuitBreakerService (org.elasticsearch.indices.breaker.NoneCircuitBreakerService)8 TestThreadPool (org.elasticsearch.threadpool.TestThreadPool)8 ThreadPool (org.elasticsearch.threadpool.ThreadPool)8 TransportAddress (org.elasticsearch.common.transport.TransportAddress)7 InetSocketAddress (java.net.InetSocketAddress)6 AtomicReference (java.util.concurrent.atomic.AtomicReference)6 UncheckedIOException (java.io.UncheckedIOException)5