Search in sources :

Example 66 with TransportService

use of org.elasticsearch.transport.TransportService in project crate by crate.

the class FollowersCheckerTests method testBehaviourOfFailingNode.

private void testBehaviourOfFailingNode(Settings testSettings, Supplier<TransportResponse.Empty> responder, String failureReason, long expectedFailureTime) {
    final DiscoveryNode localNode = new DiscoveryNode("local-node", buildNewFakeTransportAddress(), Version.CURRENT);
    final DiscoveryNode otherNode = new DiscoveryNode("other-node", buildNewFakeTransportAddress(), Version.CURRENT);
    final Settings settings = Settings.builder().put(NODE_NAME_SETTING.getKey(), localNode.getName()).put(testSettings).build();
    final DeterministicTaskQueue deterministicTaskQueue = new DeterministicTaskQueue(settings, random());
    final MockTransport mockTransport = new MockTransport() {

        @Override
        protected void onSendRequest(long requestId, String action, TransportRequest request, DiscoveryNode node) {
            assertFalse(node.equals(localNode));
            deterministicTaskQueue.scheduleNow(new Runnable() {

                @Override
                public void run() {
                    if (node.equals(otherNode) == false) {
                        // other nodes are ok
                        handleResponse(requestId, Empty.INSTANCE);
                        return;
                    }
                    try {
                        final Empty response = responder.get();
                        if (response != null) {
                            handleResponse(requestId, response);
                        }
                    } catch (Exception e) {
                        handleRemoteError(requestId, e);
                    }
                }

                @Override
                public String toString() {
                    return "sending response to [" + action + "][" + requestId + "] from " + node;
                }
            });
        }
    };
    final TransportService transportService = mockTransport.createTransportService(settings, deterministicTaskQueue.getThreadPool(), boundTransportAddress -> localNode, null);
    transportService.start();
    transportService.acceptIncomingRequests();
    final AtomicBoolean nodeFailed = new AtomicBoolean();
    final FollowersChecker followersChecker = new FollowersChecker(settings, transportService, fcr -> {
        assert false : fcr;
    }, (node, reason) -> {
        assertTrue(nodeFailed.compareAndSet(false, true));
        assertThat(reason, equalTo(failureReason));
    });
    DiscoveryNodes discoveryNodes = DiscoveryNodes.builder().add(localNode).add(otherNode).localNodeId(localNode.getId()).build();
    followersChecker.setCurrentNodes(discoveryNodes);
    while (nodeFailed.get() == false) {
        if (deterministicTaskQueue.hasRunnableTasks() == false) {
            deterministicTaskQueue.advanceTime();
        }
        deterministicTaskQueue.runAllRunnableTasks();
    }
    assertThat(deterministicTaskQueue.getCurrentTimeMillis(), equalTo(expectedFailureTime));
    assertThat(followersChecker.getFaultyNodes(), contains(otherNode));
    deterministicTaskQueue.runAllTasks();
    // add another node and see that it schedules checks for this new node but keeps on considering the old one faulty
    final DiscoveryNode otherNode2 = new DiscoveryNode("other-node-2", buildNewFakeTransportAddress(), Version.CURRENT);
    discoveryNodes = DiscoveryNodes.builder(discoveryNodes).add(otherNode2).build();
    followersChecker.setCurrentNodes(discoveryNodes);
    deterministicTaskQueue.runAllRunnableTasks();
    deterministicTaskQueue.advanceTime();
    deterministicTaskQueue.runAllRunnableTasks();
    assertThat(followersChecker.getFaultyNodes(), contains(otherNode));
    // remove the faulty node and see that it is removed
    discoveryNodes = DiscoveryNodes.builder(discoveryNodes).remove(otherNode).build();
    followersChecker.setCurrentNodes(discoveryNodes);
    assertThat(followersChecker.getFaultyNodes(), empty());
    deterministicTaskQueue.runAllRunnableTasks();
    deterministicTaskQueue.advanceTime();
    deterministicTaskQueue.runAllRunnableTasks();
    // remove the working node and see that everything eventually stops
    discoveryNodes = DiscoveryNodes.builder(discoveryNodes).remove(otherNode2).build();
    followersChecker.setCurrentNodes(discoveryNodes);
    deterministicTaskQueue.runAllTasks();
    // add back the faulty node afresh and see that it fails again
    discoveryNodes = DiscoveryNodes.builder(discoveryNodes).add(otherNode).build();
    followersChecker.setCurrentNodes(discoveryNodes);
    nodeFailed.set(false);
    assertThat(followersChecker.getFaultyNodes(), empty());
    deterministicTaskQueue.runAllTasksInTimeOrder();
    assertTrue(nodeFailed.get());
    assertThat(followersChecker.getFaultyNodes(), contains(otherNode));
}
Also used : DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) TransportRequest(org.elasticsearch.transport.TransportRequest) ElasticsearchException(org.elasticsearch.ElasticsearchException) ConnectTransportException(org.elasticsearch.transport.ConnectTransportException) TransportException(org.elasticsearch.transport.TransportException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Empty(org.elasticsearch.transport.TransportResponse.Empty) TransportService(org.elasticsearch.transport.TransportService) MockTransport(org.elasticsearch.test.transport.MockTransport) Settings(org.elasticsearch.common.settings.Settings) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes)

