Search in sources :

Example 11 with MockTerminal

use of org.opensearch.cli.MockTerminal in project OpenSearch by opensearch-project.

the class RemovePluginCommandTests method testPurgePluginExists.

public void testPurgePluginExists() throws Exception {
    createPlugin("fake");
    final Path configDir = env.configDir().resolve("fake");
    if (randomBoolean()) {
        Files.createDirectories(configDir);
        Files.createFile(configDir.resolve("fake.yml"));
    }
    final MockTerminal terminal = removePlugin("fake", home, true);
    assertFalse(Files.exists(env.configDir().resolve("fake")));
    assertThat(terminal.getOutput(), not(containsString(expectedConfigDirPreservedMessage(configDir))));
    assertRemoveCleaned(env);
}
Also used : Path(java.nio.file.Path) MockTerminal(org.opensearch.cli.MockTerminal)

Example 12 with MockTerminal

use of org.opensearch.cli.MockTerminal in project OpenSearch by opensearch-project.

the class RemoveCorruptedShardDataCommandIT method testCorruptTranslogTruncationOfReplica.

public void testCorruptTranslogTruncationOfReplica() throws Exception {
    internalCluster().startClusterManagerOnlyNode();
    final String node1 = internalCluster().startDataOnlyNode();
    final String node2 = internalCluster().startDataOnlyNode();
    logger.info("--> nodes name: {}, {}", node1, node2);
    final String indexName = "test";
    assertAcked(prepareCreate(indexName).setSettings(Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1).put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 1).put(IndexSettings.INDEX_REFRESH_INTERVAL_SETTING.getKey(), "-1").put(MockEngineSupport.DISABLE_FLUSH_ON_CLOSE.getKey(), // never flush - always recover from translog
    true).put("index.routing.allocation.exclude._name", node2)));
    ensureYellow();
    assertAcked(client().admin().indices().prepareUpdateSettings(indexName).setSettings(Settings.builder().put("index.routing.allocation.exclude._name", (String) null)));
    ensureGreen();
    // Index some documents
    int numDocsToKeep = randomIntBetween(0, 100);
    logger.info("--> indexing [{}] docs to be kept", numDocsToKeep);
    IndexRequestBuilder[] builders = new IndexRequestBuilder[numDocsToKeep];
    for (int i = 0; i < builders.length; i++) {
        builders[i] = client().prepareIndex(indexName).setSource("foo", "bar");
    }
    indexRandom(false, false, false, Arrays.asList(builders));
    flush(indexName);
    disableTranslogFlush(indexName);
    // having no extra docs is an interesting case for seq no based recoveries - test it more often
    int numDocsToTruncate = randomBoolean() ? 0 : randomIntBetween(0, 100);
    logger.info("--> indexing [{}] more docs to be truncated", numDocsToTruncate);
    builders = new IndexRequestBuilder[numDocsToTruncate];
    for (int i = 0; i < builders.length; i++) {
        builders[i] = client().prepareIndex(indexName).setSource("foo", "bar");
    }
    indexRandom(false, false, false, Arrays.asList(builders));
    final int totalDocs = numDocsToKeep + numDocsToTruncate;
    // sample the replica node translog dirs
    final ShardId shardId = new ShardId(resolveIndex(indexName), 0);
    final Path translogDir = getPathToShardData(node2, shardId, ShardPath.TRANSLOG_FOLDER_NAME);
    final Settings node1PathSettings = internalCluster().dataPathSettings(node1);
    final Settings node2PathSettings = internalCluster().dataPathSettings(node2);
    assertBusy(() -> internalCluster().getInstances(GatewayMetaState.class).forEach(gw -> assertTrue(gw.allPendingAsyncStatesWritten())));
    // stop data nodes
    internalCluster().stopRandomDataNode();
    internalCluster().stopRandomDataNode();
    // Corrupt the translog file(s) on the replica
    logger.info("--> corrupting translog");
    TestTranslog.corruptRandomTranslogFile(logger, random(), translogDir);
    // Start the node with the non-corrupted data path
    logger.info("--> starting node");
    internalCluster().startNode(node1PathSettings);
    ensureYellow();
    // Run a search and make sure it succeeds
    assertHitCount(client().prepareSearch(indexName).setQuery(matchAllQuery()).get(), totalDocs);
    // check replica corruption
    final RemoveCorruptedShardDataCommand command = new RemoveCorruptedShardDataCommand();
    final MockTerminal terminal = new MockTerminal();
    final OptionParser parser = command.getParser();
    final Environment environment = TestEnvironment.newEnvironment(Settings.builder().put(internalCluster().getDefaultSettings()).put(node2PathSettings).build());
    terminal.addTextInput("y");
    OptionSet options = parser.parse("-d", translogDir.toAbsolutePath().toString());
    logger.info("--> running command for [{}]", translogDir.toAbsolutePath());
    command.execute(terminal, options, environment);
    logger.info("--> output:\n{}", terminal.getOutput());
    logger.info("--> starting the replica node to test recovery");
    internalCluster().startNode(node2PathSettings);
    ensureGreen(indexName);
    for (String node : internalCluster().nodesInclude(indexName)) {
        assertHitCount(client().prepareSearch(indexName).setPreference("_only_nodes:" + node).setQuery(matchAllQuery()).get(), totalDocs);
    }
    final RecoveryResponse recoveryResponse = client().admin().indices().prepareRecoveries(indexName).setActiveOnly(false).get();
    final RecoveryState replicaRecoveryState = recoveryResponse.shardRecoveryStates().get(indexName).stream().filter(recoveryState -> recoveryState.getPrimary() == false).findFirst().get();
    // the replica translog was disabled so it doesn't know what hte global checkpoint is and thus can't do ops based recovery
    assertThat(replicaRecoveryState.getIndex().toString(), replicaRecoveryState.getIndex().recoveredFileCount(), greaterThan(0));
    // Ensure that the global checkpoint and local checkpoint are restored from the max seqno of the last commit.
    final SeqNoStats seqNoStats = getSeqNoStats(indexName, 0);
    assertThat(seqNoStats.getGlobalCheckpoint(), equalTo(seqNoStats.getMaxSeqNo()));
    assertThat(seqNoStats.getLocalCheckpoint(), equalTo(seqNoStats.getMaxSeqNo()));
}
Also used : Path(java.nio.file.Path) IndexRequestBuilder(org.opensearch.action.index.IndexRequestBuilder) SeqNoStats(org.opensearch.index.seqno.SeqNoStats) Arrays(java.util.Arrays) TranslogCorruptedException(org.opensearch.index.translog.TranslogCorruptedException) MockTerminal(org.opensearch.cli.MockTerminal) Matchers.not(org.hamcrest.Matchers.not) ByteSizeUnit(org.opensearch.common.unit.ByteSizeUnit) AllocateStalePrimaryAllocationCommand(org.opensearch.cluster.routing.allocation.command.AllocateStalePrimaryAllocationCommand) ObjectObjectCursor(com.carrotsearch.hppc.cursors.ObjectObjectCursor) ClusterAllocationExplanation(org.opensearch.action.admin.cluster.allocation.ClusterAllocationExplanation) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) Matcher(java.util.regex.Matcher) OpenSearchAssertions.assertHitCount(org.opensearch.test.hamcrest.OpenSearchAssertions.assertHitCount) QueryBuilders.matchAllQuery(org.opensearch.index.query.QueryBuilders.matchAllQuery) RecoveryState(org.opensearch.indices.recovery.RecoveryState) Directory(org.apache.lucene.store.Directory) Map(java.util.Map) Matchers.nullValue(org.hamcrest.Matchers.nullValue) OptionParser(joptsimple.OptionParser) SearchRequestBuilder(org.opensearch.action.search.SearchRequestBuilder) UnassignedInfo(org.opensearch.cluster.routing.UnassignedInfo) Path(java.nio.file.Path) OptionSet(joptsimple.OptionSet) NodeEnvironment(org.opensearch.env.NodeEnvironment) CollectionUtils.iterableAsArrayList(org.opensearch.common.util.CollectionUtils.iterableAsArrayList) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) Index(org.opensearch.index.Index) Matchers.allOf(org.hamcrest.Matchers.allOf) Collection(java.util.Collection) ShardAllocationDecision(org.opensearch.cluster.routing.allocation.ShardAllocationDecision) IndicesService(org.opensearch.indices.IndicesService) ExceptionsHelper(org.opensearch.ExceptionsHelper) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) Collectors(java.util.stream.Collectors) Matchers.startsWith(org.hamcrest.Matchers.startsWith) IndexWriter(org.apache.lucene.index.IndexWriter) GatewayMetaState(org.opensearch.gateway.GatewayMetaState) List(java.util.List) Stream(java.util.stream.Stream) Matchers.equalTo(org.hamcrest.Matchers.equalTo) IndexSettings(org.opensearch.index.IndexSettings) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) Pattern(java.util.regex.Pattern) OpenSearchIntegTestCase(org.opensearch.test.OpenSearchIntegTestCase) Matchers.containsString(org.hamcrest.Matchers.containsString) PathUtils(org.opensearch.common.io.PathUtils) FS(org.opensearch.action.admin.cluster.node.stats.NodesStatsRequest.Metric.FS) TestEnvironment(org.opensearch.env.TestEnvironment) DiscoveryNodes(org.opensearch.cluster.node.DiscoveryNodes) RandomPicks(com.carrotsearch.randomizedtesting.generators.RandomPicks) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) FlushRequest(org.opensearch.action.admin.indices.flush.FlushRequest) ShardIterator(org.opensearch.cluster.routing.ShardIterator) LockObtainFailedException(org.apache.lucene.store.LockObtainFailedException) NativeFSLockFactory(org.apache.lucene.store.NativeFSLockFactory) ByteSizeValue(org.opensearch.common.unit.ByteSizeValue) HashMap(java.util.HashMap) MockTransportService(org.opensearch.test.transport.MockTransportService) InternalTestCluster(org.opensearch.test.InternalTestCluster) ClusterState(org.opensearch.cluster.ClusterState) Lock(org.apache.lucene.store.Lock) InternalSettingsPlugin(org.opensearch.test.InternalSettingsPlugin) ShardRoutingState(org.opensearch.cluster.routing.ShardRoutingState) Matchers.hasSize(org.hamcrest.Matchers.hasSize) StreamSupport(java.util.stream.StreamSupport) CorruptionUtils(org.opensearch.test.CorruptionUtils) FSDirectory(org.apache.lucene.store.FSDirectory) AllocationDecision(org.opensearch.cluster.routing.allocation.AllocationDecision) Environment(org.opensearch.env.Environment) OpenSearchAssertions.assertAcked(org.opensearch.test.hamcrest.OpenSearchAssertions.assertAcked) MockEngineFactoryPlugin(org.opensearch.index.MockEngineFactoryPlugin) Files(java.nio.file.Files) TestTranslog(org.opensearch.index.translog.TestTranslog) IOException(java.io.IOException) MockEngineSupport(org.opensearch.test.engine.MockEngineSupport) Plugin(org.opensearch.plugins.Plugin) ShardRouting(org.opensearch.cluster.routing.ShardRouting) GroupShardsIterator(org.opensearch.cluster.routing.GroupShardsIterator) RecoveryResponse(org.opensearch.action.admin.indices.recovery.RecoveryResponse) NodesStatsResponse(org.opensearch.action.admin.cluster.node.stats.NodesStatsResponse) ShardStats(org.opensearch.action.admin.indices.stats.ShardStats) MergePolicyConfig(org.opensearch.index.MergePolicyConfig) Matchers.containsString(org.hamcrest.Matchers.containsString) MockTerminal(org.opensearch.cli.MockTerminal) OptionParser(joptsimple.OptionParser) RecoveryResponse(org.opensearch.action.admin.indices.recovery.RecoveryResponse) IndexRequestBuilder(org.opensearch.action.index.IndexRequestBuilder) SeqNoStats(org.opensearch.index.seqno.SeqNoStats) NodeEnvironment(org.opensearch.env.NodeEnvironment) TestEnvironment(org.opensearch.env.TestEnvironment) Environment(org.opensearch.env.Environment) OptionSet(joptsimple.OptionSet) RecoveryState(org.opensearch.indices.recovery.RecoveryState) Settings(org.opensearch.common.settings.Settings) IndexSettings(org.opensearch.index.IndexSettings)

