Search in sources :

Example 1 with IMMEDIATE

use of org.opensearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE in project OpenSearch by opensearch-project.

the class SearchServiceTests method testSetSearchThrottled.

public void testSetSearchThrottled() {
    createIndex("throttled_threadpool_index");
    client().execute(InternalOrPrivateSettingsPlugin.UpdateInternalOrPrivateAction.INSTANCE, new InternalOrPrivateSettingsPlugin.UpdateInternalOrPrivateAction.Request("throttled_threadpool_index", IndexSettings.INDEX_SEARCH_THROTTLED.getKey(), "true")).actionGet();
    final SearchService service = getInstanceFromNode(SearchService.class);
    Index index = resolveIndex("throttled_threadpool_index");
    assertTrue(service.getIndicesService().indexServiceSafe(index).getIndexSettings().isSearchThrottled());
    client().prepareIndex("throttled_threadpool_index").setId("1").setSource("field", "value").setRefreshPolicy(IMMEDIATE).get();
    SearchResponse searchResponse = client().prepareSearch("throttled_threadpool_index").setIndicesOptions(IndicesOptions.STRICT_EXPAND_OPEN_FORBID_CLOSED).setSize(1).get();
    assertSearchHits(searchResponse, "1");
    // we add a search action listener in a plugin above to assert that this is actually used
    client().execute(InternalOrPrivateSettingsPlugin.UpdateInternalOrPrivateAction.INSTANCE, new InternalOrPrivateSettingsPlugin.UpdateInternalOrPrivateAction.Request("throttled_threadpool_index", IndexSettings.INDEX_SEARCH_THROTTLED.getKey(), "false")).actionGet();
    IllegalArgumentException iae = expectThrows(IllegalArgumentException.class, () -> client().admin().indices().prepareUpdateSettings("throttled_threadpool_index").setSettings(Settings.builder().put(IndexSettings.INDEX_SEARCH_THROTTLED.getKey(), false)).get());
    assertEquals("can not update private setting [index.search.throttled]; this setting is managed by OpenSearch", iae.getMessage());
    assertFalse(service.getIndicesService().indexServiceSafe(index).getIndexSettings().isSearchThrottled());
    SearchRequest searchRequest = new SearchRequest().allowPartialSearchResults(false);
    ShardSearchRequest req = new ShardSearchRequest(OriginalIndices.NONE, searchRequest, new ShardId(index, 0), 1, new AliasFilter(null, Strings.EMPTY_ARRAY), 1f, -1, null, null);
    Thread currentThread = Thread.currentThread();
    // we still make sure can match is executed on the network thread
    service.canMatch(req, ActionListener.wrap(r -> assertSame(Thread.currentThread(), currentThread), e -> fail("unexpected")));
}
Also used : ShardId(org.opensearch.index.shard.ShardId) Query(org.apache.lucene.search.Query) OpenSearchRejectedExecutionException(org.opensearch.common.util.concurrent.OpenSearchRejectedExecutionException) CoreMatchers.is(org.hamcrest.CoreMatchers.is) OpenSearchSingleNodeTestCase(org.opensearch.test.OpenSearchSingleNodeTestCase) ShardSearchContextId(org.opensearch.search.internal.ShardSearchContextId) IndexResponse(org.opensearch.action.index.IndexResponse) SearchStats(org.opensearch.index.search.stats.SearchStats) SearchContext(org.opensearch.search.internal.SearchContext) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) CoreMatchers.startsWith(org.hamcrest.CoreMatchers.startsWith) Strings(org.opensearch.common.Strings) Collections.singletonList(java.util.Collections.singletonList) CoreMatchers.notNullValue(org.hamcrest.CoreMatchers.notNullValue) ScriptType(org.opensearch.script.ScriptType) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) WriteRequest(org.opensearch.action.support.WriteRequest) OpenSearchAssertions.assertHitCount(org.opensearch.test.hamcrest.OpenSearchAssertions.assertHitCount) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IntArrayList(com.carrotsearch.hppc.IntArrayList) Locale(java.util.Locale) AliasFilter(org.opensearch.search.internal.AliasFilter) Map(java.util.Map) OpenSearchAssertions.assertSearchHits(org.opensearch.test.hamcrest.OpenSearchAssertions.assertSearchHits) ActionListener(org.opensearch.action.ActionListener) MockScriptEngine(org.opensearch.script.MockScriptEngine) IndexModule(org.opensearch.index.IndexModule) ValueType(org.opensearch.search.aggregations.support.ValueType) TimeValue(org.opensearch.common.unit.TimeValue) DELETED(org.opensearch.indices.cluster.IndicesClusterStateService.AllocatedIndices.IndexRemovalReason.DELETED) Index(org.opensearch.index.Index) DirectoryReader(org.apache.lucene.index.DirectoryReader) Script(org.opensearch.script.Script) Collection(java.util.Collection) IndicesService(org.opensearch.indices.IndicesService) GlobalAggregationBuilder(org.opensearch.search.aggregations.bucket.global.GlobalAggregationBuilder) Settings(org.opensearch.common.settings.Settings) RestStatus(org.opensearch.rest.RestStatus) MatchNoneQueryBuilder(org.opensearch.index.query.MatchNoneQueryBuilder) OriginalIndices(org.opensearch.action.OriginalIndices) Engine(org.opensearch.index.engine.Engine) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) SuggestBuilder(org.opensearch.search.suggest.SuggestBuilder) QueryBuilder(org.opensearch.index.query.QueryBuilder) IMMEDIATE(org.opensearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) LeafReader(org.apache.lucene.index.LeafReader) IndexSettings(org.opensearch.index.IndexSettings) QueryShardContext(org.opensearch.index.query.QueryShardContext) MockScriptPlugin(org.opensearch.script.MockScriptPlugin) AbstractQueryBuilder(org.opensearch.index.query.AbstractQueryBuilder) InternalAggregation(org.opensearch.search.aggregations.InternalAggregation) MultiBucketConsumerService(org.opensearch.search.aggregations.MultiBucketConsumerService) ShardFetchRequest(org.opensearch.search.fetch.ShardFetchRequest) ShardSearchRequest(org.opensearch.search.internal.ShardSearchRequest) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) ThreadPool(org.opensearch.threadpool.ThreadPool) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) StreamOutput(org.opensearch.common.io.stream.StreamOutput) InternalOrPrivateSettingsPlugin(org.opensearch.indices.settings.InternalOrPrivateSettingsPlugin) IndicesOptions(org.opensearch.action.support.IndicesOptions) QuerySearchResult(org.opensearch.search.query.QuerySearchResult) Function(java.util.function.Function) ArrayList(java.util.ArrayList) SearchShardTask(org.opensearch.action.search.SearchShardTask) IndexShard(org.opensearch.index.shard.IndexShard) FilterDirectoryReader(org.apache.lucene.index.FilterDirectoryReader) ReaderContext(org.opensearch.search.internal.ReaderContext) SearchRequest(org.opensearch.action.search.SearchRequest) SearchResponse(org.opensearch.action.search.SearchResponse) UUIDs(org.opensearch.common.UUIDs) LinkedList(java.util.LinkedList) Before(org.junit.Before) StreamInput(org.opensearch.common.io.stream.StreamInput) OpenSearchAssertions.assertAcked(org.opensearch.test.hamcrest.OpenSearchAssertions.assertAcked) Semaphore(java.util.concurrent.Semaphore) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) SearchPlugin(org.opensearch.plugins.SearchPlugin) SearchType(org.opensearch.action.search.SearchType) TermQueryBuilder(org.opensearch.index.query.TermQueryBuilder) IOException(java.io.IOException) IndexService(org.opensearch.index.IndexService) SearchOperationListener(org.opensearch.index.shard.SearchOperationListener) Plugin(org.opensearch.plugins.Plugin) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) ShardId(org.opensearch.index.shard.ShardId) ExecutionException(java.util.concurrent.ExecutionException) AggregationBuilders(org.opensearch.search.aggregations.AggregationBuilders) QueryRewriteContext(org.opensearch.index.query.QueryRewriteContext) TermsAggregationBuilder(org.opensearch.search.aggregations.bucket.terms.TermsAggregationBuilder) ClearScrollRequest(org.opensearch.action.search.ClearScrollRequest) SearchPhaseExecutionException(org.opensearch.action.search.SearchPhaseExecutionException) MatchAllQueryBuilder(org.opensearch.index.query.MatchAllQueryBuilder) FetchSearchResult(org.opensearch.search.fetch.FetchSearchResult) Collections(java.util.Collections) ShardSearchRequest(org.opensearch.search.internal.ShardSearchRequest) SearchRequest(org.opensearch.action.search.SearchRequest) AliasFilter(org.opensearch.search.internal.AliasFilter) WriteRequest(org.opensearch.action.support.WriteRequest) ShardFetchRequest(org.opensearch.search.fetch.ShardFetchRequest) ShardSearchRequest(org.opensearch.search.internal.ShardSearchRequest) SearchRequest(org.opensearch.action.search.SearchRequest) ClearScrollRequest(org.opensearch.action.search.ClearScrollRequest) ShardSearchRequest(org.opensearch.search.internal.ShardSearchRequest) Index(org.opensearch.index.Index) InternalOrPrivateSettingsPlugin(org.opensearch.indices.settings.InternalOrPrivateSettingsPlugin) SearchResponse(org.opensearch.action.search.SearchResponse)

