Search in sources :

Example 1 with BackgroundIndexer

use of org.opensearch.test.BackgroundIndexer in project OpenSearch by opensearch-project.

the class DiskDisruptionIT method testGlobalCheckpointIsSafe.

/**
 * This test checks that all operations below the global checkpoint are properly persisted.
 * It simulates a full power outage by preventing translog checkpoint files to be written and restart the cluster. This means that
 * all un-fsynced data will be lost.
 */
public void testGlobalCheckpointIsSafe() throws Exception {
    startCluster(rarely() ? 5 : 3);
    final int numberOfShards = 1 + randomInt(2);
    assertAcked(prepareCreate("test").setSettings(Settings.builder().put(indexSettings()).put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, numberOfShards).put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, randomInt(2))));
    ensureGreen();
    AtomicBoolean stopGlobalCheckpointFetcher = new AtomicBoolean();
    Map<Integer, Long> shardToGcp = new ConcurrentHashMap<>();
    for (int i = 0; i < numberOfShards; i++) {
        shardToGcp.put(i, SequenceNumbers.NO_OPS_PERFORMED);
    }
    final Thread globalCheckpointSampler = new Thread(() -> {
        while (stopGlobalCheckpointFetcher.get() == false) {
            try {
                for (ShardStats shardStats : client().admin().indices().prepareStats("test").clear().get().getShards()) {
                    final int shardId = shardStats.getShardRouting().id();
                    final long globalCheckpoint = shardStats.getSeqNoStats().getGlobalCheckpoint();
                    shardToGcp.compute(shardId, (i, v) -> Math.max(v, globalCheckpoint));
                }
            } catch (Exception e) {
                // ignore
                logger.debug("failed to fetch shard stats", e);
            }
        }
    });
    globalCheckpointSampler.start();
    try (BackgroundIndexer indexer = new BackgroundIndexer("test", "_doc", client(), -1, RandomizedTest.scaledRandomIntBetween(2, 5), false, random())) {
        indexer.setRequestTimeout(TimeValue.ZERO);
        indexer.setIgnoreIndexingFailures(true);
        indexer.setFailureAssertion(e -> {
        });
        indexer.start(-1);
        waitForDocs(randomIntBetween(1, 100), indexer);
        logger.info("injecting failures");
        injectTranslogFailures();
        logger.info("stopping indexing");
    }
    logger.info("full cluster restart");
    internalCluster().fullRestart(new InternalTestCluster.RestartCallback() {

        @Override
        public void onAllNodesStopped() {
            logger.info("stopping failures");
            stopTranslogFailures();
        }
    });
    stopGlobalCheckpointFetcher.set(true);
    logger.info("waiting for global checkpoint sampler");
    globalCheckpointSampler.join();
    logger.info("waiting for green");
    ensureGreen("test");
    for (ShardStats shardStats : client().admin().indices().prepareStats("test").clear().get().getShards()) {
        final int shardId = shardStats.getShardRouting().id();
        final long maxSeqNo = shardStats.getSeqNoStats().getMaxSeqNo();
        if (shardStats.getShardRouting().active()) {
            assertThat(maxSeqNo, greaterThanOrEqualTo(shardToGcp.get(shardId)));
        }
    }
}
Also used : ShardStats(org.opensearch.action.admin.indices.stats.ShardStats) BackgroundIndexer(org.opensearch.test.BackgroundIndexer) InternalTestCluster(org.opensearch.test.InternalTestCluster) IOException(java.io.IOException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 2 with BackgroundIndexer

use of org.opensearch.test.BackgroundIndexer in project OpenSearch by opensearch-project.

the class CloseIndexIT method testConcurrentClosesAndOpens.

public void testConcurrentClosesAndOpens() throws Exception {
    final String indexName = randomAlphaOfLength(10).toLowerCase(Locale.ROOT);
    createIndex(indexName);
    final BackgroundIndexer indexer = new BackgroundIndexer(indexName, "_doc", client(), MAX_DOCS);
    indexer.setFailureAssertion(e -> {
    });
    waitForDocs(1, indexer);
    final CountDownLatch latch = new CountDownLatch(1);
    final Runnable waitForLatch = () -> {
        try {
            latch.await();
        } catch (final InterruptedException e) {
            throw new AssertionError(e);
        }
    };
    final List<Thread> threads = new ArrayList<>();
    for (int i = 0; i < randomIntBetween(1, 3); i++) {
        threads.add(new Thread(() -> {
            try {
                waitForLatch.run();
                client().admin().indices().prepareClose(indexName).get();
            } catch (final Exception e) {
                throw new AssertionError(e);
            }
        }));
    }
    for (int i = 0; i < randomIntBetween(1, 3); i++) {
        threads.add(new Thread(() -> {
            try {
                waitForLatch.run();
                assertAcked(client().admin().indices().prepareOpen(indexName).get());
            } catch (final Exception e) {
                throw new AssertionError(e);
            }
        }));
    }
    for (Thread thread : threads) {
        thread.start();
    }
    latch.countDown();
    for (Thread thread : threads) {
        thread.join();
    }
    indexer.stopAndAwaitStopped();
    final ClusterState clusterState = client().admin().cluster().prepareState().get().getState();
    if (clusterState.metadata().indices().get(indexName).getState() == IndexMetadata.State.CLOSE) {
        assertIndexIsClosed(indexName);
        assertAcked(client().admin().indices().prepareOpen(indexName));
    }
    refresh(indexName);
    assertIndexIsOpened(indexName);
    assertHitCount(client().prepareSearch(indexName).setSize(0).setTrackTotalHitsUpTo(TRACK_TOTAL_HITS_ACCURATE).get(), indexer.totalIndexedDocs());
}
Also used : ClusterState(org.opensearch.cluster.ClusterState) BackgroundIndexer(org.opensearch.test.BackgroundIndexer) ArrayList(java.util.ArrayList) Matchers.containsString(org.hamcrest.Matchers.containsString) CountDownLatch(java.util.concurrent.CountDownLatch) ActionRequestValidationException(org.opensearch.action.ActionRequestValidationException) IndexClosedException(org.opensearch.indices.IndexClosedException) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) ClusterBlockException(org.opensearch.cluster.block.ClusterBlockException)

