Search in sources :

Example 1 with ShardStateAction

use of org.opensearch.cluster.action.shard.ShardStateAction in project OpenSearch by opensearch-project.

the class TransportVerifyShardBeforeCloseActionTests method setUp.

@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    indexShard = mock(IndexShard.class);
    when(indexShard.getActiveOperationsCount()).thenReturn(IndexShard.OPERATIONS_BLOCKED);
    final ShardId shardId = new ShardId("index", "_na_", randomIntBetween(0, 3));
    when(indexShard.shardId()).thenReturn(shardId);
    clusterService = createClusterService(threadPool);
    clusterBlock = MetadataIndexStateService.createIndexClosingBlock();
    setState(clusterService, new ClusterState.Builder(clusterService.state()).blocks(ClusterBlocks.builder().blocks(clusterService.state().blocks()).addIndexBlock("index", clusterBlock).build()).build());
    transport = new CapturingTransport();
    TransportService transportService = transport.createTransportService(Settings.EMPTY, threadPool, TransportService.NOOP_TRANSPORT_INTERCEPTOR, x -> clusterService.localNode(), null, Collections.emptySet());
    transportService.start();
    transportService.acceptIncomingRequests();
    ShardStateAction shardStateAction = new ShardStateAction(clusterService, transportService, null, null, threadPool);
    action = new TransportVerifyShardBeforeCloseAction(Settings.EMPTY, transportService, clusterService, mock(IndicesService.class), mock(ThreadPool.class), shardStateAction, mock(ActionFilters.class));
}
Also used : ShardId(org.opensearch.index.shard.ShardId) ClusterState(org.opensearch.cluster.ClusterState) TransportService(org.opensearch.transport.TransportService) IndexShard(org.opensearch.index.shard.IndexShard) CapturingTransport(org.opensearch.test.transport.CapturingTransport) ShardStateAction(org.opensearch.cluster.action.shard.ShardStateAction) Before(org.junit.Before)

Example 2 with ShardStateAction

use of org.opensearch.cluster.action.shard.ShardStateAction in project OpenSearch by opensearch-project.

the class TransportWriteActionTests method testReplicaProxy.

