Search in sources :

Example 51 with IndexSettings

use of org.opensearch.index.IndexSettings in project OpenSearch by opensearch-project.

the class SimilarityServiceTests method testOverrideBuiltInSimilarity.

// Tests #16594
public void testOverrideBuiltInSimilarity() {
    Settings settings = Settings.builder().put("index.similarity.BM25.type", "classic").build();
    IndexSettings indexSettings = IndexSettingsModule.newIndexSettings("test", settings);
    try {
        new SimilarityService(indexSettings, null, Collections.emptyMap());
        fail("can't override bm25");
    } catch (IllegalArgumentException ex) {
        assertEquals(ex.getMessage(), "Cannot redefine built-in Similarity [BM25]");
    }
}
Also used : IndexSettings(org.opensearch.index.IndexSettings) Settings(org.opensearch.common.settings.Settings) IndexSettings(org.opensearch.index.IndexSettings)

Example 52 with IndexSettings

use of org.opensearch.index.IndexSettings in project OpenSearch by opensearch-project.

the class IndicesLifecycleListenerSingleNodeTests method testStartDeleteIndexEventCallback.

public void testStartDeleteIndexEventCallback() throws Throwable {
    IndicesService indicesService = getInstanceFromNode(IndicesService.class);
    assertAcked(client().admin().indices().prepareCreate("test").setSettings(Settings.builder().put(SETTING_NUMBER_OF_SHARDS, 1).put(SETTING_NUMBER_OF_REPLICAS, 0)));
    ensureGreen();
    Index idx = resolveIndex("test");
    IndexMetadata metadata = indicesService.indexService(idx).getMetadata();
    ShardRouting shardRouting = indicesService.indexService(idx).getShard(0).routingEntry();
    final AtomicInteger counter = new AtomicInteger(1);
    IndexEventListener countingListener = new IndexEventListener() {

        @Override
        public void beforeIndexCreated(Index index, Settings indexSettings) {
            assertEquals("test", index.getName());
            assertEquals(1, counter.get());
            counter.incrementAndGet();
        }

        @Override
        public void afterIndexCreated(IndexService indexService) {
            assertEquals("test", indexService.index().getName());
            assertEquals(2, counter.get());
            counter.incrementAndGet();
        }

        @Override
        public void beforeIndexShardCreated(ShardId shardId, Settings indexSettings) {
            assertEquals(3, counter.get());
            counter.incrementAndGet();
        }

        @Override
        public void afterIndexShardCreated(IndexShard indexShard) {
            assertEquals(4, counter.get());
            counter.incrementAndGet();
        }

        @Override
        public void afterIndexShardStarted(IndexShard indexShard) {
            assertEquals(5, counter.get());
            counter.incrementAndGet();
        }

        @Override
        public void beforeIndexRemoved(IndexService indexService, IndexRemovalReason reason) {
            assertEquals(DELETED, reason);
            assertEquals(6, counter.get());
            counter.incrementAndGet();
        }

        @Override
        public void beforeIndexShardDeleted(ShardId shardId, Settings indexSettings) {
            assertEquals(7, counter.get());
            counter.incrementAndGet();
        }

        @Override
        public void afterIndexShardDeleted(ShardId shardId, Settings indexSettings) {
            assertEquals(8, counter.get());
            counter.incrementAndGet();
        }

        @Override
        public void afterIndexRemoved(Index index, IndexSettings indexSettings, IndexRemovalReason reason) {
            assertEquals(DELETED, reason);
            assertEquals(9, counter.get());
            counter.incrementAndGet();
        }
    };
    indicesService.removeIndex(idx, DELETED, "simon says");
    try {
        IndexService index = indicesService.createIndex(metadata, Arrays.asList(countingListener), false);
        assertEquals(3, counter.get());
        idx = index.index();
        ShardRouting newRouting = shardRouting;
        String nodeId = newRouting.currentNodeId();
        UnassignedInfo unassignedInfo = new UnassignedInfo(UnassignedInfo.Reason.INDEX_CREATED, "boom");
        newRouting = newRouting.moveToUnassigned(unassignedInfo).updateUnassigned(unassignedInfo, RecoverySource.EmptyStoreRecoverySource.INSTANCE);
        newRouting = ShardRoutingHelper.initialize(newRouting, nodeId);
        IndexShard shard = index.createShard(newRouting, s -> {
        }, RetentionLeaseSyncer.EMPTY);
        IndexShardTestCase.updateRoutingEntry(shard, newRouting);
        assertEquals(5, counter.get());
        final DiscoveryNode localNode = new DiscoveryNode("foo", buildNewFakeTransportAddress(), emptyMap(), emptySet(), Version.CURRENT);
        shard.markAsRecovering("store", new RecoveryState(newRouting, localNode, null));
        IndexShardTestCase.recoverFromStore(shard);
        newRouting = ShardRoutingHelper.moveToStarted(newRouting);
        IndexShardTestCase.updateRoutingEntry(shard, newRouting);
        assertEquals(6, counter.get());
    } finally {
        indicesService.removeIndex(idx, DELETED, "simon says");
    }
    assertEquals(10, counter.get());
}
Also used : DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) IndexService(org.opensearch.index.IndexService) UnassignedInfo(org.opensearch.cluster.routing.UnassignedInfo) IndexShard(org.opensearch.index.shard.IndexShard) IndexSettings(org.opensearch.index.IndexSettings) Index(org.opensearch.index.Index) ShardId(org.opensearch.index.shard.ShardId) IndexEventListener(org.opensearch.index.shard.IndexEventListener) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IndexRemovalReason(org.opensearch.indices.cluster.IndicesClusterStateService.AllocatedIndices.IndexRemovalReason) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) ShardRouting(org.opensearch.cluster.routing.ShardRouting) RecoveryState(org.opensearch.indices.recovery.RecoveryState) Settings(org.opensearch.common.settings.Settings) IndexSettings(org.opensearch.index.IndexSettings)

