Search in sources :

Example 6 with TransportService

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

the class IndicesStoreIntegrationIT method relocateAndBlockCompletion.

/**
     * relocate a shard and block cluster state processing on the relocation target node to activate the shard
     */
public static BlockClusterStateProcessing relocateAndBlockCompletion(Logger logger, String index, int shard, String nodeFrom, String nodeTo) throws InterruptedException {
    BlockClusterStateProcessing disruption = new BlockClusterStateProcessing(nodeTo, random());
    internalCluster().setDisruptionScheme(disruption);
    MockTransportService transportService = (MockTransportService) internalCluster().getInstance(TransportService.class, nodeTo);
    ClusterService clusterService = internalCluster().getInstance(ClusterService.class, nodeTo);
    CountDownLatch beginRelocationLatch = new CountDownLatch(1);
    CountDownLatch receivedShardExistsRequestLatch = new CountDownLatch(1);
    // use a tracer on the target node to track relocation start and end
    transportService.addTracer(new MockTransportService.Tracer() {

        @Override
        public void receivedRequest(long requestId, String action) {
            if (action.equals(PeerRecoveryTargetService.Actions.FILES_INFO)) {
                logger.info("received: {}, relocation starts", action);
                beginRelocationLatch.countDown();
            } else if (action.equals(IndicesStore.ACTION_SHARD_EXISTS)) {
                // Whenever a node deletes a shard because it was relocated somewhere else, it first
                // checks if enough other copies are started somewhere else. The node sends a ShardActiveRequest
                // to the other nodes that should have a copy according to cluster state.
                receivedShardExistsRequestLatch.countDown();
                logger.info("received: {}, relocation done", action);
            } else if (action.equals(PeerRecoveryTargetService.Actions.WAIT_CLUSTERSTATE)) {
                logger.info("received: {}, waiting on cluster state", action);
                // a race with the BlockClusterStateProcessing block that is added below.
                try {
                    assertBusy(() -> assertTrue(clusterService.state().routingTable().index(index).shard(shard).primaryShard().relocating()));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    });
    internalCluster().client().admin().cluster().prepareReroute().add(new MoveAllocationCommand(index, shard, nodeFrom, nodeTo)).get();
    logger.info("--> waiting for relocation to start");
    beginRelocationLatch.await();
    logger.info("--> starting disruption");
    disruption.startDisrupting();
    logger.info("--> waiting for relocation to finish");
    receivedShardExistsRequestLatch.await();
    logger.info("--> relocation completed (but cluster state processing block still in place)");
    return disruption;
}
Also used : BlockClusterStateProcessing(org.elasticsearch.test.disruption.BlockClusterStateProcessing) ClusterService(org.elasticsearch.cluster.service.ClusterService) MockTransportService(org.elasticsearch.test.transport.MockTransportService) MockTransportService(org.elasticsearch.test.transport.MockTransportService) TransportService(org.elasticsearch.transport.TransportService) MoveAllocationCommand(org.elasticsearch.cluster.routing.allocation.command.MoveAllocationCommand) CountDownLatch(java.util.concurrent.CountDownLatch) ConnectTransportException(org.elasticsearch.transport.ConnectTransportException) IOException(java.io.IOException)

Example 7 with TransportService

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

the class TransportReplicationActionTests method setUp.

@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    transport = new CapturingTransport();
    clusterService = createClusterService(threadPool);
    transportService = new TransportService(clusterService.getSettings(), transport, threadPool, TransportService.NOOP_TRANSPORT_INTERCEPTOR, x -> clusterService.localNode(), null);
    transportService.start();
    transportService.acceptIncomingRequests();
    shardStateAction = new ShardStateAction(Settings.EMPTY, clusterService, transportService, null, null, threadPool);
    action = new TestAction(Settings.EMPTY, "testAction", transportService, clusterService, shardStateAction, threadPool);
}
Also used : ElasticsearchException(org.elasticsearch.ElasticsearchException) MetaData(org.elasticsearch.cluster.metadata.MetaData) ShardId(org.elasticsearch.index.shard.ShardId) ESAllocationTestCase(org.elasticsearch.cluster.ESAllocationTestCase) StreamOutput(org.elasticsearch.common.io.stream.StreamOutput) TransportRequest(org.elasticsearch.transport.TransportRequest) Nullable(org.elasticsearch.common.Nullable) ClusterServiceUtils.createClusterService(org.elasticsearch.test.ClusterServiceUtils.createClusterService) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) AllocationService(org.elasticsearch.cluster.routing.allocation.AllocationService) ClusterBlocks(org.elasticsearch.cluster.block.ClusterBlocks) IndexClosedException(org.elasticsearch.indices.IndexClosedException) NodeClosedException(org.elasticsearch.node.NodeClosedException) ShardNotFoundException(org.elasticsearch.index.shard.ShardNotFoundException) CapturingTransport(org.elasticsearch.test.transport.CapturingTransport) Mockito.doThrow(org.mockito.Mockito.doThrow) ClusterState(org.elasticsearch.cluster.ClusterState) Settings(org.elasticsearch.common.settings.Settings) ClusterBlock(org.elasticsearch.cluster.block.ClusterBlock) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) Locale(java.util.Locale) After(org.junit.After) Matchers.nullValue(org.hamcrest.Matchers.nullValue) Mockito.doAnswer(org.mockito.Mockito.doAnswer) ClusterStateCreationUtils.stateWithActivePrimary(org.elasticsearch.action.support.replication.ClusterStateCreationUtils.stateWithActivePrimary) Matchers.anyInt(org.mockito.Matchers.anyInt) ThreadPool(org.elasticsearch.threadpool.ThreadPool) Releasable(org.elasticsearch.common.lease.Releasable) TransportResponseOptions(org.elasticsearch.transport.TransportResponseOptions) AfterClass(org.junit.AfterClass) ActionFilters(org.elasticsearch.action.support.ActionFilters) ClusterStateChanges(org.elasticsearch.indices.cluster.ClusterStateChanges) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) ReplicaResponse(org.elasticsearch.action.support.replication.ReplicationOperation.ReplicaResponse) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture) NoNodeAvailableException(org.elasticsearch.client.transport.NoNodeAvailableException) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) Collectors(java.util.stream.Collectors) ActiveShardCount(org.elasticsearch.action.support.ActiveShardCount) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) Matchers.any(org.mockito.Matchers.any) List(java.util.List) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) ShardStateAction(org.elasticsearch.cluster.action.shard.ShardStateAction) RestStatus(org.elasticsearch.rest.RestStatus) Matchers.equalTo(org.hamcrest.Matchers.equalTo) TransportException(org.elasticsearch.transport.TransportException) TestShardRouting(org.elasticsearch.cluster.routing.TestShardRouting) Mockito.mock(org.mockito.Mockito.mock) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) ClusterStateCreationUtils.state(org.elasticsearch.action.support.replication.ClusterStateCreationUtils.state) Matchers.arrayWithSize(org.hamcrest.Matchers.arrayWithSize) IndexShardClosedException(org.elasticsearch.index.shard.IndexShardClosedException) TransportChannel(org.elasticsearch.transport.TransportChannel) BeforeClass(org.junit.BeforeClass) ClusterService(org.elasticsearch.cluster.service.ClusterService) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Index(org.elasticsearch.index.Index) ShardRoutingState(org.elasticsearch.cluster.routing.ShardRoutingState) AtomicReference(java.util.concurrent.atomic.AtomicReference) Matchers.anyString(org.mockito.Matchers.anyString) HashSet(java.util.HashSet) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException) Matchers.anyLong(org.mockito.Matchers.anyLong) TransportResponse(org.elasticsearch.transport.TransportResponse) IndicesService(org.elasticsearch.indices.IndicesService) ESTestCase(org.elasticsearch.test.ESTestCase) TransportService(org.elasticsearch.transport.TransportService) ClusterBlockLevel(org.elasticsearch.cluster.block.ClusterBlockLevel) Before(org.junit.Before) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) TestThreadPool(org.elasticsearch.threadpool.TestThreadPool) IndexShardState(org.elasticsearch.index.shard.IndexShardState) IndexService(org.elasticsearch.index.IndexService) IndexShard(org.elasticsearch.index.shard.IndexShard) RoutingNode(org.elasticsearch.cluster.routing.RoutingNode) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) UnavailableShardsException(org.elasticsearch.action.UnavailableShardsException) Mockito.verify(org.mockito.Mockito.verify) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) CloseIndexRequest(org.elasticsearch.action.admin.indices.close.CloseIndexRequest) SETTING_WAIT_FOR_ACTIVE_SHARDS(org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_WAIT_FOR_ACTIVE_SHARDS) StreamInput(org.elasticsearch.common.io.stream.StreamInput) Matcher(org.hamcrest.Matcher) AllocationId(org.elasticsearch.cluster.routing.AllocationId) IndexNameExpressionResolver(org.elasticsearch.cluster.metadata.IndexNameExpressionResolver) Collections(java.util.Collections) ClusterServiceUtils.setState(org.elasticsearch.test.ClusterServiceUtils.setState) ActionListener(org.elasticsearch.action.ActionListener) TransportService(org.elasticsearch.transport.TransportService) CapturingTransport(org.elasticsearch.test.transport.CapturingTransport) ShardStateAction(org.elasticsearch.cluster.action.shard.ShardStateAction) Before(org.junit.Before)

