Search in sources :

Example 31 with ClusterStateResponse

use of org.opensearch.action.admin.cluster.state.ClusterStateResponse in project OpenSearch by opensearch-project.

the class SnapshotResiliencyTests method testSnapshotPrimaryRelocations.

/**
 * Simulates concurrent restarts of data and cluster-manager nodes as well as relocating a primary shard, while starting and subsequently
 * deleting a snapshot.
 */
public void testSnapshotPrimaryRelocations() {
    final int clusterManagerNodeCount = randomFrom(1, 3, 5);
    setupTestCluster(clusterManagerNodeCount, randomIntBetween(2, 5));
    String repoName = "repo";
    String snapshotName = "snapshot";
    final String index = "test";
    final int shards = randomIntBetween(1, 5);
    final TestClusterNodes.TestClusterNode clusterManagerNode = testClusterNodes.currentClusterManager(testClusterNodes.nodes.values().iterator().next().clusterService.state());
    final AtomicBoolean createdSnapshot = new AtomicBoolean();
    final AdminClient clusterManagerAdminClient = clusterManagerNode.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<>();
                clusterManagerAdminClient.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 (clusterManagerNodeCount > 1) {
                            scheduleNow(() -> testClusterNodes.stopNode(clusterManagerNode));
                        }
                        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.randomClusterManagerNodeSafe().client.admin().cluster().reroute(new ClusterRerouteRequest().add(new AllocateEmptyPrimaryAllocationCommand(index, shardRouting.shardId().id(), otherNode.node.getName(), true)), noopListener()));
                    } else {
                        scheduleSoon(this);
                    }
                });
            }
        });
    });
    runUntil(() -> testClusterNodes.randomClusterManagerNode().map(clusterManager -> {
        if (createdSnapshot.get() == false) {
            return false;
        }
        return clusterManager.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.randomClusterManagerNodeSafe().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) QueryPhase(org.opensearch.search.query.QueryPhase) 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) SegmentReplicationCheckpointPublisher(org.opensearch.indices.replication.checkpoint.SegmentReplicationCheckpointPublisher) 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 32 with ClusterStateResponse

use of org.opensearch.action.admin.cluster.state.ClusterStateResponse in project OpenSearch by opensearch-project.

the class GatewayIndexStateIT method testJustMasterNode.

public void testJustMasterNode() throws Exception {
    logger.info("--> cleaning nodes");
    logger.info("--> starting 1 master node non data");
    internalCluster().startNode(nonDataNode());
    logger.info("--> create an index");
    client().admin().indices().prepareCreate("test").setWaitForActiveShards(ActiveShardCount.NONE).execute().actionGet();
    logger.info("--> restarting master node");
    internalCluster().fullRestart(new RestartCallback() {

        @Override
        public Settings onNodeStopped(String nodeName) {
            return nonDataNode();
        }
    });
    logger.info("--> waiting for test index to be created");
    ClusterHealthResponse health = client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setIndices("test").execute().actionGet();
    assertThat(health.isTimedOut(), equalTo(false));
    logger.info("--> verify we have an index");
    ClusterStateResponse clusterStateResponse = client().admin().cluster().prepareState().setIndices("test").execute().actionGet();
    assertThat(clusterStateResponse.getState().metadata().hasIndex("test"), equalTo(true));
}
Also used : ClusterHealthResponse(org.opensearch.action.admin.cluster.health.ClusterHealthResponse) ClusterStateResponse(org.opensearch.action.admin.cluster.state.ClusterStateResponse) Matchers.containsString(org.hamcrest.Matchers.containsString) RestartCallback(org.opensearch.test.InternalTestCluster.RestartCallback) Settings(org.opensearch.common.settings.Settings)

Example 33 with ClusterStateResponse

use of org.opensearch.action.admin.cluster.state.ClusterStateResponse in project OpenSearch by opensearch-project.

the class NoMasterNodeIT method testNoMasterActionsMetadataWriteMasterBlock.

public void testNoMasterActionsMetadataWriteMasterBlock() throws Exception {
    Settings settings = Settings.builder().put(NoMasterBlockService.NO_MASTER_BLOCK_SETTING.getKey(), "metadata_write").put(MappingUpdatedAction.INDICES_MAPPING_DYNAMIC_TIMEOUT_SETTING.getKey(), "100ms").build();
    final List<String> nodes = internalCluster().startNodes(3, settings);
    prepareCreate("test1").setSettings(Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1).put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 1)).get();
    client().admin().cluster().prepareHealth("_all").setWaitForGreenStatus().get();
    client().prepareIndex("test1").setId("1").setSource("field", "value1").get();
    refresh();
    ensureGreen("test1");
    ClusterStateResponse clusterState = client().admin().cluster().prepareState().get();
    logger.info("Cluster state:\n{}", clusterState.getState());
    final List<String> nodesWithShards = clusterState.getState().routingTable().index("test1").shard(0).activeShards().stream().map(shardRouting -> shardRouting.currentNodeId()).map(nodeId -> clusterState.getState().nodes().resolveNode(nodeId)).map(DiscoveryNode::getName).collect(Collectors.toList());
    client().execute(AddVotingConfigExclusionsAction.INSTANCE, new AddVotingConfigExclusionsRequest(nodesWithShards.toArray(new String[0]))).get();
    ensureGreen("test1");
    String partitionedNode = nodes.stream().filter(n -> nodesWithShards.contains(n) == false).findFirst().get();
    final NetworkDisruption disruptionScheme = new NetworkDisruption(new NetworkDisruption.TwoPartitions(Collections.singleton(partitionedNode), new HashSet<>(nodesWithShards)), NetworkDisruption.DISCONNECT);
    internalCluster().setDisruptionScheme(disruptionScheme);
    disruptionScheme.startDisrupting();
    assertBusy(() -> {
        for (String node : nodesWithShards) {
            ClusterState state = client(node).admin().cluster().prepareState().setLocal(true).get().getState();
            assertTrue(state.blocks().hasGlobalBlockWithId(NoMasterBlockService.NO_MASTER_BLOCK_ID));
        }
    });
    GetResponse getResponse = client(randomFrom(nodesWithShards)).prepareGet("test1", "1").get();
    assertExists(getResponse);
    expectThrows(Exception.class, () -> client(partitionedNode).prepareGet("test1", "1").get());
    SearchResponse countResponse = client(randomFrom(nodesWithShards)).prepareSearch("test1").setAllowPartialSearchResults(true).setSize(0).get();
    assertHitCount(countResponse, 1L);
    expectThrows(Exception.class, () -> client(partitionedNode).prepareSearch("test1").setAllowPartialSearchResults(true).setSize(0).get());
    TimeValue timeout = TimeValue.timeValueMillis(200);
    client(randomFrom(nodesWithShards)).prepareUpdate("test1", "1").setDoc(Requests.INDEX_CONTENT_TYPE, "field", "value2").setTimeout(timeout).get();
    expectThrows(Exception.class, () -> client(partitionedNode).prepareUpdate("test1", "1").setDoc(Requests.INDEX_CONTENT_TYPE, "field", "value2").setTimeout(timeout).get());
    client(randomFrom(nodesWithShards)).prepareIndex("test1").setId("1").setSource(XContentFactory.jsonBuilder().startObject().endObject()).setTimeout(timeout).get();
    // dynamic mapping updates fail
    expectThrows(MasterNotDiscoveredException.class, () -> client(randomFrom(nodesWithShards)).prepareIndex("test1").setId("1").setSource(XContentFactory.jsonBuilder().startObject().field("new_field", "value").endObject()).setTimeout(timeout).get());
    // dynamic index creation fails
    expectThrows(MasterNotDiscoveredException.class, () -> client(randomFrom(nodesWithShards)).prepareIndex("test2").setId("1").setSource(XContentFactory.jsonBuilder().startObject().endObject()).setTimeout(timeout).get());
    expectThrows(Exception.class, () -> client(partitionedNode).prepareIndex("test1").setId("1").setSource(XContentFactory.jsonBuilder().startObject().endObject()).setTimeout(timeout).get());
    internalCluster().clearDisruptionScheme(true);
}
Also used : ActionRequestBuilder(org.opensearch.action.ActionRequestBuilder) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) ClusterStateResponse(org.opensearch.action.admin.cluster.state.ClusterStateResponse) ClusterScope(org.opensearch.test.OpenSearchIntegTestCase.ClusterScope) MasterNotDiscoveredException(org.opensearch.discovery.MasterNotDiscoveredException) MockTransportService(org.opensearch.test.transport.MockTransportService) BulkRequestBuilder(org.opensearch.action.bulk.BulkRequestBuilder) AutoCreateIndex(org.opensearch.action.support.AutoCreateIndex) MappingUpdatedAction(org.opensearch.cluster.action.index.MappingUpdatedAction) ScriptType(org.opensearch.script.ScriptType) HashSet(java.util.HashSet) Requests(org.opensearch.client.Requests) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) OpenSearchAssertions.assertHitCount(org.opensearch.test.hamcrest.OpenSearchAssertions.assertHitCount) AddVotingConfigExclusionsAction(org.opensearch.action.admin.cluster.configuration.AddVotingConfigExclusionsAction) XContentFactory(org.opensearch.common.xcontent.XContentFactory) IsolateAllNodes(org.opensearch.test.disruption.NetworkDisruption.IsolateAllNodes) SearchResponse(org.opensearch.action.search.SearchResponse) NoMasterBlockService(org.opensearch.cluster.coordination.NoMasterBlockService) GetResponse(org.opensearch.action.get.GetResponse) OpenSearchAssertions.assertRequestBuilderThrows(org.opensearch.test.hamcrest.OpenSearchAssertions.assertRequestBuilderThrows) Client(org.opensearch.client.Client) TimeValue(org.opensearch.common.unit.TimeValue) Script(org.opensearch.script.Script) Collection(java.util.Collection) AddVotingConfigExclusionsRequest(org.opensearch.action.admin.cluster.configuration.AddVotingConfigExclusionsRequest) ClusterBlockException(org.opensearch.cluster.block.ClusterBlockException) Settings(org.opensearch.common.settings.Settings) RestStatus(org.opensearch.rest.RestStatus) Scope(org.opensearch.test.OpenSearchIntegTestCase.Scope) Collectors(java.util.stream.Collectors) Plugin(org.opensearch.plugins.Plugin) List(java.util.List) Matchers.equalTo(org.hamcrest.Matchers.equalTo) NetworkDisruption(org.opensearch.test.disruption.NetworkDisruption) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) OpenSearchAssertions.assertExists(org.opensearch.test.hamcrest.OpenSearchAssertions.assertExists) OpenSearchIntegTestCase(org.opensearch.test.OpenSearchIntegTestCase) Collections(java.util.Collections) ClusterStateResponse(org.opensearch.action.admin.cluster.state.ClusterStateResponse) GetResponse(org.opensearch.action.get.GetResponse) SearchResponse(org.opensearch.action.search.SearchResponse) AddVotingConfigExclusionsRequest(org.opensearch.action.admin.cluster.configuration.AddVotingConfigExclusionsRequest) NetworkDisruption(org.opensearch.test.disruption.NetworkDisruption) Settings(org.opensearch.common.settings.Settings) TimeValue(org.opensearch.common.unit.TimeValue) HashSet(java.util.HashSet)

