Search in sources :

Example 56 with Environment

use of org.opensearch.env.Environment in project OpenSearch by opensearch-project.

the class RemoveCorruptedShardDataCommandTests method testCorruptedTranslog.

public void testCorruptedTranslog() throws Exception {
    final int numDocsToKeep = indexDocs(indexShard, false);
    // close shard
    closeShards(indexShard);
    TestTranslog.corruptRandomTranslogFile(logger, random(), translogPath);
    // test corrupted shard
    final IndexShard corruptedShard = reopenIndexShard(true);
    allowShardFailures();
    // it has to fail on start up due to index.shard.check_on_startup = checksum
    final Exception exception = expectThrows(Exception.class, () -> newStartedShard(p -> corruptedShard, true));
    final Throwable cause = exception.getCause() instanceof EngineException ? exception.getCause().getCause() : exception.getCause();
    assertThat(cause, instanceOf(TranslogCorruptedException.class));
    // translog is corrupted already - do not check consistency
    closeShard(corruptedShard, false);
    final RemoveCorruptedShardDataCommand command = new RemoveCorruptedShardDataCommand();
    final MockTerminal t = new MockTerminal();
    final OptionParser parser = command.getParser();
    final OptionSet options = parser.parse("-d", translogPath.toString());
    // run command with dry-run
    // mean dry run
    t.addTextInput("n");
    t.setVerbosity(Terminal.Verbosity.VERBOSE);
    try {
        command.execute(t, options, environment);
        fail();
    } catch (OpenSearchException e) {
        assertThat(e.getMessage(), containsString("aborted by user"));
        assertThat(t.getOutput(), containsString("Continue and remove corrupted data from the shard ?"));
    }
    logger.info("--> output:\n{}", t.getOutput());
    // run command without dry-run
    t.reset();
    t.addTextInput("y");
    command.execute(t, options, environment);
    final String output = t.getOutput();
    logger.info("--> output:\n{}", output);
    // reopen shard
    failOnShardFailures();
    final IndexShard newShard = newStartedShard(p -> reopenIndexShard(false), true);
    final Set<String> shardDocUIDs = getShardDocUIDs(newShard);
    assertThat(shardDocUIDs.size(), equalTo(numDocsToKeep));
    closeShards(newShard);
}
Also used : EngineException(org.opensearch.index.engine.EngineException) Arrays(java.util.Arrays) TranslogCorruptedException(org.opensearch.index.translog.TranslogCorruptedException) Matchers.either(org.hamcrest.Matchers.either) MockTerminal(org.opensearch.cli.MockTerminal) Metadata(org.opensearch.cluster.metadata.Metadata) TRUNCATE_CLEAN_TRANSLOG_FLAG(org.opensearch.index.shard.RemoveCorruptedShardDataCommand.TRUNCATE_CLEAN_TRANSLOG_FLAG) CheckedFunction(org.opensearch.common.CheckedFunction) Version(org.opensearch.Version) OpenSearchException(org.opensearch.OpenSearchException) Matcher(java.util.regex.Matcher) OptionParser(joptsimple.OptionParser) DummyShardLock(org.opensearch.test.DummyShardLock) Path(java.nio.file.Path) OptionSet(joptsimple.OptionSet) NodeEnvironment(org.opensearch.env.NodeEnvironment) Matchers.allOf(org.hamcrest.Matchers.allOf) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) Store(org.opensearch.index.store.Store) Matchers.startsWith(org.hamcrest.Matchers.startsWith) Objects(java.util.Objects) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) EngineConfigFactory(org.opensearch.index.engine.EngineConfigFactory) Matchers.equalTo(org.hamcrest.Matchers.equalTo) IndexSettings(org.opensearch.index.IndexSettings) Matchers.is(org.hamcrest.Matchers.is) ShardRoutingHelper(org.opensearch.cluster.routing.ShardRoutingHelper) Pattern(java.util.regex.Pattern) BigArrays(org.opensearch.common.util.BigArrays) Matchers.containsString(org.hamcrest.Matchers.containsString) TestEnvironment(org.opensearch.env.TestEnvironment) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) RecoverySource(org.opensearch.cluster.routing.RecoverySource) BaseDirectoryWrapper(org.apache.lucene.store.BaseDirectoryWrapper) PersistedClusterStateService(org.opensearch.gateway.PersistedClusterStateService) ClusterState(org.opensearch.cluster.ClusterState) ShardRoutingState(org.opensearch.cluster.routing.ShardRoutingState) UUIDs(org.opensearch.common.UUIDs) ClusterSettings(org.opensearch.common.settings.ClusterSettings) CorruptionUtils(org.opensearch.test.CorruptionUtils) Before(org.junit.Before) Environment(org.opensearch.env.Environment) InternalEngineFactory(org.opensearch.index.engine.InternalEngineFactory) Terminal(org.opensearch.cli.Terminal) Files(java.nio.file.Files) TestTranslog(org.opensearch.index.translog.TestTranslog) IOException(java.io.IOException) ShardRouting(org.opensearch.cluster.routing.ShardRouting) TestShardRouting(org.opensearch.cluster.routing.TestShardRouting) ClusterName(org.opensearch.cluster.ClusterName) MergePolicyConfig(org.opensearch.index.MergePolicyConfig) RetentionLeaseSyncer(org.opensearch.index.seqno.RetentionLeaseSyncer) EngineException(org.opensearch.index.engine.EngineException) Matchers.containsString(org.hamcrest.Matchers.containsString) MockTerminal(org.opensearch.cli.MockTerminal) OptionParser(joptsimple.OptionParser) EngineException(org.opensearch.index.engine.EngineException) TranslogCorruptedException(org.opensearch.index.translog.TranslogCorruptedException) OpenSearchException(org.opensearch.OpenSearchException) IOException(java.io.IOException) TranslogCorruptedException(org.opensearch.index.translog.TranslogCorruptedException) OpenSearchException(org.opensearch.OpenSearchException) OptionSet(joptsimple.OptionSet)

