Search in sources :

Example 1 with RestoreInProgress

use of org.elasticsearch.cluster.RestoreInProgress in project elasticsearch by elastic.

the class RestoreService method restoreSnapshot.

/**
     * Restores snapshot specified in the restore request.
     *
     * @param request  restore request
     * @param listener restore listener
     */
public void restoreSnapshot(final RestoreRequest request, final ActionListener<RestoreCompletionResponse> listener) {
    try {
        // Read snapshot info and metadata from the repository
        Repository repository = repositoriesService.repository(request.repositoryName);
        final RepositoryData repositoryData = repository.getRepositoryData();
        final Optional<SnapshotId> incompatibleSnapshotId = repositoryData.getIncompatibleSnapshotIds().stream().filter(s -> request.snapshotName.equals(s.getName())).findFirst();
        if (incompatibleSnapshotId.isPresent()) {
            throw new SnapshotRestoreException(request.repositoryName, request.snapshotName, "cannot restore incompatible snapshot");
        }
        final Optional<SnapshotId> matchingSnapshotId = repositoryData.getSnapshotIds().stream().filter(s -> request.snapshotName.equals(s.getName())).findFirst();
        if (matchingSnapshotId.isPresent() == false) {
            throw new SnapshotRestoreException(request.repositoryName, request.snapshotName, "snapshot does not exist");
        }
        final SnapshotId snapshotId = matchingSnapshotId.get();
        final SnapshotInfo snapshotInfo = repository.getSnapshotInfo(snapshotId);
        final Snapshot snapshot = new Snapshot(request.repositoryName, snapshotId);
        List<String> filteredIndices = SnapshotUtils.filterIndices(snapshotInfo.indices(), request.indices(), request.indicesOptions());
        MetaData metaData = repository.getSnapshotMetaData(snapshotInfo, repositoryData.resolveIndices(filteredIndices));
        // Make sure that we can restore from this snapshot
        validateSnapshotRestorable(request.repositoryName, snapshotInfo);
        // Find list of indices that we need to restore
        final Map<String, String> renamedIndices = renamedIndices(request, filteredIndices);
        // Now we can start the actual restore process by adding shards to be recovered in the cluster state
        // and updating cluster metadata (global and index) as needed
        clusterService.submitStateUpdateTask(request.cause(), new ClusterStateUpdateTask() {

            RestoreInfo restoreInfo = null;

            @Override
            public ClusterState execute(ClusterState currentState) {
                // Check if another restore process is already running - cannot run two restore processes at the
                // same time
                RestoreInProgress restoreInProgress = currentState.custom(RestoreInProgress.TYPE);
                if (restoreInProgress != null && !restoreInProgress.entries().isEmpty()) {
                    throw new ConcurrentSnapshotExecutionException(snapshot, "Restore process is already running in this cluster");
                }
                // Check if the snapshot to restore is currently being deleted
                SnapshotDeletionsInProgress deletionsInProgress = currentState.custom(SnapshotDeletionsInProgress.TYPE);
                if (deletionsInProgress != null && deletionsInProgress.hasDeletionsInProgress()) {
                    throw new ConcurrentSnapshotExecutionException(snapshot, "cannot restore a snapshot while a snapshot deletion is in-progress [" + deletionsInProgress.getEntries().get(0).getSnapshot() + "]");
                }
                // Updating cluster state
                ClusterState.Builder builder = ClusterState.builder(currentState);
                MetaData.Builder mdBuilder = MetaData.builder(currentState.metaData());
                ClusterBlocks.Builder blocks = ClusterBlocks.builder().blocks(currentState.blocks());
                RoutingTable.Builder rtBuilder = RoutingTable.builder(currentState.routingTable());
                ImmutableOpenMap<ShardId, RestoreInProgress.ShardRestoreStatus> shards;
                Set<String> aliases = new HashSet<>();
                if (!renamedIndices.isEmpty()) {
                    // We have some indices to restore
                    ImmutableOpenMap.Builder<ShardId, RestoreInProgress.ShardRestoreStatus> shardsBuilder = ImmutableOpenMap.builder();
                    final Version minIndexCompatibilityVersion = currentState.getNodes().getMaxNodeVersion().minimumIndexCompatibilityVersion();
                    for (Map.Entry<String, String> indexEntry : renamedIndices.entrySet()) {
                        String index = indexEntry.getValue();
                        boolean partial = checkPartial(index);
                        SnapshotRecoverySource recoverySource = new SnapshotRecoverySource(snapshot, snapshotInfo.version(), index);
                        String renamedIndexName = indexEntry.getKey();
                        IndexMetaData snapshotIndexMetaData = metaData.index(index);
                        snapshotIndexMetaData = updateIndexSettings(snapshotIndexMetaData, request.indexSettings, request.ignoreIndexSettings);
                        try {
                            snapshotIndexMetaData = metaDataIndexUpgradeService.upgradeIndexMetaData(snapshotIndexMetaData, minIndexCompatibilityVersion);
                        } catch (Exception ex) {
                            throw new SnapshotRestoreException(snapshot, "cannot restore index [" + index + "] because it cannot be upgraded", ex);
                        }
                        // Check that the index is closed or doesn't exist
                        IndexMetaData currentIndexMetaData = currentState.metaData().index(renamedIndexName);
                        IntSet ignoreShards = new IntHashSet();
                        final Index renamedIndex;
                        if (currentIndexMetaData == null) {
                            // Index doesn't exist - create it and start recovery
                            // Make sure that the index we are about to create has a validate name
                            MetaDataCreateIndexService.validateIndexName(renamedIndexName, currentState);
                            createIndexService.validateIndexSettings(renamedIndexName, snapshotIndexMetaData.getSettings());
                            IndexMetaData.Builder indexMdBuilder = IndexMetaData.builder(snapshotIndexMetaData).state(IndexMetaData.State.OPEN).index(renamedIndexName);
                            indexMdBuilder.settings(Settings.builder().put(snapshotIndexMetaData.getSettings()).put(IndexMetaData.SETTING_INDEX_UUID, UUIDs.randomBase64UUID()));
                            if (!request.includeAliases() && !snapshotIndexMetaData.getAliases().isEmpty()) {
                                // Remove all aliases - they shouldn't be restored
                                indexMdBuilder.removeAllAliases();
                            } else {
                                for (ObjectCursor<String> alias : snapshotIndexMetaData.getAliases().keys()) {
                                    aliases.add(alias.value);
                                }
                            }
                            IndexMetaData updatedIndexMetaData = indexMdBuilder.build();
                            if (partial) {
                                populateIgnoredShards(index, ignoreShards);
                            }
                            rtBuilder.addAsNewRestore(updatedIndexMetaData, recoverySource, ignoreShards);
                            blocks.addBlocks(updatedIndexMetaData);
                            mdBuilder.put(updatedIndexMetaData, true);
                            renamedIndex = updatedIndexMetaData.getIndex();
                        } else {
                            validateExistingIndex(currentIndexMetaData, snapshotIndexMetaData, renamedIndexName, partial);
                            // Index exists and it's closed - open it in metadata and start recovery
                            IndexMetaData.Builder indexMdBuilder = IndexMetaData.builder(snapshotIndexMetaData).state(IndexMetaData.State.OPEN);
                            indexMdBuilder.version(Math.max(snapshotIndexMetaData.getVersion(), currentIndexMetaData.getVersion() + 1));
                            if (!request.includeAliases()) {
                                // Remove all snapshot aliases
                                if (!snapshotIndexMetaData.getAliases().isEmpty()) {
                                    indexMdBuilder.removeAllAliases();
                                }
                                /// Add existing aliases
                                for (ObjectCursor<AliasMetaData> alias : currentIndexMetaData.getAliases().values()) {
                                    indexMdBuilder.putAlias(alias.value);
                                }
                            } else {
                                for (ObjectCursor<String> alias : snapshotIndexMetaData.getAliases().keys()) {
                                    aliases.add(alias.value);
                                }
                            }
                            indexMdBuilder.settings(Settings.builder().put(snapshotIndexMetaData.getSettings()).put(IndexMetaData.SETTING_INDEX_UUID, currentIndexMetaData.getIndexUUID()));
                            IndexMetaData updatedIndexMetaData = indexMdBuilder.index(renamedIndexName).build();
                            rtBuilder.addAsRestore(updatedIndexMetaData, recoverySource);
                            blocks.updateBlocks(updatedIndexMetaData);
                            mdBuilder.put(updatedIndexMetaData, true);
                            renamedIndex = updatedIndexMetaData.getIndex();
                        }
                        for (int shard = 0; shard < snapshotIndexMetaData.getNumberOfShards(); shard++) {
                            if (!ignoreShards.contains(shard)) {
                                shardsBuilder.put(new ShardId(renamedIndex, shard), new RestoreInProgress.ShardRestoreStatus(clusterService.state().nodes().getLocalNodeId()));
                            } else {
                                shardsBuilder.put(new ShardId(renamedIndex, shard), new RestoreInProgress.ShardRestoreStatus(clusterService.state().nodes().getLocalNodeId(), RestoreInProgress.State.FAILURE));
                            }
                        }
                    }
                    shards = shardsBuilder.build();
                    RestoreInProgress.Entry restoreEntry = new RestoreInProgress.Entry(snapshot, overallState(RestoreInProgress.State.INIT, shards), Collections.unmodifiableList(new ArrayList<>(renamedIndices.keySet())), shards);
                    builder.putCustom(RestoreInProgress.TYPE, new RestoreInProgress(restoreEntry));
                } else {
                    shards = ImmutableOpenMap.of();
                }
                checkAliasNameConflicts(renamedIndices, aliases);
                // Restore global state if needed
                restoreGlobalStateIfRequested(mdBuilder);
                if (completed(shards)) {
                    // We don't have any indices to restore - we are done
                    restoreInfo = new RestoreInfo(snapshotId.getName(), Collections.unmodifiableList(new ArrayList<>(renamedIndices.keySet())), shards.size(), shards.size() - failedShards(shards));
                }
                RoutingTable rt = rtBuilder.build();
                ClusterState updatedState = builder.metaData(mdBuilder).blocks(blocks).routingTable(rt).build();
                return allocationService.reroute(updatedState, "restored snapshot [" + snapshot + "]");
            }

            private void checkAliasNameConflicts(Map<String, String> renamedIndices, Set<String> aliases) {
                for (Map.Entry<String, String> renamedIndex : renamedIndices.entrySet()) {
                    if (aliases.contains(renamedIndex.getKey())) {
                        throw new SnapshotRestoreException(snapshot, "cannot rename index [" + renamedIndex.getValue() + "] into [" + renamedIndex.getKey() + "] because of conflict with an alias with the same name");
                    }
                }
            }

            private void populateIgnoredShards(String index, IntSet ignoreShards) {
                for (SnapshotShardFailure failure : snapshotInfo.shardFailures()) {
                    if (index.equals(failure.index())) {
                        ignoreShards.add(failure.shardId());
                    }
                }
            }

            private boolean checkPartial(String index) {
                // Make sure that index was fully snapshotted
                if (failed(snapshotInfo, index)) {
                    if (request.partial()) {
                        return true;
                    } else {
                        throw new SnapshotRestoreException(snapshot, "index [" + index + "] wasn't fully snapshotted - cannot restore");
                    }
                } else {
                    return false;
                }
            }

            private void validateExistingIndex(IndexMetaData currentIndexMetaData, IndexMetaData snapshotIndexMetaData, String renamedIndex, boolean partial) {
                // Index exist - checking that it's closed
                if (currentIndexMetaData.getState() != IndexMetaData.State.CLOSE) {
                    // TODO: Enable restore for open indices
                    throw new SnapshotRestoreException(snapshot, "cannot restore index [" + renamedIndex + "] because it's open");
                }
                // Index exist - checking if it's partial restore
                if (partial) {
                    throw new SnapshotRestoreException(snapshot, "cannot restore partial index [" + renamedIndex + "] because such index already exists");
                }
                // Make sure that the number of shards is the same. That's the only thing that we cannot change
                if (currentIndexMetaData.getNumberOfShards() != snapshotIndexMetaData.getNumberOfShards()) {
                    throw new SnapshotRestoreException(snapshot, "cannot restore index [" + renamedIndex + "] with [" + currentIndexMetaData.getNumberOfShards() + "] shard from snapshot with [" + snapshotIndexMetaData.getNumberOfShards() + "] shards");
                }
            }

            /**
                 * Optionally updates index settings in indexMetaData by removing settings listed in ignoreSettings and
                 * merging them with settings in changeSettings.
                 */
            private IndexMetaData updateIndexSettings(IndexMetaData indexMetaData, Settings changeSettings, String[] ignoreSettings) {
                if (changeSettings.names().isEmpty() && ignoreSettings.length == 0) {
                    return indexMetaData;
                }
                Settings normalizedChangeSettings = Settings.builder().put(changeSettings).normalizePrefix(IndexMetaData.INDEX_SETTING_PREFIX).build();
                IndexMetaData.Builder builder = IndexMetaData.builder(indexMetaData);
                Map<String, String> settingsMap = new HashMap<>(indexMetaData.getSettings().getAsMap());
                List<String> simpleMatchPatterns = new ArrayList<>();
                for (String ignoredSetting : ignoreSettings) {
                    if (!Regex.isSimpleMatchPattern(ignoredSetting)) {
                        if (UNREMOVABLE_SETTINGS.contains(ignoredSetting)) {
                            throw new SnapshotRestoreException(snapshot, "cannot remove setting [" + ignoredSetting + "] on restore");
                        } else {
                            settingsMap.remove(ignoredSetting);
                        }
                    } else {
                        simpleMatchPatterns.add(ignoredSetting);
                    }
                }
                if (!simpleMatchPatterns.isEmpty()) {
                    String[] removePatterns = simpleMatchPatterns.toArray(new String[simpleMatchPatterns.size()]);
                    Iterator<Map.Entry<String, String>> iterator = settingsMap.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry<String, String> entry = iterator.next();
                        if (UNREMOVABLE_SETTINGS.contains(entry.getKey()) == false) {
                            if (Regex.simpleMatch(removePatterns, entry.getKey())) {
                                iterator.remove();
                            }
                        }
                    }
                }
                for (Map.Entry<String, String> entry : normalizedChangeSettings.getAsMap().entrySet()) {
                    if (UNMODIFIABLE_SETTINGS.contains(entry.getKey())) {
                        throw new SnapshotRestoreException(snapshot, "cannot modify setting [" + entry.getKey() + "] on restore");
                    } else {
                        settingsMap.put(entry.getKey(), entry.getValue());
                    }
                }
                return builder.settings(Settings.builder().put(settingsMap)).build();
            }

            private void restoreGlobalStateIfRequested(MetaData.Builder mdBuilder) {
                if (request.includeGlobalState()) {
                    if (metaData.persistentSettings() != null) {
                        Settings settings = metaData.persistentSettings();
                        clusterSettings.validateUpdate(settings);
                        mdBuilder.persistentSettings(settings);
                    }
                    if (metaData.templates() != null) {
                        // TODO: Should all existing templates be deleted first?
                        for (ObjectCursor<IndexTemplateMetaData> cursor : metaData.templates().values()) {
                            mdBuilder.put(cursor.value);
                        }
                    }
                    if (metaData.customs() != null) {
                        for (ObjectObjectCursor<String, MetaData.Custom> cursor : metaData.customs()) {
                            if (!RepositoriesMetaData.TYPE.equals(cursor.key)) {
                                // Don't restore repositories while we are working with them
                                // TODO: Should we restore them at the end?
                                mdBuilder.putCustom(cursor.key, cursor.value);
                            }
                        }
                    }
                }
            }

            @Override
            public void onFailure(String source, Exception e) {
                logger.warn((Supplier<?>) () -> new ParameterizedMessage("[{}] failed to restore snapshot", snapshotId), e);
                listener.onFailure(e);
            }

            @Override
            public TimeValue timeout() {
                return request.masterNodeTimeout();
            }

            @Override
            public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
                listener.onResponse(new RestoreCompletionResponse(snapshot, restoreInfo));
            }
        });
    } catch (Exception e) {
        logger.warn((Supplier<?>) () -> new ParameterizedMessage("[{}] failed to restore snapshot", request.repositoryName + ":" + request.snapshotName), e);
        listener.onFailure(e);
    }
}
Also used : MetaData(org.elasticsearch.cluster.metadata.MetaData) ShardId(org.elasticsearch.index.shard.ShardId) SETTING_INDEX_UUID(org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_INDEX_UUID) SETTING_VERSION_MINIMUM_COMPATIBLE(org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_VERSION_MINIMUM_COMPATIBLE) SnapshotRecoverySource(org.elasticsearch.cluster.routing.RecoverySource.SnapshotRecoverySource) AllocationService(org.elasticsearch.cluster.routing.allocation.AllocationService) ClusterBlocks(org.elasticsearch.cluster.block.ClusterBlocks) 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) Map(java.util.Map) IndicesOptions(org.elasticsearch.action.support.IndicesOptions) SETTING_VERSION_UPGRADED(org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_VERSION_UPGRADED) Priority(org.elasticsearch.common.Priority) SnapshotDeletionsInProgress(org.elasticsearch.cluster.SnapshotDeletionsInProgress) AliasMetaData(org.elasticsearch.cluster.metadata.AliasMetaData) UUIDs(org.elasticsearch.common.UUIDs) Set(java.util.Set) ObjectCursor(com.carrotsearch.hppc.cursors.ObjectCursor) ClusterChangedEvent(org.elasticsearch.cluster.ClusterChangedEvent) Collectors(java.util.stream.Collectors) Sets(org.elasticsearch.common.util.set.Sets) Objects(java.util.Objects) RecoverySource(org.elasticsearch.cluster.routing.RecoverySource) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Version(org.elasticsearch.Version) Supplier(org.apache.logging.log4j.util.Supplier) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) Optional(java.util.Optional) RepositoryData(org.elasticsearch.repositories.RepositoryData) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) MetaDataCreateIndexService(org.elasticsearch.cluster.metadata.MetaDataCreateIndexService) ImmutableOpenMap(org.elasticsearch.common.collect.ImmutableOpenMap) ClusterService(org.elasticsearch.cluster.service.ClusterService) HashMap(java.util.HashMap) Index(org.elasticsearch.index.Index) Sets.newHashSet(org.elasticsearch.common.util.set.Sets.newHashSet) Lucene(org.elasticsearch.common.lucene.Lucene) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) Inject(org.elasticsearch.common.inject.Inject) ArrayList(java.util.ArrayList) SETTING_NUMBER_OF_REPLICAS(org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS) HashSet(java.util.HashSet) ClusterStateTaskListener(org.elasticsearch.cluster.ClusterStateTaskListener) TimeValue(org.elasticsearch.common.unit.TimeValue) Regex(org.elasticsearch.common.regex.Regex) SETTING_VERSION_CREATED(org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_VERSION_CREATED) SETTING_AUTO_EXPAND_REPLICAS(org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_AUTO_EXPAND_REPLICAS) SETTING_CREATION_DATE(org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_CREATION_DATE) ShardRestoreStatus(org.elasticsearch.cluster.RestoreInProgress.ShardRestoreStatus) ClusterStateApplier(org.elasticsearch.cluster.ClusterStateApplier) RepositoriesMetaData(org.elasticsearch.cluster.metadata.RepositoriesMetaData) Repository(org.elasticsearch.repositories.Repository) AbstractComponent(org.elasticsearch.common.component.AbstractComponent) Iterator(java.util.Iterator) SETTING_NUMBER_OF_SHARDS(org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS) IndexShard(org.elasticsearch.index.shard.IndexShard) IntHashSet(com.carrotsearch.hppc.IntHashSet) IntSet(com.carrotsearch.hppc.IntSet) ClusterStateTaskConfig(org.elasticsearch.cluster.ClusterStateTaskConfig) ClusterStateTaskExecutor(org.elasticsearch.cluster.ClusterStateTaskExecutor) RoutingChangesObserver(org.elasticsearch.cluster.routing.RoutingChangesObserver) UnassignedInfo(org.elasticsearch.cluster.routing.UnassignedInfo) RepositoriesService(org.elasticsearch.repositories.RepositoriesService) ClusterSettings(org.elasticsearch.common.settings.ClusterSettings) Collections.unmodifiableSet(java.util.Collections.unmodifiableSet) MetaDataIndexUpgradeService(org.elasticsearch.cluster.metadata.MetaDataIndexUpgradeService) RoutingTable(org.elasticsearch.cluster.routing.RoutingTable) IndexTemplateMetaData(org.elasticsearch.cluster.metadata.IndexTemplateMetaData) Collections(java.util.Collections) ActionListener(org.elasticsearch.action.ActionListener) IntHashSet(com.carrotsearch.hppc.IntHashSet) ArrayList(java.util.ArrayList) Index(org.elasticsearch.index.Index) SnapshotDeletionsInProgress(org.elasticsearch.cluster.SnapshotDeletionsInProgress) Version(org.elasticsearch.Version) MetaData(org.elasticsearch.cluster.metadata.MetaData) AliasMetaData(org.elasticsearch.cluster.metadata.AliasMetaData) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) RepositoriesMetaData(org.elasticsearch.cluster.metadata.RepositoriesMetaData) IndexTemplateMetaData(org.elasticsearch.cluster.metadata.IndexTemplateMetaData) List(java.util.List) ArrayList(java.util.ArrayList) Settings(org.elasticsearch.common.settings.Settings) ClusterSettings(org.elasticsearch.common.settings.ClusterSettings) TimeValue(org.elasticsearch.common.unit.TimeValue) ClusterState(org.elasticsearch.cluster.ClusterState) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) RestoreInProgress(org.elasticsearch.cluster.RestoreInProgress) SnapshotRecoverySource(org.elasticsearch.cluster.routing.RecoverySource.SnapshotRecoverySource) RoutingTable(org.elasticsearch.cluster.routing.RoutingTable) ObjectObjectCursor(com.carrotsearch.hppc.cursors.ObjectObjectCursor) ObjectObjectCursor(com.carrotsearch.hppc.cursors.ObjectObjectCursor) ObjectCursor(com.carrotsearch.hppc.cursors.ObjectCursor) Map(java.util.Map) ImmutableOpenMap(org.elasticsearch.common.collect.ImmutableOpenMap) HashMap(java.util.HashMap) Set(java.util.Set) Sets.newHashSet(org.elasticsearch.common.util.set.Sets.newHashSet) HashSet(java.util.HashSet) IntHashSet(com.carrotsearch.hppc.IntHashSet) IntSet(com.carrotsearch.hppc.IntSet) Collections.unmodifiableSet(java.util.Collections.unmodifiableSet) IntSet(com.carrotsearch.hppc.IntSet) ImmutableOpenMap(org.elasticsearch.common.collect.ImmutableOpenMap) ShardId(org.elasticsearch.index.shard.ShardId) Iterator(java.util.Iterator) Supplier(org.apache.logging.log4j.util.Supplier) ClusterStateUpdateTask(org.elasticsearch.cluster.ClusterStateUpdateTask) RepositoryData(org.elasticsearch.repositories.RepositoryData) Repository(org.elasticsearch.repositories.Repository) ShardRestoreStatus(org.elasticsearch.cluster.RestoreInProgress.ShardRestoreStatus) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage)

