Search in sources :

Example 1 with ClusterRerouteRequest

use of org.opensearch.action.admin.cluster.reroute.ClusterRerouteRequest in project OpenSearch by opensearch-project.

the class FailedNodeRoutingTests method testRandomClusterPromotesNewestReplica.

public void testRandomClusterPromotesNewestReplica() throws InterruptedException {
    ThreadPool threadPool = new TestThreadPool(getClass().getName());
    ClusterStateChanges cluster = new ClusterStateChanges(xContentRegistry(), threadPool);
    ClusterState state = randomInitialClusterState();
    // randomly add nodes of mixed versions
    logger.info("--> adding random nodes");
    for (int i = 0; i < randomIntBetween(4, 8); i++) {
        DiscoveryNodes newNodes = DiscoveryNodes.builder(state.nodes()).add(createNode()).build();
        state = ClusterState.builder(state).nodes(newNodes).build();
        // always reroute after adding node
        state = cluster.reroute(state, new ClusterRerouteRequest());
    }
    // Log the node versions (for debugging if necessary)
    for (ObjectCursor<DiscoveryNode> cursor : state.nodes().getDataNodes().values()) {
        Version nodeVer = cursor.value.getVersion();
        logger.info("--> node [{}] has version [{}]", cursor.value.getId(), nodeVer);
    }
    // randomly create some indices
    logger.info("--> creating some indices");
    for (int i = 0; i < randomIntBetween(2, 5); i++) {
        String name = "index_" + randomAlphaOfLength(8).toLowerCase(Locale.ROOT);
        Settings.Builder settingsBuilder = Settings.builder().put(SETTING_NUMBER_OF_SHARDS, randomIntBetween(1, 4)).put(SETTING_NUMBER_OF_REPLICAS, randomIntBetween(2, 4));
        CreateIndexRequest request = new CreateIndexRequest(name, settingsBuilder.build()).waitForActiveShards(ActiveShardCount.NONE);
        state = cluster.createIndex(state, request);
        assertTrue(state.metadata().hasIndex(name));
    }
    logger.info("--> starting shards");
    state = cluster.applyStartedShards(state, state.getRoutingNodes().shardsWithState(INITIALIZING));
    logger.info("--> starting replicas a random number of times");
    for (int i = 0; i < randomIntBetween(1, 10); i++) {
        state = cluster.applyStartedShards(state, state.getRoutingNodes().shardsWithState(INITIALIZING));
    }
    boolean keepGoing = true;
    while (keepGoing) {
        List<ShardRouting> primaries = state.getRoutingNodes().shardsWithState(STARTED).stream().filter(ShardRouting::primary).collect(Collectors.toList());
        // Pick a random subset of primaries to fail
        List<FailedShard> shardsToFail = new ArrayList<>();
        List<ShardRouting> failedPrimaries = randomSubsetOf(primaries);
        failedPrimaries.stream().forEach(sr -> {
            shardsToFail.add(new FailedShard(randomFrom(sr), "failed primary", new Exception(), randomBoolean()));
        });
        logger.info("--> state before failing shards: {}", state);
        state = cluster.applyFailedShards(state, shardsToFail);
        final ClusterState compareState = state;
        failedPrimaries.forEach(shardRouting -> {
            logger.info("--> verifying version for {}", shardRouting);
            ShardRouting newPrimary = compareState.routingTable().index(shardRouting.index()).shard(shardRouting.id()).primaryShard();
            Version newPrimaryVersion = getNodeVersion(newPrimary, compareState);
            logger.info("--> new primary is on version {}: {}", newPrimaryVersion, newPrimary);
            compareState.routingTable().shardRoutingTable(newPrimary.shardId()).shardsWithState(STARTED).stream().forEach(sr -> {
                Version candidateVer = getNodeVersion(sr, compareState);
                if (candidateVer != null) {
                    logger.info("--> candidate on {} node; shard routing: {}", candidateVer, sr);
                    assertTrue("candidate was not on the newest version, new primary is on " + newPrimaryVersion + " and there is a candidate on " + candidateVer, candidateVer.onOrBefore(newPrimaryVersion));
                }
            });
        });
        keepGoing = randomBoolean();
    }
    terminate(threadPool);
}
Also used : ClusterState(org.opensearch.cluster.ClusterState) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) ThreadPool(org.opensearch.threadpool.ThreadPool) TestThreadPool(org.opensearch.threadpool.TestThreadPool) ArrayList(java.util.ArrayList) TestThreadPool(org.opensearch.threadpool.TestThreadPool) ClusterStateChanges(org.opensearch.indices.cluster.ClusterStateChanges) ClusterRerouteRequest(org.opensearch.action.admin.cluster.reroute.ClusterRerouteRequest) Version(org.opensearch.Version) CreateIndexRequest(org.opensearch.action.admin.indices.create.CreateIndexRequest) ShardRouting(org.opensearch.cluster.routing.ShardRouting) DiscoveryNodes(org.opensearch.cluster.node.DiscoveryNodes) Settings(org.opensearch.common.settings.Settings)

Example 2 with ClusterRerouteRequest

use of org.opensearch.action.admin.cluster.reroute.ClusterRerouteRequest in project OpenSearch by opensearch-project.

the class IndicesClusterStateServiceRandomUpdatesTests method randomlyUpdateClusterState.