Example 57 with Environment

use of org.opensearch.env.Environment in project OpenSearch by opensearch-project.

the class RemoveCorruptedShardDataCommandTests method testCorruptedIndex.

public void testCorruptedIndex() throws Exception {
    final int numDocs = indexDocs(indexShard, true);
    // close shard
    closeShards(indexShard);
    final boolean corruptSegments = randomBoolean();
    CorruptionUtils.corruptIndex(random(), indexPath, corruptSegments);
    if (randomBoolean()) {
        // test corrupted shard and add corruption marker
        final IndexShard corruptedShard = reopenIndexShard(true);
        allowShardFailures();
        expectThrows(IndexShardRecoveryException.class, () -> newStartedShard(p -> corruptedShard, true));
        closeShards(corruptedShard);
    }
    final RemoveCorruptedShardDataCommand command = new RemoveCorruptedShardDataCommand();
    final MockTerminal t = new MockTerminal();
    final OptionParser parser = command.getParser();
    // run command with dry-run
    // mean dry run
    t.addTextInput("n");
    final OptionSet options = parser.parse("-d", indexPath.toString());
    t.setVerbosity(Terminal.Verbosity.VERBOSE);
    try {
        command.execute(t, options, environment);
        fail();
    } catch (OpenSearchException e) {
        if (corruptSegments) {
            assertThat(e.getMessage(), either(is("Index is unrecoverable")).or(startsWith("unable to list commits")));
        } else {
            assertThat(e.getMessage(), containsString("aborted by user"));
        }
    } finally {
        logger.info("--> output:\n{}", t.getOutput());
    }
    if (corruptSegments == false) {
        // run command without dry-run
        t.addTextInput("y");
        command.execute(t, options, environment);
        final String output = t.getOutput();
        logger.info("--> output:\n{}", output);
        // reopen shard
        failOnShardFailures();
        final IndexShard newShard = newStartedShard(p -> reopenIndexShard(false), true);
        final Set<String> shardDocUIDs = getShardDocUIDs(newShard);
        final Matcher matcher = NUM_CORRUPT_DOCS_PATTERN.matcher(output);
        assertThat(matcher.find(), equalTo(true));
        final int expectedNumDocs = numDocs - Integer.parseInt(matcher.group("docs"));
        assertThat(shardDocUIDs.size(), equalTo(expectedNumDocs));
        closeShards(newShard);
    }
}
Also used : EngineException(org.opensearch.index.engine.EngineException) Arrays(java.util.Arrays) TranslogCorruptedException(org.opensearch.index.translog.TranslogCorruptedException) Matchers.either(org.hamcrest.Matchers.either) MockTerminal(org.opensearch.cli.MockTerminal) Metadata(org.opensearch.cluster.metadata.Metadata) TRUNCATE_CLEAN_TRANSLOG_FLAG(org.opensearch.index.shard.RemoveCorruptedShardDataCommand.TRUNCATE_CLEAN_TRANSLOG_FLAG) CheckedFunction(org.opensearch.common.CheckedFunction) Version(org.opensearch.Version) OpenSearchException(org.opensearch.OpenSearchException) Matcher(java.util.regex.Matcher) OptionParser(joptsimple.OptionParser) DummyShardLock(org.opensearch.test.DummyShardLock) Path(java.nio.file.Path) OptionSet(joptsimple.OptionSet) NodeEnvironment(org.opensearch.env.NodeEnvironment) Matchers.allOf(org.hamcrest.Matchers.allOf) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) Store(org.opensearch.index.store.Store) Matchers.startsWith(org.hamcrest.Matchers.startsWith) Objects(java.util.Objects) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) EngineConfigFactory(org.opensearch.index.engine.EngineConfigFactory) Matchers.equalTo(org.hamcrest.Matchers.equalTo) IndexSettings(org.opensearch.index.IndexSettings) Matchers.is(org.hamcrest.Matchers.is) ShardRoutingHelper(org.opensearch.cluster.routing.ShardRoutingHelper) Pattern(java.util.regex.Pattern) BigArrays(org.opensearch.common.util.BigArrays) Matchers.containsString(org.hamcrest.Matchers.containsString) TestEnvironment(org.opensearch.env.TestEnvironment) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) RecoverySource(org.opensearch.cluster.routing.RecoverySource) BaseDirectoryWrapper(org.apache.lucene.store.BaseDirectoryWrapper) PersistedClusterStateService(org.opensearch.gateway.PersistedClusterStateService) ClusterState(org.opensearch.cluster.ClusterState) ShardRoutingState(org.opensearch.cluster.routing.ShardRoutingState) UUIDs(org.opensearch.common.UUIDs) ClusterSettings(org.opensearch.common.settings.ClusterSettings) CorruptionUtils(org.opensearch.test.CorruptionUtils) Before(org.junit.Before) Environment(org.opensearch.env.Environment) InternalEngineFactory(org.opensearch.index.engine.InternalEngineFactory) Terminal(org.opensearch.cli.Terminal) Files(java.nio.file.Files) TestTranslog(org.opensearch.index.translog.TestTranslog) IOException(java.io.IOException) ShardRouting(org.opensearch.cluster.routing.ShardRouting) TestShardRouting(org.opensearch.cluster.routing.TestShardRouting) ClusterName(org.opensearch.cluster.ClusterName) MergePolicyConfig(org.opensearch.index.MergePolicyConfig) RetentionLeaseSyncer(org.opensearch.index.seqno.RetentionLeaseSyncer) Matcher(java.util.regex.Matcher) OpenSearchException(org.opensearch.OpenSearchException) Matchers.containsString(org.hamcrest.Matchers.containsString) OptionSet(joptsimple.OptionSet) MockTerminal(org.opensearch.cli.MockTerminal) OptionParser(joptsimple.OptionParser)