Example 8 with TransportService

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

the class BroadcastReplicationTests method setUp.

@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    MockTcpTransport transport = new MockTcpTransport(Settings.EMPTY, threadPool, BigArrays.NON_RECYCLING_INSTANCE, circuitBreakerService, new NamedWriteableRegistry(Collections.emptyList()), new NetworkService(Settings.EMPTY, Collections.emptyList()));
    clusterService = createClusterService(threadPool);
    transportService = new TransportService(clusterService.getSettings(), transport, threadPool, TransportService.NOOP_TRANSPORT_INTERCEPTOR, x -> clusterService.localNode(), null);
    transportService.start();
    transportService.acceptIncomingRequests();
    broadcastReplicationAction = new TestBroadcastReplicationAction(Settings.EMPTY, threadPool, clusterService, transportService, new ActionFilters(new HashSet<>()), new IndexNameExpressionResolver(Settings.EMPTY), null);
}
Also used : NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) ShardId(org.elasticsearch.index.shard.ShardId) BigArrays(org.elasticsearch.common.util.BigArrays) Date(java.util.Date) ClusterServiceUtils.createClusterService(org.elasticsearch.test.ClusterServiceUtils.createClusterService) ConcurrentCollections(org.elasticsearch.common.util.concurrent.ConcurrentCollections) ClusterState(org.elasticsearch.cluster.ClusterState) Future(java.util.concurrent.Future) Settings(org.elasticsearch.common.settings.Settings) After(org.junit.After) BroadcastRequest(org.elasticsearch.action.support.broadcast.BroadcastRequest) ThreadPool(org.elasticsearch.threadpool.ThreadPool) AfterClass(org.junit.AfterClass) ActionFilters(org.elasticsearch.action.support.ActionFilters) BroadcastResponse(org.elasticsearch.action.support.broadcast.BroadcastResponse) Matchers.lessThanOrEqualTo(org.hamcrest.Matchers.lessThanOrEqualTo) MockTcpTransport(org.elasticsearch.transport.MockTcpTransport) Set(java.util.Set) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) List(java.util.List) RestStatus(org.elasticsearch.rest.RestStatus) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Task(org.elasticsearch.tasks.Task) ClusterStateCreationUtils.stateWithNoShard(org.elasticsearch.action.support.replication.ClusterStateCreationUtils.stateWithNoShard) ClusterStateCreationUtils.state(org.elasticsearch.action.support.replication.ClusterStateCreationUtils.state) BeforeClass(org.junit.BeforeClass) ClusterService(org.elasticsearch.cluster.service.ClusterService) ShardRoutingState(org.elasticsearch.cluster.routing.ShardRoutingState) CircuitBreakerService(org.elasticsearch.indices.breaker.CircuitBreakerService) HashSet(java.util.HashSet) NetworkService(org.elasticsearch.common.network.NetworkService) NoneCircuitBreakerService(org.elasticsearch.indices.breaker.NoneCircuitBreakerService) NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) ClusterStateCreationUtils.stateWithAssignedPrimariesAndOneReplica(org.elasticsearch.action.support.replication.ClusterStateCreationUtils.stateWithAssignedPrimariesAndOneReplica) ESTestCase(org.elasticsearch.test.ESTestCase) TransportService(org.elasticsearch.transport.TransportService) FlushResponse(org.elasticsearch.action.admin.indices.flush.FlushResponse) Before(org.junit.Before) TestThreadPool(org.elasticsearch.threadpool.TestThreadPool) TransportFlushAction(org.elasticsearch.action.admin.indices.flush.TransportFlushAction) IOUtils(org.apache.lucene.util.IOUtils) NoShardAvailableActionException(org.elasticsearch.action.NoShardAvailableActionException) IOException(java.io.IOException) ShardOperationFailedException(org.elasticsearch.action.ShardOperationFailedException) UnavailableShardsException(org.elasticsearch.action.UnavailableShardsException) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) FlushRequest(org.elasticsearch.action.admin.indices.flush.FlushRequest) IndexNameExpressionResolver(org.elasticsearch.cluster.metadata.IndexNameExpressionResolver) Tuple(org.elasticsearch.common.collect.Tuple) Collections(java.util.Collections) ClusterServiceUtils.setState(org.elasticsearch.test.ClusterServiceUtils.setState) ActionListener(org.elasticsearch.action.ActionListener) TransportService(org.elasticsearch.transport.TransportService) NetworkService(org.elasticsearch.common.network.NetworkService) ActionFilters(org.elasticsearch.action.support.ActionFilters) IndexNameExpressionResolver(org.elasticsearch.cluster.metadata.IndexNameExpressionResolver) MockTcpTransport(org.elasticsearch.transport.MockTcpTransport) Before(org.junit.Before)

