Search in sources :

Example 1 with AdminClient

use of org.opensearch.client.AdminClient in project OpenSearch by opensearch-project.

the class TemplateUpgradeServiceTests method testUpdateTemplates.

@SuppressWarnings("unchecked")
public void testUpdateTemplates() {
    int additionsCount = randomIntBetween(0, 5);
    int deletionsCount = randomIntBetween(0, 3);
    List<ActionListener<AcknowledgedResponse>> putTemplateListeners = new ArrayList<>();
    List<ActionListener<AcknowledgedResponse>> deleteTemplateListeners = new ArrayList<>();
    Client mockClient = mock(Client.class);
    AdminClient mockAdminClient = mock(AdminClient.class);
    IndicesAdminClient mockIndicesAdminClient = mock(IndicesAdminClient.class);
    when(mockClient.admin()).thenReturn(mockAdminClient);
    when(mockAdminClient.indices()).thenReturn(mockIndicesAdminClient);
    doAnswer(invocation -> {
        Object[] args = invocation.getArguments();
        assert args.length == 2;
        PutIndexTemplateRequest request = (PutIndexTemplateRequest) args[0];
        assertThat(request.name(), equalTo("add_template_" + request.order()));
        putTemplateListeners.add((ActionListener) args[1]);
        return null;
    }).when(mockIndicesAdminClient).putTemplate(any(PutIndexTemplateRequest.class), any(ActionListener.class));
    doAnswer(invocation -> {
        Object[] args = invocation.getArguments();
        assert args.length == 2;
        DeleteIndexTemplateRequest request = (DeleteIndexTemplateRequest) args[0];
        assertThat(request.name(), startsWith("remove_template_"));
        deleteTemplateListeners.add((ActionListener) args[1]);
        return null;
    }).when(mockIndicesAdminClient).deleteTemplate(any(DeleteIndexTemplateRequest.class), any(ActionListener.class));
    Set<String> deletions = new HashSet<>(deletionsCount);
    for (int i = 0; i < deletionsCount; i++) {
        deletions.add("remove_template_" + i);
    }
    Map<String, BytesReference> additions = new HashMap<>(additionsCount);
    for (int i = 0; i < additionsCount; i++) {
        additions.put("add_template_" + i, new BytesArray("{\"index_patterns\" : \"*\", \"order\" : " + i + "}"));
    }
    final TemplateUpgradeService service = new TemplateUpgradeService(mockClient, clusterService, threadPool, Collections.emptyList());
    IllegalStateException ise = expectThrows(IllegalStateException.class, () -> service.upgradeTemplates(additions, deletions));
    assertThat(ise.getMessage(), containsString("template upgrade service should always happen in a system context"));
    // +2 to skip tryFinishUpgrade
    service.upgradesInProgress.set(additionsCount + deletionsCount + 2);
    final ThreadContext threadContext = threadPool.getThreadContext();
    try (ThreadContext.StoredContext ignore = threadContext.stashContext()) {
        threadContext.markAsSystemContext();
        service.upgradeTemplates(additions, deletions);
    }
    assertThat(putTemplateListeners, hasSize(additionsCount));
    assertThat(deleteTemplateListeners, hasSize(deletionsCount));
    for (int i = 0; i < additionsCount; i++) {
        if (randomBoolean()) {
            putTemplateListeners.get(i).onFailure(new RuntimeException("test - ignore"));
        } else {
            putTemplateListeners.get(i).onResponse(new AcknowledgedResponse(randomBoolean()) {
            });
        }
    }
    for (int i = 0; i < deletionsCount; i++) {
        if (randomBoolean()) {
            int prevUpdatesInProgress = service.upgradesInProgress.get();
            deleteTemplateListeners.get(i).onFailure(new RuntimeException("test - ignore"));
            assertThat(prevUpdatesInProgress - service.upgradesInProgress.get(), equalTo(1));
        } else {
            int prevUpdatesInProgress = service.upgradesInProgress.get();
            deleteTemplateListeners.get(i).onResponse(new AcknowledgedResponse(randomBoolean()) {
            });
            assertThat(prevUpdatesInProgress - service.upgradesInProgress.get(), equalTo(1));
        }
    }
    // tryFinishUpgrade was skipped
    assertThat(service.upgradesInProgress.get(), equalTo(2));
}
Also used : BytesReference(org.opensearch.common.bytes.BytesReference) BytesArray(org.opensearch.common.bytes.BytesArray) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) AcknowledgedResponse(org.opensearch.action.support.master.AcknowledgedResponse) PutIndexTemplateRequest(org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest) IndicesAdminClient(org.opensearch.client.IndicesAdminClient) Matchers.containsString(org.hamcrest.Matchers.containsString) DeleteIndexTemplateRequest(org.opensearch.action.admin.indices.template.delete.DeleteIndexTemplateRequest) ActionListener(org.opensearch.action.ActionListener) Client(org.opensearch.client.Client) AdminClient(org.opensearch.client.AdminClient) IndicesAdminClient(org.opensearch.client.IndicesAdminClient) AdminClient(org.opensearch.client.AdminClient) IndicesAdminClient(org.opensearch.client.IndicesAdminClient) HashSet(java.util.HashSet)