Example 3 with BackgroundIndexer

use of org.opensearch.test.BackgroundIndexer in project OpenSearch by opensearch-project.

the class CloseIndexIT method testCloseWhileIndexingDocuments.

public void testCloseWhileIndexingDocuments() throws Exception {
    final String indexName = randomAlphaOfLength(10).toLowerCase(Locale.ROOT);
    createIndex(indexName);
    int nbDocs = 0;
    try (BackgroundIndexer indexer = new BackgroundIndexer(indexName, "_doc", client(), MAX_DOCS)) {
        indexer.setFailureAssertion(t -> assertException(t, indexName));
        waitForDocs(randomIntBetween(10, 50), indexer);
        assertBusy(() -> closeIndices(indexName));
        indexer.stopAndAwaitStopped();
        nbDocs += indexer.totalIndexedDocs();
    }
    assertIndexIsClosed(indexName);
    assertAcked(client().admin().indices().prepareOpen(indexName));
    assertHitCount(client().prepareSearch(indexName).setSize(0).setTrackTotalHitsUpTo(TRACK_TOTAL_HITS_ACCURATE).get(), nbDocs);
}
Also used : BackgroundIndexer(org.opensearch.test.BackgroundIndexer) Matchers.containsString(org.hamcrest.Matchers.containsString)

Example 4 with BackgroundIndexer

use of org.opensearch.test.BackgroundIndexer in project OpenSearch by opensearch-project.

the class SimpleBlocksIT method testAddBlockWhileIndexingDocuments.