Example 2 with RestoreInProgress

use of org.elasticsearch.cluster.RestoreInProgress in project elasticsearch by elastic.

the class RestoreService method updateRestoreStateWithDeletedIndices.

public static RestoreInProgress updateRestoreStateWithDeletedIndices(RestoreInProgress oldRestore, Set<Index> deletedIndices) {
    boolean changesMade = false;
    final List<RestoreInProgress.Entry> entries = new ArrayList<>();
    for (RestoreInProgress.Entry entry : oldRestore.entries()) {
        ImmutableOpenMap.Builder<ShardId, ShardRestoreStatus> shardsBuilder = null;
        for (ObjectObjectCursor<ShardId, ShardRestoreStatus> cursor : entry.shards()) {
            ShardId shardId = cursor.key;
            if (deletedIndices.contains(shardId.getIndex())) {
                changesMade = true;
                if (shardsBuilder == null) {
                    shardsBuilder = ImmutableOpenMap.builder(entry.shards());
                }
                shardsBuilder.put(shardId, new ShardRestoreStatus(null, RestoreInProgress.State.FAILURE, "index was deleted"));
            }
        }
        if (shardsBuilder != null) {
            ImmutableOpenMap<ShardId, ShardRestoreStatus> shards = shardsBuilder.build();
            entries.add(new RestoreInProgress.Entry(entry.snapshot(), overallState(RestoreInProgress.State.STARTED, shards), entry.indices(), shards));
        } else {
            entries.add(entry);
        }
    }
    if (changesMade) {
        return new RestoreInProgress(entries.toArray(new RestoreInProgress.Entry[entries.size()]));
    } else {
        return oldRestore;
    }
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) RestoreInProgress(org.elasticsearch.cluster.RestoreInProgress) ShardRestoreStatus(org.elasticsearch.cluster.RestoreInProgress.ShardRestoreStatus) ArrayList(java.util.ArrayList) ImmutableOpenMap(org.elasticsearch.common.collect.ImmutableOpenMap)