Example 2 with AdminClient

use of org.opensearch.client.AdminClient in project OpenSearch by opensearch-project.

the class TemplateUpgradeServiceTests method testClusterStateUpdate.

@SuppressWarnings("unchecked")
public void testClusterStateUpdate() throws InterruptedException {
    final AtomicReference<ActionListener<AcknowledgedResponse>> addedListener = new AtomicReference<>();
    final AtomicReference<ActionListener<AcknowledgedResponse>> changedListener = new AtomicReference<>();
    final AtomicReference<ActionListener<AcknowledgedResponse>> removedListener = new AtomicReference<>();
    final Semaphore updateInvocation = new Semaphore(0);
    final Semaphore calculateInvocation = new Semaphore(0);
    final Semaphore changedInvocation = new Semaphore(0);
    final Semaphore finishInvocation = new Semaphore(0);
    Metadata metadata = randomMetadata(IndexTemplateMetadata.builder("user_template").patterns(randomIndexPatterns()).build(), IndexTemplateMetadata.builder("removed_test_template").patterns(randomIndexPatterns()).build(), IndexTemplateMetadata.builder("changed_test_template").patterns(randomIndexPatterns()).build());
    Client mockClient = mock(Client.class);
    AdminClient mockAdminClient = mock(AdminClient.class);
    IndicesAdminClient mockIndicesAdminClient = mock(IndicesAdminClient.class);
    when(mockClient.admin()).thenReturn(mockAdminClient);
    when(mockAdminClient.indices()).thenReturn(mockIndicesAdminClient);
    doAnswer(invocation -> {
        Object[] args = invocation.getArguments();
        assert args.length == 2;
        PutIndexTemplateRequest request = (PutIndexTemplateRequest) args[0];
        if (request.name().equals("added_test_template")) {
            assertThat(addedListener.getAndSet((ActionListener) args[1]), nullValue());
        } else if (request.name().equals("changed_test_template")) {
            assertThat(changedListener.getAndSet((ActionListener) args[1]), nullValue());
        } else {
            fail("unexpected put template call for " + request.name());
        }
        return null;
    }).when(mockIndicesAdminClient).putTemplate(any(PutIndexTemplateRequest.class), any(ActionListener.class));
    doAnswer(invocation -> {
        Object[] args = invocation.getArguments();
        assert args.length == 2;
        DeleteIndexTemplateRequest request = (DeleteIndexTemplateRequest) args[0];
        assertThat(request.name(), startsWith("removed_test_template"));
        assertThat(removedListener.getAndSet((ActionListener) args[1]), nullValue());
        return null;
    }).when(mockIndicesAdminClient).deleteTemplate(any(DeleteIndexTemplateRequest.class), any(ActionListener.class));
    new TemplateUpgradeService(mockClient, clusterService, threadPool, Arrays.asList(templates -> {
        assertNull(templates.put("added_test_template", IndexTemplateMetadata.builder("added_test_template").patterns(Collections.singletonList("*")).build()));
        return templates;
    }, templates -> {
        assertNotNull(templates.remove("removed_test_template"));
        return templates;
    }, templates -> {
        assertNotNull(templates.put("changed_test_template", IndexTemplateMetadata.builder("changed_test_template").patterns(Collections.singletonList("*")).order(10).build()));
        return templates;
    })) {

        @Override
        void tryFinishUpgrade(AtomicBoolean anyUpgradeFailed) {
            super.tryFinishUpgrade(anyUpgradeFailed);
            finishInvocation.release();
        }

        @Override
        void upgradeTemplates(Map<String, BytesReference> changes, Set<String> deletions) {
            super.upgradeTemplates(changes, deletions);
            updateInvocation.release();
        }

        @Override
        Optional<Tuple<Map<String, BytesReference>, Set<String>>> calculateTemplateChanges(ImmutableOpenMap<String, IndexTemplateMetadata> templates) {
            final Optional<Tuple<Map<String, BytesReference>, Set<String>>> ans = super.calculateTemplateChanges(templates);
            calculateInvocation.release();
            return ans;
        }

        @Override
        public void clusterChanged(ClusterChangedEvent event) {
            super.clusterChanged(event);
            changedInvocation.release();
        }
    };
    ClusterState prevState = ClusterState.EMPTY_STATE;
    ClusterState state = ClusterState.builder(prevState).nodes(DiscoveryNodes.builder().add(new DiscoveryNode("node1", "node1", buildNewFakeTransportAddress(), emptyMap(), MASTER_DATA_ROLES, Version.CURRENT)).localNodeId("node1").masterNodeId("node1").build()).metadata(metadata).build();
    setState(clusterService, state);
    changedInvocation.acquire();
    assertThat(changedInvocation.availablePermits(), equalTo(0));
    calculateInvocation.acquire();
    assertThat(calculateInvocation.availablePermits(), equalTo(0));
    updateInvocation.acquire();
    assertThat(updateInvocation.availablePermits(), equalTo(0));
    assertThat(finishInvocation.availablePermits(), equalTo(0));
    assertThat(addedListener.get(), notNullValue());
    assertThat(changedListener.get(), notNullValue());
    assertThat(removedListener.get(), notNullValue());
    prevState = state;
    state = ClusterState.builder(prevState).metadata(Metadata.builder(state.metadata()).removeTemplate("user_template")).build();
    setState(clusterService, state);
    // Make sure that update wasn't invoked since we are still running
    changedInvocation.acquire();
    assertThat(changedInvocation.availablePermits(), equalTo(0));
    assertThat(calculateInvocation.availablePermits(), equalTo(0));
    assertThat(updateInvocation.availablePermits(), equalTo(0));
    assertThat(finishInvocation.availablePermits(), equalTo(0));
    addedListener.getAndSet(null).onResponse(new AcknowledgedResponse(true) {
    });
    changedListener.getAndSet(null).onResponse(new AcknowledgedResponse(true) {
    });
    removedListener.getAndSet(null).onResponse(new AcknowledgedResponse(true) {
    });
    // 3 upgrades should be completed, in addition to the final calculate
    finishInvocation.acquire(3);
    assertThat(finishInvocation.availablePermits(), equalTo(0));
    calculateInvocation.acquire();
    assertThat(calculateInvocation.availablePermits(), equalTo(0));
    setState(clusterService, state);
    // Make sure that update was called this time since we are no longer running
    changedInvocation.acquire();
    assertThat(changedInvocation.availablePermits(), equalTo(0));
    calculateInvocation.acquire();
    assertThat(calculateInvocation.availablePermits(), equalTo(0));
    updateInvocation.acquire();
    assertThat(updateInvocation.availablePermits(), equalTo(0));
    assertThat(finishInvocation.availablePermits(), equalTo(0));
    addedListener.getAndSet(null).onFailure(new RuntimeException("test - ignore"));
    changedListener.getAndSet(null).onFailure(new RuntimeException("test - ignore"));
    removedListener.getAndSet(null).onFailure(new RuntimeException("test - ignore"));
    finishInvocation.acquire(3);
    assertThat(finishInvocation.availablePermits(), equalTo(0));
    calculateInvocation.acquire();
    assertThat(calculateInvocation.availablePermits(), equalTo(0));
    setState(clusterService, state);
    // Make sure that update wasn't called this time since the index template metadata didn't change
    changedInvocation.acquire();
    assertThat(changedInvocation.availablePermits(), equalTo(0));
    assertThat(calculateInvocation.availablePermits(), equalTo(0));
    assertThat(updateInvocation.availablePermits(), equalTo(0));
    assertThat(finishInvocation.availablePermits(), equalTo(0));
}
Also used : ImmutableOpenMap(org.opensearch.common.collect.ImmutableOpenMap) Arrays(java.util.Arrays) PutIndexTemplateRequest(org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest) TestThreadPool(org.opensearch.threadpool.TestThreadPool) Version(org.opensearch.Version) ClusterServiceUtils.setState(org.opensearch.test.ClusterServiceUtils.setState) CoreMatchers.startsWith(org.hamcrest.CoreMatchers.startsWith) ThreadContext(org.opensearch.common.util.concurrent.ThreadContext) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) After(org.junit.After) Map(java.util.Map) Mockito.doAnswer(org.mockito.Mockito.doAnswer) ActionListener(org.opensearch.action.ActionListener) DeleteIndexTemplateRequest(org.opensearch.action.admin.indices.template.delete.DeleteIndexTemplateRequest) Client(org.opensearch.client.Client) AdminClient(org.opensearch.client.AdminClient) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) Set(java.util.Set) DiscoveryNodeRole(org.opensearch.cluster.node.DiscoveryNodeRole) Collectors(java.util.stream.Collectors) Tuple(org.opensearch.common.collect.Tuple) List(java.util.List) BytesArray(org.opensearch.common.bytes.BytesArray) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Optional(java.util.Optional) Mockito.any(org.mockito.Mockito.any) Matchers.containsString(org.hamcrest.Matchers.containsString) Mockito.mock(org.mockito.Mockito.mock) IntStream(java.util.stream.IntStream) DiscoveryNodes(org.opensearch.cluster.node.DiscoveryNodes) BytesReference(org.opensearch.common.bytes.BytesReference) ThreadPool(org.opensearch.threadpool.ThreadPool) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ClusterState(org.opensearch.cluster.ClusterState) Matchers.hasSize(org.hamcrest.Matchers.hasSize) CoreMatchers.nullValue(org.hamcrest.CoreMatchers.nullValue) Before(org.junit.Before) Collections.emptyMap(java.util.Collections.emptyMap) Matchers.empty(org.hamcrest.Matchers.empty) ClusterServiceUtils.createClusterService(org.opensearch.test.ClusterServiceUtils.createClusterService) Semaphore(java.util.concurrent.Semaphore) Mockito.when(org.mockito.Mockito.when) AcknowledgedResponse(org.opensearch.action.support.master.AcknowledgedResponse) IndicesAdminClient(org.opensearch.client.IndicesAdminClient) ClusterService(org.opensearch.cluster.service.ClusterService) Collections(java.util.Collections) ClusterChangedEvent(org.opensearch.cluster.ClusterChangedEvent) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) Set(java.util.Set) HashSet(java.util.HashSet) PutIndexTemplateRequest(org.opensearch.action.admin.indices.template.put.PutIndexTemplateRequest) IndicesAdminClient(org.opensearch.client.IndicesAdminClient) ClusterChangedEvent(org.opensearch.cluster.ClusterChangedEvent) Semaphore(java.util.concurrent.Semaphore) Matchers.containsString(org.hamcrest.Matchers.containsString) DeleteIndexTemplateRequest(org.opensearch.action.admin.indices.template.delete.DeleteIndexTemplateRequest) ImmutableOpenMap(org.opensearch.common.collect.ImmutableOpenMap) Client(org.opensearch.client.Client) AdminClient(org.opensearch.client.AdminClient) IndicesAdminClient(org.opensearch.client.IndicesAdminClient) BytesReference(org.opensearch.common.bytes.BytesReference) ClusterState(org.opensearch.cluster.ClusterState) AcknowledgedResponse(org.opensearch.action.support.master.AcknowledgedResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ActionListener(org.opensearch.action.ActionListener) ImmutableOpenMap(org.opensearch.common.collect.ImmutableOpenMap) Map(java.util.Map) HashMap(java.util.HashMap) Collections.emptyMap(java.util.Collections.emptyMap) Tuple(org.opensearch.common.collect.Tuple) AdminClient(org.opensearch.client.AdminClient) IndicesAdminClient(org.opensearch.client.IndicesAdminClient)

Example 3 with AdminClient

use of org.opensearch.client.AdminClient 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 4 with AdminClient

use of org.opensearch.client.AdminClient in project OpenSearch by opensearch-project.

the class MappingUpdatedActionTests method testSendUpdateMappingUsingAutoPutMappingAction.

public void testSendUpdateMappingUsingAutoPutMappingAction() {
    DiscoveryNodes nodes = DiscoveryNodes.builder().add(new DiscoveryNode("first", buildNewFakeTransportAddress(), LegacyESVersion.V_7_9_0)).build();
    ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).nodes(nodes).build();
    ClusterService clusterService = mock(ClusterService.class);
    when(clusterService.state()).thenReturn(clusterState);
    IndicesAdminClient indicesAdminClient = mock(IndicesAdminClient.class);
    AdminClient adminClient = mock(AdminClient.class);
    when(adminClient.indices()).thenReturn(indicesAdminClient);
    Client client = mock(Client.class);
    when(client.admin()).thenReturn(adminClient);
    MappingUpdatedAction mua = new MappingUpdatedAction(Settings.EMPTY, new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS), clusterService);
    mua.setClient(client);
    Settings indexSettings = Settings.builder().put(SETTING_VERSION_CREATED, Version.CURRENT).build();
    final Mapper.BuilderContext context = new Mapper.BuilderContext(indexSettings, new ContentPath());
    RootObjectMapper rootObjectMapper = new RootObjectMapper.Builder("name").build(context);
    Mapping update = new Mapping(LegacyESVersion.V_7_9_0, rootObjectMapper, new MetadataFieldMapper[0], Map.of());
    mua.sendUpdateMapping(new Index("name", "uuid"), update, ActionListener.wrap(() -> {
    }));
    verify(indicesAdminClient).execute(eq(AutoPutMappingAction.INSTANCE), any(), any());
}
Also used : ClusterState(org.opensearch.cluster.ClusterState) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) ClusterSettings(org.opensearch.common.settings.ClusterSettings) RootObjectMapper(org.opensearch.index.mapper.RootObjectMapper) IndicesAdminClient(org.opensearch.client.IndicesAdminClient) Mapping(org.opensearch.index.mapper.Mapping) Index(org.opensearch.index.Index) ContentPath(org.opensearch.index.mapper.ContentPath) Mapper(org.opensearch.index.mapper.Mapper) RootObjectMapper(org.opensearch.index.mapper.RootObjectMapper) MetadataFieldMapper(org.opensearch.index.mapper.MetadataFieldMapper) ClusterService(org.opensearch.cluster.service.ClusterService) ClusterName(org.opensearch.cluster.ClusterName) Client(org.opensearch.client.Client) AdminClient(org.opensearch.client.AdminClient) IndicesAdminClient(org.opensearch.client.IndicesAdminClient) DiscoveryNodes(org.opensearch.cluster.node.DiscoveryNodes) ClusterSettings(org.opensearch.common.settings.ClusterSettings) Settings(org.opensearch.common.settings.Settings) AdminClient(org.opensearch.client.AdminClient) IndicesAdminClient(org.opensearch.client.IndicesAdminClient)