Example 58 with Environment

use of org.opensearch.env.Environment in project OpenSearch by opensearch-project.

the class AnalysisModuleTests method testRegisterHunspellDictionary.

public void testRegisterHunspellDictionary() throws Exception {
    Settings settings = Settings.builder().put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString()).put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT).build();
    Environment environment = TestEnvironment.newEnvironment(settings);
    InputStream aff = getClass().getResourceAsStream("/indices/analyze/conf_dir/hunspell/en_US/en_US.aff");
    InputStream dic = getClass().getResourceAsStream("/indices/analyze/conf_dir/hunspell/en_US/en_US.dic");
    Dictionary dictionary;
    try (Directory tmp = new NIOFSDirectory(environment.tmpFile())) {
        dictionary = new Dictionary(tmp, "hunspell", aff, dic);
    }
    AnalysisModule module = new AnalysisModule(environment, singletonList(new AnalysisPlugin() {

        @Override
        public Map<String, Dictionary> getHunspellDictionaries() {
            return singletonMap("foo", dictionary);
        }
    }));
    assertSame(dictionary, module.getHunspellService().getDictionary("foo"));
}
Also used : Dictionary(org.apache.lucene.analysis.hunspell.Dictionary) NIOFSDirectory(org.apache.lucene.store.NIOFSDirectory) InputStream(java.io.InputStream) TestEnvironment(org.opensearch.env.TestEnvironment) Environment(org.opensearch.env.Environment) Settings(org.opensearch.common.settings.Settings) IndexSettings(org.opensearch.index.IndexSettings) Directory(org.apache.lucene.store.Directory) NIOFSDirectory(org.apache.lucene.store.NIOFSDirectory) AnalysisPlugin(org.opensearch.plugins.AnalysisPlugin)

