Search in sources :

Example 1 with IndexId

use of org.opensearch.repositories.IndexId in project OpenSearch by opensearch-project.

the class TransportGetSnapshotsAction method buildSimpleSnapshotInfos.

private List<SnapshotInfo> buildSimpleSnapshotInfos(final Set<SnapshotId> toResolve, final RepositoryData repositoryData, final List<SnapshotInfo> currentSnapshots) {
    List<SnapshotInfo> snapshotInfos = new ArrayList<>();
    for (SnapshotInfo snapshotInfo : currentSnapshots) {
        if (toResolve.remove(snapshotInfo.snapshotId())) {
            snapshotInfos.add(snapshotInfo.basic());
        }
    }
    Map<SnapshotId, List<String>> snapshotsToIndices = new HashMap<>();
    for (IndexId indexId : repositoryData.getIndices().values()) {
        for (SnapshotId snapshotId : repositoryData.getSnapshots(indexId)) {
            if (toResolve.contains(snapshotId)) {
                snapshotsToIndices.computeIfAbsent(snapshotId, (k) -> new ArrayList<>()).add(indexId.getName());
            }
        }
    }
    for (SnapshotId snapshotId : toResolve) {
        final List<String> indices = snapshotsToIndices.getOrDefault(snapshotId, Collections.emptyList());
        CollectionUtil.timSort(indices);
        snapshotInfos.add(new SnapshotInfo(snapshotId, indices, Collections.emptyList(), repositoryData.getSnapshotState(snapshotId)));
    }
    CollectionUtil.timSort(snapshotInfos);
    return unmodifiableList(snapshotInfos);
}
Also used : RepositoriesService(org.opensearch.repositories.RepositoriesService) Collections.unmodifiableList(java.util.Collections.unmodifiableList) ThreadPool(org.opensearch.threadpool.ThreadPool) SnapshotsInProgress(org.opensearch.cluster.SnapshotsInProgress) HashMap(java.util.HashMap) TransportMasterNodeAction(org.opensearch.action.support.master.TransportMasterNodeAction) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) SnapshotsService(org.opensearch.snapshots.SnapshotsService) Regex(org.opensearch.common.regex.Regex) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ClusterState(org.opensearch.cluster.ClusterState) SnapshotMissingException(org.opensearch.snapshots.SnapshotMissingException) IndexId(org.opensearch.repositories.IndexId) PlainActionFuture(org.opensearch.action.support.PlainActionFuture) SnapshotException(org.opensearch.snapshots.SnapshotException) Map(java.util.Map) Inject(org.opensearch.common.inject.Inject) ActionListener(org.opensearch.action.ActionListener) Repository(org.opensearch.repositories.Repository) StreamInput(org.opensearch.common.io.stream.StreamInput) RepositoryData(org.opensearch.repositories.RepositoryData) SnapshotId(org.opensearch.snapshots.SnapshotId) SnapshotInfo(org.opensearch.snapshots.SnapshotInfo) ClusterBlockLevel(org.opensearch.cluster.block.ClusterBlockLevel) ClusterBlockException(org.opensearch.cluster.block.ClusterBlockException) Set(java.util.Set) IOException(java.io.IOException) TransportService(org.opensearch.transport.TransportService) Collectors(java.util.stream.Collectors) Nullable(org.opensearch.common.Nullable) CollectionUtil(org.apache.lucene.util.CollectionUtil) ActionFilters(org.opensearch.action.support.ActionFilters) List(java.util.List) Logger(org.apache.logging.log4j.Logger) ClusterService(org.opensearch.cluster.service.ClusterService) LogManager(org.apache.logging.log4j.LogManager) Collections(java.util.Collections) IndexNameExpressionResolver(org.opensearch.cluster.metadata.IndexNameExpressionResolver) SnapshotId(org.opensearch.snapshots.SnapshotId) IndexId(org.opensearch.repositories.IndexId) SnapshotInfo(org.opensearch.snapshots.SnapshotInfo) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Collections.unmodifiableList(java.util.Collections.unmodifiableList) ArrayList(java.util.ArrayList) List(java.util.List)

Example 2 with IndexId

use of org.opensearch.repositories.IndexId in project OpenSearch by opensearch-project.

the class TransportSnapshotsStatusAction method snapshotShards.

/**
 * Returns status of shards currently finished snapshots
 * <p>
 * This method is executed on master node and it's complimentary to the
 * {@link SnapshotShardsService#currentSnapshotShards(Snapshot)} because it
 * returns similar information but for already finished snapshots.
 * </p>
 *
 * @param repositoryName  repository name
 * @param snapshotInfo    snapshot info
 * @return map of shard id to snapshot status
 */