Example 67 with TransportService

use of org.elasticsearch.transport.TransportService in project crate by crate.

the class PreVoteCollectorTests method createObjects.

@Before
public void createObjects() {
    Settings settings = Settings.builder().put(NODE_NAME_SETTING.getKey(), "node").build();
    deterministicTaskQueue = new DeterministicTaskQueue(settings, random());
    final MockTransport mockTransport = new MockTransport() {

        @Override
        protected void onSendRequest(final long requestId, final String action, final TransportRequest request, final DiscoveryNode node) {
            super.onSendRequest(requestId, action, request, node);
            assertThat(action, is(REQUEST_PRE_VOTE_ACTION_NAME));
            assertThat(request, instanceOf(PreVoteRequest.class));
            assertThat(node, not(equalTo(localNode)));
            PreVoteRequest preVoteRequest = (PreVoteRequest) request;
            assertThat(preVoteRequest.getSourceNode(), equalTo(localNode));
            deterministicTaskQueue.scheduleNow(new Runnable() {

                @Override
                public void run() {
                    final PreVoteResponse response = responsesByNode.get(node);
                    if (response == null) {
                        handleRemoteError(requestId, new ConnectTransportException(node, "no response"));
                    } else {
                        handleResponse(requestId, response);
                    }
                }

                @Override
                public String toString() {
                    return "response to " + request + " from " + node;
                }
            });
        }
    };
    lastAcceptedTerm = randomNonNegativeLong();
    currentTerm = randomLongBetween(lastAcceptedTerm, Long.MAX_VALUE);
    lastAcceptedVersion = randomNonNegativeLong();
    localNode = new DiscoveryNode("local-node", buildNewFakeTransportAddress(), Version.CURRENT);
    responsesByNode.put(localNode, new PreVoteResponse(currentTerm, lastAcceptedTerm, lastAcceptedVersion));
    transportService = mockTransport.createTransportService(settings, deterministicTaskQueue.getThreadPool(), boundTransportAddress -> localNode, null);
    transportService.start();
    transportService.acceptIncomingRequests();
    preVoteCollector = new PreVoteCollector(transportService, () -> {
        assert electionOccurred == false;
        electionOccurred = true;
    }, l -> {
    });
    // TODO need tests that check that the max term seen is updated
    preVoteCollector.update(getLocalPreVoteResponse(), null);
}
Also used : Arrays(java.util.Arrays) TransportRequest(org.elasticsearch.transport.TransportRequest) SAME(org.elasticsearch.threadpool.ThreadPool.Names.SAME) Matchers.not(org.hamcrest.Matchers.not) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) HashSet(java.util.HashSet) ClusterState(org.elasticsearch.cluster.ClusterState) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) ConnectTransportException(org.elasticsearch.transport.ConnectTransportException) Settings(org.elasticsearch.common.settings.Settings) Map(java.util.Map) Matchers.nullValue(org.hamcrest.Matchers.nullValue) VotingConfiguration(org.elasticsearch.cluster.coordination.CoordinationMetadata.VotingConfiguration) ESTestCase(org.elasticsearch.test.ESTestCase) TransportService(org.elasticsearch.transport.TransportService) Releasable(org.elasticsearch.common.lease.Releasable) Before(org.junit.Before) REQUEST_PRE_VOTE_ACTION_NAME(org.elasticsearch.cluster.coordination.PreVoteCollector.REQUEST_PRE_VOTE_ACTION_NAME) MockTransport(org.elasticsearch.test.transport.MockTransport) Set(java.util.Set) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) RemoteTransportException(org.elasticsearch.transport.RemoteTransportException) Version(org.elasticsearch.Version) NODE_NAME_SETTING(org.elasticsearch.node.Node.NODE_NAME_SETTING) StreamInput(org.elasticsearch.common.io.stream.StreamInput) Matchers.equalTo(org.hamcrest.Matchers.equalTo) TransportResponseHandler(org.elasticsearch.transport.TransportResponseHandler) Matchers.is(org.hamcrest.Matchers.is) TransportException(org.elasticsearch.transport.TransportException) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) TransportRequest(org.elasticsearch.transport.TransportRequest) ConnectTransportException(org.elasticsearch.transport.ConnectTransportException) MockTransport(org.elasticsearch.test.transport.MockTransport) Settings(org.elasticsearch.common.settings.Settings) Before(org.junit.Before)