Example 53 with IndexSettings

use of org.opensearch.index.IndexSettings in project OpenSearch by opensearch-project.

the class AnalysisModuleTests method testPluginPreConfiguredCharFilters.

/**
 * Tests that plugins can register pre-configured char filters that vary in behavior based on OpenSearch version, Lucene version,
 * and that do not vary based on version at all.
 */
public void testPluginPreConfiguredCharFilters() throws IOException {
    boolean noVersionSupportsMultiTerm = randomBoolean();
    boolean luceneVersionSupportsMultiTerm = randomBoolean();
    boolean opensearchVersionSupportsMultiTerm = randomBoolean();
    AnalysisRegistry registry = new AnalysisModule(TestEnvironment.newEnvironment(emptyNodeSettings), singletonList(new AnalysisPlugin() {

        @Override
        public List<PreConfiguredCharFilter> getPreConfiguredCharFilters() {
            return Arrays.asList(PreConfiguredCharFilter.singleton("no_version", noVersionSupportsMultiTerm, tokenStream -> new AppendCharFilter(tokenStream, "no_version")), PreConfiguredCharFilter.luceneVersion("lucene_version", luceneVersionSupportsMultiTerm, (tokenStream, luceneVersion) -> new AppendCharFilter(tokenStream, luceneVersion.toString())), PreConfiguredCharFilter.openSearchVersion("opensearch_version", opensearchVersionSupportsMultiTerm, (tokenStream, esVersion) -> new AppendCharFilter(tokenStream, esVersion.toString())));
        }

        @Override
        public Map<String, AnalysisProvider<TokenizerFactory>> getTokenizers() {
            // Need mock keyword tokenizer here, because alpha / beta versions are broken up by the dash.
            return singletonMap("keyword", (indexSettings, environment, name, settings) -> TokenizerFactory.newFactory(name, () -> new MockTokenizer(MockTokenizer.KEYWORD, false)));
        }
    })).getAnalysisRegistry();
    Version version = VersionUtils.randomVersion(random());
    IndexAnalyzers analyzers = getIndexAnalyzers(registry, Settings.builder().put("index.analysis.analyzer.no_version.tokenizer", "keyword").put("index.analysis.analyzer.no_version.char_filter", "no_version").put("index.analysis.analyzer.lucene_version.tokenizer", "keyword").put("index.analysis.analyzer.lucene_version.char_filter", "lucene_version").put("index.analysis.analyzer.opensearch_version.tokenizer", "keyword").put("index.analysis.analyzer.opensearch_version.char_filter", "opensearch_version").put(IndexMetadata.SETTING_VERSION_CREATED, version).build());
    assertTokenStreamContents(analyzers.get("no_version").tokenStream("", "test"), new String[] { "testno_version" });
    assertTokenStreamContents(analyzers.get("lucene_version").tokenStream("", "test"), new String[] { "test" + version.luceneVersion });
    assertTokenStreamContents(analyzers.get("opensearch_version").tokenStream("", "test"), new String[] { "test" + version });
    assertEquals("test" + (noVersionSupportsMultiTerm ? "no_version" : ""), analyzers.get("no_version").normalize("", "test").utf8ToString());
    assertEquals("test" + (luceneVersionSupportsMultiTerm ? version.luceneVersion.toString() : ""), analyzers.get("lucene_version").normalize("", "test").utf8ToString());
    assertEquals("test" + (opensearchVersionSupportsMultiTerm ? version.toString() : ""), analyzers.get("opensearch_version").normalize("", "test").utf8ToString());
}
Also used : Arrays(java.util.Arrays) Matchers.either(org.hamcrest.Matchers.either) Version(org.opensearch.Version) StopTokenFilterFactory(org.opensearch.index.analysis.StopTokenFilterFactory) Collections.singletonList(java.util.Collections.singletonList) AnalysisRegistry(org.opensearch.index.analysis.AnalysisRegistry) Directory(org.apache.lucene.store.Directory) Map(java.util.Map) PreConfiguredTokenizer(org.opensearch.index.analysis.PreConfiguredTokenizer) CustomAnalyzer(org.opensearch.index.analysis.CustomAnalyzer) Path(java.nio.file.Path) PreConfiguredTokenFilter(org.opensearch.index.analysis.PreConfiguredTokenFilter) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) Reader(java.io.Reader) StandardCharsets(java.nio.charset.StandardCharsets) UncheckedIOException(java.io.UncheckedIOException) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) List(java.util.List) MatcherAssert(org.hamcrest.MatcherAssert) Matchers.equalTo(org.hamcrest.Matchers.equalTo) IndexSettings(org.opensearch.index.IndexSettings) TokenFilter(org.apache.lucene.analysis.TokenFilter) BaseTokenStreamTestCase.assertTokenStreamContents(org.apache.lucene.analysis.BaseTokenStreamTestCase.assertTokenStreamContents) XContentType(org.opensearch.common.xcontent.XContentType) Dictionary(org.apache.lucene.analysis.hunspell.Dictionary) IndexAnalyzers(org.opensearch.index.analysis.IndexAnalyzers) MyFilterTokenFilterFactory(org.opensearch.index.analysis.MyFilterTokenFilterFactory) IndexSettingsModule(org.opensearch.test.IndexSettingsModule) TestEnvironment(org.opensearch.env.TestEnvironment) TokenizerFactory(org.opensearch.index.analysis.TokenizerFactory) Tokenizer(org.apache.lucene.analysis.Tokenizer) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) MockTokenizer(org.apache.lucene.analysis.MockTokenizer) TokenFilterFactory(org.opensearch.index.analysis.TokenFilterFactory) CharFilter(org.apache.lucene.analysis.CharFilter) LegacyESVersion(org.opensearch.LegacyESVersion) Analysis(org.opensearch.index.analysis.Analysis) VersionUtils(org.opensearch.test.VersionUtils) Streams(org.opensearch.common.io.Streams) CharFilterFactory(org.opensearch.index.analysis.CharFilterFactory) StandardTokenizerFactory(org.opensearch.index.analysis.StandardTokenizerFactory) AnalysisProvider(org.opensearch.indices.analysis.AnalysisModule.AnalysisProvider) Collections.singletonMap(java.util.Collections.singletonMap) CharTermAttribute(org.apache.lucene.analysis.tokenattributes.CharTermAttribute) Environment(org.opensearch.env.Environment) TokenStream(org.apache.lucene.analysis.TokenStream) Files(java.nio.file.Files) BufferedWriter(java.io.BufferedWriter) Analyzer(org.apache.lucene.analysis.Analyzer) IOException(java.io.IOException) PreConfiguredCharFilter(org.opensearch.index.analysis.PreConfiguredCharFilter) AnalysisPlugin(org.opensearch.plugins.AnalysisPlugin) StringReader(java.io.StringReader) NIOFSDirectory(org.apache.lucene.store.NIOFSDirectory) InputStream(java.io.InputStream) TokenizerFactory(org.opensearch.index.analysis.TokenizerFactory) StandardTokenizerFactory(org.opensearch.index.analysis.StandardTokenizerFactory) MockTokenizer(org.apache.lucene.analysis.MockTokenizer) AnalysisRegistry(org.opensearch.index.analysis.AnalysisRegistry) Version(org.opensearch.Version) LegacyESVersion(org.opensearch.LegacyESVersion) IndexAnalyzers(org.opensearch.index.analysis.IndexAnalyzers) Collections.singletonList(java.util.Collections.singletonList) List(java.util.List) Map(java.util.Map) Collections.singletonMap(java.util.Collections.singletonMap) AnalysisPlugin(org.opensearch.plugins.AnalysisPlugin)