Example 3 with RestoreInProgress

use of org.elasticsearch.cluster.RestoreInProgress in project elasticsearch by elastic.

the class SnapshotsService method deleteSnapshot.

/**
     * Deletes snapshot from repository.
     * <p>
     * If the snapshot is still running cancels the snapshot first and then deletes it from the repository.
     *
     * @param snapshot snapshot
     * @param listener listener
     * @param repositoryStateId the unique id for the state of the repository
     */
private void deleteSnapshot(final Snapshot snapshot, final DeleteSnapshotListener listener, final long repositoryStateId, final boolean immediatePriority) {
    Priority priority = immediatePriority ? Priority.IMMEDIATE : Priority.NORMAL;
    clusterService.submitStateUpdateTask("delete snapshot", new ClusterStateUpdateTask(priority) {

        boolean waitForSnapshot = false;

        @Override
        public ClusterState execute(ClusterState currentState) throws Exception {
            SnapshotDeletionsInProgress deletionsInProgress = currentState.custom(SnapshotDeletionsInProgress.TYPE);
            if (deletionsInProgress != null && deletionsInProgress.hasDeletionsInProgress()) {
                throw new ConcurrentSnapshotExecutionException(snapshot, "cannot delete - another snapshot is currently being deleted");
            }
            RestoreInProgress restoreInProgress = currentState.custom(RestoreInProgress.TYPE);
            if (restoreInProgress != null) {
                // and the files the restore depends on would all be gone
                if (restoreInProgress.entries().isEmpty() == false) {
                    throw new ConcurrentSnapshotExecutionException(snapshot, "cannot delete snapshot during a restore");
                }
            }
            ClusterState.Builder clusterStateBuilder = ClusterState.builder(currentState);
            SnapshotsInProgress snapshots = currentState.custom(SnapshotsInProgress.TYPE);
            SnapshotsInProgress.Entry snapshotEntry = snapshots != null ? snapshots.snapshot(snapshot) : null;
            if (snapshotEntry == null) {
                // This snapshot is not running - delete
                if (snapshots != null && !snapshots.entries().isEmpty()) {
                    // However other snapshots are running - cannot continue
                    throw new ConcurrentSnapshotExecutionException(snapshot, "another snapshot is currently running cannot delete");
                }
                // add the snapshot deletion to the cluster state
                SnapshotDeletionsInProgress.Entry entry = new SnapshotDeletionsInProgress.Entry(snapshot, System.currentTimeMillis(), repositoryStateId);
                if (deletionsInProgress != null) {
                    deletionsInProgress = deletionsInProgress.withAddedEntry(entry);
                } else {
                    deletionsInProgress = SnapshotDeletionsInProgress.newInstance(entry);
                }
                clusterStateBuilder.putCustom(SnapshotDeletionsInProgress.TYPE, deletionsInProgress);
            } else {
                // This snapshot is currently running - stopping shards first
                waitForSnapshot = true;
                ImmutableOpenMap<ShardId, ShardSnapshotStatus> shards;
                if (snapshotEntry.state() == State.STARTED && snapshotEntry.shards() != null) {
                    // snapshot is currently running - stop started shards
                    ImmutableOpenMap.Builder<ShardId, ShardSnapshotStatus> shardsBuilder = ImmutableOpenMap.builder();
                    for (ObjectObjectCursor<ShardId, ShardSnapshotStatus> shardEntry : snapshotEntry.shards()) {
                        ShardSnapshotStatus status = shardEntry.value;
                        if (!status.state().completed()) {
                            shardsBuilder.put(shardEntry.key, new ShardSnapshotStatus(status.nodeId(), State.ABORTED));
                        } else {
                            shardsBuilder.put(shardEntry.key, status);
                        }
                    }
                    shards = shardsBuilder.build();
                } else if (snapshotEntry.state() == State.INIT) {
                    // snapshot hasn't started yet - end it
                    shards = snapshotEntry.shards();
                    endSnapshot(snapshotEntry);
                } else {
                    boolean hasUncompletedShards = false;
                    // Cleanup in case a node gone missing and snapshot wasn't updated for some reason
                    for (ObjectCursor<ShardSnapshotStatus> shardStatus : snapshotEntry.shards().values()) {
                        // Check if we still have shard running on existing nodes
                        if (shardStatus.value.state().completed() == false && shardStatus.value.nodeId() != null && currentState.nodes().get(shardStatus.value.nodeId()) != null) {
                            hasUncompletedShards = true;
                            break;
                        }
                    }
                    if (hasUncompletedShards) {
                        // snapshot is being finalized - wait for shards to complete finalization process
                        logger.debug("trying to delete completed snapshot - should wait for shards to finalize on all nodes");
                        return currentState;
                    } else {
                        // no shards to wait for - finish the snapshot
                        logger.debug("trying to delete completed snapshot with no finalizing shards - can delete immediately");
                        shards = snapshotEntry.shards();
                        endSnapshot(snapshotEntry);
                    }
                }
                SnapshotsInProgress.Entry newSnapshot = new SnapshotsInProgress.Entry(snapshotEntry, State.ABORTED, shards);
                snapshots = new SnapshotsInProgress(newSnapshot);
                clusterStateBuilder.putCustom(SnapshotsInProgress.TYPE, snapshots);
            }
            return clusterStateBuilder.build();
        }

        @Override
        public void onFailure(String source, Exception e) {
            listener.onFailure(e);
        }

        @Override
        public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
            if (waitForSnapshot) {
                logger.trace("adding snapshot completion listener to wait for deleted snapshot to finish");
                addListener(new SnapshotCompletionListener() {

                    @Override
                    public void onSnapshotCompletion(Snapshot completedSnapshot, SnapshotInfo snapshotInfo) {
                        if (completedSnapshot.equals(snapshot)) {
                            logger.trace("deleted snapshot completed - deleting files");
                            removeListener(this);
                            threadPool.executor(ThreadPool.Names.SNAPSHOT).execute(() -> deleteSnapshot(completedSnapshot.getRepository(), completedSnapshot.getSnapshotId().getName(), listener, true));
                        }
                    }

                    @Override
                    public void onSnapshotFailure(Snapshot failedSnapshot, Exception e) {
                        if (failedSnapshot.equals(snapshot)) {
                            logger.trace("deleted snapshot failed - deleting files", e);
                            removeListener(this);
                            threadPool.executor(ThreadPool.Names.SNAPSHOT).execute(() -> deleteSnapshot(failedSnapshot.getRepository(), failedSnapshot.getSnapshotId().getName(), listener, true));
                        }
                    }
                });
            } else {
                logger.trace("deleted snapshot is not running - deleting files");
                deleteSnapshotFromRepository(snapshot, listener, repositoryStateId);
            }
        }
    });
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) Priority(org.elasticsearch.common.Priority) ClusterStateUpdateTask(org.elasticsearch.cluster.ClusterStateUpdateTask) ImmutableOpenMap(org.elasticsearch.common.collect.ImmutableOpenMap) RepositoryMissingException(org.elasticsearch.repositories.RepositoryMissingException) IOException(java.io.IOException) SnapshotDeletionsInProgress(org.elasticsearch.cluster.SnapshotDeletionsInProgress) RestoreInProgress(org.elasticsearch.cluster.RestoreInProgress) SnapshotsInProgress(org.elasticsearch.cluster.SnapshotsInProgress) ShardSnapshotStatus(org.elasticsearch.cluster.SnapshotsInProgress.ShardSnapshotStatus) IndexShardSnapshotStatus(org.elasticsearch.index.snapshots.IndexShardSnapshotStatus) ObjectObjectCursor(com.carrotsearch.hppc.cursors.ObjectObjectCursor)

