Search in sources :

Example 21 with Repository

use of org.elasticsearch.repositories.Repository in project elasticsearch by elastic.

the class IndexShard method startRecovery.

public void startRecovery(RecoveryState recoveryState, PeerRecoveryTargetService recoveryTargetService, PeerRecoveryTargetService.RecoveryListener recoveryListener, RepositoriesService repositoriesService, BiConsumer<String, MappingMetaData> mappingUpdateConsumer, IndicesService indicesService) {
    // }
    assert recoveryState.getRecoverySource().equals(shardRouting.recoverySource());
    switch(recoveryState.getRecoverySource().getType()) {
        case EMPTY_STORE:
        case EXISTING_STORE:
            // mark the shard as recovering on the cluster state thread
            markAsRecovering("from store", recoveryState);
            threadPool.generic().execute(() -> {
                try {
                    if (recoverFromStore()) {
                        recoveryListener.onRecoveryDone(recoveryState);
                    }
                } catch (Exception e) {
                    recoveryListener.onRecoveryFailure(recoveryState, new RecoveryFailedException(recoveryState, null, e), true);
                }
            });
            break;
        case PEER:
            try {
                markAsRecovering("from " + recoveryState.getSourceNode(), recoveryState);
                recoveryTargetService.startRecovery(this, recoveryState.getSourceNode(), recoveryListener);
            } catch (Exception e) {
                failShard("corrupted preexisting index", e);
                recoveryListener.onRecoveryFailure(recoveryState, new RecoveryFailedException(recoveryState, null, e), true);
            }
            break;
        case SNAPSHOT:
            // mark the shard as recovering on the cluster state thread
            markAsRecovering("from snapshot", recoveryState);
            SnapshotRecoverySource recoverySource = (SnapshotRecoverySource) recoveryState.getRecoverySource();
            threadPool.generic().execute(() -> {
                try {
                    final Repository repository = repositoriesService.repository(recoverySource.snapshot().getRepository());
                    if (restoreFromRepository(repository)) {
                        recoveryListener.onRecoveryDone(recoveryState);
                    }
                } catch (Exception e) {
                    recoveryListener.onRecoveryFailure(recoveryState, new RecoveryFailedException(recoveryState, null, e), true);
                }
            });
            break;
        case LOCAL_SHARDS:
            final IndexMetaData indexMetaData = indexSettings().getIndexMetaData();
            final Index mergeSourceIndex = indexMetaData.getMergeSourceIndex();
            final List<IndexShard> startedShards = new ArrayList<>();
            final IndexService sourceIndexService = indicesService.indexService(mergeSourceIndex);
            final int numShards = sourceIndexService != null ? sourceIndexService.getIndexSettings().getNumberOfShards() : -1;
            if (sourceIndexService != null) {
                for (IndexShard shard : sourceIndexService) {
                    if (shard.state() == IndexShardState.STARTED) {
                        startedShards.add(shard);
                    }
                }
            }
            if (numShards == startedShards.size()) {
                // mark the shard as recovering on the cluster state thread
                markAsRecovering("from local shards", recoveryState);
                threadPool.generic().execute(() -> {
                    try {
                        final Set<ShardId> shards = IndexMetaData.selectShrinkShards(shardId().id(), sourceIndexService.getMetaData(), +indexMetaData.getNumberOfShards());
                        if (recoverFromLocalShards(mappingUpdateConsumer, startedShards.stream().filter((s) -> shards.contains(s.shardId())).collect(Collectors.toList()))) {
                            recoveryListener.onRecoveryDone(recoveryState);
                        }
                    } catch (Exception e) {
                        recoveryListener.onRecoveryFailure(recoveryState, new RecoveryFailedException(recoveryState, null, e), true);
                    }
                });
            } else {
                final RuntimeException e;
                if (numShards == -1) {
                    e = new IndexNotFoundException(mergeSourceIndex);
                } else {
                    e = new IllegalStateException("not all shards from index " + mergeSourceIndex + " are started yet, expected " + numShards + " found " + startedShards.size() + " can't recover shard " + shardId());
                }
                throw e;
            }
            break;
        default:
            throw new IllegalArgumentException("Unknown recovery source " + recoveryState.getRecoverySource());
    }
}
Also used : IndexService(org.elasticsearch.index.IndexService) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) CheckIndex(org.apache.lucene.index.CheckIndex) Index(org.elasticsearch.index.Index) IndexFormatTooNewException(org.apache.lucene.index.IndexFormatTooNewException) AlreadyClosedException(org.apache.lucene.store.AlreadyClosedException) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) ClosedByInterruptException(java.nio.channels.ClosedByInterruptException) ThreadInterruptedException(org.apache.lucene.util.ThreadInterruptedException) RecoveryFailedException(org.elasticsearch.indices.recovery.RecoveryFailedException) EngineException(org.elasticsearch.index.engine.EngineException) IOException(java.io.IOException) ElasticsearchException(org.elasticsearch.ElasticsearchException) NoSuchFileException(java.nio.file.NoSuchFileException) TimeoutException(java.util.concurrent.TimeoutException) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) RefreshFailedEngineException(org.elasticsearch.index.engine.RefreshFailedEngineException) FileNotFoundException(java.io.FileNotFoundException) IndexFormatTooOldException(org.apache.lucene.index.IndexFormatTooOldException) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) Repository(org.elasticsearch.repositories.Repository) SnapshotRecoverySource(org.elasticsearch.cluster.routing.RecoverySource.SnapshotRecoverySource) RecoveryFailedException(org.elasticsearch.indices.recovery.RecoveryFailedException) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException)