Example 68 with TransportService

use of org.elasticsearch.transport.TransportService in project crate by crate.

the class PublicationTransportHandlerTests method testDiffSerializationFailure.

public void testDiffSerializationFailure() {
    DeterministicTaskQueue deterministicTaskQueue = new DeterministicTaskQueue(Settings.builder().put(Node.NODE_NAME_SETTING.getKey(), "test").build(), random());
    final ClusterSettings clusterSettings = new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS);
    final DiscoveryNode localNode = new DiscoveryNode("localNode", buildNewFakeTransportAddress(), Version.CURRENT);
    final TransportService transportService = new CapturingTransport().createTransportService(Settings.EMPTY, deterministicTaskQueue.getThreadPool(), x -> localNode, clusterSettings);
    final PublicationTransportHandler handler = new PublicationTransportHandler(transportService, writableRegistry(), pu -> null, (pu, l) -> {
    });
    transportService.start();
    transportService.acceptIncomingRequests();
    final DiscoveryNode otherNode = new DiscoveryNode("otherNode", buildNewFakeTransportAddress(), Version.CURRENT);
    final ClusterState clusterState = CoordinationStateTests.clusterState(2L, 1L, DiscoveryNodes.builder().add(localNode).add(otherNode).localNodeId(localNode.getId()).build(), VotingConfiguration.EMPTY_CONFIG, VotingConfiguration.EMPTY_CONFIG, 0L);
    final ClusterState unserializableClusterState = new ClusterState(clusterState.version(), clusterState.stateUUID(), clusterState) {

        @Override
        public Diff<ClusterState> diff(ClusterState previousState) {
            return new Diff<ClusterState>() {

                @Override
                public ClusterState apply(ClusterState part) {
                    fail("this diff shouldn't be applied");
                    return part;
                }

                @Override
                public void writeTo(StreamOutput out) throws IOException {
                    throw new IOException("Simulated failure of diff serialization");
                }
            };
        }
    };
    ElasticsearchException e = expectThrows(ElasticsearchException.class, () -> handler.newPublicationContext(new ClusterChangedEvent("test", unserializableClusterState, clusterState)));
    assertNotNull(e.getCause());
    assertThat(e.getCause(), instanceOf(IOException.class));
    assertThat(e.getCause().getMessage(), containsString("Simulated failure of diff serialization"));
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) ClusterSettings(org.elasticsearch.common.settings.ClusterSettings) TransportService(org.elasticsearch.transport.TransportService) Diff(org.elasticsearch.cluster.Diff) CapturingTransport(org.elasticsearch.test.transport.CapturingTransport) ClusterChangedEvent(org.elasticsearch.cluster.ClusterChangedEvent) IOException(java.io.IOException) ElasticsearchException(org.elasticsearch.ElasticsearchException) StreamOutput(org.elasticsearch.common.io.stream.StreamOutput)