Example 9 with TransportService

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

the class TransportWriteActionTests method testReplicaProxy.

public void testReplicaProxy() throws InterruptedException, ExecutionException {
    CapturingTransport transport = new CapturingTransport();
    TransportService transportService = new TransportService(clusterService.getSettings(), transport, threadPool, TransportService.NOOP_TRANSPORT_INTERCEPTOR, x -> clusterService.localNode(), null);
    transportService.start();
    transportService.acceptIncomingRequests();
    ShardStateAction shardStateAction = new ShardStateAction(Settings.EMPTY, clusterService, transportService, null, null, threadPool);
    TestAction action = action = new TestAction(Settings.EMPTY, "testAction", transportService, clusterService, shardStateAction, threadPool);
    ReplicationOperation.Replicas proxy = action.newReplicasProxy();
    final String index = "test";
    final ShardId shardId = new ShardId(index, "_na_", 0);
    ClusterState state = ClusterStateCreationUtils.stateWithActivePrimary(index, true, 1 + randomInt(3), randomInt(2));
    logger.info("using state: {}", state);
    ClusterServiceUtils.setState(clusterService, state);
    // check that at unknown node fails
    PlainActionFuture<ReplicaResponse> listener = new PlainActionFuture<>();
    proxy.performOn(TestShardRouting.newShardRouting(shardId, "NOT THERE", false, randomFrom(ShardRoutingState.values())), new TestRequest(), listener);
    assertTrue(listener.isDone());
    assertListenerThrows("non existent node should throw a NoNodeAvailableException", listener, NoNodeAvailableException.class);
    final IndexShardRoutingTable shardRoutings = state.routingTable().shardRoutingTable(shardId);
    final ShardRouting replica = randomFrom(shardRoutings.replicaShards().stream().filter(ShardRouting::assignedToNode).collect(Collectors.toList()));
    listener = new PlainActionFuture<>();
    proxy.performOn(replica, new TestRequest(), listener);
    assertFalse(listener.isDone());
    CapturingTransport.CapturedRequest[] captures = transport.getCapturedRequestsAndClear();
    assertThat(captures, arrayWithSize(1));
    if (randomBoolean()) {
        final TransportReplicationAction.ReplicaResponse response = new TransportReplicationAction.ReplicaResponse(randomAsciiOfLength(10), randomLong());
        transport.handleResponse(captures[0].requestId, response);
        assertTrue(listener.isDone());
        assertThat(listener.get(), equalTo(response));
    } else if (randomBoolean()) {
        transport.handleRemoteError(captures[0].requestId, new ElasticsearchException("simulated"));
        assertTrue(listener.isDone());
        assertListenerThrows("listener should reflect remote error", listener, ElasticsearchException.class);
    } else {
        transport.handleError(captures[0].requestId, new TransportException("simulated"));
        assertTrue(listener.isDone());
        assertListenerThrows("listener should reflect remote error", listener, TransportException.class);
    }
    AtomicReference<Object> failure = new AtomicReference<>();
    AtomicReference<Object> ignoredFailure = new AtomicReference<>();
    AtomicBoolean success = new AtomicBoolean();
    proxy.failShardIfNeeded(replica, randomIntBetween(1, 10), "test", new ElasticsearchException("simulated"), () -> success.set(true), failure::set, ignoredFailure::set);
    CapturingTransport.CapturedRequest[] shardFailedRequests = transport.getCapturedRequestsAndClear();
    // A write replication action proxy should fail the shard
    assertEquals(1, shardFailedRequests.length);
    CapturingTransport.CapturedRequest shardFailedRequest = shardFailedRequests[0];
    ShardStateAction.ShardEntry shardEntry = (ShardStateAction.ShardEntry) shardFailedRequest.request;
    // the shard the request was sent to and the shard to be failed should be the same
    assertEquals(shardEntry.getShardId(), replica.shardId());
    assertEquals(shardEntry.getAllocationId(), replica.allocationId().getId());
    if (randomBoolean()) {
        // simulate success
        transport.handleResponse(shardFailedRequest.requestId, TransportResponse.Empty.INSTANCE);
        assertTrue(success.get());
        assertNull(failure.get());
        assertNull(ignoredFailure.get());
    } else if (randomBoolean()) {
        // simulate the primary has been demoted
        transport.handleRemoteError(shardFailedRequest.requestId, new ShardStateAction.NoLongerPrimaryShardException(replica.shardId(), "shard-failed-test"));
        assertFalse(success.get());
        assertNotNull(failure.get());
        assertNull(ignoredFailure.get());
    } else {
        // simulated an "ignored" exception
        transport.handleRemoteError(shardFailedRequest.requestId, new NodeClosedException(state.nodes().getLocalNode()));
        assertFalse(success.get());
        assertNull(failure.get());
        assertNotNull(ignoredFailure.get());
    }
}
Also used : IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) ShardStateAction(org.elasticsearch.cluster.action.shard.ShardStateAction) Matchers.anyString(org.mockito.Matchers.anyString) ElasticsearchException(org.elasticsearch.ElasticsearchException) ShardId(org.elasticsearch.index.shard.ShardId) NodeClosedException(org.elasticsearch.node.NodeClosedException) ReplicationOperation(org.elasticsearch.action.support.replication.ReplicationOperation) ClusterState(org.elasticsearch.cluster.ClusterState) CapturingTransport(org.elasticsearch.test.transport.CapturingTransport) AtomicReference(java.util.concurrent.atomic.AtomicReference) TransportException(org.elasticsearch.transport.TransportException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TransportService(org.elasticsearch.transport.TransportService) PlainActionFuture(org.elasticsearch.action.support.PlainActionFuture) ReplicaResponse(org.elasticsearch.action.support.replication.ReplicationOperation.ReplicaResponse) TestShardRouting(org.elasticsearch.cluster.routing.TestShardRouting) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting)