Example 54 with IndexSettings

use of org.opensearch.index.IndexSettings in project OpenSearch by opensearch-project.

the class IndicesServiceTests method testPendingTasks.

public void testPendingTasks() throws Exception {
    final IndexService indexService = createIndex("test");
    final Index index = indexService.index();
    final IndexSettings indexSettings = indexService.getIndexSettings();
    final IndexShard indexShard = indexService.getShardOrNull(0);
    assertNotNull(indexShard);
    assertTrue(indexShard.routingEntry().started());
    final ShardPath shardPath = indexShard.shardPath();
    assertEquals(ShardPath.loadShardPath(logger, getNodeEnvironment(), indexShard.shardId(), indexSettings.customDataPath()), shardPath);
    final IndicesService indicesService = getIndicesService();
    expectThrows(ShardLockObtainFailedException.class, () -> indicesService.processPendingDeletes(index, indexSettings, TimeValue.timeValueMillis(0)));
    assertTrue(shardPath.exists());
    int numPending = 1;
    if (randomBoolean()) {
        indicesService.addPendingDelete(indexShard.shardId(), indexSettings);
    } else {
        if (randomBoolean()) {
            numPending++;
            indicesService.addPendingDelete(indexShard.shardId(), indexSettings);
        }
        indicesService.addPendingDelete(index, indexSettings);
    }
    assertAcked(client().admin().indices().prepareClose("test"));
    assertTrue(shardPath.exists());
    ensureGreen("test");
    assertEquals(indicesService.numPendingDeletes(index), numPending);
    assertTrue(indicesService.hasUncompletedPendingDeletes());
    expectThrows(ShardLockObtainFailedException.class, () -> indicesService.processPendingDeletes(index, indexSettings, TimeValue.timeValueMillis(0)));
    assertEquals(indicesService.numPendingDeletes(index), numPending);
    assertTrue(indicesService.hasUncompletedPendingDeletes());
    final boolean hasBogus = randomBoolean();
    if (hasBogus) {
        indicesService.addPendingDelete(new ShardId(index, 0), indexSettings);
        indicesService.addPendingDelete(new ShardId(index, 1), indexSettings);
        indicesService.addPendingDelete(new ShardId("bogus", "_na_", 1), indexSettings);
        assertEquals(indicesService.numPendingDeletes(index), numPending + 2);
        assertTrue(indicesService.hasUncompletedPendingDeletes());
    }
    assertAcked(client().admin().indices().prepareDelete("test"));
    assertBusy(() -> {
        try {
            indicesService.processPendingDeletes(index, indexSettings, TimeValue.timeValueMillis(0));
            assertEquals(indicesService.numPendingDeletes(index), 0);
        } catch (final Exception e) {
            fail(e.getMessage());
        }
    });
    assertBusy(() -> {
        // "bogus" index has not been removed
        assertThat(indicesService.hasUncompletedPendingDeletes(), equalTo(hasBogus));
        assertFalse(shardPath.exists());
    });
}
Also used : ShardId(org.opensearch.index.shard.ShardId) IndexService(org.opensearch.index.IndexService) ShardPath(org.opensearch.index.shard.ShardPath) IndexSettings(org.opensearch.index.IndexSettings) IndexShard(org.opensearch.index.shard.IndexShard) Index(org.opensearch.index.Index) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) IllegalIndexShardStateException(org.opensearch.index.shard.IllegalIndexShardStateException) ShardLockObtainFailedException(org.opensearch.env.ShardLockObtainFailedException) IOException(java.io.IOException)