Example 69 with TransportService

use of org.elasticsearch.transport.TransportService in project crate by crate.

the class PeerFinderTests method setup.

@Before
public void setup() {
    capturingTransport = new CapturingTransport();
    transportAddressConnector = new MockTransportAddressConnector();
    providedAddresses = new ArrayList<>();
    addressResolveDelay = 0L;
    final Settings settings = Settings.builder().put(NODE_NAME_SETTING.getKey(), "node").build();
    deterministicTaskQueue = new DeterministicTaskQueue(settings, random());
    localNode = newDiscoveryNode("local-node");
    ConnectionManager innerConnectionManager = new ConnectionManager(settings, capturingTransport);
    StubbableConnectionManager connectionManager = new StubbableConnectionManager(innerConnectionManager, settings, capturingTransport, deterministicTaskQueue.getThreadPool());
    connectionManager.setDefaultNodeConnectedBehavior(cm -> {
        assertTrue(Sets.haveEmptyIntersection(connectedNodes, disconnectedNodes));
        return connectedNodes;
    });
    connectionManager.setDefaultGetConnectionBehavior((cm, discoveryNode) -> capturingTransport.createConnection(discoveryNode));
    transportService = new TransportService(settings, capturingTransport, deterministicTaskQueue.getThreadPool(), boundTransportAddress -> localNode, null, connectionManager);
    transportService.start();
    transportService.acceptIncomingRequests();
    lastAcceptedNodes = DiscoveryNodes.builder().localNodeId(localNode.getId()).add(localNode).build();
    peerFinder = new TestPeerFinder(settings, transportService, transportAddressConnector);
    foundPeersFromNotification = emptyList();
}
Also used : ElasticsearchException(org.elasticsearch.ElasticsearchException) Arrays(java.util.Arrays) Builder(org.elasticsearch.cluster.node.DiscoveryNodes.Builder) Matchers.emptyArray(org.hamcrest.Matchers.emptyArray) CapturingTransport(org.elasticsearch.test.transport.CapturingTransport) Collections.singletonList(java.util.Collections.singletonList) Sets(io.crate.common.collections.Sets) Settings(org.elasticsearch.common.settings.Settings) After(org.junit.After) Map(java.util.Map) Matchers.nullValue(org.hamcrest.Matchers.nullValue) DeterministicTaskQueue(org.elasticsearch.cluster.coordination.DeterministicTaskQueue) Collections.emptyList(java.util.Collections.emptyList) Set(java.util.Set) ConnectionManager(org.elasticsearch.transport.ConnectionManager) Collectors(java.util.stream.Collectors) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) List(java.util.List) Version(org.elasticsearch.Version) Stream(java.util.stream.Stream) TransportAddress(org.elasticsearch.common.transport.TransportAddress) NODE_NAME_SETTING(org.elasticsearch.node.Node.NODE_NAME_SETTING) Matchers.contains(org.hamcrest.Matchers.contains) PeersResponse(org.elasticsearch.cluster.coordination.PeersResponse) Matchers.equalTo(org.hamcrest.Matchers.equalTo) TransportResponseHandler(org.elasticsearch.transport.TransportResponseHandler) Optional(java.util.Optional) Matchers.is(org.hamcrest.Matchers.is) REQUEST_PEERS_ACTION_NAME(org.elasticsearch.discovery.PeerFinder.REQUEST_PEERS_ACTION_NAME) TransportException(org.elasticsearch.transport.TransportException) CapturedRequest(org.elasticsearch.test.transport.CapturingTransport.CapturedRequest) TransportAddressConnector(org.elasticsearch.discovery.PeerFinder.TransportAddressConnector) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) Names(org.elasticsearch.threadpool.ThreadPool.Names) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) OptionalLong(java.util.OptionalLong) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) StreamSupport(java.util.stream.StreamSupport) ESTestCase(org.elasticsearch.test.ESTestCase) TransportService(org.elasticsearch.transport.TransportService) Before(org.junit.Before) StubbableConnectionManager(org.elasticsearch.test.transport.StubbableConnectionManager) Collections.emptyMap(java.util.Collections.emptyMap) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) Matchers.empty(org.hamcrest.Matchers.empty) Collections.emptySet(java.util.Collections.emptySet) IOException(java.io.IOException) Consumer(java.util.function.Consumer) StreamInput(org.elasticsearch.common.io.stream.StreamInput) Collections(java.util.Collections) ActionListener(org.elasticsearch.action.ActionListener) ConnectionManager(org.elasticsearch.transport.ConnectionManager) StubbableConnectionManager(org.elasticsearch.test.transport.StubbableConnectionManager) StubbableConnectionManager(org.elasticsearch.test.transport.StubbableConnectionManager) DeterministicTaskQueue(org.elasticsearch.cluster.coordination.DeterministicTaskQueue) TransportService(org.elasticsearch.transport.TransportService) CapturingTransport(org.elasticsearch.test.transport.CapturingTransport) Settings(org.elasticsearch.common.settings.Settings) Before(org.junit.Before)