public void testReplicaProxy() throws InterruptedException, ExecutionException {
    CapturingTransport transport = new CapturingTransport();
    TransportService transportService = transport.createTransportService(clusterService.getSettings(), threadPool, TransportService.NOOP_TRANSPORT_INTERCEPTOR, x -> clusterService.localNode(), null, Collections.emptySet());
    transportService.start();
    transportService.acceptIncomingRequests();
    ShardStateAction shardStateAction = new ShardStateAction(clusterService, transportService, null, null, threadPool);
    TestAction action = new TestAction(Settings.EMPTY, "internal:testAction", transportService, clusterService, shardStateAction, threadPool);
    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);
    final long primaryTerm = state.metadata().index(index).primaryTerm(0);
    ReplicationOperation.Replicas<TestRequest> proxy = action.newReplicasProxy();
    // check that at unknown node fails
    PlainActionFuture<ReplicaResponse> listener = new PlainActionFuture<>();
    ShardRoutingState routingState = randomFrom(ShardRoutingState.INITIALIZING, ShardRoutingState.STARTED, ShardRoutingState.RELOCATING);
    proxy.performOn(TestShardRouting.newShardRouting(shardId, "NOT THERE", routingState == ShardRoutingState.RELOCATING ? state.nodes().iterator().next().getId() : null, false, routingState), new TestRequest(), primaryTerm, randomNonNegativeLong(), randomNonNegativeLong(), 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(), primaryTerm, randomNonNegativeLong(), randomNonNegativeLong(), listener);
    assertFalse(listener.isDone());
    CapturingTransport.CapturedRequest[] captures = transport.getCapturedRequestsAndClear();
    assertThat(captures, arrayWithSize(1));
    if (randomBoolean()) {
        final TransportReplicationAction.ReplicaResponse response = new TransportReplicationAction.ReplicaResponse(randomLong(), randomLong());
        transport.handleResponse(captures[0].requestId, response);
        assertTrue(listener.isDone());
        assertThat(listener.get(), equalTo(response));
    } else if (randomBoolean()) {
        transport.handleRemoteError(captures[0].requestId, new OpenSearchException("simulated"));
        assertTrue(listener.isDone());
        assertListenerThrows("listener should reflect remote error", listener, OpenSearchException.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<>();
    AtomicBoolean success = new AtomicBoolean();
    proxy.failShardIfNeeded(replica, primaryTerm, "test", new OpenSearchException("simulated"), ActionListener.wrap(r -> success.set(true), failure::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.FailedShardEntry shardEntry = (ShardStateAction.FailedShardEntry) 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());
    } 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());
    } else {
        // simulated a node closing exception
        transport.handleRemoteError(shardFailedRequest.requestId, new NodeClosedException(state.nodes().getLocalNode()));
        assertFalse(success.get());
        assertNotNull(failure.get());
    }
}
Also used : TestThreadPool(org.opensearch.threadpool.TestThreadPool) OpenSearchException(org.opensearch.OpenSearchException) NoNodeAvailableException(org.opensearch.client.transport.NoNodeAvailableException) Transport(org.opensearch.transport.Transport) ReplicaResponse(org.opensearch.action.support.replication.ReplicationOperation.ReplicaResponse) Mockito.doThrow(org.mockito.Mockito.doThrow) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Locale(java.util.Locale) WriteResponse(org.opensearch.action.support.WriteResponse) After(org.junit.After) Mockito.doAnswer(org.mockito.Mockito.doAnswer) NodeClosedException(org.opensearch.node.NodeClosedException) ActionListener(org.opensearch.action.ActionListener) ShardStateAction(org.opensearch.cluster.action.shard.ShardStateAction) IndexShardRoutingTable(org.opensearch.cluster.routing.IndexShardRoutingTable) AfterClass(org.junit.AfterClass) Index(org.opensearch.index.Index) IndexingPressureService(org.opensearch.index.IndexingPressureService) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) IndicesService(org.opensearch.indices.IndicesService) Settings(org.opensearch.common.settings.Settings) TransportResponse(org.opensearch.transport.TransportResponse) TransportService(org.opensearch.transport.TransportService) Collectors(java.util.stream.Collectors) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) ActionFilters(org.opensearch.action.support.ActionFilters) ActionTestUtils(org.opensearch.action.support.ActionTestUtils) Matchers.equalTo(org.hamcrest.Matchers.equalTo) RoutingNode(org.opensearch.cluster.routing.RoutingNode) Mockito.any(org.mockito.Mockito.any) ClusterServiceUtils(org.opensearch.test.ClusterServiceUtils) TransportException(org.opensearch.transport.TransportException) RefreshPolicy(org.opensearch.action.support.WriteRequest.RefreshPolicy) Mockito.mock(org.mockito.Mockito.mock) Matchers.arrayWithSize(org.hamcrest.Matchers.arrayWithSize) BeforeClass(org.junit.BeforeClass) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) ThreadPool(org.opensearch.threadpool.ThreadPool) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Releasable(org.opensearch.common.lease.Releasable) AtomicReference(java.util.concurrent.atomic.AtomicReference) HashSet(java.util.HashSet) ClusterState(org.opensearch.cluster.ClusterState) IndexShard(org.opensearch.index.shard.IndexShard) ArgumentCaptor(org.mockito.ArgumentCaptor) ShardRoutingState(org.opensearch.cluster.routing.ShardRoutingState) Translog(org.opensearch.index.translog.Translog) Mockito.anyLong(org.mockito.Mockito.anyLong) Mockito.anyString(org.mockito.Mockito.anyString) Before(org.junit.Before) StreamInput(org.opensearch.common.io.stream.StreamInput) Collections.emptyMap(java.util.Collections.emptyMap) ClusterServiceUtils.createClusterService(org.opensearch.test.ClusterServiceUtils.createClusterService) IOException(java.io.IOException) ShardNotFoundException(org.opensearch.index.shard.ShardNotFoundException) Mockito.when(org.mockito.Mockito.when) IndexService(org.opensearch.index.IndexService) Mockito.verify(org.mockito.Mockito.verify) ShardRouting(org.opensearch.cluster.routing.ShardRouting) ShardId(org.opensearch.index.shard.ShardId) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) TestShardRouting(org.opensearch.cluster.routing.TestShardRouting) SystemIndices(org.opensearch.indices.SystemIndices) Mockito.never(org.mockito.Mockito.never) ClusterService(org.opensearch.cluster.service.ClusterService) Mockito.anyInt(org.mockito.Mockito.anyInt) CapturingTransport(org.opensearch.test.transport.CapturingTransport) Collections(java.util.Collections) IndexShardRoutingTable(org.opensearch.cluster.routing.IndexShardRoutingTable) ShardStateAction(org.opensearch.cluster.action.shard.ShardStateAction) Mockito.anyString(org.mockito.Mockito.anyString) ShardId(org.opensearch.index.shard.ShardId) NodeClosedException(org.opensearch.node.NodeClosedException) ClusterState(org.opensearch.cluster.ClusterState) CapturingTransport(org.opensearch.test.transport.CapturingTransport) AtomicReference(java.util.concurrent.atomic.AtomicReference) ShardRoutingState(org.opensearch.cluster.routing.ShardRoutingState) TransportException(org.opensearch.transport.TransportException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TransportService(org.opensearch.transport.TransportService) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) ReplicaResponse(org.opensearch.action.support.replication.ReplicationOperation.ReplicaResponse) OpenSearchException(org.opensearch.OpenSearchException) ShardRouting(org.opensearch.cluster.routing.ShardRouting) TestShardRouting(org.opensearch.cluster.routing.TestShardRouting)