Example 22 with Repository

use of org.elasticsearch.repositories.Repository in project elasticsearch by elastic.

the class SnapshotsService 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
     */
public Map<ShardId, IndexShardSnapshotStatus> snapshotShards(final String repositoryName, final SnapshotInfo snapshotInfo) throws IOException {
    Map<ShardId, IndexShardSnapshotStatus> shardStatus = new HashMap<>();
    Repository repository = repositoriesService.repository(repositoryName);
    RepositoryData repositoryData = repository.getRepositoryData();
    MetaData metaData = repository.getSnapshotMetaData(snapshotInfo, repositoryData.resolveIndices(snapshotInfo.indices()));
    for (String index : snapshotInfo.indices()) {
        IndexId indexId = repositoryData.resolveIndexId(index);
        IndexMetaData indexMetaData = metaData.indices().get(index);
        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) {
                    IndexShardSnapshotStatus shardSnapshotStatus = new IndexShardSnapshotStatus();
                    shardSnapshotStatus.updateStage(IndexShardSnapshotStatus.Stage.FAILURE);
                    shardSnapshotStatus.failure(shardFailure.reason());
                    shardStatus.put(shardId, shardSnapshotStatus);
                } else {
                    IndexShardSnapshotStatus shardSnapshotStatus = repository.getShardSnapshotStatus(snapshotInfo.snapshotId(), snapshotInfo.version(), indexId, shardId);
                    shardStatus.put(shardId, shardSnapshotStatus);
                }
            }
        }
    }
    return unmodifiableMap(shardStatus);
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) IndexShardSnapshotStatus(org.elasticsearch.index.snapshots.IndexShardSnapshotStatus) IndexId(org.elasticsearch.repositories.IndexId) Repository(org.elasticsearch.repositories.Repository) HashMap(java.util.HashMap) MetaData(org.elasticsearch.cluster.metadata.MetaData) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) RepositoriesMetaData(org.elasticsearch.cluster.metadata.RepositoriesMetaData) RepositoryData(org.elasticsearch.repositories.RepositoryData) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData)

Example 23 with Repository

use of org.elasticsearch.repositories.Repository in project elasticsearch by elastic.

the class SnapshotsService method deleteSnapshot.

/**
     * Deletes a snapshot from the repository, looking up the {@link Snapshot} reference before deleting.
     * If the snapshot is still running cancels the snapshot first and then deletes it from the repository.
     *
     * @param repositoryName  repositoryName
     * @param snapshotName    snapshotName
     * @param listener        listener
     */