Example 5 with AdminClient

use of org.opensearch.client.AdminClient in project OpenSearch by opensearch-project.

the class MappingUpdatedActionTests method testSendUpdateMappingUsingPutMappingAction.

public void testSendUpdateMappingUsingPutMappingAction() {
    DiscoveryNodes nodes = DiscoveryNodes.builder().add(new DiscoveryNode("first", buildNewFakeTransportAddress(), LegacyESVersion.V_7_8_0)).build();
    ClusterState clusterState = ClusterState.builder(new ClusterName("_name")).nodes(nodes).build();
    ClusterService clusterService = mock(ClusterService.class);
    when(clusterService.state()).thenReturn(clusterState);
    IndicesAdminClient indicesAdminClient = mock(IndicesAdminClient.class);
    AdminClient adminClient = mock(AdminClient.class);
    when(adminClient.indices()).thenReturn(indicesAdminClient);
    Client client = mock(Client.class);
    when(client.admin()).thenReturn(adminClient);
    MappingUpdatedAction mua = new MappingUpdatedAction(Settings.EMPTY, new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS), clusterService);
    mua.setClient(client);
    Settings indexSettings = Settings.builder().put(SETTING_VERSION_CREATED, Version.CURRENT).build();
    final Mapper.BuilderContext context = new Mapper.BuilderContext(indexSettings, new ContentPath());
    RootObjectMapper rootObjectMapper = new RootObjectMapper.Builder("name").build(context);
    Mapping update = new Mapping(LegacyESVersion.V_7_8_0, rootObjectMapper, new MetadataFieldMapper[0], Map.of());
    mua.sendUpdateMapping(new Index("name", "uuid"), update, ActionListener.wrap(() -> {
    }));
    verify(indicesAdminClient).putMapping(any(), any());
}
Also used : ClusterState(org.opensearch.cluster.ClusterState) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) ClusterSettings(org.opensearch.common.settings.ClusterSettings) RootObjectMapper(org.opensearch.index.mapper.RootObjectMapper) IndicesAdminClient(org.opensearch.client.IndicesAdminClient) Mapping(org.opensearch.index.mapper.Mapping) Index(org.opensearch.index.Index) ContentPath(org.opensearch.index.mapper.ContentPath) Mapper(org.opensearch.index.mapper.Mapper) RootObjectMapper(org.opensearch.index.mapper.RootObjectMapper) MetadataFieldMapper(org.opensearch.index.mapper.MetadataFieldMapper) ClusterService(org.opensearch.cluster.service.ClusterService) ClusterName(org.opensearch.cluster.ClusterName) Client(org.opensearch.client.Client) AdminClient(org.opensearch.client.AdminClient) IndicesAdminClient(org.opensearch.client.IndicesAdminClient) DiscoveryNodes(org.opensearch.cluster.node.DiscoveryNodes) ClusterSettings(org.opensearch.common.settings.ClusterSettings) Settings(org.opensearch.common.settings.Settings) AdminClient(org.opensearch.client.AdminClient) IndicesAdminClient(org.opensearch.client.IndicesAdminClient)

Aggregations

AdminClient (org.opensearch.client.AdminClient)5 Client (org.opensearch.client.Client)4 IndicesAdminClient (org.opensearch.client.IndicesAdminClient)4 ClusterState (org.opensearch.cluster.ClusterState)4 DiscoveryNode (org.opensearch.cluster.node.DiscoveryNode)4 DiscoveryNodes (org.opensearch.cluster.node.DiscoveryNodes)4 ClusterService (org.opensearch.cluster.service.ClusterService)4 HashMap (java.util.HashMap)3 HashSet (java.util.HashSet)3 ActionListener (org.opensearch.action.ActionListener)3 AcknowledgedResponse (org.opensearch.action.support.master.AcknowledgedResponse)3 ThreadContext (org.opensearch.common.util.concurrent.ThreadContext)3 ArrayList (java.util.ArrayList)2 Arrays (java.util.Arrays)2 Collections (java.util.Collections)2 Collections.emptyMap (java.util.Collections.emptyMap)2 List (java.util.List)2 Map (java.util.Map)2 Optional (java.util.Optional)2 Set (java.util.Set)2