public ClusterState randomlyUpdateClusterState(ClusterState state, Map<DiscoveryNode, IndicesClusterStateService> clusterStateServiceMap, Supplier<MockIndicesService> indicesServiceSupplier) {
    // randomly remove no_master blocks
    if (randomBoolean() && state.blocks().hasGlobalBlockWithId(NoMasterBlockService.NO_MASTER_BLOCK_ID)) {
        state = ClusterState.builder(state).blocks(ClusterBlocks.builder().blocks(state.blocks()).removeGlobalBlock(NoMasterBlockService.NO_MASTER_BLOCK_ID)).build();
    }
    // randomly add no_master blocks
    if (rarely() && state.blocks().hasGlobalBlockWithId(NoMasterBlockService.NO_MASTER_BLOCK_ID) == false) {
        ClusterBlock block = randomBoolean() ? NoMasterBlockService.NO_MASTER_BLOCK_ALL : NoMasterBlockService.NO_MASTER_BLOCK_WRITES;
        state = ClusterState.builder(state).blocks(ClusterBlocks.builder().blocks(state.blocks()).addGlobalBlock(block)).build();
    }
    // if no_master block is in place, make no other cluster state changes
    if (state.blocks().hasGlobalBlockWithId(NoMasterBlockService.NO_MASTER_BLOCK_ID)) {
        return state;
    }
    // randomly create new indices (until we have 200 max)
    for (int i = 0; i < randomInt(5); i++) {
        if (state.metadata().indices().size() > 200) {
            break;
        }
        String name = "index_" + randomAlphaOfLength(15).toLowerCase(Locale.ROOT);
        Settings.Builder settingsBuilder = Settings.builder().put(SETTING_NUMBER_OF_SHARDS, randomIntBetween(1, 3));
        if (randomBoolean()) {
            int min = randomInt(2);
            int max = min + randomInt(3);
            settingsBuilder.put(SETTING_AUTO_EXPAND_REPLICAS, randomBoolean() ? min + "-" + max : min + "-all");
        } else {
            settingsBuilder.put(SETTING_NUMBER_OF_REPLICAS, randomInt(2));
        }
        CreateIndexRequest request = new CreateIndexRequest(name, settingsBuilder.build()).waitForActiveShards(ActiveShardCount.NONE);
        state = cluster.createIndex(state, request);
        assertTrue(state.metadata().hasIndex(name));
    }
    // randomly delete indices
    Set<String> indicesToDelete = new HashSet<>();
    int numberOfIndicesToDelete = randomInt(Math.min(2, state.metadata().indices().size()));
    for (String index : randomSubsetOf(numberOfIndicesToDelete, state.metadata().indices().keys().toArray(String.class))) {
        indicesToDelete.add(state.metadata().index(index).getIndex().getName());
    }
    if (indicesToDelete.isEmpty() == false) {
        DeleteIndexRequest deleteRequest = new DeleteIndexRequest(indicesToDelete.toArray(new String[indicesToDelete.size()]));
        state = cluster.deleteIndices(state, deleteRequest);
        for (String index : indicesToDelete) {
            assertFalse(state.metadata().hasIndex(index));
        }
    }
    // randomly close indices
    int numberOfIndicesToClose = randomInt(Math.min(1, state.metadata().indices().size()));
    for (String index : randomSubsetOf(numberOfIndicesToClose, state.metadata().indices().keys().toArray(String.class))) {
        CloseIndexRequest closeIndexRequest = new CloseIndexRequest(state.metadata().index(index).getIndex().getName());
        state = cluster.closeIndices(state, closeIndexRequest);
    }
    // randomly open indices
    int numberOfIndicesToOpen = randomInt(Math.min(1, state.metadata().indices().size()));
    for (String index : randomSubsetOf(numberOfIndicesToOpen, state.metadata().indices().keys().toArray(String.class))) {
        OpenIndexRequest openIndexRequest = new OpenIndexRequest(state.metadata().index(index).getIndex().getName());
        state = cluster.openIndices(state, openIndexRequest);
    }
    // randomly update settings
    Set<String> indicesToUpdate = new HashSet<>();
    boolean containsClosedIndex = false;
    int numberOfIndicesToUpdate = randomInt(Math.min(2, state.metadata().indices().size()));
    for (String index : randomSubsetOf(numberOfIndicesToUpdate, state.metadata().indices().keys().toArray(String.class))) {
        indicesToUpdate.add(state.metadata().index(index).getIndex().getName());
        if (state.metadata().index(index).getState() == IndexMetadata.State.CLOSE) {
            containsClosedIndex = true;
        }
    }
    if (indicesToUpdate.isEmpty() == false) {
        UpdateSettingsRequest updateSettingsRequest = new UpdateSettingsRequest(indicesToUpdate.toArray(new String[indicesToUpdate.size()]));
        Settings.Builder settings = Settings.builder();
        if (containsClosedIndex == false) {
            settings.put(SETTING_NUMBER_OF_REPLICAS, randomInt(2));
        }
        settings.put("index.refresh_interval", randomIntBetween(1, 5) + "s");
        updateSettingsRequest.settings(settings.build());
        state = cluster.updateSettings(state, updateSettingsRequest);
    }
    // randomly reroute
    if (rarely()) {
        state = cluster.reroute(state, new ClusterRerouteRequest());
    }
    // randomly start and fail allocated shards
    final Map<ShardRouting, Long> startedShards = new HashMap<>();
    List<FailedShard> failedShards = new ArrayList<>();
    for (DiscoveryNode node : state.nodes()) {
        IndicesClusterStateService indicesClusterStateService = clusterStateServiceMap.get(node);
        MockIndicesService indicesService = (MockIndicesService) indicesClusterStateService.indicesService;
        for (MockIndexService indexService : indicesService) {
            for (MockIndexShard indexShard : indexService) {
                ShardRouting persistedShardRouting = indexShard.routingEntry();
                if (persistedShardRouting.initializing() && randomBoolean()) {
                    startedShards.put(persistedShardRouting, indexShard.term());
                } else if (rarely()) {
                    failedShards.add(new FailedShard(persistedShardRouting, "fake shard failure", new Exception(), randomBoolean()));
                }
            }
        }
    }
    state = cluster.applyFailedShards(state, failedShards);
    state = cluster.applyStartedShards(state, startedShards);
    // randomly add and remove nodes (except current master)
    if (rarely()) {
        if (randomBoolean()) {
            // add node
            if (state.nodes().getSize() < 10) {
                state = cluster.addNodes(state, Collections.singletonList(createNode()));
                updateNodes(state, clusterStateServiceMap, indicesServiceSupplier);
            }
        } else {
            // remove node
            if (state.nodes().getDataNodes().size() > 3) {
                DiscoveryNode discoveryNode = randomFrom(state.nodes().getNodes().values().toArray(DiscoveryNode.class));
                if (discoveryNode.equals(state.nodes().getMasterNode()) == false) {
                    state = cluster.removeNodes(state, Collections.singletonList(discoveryNode));
                    updateNodes(state, clusterStateServiceMap, indicesServiceSupplier);
                }
                if (randomBoolean()) {
                    // and add it back
                    state = cluster.addNodes(state, Collections.singletonList(discoveryNode));
                    updateNodes(state, clusterStateServiceMap, indicesServiceSupplier);
                }
            }
        }
    }
    return state;
}
Also used : DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) UpdateSettingsRequest(org.opensearch.action.admin.indices.settings.put.UpdateSettingsRequest) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) DeleteIndexRequest(org.opensearch.action.admin.indices.delete.DeleteIndexRequest) ClusterBlock(org.opensearch.cluster.block.ClusterBlock) ClusterRerouteRequest(org.opensearch.action.admin.cluster.reroute.ClusterRerouteRequest) Settings(org.opensearch.common.settings.Settings) HashSet(java.util.HashSet) OpenIndexRequest(org.opensearch.action.admin.indices.open.OpenIndexRequest) FailedShard(org.opensearch.cluster.routing.allocation.FailedShard) CloseIndexRequest(org.opensearch.action.admin.indices.close.CloseIndexRequest) CreateIndexRequest(org.opensearch.action.admin.indices.create.CreateIndexRequest) ShardRouting(org.opensearch.cluster.routing.ShardRouting)

Example 3 with ClusterRerouteRequest

use of org.opensearch.action.admin.cluster.reroute.ClusterRerouteRequest in project OpenSearch by opensearch-project.

the class AutoExpandReplicasTests method testAutoExpandWhenNodeLeavesAndPossiblyRejoins.