public void testAddBlockWhileIndexingDocuments() throws Exception {
    final String indexName = randomAlphaOfLength(10).toLowerCase(Locale.ROOT);
    createIndex(indexName);
    final APIBlock block = randomAddableBlock();
    int nbDocs = 0;
    try {
        try (BackgroundIndexer indexer = new BackgroundIndexer(indexName, "_doc", client(), 1000)) {
            indexer.setFailureAssertion(t -> {
                Throwable cause = ExceptionsHelper.unwrapCause(t);
                assertThat(cause, instanceOf(ClusterBlockException.class));
                ClusterBlockException e = (ClusterBlockException) cause;
                assertThat(e.blocks(), hasSize(1));
                assertTrue(e.blocks().stream().allMatch(b -> b.id() == block.getBlock().id()));
            });
            waitForDocs(randomIntBetween(10, 50), indexer);
            assertAcked(client().admin().indices().prepareAddBlock(block, indexName));
            indexer.stopAndAwaitStopped();
            nbDocs += indexer.totalIndexedDocs();
        }
        assertIndexHasBlock(block, indexName);
    } finally {
        disableIndexBlock(indexName, block);
    }
    refresh(indexName);
    assertHitCount(client().prepareSearch(indexName).setSize(0).setTrackTotalHitsUpTo(TRACK_TOTAL_HITS_ACCURATE).get(), nbDocs);
}
Also used : IndexRequestBuilder(org.opensearch.action.index.IndexRequestBuilder) IntStream(java.util.stream.IntStream) APIBlock(org.opensearch.cluster.metadata.IndexMetadata.APIBlock) Arrays(java.util.Arrays) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) IndexResponse(org.opensearch.action.index.IndexResponse) HashMap(java.util.HashMap) ActionRequestValidationException(org.opensearch.action.ActionRequestValidationException) AddIndexBlockRequestBuilder(org.opensearch.action.admin.indices.readonly.AddIndexBlockRequestBuilder) ArrayList(java.util.ArrayList) ClusterState(org.opensearch.cluster.ClusterState) OpenSearchAssertions.assertHitCount(org.opensearch.test.hamcrest.OpenSearchAssertions.assertHitCount) Locale(java.util.Locale) Matchers.hasSize(org.hamcrest.Matchers.hasSize) BackgroundIndexer(org.opensearch.test.BackgroundIndexer) TRACK_TOTAL_HITS_ACCURATE(org.opensearch.search.internal.SearchContext.TRACK_TOTAL_HITS_ACCURATE) IndicesOptions.lenientExpandOpen(org.opensearch.action.support.IndicesOptions.lenientExpandOpen) OpenSearchAssertions.assertAcked(org.opensearch.test.hamcrest.OpenSearchAssertions.assertAcked) OpenSearchAssertions.assertBlocked(org.opensearch.test.hamcrest.OpenSearchAssertions.assertBlocked) Collections.emptySet(java.util.Collections.emptySet) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) ClusterBlockLevel(org.opensearch.cluster.block.ClusterBlockLevel) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) ExceptionsHelper(org.opensearch.ExceptionsHelper) ClusterBlockException(org.opensearch.cluster.block.ClusterBlockException) Settings(org.opensearch.common.settings.Settings) CreateIndexResponse(org.opensearch.action.admin.indices.create.CreateIndexResponse) ActiveShardCount(org.opensearch.action.support.ActiveShardCount) AcknowledgedResponse(org.opensearch.action.support.master.AcknowledgedResponse) ShardRouting(org.opensearch.cluster.routing.ShardRouting) Consumer(java.util.function.Consumer) SETTING_READ_ONLY(org.opensearch.cluster.metadata.IndexMetadata.SETTING_READ_ONLY) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) SETTING_BLOCKS_WRITE(org.opensearch.cluster.metadata.IndexMetadata.SETTING_BLOCKS_WRITE) Matchers.equalTo(org.hamcrest.Matchers.equalTo) UpdateSettingsRequestBuilder(org.opensearch.action.admin.indices.settings.put.UpdateSettingsRequestBuilder) Matchers.is(org.hamcrest.Matchers.is) IndicesExistsResponse(org.opensearch.action.admin.indices.exists.indices.IndicesExistsResponse) OpenSearchIntegTestCase(org.opensearch.test.OpenSearchIntegTestCase) Matchers.containsString(org.hamcrest.Matchers.containsString) BackgroundIndexer(org.opensearch.test.BackgroundIndexer) APIBlock(org.opensearch.cluster.metadata.IndexMetadata.APIBlock) Matchers.containsString(org.hamcrest.Matchers.containsString) ClusterBlockException(org.opensearch.cluster.block.ClusterBlockException)