Example 13 with MockTerminal

use of org.opensearch.cli.MockTerminal in project OpenSearch by opensearch-project.

the class UnsafeBootstrapAndDetachCommandIT method test3ClusterManagerNodes2Failed.

public void test3ClusterManagerNodes2Failed() throws Exception {
    internalCluster().setBootstrapClusterManagerNodeIndex(2);
    List<String> clusterManagerNodes = new ArrayList<>();
    logger.info("--> start 1st cluster-manager-eligible node");
    clusterManagerNodes.add(internalCluster().startClusterManagerOnlyNode(Settings.builder().put(DiscoverySettings.INITIAL_STATE_TIMEOUT_SETTING.getKey(), "0s").build()));
    // node ordinal 0
    logger.info("--> start one data-only node");
    String dataNode = internalCluster().startDataOnlyNode(Settings.builder().put(DiscoverySettings.INITIAL_STATE_TIMEOUT_SETTING.getKey(), "0s").build());
    // node ordinal 1
    logger.info("--> start 2nd and 3rd cluster-manager-eligible nodes and bootstrap");
    // node ordinals 2 and 3
    clusterManagerNodes.addAll(internalCluster().startMasterOnlyNodes(2));
    logger.info("--> wait for all nodes to join the cluster");
    ensureStableCluster(4);
    List<String> currentClusterNodes = new ArrayList<>(clusterManagerNodes);
    currentClusterNodes.add(dataNode);
    currentClusterNodes.forEach(node -> ensureReadOnlyBlock(false, node));
    logger.info("--> create index test");
    createIndex("test");
    ensureGreen("test");
    Settings clusterManager1DataPathSettings = internalCluster().dataPathSettings(clusterManagerNodes.get(0));
    Settings clusterManager2DataPathSettings = internalCluster().dataPathSettings(clusterManagerNodes.get(1));
    Settings clusterManager3DataPathSettings = internalCluster().dataPathSettings(clusterManagerNodes.get(2));
    Settings dataNodeDataPathSettings = internalCluster().dataPathSettings(dataNode);
    logger.info("--> stop 2nd and 3d cluster-manager eligible node");
    internalCluster().stopRandomNode(InternalTestCluster.nameFilter(clusterManagerNodes.get(1)));
    internalCluster().stopRandomNode(InternalTestCluster.nameFilter(clusterManagerNodes.get(2)));
    logger.info("--> ensure NO_MASTER_BLOCK on data-only node");
    assertBusy(() -> {
        ClusterState state = internalCluster().client(dataNode).admin().cluster().prepareState().setLocal(true).execute().actionGet().getState();
        assertTrue(state.blocks().hasGlobalBlockWithId(NoMasterBlockService.NO_MASTER_BLOCK_ID));
    });
    logger.info("--> try to unsafely bootstrap 1st cluster-manager-eligible node, while node lock is held");
    Environment environmentClusterManager1 = TestEnvironment.newEnvironment(Settings.builder().put(internalCluster().getDefaultSettings()).put(clusterManager1DataPathSettings).build());
    expectThrows(() -> unsafeBootstrap(environmentClusterManager1), UnsafeBootstrapMasterCommand.FAILED_TO_OBTAIN_NODE_LOCK_MSG);
    logger.info("--> stop 1st cluster-manager-eligible node and data-only node");
    NodeEnvironment nodeEnvironment = internalCluster().getMasterNodeInstance(NodeEnvironment.class);
    internalCluster().stopRandomNode(InternalTestCluster.nameFilter(clusterManagerNodes.get(0)));
    assertBusy(() -> internalCluster().getInstance(GatewayMetaState.class, dataNode).allPendingAsyncStatesWritten());
    internalCluster().stopRandomDataNode();
    logger.info("--> unsafely-bootstrap 1st cluster-manager-eligible node");
    MockTerminal terminal = unsafeBootstrap(environmentClusterManager1, false, true);
    Metadata metadata = OpenSearchNodeCommand.createPersistedClusterStateService(Settings.EMPTY, nodeEnvironment.nodeDataPaths()).loadBestOnDiskState().metadata;
    assertThat(terminal.getOutput(), containsString(String.format(Locale.ROOT, UnsafeBootstrapMasterCommand.CLUSTER_STATE_TERM_VERSION_MSG_FORMAT, metadata.coordinationMetadata().term(), metadata.version())));
    logger.info("--> start 1st cluster-manager-eligible node");
    String clusterManagerNode2 = internalCluster().startClusterManagerOnlyNode(clusterManager1DataPathSettings);
    logger.info("--> detach-cluster on data-only node");
    Environment environmentData = TestEnvironment.newEnvironment(Settings.builder().put(internalCluster().getDefaultSettings()).put(dataNodeDataPathSettings).build());
    detachCluster(environmentData, false);
    logger.info("--> start data-only node");
    String dataNode2 = internalCluster().startDataOnlyNode(dataNodeDataPathSettings);
    logger.info("--> ensure there is no NO_MASTER_BLOCK and unsafe-bootstrap is reflected in cluster state");
    assertBusy(() -> {
        ClusterState state = internalCluster().client(dataNode2).admin().cluster().prepareState().setLocal(true).execute().actionGet().getState();
        assertFalse(state.blocks().hasGlobalBlockWithId(NoMasterBlockService.NO_MASTER_BLOCK_ID));
        assertTrue(state.metadata().persistentSettings().getAsBoolean(UnsafeBootstrapMasterCommand.UNSAFE_BOOTSTRAP.getKey(), false));
    });
    List<String> bootstrappedNodes = new ArrayList<>();
    bootstrappedNodes.add(dataNode2);
    bootstrappedNodes.add(clusterManagerNode2);
    bootstrappedNodes.forEach(node -> ensureReadOnlyBlock(true, node));
    logger.info("--> ensure index test is green");
    ensureGreen("test");
    IndexMetadata indexMetadata = clusterService().state().metadata().index("test");
    assertThat(indexMetadata.getSettings().get(IndexMetadata.SETTING_HISTORY_UUID), notNullValue());
    logger.info("--> detach-cluster on 2nd and 3rd cluster-manager-eligible nodes");
    Environment environmentClusterManager2 = TestEnvironment.newEnvironment(Settings.builder().put(internalCluster().getDefaultSettings()).put(clusterManager2DataPathSettings).build());
    detachCluster(environmentClusterManager2, false);
    Environment environmentClusterManager3 = TestEnvironment.newEnvironment(Settings.builder().put(internalCluster().getDefaultSettings()).put(clusterManager3DataPathSettings).build());
    detachCluster(environmentClusterManager3, false);
    logger.info("--> start 2nd and 3rd cluster-manager-eligible nodes and ensure 4 nodes stable cluster");
    bootstrappedNodes.add(internalCluster().startClusterManagerOnlyNode(clusterManager2DataPathSettings));
    bootstrappedNodes.add(internalCluster().startClusterManagerOnlyNode(clusterManager3DataPathSettings));
    ensureStableCluster(4);
    bootstrappedNodes.forEach(node -> ensureReadOnlyBlock(true, node));
    removeBlock();
}
Also used : ClusterState(org.opensearch.cluster.ClusterState) NodeEnvironment(org.opensearch.env.NodeEnvironment) ArrayList(java.util.ArrayList) Metadata(org.opensearch.cluster.metadata.Metadata) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) TestEnvironment(org.opensearch.env.TestEnvironment) Environment(org.opensearch.env.Environment) NodeEnvironment(org.opensearch.env.NodeEnvironment) Matchers.containsString(org.hamcrest.Matchers.containsString) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) MockTerminal(org.opensearch.cli.MockTerminal) Settings(org.opensearch.common.settings.Settings) DiscoverySettings(org.opensearch.node.Node.DiscoverySettings)