Example 2 with IMMEDIATE

use of org.opensearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE in project OpenSearch by opensearch-project.

the class UnsafeBootstrapAndDetachCommandIT method testAllClusterManagerEligibleNodesFailedDanglingIndexImport.

public void testAllClusterManagerEligibleNodesFailedDanglingIndexImport() throws Exception {
    internalCluster().setBootstrapClusterManagerNodeIndex(0);
    Settings settings = Settings.builder().put(AUTO_IMPORT_DANGLING_INDICES_SETTING.getKey(), true).build();
    logger.info("--> start mixed data and cluster-manager-eligible node and bootstrap cluster");
    // node ordinal 0
    String clusterManagerNode = internalCluster().startNode(settings);
    logger.info("--> start data-only node and ensure 2 nodes stable cluster");
    // node ordinal 1
    String dataNode = internalCluster().startDataOnlyNode(settings);
    ensureStableCluster(2);
    logger.info("--> index 1 doc and ensure index is green");
    client().prepareIndex("test").setId("1").setSource("field1", "value1").setRefreshPolicy(IMMEDIATE).get();
    ensureGreen("test");
    assertBusy(() -> internalCluster().getInstances(IndicesService.class).forEach(indicesService -> assertTrue(indicesService.allPendingDanglingIndicesWritten())));
    logger.info("--> verify 1 doc in the index");
    assertHitCount(client().prepareSearch().setQuery(matchAllQuery()).get(), 1L);
    assertThat(client().prepareGet("test", "1").execute().actionGet().isExists(), equalTo(true));
    logger.info("--> stop data-only node and detach it from the old cluster");
    Settings dataNodeDataPathSettings = Settings.builder().put(internalCluster().dataPathSettings(dataNode), true).put(AUTO_IMPORT_DANGLING_INDICES_SETTING.getKey(), true).build();
    assertBusy(() -> internalCluster().getInstance(GatewayMetaState.class, dataNode).allPendingAsyncStatesWritten());
    internalCluster().stopRandomNode(InternalTestCluster.nameFilter(dataNode));
    final Environment environment = TestEnvironment.newEnvironment(Settings.builder().put(internalCluster().getDefaultSettings()).put(dataNodeDataPathSettings).put(AUTO_IMPORT_DANGLING_INDICES_SETTING.getKey(), true).build());
    detachCluster(environment, false);
    logger.info("--> stop cluster-manager-eligible node, clear its data and start it again - new cluster should form");
    internalCluster().restartNode(clusterManagerNode, new InternalTestCluster.RestartCallback() {

        @Override
        public boolean clearData(String nodeName) {
            return true;
        }
    });
    logger.info("--> start data-only only node and ensure 2 nodes stable cluster");
    internalCluster().startDataOnlyNode(dataNodeDataPathSettings);
    ensureStableCluster(2);
    logger.info("--> verify that the dangling index exists and has green status");
    assertBusy(() -> {
        assertThat(client().admin().indices().prepareExists("test").execute().actionGet().isExists(), equalTo(true));
    });
    ensureGreen("test");
    logger.info("--> verify the doc is there");
    assertThat(client().prepareGet("test", "1").execute().actionGet().isExists(), equalTo(true));
}
Also used : TestEnvironment(org.opensearch.env.TestEnvironment) MockTerminal(org.opensearch.cli.MockTerminal) Metadata(org.opensearch.cluster.metadata.Metadata) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) NodeRoles.nonMasterNode(org.opensearch.test.NodeRoles.nonMasterNode) ClusterUpdateSettingsRequest(org.opensearch.action.admin.cluster.settings.ClusterUpdateSettingsRequest) OpenSearchException(org.opensearch.OpenSearchException) InternalTestCluster(org.opensearch.test.InternalTestCluster) ArrayList(java.util.ArrayList) PersistedClusterStateService(org.opensearch.gateway.PersistedClusterStateService) ClusterState(org.opensearch.cluster.ClusterState) OpenSearchAssertions.assertHitCount(org.opensearch.test.hamcrest.OpenSearchAssertions.assertHitCount) QueryBuilders.matchAllQuery(org.opensearch.index.query.QueryBuilders.matchAllQuery) Locale(java.util.Locale) AUTO_IMPORT_DANGLING_INDICES_SETTING(org.opensearch.gateway.DanglingIndicesState.AUTO_IMPORT_DANGLING_INDICES_SETTING) OptionSet(joptsimple.OptionSet) Environment(org.opensearch.env.Environment) NodeEnvironment(org.opensearch.env.NodeEnvironment) OpenSearchAssertions.assertAcked(org.opensearch.test.hamcrest.OpenSearchAssertions.assertAcked) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) IndicesService(org.opensearch.indices.IndicesService) Settings(org.opensearch.common.settings.Settings) IOException(java.io.IOException) DiscoverySettings(org.opensearch.node.Node.DiscoverySettings) Objects(java.util.Objects) GatewayMetaState(org.opensearch.gateway.GatewayMetaState) List(java.util.List) IMMEDIATE(org.opensearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE) Matchers.equalTo(org.hamcrest.Matchers.equalTo) OpenSearchIntegTestCase(org.opensearch.test.OpenSearchIntegTestCase) Matchers.containsString(org.hamcrest.Matchers.containsString) INDICES_RECOVERY_MAX_BYTES_PER_SEC_SETTING(org.opensearch.indices.recovery.RecoverySettings.INDICES_RECOVERY_MAX_BYTES_PER_SEC_SETTING) TestEnvironment(org.opensearch.env.TestEnvironment) Environment(org.opensearch.env.Environment) NodeEnvironment(org.opensearch.env.NodeEnvironment) InternalTestCluster(org.opensearch.test.InternalTestCluster) Matchers.containsString(org.hamcrest.Matchers.containsString) Settings(org.opensearch.common.settings.Settings) DiscoverySettings(org.opensearch.node.Node.DiscoverySettings)