public void deleteSnapshot(final String repositoryName, final String snapshotName, final DeleteSnapshotListener listener, final boolean immediatePriority) {
    // First, look for the snapshot in the repository
    final Repository repository = repositoriesService.repository(repositoryName);
    final RepositoryData repositoryData = repository.getRepositoryData();
    final Optional<SnapshotId> incompatibleSnapshotId = repositoryData.getIncompatibleSnapshotIds().stream().filter(s -> snapshotName.equals(s.getName())).findFirst();
    if (incompatibleSnapshotId.isPresent()) {
        throw new SnapshotException(repositoryName, snapshotName, "cannot delete incompatible snapshot");
    }
    Optional<SnapshotId> matchedEntry = repositoryData.getSnapshotIds().stream().filter(s -> s.getName().equals(snapshotName)).findFirst();
    // if nothing found by the same name, then look in the cluster state for current in progress snapshots
    if (matchedEntry.isPresent() == false) {
        matchedEntry = currentSnapshots(repositoryName, Collections.emptyList()).stream().map(e -> e.snapshot().getSnapshotId()).filter(s -> s.getName().equals(snapshotName)).findFirst();
    }
    if (matchedEntry.isPresent() == false) {
        throw new SnapshotMissingException(repositoryName, snapshotName);
    }
    deleteSnapshot(new Snapshot(repositoryName, matchedEntry.get()), listener, repositoryData.getGenId(), immediatePriority);
}
Also used : MetaData(org.elasticsearch.cluster.metadata.MetaData) ShardId(org.elasticsearch.index.shard.ShardId) Arrays(java.util.Arrays) Nullable(org.elasticsearch.common.Nullable) ObjectObjectCursor(com.carrotsearch.hppc.cursors.ObjectObjectCursor) ClusterState(org.elasticsearch.cluster.ClusterState) ClusterStateUpdateTask(org.elasticsearch.cluster.ClusterStateUpdateTask) Settings(org.elasticsearch.common.settings.Settings) RestoreInProgress(org.elasticsearch.cluster.RestoreInProgress) Locale(java.util.Locale) Map(java.util.Map) IndicesOptions(org.elasticsearch.action.support.IndicesOptions) ThreadPool(org.elasticsearch.threadpool.ThreadPool) Priority(org.elasticsearch.common.Priority) ShardSearchFailure(org.elasticsearch.action.search.ShardSearchFailure) SnapshotDeletionsInProgress(org.elasticsearch.cluster.SnapshotDeletionsInProgress) UUIDs(org.elasticsearch.common.UUIDs) Set(java.util.Set) State(org.elasticsearch.cluster.SnapshotsInProgress.State) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable) ObjectCursor(com.carrotsearch.hppc.cursors.ObjectCursor) ClusterChangedEvent(org.elasticsearch.cluster.ClusterChangedEvent) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) Supplier(org.apache.logging.log4j.util.Supplier) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) RepositoryMissingException(org.elasticsearch.repositories.RepositoryMissingException) Optional(java.util.Optional) ShardSnapshotStatus(org.elasticsearch.cluster.SnapshotsInProgress.ShardSnapshotStatus) RepositoryData(org.elasticsearch.repositories.RepositoryData) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) SearchShardTarget(org.elasticsearch.search.SearchShardTarget) ImmutableOpenMap(org.elasticsearch.common.collect.ImmutableOpenMap) ClusterService(org.elasticsearch.cluster.service.ClusterService) IndexShardSnapshotStatus(org.elasticsearch.index.snapshots.IndexShardSnapshotStatus) HashMap(java.util.HashMap) Index(org.elasticsearch.index.Index) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) IndexId(org.elasticsearch.repositories.IndexId) SnapshotsInProgress.completed(org.elasticsearch.cluster.SnapshotsInProgress.completed) Strings(org.elasticsearch.common.Strings) Inject(org.elasticsearch.common.inject.Inject) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) TimeValue(org.elasticsearch.common.unit.TimeValue) ClusterStateApplier(org.elasticsearch.cluster.ClusterStateApplier) RepositoriesMetaData(org.elasticsearch.cluster.metadata.RepositoriesMetaData) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) Repository(org.elasticsearch.repositories.Repository) IOException(java.io.IOException) RepositoriesService(org.elasticsearch.repositories.RepositoriesService) AbstractLifecycleComponent(org.elasticsearch.common.component.AbstractLifecycleComponent) CollectionUtil(org.apache.lucene.util.CollectionUtil) ExceptionsHelper(org.elasticsearch.ExceptionsHelper) RoutingTable(org.elasticsearch.cluster.routing.RoutingTable) SnapshotsInProgress(org.elasticsearch.cluster.SnapshotsInProgress) Collections.unmodifiableMap(java.util.Collections.unmodifiableMap) IndexNameExpressionResolver(org.elasticsearch.cluster.metadata.IndexNameExpressionResolver) Tuple(org.elasticsearch.common.collect.Tuple) Collections(java.util.Collections) ActionListener(org.elasticsearch.action.ActionListener) Repository(org.elasticsearch.repositories.Repository) RepositoryData(org.elasticsearch.repositories.RepositoryData)

Example 24 with Repository

use of org.elasticsearch.repositories.Repository in project crate by crate.

the class SnapshotRestoreIntegrationTest method getRepositoryData.