Example 5 with BackgroundIndexer

use of org.opensearch.test.BackgroundIndexer in project OpenSearch by opensearch-project.

the class ReplicaToPrimaryPromotionIT method testPromoteReplicaToPrimary.

public void testPromoteReplicaToPrimary() throws Exception {
    final String indexName = randomAlphaOfLength(5).toLowerCase(Locale.ROOT);
    createIndex(indexName);
    final int numOfDocs = scaledRandomIntBetween(0, 200);
    if (numOfDocs > 0) {
        try (BackgroundIndexer indexer = new BackgroundIndexer(indexName, "_doc", client(), numOfDocs)) {
            waitForDocs(numOfDocs, indexer);
        }
        refresh(indexName);
    }
    assertHitCount(client().prepareSearch(indexName).setSize(0).get(), numOfDocs);
    ensureGreen(indexName);
    // sometimes test with a closed index
    final IndexMetadata.State indexState = randomFrom(IndexMetadata.State.OPEN, IndexMetadata.State.CLOSE);
    if (indexState == IndexMetadata.State.CLOSE) {
        CloseIndexResponse closeIndexResponse = client().admin().indices().prepareClose(indexName).get();
        assertThat("close index not acked - " + closeIndexResponse, closeIndexResponse.isAcknowledged(), equalTo(true));
        ensureGreen(indexName);
    }
    // pick up a data node that contains a random primary shard
    ClusterState state = client(internalCluster().getMasterName()).admin().cluster().prepareState().get().getState();
    final int numShards = state.metadata().index(indexName).getNumberOfShards();
    final ShardRouting primaryShard = state.routingTable().index(indexName).shard(randomIntBetween(0, numShards - 1)).primaryShard();
    final DiscoveryNode randomNode = state.nodes().resolveNode(primaryShard.currentNodeId());
    // stop the random data node, all remaining shards are promoted to primaries
    internalCluster().stopRandomNode(InternalTestCluster.nameFilter(randomNode.getName()));
    ensureYellowAndNoInitializingShards(indexName);
    state = client(internalCluster().getMasterName()).admin().cluster().prepareState().get().getState();
    for (IndexShardRoutingTable shardRoutingTable : state.routingTable().index(indexName)) {
        for (ShardRouting shardRouting : shardRoutingTable.activeShards()) {
            assertThat(shardRouting + " should be promoted as a primary", shardRouting.primary(), is(true));
        }
    }
    if (indexState == IndexMetadata.State.CLOSE) {
        assertAcked(client().admin().indices().prepareOpen(indexName));
        ensureYellowAndNoInitializingShards(indexName);
    }
    assertHitCount(client().prepareSearch(indexName).setSize(0).get(), numOfDocs);
}
Also used : ClusterState(org.opensearch.cluster.ClusterState) IndexShardRoutingTable(org.opensearch.cluster.routing.IndexShardRoutingTable) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) BackgroundIndexer(org.opensearch.test.BackgroundIndexer) CloseIndexResponse(org.opensearch.action.admin.indices.close.CloseIndexResponse) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) ShardRouting(org.opensearch.cluster.routing.ShardRouting)

Aggregations

BackgroundIndexer (org.opensearch.test.BackgroundIndexer)14 ClusterState (org.opensearch.cluster.ClusterState)5 ArrayList (java.util.ArrayList)4 CountDownLatch (java.util.concurrent.CountDownLatch)4 List (java.util.List)3 Matchers.containsString (org.hamcrest.Matchers.containsString)3 IOException (java.io.IOException)2 Arrays (java.util.Arrays)2 Collection (java.util.Collection)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 Set (java.util.Set)2 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 Collectors (java.util.stream.Collectors)2 IntStream (java.util.stream.IntStream)2 ActionRequestValidationException (org.opensearch.action.ActionRequestValidationException)2 ClusterBlockException (org.opensearch.cluster.block.ClusterBlockException)2 IndexMetadata (org.opensearch.cluster.metadata.IndexMetadata)2 DiscoveryNode (org.opensearch.cluster.node.DiscoveryNode)2 ShardRouting (org.opensearch.cluster.routing.ShardRouting)2