/**
 * Checks that when nodes leave the cluster that the auto-expand-replica functionality only triggers after failing the shards on
 * the removed nodes. This ensures that active shards on other live nodes are not failed if the primary resided on a now dead node.
 * Instead, one of the replicas on the live nodes first gets promoted to primary, and the auto-expansion (removing replicas) only
 * triggers in a follow-up step.
 */
public void testAutoExpandWhenNodeLeavesAndPossiblyRejoins() throws InterruptedException {
    final ThreadPool threadPool = new TestThreadPool(getClass().getName());
    final ClusterStateChanges cluster = new ClusterStateChanges(xContentRegistry(), threadPool);
    try {
        List<DiscoveryNode> allNodes = new ArrayList<>();
        // local node is the master
        DiscoveryNode localNode = createNode(DiscoveryNodeRole.MASTER_ROLE);
        allNodes.add(localNode);
        int numDataNodes = randomIntBetween(3, 5);
        List<DiscoveryNode> dataNodes = new ArrayList<>(numDataNodes);
        for (int i = 0; i < numDataNodes; i++) {
            dataNodes.add(createNode(DiscoveryNodeRole.DATA_ROLE));
        }
        allNodes.addAll(dataNodes);
        ClusterState state = ClusterStateCreationUtils.state(localNode, localNode, allNodes.toArray(new DiscoveryNode[0]));
        CreateIndexRequest request = new CreateIndexRequest("index", Settings.builder().put(SETTING_NUMBER_OF_SHARDS, 1).put(SETTING_AUTO_EXPAND_REPLICAS, "0-all").build()).waitForActiveShards(ActiveShardCount.NONE);
        state = cluster.createIndex(state, request);
        assertTrue(state.metadata().hasIndex("index"));
        while (state.routingTable().index("index").shard(0).allShardsStarted() == false) {
            logger.info(state);
            state = cluster.applyStartedShards(state, state.routingTable().index("index").shard(0).shardsWithState(ShardRoutingState.INITIALIZING));
            state = cluster.reroute(state, new ClusterRerouteRequest());
        }
        IndexShardRoutingTable preTable = state.routingTable().index("index").shard(0);
        final Set<String> unchangedNodeIds;
        final IndexShardRoutingTable postTable;
        if (randomBoolean()) {
            // simulate node removal
            List<DiscoveryNode> nodesToRemove = randomSubsetOf(2, dataNodes);
            unchangedNodeIds = dataNodes.stream().filter(n -> nodesToRemove.contains(n) == false).map(DiscoveryNode::getId).collect(Collectors.toSet());
            state = cluster.removeNodes(state, nodesToRemove);
            postTable = state.routingTable().index("index").shard(0);
            assertTrue("not all shards started in " + state.toString(), postTable.allShardsStarted());
            assertThat(postTable.toString(), postTable.getAllAllocationIds(), everyItem(is(in(preTable.getAllAllocationIds()))));
        } else {
            // fake an election where conflicting nodes are removed and readded
            state = ClusterState.builder(state).nodes(DiscoveryNodes.builder(state.nodes()).masterNodeId(null).build()).build();
            List<DiscoveryNode> conflictingNodes = randomSubsetOf(2, dataNodes);
            unchangedNodeIds = dataNodes.stream().filter(n -> conflictingNodes.contains(n) == false).map(DiscoveryNode::getId).collect(Collectors.toSet());
            List<DiscoveryNode> nodesToAdd = conflictingNodes.stream().map(n -> new DiscoveryNode(n.getName(), n.getId(), buildNewFakeTransportAddress(), n.getAttributes(), n.getRoles(), n.getVersion())).collect(Collectors.toList());
            if (randomBoolean()) {
                nodesToAdd.add(createNode(DiscoveryNodeRole.DATA_ROLE));
            }
            state = cluster.joinNodesAndBecomeMaster(state, nodesToAdd);
            postTable = state.routingTable().index("index").shard(0);
        }
        Set<String> unchangedAllocationIds = preTable.getShards().stream().filter(shr -> unchangedNodeIds.contains(shr.currentNodeId())).map(shr -> shr.allocationId().getId()).collect(Collectors.toSet());
        assertThat(postTable.toString(), unchangedAllocationIds, everyItem(is(in(postTable.getAllAllocationIds()))));
        postTable.getShards().forEach(shardRouting -> {
            if (shardRouting.assignedToNode() && unchangedAllocationIds.contains(shardRouting.allocationId().getId())) {
                assertTrue("Shard should be active: " + shardRouting, shardRouting.active());
            }
        });
    } finally {
        terminate(threadPool);
    }
}
Also used : DiscoveryNodes(org.opensearch.cluster.node.DiscoveryNodes) UpdateSettingsRequest(org.opensearch.action.admin.indices.settings.put.UpdateSettingsRequest) SETTING_AUTO_EXPAND_REPLICAS(org.opensearch.cluster.metadata.IndexMetadata.SETTING_AUTO_EXPAND_REPLICAS) ThreadPool(org.opensearch.threadpool.ThreadPool) TestThreadPool(org.opensearch.threadpool.TestThreadPool) ClusterStateChanges(org.opensearch.indices.cluster.ClusterStateChanges) Version(org.opensearch.Version) ClusterRerouteRequest(org.opensearch.action.admin.cluster.reroute.ClusterRerouteRequest) ClusterStateCreationUtils(org.opensearch.action.support.replication.ClusterStateCreationUtils) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ClusterState(org.opensearch.cluster.ClusterState) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) LegacyESVersion(org.opensearch.LegacyESVersion) Matchers.everyItem(org.hamcrest.Matchers.everyItem) VersionUtils(org.opensearch.test.VersionUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Locale(java.util.Locale) ShardRoutingState(org.opensearch.cluster.routing.ShardRoutingState) CreateIndexRequest(org.opensearch.action.admin.indices.create.CreateIndexRequest) IndexShardRoutingTable(org.opensearch.cluster.routing.IndexShardRoutingTable) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) DiscoveryNodeRole(org.opensearch.cluster.node.DiscoveryNodeRole) Collectors(java.util.stream.Collectors) ActiveShardCount(org.opensearch.action.support.ActiveShardCount) List(java.util.List) Matchers.equalTo(org.hamcrest.Matchers.equalTo) SETTING_NUMBER_OF_SHARDS(org.opensearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_SHARDS) Matchers.is(org.hamcrest.Matchers.is) Collections(java.util.Collections) Matchers.in(org.hamcrest.Matchers.in) ClusterState(org.opensearch.cluster.ClusterState) IndexShardRoutingTable(org.opensearch.cluster.routing.IndexShardRoutingTable) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) ThreadPool(org.opensearch.threadpool.ThreadPool) TestThreadPool(org.opensearch.threadpool.TestThreadPool) ArrayList(java.util.ArrayList) TestThreadPool(org.opensearch.threadpool.TestThreadPool) ClusterStateChanges(org.opensearch.indices.cluster.ClusterStateChanges) ClusterRerouteRequest(org.opensearch.action.admin.cluster.reroute.ClusterRerouteRequest) CreateIndexRequest(org.opensearch.action.admin.indices.create.CreateIndexRequest)