Example 3 with ShardStateAction

use of org.opensearch.cluster.action.shard.ShardStateAction in project OpenSearch by opensearch-project.

the class TransportReplicationActionTests method setUp.

@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    forceExecute = randomBoolean();
    transport = new CapturingTransport();
    clusterService = createClusterService(threadPool);
    transportService = transport.createTransportService(clusterService.getSettings(), threadPool, TransportService.NOOP_TRANSPORT_INTERCEPTOR, x -> clusterService.localNode(), null, Collections.emptySet());
    transportService.start();
    transportService.acceptIncomingRequests();
    shardStateAction = new ShardStateAction(clusterService, transportService, null, null, threadPool);
    action = new TestAction(Settings.EMPTY, "internal:testAction", transportService, clusterService, shardStateAction, threadPool);
}
Also used : Matchers.hasToString(org.hamcrest.Matchers.hasToString) Metadata(org.opensearch.cluster.metadata.Metadata) AllocationService(org.opensearch.cluster.routing.allocation.AllocationService) TestThreadPool(org.opensearch.threadpool.TestThreadPool) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) ClusterStateChanges(org.opensearch.indices.cluster.ClusterStateChanges) Version(org.opensearch.Version) ClusterServiceUtils.setState(org.opensearch.test.ClusterServiceUtils.setState) NoNodeAvailableException(org.opensearch.client.transport.NoNodeAvailableException) Transport(org.opensearch.transport.Transport) Mockito.doThrow(org.mockito.Mockito.doThrow) ClusterBlock(org.opensearch.cluster.block.ClusterBlock) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) OpenSearchAllocationTestCase(org.opensearch.cluster.OpenSearchAllocationTestCase) Matchers.nullValue(org.hamcrest.Matchers.nullValue) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Is.is(org.hamcrest.core.Is.is) ActionListener(org.opensearch.action.ActionListener) CreateIndexRequest(org.opensearch.action.admin.indices.create.CreateIndexRequest) ShardStateAction(org.opensearch.cluster.action.shard.ShardStateAction) EnumSet(java.util.EnumSet) AfterClass(org.junit.AfterClass) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) Index(org.opensearch.index.Index) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) TransportService(org.opensearch.transport.TransportService) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) ActionFilters(org.opensearch.action.support.ActionFilters) ActionTestUtils(org.opensearch.action.support.ActionTestUtils) RoutingNode(org.opensearch.cluster.routing.RoutingNode) TransportException(org.opensearch.transport.TransportException) Mockito.eq(org.mockito.Mockito.eq) Mockito.mock(org.mockito.Mockito.mock) Matchers.arrayWithSize(org.hamcrest.Matchers.arrayWithSize) IndexShardState(org.opensearch.index.shard.IndexShardState) ThreadPool(org.opensearch.threadpool.ThreadPool) Releasable(org.opensearch.common.lease.Releasable) MockTransportService(org.opensearch.test.transport.MockTransportService) ClusterState(org.opensearch.cluster.ClusterState) ShardRoutingState(org.opensearch.cluster.routing.ShardRoutingState) Mockito.anyLong(org.mockito.Mockito.anyLong) ClusterBlocks(org.opensearch.cluster.block.ClusterBlocks) Mockito.anyString(org.mockito.Mockito.anyString) Before(org.junit.Before) MockNioTransport(org.opensearch.transport.nio.MockNioTransport) IOException(java.io.IOException) ShardNotFoundException(org.opensearch.index.shard.ShardNotFoundException) IndexService(org.opensearch.index.IndexService) SETTING_WAIT_FOR_ACTIVE_SHARDS(org.opensearch.cluster.metadata.IndexMetadata.SETTING_WAIT_FOR_ACTIVE_SHARDS) ExecutionException(java.util.concurrent.ExecutionException) Matcher(org.hamcrest.Matcher) ClusterService(org.opensearch.cluster.service.ClusterService) NetworkService(org.opensearch.common.network.NetworkService) Mockito.anyInt(org.mockito.Mockito.anyInt) ReplicationGroup(org.opensearch.index.shard.ReplicationGroup) Assert(org.junit.Assert) PageCacheRecycler(org.opensearch.common.util.PageCacheRecycler) NoneCircuitBreakerService(org.opensearch.indices.breaker.NoneCircuitBreakerService) OpenSearchException(org.opensearch.OpenSearchException) TestTransportChannel(org.opensearch.transport.TestTransportChannel) ReplicaResponse(org.opensearch.action.support.replication.ReplicationOperation.ReplicaResponse) Collections.singleton(java.util.Collections.singleton) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Locale(java.util.Locale) After(org.junit.After) UnavailableShardsException(org.opensearch.action.UnavailableShardsException) CloseIndexRequest(org.opensearch.action.admin.indices.close.CloseIndexRequest) IndexShardRoutingTable(org.opensearch.cluster.routing.IndexShardRoutingTable) TransportChannel(org.opensearch.transport.TransportChannel) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) IndicesService(org.opensearch.indices.IndicesService) ClusterBlockException(org.opensearch.cluster.block.ClusterBlockException) IndexShardClosedException(org.opensearch.index.shard.IndexShardClosedException) TransportResponse(org.opensearch.transport.TransportResponse) RestStatus(org.opensearch.rest.RestStatus) ClusterStateCreationUtils.state(org.opensearch.action.support.replication.ClusterStateCreationUtils.state) Collectors(java.util.stream.Collectors) Nullable(org.opensearch.common.Nullable) List(java.util.List) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Mockito.any(org.mockito.Mockito.any) DiscoveryNodes(org.opensearch.cluster.node.DiscoveryNodes) BeforeClass(org.junit.BeforeClass) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) ShardNotInPrimaryModeException(org.opensearch.index.shard.ShardNotInPrimaryModeException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) StreamOutput(org.opensearch.common.io.stream.StreamOutput) AtomicReference(java.util.concurrent.atomic.AtomicReference) NamedWriteableRegistry(org.opensearch.common.io.stream.NamedWriteableRegistry) HashSet(java.util.HashSet) IndexShard(org.opensearch.index.shard.IndexShard) IndexClosedException(org.opensearch.indices.IndexClosedException) StreamInput(org.opensearch.common.io.stream.StreamInput) ClusterServiceUtils.createClusterService(org.opensearch.test.ClusterServiceUtils.createClusterService) TransportRequest(org.opensearch.transport.TransportRequest) AllocationId(org.opensearch.cluster.routing.AllocationId) ClusterBlockLevel(org.opensearch.cluster.block.ClusterBlockLevel) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) ClusterStateCreationUtils.stateWithActivePrimary(org.opensearch.action.support.replication.ClusterStateCreationUtils.stateWithActivePrimary) Mockito.when(org.mockito.Mockito.when) ActiveShardCount(org.opensearch.action.support.ActiveShardCount) Mockito.verify(org.mockito.Mockito.verify) ShardRouting(org.opensearch.cluster.routing.ShardRouting) ShardId(org.opensearch.index.shard.ShardId) TimeUnit(java.util.concurrent.TimeUnit) TestShardRouting(org.opensearch.cluster.routing.TestShardRouting) CapturingTransport(org.opensearch.test.transport.CapturingTransport) Collections(java.util.Collections) CapturingTransport(org.opensearch.test.transport.CapturingTransport) ShardStateAction(org.opensearch.cluster.action.shard.ShardStateAction) Before(org.junit.Before)