Example 34 with ClusterStateResponse

use of org.opensearch.action.admin.cluster.state.ClusterStateResponse in project OpenSearch by opensearch-project.

the class NoMasterNodeIT method testNoMasterActionsWriteMasterBlock.

public void testNoMasterActionsWriteMasterBlock() throws Exception {
    Settings settings = Settings.builder().put(AutoCreateIndex.AUTO_CREATE_INDEX_SETTING.getKey(), false).put(NoMasterBlockService.NO_MASTER_BLOCK_SETTING.getKey(), "write").build();
    final List<String> nodes = internalCluster().startNodes(3, settings);
    prepareCreate("test1").setSettings(Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1).put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 2)).get();
    prepareCreate("test2").setSettings(Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 3).put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0)).get();
    client().admin().cluster().prepareHealth("_all").setWaitForGreenStatus().get();
    client().prepareIndex("test1").setId("1").setSource("field", "value1").get();
    client().prepareIndex("test2").setId("1").setSource("field", "value1").get();
    refresh();
    ensureSearchable("test1", "test2");
    ClusterStateResponse clusterState = client().admin().cluster().prepareState().get();
    logger.info("Cluster state:\n{}", clusterState.getState());
    final NetworkDisruption disruptionScheme = new NetworkDisruption(new IsolateAllNodes(new HashSet<>(nodes)), NetworkDisruption.DISCONNECT);
    internalCluster().setDisruptionScheme(disruptionScheme);
    disruptionScheme.startDisrupting();
    final Client clientToMasterlessNode = client();
    assertBusy(() -> {
        ClusterState state = clientToMasterlessNode.admin().cluster().prepareState().setLocal(true).get().getState();
        assertTrue(state.blocks().hasGlobalBlockWithId(NoMasterBlockService.NO_MASTER_BLOCK_ID));
    });
    GetResponse getResponse = clientToMasterlessNode.prepareGet("test1", "1").get();
    assertExists(getResponse);
    SearchResponse countResponse = clientToMasterlessNode.prepareSearch("test1").setAllowPartialSearchResults(true).setSize(0).get();
    assertHitCount(countResponse, 1L);
    logger.info("--> here 3");
    SearchResponse searchResponse = clientToMasterlessNode.prepareSearch("test1").setAllowPartialSearchResults(true).get();
    assertHitCount(searchResponse, 1L);
    countResponse = clientToMasterlessNode.prepareSearch("test2").setAllowPartialSearchResults(true).setSize(0).get();
    assertThat(countResponse.getTotalShards(), equalTo(3));
    assertThat(countResponse.getSuccessfulShards(), equalTo(1));
    TimeValue timeout = TimeValue.timeValueMillis(200);
    long now = System.currentTimeMillis();
    try {
        clientToMasterlessNode.prepareUpdate("test1", "1").setDoc(Requests.INDEX_CONTENT_TYPE, "field", "value2").setTimeout(timeout).get();
        fail("Expected ClusterBlockException");
    } catch (ClusterBlockException e) {
        assertThat(System.currentTimeMillis() - now, greaterThan(timeout.millis() - 50));
        assertThat(e.status(), equalTo(RestStatus.SERVICE_UNAVAILABLE));
    } catch (Exception e) {
        logger.info("unexpected", e);
        throw e;
    }
    try {
        clientToMasterlessNode.prepareIndex("test1").setId("1").setSource(XContentFactory.jsonBuilder().startObject().endObject()).setTimeout(timeout).get();
        fail("Expected ClusterBlockException");
    } catch (ClusterBlockException e) {
        assertThat(e.status(), equalTo(RestStatus.SERVICE_UNAVAILABLE));
    }
    internalCluster().clearDisruptionScheme(true);
}
Also used : IsolateAllNodes(org.opensearch.test.disruption.NetworkDisruption.IsolateAllNodes) ClusterStateResponse(org.opensearch.action.admin.cluster.state.ClusterStateResponse) GetResponse(org.opensearch.action.get.GetResponse) ClusterBlockException(org.opensearch.cluster.block.ClusterBlockException) MasterNotDiscoveredException(org.opensearch.discovery.MasterNotDiscoveredException) ClusterBlockException(org.opensearch.cluster.block.ClusterBlockException) SearchResponse(org.opensearch.action.search.SearchResponse) NetworkDisruption(org.opensearch.test.disruption.NetworkDisruption) Client(org.opensearch.client.Client) Settings(org.opensearch.common.settings.Settings) TimeValue(org.opensearch.common.unit.TimeValue) HashSet(java.util.HashSet)