Example 14 with MockTerminal

use of org.opensearch.cli.MockTerminal in project OpenSearch by opensearch-project.

the class UnsafeBootstrapAndDetachCommandIT method detachCluster.

private MockTerminal detachCluster(Environment environment, boolean abort) throws Exception {
    final MockTerminal terminal = executeCommand(new DetachClusterCommand(), environment, 0, abort, null);
    assertThat(terminal.getOutput(), containsString(DetachClusterCommand.CONFIRMATION_MSG));
    assertThat(terminal.getOutput(), containsString(DetachClusterCommand.NODE_DETACHED_MSG));
    return terminal;
}
Also used : MockTerminal(org.opensearch.cli.MockTerminal)

Example 15 with MockTerminal

use of org.opensearch.cli.MockTerminal in project OpenSearch by opensearch-project.

the class UnsafeBootstrapAndDetachCommandIT method unsafeBootstrap.

private MockTerminal unsafeBootstrap(Environment environment, boolean abort, Boolean applyClusterReadOnlyBlock) throws Exception {
    final MockTerminal terminal = executeCommand(new UnsafeBootstrapMasterCommand(), environment, 0, abort, applyClusterReadOnlyBlock);
    assertThat(terminal.getOutput(), containsString(UnsafeBootstrapMasterCommand.CONFIRMATION_MSG));
    assertThat(terminal.getOutput(), containsString(UnsafeBootstrapMasterCommand.CLUSTER_MANAGER_NODE_BOOTSTRAPPED_MSG));
    return terminal;
}
Also used : MockTerminal(org.opensearch.cli.MockTerminal)

Aggregations

MockTerminal (org.opensearch.cli.MockTerminal)51 Environment (org.opensearch.env.Environment)17 Matchers.containsString (org.hamcrest.Matchers.containsString)16 Settings (org.opensearch.common.settings.Settings)16 TestEnvironment (org.opensearch.env.TestEnvironment)16 Path (java.nio.file.Path)15 OptionSet (joptsimple.OptionSet)13 OpenSearchException (org.opensearch.OpenSearchException)12 IOException (java.io.IOException)10 OptionParser (joptsimple.OptionParser)10 Version (org.opensearch.Version)10 ClusterState (org.opensearch.cluster.ClusterState)10 NodeEnvironment (org.opensearch.env.NodeEnvironment)10 IndexMetadata (org.opensearch.cluster.metadata.IndexMetadata)8 TranslogCorruptedException (org.opensearch.index.translog.TranslogCorruptedException)8 Metadata (org.opensearch.cluster.metadata.Metadata)7 IndexSettings (org.opensearch.index.IndexSettings)7 Files (java.nio.file.Files)6 Arrays (java.util.Arrays)6 Matcher (java.util.regex.Matcher)6