Example 55 with IndexSettings

use of org.opensearch.index.IndexSettings in project OpenSearch by opensearch-project.

the class IndicesService method deleteShardStore.

/**
 * This method deletes the shard contents on disk for the given shard ID. This method will fail if the shard deleting
 * is prevented by {@link #canDeleteShardContent(ShardId, IndexSettings)}
 * of if the shards lock can not be acquired.
 *
 * On data nodes, if the deleted shard is the last shard folder in its index, the method will attempt to remove
 * the index folder as well.
 *
 * @param reason the reason for the shard deletion
 * @param shardId the shards ID to delete
 * @param clusterState . This is required to access the indexes settings etc.
 * @throws IOException if an IOException occurs
 */
public void deleteShardStore(String reason, ShardId shardId, ClusterState clusterState) throws IOException, ShardLockObtainFailedException {
    final IndexMetadata metadata = clusterState.getMetadata().indices().get(shardId.getIndexName());
    final IndexSettings indexSettings = buildIndexSettings(metadata);
    ShardDeletionCheckResult shardDeletionCheckResult = canDeleteShardContent(shardId, indexSettings);
    if (shardDeletionCheckResult != ShardDeletionCheckResult.FOLDER_FOUND_CAN_DELETE) {
        throw new IllegalStateException("Can't delete shard " + shardId + " (cause: " + shardDeletionCheckResult + ")");
    }
    nodeEnv.deleteShardDirectorySafe(shardId, indexSettings);
    logger.debug("{} deleted shard reason [{}]", shardId, reason);
    if (canDeleteIndexContents(shardId.getIndex(), indexSettings)) {
        if (nodeEnv.findAllShardIds(shardId.getIndex()).isEmpty()) {
            try {
                // note that deleteIndexStore have more safety checks and may throw an exception if index was concurrently created.
                deleteIndexStore("no longer used", metadata);
            } catch (Exception e) {
                // wrap the exception to indicate we already deleted the shard
                throw new OpenSearchException("failed to delete unused index after deleting its last shard (" + shardId + ")", e);
            }
        } else {
            logger.trace("[{}] still has shard stores, leaving as is", shardId.getIndex());
        }
    }
}
Also used : IndexSettings(org.opensearch.index.IndexSettings) OpenSearchException(org.opensearch.OpenSearchException) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) OpenSearchRejectedExecutionException(org.opensearch.common.util.concurrent.OpenSearchRejectedExecutionException) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) OpenSearchException(org.opensearch.OpenSearchException) ResourceAlreadyExistsException(org.opensearch.ResourceAlreadyExistsException) IllegalIndexShardStateException(org.opensearch.index.shard.IllegalIndexShardStateException) ShardLockObtainFailedException(org.opensearch.env.ShardLockObtainFailedException) IndexNotFoundException(org.opensearch.index.IndexNotFoundException)

Aggregations

IndexSettings (org.opensearch.index.IndexSettings)195 Settings (org.opensearch.common.settings.Settings)137 IndexMetadata (org.opensearch.cluster.metadata.IndexMetadata)72 IOException (java.io.IOException)39 Index (org.opensearch.index.Index)32 Matchers.containsString (org.hamcrest.Matchers.containsString)25 Version (org.opensearch.Version)23 Store (org.opensearch.index.store.Store)23 Map (java.util.Map)22 QueryShardContext (org.opensearch.index.query.QueryShardContext)22 OpenSearchException (org.opensearch.OpenSearchException)21 MapperService (org.opensearch.index.mapper.MapperService)20 ShardId (org.opensearch.index.shard.ShardId)19 HashMap (java.util.HashMap)18 ArrayList (java.util.ArrayList)17 List (java.util.List)17 IndexService (org.opensearch.index.IndexService)17 IndexShard (org.opensearch.index.shard.IndexShard)17 HashSet (java.util.HashSet)16 Query (org.apache.lucene.search.Query)16