Example 35 with ClusterStateResponse

use of org.opensearch.action.admin.cluster.state.ClusterStateResponse in project OpenSearch by opensearch-project.

the class RemoteClusterConnectionTests method startTransport.

public static MockTransportService startTransport(final String id, final List<DiscoveryNode> knownNodes, final Version version, final ThreadPool threadPool, final Settings settings) {
    boolean success = false;
    final Settings s = Settings.builder().put(settings).put("node.name", id).build();
    ClusterName clusterName = ClusterName.CLUSTER_NAME_SETTING.get(s);
    MockTransportService newService = MockTransportService.createNewService(s, version, threadPool, null);
    try {
        newService.registerRequestHandler(ClusterSearchShardsAction.NAME, ThreadPool.Names.SAME, ClusterSearchShardsRequest::new, (request, channel, task) -> {
            if ("index_not_found".equals(request.preference())) {
                channel.sendResponse(new IndexNotFoundException("index"));
            } else {
                channel.sendResponse(new ClusterSearchShardsResponse(new ClusterSearchShardsGroup[0], knownNodes.toArray(new DiscoveryNode[0]), Collections.emptyMap()));
            }
        });
        newService.registerRequestHandler(SearchAction.NAME, ThreadPool.Names.SAME, SearchRequest::new, (request, channel, task) -> {
            if ("index_not_found".equals(request.preference())) {
                channel.sendResponse(new IndexNotFoundException("index"));
                return;
            }
            SearchHits searchHits;
            if ("null_target".equals(request.preference())) {
                searchHits = new SearchHits(new SearchHit[] { new SearchHit(0) }, new TotalHits(1, TotalHits.Relation.EQUAL_TO), 1F);
            } else {
                searchHits = new SearchHits(new SearchHit[0], new TotalHits(0, TotalHits.Relation.EQUAL_TO), Float.NaN);
            }
            InternalSearchResponse response = new InternalSearchResponse(searchHits, InternalAggregations.EMPTY, null, null, false, null, 1);
            SearchResponse searchResponse = new SearchResponse(response, null, 1, 1, 0, 100, ShardSearchFailure.EMPTY_ARRAY, SearchResponse.Clusters.EMPTY);
            channel.sendResponse(searchResponse);
        });
        newService.registerRequestHandler(ClusterStateAction.NAME, ThreadPool.Names.SAME, ClusterStateRequest::new, (request, channel, task) -> {
            DiscoveryNodes.Builder builder = DiscoveryNodes.builder();
            for (DiscoveryNode node : knownNodes) {
                builder.add(node);
            }
            ClusterState build = ClusterState.builder(clusterName).nodes(builder.build()).build();
            channel.sendResponse(new ClusterStateResponse(clusterName, build, false));
        });
        newService.start();
        newService.acceptIncomingRequests();
        success = true;
        return newService;
    } finally {
        if (success == false) {
            newService.close();
        }
    }
}
Also used : ClusterSearchShardsResponse(org.opensearch.action.admin.cluster.shards.ClusterSearchShardsResponse) TotalHits(org.apache.lucene.search.TotalHits) SearchRequest(org.opensearch.action.search.SearchRequest) ClusterState(org.opensearch.cluster.ClusterState) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) MockTransportService(org.opensearch.test.transport.MockTransportService) SearchHit(org.opensearch.search.SearchHit) ClusterStateResponse(org.opensearch.action.admin.cluster.state.ClusterStateResponse) ClusterStateRequest(org.opensearch.action.admin.cluster.state.ClusterStateRequest) ClusterSearchShardsGroup(org.opensearch.action.admin.cluster.shards.ClusterSearchShardsGroup) SearchResponse(org.opensearch.action.search.SearchResponse) InternalSearchResponse(org.opensearch.search.internal.InternalSearchResponse) ClusterSearchShardsRequest(org.opensearch.action.admin.cluster.shards.ClusterSearchShardsRequest) ClusterName(org.opensearch.cluster.ClusterName) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) SearchHits(org.opensearch.search.SearchHits) Settings(org.opensearch.common.settings.Settings) DiscoveryNodes(org.opensearch.cluster.node.DiscoveryNodes) InternalSearchResponse(org.opensearch.search.internal.InternalSearchResponse)