private Map<ShardId, IndexShardSnapshotStatus> snapshotShards(final String repositoryName, final RepositoryData repositoryData, final SnapshotInfo snapshotInfo) throws IOException {
    final Repository repository = repositoriesService.repository(repositoryName);
    final Map<ShardId, IndexShardSnapshotStatus> shardStatus = new HashMap<>();
    for (String index : snapshotInfo.indices()) {
        IndexId indexId = repositoryData.resolveIndexId(index);
        IndexMetadata indexMetadata = repository.getSnapshotIndexMetaData(repositoryData, snapshotInfo.snapshotId(), indexId);
        if (indexMetadata != null) {
            int numberOfShards = indexMetadata.getNumberOfShards();
            for (int i = 0; i < numberOfShards; i++) {
                ShardId shardId = new ShardId(indexMetadata.getIndex(), i);
                SnapshotShardFailure shardFailure = findShardFailure(snapshotInfo.shardFailures(), shardId);
                if (shardFailure != null) {
                    shardStatus.put(shardId, IndexShardSnapshotStatus.newFailed(shardFailure.reason()));
                } else {
                    final IndexShardSnapshotStatus shardSnapshotStatus;
                    if (snapshotInfo.state() == SnapshotState.FAILED) {
                        // If the snapshot failed, but the shard's snapshot does
                        // not have an exception, it means that partial snapshots
                        // were disabled and in this case, the shard snapshot will
                        // *not* have any metadata, so attempting to read the shard
                        // snapshot status will throw an exception. Instead, we create
                        // a status for the shard to indicate that the shard snapshot
                        // could not be taken due to partial being set to false.
                        shardSnapshotStatus = IndexShardSnapshotStatus.newFailed("skipped");
                    } else {
                        shardSnapshotStatus = repository.getShardSnapshotStatus(snapshotInfo.snapshotId(), indexId, shardId);
                    }
                    shardStatus.put(shardId, shardSnapshotStatus);
                }
            }
        }
    }
    return unmodifiableMap(shardStatus);
}
Also used : ShardId(org.opensearch.index.shard.ShardId) IndexShardSnapshotStatus(org.opensearch.index.snapshots.IndexShardSnapshotStatus) IndexId(org.opensearch.repositories.IndexId) Repository(org.opensearch.repositories.Repository) SnapshotShardFailure(org.opensearch.snapshots.SnapshotShardFailure) HashMap(java.util.HashMap) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata)

Example 3 with IndexId

use of org.opensearch.repositories.IndexId in project OpenSearch by opensearch-project.

the class SharedClusterSnapshotRestoreIT method testRestoreSnapshotWithCorruptedIndexMetadata.

/**
 * Tests that a snapshot of multiple indices including one with a corrupted index metadata
 * file can still be used to restore the non corrupted indices
 */