Example 4 with ClusterRerouteRequest

use of org.opensearch.action.admin.cluster.reroute.ClusterRerouteRequest in project OpenSearch by opensearch-project.

the class SnapshotResiliencyTests method testSnapshotPrimaryRelocations.

/**
 * Simulates concurrent restarts of data and master nodes as well as relocating a primary shard, while starting and subsequently
 * deleting a snapshot.
 */
public void testSnapshotPrimaryRelocations() {
    final int masterNodeCount = randomFrom(1, 3, 5);
    setupTestCluster(masterNodeCount, randomIntBetween(2, 5));
    String repoName = "repo";
    String snapshotName = "snapshot";
    final String index = "test";
    final int shards = randomIntBetween(1, 5);
    final TestClusterNodes.TestClusterNode masterNode = testClusterNodes.currentMaster(testClusterNodes.nodes.values().iterator().next().clusterService.state());
    final AtomicBoolean createdSnapshot = new AtomicBoolean();
    final AdminClient masterAdminClient = masterNode.client.admin();
    final StepListener<ClusterStateResponse> clusterStateResponseStepListener = new StepListener<>();
    continueOrDie(createRepoAndIndex(repoName, index, shards), createIndexResponse -> client().admin().cluster().state(new ClusterStateRequest(), clusterStateResponseStepListener));
    continueOrDie(clusterStateResponseStepListener, clusterStateResponse -> {
        final ShardRouting shardToRelocate = clusterStateResponse.getState().routingTable().allShards(index).get(0);
        final TestClusterNodes.TestClusterNode currentPrimaryNode = testClusterNodes.nodeById(shardToRelocate.currentNodeId());
        final TestClusterNodes.TestClusterNode otherNode = testClusterNodes.randomDataNodeSafe(currentPrimaryNode.node.getName());
        scheduleNow(() -> testClusterNodes.stopNode(currentPrimaryNode));
        scheduleNow(new Runnable() {

            @Override
            public void run() {
                final StepListener<ClusterStateResponse> updatedClusterStateResponseStepListener = new StepListener<>();
                masterAdminClient.cluster().state(new ClusterStateRequest(), updatedClusterStateResponseStepListener);
                continueOrDie(updatedClusterStateResponseStepListener, updatedClusterState -> {
                    final ShardRouting shardRouting = updatedClusterState.getState().routingTable().shardRoutingTable(shardToRelocate.shardId()).primaryShard();
                    if (shardRouting.unassigned() && shardRouting.unassignedInfo().getReason() == UnassignedInfo.Reason.NODE_LEFT) {
                        if (masterNodeCount > 1) {
                            scheduleNow(() -> testClusterNodes.stopNode(masterNode));
                        }
                        testClusterNodes.randomDataNodeSafe().client.admin().cluster().prepareCreateSnapshot(repoName, snapshotName).execute(ActionListener.wrap(() -> {
                            createdSnapshot.set(true);
                            testClusterNodes.randomDataNodeSafe().client.admin().cluster().deleteSnapshot(new DeleteSnapshotRequest(repoName, snapshotName), noopListener());
                        }));
                        scheduleNow(() -> testClusterNodes.randomMasterNodeSafe().client.admin().cluster().reroute(new ClusterRerouteRequest().add(new AllocateEmptyPrimaryAllocationCommand(index, shardRouting.shardId().id(), otherNode.node.getName(), true)), noopListener()));
                    } else {
                        scheduleSoon(this);
                    }
                });
            }
        });
    });
    runUntil(() -> testClusterNodes.randomMasterNode().map(master -> {
        if (createdSnapshot.get() == false) {
            return false;
        }
        return master.clusterService.state().custom(SnapshotsInProgress.TYPE, SnapshotsInProgress.EMPTY).entries().isEmpty();
    }).orElse(false), TimeUnit.MINUTES.toMillis(1L));
    clearDisruptionsAndAwaitSync();
    assertTrue(createdSnapshot.get());
    assertThat(testClusterNodes.randomDataNodeSafe().clusterService.state().custom(SnapshotsInProgress.TYPE, SnapshotsInProgress.EMPTY).entries(), empty());
    final Repository repository = testClusterNodes.randomMasterNodeSafe().repositoriesService.repository(repoName);
    Collection<SnapshotId> snapshotIds = getRepositoryData(repository).getSnapshotIds();
    assertThat(snapshotIds, either(hasSize(1)).or(hasSize(0)));
}
Also used : PrioritizedOpenSearchThreadPoolExecutor(org.opensearch.common.util.concurrent.PrioritizedOpenSearchThreadPoolExecutor) Version(org.opensearch.Version) TransportPutMappingAction(org.opensearch.action.admin.indices.mapping.put.TransportPutMappingAction) BulkAction(org.opensearch.action.bulk.BulkAction) TransportPutRepositoryAction(org.opensearch.action.admin.cluster.repositories.put.TransportPutRepositoryAction) GroupedActionListener(org.opensearch.action.support.GroupedActionListener) WriteRequest(org.opensearch.action.support.WriteRequest) RestoreSnapshotRequest(org.opensearch.action.admin.cluster.snapshots.restore.RestoreSnapshotRequest) OpenSearchAllocationTestCase(org.opensearch.cluster.OpenSearchAllocationTestCase) Map(java.util.Map) PutMappingAction(org.opensearch.action.admin.indices.mapping.put.PutMappingAction) Path(java.nio.file.Path) ShardStateAction(org.opensearch.cluster.action.shard.ShardStateAction) NodeEnvironment(org.opensearch.env.NodeEnvironment) NodeClient(org.opensearch.client.node.NodeClient) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) MasterService(org.opensearch.cluster.service.MasterService) IndexingPressureService(org.opensearch.index.IndexingPressureService) TransportResyncReplicationAction(org.opensearch.action.resync.TransportResyncReplicationAction) ExceptionsHelper(org.opensearch.ExceptionsHelper) HEALTHY(org.opensearch.monitor.StatusInfo.Status.HEALTHY) TransportService(org.opensearch.transport.TransportService) TransportClusterRerouteAction(org.opensearch.action.admin.cluster.reroute.TransportClusterRerouteAction) Logger(org.apache.logging.log4j.Logger) Stream(java.util.stream.Stream) ActionTestUtils(org.opensearch.action.support.ActionTestUtils) IndexNameExpressionResolver(org.opensearch.cluster.metadata.IndexNameExpressionResolver) Mockito.mock(org.mockito.Mockito.mock) SearchAction(org.opensearch.action.search.SearchAction) TransportRequestHandler(org.opensearch.transport.TransportRequestHandler) ThreadPool(org.opensearch.threadpool.ThreadPool) Supplier(java.util.function.Supplier) LinkedHashMap(java.util.LinkedHashMap) RestoreSnapshotResponse(org.opensearch.action.admin.cluster.snapshots.restore.RestoreSnapshotResponse) ResponseCollectorService(org.opensearch.node.ResponseCollectorService) MapperRegistry(org.opensearch.indices.mapper.MapperRegistry) RestoreSnapshotAction(org.opensearch.action.admin.cluster.snapshots.restore.RestoreSnapshotAction) Matchers.hasSize(org.hamcrest.Matchers.hasSize) ElectionStrategy(org.opensearch.cluster.coordination.ElectionStrategy) Before(org.junit.Before) DisruptableMockTransport(org.opensearch.test.disruption.DisruptableMockTransport) IOException(java.io.IOException) AnalysisModule(org.opensearch.indices.analysis.AnalysisModule) RetentionLeaseSyncer(org.opensearch.index.seqno.RetentionLeaseSyncer) PageCacheRecycler(org.opensearch.common.util.PageCacheRecycler) DestructiveOperations(org.opensearch.action.support.DestructiveOperations) AbstractRunnable(org.opensearch.common.util.concurrent.AbstractRunnable) FetchPhase(org.opensearch.search.fetch.FetchPhase) BulkRequest(org.opensearch.action.bulk.BulkRequest) DeleteSnapshotAction(org.opensearch.action.admin.cluster.snapshots.delete.DeleteSnapshotAction) IndicesShardStoresAction(org.opensearch.action.admin.indices.shards.IndicesShardStoresAction) SearchTransportService(org.opensearch.action.search.SearchTransportService) MetadataIndexUpgradeService(org.opensearch.cluster.metadata.MetadataIndexUpgradeService) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Coordinator(org.opensearch.cluster.coordination.Coordinator) UnassignedInfo(org.opensearch.cluster.routing.UnassignedInfo) RecoverySettings(org.opensearch.indices.recovery.RecoverySettings) SearchPhaseController(org.opensearch.action.search.SearchPhaseController) PATH_HOME_SETTING(org.opensearch.env.Environment.PATH_HOME_SETTING) TransportAutoPutMappingAction(org.opensearch.action.admin.indices.mapping.put.TransportAutoPutMappingAction) MockEventuallyConsistentRepository(org.opensearch.snapshots.mockstore.MockEventuallyConsistentRepository) ClusterStateAction(org.opensearch.action.admin.cluster.state.ClusterStateAction) Matchers.lessThanOrEqualTo(org.hamcrest.Matchers.lessThanOrEqualTo) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) Collection(java.util.Collection) CreateSnapshotAction(org.opensearch.action.admin.cluster.snapshots.create.CreateSnapshotAction) AutoPutMappingAction(org.opensearch.action.admin.indices.mapping.put.AutoPutMappingAction) Collectors(java.util.stream.Collectors) AliasValidator(org.opensearch.cluster.metadata.AliasValidator) Objects(java.util.Objects) FakeThreadPoolMasterService(org.opensearch.cluster.service.FakeThreadPoolMasterService) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) StatusInfo(org.opensearch.monitor.StatusInfo) BigArrays(org.opensearch.common.util.BigArrays) IntStream(java.util.stream.IntStream) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) CheckedConsumer(org.opensearch.common.CheckedConsumer) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) DeleteIndexAction(org.opensearch.action.admin.indices.delete.DeleteIndexAction) CoordinatorTests(org.opensearch.cluster.coordination.CoordinatorTests) SnapshotDeletionsInProgress(org.opensearch.cluster.SnapshotDeletionsInProgress) NamedWriteableRegistry(org.opensearch.common.io.stream.NamedWriteableRegistry) MappingUpdatedAction(org.opensearch.cluster.action.index.MappingUpdatedAction) HashSet(java.util.HashSet) TransportShardBulkAction(org.opensearch.action.bulk.TransportShardBulkAction) PeerRecoveryTargetService(org.opensearch.indices.recovery.PeerRecoveryTargetService) TransportCreateIndexAction(org.opensearch.action.admin.indices.create.TransportCreateIndexAction) Matchers.iterableWithSize(org.hamcrest.Matchers.iterableWithSize) SearchResponse(org.opensearch.action.search.SearchResponse) PutRepositoryAction(org.opensearch.action.admin.cluster.repositories.put.PutRepositoryAction) RepositoryData(org.opensearch.repositories.RepositoryData) Collections.emptyMap(java.util.Collections.emptyMap) Matchers.empty(org.hamcrest.Matchers.empty) ShardLimitValidator(org.opensearch.indices.ShardLimitValidator) IngestService(org.opensearch.ingest.IngestService) BlobStoreTestUtil(org.opensearch.repositories.blobstore.BlobStoreTestUtil) TransportRequest(org.opensearch.transport.TransportRequest) ActionTestUtils.assertNoFailureListener(org.opensearch.action.support.ActionTestUtils.assertNoFailureListener) CreateIndexResponse(org.opensearch.action.admin.indices.create.CreateIndexResponse) FsRepository(org.opensearch.repositories.fs.FsRepository) ShardRouting(org.opensearch.cluster.routing.ShardRouting) ClusterStateRequest(org.opensearch.action.admin.cluster.state.ClusterStateRequest) ClusterName(org.opensearch.cluster.ClusterName) Comparator(java.util.Comparator) LogManager(org.apache.logging.log4j.LogManager) IndicesModule(org.opensearch.indices.IndicesModule) Arrays(java.util.Arrays) ClusterBootstrapService(org.opensearch.cluster.coordination.ClusterBootstrapService) IndexScopedSettings(org.opensearch.common.settings.IndexScopedSettings) ClusterStateResponse(org.opensearch.action.admin.cluster.state.ClusterStateResponse) TransportInterceptor(org.opensearch.transport.TransportInterceptor) ClusterRerouteAction(org.opensearch.action.admin.cluster.reroute.ClusterRerouteAction) AllocationService(org.opensearch.cluster.routing.allocation.AllocationService) CleanupRepositoryAction(org.opensearch.action.admin.cluster.repositories.cleanup.CleanupRepositoryAction) RequestValidators(org.opensearch.action.RequestValidators) TransportNodesListGatewayStartedShards(org.opensearch.gateway.TransportNodesListGatewayStartedShards) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) TransportCreateSnapshotAction(org.opensearch.action.admin.cluster.snapshots.create.TransportCreateSnapshotAction) SearchExecutionStatsCollector(org.opensearch.action.search.SearchExecutionStatsCollector) ActionListener(org.opensearch.action.ActionListener) ActionType(org.opensearch.action.ActionType) AbstractCoordinatorTestCase(org.opensearch.cluster.coordination.AbstractCoordinatorTestCase) CreateIndexRequest(org.opensearch.action.admin.indices.create.CreateIndexRequest) Repository(org.opensearch.repositories.Repository) MockSinglePrioritizingExecutor(org.opensearch.cluster.coordination.MockSinglePrioritizingExecutor) ScriptService(org.opensearch.script.ScriptService) Index(org.opensearch.index.Index) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) DiscoveryNodeRole(org.opensearch.cluster.node.DiscoveryNodeRole) ActionFilters(org.opensearch.action.support.ActionFilters) Matchers.contains(org.hamcrest.Matchers.contains) StepListener(org.opensearch.action.StepListener) Matchers.is(org.hamcrest.Matchers.is) Matchers.endsWith(org.hamcrest.Matchers.endsWith) TransportException(org.opensearch.transport.TransportException) RepositoriesService(org.opensearch.repositories.RepositoriesService) TransportDeleteSnapshotAction(org.opensearch.action.admin.cluster.snapshots.delete.TransportDeleteSnapshotAction) ClusterState(org.opensearch.cluster.ClusterState) TransportClusterStateAction(org.opensearch.action.admin.cluster.state.TransportClusterStateAction) SearchRequest(org.opensearch.action.search.SearchRequest) Environment(org.opensearch.env.Environment) SetOnce(org.apache.lucene.util.SetOnce) TransportIndicesShardStoresAction(org.opensearch.action.admin.indices.shards.TransportIndicesShardStoresAction) UpdateHelper(org.opensearch.action.update.UpdateHelper) VotingConfiguration(org.opensearch.cluster.coordination.CoordinationMetadata.VotingConfiguration) DeleteSnapshotRequest(org.opensearch.action.admin.cluster.snapshots.delete.DeleteSnapshotRequest) SystemIndices(org.opensearch.indices.SystemIndices) PluginsService(org.opensearch.plugins.PluginsService) InMemoryPersistedState(org.opensearch.cluster.coordination.InMemoryPersistedState) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterService(org.opensearch.cluster.service.ClusterService) ClusterChangedEvent(org.opensearch.cluster.ClusterChangedEvent) BlobStoreRepository(org.opensearch.repositories.blobstore.BlobStoreRepository) Matchers.either(org.hamcrest.Matchers.either) MetadataDeleteIndexService(org.opensearch.cluster.metadata.MetadataDeleteIndexService) NoneCircuitBreakerService(org.opensearch.indices.breaker.NoneCircuitBreakerService) ClusterRerouteRequest(org.opensearch.action.admin.cluster.reroute.ClusterRerouteRequest) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) PrimaryReplicaSyncer(org.opensearch.index.shard.PrimaryReplicaSyncer) ClusterApplierService(org.opensearch.cluster.service.ClusterApplierService) TransportRestoreSnapshotAction(org.opensearch.action.admin.cluster.snapshots.restore.TransportRestoreSnapshotAction) TransportSearchAction(org.opensearch.action.search.TransportSearchAction) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) AnalysisRegistry(org.opensearch.index.analysis.AnalysisRegistry) After(org.junit.After) TransportCleanupRepositoryAction(org.opensearch.action.admin.cluster.repositories.cleanup.TransportCleanupRepositoryAction) IndicesClusterStateService(org.opensearch.indices.cluster.IndicesClusterStateService) DeterministicTaskQueue(org.opensearch.cluster.coordination.DeterministicTaskQueue) AdminClient(org.opensearch.client.AdminClient) IndicesService(org.opensearch.indices.IndicesService) PeerRecoverySourceService(org.opensearch.indices.recovery.PeerRecoverySourceService) CreateIndexAction(org.opensearch.action.admin.indices.create.CreateIndexAction) BatchedRerouteService(org.opensearch.cluster.routing.BatchedRerouteService) Nullable(org.opensearch.common.Nullable) ClusterModule(org.opensearch.cluster.ClusterModule) TransportAddress(org.opensearch.common.transport.TransportAddress) TransportAction(org.opensearch.action.support.TransportAction) List(java.util.List) GlobalCheckpointSyncAction(org.opensearch.index.seqno.GlobalCheckpointSyncAction) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) CoordinationState(org.opensearch.cluster.coordination.CoordinationState) Optional(java.util.Optional) TransportBulkAction(org.opensearch.action.bulk.TransportBulkAction) AllocateEmptyPrimaryAllocationCommand(org.opensearch.cluster.routing.allocation.command.AllocateEmptyPrimaryAllocationCommand) TestEnvironment(org.opensearch.env.TestEnvironment) DiscoveryNodes(org.opensearch.cluster.node.DiscoveryNodes) MetaStateService(org.opensearch.gateway.MetaStateService) SnapshotsInProgress(org.opensearch.cluster.SnapshotsInProgress) HashMap(java.util.HashMap) ClusterStateListener(org.opensearch.cluster.ClusterStateListener) AutoCreateIndex(org.opensearch.action.support.AutoCreateIndex) NodeConnectionsService(org.opensearch.cluster.NodeConnectionsService) MetadataCreateIndexService(org.opensearch.cluster.metadata.MetadataCreateIndexService) DeleteIndexRequest(org.opensearch.action.admin.indices.delete.DeleteIndexRequest) NetworkModule(org.opensearch.common.network.NetworkModule) MetadataMappingService(org.opensearch.cluster.metadata.MetadataMappingService) RerouteService(org.opensearch.cluster.routing.RerouteService) NodeMappingRefreshAction(org.opensearch.cluster.action.index.NodeMappingRefreshAction) ClusterSettings(org.opensearch.common.settings.ClusterSettings) SearchService(org.opensearch.search.SearchService) CleanupRepositoryRequest(org.opensearch.action.admin.cluster.repositories.cleanup.CleanupRepositoryRequest) TransportDeleteIndexAction(org.opensearch.action.admin.indices.delete.TransportDeleteIndexAction) CreateSnapshotResponse(org.opensearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse) Collections.emptySet(java.util.Collections.emptySet) CleanupRepositoryResponse(org.opensearch.action.admin.cluster.repositories.cleanup.CleanupRepositoryResponse) ActiveShardCount(org.opensearch.action.support.ActiveShardCount) AcknowledgedResponse(org.opensearch.action.support.master.AcknowledgedResponse) TimeUnit(java.util.concurrent.TimeUnit) NODE_NAME_SETTING(org.opensearch.node.Node.NODE_NAME_SETTING) BulkResponse(org.opensearch.action.bulk.BulkResponse) IndexRequest(org.opensearch.action.index.IndexRequest) Collections(java.util.Collections) ClusterStateResponse(org.opensearch.action.admin.cluster.state.ClusterStateResponse) ClusterStateRequest(org.opensearch.action.admin.cluster.state.ClusterStateRequest) AllocateEmptyPrimaryAllocationCommand(org.opensearch.cluster.routing.allocation.command.AllocateEmptyPrimaryAllocationCommand) DeleteSnapshotRequest(org.opensearch.action.admin.cluster.snapshots.delete.DeleteSnapshotRequest) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ClusterRerouteRequest(org.opensearch.action.admin.cluster.reroute.ClusterRerouteRequest) MockEventuallyConsistentRepository(org.opensearch.snapshots.mockstore.MockEventuallyConsistentRepository) FsRepository(org.opensearch.repositories.fs.FsRepository) Repository(org.opensearch.repositories.Repository) BlobStoreRepository(org.opensearch.repositories.blobstore.BlobStoreRepository) AbstractRunnable(org.opensearch.common.util.concurrent.AbstractRunnable) StepListener(org.opensearch.action.StepListener) ShardRouting(org.opensearch.cluster.routing.ShardRouting) AdminClient(org.opensearch.client.AdminClient)