Example 4 with ShardStateAction

use of org.opensearch.cluster.action.shard.ShardStateAction in project OpenSearch by opensearch-project.

the class ClusterDisruptionIT method testSendingShardFailure.

// simulate handling of sending shard failure during an isolation
public void testSendingShardFailure() throws Exception {
    List<String> nodes = startCluster(3);
    String masterNode = internalCluster().getMasterName();
    List<String> nonMasterNodes = nodes.stream().filter(node -> !node.equals(masterNode)).collect(Collectors.toList());
    String nonMasterNode = randomFrom(nonMasterNodes);
    assertAcked(prepareCreate("test").setSettings(Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 3).put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 2)));
    ensureGreen();
    String nonMasterNodeId = internalCluster().clusterService(nonMasterNode).localNode().getId();
    // fail a random shard
    ShardRouting failedShard = randomFrom(clusterService().state().getRoutingNodes().node(nonMasterNodeId).shardsWithState(ShardRoutingState.STARTED));
    ShardStateAction service = internalCluster().getInstance(ShardStateAction.class, nonMasterNode);
    CountDownLatch latch = new CountDownLatch(1);
    AtomicBoolean success = new AtomicBoolean();
    String isolatedNode = randomBoolean() ? masterNode : nonMasterNode;
    TwoPartitions partitions = isolateNode(isolatedNode);
    // we cannot use the NetworkUnresponsive disruption type here as it will swallow the "shard failed" request, calling neither
    // onSuccess nor onFailure on the provided listener.
    NetworkDisruption networkDisruption = new NetworkDisruption(partitions, NetworkDisruption.DISCONNECT);
    setDisruptionScheme(networkDisruption);
    networkDisruption.startDisrupting();
    service.localShardFailed(failedShard, "simulated", new CorruptIndexException("simulated", (String) null), new ActionListener<Void>() {

        @Override
        public void onResponse(final Void aVoid) {
            success.set(true);
            latch.countDown();
        }

        @Override
        public void onFailure(Exception e) {
            success.set(false);
            latch.countDown();
            assert false;
        }
    });
    if (isolatedNode.equals(nonMasterNode)) {
        assertNoMaster(nonMasterNode);
    } else {
        ensureStableCluster(2, nonMasterNode);
    }
    // heal the partition
    networkDisruption.removeAndEnsureHealthy(internalCluster());
    // the cluster should stabilize
    ensureStableCluster(3);
    latch.await();
    // the listener should be notified
    assertTrue(success.get());
    // the failed shard should be gone
    List<ShardRouting> shards = clusterService().state().getRoutingTable().allShards("test");
    for (ShardRouting shard : shards) {
        assertThat(shard.allocationId(), not(equalTo(failedShard.allocationId())));
    }
}
Also used : IndexRequestBuilder(org.opensearch.action.index.IndexRequestBuilder) ClusterBootstrapService(org.opensearch.cluster.coordination.ClusterBootstrapService) IndexResponse(org.opensearch.action.index.IndexResponse) Matchers.not(org.hamcrest.Matchers.not) OpenSearchException(org.opensearch.OpenSearchException) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) ConcurrentCollections(org.opensearch.common.util.concurrent.ConcurrentCollections) Bridge(org.opensearch.test.disruption.NetworkDisruption.Bridge) IndexShardTestCase(org.opensearch.index.shard.IndexShardTestCase) Matchers.everyItem(org.hamcrest.Matchers.everyItem) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ActionListener(org.opensearch.action.ActionListener) GetResponse(org.opensearch.action.get.GetResponse) ShardStateAction(org.opensearch.cluster.action.shard.ShardStateAction) Client(org.opensearch.client.Client) TimeValue(org.opensearch.common.unit.TimeValue) IndicesService(org.opensearch.indices.IndicesService) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) ServiceDisruptionScheme(org.opensearch.test.disruption.ServiceDisruptionScheme) Collectors(java.util.stream.Collectors) CountDownLatch(java.util.concurrent.CountDownLatch) VersionType(org.opensearch.index.VersionType) List(java.util.List) UPDATED(org.opensearch.action.DocWriteResponse.Result.UPDATED) CREATED(org.opensearch.action.DocWriteResponse.Result.CREATED) Matchers.equalTo(org.hamcrest.Matchers.equalTo) LagDetector(org.opensearch.cluster.coordination.LagDetector) XContentType(org.opensearch.common.xcontent.XContentType) Matchers.is(org.hamcrest.Matchers.is) OpenSearchIntegTestCase(org.opensearch.test.OpenSearchIntegTestCase) Matchers.in(org.hamcrest.Matchers.in) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) IntStream(java.util.stream.IntStream) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) InternalTestCluster(org.opensearch.test.InternalTestCluster) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) ClusterState(org.opensearch.cluster.ClusterState) IndexShard(org.opensearch.index.shard.IndexShard) Murmur3HashFunction(org.opensearch.cluster.routing.Murmur3HashFunction) ShardRoutingState(org.opensearch.cluster.routing.ShardRoutingState) TestIssueLogging(org.opensearch.test.junit.annotations.TestIssueLogging) OpenSearchAssertions.assertAcked(org.opensearch.test.hamcrest.OpenSearchAssertions.assertAcked) Matchers.oneOf(org.hamcrest.Matchers.oneOf) Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) Semaphore(java.util.concurrent.Semaphore) ShardRouting(org.opensearch.cluster.routing.ShardRouting) TimeUnit(java.util.concurrent.TimeUnit) TwoPartitions(org.opensearch.test.disruption.NetworkDisruption.TwoPartitions) NetworkDisruption(org.opensearch.test.disruption.NetworkDisruption) NoShardAvailableActionException(org.opensearch.action.NoShardAvailableActionException) Collections(java.util.Collections) TwoPartitions(org.opensearch.test.disruption.NetworkDisruption.TwoPartitions) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) ShardStateAction(org.opensearch.cluster.action.shard.ShardStateAction) CountDownLatch(java.util.concurrent.CountDownLatch) OpenSearchException(org.opensearch.OpenSearchException) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) NoShardAvailableActionException(org.opensearch.action.NoShardAvailableActionException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ShardRouting(org.opensearch.cluster.routing.ShardRouting) NetworkDisruption(org.opensearch.test.disruption.NetworkDisruption)

Example 5 with ShardStateAction

use of org.opensearch.cluster.action.shard.ShardStateAction in project OpenSearch by opensearch-project.

the class TransportResyncReplicationActionTests method testResyncDoesNotBlockOnPrimaryAction.

public void testResyncDoesNotBlockOnPrimaryAction() throws Exception {
    try (ClusterService clusterService = createClusterService(threadPool)) {
        final String indexName = randomAlphaOfLength(5);
        setState(clusterService, state(indexName, true, ShardRoutingState.STARTED));
        setState(clusterService, ClusterState.builder(clusterService.state()).blocks(ClusterBlocks.builder().addGlobalBlock(NoMasterBlockService.NO_MASTER_BLOCK_ALL).addIndexBlock(indexName, IndexMetadata.INDEX_WRITE_BLOCK)));
        try (MockNioTransport transport = new MockNioTransport(Settings.EMPTY, Version.CURRENT, threadPool, new NetworkService(emptyList()), PageCacheRecycler.NON_RECYCLING_INSTANCE, new NamedWriteableRegistry(emptyList()), new NoneCircuitBreakerService())) {
            final MockTransportService transportService = new MockTransportService(Settings.EMPTY, transport, threadPool, NOOP_TRANSPORT_INTERCEPTOR, x -> clusterService.localNode(), null, Collections.emptySet());
            transportService.start();
            transportService.acceptIncomingRequests();
            final ShardStateAction shardStateAction = new ShardStateAction(clusterService, transportService, null, null, threadPool);
            final IndexMetadata indexMetadata = clusterService.state().metadata().index(indexName);
            final Index index = indexMetadata.getIndex();
            final ShardId shardId = new ShardId(index, 0);
            final IndexShardRoutingTable shardRoutingTable = clusterService.state().routingTable().shardRoutingTable(shardId);
            final ShardRouting primaryShardRouting = clusterService.state().routingTable().shardRoutingTable(shardId).primaryShard();
            final String allocationId = primaryShardRouting.allocationId().getId();
            final long primaryTerm = indexMetadata.primaryTerm(shardId.id());
            final AtomicInteger acquiredPermits = new AtomicInteger();
            final IndexShard indexShard = mock(IndexShard.class);
            when(indexShard.indexSettings()).thenReturn(new IndexSettings(indexMetadata, Settings.EMPTY));
            when(indexShard.shardId()).thenReturn(shardId);
            when(indexShard.routingEntry()).thenReturn(primaryShardRouting);
            when(indexShard.getPendingPrimaryTerm()).thenReturn(primaryTerm);
            when(indexShard.getOperationPrimaryTerm()).thenReturn(primaryTerm);
            when(indexShard.getActiveOperationsCount()).then(i -> acquiredPermits.get());
            doAnswer(invocation -> {
                ActionListener<Releasable> callback = (ActionListener<Releasable>) invocation.getArguments()[0];
                acquiredPermits.incrementAndGet();
                callback.onResponse(acquiredPermits::decrementAndGet);
                return null;
            }).when(indexShard).acquirePrimaryOperationPermit(any(ActionListener.class), anyString(), any(), eq(true));
            when(indexShard.getReplicationGroup()).thenReturn(new ReplicationGroup(shardRoutingTable, clusterService.state().metadata().index(index).inSyncAllocationIds(shardId.id()), shardRoutingTable.getAllAllocationIds(), 0));
            final IndexService indexService = mock(IndexService.class);
            when(indexService.getShard(eq(shardId.id()))).thenReturn(indexShard);
            final IndicesService indexServices = mock(IndicesService.class);
            when(indexServices.indexServiceSafe(eq(index))).thenReturn(indexService);
            final TransportResyncReplicationAction action = new TransportResyncReplicationAction(Settings.EMPTY, transportService, clusterService, indexServices, threadPool, shardStateAction, new ActionFilters(new HashSet<>()), new IndexingPressureService(Settings.EMPTY, clusterService), new SystemIndices(emptyMap()));
            assertThat(action.globalBlockLevel(), nullValue());
            assertThat(action.indexBlockLevel(), nullValue());
            final Task task = mock(Task.class);
            when(task.getId()).thenReturn(randomNonNegativeLong());
            final byte[] bytes = "{}".getBytes(Charset.forName("UTF-8"));
            final ResyncReplicationRequest request = new ResyncReplicationRequest(shardId, 42L, 100, new Translog.Operation[] { new Translog.Index("type", "id", 0, primaryTerm, 0L, bytes, null, -1) });
            final PlainActionFuture<ResyncReplicationResponse> listener = new PlainActionFuture<>();
            action.sync(request, task, allocationId, primaryTerm, listener);
            assertThat(listener.get().getShardInfo().getFailed(), equalTo(0));
            assertThat(listener.isDone(), is(true));
        }
    }
}
Also used : NamedWriteableRegistry(org.opensearch.common.io.stream.NamedWriteableRegistry) IndexShardRoutingTable(org.opensearch.cluster.routing.IndexShardRoutingTable) Task(org.opensearch.tasks.Task) MockTransportService(org.opensearch.test.transport.MockTransportService) IndexService(org.opensearch.index.IndexService) IndexSettings(org.opensearch.index.IndexSettings) Index(org.opensearch.index.Index) Mockito.anyString(org.mockito.Mockito.anyString) ShardStateAction(org.opensearch.cluster.action.shard.ShardStateAction) ReplicationGroup(org.opensearch.index.shard.ReplicationGroup) Translog(org.opensearch.index.translog.Translog) ShardId(org.opensearch.index.shard.ShardId) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) HashSet(java.util.HashSet) IndexingPressureService(org.opensearch.index.IndexingPressureService) IndexShard(org.opensearch.index.shard.IndexShard) IndicesService(org.opensearch.indices.IndicesService) ActionFilters(org.opensearch.action.support.ActionFilters) ClusterServiceUtils.createClusterService(org.opensearch.test.ClusterServiceUtils.createClusterService) ClusterService(org.opensearch.cluster.service.ClusterService) ActionListener(org.opensearch.action.ActionListener) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) MockNioTransport(org.opensearch.transport.nio.MockNioTransport) NetworkService(org.opensearch.common.network.NetworkService) Releasable(org.opensearch.common.lease.Releasable) ShardRouting(org.opensearch.cluster.routing.ShardRouting) SystemIndices(org.opensearch.indices.SystemIndices) NoneCircuitBreakerService(org.opensearch.indices.breaker.NoneCircuitBreakerService)

Aggregations

ShardStateAction (org.opensearch.cluster.action.shard.ShardStateAction)16 IndexShard (org.opensearch.index.shard.IndexShard)15 ShardId (org.opensearch.index.shard.ShardId)14 TransportService (org.opensearch.transport.TransportService)14 ActionFilters (org.opensearch.action.support.ActionFilters)13 Collections (java.util.Collections)12 Mockito.mock (org.mockito.Mockito.mock)12 Mockito.when (org.mockito.Mockito.when)12 ActionListener (org.opensearch.action.ActionListener)12 ClusterService (org.opensearch.cluster.service.ClusterService)12 Settings (org.opensearch.common.settings.Settings)12 IndicesService (org.opensearch.indices.IndicesService)12 CapturingTransport (org.opensearch.test.transport.CapturingTransport)12 PlainActionFuture (org.opensearch.action.support.PlainActionFuture)11 IndexService (org.opensearch.index.IndexService)11 ClusterServiceUtils.createClusterService (org.opensearch.test.ClusterServiceUtils.createClusterService)11 ThreadPool (org.opensearch.threadpool.ThreadPool)11 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)10 Mockito.verify (org.mockito.Mockito.verify)10 ActionTestUtils (org.opensearch.action.support.ActionTestUtils)10