public void testRestoreSnapshotWithCorruptedIndexMetadata() throws Exception {
    final Client client = client();
    final Path repo = randomRepoPath();
    final int nbIndices = randomIntBetween(2, 3);
    final Map<String, Integer> nbDocsPerIndex = new HashMap<>();
    for (int i = 0; i < nbIndices; i++) {
        String indexName = "test-idx-" + i;
        assertAcked(prepareCreate(indexName).setSettings(indexSettingsNoReplicas(Math.min(2, numberOfShards()))));
        int nbDocs = randomIntBetween(1, 10);
        nbDocsPerIndex.put(indexName, nbDocs);
        IndexRequestBuilder[] documents = new IndexRequestBuilder[nbDocs];
        for (int j = 0; j < nbDocs; j++) {
            documents[j] = client.prepareIndex(indexName).setSource("foo", "bar");
        }
        indexRandom(true, documents);
    }
    flushAndRefresh();
    createRepository("test-repo", "fs", repo);
    final SnapshotInfo snapshotInfo = createFullSnapshot("test-repo", "test-snap");
    assertThat(snapshotInfo.indices(), hasSize(nbIndices));
    final RepositoryData repositoryData = getRepositoryData("test-repo");
    final Map<String, IndexId> indexIds = repositoryData.getIndices();
    assertThat(indexIds.size(), equalTo(nbIndices));
    // Choose a random index from the snapshot
    final IndexId corruptedIndex = randomFrom(indexIds.values());
    final Path indexMetadataPath = repo.resolve("indices").resolve(corruptedIndex.getId()).resolve("meta-" + repositoryData.indexMetaDataGenerations().indexMetaBlobId(snapshotInfo.snapshotId(), corruptedIndex) + ".dat");
    // Truncate the index metadata file
    try (SeekableByteChannel outChan = Files.newByteChannel(indexMetadataPath, StandardOpenOption.WRITE)) {
        outChan.truncate(randomInt(10));
    }
    List<SnapshotInfo> snapshotInfos = clusterAdmin().prepareGetSnapshots("test-repo").get().getSnapshots();
    assertThat(snapshotInfos.size(), equalTo(1));
    assertThat(snapshotInfos.get(0).state(), equalTo(SnapshotState.SUCCESS));
    assertThat(snapshotInfos.get(0).snapshotId().getName(), equalTo("test-snap"));
    assertAcked(client().admin().indices().prepareDelete(nbDocsPerIndex.keySet().toArray(new String[nbDocsPerIndex.size()])));
    Predicate<String> isRestorableIndex = index -> corruptedIndex.getName().equals(index) == false;
    clusterAdmin().prepareRestoreSnapshot("test-repo", "test-snap").setIndices(nbDocsPerIndex.keySet().stream().filter(isRestorableIndex).toArray(String[]::new)).setRestoreGlobalState(randomBoolean()).setWaitForCompletion(true).get();
    ensureGreen();
    for (Map.Entry<String, Integer> entry : nbDocsPerIndex.entrySet()) {
        if (isRestorableIndex.test(entry.getKey())) {
            assertHitCount(client().prepareSearch(entry.getKey()).setSize(0).get(), entry.getValue().longValue());
        }
    }
    assertAcked(startDeleteSnapshot("test-repo", snapshotInfo.snapshotId().getName()).get());
}
Also used : Path(java.nio.file.Path) IndexRequestBuilder(org.opensearch.action.index.IndexRequestBuilder) Arrays(java.util.Arrays) SnapshotIndexShardStatus(org.opensearch.action.admin.cluster.snapshots.status.SnapshotIndexShardStatus) BlobStoreRepository(org.opensearch.repositories.blobstore.BlobStoreRepository) ClusterStateResponse(org.opensearch.action.admin.cluster.state.ClusterStateResponse) Matchers.not(org.hamcrest.Matchers.not) ByteSizeUnit(org.opensearch.common.unit.ByteSizeUnit) SETTING_ALLOCATION_MAX_RETRY(org.opensearch.cluster.routing.allocation.decider.MaxRetryAllocationDecider.SETTING_ALLOCATION_MAX_RETRY) Version(org.opensearch.Version) OpenSearchException(org.opensearch.OpenSearchException) SnapshotsStatusResponse(org.opensearch.action.admin.cluster.snapshots.status.SnapshotsStatusResponse) MapperService(org.opensearch.index.mapper.MapperService) IndexId(org.opensearch.repositories.IndexId) OpenSearchAssertions.assertHitCount(org.opensearch.test.hamcrest.OpenSearchAssertions.assertHitCount) SnapshotStatus(org.opensearch.action.admin.cluster.snapshots.status.SnapshotStatus) Map(java.util.Map) Matchers.nullValue(org.hamcrest.Matchers.nullValue) UnassignedInfo(org.opensearch.cluster.routing.UnassignedInfo) Path(java.nio.file.Path) RepositoryException(org.opensearch.repositories.RepositoryException) OpenSearchAssertions.assertRequestBuilderThrows(org.opensearch.test.hamcrest.OpenSearchAssertions.assertRequestBuilderThrows) Client(org.opensearch.client.Client) EngineTestCase(org.opensearch.index.engine.EngineTestCase) TimeValue(org.opensearch.common.unit.TimeValue) OpenSearchAssertions.assertNoFailures(org.opensearch.test.hamcrest.OpenSearchAssertions.assertNoFailures) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) BytesRef(org.apache.lucene.util.BytesRef) Index(org.opensearch.index.Index) Predicate(java.util.function.Predicate) IndicesService(org.opensearch.indices.IndicesService) StandardOpenOption(java.nio.file.StandardOpenOption) ExceptionsHelper(org.opensearch.ExceptionsHelper) SnapshotIndexShardStage(org.opensearch.action.admin.cluster.snapshots.status.SnapshotIndexShardStage) Settings(org.opensearch.common.settings.Settings) MockRepository(org.opensearch.snapshots.mockstore.MockRepository) Engine(org.opensearch.index.engine.Engine) SeekableByteChannel(java.nio.channels.SeekableByteChannel) List(java.util.List) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) Matchers.equalTo(org.hamcrest.Matchers.equalTo) IndicesStatsResponse(org.opensearch.action.admin.indices.stats.IndicesStatsResponse) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) Matchers.is(org.hamcrest.Matchers.is) State(org.opensearch.cluster.SnapshotsInProgress.State) Matchers.anyOf(org.hamcrest.Matchers.anyOf) Matchers.containsString(org.hamcrest.Matchers.containsString) Matchers.endsWith(org.hamcrest.Matchers.endsWith) INDICES_RECOVERY_MAX_BYTES_PER_SEC_SETTING(org.opensearch.indices.recovery.RecoverySettings.INDICES_RECOVERY_MAX_BYTES_PER_SEC_SETTING) FlushResponse(org.opensearch.action.admin.indices.flush.FlushResponse) RepositoriesService(org.opensearch.repositories.RepositoriesService) IntStream(java.util.stream.IntStream) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) SnapshotIndexStatus(org.opensearch.action.admin.cluster.snapshots.status.SnapshotIndexStatus) ThreadPool(org.opensearch.threadpool.ThreadPool) HashMap(java.util.HashMap) IndicesOptions(org.opensearch.action.support.IndicesOptions) ArrayList(java.util.ArrayList) RecoverySource(org.opensearch.cluster.routing.RecoverySource) RestoreSnapshotResponse(org.opensearch.action.admin.cluster.snapshots.restore.RestoreSnapshotResponse) IndexRoutingTable(org.opensearch.cluster.routing.IndexRoutingTable) ClusterState(org.opensearch.cluster.ClusterState) IndexShard(org.opensearch.index.shard.IndexShard) Numbers(org.opensearch.common.Numbers) ShardRoutingState(org.opensearch.cluster.routing.ShardRoutingState) Matchers.lessThan(org.hamcrest.Matchers.lessThan) Matchers.hasSize(org.hamcrest.Matchers.hasSize) MetadataIndexStateService(org.opensearch.cluster.metadata.MetadataIndexStateService) OpenSearchAssertions.assertAcked(org.opensearch.test.hamcrest.OpenSearchAssertions.assertAcked) RepositoryData(org.opensearch.repositories.RepositoryData) CreateSnapshotResponse(org.opensearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse) Matchers.empty(org.hamcrest.Matchers.empty) Files(java.nio.file.Files) IndexService(org.opensearch.index.IndexService) ActionFuture(org.opensearch.action.ActionFuture) ActiveShardCount(org.opensearch.action.support.ActiveShardCount) ShardRouting(org.opensearch.cluster.routing.ShardRouting) ShardId(org.opensearch.index.shard.ShardId) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) OpenSearchAssertions.assertAllSuccessful(org.opensearch.test.hamcrest.OpenSearchAssertions.assertAllSuccessful) ClusterService(org.opensearch.cluster.service.ClusterService) RestoreInProgress(org.opensearch.cluster.RestoreInProgress) SETTING_NUMBER_OF_SHARDS(org.opensearch.cluster.metadata.IndexMetadata.SETTING_NUMBER_OF_SHARDS) ShardStats(org.opensearch.action.admin.indices.stats.ShardStats) GetSnapshotsResponse(org.opensearch.action.admin.cluster.snapshots.get.GetSnapshotsResponse) Collections(java.util.Collections) IndexShardTests.getEngineFromShard(org.opensearch.index.shard.IndexShardTests.getEngineFromShard) IndexId(org.opensearch.repositories.IndexId) HashMap(java.util.HashMap) Matchers.containsString(org.hamcrest.Matchers.containsString) RepositoryData(org.opensearch.repositories.RepositoryData) IndexRequestBuilder(org.opensearch.action.index.IndexRequestBuilder) SeekableByteChannel(java.nio.channels.SeekableByteChannel) Client(org.opensearch.client.Client) Map(java.util.Map) HashMap(java.util.HashMap)