Aggregations

ClusterStateResponse (org.opensearch.action.admin.cluster.state.ClusterStateResponse)60 Settings (org.opensearch.common.settings.Settings)23 DiscoveryNode (org.opensearch.cluster.node.DiscoveryNode)20 ClusterStateRequest (org.opensearch.action.admin.cluster.state.ClusterStateRequest)19 List (java.util.List)17 NodeClient (org.opensearch.client.node.NodeClient)13 DiscoveryNodes (org.opensearch.cluster.node.DiscoveryNodes)13 DeprecationLogger (org.opensearch.common.logging.DeprecationLogger)12 RestRequest (org.opensearch.rest.RestRequest)12 GET (org.opensearch.rest.RestRequest.Method.GET)12 RestResponse (org.opensearch.rest.RestResponse)12 Table (org.opensearch.common.Table)11 SearchResponse (org.opensearch.action.search.SearchResponse)10 Client (org.opensearch.client.Client)10 ClusterState (org.opensearch.cluster.ClusterState)10 RestResponseListener (org.opensearch.rest.action.RestResponseListener)10 MockTransportService (org.opensearch.test.transport.MockTransportService)10 HashSet (java.util.HashSet)9 ShardRouting (org.opensearch.cluster.routing.ShardRouting)8 Strings (org.opensearch.common.Strings)8