Example 3 with IMMEDIATE

use of org.opensearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE in project OpenSearch by opensearch-project.

the class IndexShardIT method testShardHasMemoryBufferOnTranslogRecover.

public void testShardHasMemoryBufferOnTranslogRecover() throws Throwable {
    createIndex("test");
    ensureGreen();
    IndicesService indicesService = getInstanceFromNode(IndicesService.class);
    IndexService indexService = indicesService.indexService(resolveIndex("test"));
    IndexShard shard = indexService.getShardOrNull(0);
    client().prepareIndex("test").setId("0").setSource("{\"foo\" : \"bar\"}", XContentType.JSON).get();
    client().prepareDelete("test", "0").get();
    client().prepareIndex("test").setId("1").setSource("{\"foo\" : \"bar\"}", XContentType.JSON).setRefreshPolicy(IMMEDIATE).get();
    CheckedFunction<DirectoryReader, DirectoryReader, IOException> wrapper = directoryReader -> directoryReader;
    shard.close("simon says", false);
    AtomicReference<IndexShard> shardRef = new AtomicReference<>();
    List<Exception> failures = new ArrayList<>();
    IndexingOperationListener listener = new IndexingOperationListener() {

        @Override
        public void postIndex(ShardId shardId, Engine.Index index, Engine.IndexResult result) {
            try {
                assertNotNull(shardRef.get());
                // this is all IMC needs to do - check current memory and refresh
                assertTrue(shardRef.get().getIndexBufferRAMBytesUsed() > 0);
                shardRef.get().refresh("test");
            } catch (Exception e) {
                failures.add(e);
                throw e;
            }
        }

        @Override
        public void postDelete(ShardId shardId, Engine.Delete delete, Engine.DeleteResult result) {
            try {
                assertNotNull(shardRef.get());
                // this is all IMC needs to do - check current memory and refresh
                assertTrue(shardRef.get().getIndexBufferRAMBytesUsed() > 0);
                shardRef.get().refresh("test");
            } catch (Exception e) {
                failures.add(e);
                throw e;
            }
        }
    };
    final IndexShard newShard = newIndexShard(indexService, shard, wrapper, getInstanceFromNode(CircuitBreakerService.class), listener);
    shardRef.set(newShard);
    recoverShard(newShard);
    try {
        ExceptionsHelper.rethrowAndSuppress(failures);
    } finally {
        newShard.close("just do it", randomBoolean());
    }
}
Also used : SequenceNumbers(org.opensearch.index.seqno.SequenceNumbers) Arrays(java.util.Arrays) OpenSearchSingleNodeTestCase(org.opensearch.test.OpenSearchSingleNodeTestCase) CheckedFunction(org.opensearch.common.CheckedFunction) Version(org.opensearch.Version) Strings(org.opensearch.common.Strings) DirectoryStream(java.nio.file.DirectoryStream) NONE(org.opensearch.action.support.WriteRequest.RefreshPolicy.NONE) RecoveryState(org.opensearch.indices.recovery.RecoveryState) ActionListener(org.opensearch.action.ActionListener) Path(java.nio.file.Path) NodeEnvironment(org.opensearch.env.NodeEnvironment) TimeValue(org.opensearch.common.unit.TimeValue) OpenSearchAssertions.assertNoFailures(org.opensearch.test.hamcrest.OpenSearchAssertions.assertNoFailures) Index(org.opensearch.index.Index) Matchers.allOf(org.hamcrest.Matchers.allOf) ExceptionsHelper(org.opensearch.ExceptionsHelper) Settings(org.opensearch.common.settings.Settings) Engine(org.opensearch.index.engine.Engine) UncheckedIOException(java.io.UncheckedIOException) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) CountDownLatch(java.util.concurrent.CountDownLatch) VersionType(org.opensearch.index.VersionType) Stream(java.util.stream.Stream) BytesArray(org.opensearch.common.bytes.BytesArray) CheckedRunnable(org.opensearch.common.CheckedRunnable) XContentType(org.opensearch.common.xcontent.XContentType) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) ShardLock(org.opensearch.env.ShardLock) TestShardRouting.newShardRouting(org.opensearch.cluster.routing.TestShardRouting.newShardRouting) LockObtainFailedException(org.apache.lucene.store.LockObtainFailedException) ClusterInfoService(org.opensearch.cluster.ClusterInfoService) ArrayList(java.util.ArrayList) RecoverySource(org.opensearch.cluster.routing.RecoverySource) ClusterState(org.opensearch.cluster.ClusterState) ShardRoutingState(org.opensearch.cluster.routing.ShardRoutingState) SearchRequest(org.opensearch.action.search.SearchRequest) CommitStats(org.opensearch.index.engine.CommitStats) Environment(org.opensearch.env.Environment) Versions(org.opensearch.common.lucene.uid.Versions) Files(java.nio.file.Files) TestTranslog(org.opensearch.index.translog.TestTranslog) FlushStats(org.opensearch.index.flush.FlushStats) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) IndexService(org.opensearch.index.IndexService) Plugin(org.opensearch.plugins.Plugin) ClusterService(org.opensearch.cluster.service.ClusterService) SETTING_NUMBER_OF_SHARDS(org.opensearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_SHARDS) RetentionLeaseSyncer(org.opensearch.index.seqno.RetentionLeaseSyncer) Assert(org.junit.Assert) RandomizedTest.randomAsciiLettersOfLength(com.carrotsearch.randomizedtesting.RandomizedTest.randomAsciiLettersOfLength) IndexShardTestCase.getTranslog(org.opensearch.index.shard.IndexShardTestCase.getTranslog) Matchers.either(org.hamcrest.Matchers.either) ByteSizeUnit(org.opensearch.common.unit.ByteSizeUnit) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) MapperService(org.opensearch.index.mapper.MapperService) OpenSearchAssertions.assertHitCount(org.opensearch.test.hamcrest.OpenSearchAssertions.assertHitCount) Locale(java.util.Locale) DummyShardLock(org.opensearch.test.DummyShardLock) UnassignedInfo(org.opensearch.cluster.routing.UnassignedInfo) SegmentReplicationCheckpointPublisher(org.opensearch.indices.replication.checkpoint.SegmentReplicationCheckpointPublisher) SETTING_NUMBER_OF_REPLICAS(org.opensearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_REPLICAS) CyclicBarrier(java.util.concurrent.CyclicBarrier) Predicate(java.util.function.Predicate) Matchers.lessThanOrEqualTo(org.hamcrest.Matchers.lessThanOrEqualTo) DirectoryReader(org.apache.lucene.index.DirectoryReader) Collection(java.util.Collection) IndicesService(org.opensearch.indices.IndicesService) InternalClusterInfoService(org.opensearch.cluster.InternalClusterInfoService) List(java.util.List) IMMEDIATE(org.opensearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) Matchers.equalTo(org.hamcrest.Matchers.equalTo) IndexSettings(org.opensearch.index.IndexSettings) TranslogStats(org.opensearch.index.translog.TranslogStats) IndexSettingsModule(org.opensearch.test.IndexSettingsModule) NoOpEngine(org.opensearch.index.engine.NoOpEngine) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ByteSizeValue(org.opensearch.common.unit.ByteSizeValue) IndicesOptions(org.opensearch.action.support.IndicesOptions) AtomicReference(java.util.concurrent.atomic.AtomicReference) SourceToParse(org.opensearch.index.mapper.SourceToParse) InternalSettingsPlugin(org.opensearch.test.InternalSettingsPlugin) IndexShardTestCase.recoverFromStore(org.opensearch.index.shard.IndexShardTestCase.recoverFromStore) Translog(org.opensearch.index.translog.Translog) SearchResponse(org.opensearch.action.search.SearchResponse) UUIDs(org.opensearch.common.UUIDs) OpenSearchAssertions.assertAcked(org.opensearch.test.hamcrest.OpenSearchAssertions.assertAcked) Collections.emptyMap(java.util.Collections.emptyMap) Collections.emptySet(java.util.Collections.emptySet) ActiveShardCount(org.opensearch.action.support.ActiveShardCount) ShardRouting(org.opensearch.cluster.routing.ShardRouting) IOUtils(org.opensearch.core.internal.io.IOUtils) TimeUnit(java.util.concurrent.TimeUnit) CircuitBreakerService(org.opensearch.indices.breaker.CircuitBreakerService) IndexRequest(org.opensearch.action.index.IndexRequest) Comparator(java.util.Comparator) Collections(java.util.Collections) IndexService(org.opensearch.index.IndexService) DirectoryReader(org.apache.lucene.index.DirectoryReader) ArrayList(java.util.ArrayList) IndicesService(org.opensearch.indices.IndicesService) AtomicReference(java.util.concurrent.atomic.AtomicReference) Index(org.opensearch.index.Index) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) UncheckedIOException(java.io.UncheckedIOException) LockObtainFailedException(org.apache.lucene.store.LockObtainFailedException) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) CircuitBreakerService(org.opensearch.indices.breaker.CircuitBreakerService)