Example 4 with IndexId

use of org.opensearch.repositories.IndexId in project OpenSearch by opensearch-project.

the class CorruptedBlobStoreRepositoryIT method testHandleSnapshotErrorWithBwCFormat.

public void testHandleSnapshotErrorWithBwCFormat() throws IOException, ExecutionException, InterruptedException {
    final String repoName = "test-repo";
    final Path repoPath = randomRepoPath();
    createRepository(repoName, "fs", repoPath);
    final String oldVersionSnapshot = initWithSnapshotVersion(repoName, repoPath, SnapshotsService.OLD_SNAPSHOT_FORMAT);
    logger.info("--> recreating repository to clear caches");
    client().admin().cluster().prepareDeleteRepository(repoName).get();
    createRepository(repoName, "fs", repoPath);
    final String indexName = "test-index";
    createIndex(indexName);
    createFullSnapshot(repoName, "snapshot-1");
    // In the old metadata version the shard level metadata could be moved to the next generation for all sorts of reasons, this should
    // not break subsequent repository operations
    logger.info("--> move shard level metadata to new generation");
    final IndexId indexId = getRepositoryData(repoName).resolveIndexId(indexName);
    final Path shardPath = repoPath.resolve("indices").resolve(indexId.getId()).resolve("0");
    final Path initialShardMetaPath = shardPath.resolve(BlobStoreRepository.INDEX_FILE_PREFIX + "0");
    assertFileExists(initialShardMetaPath);
    Files.move(initialShardMetaPath, shardPath.resolve(BlobStoreRepository.INDEX_FILE_PREFIX + "1"));
    startDeleteSnapshot(repoName, oldVersionSnapshot).get();
    createFullSnapshot(repoName, "snapshot-2");
}
Also used : Path(java.nio.file.Path) IndexId(org.opensearch.repositories.IndexId) Matchers.containsString(org.hamcrest.Matchers.containsString)