Example 70 with TransportService

use of org.elasticsearch.transport.TransportService in project crate by crate.

the class IndexRecoveryIT method testCancelNewShardRecoveryAndUsesExistingShardCopy.

@Test
public void testCancelNewShardRecoveryAndUsesExistingShardCopy() throws Exception {
    logger.info("--> start node A");
    final String nodeA = internalCluster().startNode();
    logger.info("--> create index on node: {}", nodeA);
    createAndPopulateIndex(INDEX_NAME, 1, SHARD_COUNT, REPLICA_COUNT);
    logger.info("--> start node B");
    // force a shard recovery from nodeA to nodeB
    final String nodeB = internalCluster().startNode();
    logger.info("--> add replica for {} on node: {}", INDEX_NAME, nodeB);
    execute("ALTER TABLE " + INDEX_NAME + " SET (number_of_replicas=1, \"unassigned.node_left.delayed_timeout\"=0)");
    ensureGreen();
    logger.info("--> start node C");
    final String nodeC = internalCluster().startNode();
    // do sync flush to gen sync id
    execute("OPTIMIZE TABLE " + INDEX_NAME);
    // assertThat(client().admin().indices().prepareSyncedFlush(INDEX_NAME).get().failedShards(), equalTo(0));
    // hold peer recovery on phase 2 after nodeB down
    CountDownLatch phase1ReadyBlocked = new CountDownLatch(1);
    CountDownLatch allowToCompletePhase1Latch = new CountDownLatch(1);
    MockTransportService transportService = (MockTransportService) internalCluster().getInstance(TransportService.class, nodeA);
    transportService.addSendBehavior((connection, requestId, action, request, options) -> {
        if (PeerRecoveryTargetService.Actions.CLEAN_FILES.equals(action)) {
            phase1ReadyBlocked.countDown();
            try {
                allowToCompletePhase1Latch.await();
            } catch (InterruptedException e) {
                throw new AssertionError(e);
            }
        }
        connection.sendRequest(requestId, action, request, options);
    });
    logger.info("--> restart node B");
    internalCluster().restartNode(nodeB, new InternalTestCluster.RestartCallback() {

        @Override
        public Settings onNodeStopped(String nodeName) throws Exception {
            phase1ReadyBlocked.await();
            // nodeB stopped, peer recovery from nodeA to nodeC, it will be cancelled after nodeB get started.
            var indexName = IndexParts.toIndexName(sqlExecutor.getCurrentSchema(), INDEX_NAME, null);
            RecoveryResponse response = client().execute(RecoveryAction.INSTANCE, new RecoveryRequest(indexName)).actionGet();
            List<RecoveryState> recoveryStates = response.shardRecoveryStates().get(indexName);
            List<RecoveryState> nodeCRecoveryStates = findRecoveriesForTargetNode(nodeC, recoveryStates);
            assertThat(nodeCRecoveryStates.size(), equalTo(1));
            assertOnGoingRecoveryState(nodeCRecoveryStates.get(0), 0, RecoverySource.PeerRecoverySource.INSTANCE, false, nodeA, nodeC);
            validateIndexRecoveryState(nodeCRecoveryStates.get(0).getIndex());
            return super.onNodeStopped(nodeName);
        }
    });
    // wait for peer recovery from nodeA to nodeB which is a no-op recovery so it skips the CLEAN_FILES stage and hence is not blocked
    ensureGreen();
    allowToCompletePhase1Latch.countDown();
    transportService.clearAllRules();
    // make sure nodeA has primary and nodeB has replica
    ClusterState state = client().admin().cluster().prepareState().get().getState();
    List<ShardRouting> startedShards = state.routingTable().shardsWithState(ShardRoutingState.STARTED);
    assertThat(startedShards.size(), equalTo(2));
    for (ShardRouting shardRouting : startedShards) {
        if (shardRouting.primary()) {
            assertThat(state.nodes().get(shardRouting.currentNodeId()).getName(), equalTo(nodeA));
        } else {
            assertThat(state.nodes().get(shardRouting.currentNodeId()).getName(), equalTo(nodeB));
        }
    }
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) MockTransportService(org.elasticsearch.test.transport.MockTransportService) InternalTestCluster(org.elasticsearch.test.InternalTestCluster) CountDownLatch(java.util.concurrent.CountDownLatch) ConnectTransportException(org.elasticsearch.transport.ConnectTransportException) IOException(java.io.IOException) EsRejectedExecutionException(org.elasticsearch.common.util.concurrent.EsRejectedExecutionException) MapperParsingException(org.elasticsearch.index.mapper.MapperParsingException) CircuitBreakingException(org.elasticsearch.common.breaker.CircuitBreakingException) RecoveryResponse(org.elasticsearch.action.admin.indices.recovery.RecoveryResponse) RecoveryRequest(org.elasticsearch.action.admin.indices.recovery.RecoveryRequest) TransportService(org.elasticsearch.transport.TransportService) MockTransportService(org.elasticsearch.test.transport.MockTransportService) ArrayList(java.util.ArrayList) List(java.util.List) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) Settings(org.elasticsearch.common.settings.Settings) IndexSettings(org.elasticsearch.index.IndexSettings) Test(org.junit.Test)

Aggregations

TransportService (org.elasticsearch.transport.TransportService)79 Settings (org.elasticsearch.common.settings.Settings)48 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)42 ThreadPool (org.elasticsearch.threadpool.ThreadPool)33 ClusterService (org.elasticsearch.cluster.service.ClusterService)30 ClusterState (org.elasticsearch.cluster.ClusterState)29 IOException (java.io.IOException)27 ESTestCase (org.elasticsearch.test.ESTestCase)27 TestThreadPool (org.elasticsearch.threadpool.TestThreadPool)25 CountDownLatch (java.util.concurrent.CountDownLatch)24 DiscoveryNodes (org.elasticsearch.cluster.node.DiscoveryNodes)24 Before (org.junit.Before)24 CapturingTransport (org.elasticsearch.test.transport.CapturingTransport)23 MockTransportService (org.elasticsearch.test.transport.MockTransportService)23 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)22 Collections (java.util.Collections)21 TimeUnit (java.util.concurrent.TimeUnit)21 HashSet (java.util.HashSet)20 ActionListener (org.elasticsearch.action.ActionListener)19 ArrayList (java.util.ArrayList)18