Example 10 with TransportService

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

the class TransportBroadcastByNodeActionTests method setUp.

@Before
public void setUp() throws Exception {
    super.setUp();
    transport = new CapturingTransport();
    clusterService = createClusterService(THREAD_POOL);
    final TransportService transportService = new TransportService(clusterService.getSettings(), transport, THREAD_POOL, TransportService.NOOP_TRANSPORT_INTERCEPTOR, x -> clusterService.localNode(), null);
    transportService.start();
    transportService.acceptIncomingRequests();
    setClusterState(clusterService, TEST_INDEX);
    action = new TestTransportBroadcastByNodeAction(Settings.EMPTY, transportService, new ActionFilters(new HashSet<>()), new MyResolver(), Request::new, ThreadPool.Names.SAME);
}
Also used : TransportService(org.elasticsearch.transport.TransportService) CapturingTransport(org.elasticsearch.test.transport.CapturingTransport) ActionFilters(org.elasticsearch.action.support.ActionFilters) Before(org.junit.Before)

Aggregations

TransportService (org.elasticsearch.transport.TransportService)42 Settings (org.elasticsearch.common.settings.Settings)25 ThreadPool (org.elasticsearch.threadpool.ThreadPool)21 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)19 ClusterState (org.elasticsearch.cluster.ClusterState)18 ClusterService (org.elasticsearch.cluster.service.ClusterService)17 Collections (java.util.Collections)16 IOException (java.io.IOException)15 CountDownLatch (java.util.concurrent.CountDownLatch)15 TimeUnit (java.util.concurrent.TimeUnit)15 Before (org.junit.Before)15 ActionFilters (org.elasticsearch.action.support.ActionFilters)14 ESTestCase (org.elasticsearch.test.ESTestCase)14 MockTransportService (org.elasticsearch.test.transport.MockTransportService)14 TestThreadPool (org.elasticsearch.threadpool.TestThreadPool)14 HashSet (java.util.HashSet)13 DiscoveryNodes (org.elasticsearch.cluster.node.DiscoveryNodes)13 IndexNameExpressionResolver (org.elasticsearch.cluster.metadata.IndexNameExpressionResolver)12 TransportAddress (org.elasticsearch.common.transport.TransportAddress)12 After (org.junit.After)12