Example 5 with IndexId

use of org.opensearch.repositories.IndexId in project OpenSearch by opensearch-project.

the class CorruptedBlobStoreRepositoryIT method testDeleteSnapshotWithMissingIndexAndShardMetadata.

public void testDeleteSnapshotWithMissingIndexAndShardMetadata() throws Exception {
    Client client = client();
    Path repo = randomRepoPath();
    createRepository("test-repo", "fs", repo);
    final String[] indices = { "test-idx-1", "test-idx-2" };
    createIndex(indices);
    logger.info("--> indexing some data");
    indexRandom(true, client().prepareIndex("test-idx-1").setSource("foo", "bar"), client().prepareIndex("test-idx-2").setSource("foo", "bar"));
    logger.info("--> creating snapshot");
    CreateSnapshotResponse createSnapshotResponse = client.admin().cluster().prepareCreateSnapshot("test-repo", "test-snap-1").setWaitForCompletion(true).setIndices(indices).get();
    final SnapshotInfo snapshotInfo = createSnapshotResponse.getSnapshotInfo();
    assertThat(snapshotInfo.successfulShards(), greaterThan(0));
    assertThat(snapshotInfo.successfulShards(), equalTo(snapshotInfo.totalShards()));
    final Map<String, IndexId> indexIds = getRepositoryData("test-repo").getIndices();
    final Path indicesPath = repo.resolve("indices");
    logger.info("--> delete index metadata and shard metadata");
    for (String index : indices) {
        Path shardZero = indicesPath.resolve(indexIds.get(index).getId()).resolve("0");
        if (randomBoolean()) {
            Files.delete(shardZero.resolve("index-" + getRepositoryData("test-repo").shardGenerations().getShardGen(indexIds.get(index), 0)));
        }
        Files.delete(shardZero.resolve("snap-" + snapshotInfo.snapshotId().getUUID() + ".dat"));
    }
    startDeleteSnapshot("test-repo", "test-snap-1").get();
    logger.info("--> make sure snapshot doesn't exist");
    expectThrows(SnapshotMissingException.class, () -> client.admin().cluster().prepareGetSnapshots("test-repo").addSnapshots("test-snap-1").get());
    for (String index : indices) {
        assertTrue(Files.notExists(indicesPath.resolve(indexIds.get(index).getId())));
    }
}
Also used : Path(java.nio.file.Path) IndexId(org.opensearch.repositories.IndexId) CreateSnapshotResponse(org.opensearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse) Matchers.containsString(org.hamcrest.Matchers.containsString) Client(org.opensearch.client.Client)

Aggregations

IndexId (org.opensearch.repositories.IndexId)65 ShardId (org.opensearch.index.shard.ShardId)37 ClusterState (org.opensearch.cluster.ClusterState)36 IndexMetadata (org.opensearch.cluster.metadata.IndexMetadata)31 Metadata (org.opensearch.cluster.metadata.Metadata)27 SnapshotsInProgress (org.opensearch.cluster.SnapshotsInProgress)26 RepositoryData (org.opensearch.repositories.RepositoryData)25 SnapshotId (org.opensearch.snapshots.SnapshotId)25 Repository (org.opensearch.repositories.Repository)24 List (java.util.List)23 Map (java.util.Map)23 Version (org.opensearch.Version)23 DiscoveryNode (org.opensearch.cluster.node.DiscoveryNode)23 Collections (java.util.Collections)22 Collectors (java.util.stream.Collectors)21 RepositoryShardId (org.opensearch.repositories.RepositoryShardId)21 ThreadPool (org.opensearch.threadpool.ThreadPool)21 IOException (java.io.IOException)20 ClusterService (org.opensearch.cluster.service.ClusterService)20 Settings (org.opensearch.common.settings.Settings)20