Example 4 with IMMEDIATE

use of org.opensearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE in project OpenSearch by opensearch-project.

the class GatewayIndexStateIT method testRecoverMissingAnalyzer.

/**
 * This test really tests worst case scenario where we have a missing analyzer setting.
 * In that case we now have the ability to check the index on local recovery from disk
 * if it is sane and if we can successfully create an IndexService.
 * This also includes plugins etc.
 */
public void testRecoverMissingAnalyzer() throws Exception {
    logger.info("--> starting one node");
    internalCluster().startNode();
    prepareCreate("test").setSettings(Settings.builder().put("index.analysis.analyzer.test.tokenizer", "standard").put("index.number_of_shards", "1")).setMapping("{\n" + "    \"properties\": {\n" + "      \"field1\": {\n" + "        \"type\": \"text\",\n" + "        \"analyzer\": \"test\"\n" + "      }\n" + "    }\n" + "  }").get();
    logger.info("--> indexing a simple document");
    client().prepareIndex("test").setId("1").setSource("field1", "value one").setRefreshPolicy(IMMEDIATE).get();
    logger.info("--> waiting for green status");
    if (usually()) {
        ensureYellow();
    } else {
        internalCluster().startNode();
        client().admin().cluster().health(Requests.clusterHealthRequest().waitForGreenStatus().waitForEvents(Priority.LANGUID).waitForNoRelocatingShards(true).waitForNodes("2")).actionGet();
    }
    ClusterState state = client().admin().cluster().prepareState().get().getState();
    final IndexMetadata metadata = state.getMetadata().index("test");
    final IndexMetadata.Builder brokenMeta = IndexMetadata.builder(metadata).settings(metadata.getSettings().filter((s) -> "index.analysis.analyzer.test.tokenizer".equals(s) == false));
    restartNodesOnBrokenClusterState(ClusterState.builder(state).metadata(Metadata.builder(state.getMetadata()).put(brokenMeta)));
    // check that the cluster does not keep reallocating shards
    assertBusy(() -> {
        final RoutingTable routingTable = client().admin().cluster().prepareState().get().getState().routingTable();
        final IndexRoutingTable indexRoutingTable = routingTable.index("test");
        assertNotNull(indexRoutingTable);
        for (IndexShardRoutingTable shardRoutingTable : indexRoutingTable) {
            assertTrue(shardRoutingTable.primaryShard().unassigned());
            assertEquals(UnassignedInfo.AllocationStatus.DECIDERS_NO, shardRoutingTable.primaryShard().unassignedInfo().getLastAllocationStatus());
            assertThat(shardRoutingTable.primaryShard().unassignedInfo().getNumFailedAllocations(), greaterThan(0));
        }
    }, 60, TimeUnit.SECONDS);
    client().admin().indices().prepareClose("test").get();
    // try to open it with the broken setting - fail again!
    OpenSearchException ex = expectThrows(OpenSearchException.class, () -> client().admin().indices().prepareOpen("test").get());
    assertEquals(ex.getMessage(), "Failed to verify index " + metadata.getIndex());
    assertNotNull(ex.getCause());
    assertEquals(MapperParsingException.class, ex.getCause().getClass());
    assertThat(ex.getCause().getMessage(), containsString("analyzer [test] has not been configured in mappings"));
}
Also used : IndexGraveyard(org.opensearch.cluster.metadata.IndexGraveyard) Metadata(org.opensearch.cluster.metadata.Metadata) ClusterStateResponse(org.opensearch.action.admin.cluster.state.ClusterStateResponse) ClusterScope(org.opensearch.test.OpenSearchIntegTestCase.ClusterScope) Version(org.opensearch.Version) OpenSearchException(org.opensearch.OpenSearchException) OpenSearchAssertions.assertHitCount(org.opensearch.test.hamcrest.OpenSearchAssertions.assertHitCount) QueryBuilders.matchAllQuery(org.opensearch.index.query.QueryBuilders.matchAllQuery) Map(java.util.Map) XContentFactory(org.opensearch.common.xcontent.XContentFactory) GetResponse(org.opensearch.action.get.GetResponse) UnassignedInfo(org.opensearch.cluster.routing.UnassignedInfo) Path(java.nio.file.Path) IndexShardRoutingTable(org.opensearch.cluster.routing.IndexShardRoutingTable) NodeEnvironment(org.opensearch.env.NodeEnvironment) Client(org.opensearch.client.Client) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) Settings(org.opensearch.common.settings.Settings) Scope(org.opensearch.test.OpenSearchIntegTestCase.Scope) Collectors(java.util.stream.Collectors) List(java.util.List) Logger(org.apache.logging.log4j.Logger) ClusterHealthResponse(org.opensearch.action.admin.cluster.health.ClusterHealthResponse) Stream(java.util.stream.Stream) IMMEDIATE(org.opensearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE) Matchers.equalTo(org.hamcrest.Matchers.equalTo) NodeRoles.nonDataNode(org.opensearch.test.NodeRoles.nonDataNode) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) OpenSearchIntegTestCase(org.opensearch.test.OpenSearchIntegTestCase) Matchers.containsString(org.hamcrest.Matchers.containsString) MappingMetadata(org.opensearch.cluster.metadata.MappingMetadata) RestartCallback(org.opensearch.test.InternalTestCluster.RestartCallback) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) MapperParsingException(org.opensearch.index.mapper.MapperParsingException) Priority(org.opensearch.common.Priority) Function(java.util.function.Function) IndexRoutingTable(org.opensearch.cluster.routing.IndexRoutingTable) Requests(org.opensearch.client.Requests) ClusterState(org.opensearch.cluster.ClusterState) IndexClosedException(org.opensearch.indices.IndexClosedException) ShardRoutingState(org.opensearch.cluster.routing.ShardRoutingState) OpenSearchAssertions.assertAcked(org.opensearch.test.hamcrest.OpenSearchAssertions.assertAcked) Matchers.empty(org.hamcrest.Matchers.empty) ShardLimitValidator(org.opensearch.indices.ShardLimitValidator) IOException(java.io.IOException) ActiveShardCount(org.opensearch.action.support.ActiveShardCount) TimeUnit(java.util.concurrent.TimeUnit) ClusterService(org.opensearch.cluster.service.ClusterService) RoutingTable(org.opensearch.cluster.routing.RoutingTable) LogManager(org.apache.logging.log4j.LogManager) ClusterState(org.opensearch.cluster.ClusterState) IndexRoutingTable(org.opensearch.cluster.routing.IndexRoutingTable) IndexShardRoutingTable(org.opensearch.cluster.routing.IndexShardRoutingTable) IndexShardRoutingTable(org.opensearch.cluster.routing.IndexShardRoutingTable) IndexRoutingTable(org.opensearch.cluster.routing.IndexRoutingTable) RoutingTable(org.opensearch.cluster.routing.RoutingTable) OpenSearchException(org.opensearch.OpenSearchException) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata)