Example 59 with Environment

use of org.opensearch.env.Environment in project OpenSearch by opensearch-project.

the class AnalysisModuleTests method testWordListPath.

public void testWordListPath() throws Exception {
    Settings settings = Settings.builder().put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString()).build();
    Environment env = TestEnvironment.newEnvironment(settings);
    String[] words = new String[] { "donau", "dampf", "schiff", "spargel", "creme", "suppe" };
    Path wordListFile = generateWordList(words);
    settings = Settings.builder().loadFromSource("index: \n  word_list_path: " + wordListFile.toAbsolutePath(), XContentType.YAML).build();
    Set<?> wordList = Analysis.getWordSet(env, settings, "index.word_list");
    MatcherAssert.assertThat(wordList.size(), equalTo(6));
    // MatcherAssert.assertThat(wordList, hasItems(words));
    Files.delete(wordListFile);
}
Also used : Path(java.nio.file.Path) TestEnvironment(org.opensearch.env.TestEnvironment) Environment(org.opensearch.env.Environment) Settings(org.opensearch.common.settings.Settings) IndexSettings(org.opensearch.index.IndexSettings)

Example 60 with Environment

use of org.opensearch.env.Environment 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)

Aggregations

Environment (org.opensearch.env.Environment)142 TestEnvironment (org.opensearch.env.TestEnvironment)98 Path (java.nio.file.Path)80 Settings (org.opensearch.common.settings.Settings)79 Matchers.containsString (org.hamcrest.Matchers.containsString)69 Matchers.hasToString (org.hamcrest.Matchers.hasToString)40 NodeEnvironment (org.opensearch.env.NodeEnvironment)32 IOException (java.io.IOException)27 UserException (org.opensearch.cli.UserException)23 ClusterState (org.opensearch.cluster.ClusterState)22 IndexSettings (org.opensearch.index.IndexSettings)22 MockTerminal (org.opensearch.cli.MockTerminal)19 IndexMetadata (org.opensearch.cluster.metadata.IndexMetadata)19 OpenSearchException (org.opensearch.OpenSearchException)18 Map (java.util.Map)16 OptionSet (joptsimple.OptionSet)15 DiscoverySettings (org.opensearch.node.Node.DiscoverySettings)14 Version (org.opensearch.Version)13 Files (java.nio.file.Files)11 Arrays (java.util.Arrays)11