Example 4 with RestoreInProgress

use of org.elasticsearch.cluster.RestoreInProgress in project elasticsearch by elastic.

the class MetaDataDeleteIndexService method deleteIndices.

/**
     * Delete some indices from the cluster state.
     */
public ClusterState deleteIndices(ClusterState currentState, Set<Index> indices) {
    final MetaData meta = currentState.metaData();
    final Set<IndexMetaData> metaDatas = indices.stream().map(i -> meta.getIndexSafe(i)).collect(toSet());
    // Check if index deletion conflicts with any running snapshots
    SnapshotsService.checkIndexDeletion(currentState, metaDatas);
    RoutingTable.Builder routingTableBuilder = RoutingTable.builder(currentState.routingTable());
    MetaData.Builder metaDataBuilder = MetaData.builder(meta);
    ClusterBlocks.Builder clusterBlocksBuilder = ClusterBlocks.builder().blocks(currentState.blocks());
    final IndexGraveyard.Builder graveyardBuilder = IndexGraveyard.builder(metaDataBuilder.indexGraveyard());
    final int previousGraveyardSize = graveyardBuilder.tombstones().size();
    for (final Index index : indices) {
        String indexName = index.getName();
        logger.info("{} deleting index", index);
        routingTableBuilder.remove(indexName);
        clusterBlocksBuilder.removeIndexBlocks(indexName);
        metaDataBuilder.remove(indexName);
    }
    // add tombstones to the cluster state for each deleted index
    final IndexGraveyard currentGraveyard = graveyardBuilder.addTombstones(indices).build(settings);
    // the new graveyard set on the metadata
    metaDataBuilder.indexGraveyard(currentGraveyard);
    logger.trace("{} tombstones purged from the cluster state. Previous tombstone size: {}. Current tombstone size: {}.", graveyardBuilder.getNumPurged(), previousGraveyardSize, currentGraveyard.getTombstones().size());
    MetaData newMetaData = metaDataBuilder.build();
    ClusterBlocks blocks = clusterBlocksBuilder.build();
    // update snapshot restore entries
    ImmutableOpenMap<String, ClusterState.Custom> customs = currentState.getCustoms();
    final RestoreInProgress restoreInProgress = currentState.custom(RestoreInProgress.TYPE);
    if (restoreInProgress != null) {
        RestoreInProgress updatedRestoreInProgress = RestoreService.updateRestoreStateWithDeletedIndices(restoreInProgress, indices);
        if (updatedRestoreInProgress != restoreInProgress) {
            ImmutableOpenMap.Builder<String, ClusterState.Custom> builder = ImmutableOpenMap.builder(customs);
            builder.put(RestoreInProgress.TYPE, updatedRestoreInProgress);
            customs = builder.build();
        }
    }
    return allocationService.reroute(ClusterState.builder(currentState).routingTable(routingTableBuilder.build()).metaData(newMetaData).blocks(blocks).customs(customs).build(), "deleted indices [" + indices + "]");
}
Also used : Arrays(java.util.Arrays) AckedClusterStateUpdateTask(org.elasticsearch.cluster.AckedClusterStateUpdateTask) Priority(org.elasticsearch.common.Priority) SnapshotsService(org.elasticsearch.snapshots.SnapshotsService) ImmutableOpenMap(org.elasticsearch.common.collect.ImmutableOpenMap) AbstractComponent(org.elasticsearch.common.component.AbstractComponent) ClusterService(org.elasticsearch.cluster.service.ClusterService) AllocationService(org.elasticsearch.cluster.routing.allocation.AllocationService) Set(java.util.Set) ClusterBlocks(org.elasticsearch.cluster.block.ClusterBlocks) Index(org.elasticsearch.index.Index) RestoreService(org.elasticsearch.snapshots.RestoreService) Sets(org.elasticsearch.common.util.set.Sets) Inject(org.elasticsearch.common.inject.Inject) DeleteIndexClusterStateUpdateRequest(org.elasticsearch.action.admin.indices.delete.DeleteIndexClusterStateUpdateRequest) ClusterState(org.elasticsearch.cluster.ClusterState) Settings(org.elasticsearch.common.settings.Settings) RestoreInProgress(org.elasticsearch.cluster.RestoreInProgress) RoutingTable(org.elasticsearch.cluster.routing.RoutingTable) ClusterStateUpdateResponse(org.elasticsearch.cluster.ack.ClusterStateUpdateResponse) ActionListener(org.elasticsearch.action.ActionListener) Collectors.toSet(java.util.stream.Collectors.toSet) ClusterBlocks(org.elasticsearch.cluster.block.ClusterBlocks) Index(org.elasticsearch.index.Index) ImmutableOpenMap(org.elasticsearch.common.collect.ImmutableOpenMap) RestoreInProgress(org.elasticsearch.cluster.RestoreInProgress) RoutingTable(org.elasticsearch.cluster.routing.RoutingTable)