Example 5 with IMMEDIATE

use of org.opensearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE in project OpenSearch by opensearch-project.

the class UnsafeBootstrapAndDetachCommandIT method testAllMasterEligibleNodesFailedDanglingIndexImport.

public void testAllMasterEligibleNodesFailedDanglingIndexImport() throws Exception {
    internalCluster().setBootstrapMasterNodeIndex(0);
    Settings settings = Settings.builder().put(AUTO_IMPORT_DANGLING_INDICES_SETTING.getKey(), true).build();
    logger.info("--> start mixed data and master-eligible node and bootstrap cluster");
    // node ordinal 0
    String masterNode = internalCluster().startNode(settings);
    logger.info("--> start data-only node and ensure 2 nodes stable cluster");
    // node ordinal 1
    String dataNode = internalCluster().startDataOnlyNode(settings);
    ensureStableCluster(2);
    logger.info("--> index 1 doc and ensure index is green");
    client().prepareIndex("test").setId("1").setSource("field1", "value1").setRefreshPolicy(IMMEDIATE).get();
    ensureGreen("test");
    assertBusy(() -> internalCluster().getInstances(IndicesService.class).forEach(indicesService -> assertTrue(indicesService.allPendingDanglingIndicesWritten())));
    logger.info("--> verify 1 doc in the index");
    assertHitCount(client().prepareSearch().setQuery(matchAllQuery()).get(), 1L);
    assertThat(client().prepareGet("test", "1").execute().actionGet().isExists(), equalTo(true));
    logger.info("--> stop data-only node and detach it from the old cluster");
    Settings dataNodeDataPathSettings = Settings.builder().put(internalCluster().dataPathSettings(dataNode), true).put(AUTO_IMPORT_DANGLING_INDICES_SETTING.getKey(), true).build();
    assertBusy(() -> internalCluster().getInstance(GatewayMetaState.class, dataNode).allPendingAsyncStatesWritten());
    internalCluster().stopRandomNode(InternalTestCluster.nameFilter(dataNode));
    final Environment environment = TestEnvironment.newEnvironment(Settings.builder().put(internalCluster().getDefaultSettings()).put(dataNodeDataPathSettings).put(AUTO_IMPORT_DANGLING_INDICES_SETTING.getKey(), true).build());
    detachCluster(environment, false);
    logger.info("--> stop master-eligible node, clear its data and start it again - new cluster should form");
    internalCluster().restartNode(masterNode, new InternalTestCluster.RestartCallback() {

        @Override
        public boolean clearData(String nodeName) {
            return true;
        }
    });
    logger.info("--> start data-only only node and ensure 2 nodes stable cluster");
    internalCluster().startDataOnlyNode(dataNodeDataPathSettings);
    ensureStableCluster(2);
    logger.info("--> verify that the dangling index exists and has green status");
    assertBusy(() -> {
        assertThat(client().admin().indices().prepareExists("test").execute().actionGet().isExists(), equalTo(true));
    });
    ensureGreen("test");
    logger.info("--> verify the doc is there");
    assertThat(client().prepareGet("test", "1").execute().actionGet().isExists(), equalTo(true));
}
Also used : TestEnvironment(org.opensearch.env.TestEnvironment) MockTerminal(org.opensearch.cli.MockTerminal) Metadata(org.opensearch.cluster.metadata.Metadata) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) NodeRoles.nonMasterNode(org.opensearch.test.NodeRoles.nonMasterNode) ClusterUpdateSettingsRequest(org.opensearch.action.admin.cluster.settings.ClusterUpdateSettingsRequest) OpenSearchException(org.opensearch.OpenSearchException) InternalTestCluster(org.opensearch.test.InternalTestCluster) ArrayList(java.util.ArrayList) PersistedClusterStateService(org.opensearch.gateway.PersistedClusterStateService) ClusterState(org.opensearch.cluster.ClusterState) OpenSearchAssertions.assertHitCount(org.opensearch.test.hamcrest.OpenSearchAssertions.assertHitCount) QueryBuilders.matchAllQuery(org.opensearch.index.query.QueryBuilders.matchAllQuery) Locale(java.util.Locale) AUTO_IMPORT_DANGLING_INDICES_SETTING(org.opensearch.gateway.DanglingIndicesState.AUTO_IMPORT_DANGLING_INDICES_SETTING) OptionSet(joptsimple.OptionSet) Environment(org.opensearch.env.Environment) NodeEnvironment(org.opensearch.env.NodeEnvironment) OpenSearchAssertions.assertAcked(org.opensearch.test.hamcrest.OpenSearchAssertions.assertAcked) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) IndicesService(org.opensearch.indices.IndicesService) Settings(org.opensearch.common.settings.Settings) IOException(java.io.IOException) DiscoverySettings(org.opensearch.node.Node.DiscoverySettings) Objects(java.util.Objects) GatewayMetaState(org.opensearch.gateway.GatewayMetaState) List(java.util.List) IMMEDIATE(org.opensearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE) Matchers.equalTo(org.hamcrest.Matchers.equalTo) OpenSearchIntegTestCase(org.opensearch.test.OpenSearchIntegTestCase) Matchers.containsString(org.hamcrest.Matchers.containsString) INDICES_RECOVERY_MAX_BYTES_PER_SEC_SETTING(org.opensearch.indices.recovery.RecoverySettings.INDICES_RECOVERY_MAX_BYTES_PER_SEC_SETTING) TestEnvironment(org.opensearch.env.TestEnvironment) Environment(org.opensearch.env.Environment) NodeEnvironment(org.opensearch.env.NodeEnvironment) InternalTestCluster(org.opensearch.test.InternalTestCluster) Matchers.containsString(org.hamcrest.Matchers.containsString) Settings(org.opensearch.common.settings.Settings) DiscoverySettings(org.opensearch.node.Node.DiscoverySettings)