Example 5 with ClusterRerouteRequest

use of org.opensearch.action.admin.cluster.reroute.ClusterRerouteRequest in project OpenSearch by opensearch-project.

the class CloseWhileRelocatingShardsIT method testCloseWhileRelocatingShards.

public void testCloseWhileRelocatingShards() throws Exception {
    final String[] indices = new String[randomIntBetween(3, 5)];
    final Map<String, Long> docsPerIndex = new HashMap<>();
    final Map<String, BackgroundIndexer> indexers = new HashMap<>();
    for (int i = 0; i < indices.length; i++) {
        final String indexName = "index-" + i;
        int nbDocs = 0;
        switch(i) {
            case 0:
                logger.debug("creating empty index {}", indexName);
                createIndex(indexName);
                break;
            case 1:
                nbDocs = scaledRandomIntBetween(1, 100);
                logger.debug("creating index {} with {} documents", indexName, nbDocs);
                createIndex(indexName);
                indexRandom(randomBoolean(), IntStream.range(0, nbDocs).mapToObj(n -> client().prepareIndex(indexName).setSource("num", n)).collect(Collectors.toList()));
                break;
            default:
                logger.debug("creating index {} with background indexing", indexName);
                final BackgroundIndexer indexer = new BackgroundIndexer(indexName, "_doc", client(), -1, 1);
                indexers.put(indexName, indexer);
                indexer.setFailureAssertion(t -> assertException(t, indexName));
                waitForDocs(1, indexer);
        }
        docsPerIndex.put(indexName, (long) nbDocs);
        indices[i] = indexName;
    }
    ensureGreen(TimeValue.timeValueSeconds(60L), indices);
    assertAcked(client().admin().cluster().prepareUpdateSettings().setTransientSettings(Settings.builder().put(EnableAllocationDecider.CLUSTER_ROUTING_REBALANCE_ENABLE_SETTING.getKey(), Rebalance.NONE.toString())));
    final String targetNode = internalCluster().startDataOnlyNode();
    // wait for the master to finish processing join.
    ensureClusterSizeConsistency();
    try {
        final ClusterService clusterService = internalCluster().getInstance(ClusterService.class, internalCluster().getMasterName());
        final ClusterState state = clusterService.state();
        final CountDownLatch latch = new CountDownLatch(indices.length);
        final CountDownLatch release = new CountDownLatch(indices.length);
        // relocate one shard for every index to be closed
        final AllocationCommands commands = new AllocationCommands();
        for (final String index : indices) {
            final NumShards numShards = getNumShards(index);
            final int shardId = numShards.numPrimaries == 1 ? 0 : randomIntBetween(0, numShards.numPrimaries - 1);
            final IndexRoutingTable indexRoutingTable = state.routingTable().index(index);
            final ShardRouting primary = indexRoutingTable.shard(shardId).primaryShard();
            assertTrue(primary.started());
            String currentNodeId = primary.currentNodeId();
            if (numShards.numReplicas > 0) {
                final ShardRouting replica = indexRoutingTable.shard(shardId).replicaShards().iterator().next();
                assertTrue(replica.started());
                if (randomBoolean()) {
                    currentNodeId = replica.currentNodeId();
                }
            }
            commands.add(new MoveAllocationCommand(index, shardId, state.nodes().resolveNode(currentNodeId).getName(), targetNode));
        }
        // Build the list of shards for which recoveries will be blocked
        final Set<ShardId> blockedShards = commands.commands().stream().map(c -> (MoveAllocationCommand) c).map(c -> new ShardId(clusterService.state().metadata().index(c.index()).getIndex(), c.shardId())).collect(Collectors.toSet());
        assertThat(blockedShards, hasSize(indices.length));
        final Set<String> acknowledgedCloses = ConcurrentCollections.newConcurrentSet();
        final Set<String> interruptedRecoveries = ConcurrentCollections.newConcurrentSet();
        // Create a SendRequestBehavior that will block outgoing start recovery request
        final StubbableTransport.SendRequestBehavior sendBehavior = (connection, requestId, action, request, options) -> {
            if (PeerRecoverySourceService.Actions.START_RECOVERY.equals(action)) {
                final StartRecoveryRequest startRecoveryRequest = ((StartRecoveryRequest) request);
                if (blockedShards.contains(startRecoveryRequest.shardId())) {
                    logger.debug("blocking recovery of shard {}", startRecoveryRequest.shardId());
                    latch.countDown();
                    try {
                        release.await();
                        logger.debug("releasing recovery of shard {}", startRecoveryRequest.shardId());
                    } catch (final InterruptedException e) {
                        logger.warn(() -> new ParameterizedMessage("exception when releasing recovery of shard {}", startRecoveryRequest.shardId()), e);
                        interruptedRecoveries.add(startRecoveryRequest.shardId().getIndexName());
                        Thread.currentThread().interrupt();
                        return;
                    }
                }
            }
            connection.sendRequest(requestId, action, request, options);
        };
        final MockTransportService targetTransportService = (MockTransportService) internalCluster().getInstance(TransportService.class, targetNode);
        for (DiscoveryNode node : state.getNodes()) {
            if (node.isDataNode() && node.getName().equals(targetNode) == false) {
                final TransportService sourceTransportService = internalCluster().getInstance(TransportService.class, node.getName());
                targetTransportService.addSendBehavior(sourceTransportService, sendBehavior);
            }
        }
        assertAcked(client().admin().cluster().reroute(new ClusterRerouteRequest().commands(commands)).get());
        // start index closing threads
        final List<Thread> threads = new ArrayList<>();
        for (final String indexToClose : indices) {
            final Thread thread = new Thread(() -> {
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    throw new AssertionError(e);
                } finally {
                    release.countDown();
                }
                // Closing is not always acknowledged when shards are relocating: this is the case when the target shard is initializing
                // or is catching up operations. In these cases the TransportVerifyShardBeforeCloseAction will detect that the global
                // and max sequence number don't match and will not ack the close.
                AcknowledgedResponse closeResponse = client().admin().indices().prepareClose(indexToClose).get();
                if (closeResponse.isAcknowledged()) {
                    assertTrue("Index closing should not be acknowledged twice", acknowledgedCloses.add(indexToClose));
                }
            });
            threads.add(thread);
            thread.start();
        }
        latch.countDown();
        for (Thread thread : threads) {
            thread.join();
        }
        // stop indexers first without waiting for stop to not redundantly index on some while waiting for another one to stop
        for (BackgroundIndexer indexer : indexers.values()) {
            indexer.stop();
        }
        for (Map.Entry<String, BackgroundIndexer> entry : indexers.entrySet()) {
            final BackgroundIndexer indexer = entry.getValue();
            indexer.awaitStopped();
            final String indexName = entry.getKey();
            docsPerIndex.computeIfPresent(indexName, (key, value) -> value + indexer.totalIndexedDocs());
        }
        for (String index : indices) {
            if (acknowledgedCloses.contains(index)) {
                assertIndexIsClosed(index);
            } else {
                assertIndexIsOpened(index);
            }
        }
        targetTransportService.clearAllRules();
        // If a shard recovery has been interrupted, we expect its index to be closed
        interruptedRecoveries.forEach(CloseIndexIT::assertIndexIsClosed);
        assertThat("Consider that the test failed if no indices were successfully closed", acknowledgedCloses.size(), greaterThan(0));
        assertAcked(client().admin().indices().prepareOpen("index-*"));
        ensureGreen(indices);
        for (String index : acknowledgedCloses) {
            long docsCount = client().prepareSearch(index).setSize(0).setTrackTotalHits(true).get().getHits().getTotalHits().value;
            assertEquals("Expected " + docsPerIndex.get(index) + " docs in index " + index + " but got " + docsCount + " (close acknowledged=" + acknowledgedCloses.contains(index) + ")", (long) docsPerIndex.get(index), docsCount);
        }
    } finally {
        assertAcked(client().admin().cluster().prepareUpdateSettings().setTransientSettings(Settings.builder().putNull(EnableAllocationDecider.CLUSTER_ROUTING_REBALANCE_ENABLE_SETTING.getKey())));
    }
}
Also used : IntStream(java.util.stream.IntStream) EnableAllocationDecider(org.opensearch.cluster.routing.allocation.decider.EnableAllocationDecider) StubbableTransport(org.opensearch.test.transport.StubbableTransport) CloseIndexIT.assertIndexIsOpened(org.opensearch.indices.state.CloseIndexIT.assertIndexIsOpened) ClusterRerouteRequest(org.opensearch.action.admin.cluster.reroute.ClusterRerouteRequest) HashMap(java.util.HashMap) ThrottlingAllocationDecider(org.opensearch.cluster.routing.allocation.decider.ThrottlingAllocationDecider) MoveAllocationCommand(org.opensearch.cluster.routing.allocation.command.MoveAllocationCommand) MockTransportService(org.opensearch.test.transport.MockTransportService) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) ArrayList(java.util.ArrayList) Collections.singletonList(java.util.Collections.singletonList) CloseIndexIT.assertException(org.opensearch.indices.state.CloseIndexIT.assertException) ConcurrentCollections(org.opensearch.common.util.concurrent.ConcurrentCollections) IndexRoutingTable(org.opensearch.cluster.routing.IndexRoutingTable) ClusterState(org.opensearch.cluster.ClusterState) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) Map(java.util.Map) CloseIndexIT.assertIndexIsClosed(org.opensearch.indices.state.CloseIndexIT.assertIndexIsClosed) Matchers.hasSize(org.hamcrest.Matchers.hasSize) BackgroundIndexer(org.opensearch.test.BackgroundIndexer) OpenSearchAssertions.assertAcked(org.opensearch.test.hamcrest.OpenSearchAssertions.assertAcked) AllocationCommands(org.opensearch.cluster.routing.allocation.command.AllocationCommands) TimeValue(org.opensearch.common.unit.TimeValue) Collection(java.util.Collection) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) PeerRecoverySourceService(org.opensearch.indices.recovery.PeerRecoverySourceService) TransportService(org.opensearch.transport.TransportService) Collectors(java.util.stream.Collectors) Plugin(org.opensearch.plugins.Plugin) Rebalance(org.opensearch.cluster.routing.allocation.decider.EnableAllocationDecider.Rebalance) AcknowledgedResponse(org.opensearch.action.support.master.AcknowledgedResponse) ShardRouting(org.opensearch.cluster.routing.ShardRouting) ShardId(org.opensearch.index.shard.ShardId) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) ConcurrentRebalanceAllocationDecider(org.opensearch.cluster.routing.allocation.decider.ConcurrentRebalanceAllocationDecider) StartRecoveryRequest(org.opensearch.indices.recovery.StartRecoveryRequest) ClusterService(org.opensearch.cluster.service.ClusterService) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) OpenSearchIntegTestCase(org.opensearch.test.OpenSearchIntegTestCase) IndexRoutingTable(org.opensearch.cluster.routing.IndexRoutingTable) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) BackgroundIndexer(org.opensearch.test.BackgroundIndexer) MockTransportService(org.opensearch.test.transport.MockTransportService) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ShardId(org.opensearch.index.shard.ShardId) ClusterRerouteRequest(org.opensearch.action.admin.cluster.reroute.ClusterRerouteRequest) ClusterState(org.opensearch.cluster.ClusterState) StartRecoveryRequest(org.opensearch.indices.recovery.StartRecoveryRequest) MoveAllocationCommand(org.opensearch.cluster.routing.allocation.command.MoveAllocationCommand) AcknowledgedResponse(org.opensearch.action.support.master.AcknowledgedResponse) CountDownLatch(java.util.concurrent.CountDownLatch) AllocationCommands(org.opensearch.cluster.routing.allocation.command.AllocationCommands) ClusterService(org.opensearch.cluster.service.ClusterService) MockTransportService(org.opensearch.test.transport.MockTransportService) TransportService(org.opensearch.transport.TransportService) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) ShardRouting(org.opensearch.cluster.routing.ShardRouting) StubbableTransport(org.opensearch.test.transport.StubbableTransport) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

ClusterRerouteRequest (org.opensearch.action.admin.cluster.reroute.ClusterRerouteRequest)8 ClusterState (org.opensearch.cluster.ClusterState)6 DiscoveryNode (org.opensearch.cluster.node.DiscoveryNode)6 Settings (org.opensearch.common.settings.Settings)6 ArrayList (java.util.ArrayList)5 CreateIndexRequest (org.opensearch.action.admin.indices.create.CreateIndexRequest)5 HashSet (java.util.HashSet)4 List (java.util.List)4 Set (java.util.Set)4 ShardRouting (org.opensearch.cluster.routing.ShardRouting)4 Collections (java.util.Collections)3 HashMap (java.util.HashMap)3 Collectors (java.util.stream.Collectors)3 Version (org.opensearch.Version)3 UpdateSettingsRequest (org.opensearch.action.admin.indices.settings.put.UpdateSettingsRequest)3 DiscoveryNodes (org.opensearch.cluster.node.DiscoveryNodes)3 ThreadPool (org.opensearch.threadpool.ThreadPool)3 IOException (java.io.IOException)2 Collection (java.util.Collection)2 Collections.singletonList (java.util.Collections.singletonList)2