Example 5 with RestoreInProgress

use of org.elasticsearch.cluster.RestoreInProgress in project elasticsearch by elastic.

the class AllocationService method buildResultAndLogHealthChange.

protected ClusterState buildResultAndLogHealthChange(ClusterState oldState, RoutingAllocation allocation, String reason) {
    RoutingTable oldRoutingTable = oldState.routingTable();
    RoutingNodes newRoutingNodes = allocation.routingNodes();
    final RoutingTable newRoutingTable = new RoutingTable.Builder().updateNodes(oldRoutingTable.version(), newRoutingNodes).build();
    MetaData newMetaData = allocation.updateMetaDataWithRoutingChanges(newRoutingTable);
    // validates the routing table is coherent with the cluster state metadata
    assert newRoutingTable.validate(newMetaData);
    final ClusterState.Builder newStateBuilder = ClusterState.builder(oldState).routingTable(newRoutingTable).metaData(newMetaData);
    final RestoreInProgress restoreInProgress = allocation.custom(RestoreInProgress.TYPE);
    if (restoreInProgress != null) {
        RestoreInProgress updatedRestoreInProgress = allocation.updateRestoreInfoWithRoutingChanges(restoreInProgress);
        if (updatedRestoreInProgress != restoreInProgress) {
            ImmutableOpenMap.Builder<String, ClusterState.Custom> customsBuilder = ImmutableOpenMap.builder(allocation.getCustoms());
            customsBuilder.put(RestoreInProgress.TYPE, updatedRestoreInProgress);
            newStateBuilder.customs(customsBuilder.build());
        }
    }
    final ClusterState newState = newStateBuilder.build();
    logClusterHealthStateChange(new ClusterStateHealth(oldState), new ClusterStateHealth(newState), reason);
    return newState;
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) ClusterStateHealth(org.elasticsearch.cluster.health.ClusterStateHealth) RestoreInProgress(org.elasticsearch.cluster.RestoreInProgress) RoutingTable(org.elasticsearch.cluster.routing.RoutingTable) RoutingNodes(org.elasticsearch.cluster.routing.RoutingNodes) MetaData(org.elasticsearch.cluster.metadata.MetaData) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) ImmutableOpenMap(org.elasticsearch.common.collect.ImmutableOpenMap)