Aggregations

IOException (java.io.IOException)5 List (java.util.List)5 IMMEDIATE (org.opensearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE)5 ArrayList (java.util.ArrayList)4 Locale (java.util.Locale)4 Matchers.equalTo (org.hamcrest.Matchers.equalTo)4 ClusterState (org.opensearch.cluster.ClusterState)4 IndexMetadata (org.opensearch.cluster.metadata.IndexMetadata)4 Settings (org.opensearch.common.settings.Settings)4 NodeEnvironment (org.opensearch.env.NodeEnvironment)4 OpenSearchAssertions.assertAcked (org.opensearch.test.hamcrest.OpenSearchAssertions.assertAcked)4 OpenSearchAssertions.assertHitCount (org.opensearch.test.hamcrest.OpenSearchAssertions.assertHitCount)4 Matchers.containsString (org.hamcrest.Matchers.containsString)3 Matchers.notNullValue (org.hamcrest.Matchers.notNullValue)3 OpenSearchException (org.opensearch.OpenSearchException)3 Metadata (org.opensearch.cluster.metadata.Metadata)3 Environment (org.opensearch.env.Environment)3 QueryBuilders.matchAllQuery (org.opensearch.index.query.QueryBuilders.matchAllQuery)3 IndicesService (org.opensearch.indices.IndicesService)3 OpenSearchIntegTestCase (org.opensearch.test.OpenSearchIntegTestCase)3