private RepositoryData getRepositoryData() throws Exception {
    RepositoriesService service = internalCluster().getInstance(RepositoriesService.class, internalCluster().getMasterName());
    Repository repository = service.repository(REPOSITORY_NAME);
    ThreadPool threadPool = internalCluster().getInstance(ThreadPool.class, internalCluster().getMasterName());
    final SetOnce<RepositoryData> repositoryData = new SetOnce<>();
    final CountDownLatch latch = new CountDownLatch(1);
    threadPool.executor(ThreadPool.Names.SNAPSHOT).execute(() -> {
        repositoryData.set(ESBlobStoreTestCase.getRepositoryData(repository));
        latch.countDown();
    });
    latch.await();
    return repositoryData.get();
}
Also used : Repository(org.elasticsearch.repositories.Repository) SetOnce(org.apache.lucene.util.SetOnce) RepositoriesService(org.elasticsearch.repositories.RepositoriesService) ThreadPool(org.elasticsearch.threadpool.ThreadPool) CountDownLatch(java.util.concurrent.CountDownLatch) RepositoryData(org.elasticsearch.repositories.RepositoryData)

Example 25 with Repository

use of org.elasticsearch.repositories.Repository in project crate by crate.

the class SnapshotShardsService method snapshot.

/**
 * Creates shard snapshot
 *
 * @param snapshot       snapshot
 * @param snapshotStatus snapshot status
 */
private void snapshot(final ShardId shardId, final Snapshot snapshot, final IndexId indexId, final IndexShardSnapshotStatus snapshotStatus, boolean writeShardGens, ActionListener<String> listener) {
    try {
        final IndexShard indexShard = indicesService.indexServiceSafe(shardId.getIndex()).getShardOrNull(shardId.id());
        if (indexShard.routingEntry().primary() == false) {
            throw new IndexShardSnapshotFailedException(shardId, "snapshot should be performed only on primary");
        }
        if (indexShard.routingEntry().relocating()) {
            // do not snapshot when in the process of relocation of primaries so we won't get conflicts
            throw new IndexShardSnapshotFailedException(shardId, "cannot snapshot while relocating");
        }
        final IndexShardState indexShardState = indexShard.state();
        if (indexShardState == IndexShardState.CREATED || indexShardState == IndexShardState.RECOVERING) {
            // shard has just been created, or still recovering
            throw new IndexShardSnapshotFailedException(shardId, "shard didn't fully recover yet");
        }
        final Repository repository = repositoriesService.repository(snapshot.getRepository());
        Engine.IndexCommitRef snapshotRef = null;
        try {
            // we flush first to make sure we get the latest writes snapshotted
            snapshotRef = indexShard.acquireLastIndexCommit(true);
            repository.snapshotShard(indexShard.store(), indexShard.mapperService(), snapshot.getSnapshotId(), indexId, snapshotRef.getIndexCommit(), snapshotStatus, writeShardGens, ActionListener.runBefore(listener, snapshotRef::close));
        } catch (Exception e) {
            IOUtils.close(snapshotRef);
            throw e;
        }
    } catch (Exception e) {
        listener.onFailure(e);
    }
}
Also used : Repository(org.elasticsearch.repositories.Repository) IndexShard(org.elasticsearch.index.shard.IndexShard) IndexShardSnapshotFailedException(org.elasticsearch.index.snapshots.IndexShardSnapshotFailedException) IndexShardState(org.elasticsearch.index.shard.IndexShardState) Engine(org.elasticsearch.index.engine.Engine) IndexShardSnapshotFailedException(org.elasticsearch.index.snapshots.IndexShardSnapshotFailedException) TransportException(org.elasticsearch.transport.TransportException) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException) IOException(java.io.IOException)

Aggregations

Repository (org.elasticsearch.repositories.Repository)33 RepositoryData (org.elasticsearch.repositories.RepositoryData)21 ArrayList (java.util.ArrayList)20 ShardId (org.elasticsearch.index.shard.ShardId)20 ParameterizedMessage (org.apache.logging.log4j.message.ParameterizedMessage)18 List (java.util.List)17 Collectors (java.util.stream.Collectors)17 ClusterState (org.elasticsearch.cluster.ClusterState)17 ClusterStateUpdateTask (org.elasticsearch.cluster.ClusterStateUpdateTask)17 IndexId (org.elasticsearch.repositories.IndexId)17 IOException (java.io.IOException)16 Collections (java.util.Collections)16 Set (java.util.Set)16 ActionListener (org.elasticsearch.action.ActionListener)16 ClusterService (org.elasticsearch.cluster.service.ClusterService)16 UUIDs (org.elasticsearch.common.UUIDs)16 Index (org.elasticsearch.index.Index)16 Settings (org.elasticsearch.common.settings.Settings)15 Map (java.util.Map)14 Logger (org.apache.logging.log4j.Logger)14