Aggregations

RestoreInProgress (org.elasticsearch.cluster.RestoreInProgress)7 ClusterState (org.elasticsearch.cluster.ClusterState)6 ImmutableOpenMap (org.elasticsearch.common.collect.ImmutableOpenMap)5 RoutingTable (org.elasticsearch.cluster.routing.RoutingTable)3 Priority (org.elasticsearch.common.Priority)3 ObjectObjectCursor (com.carrotsearch.hppc.cursors.ObjectObjectCursor)2 ArrayList (java.util.ArrayList)2 Set (java.util.Set)2 ActionListener (org.elasticsearch.action.ActionListener)2 ClusterStateUpdateTask (org.elasticsearch.cluster.ClusterStateUpdateTask)2 ShardRestoreStatus (org.elasticsearch.cluster.RestoreInProgress.ShardRestoreStatus)2 SnapshotDeletionsInProgress (org.elasticsearch.cluster.SnapshotDeletionsInProgress)2 ClusterBlocks (org.elasticsearch.cluster.block.ClusterBlocks)2 IndexMetaData (org.elasticsearch.cluster.metadata.IndexMetaData)2 MetaData (org.elasticsearch.cluster.metadata.MetaData)2 AllocationService (org.elasticsearch.cluster.routing.allocation.AllocationService)2 ClusterService (org.elasticsearch.cluster.service.ClusterService)2 AbstractComponent (org.elasticsearch.common.component.AbstractComponent)2 Inject (org.elasticsearch.common.inject.Inject)2 Settings (org.elasticsearch.common.settings.Settings)2