Search in sources :

Example 6 with RepositoryData

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

the class TransportSnapshotsStatusAction method buildResponse.

private SnapshotsStatusResponse buildResponse(SnapshotsStatusRequest request, List<SnapshotsInProgress.Entry> currentSnapshotEntries, TransportNodesSnapshotsStatus.NodesSnapshotStatus nodeSnapshotStatuses) throws IOException {
    // First process snapshot that are currently processed
    List<SnapshotStatus> builder = new ArrayList<>();
    Set<String> currentSnapshotNames = new HashSet<>();
    if (!currentSnapshotEntries.isEmpty()) {
        Map<String, TransportNodesSnapshotsStatus.NodeSnapshotStatus> nodeSnapshotStatusMap;
        if (nodeSnapshotStatuses != null) {
            nodeSnapshotStatusMap = nodeSnapshotStatuses.getNodesMap();
        } else {
            nodeSnapshotStatusMap = new HashMap<>();
        }
        for (SnapshotsInProgress.Entry entry : currentSnapshotEntries) {
            currentSnapshotNames.add(entry.snapshot().getSnapshotId().getName());
            List<SnapshotIndexShardStatus> shardStatusBuilder = new ArrayList<>();
            for (ObjectObjectCursor<ShardId, SnapshotsInProgress.ShardSnapshotStatus> shardEntry : entry.shards()) {
                SnapshotsInProgress.ShardSnapshotStatus status = shardEntry.value;
                if (status.nodeId() != null) {
                    // We should have information about this shard from the shard:
                    TransportNodesSnapshotsStatus.NodeSnapshotStatus nodeStatus = nodeSnapshotStatusMap.get(status.nodeId());
                    if (nodeStatus != null) {
                        Map<ShardId, SnapshotIndexShardStatus> shardStatues = nodeStatus.status().get(entry.snapshot());
                        if (shardStatues != null) {
                            SnapshotIndexShardStatus shardStatus = shardStatues.get(shardEntry.key);
                            if (shardStatus != null) {
                                // We have full information about this shard
                                shardStatusBuilder.add(shardStatus);
                                continue;
                            }
                        }
                    }
                }
                final SnapshotIndexShardStage stage;
                switch(shardEntry.value.state()) {
                    case FAILED:
                    case ABORTED:
                    case MISSING:
                        stage = SnapshotIndexShardStage.FAILURE;
                        break;
                    case INIT:
                    case WAITING:
                    case STARTED:
                        stage = SnapshotIndexShardStage.STARTED;
                        break;
                    case SUCCESS:
                        stage = SnapshotIndexShardStage.DONE;
                        break;
                    default:
                        throw new IllegalArgumentException("Unknown snapshot state " + shardEntry.value.state());
                }
                SnapshotIndexShardStatus shardStatus = new SnapshotIndexShardStatus(shardEntry.key, stage);
                shardStatusBuilder.add(shardStatus);
            }
            builder.add(new SnapshotStatus(entry.snapshot(), entry.state(), Collections.unmodifiableList(shardStatusBuilder)));
        }
    }
    // Now add snapshots on disk that are not currently running
    final String repositoryName = request.repository();
    if (Strings.hasText(repositoryName) && request.snapshots() != null && request.snapshots().length > 0) {
        final Set<String> requestedSnapshotNames = Sets.newHashSet(request.snapshots());
        final RepositoryData repositoryData = snapshotsService.getRepositoryData(repositoryName);
        final Map<String, SnapshotId> matchedSnapshotIds = repositoryData.getAllSnapshotIds().stream().filter(s -> requestedSnapshotNames.contains(s.getName())).collect(Collectors.toMap(SnapshotId::getName, Function.identity()));
        for (final String snapshotName : request.snapshots()) {
            if (currentSnapshotNames.contains(snapshotName)) {
                // we've already found this snapshot in the current snapshot entries, so skip over
                continue;
            }
            SnapshotId snapshotId = matchedSnapshotIds.get(snapshotName);
            if (snapshotId == null) {
                // neither in the current snapshot entries nor found in the repository
                if (request.ignoreUnavailable()) {
                    // ignoring unavailable snapshots, so skip over
                    logger.debug("snapshot status request ignoring snapshot [{}], not found in repository [{}]", snapshotName, repositoryName);
                    continue;
                } else {
                    throw new SnapshotMissingException(repositoryName, snapshotName);
                }
            } else if (repositoryData.getIncompatibleSnapshotIds().contains(snapshotId)) {
                throw new SnapshotException(repositoryName, snapshotName, "cannot get the status for an incompatible snapshot");
            }
            SnapshotInfo snapshotInfo = snapshotsService.snapshot(repositoryName, snapshotId);
            List<SnapshotIndexShardStatus> shardStatusBuilder = new ArrayList<>();
            if (snapshotInfo.state().completed()) {
                Map<ShardId, IndexShardSnapshotStatus> shardStatues = snapshotsService.snapshotShards(request.repository(), snapshotInfo);
                for (Map.Entry<ShardId, IndexShardSnapshotStatus> shardStatus : shardStatues.entrySet()) {
                    shardStatusBuilder.add(new SnapshotIndexShardStatus(shardStatus.getKey(), shardStatus.getValue()));
                }
                final SnapshotsInProgress.State state;
                switch(snapshotInfo.state()) {
                    case FAILED:
                        state = SnapshotsInProgress.State.FAILED;
                        break;
                    case SUCCESS:
                    case PARTIAL:
                        // Translating both PARTIAL and SUCCESS to SUCCESS for now
                        // TODO: add the differentiation on the metadata level in the next major release
                        state = SnapshotsInProgress.State.SUCCESS;
                        break;
                    default:
                        throw new IllegalArgumentException("Unknown snapshot state " + snapshotInfo.state());
                }
                builder.add(new SnapshotStatus(new Snapshot(repositoryName, snapshotId), state, Collections.unmodifiableList(shardStatusBuilder)));
            }
        }
    }
    return new SnapshotsStatusResponse(Collections.unmodifiableList(builder));
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) SnapshotMissingException(org.elasticsearch.snapshots.SnapshotMissingException) SnapshotId(org.elasticsearch.snapshots.SnapshotId) Arrays(java.util.Arrays) ClusterService(org.elasticsearch.cluster.service.ClusterService) IndexShardSnapshotStatus(org.elasticsearch.index.snapshots.IndexShardSnapshotStatus) HashMap(java.util.HashMap) SnapshotInfo(org.elasticsearch.snapshots.SnapshotInfo) Function(java.util.function.Function) Strings(org.elasticsearch.common.Strings) Inject(org.elasticsearch.common.inject.Inject) ArrayList(java.util.ArrayList) TransportMasterNodeAction(org.elasticsearch.action.support.master.TransportMasterNodeAction) HashSet(java.util.HashSet) ObjectObjectCursor(com.carrotsearch.hppc.cursors.ObjectObjectCursor) ClusterState(org.elasticsearch.cluster.ClusterState) Settings(org.elasticsearch.common.settings.Settings) ClusterBlockException(org.elasticsearch.cluster.block.ClusterBlockException) Map(java.util.Map) ThreadPool(org.elasticsearch.threadpool.ThreadPool) TransportService(org.elasticsearch.transport.TransportService) ClusterBlockLevel(org.elasticsearch.cluster.block.ClusterBlockLevel) ActionFilters(org.elasticsearch.action.support.ActionFilters) SnapshotsService(org.elasticsearch.snapshots.SnapshotsService) Set(java.util.Set) IOException(java.io.IOException) ObjectCursor(com.carrotsearch.hppc.cursors.ObjectCursor) Collectors(java.util.stream.Collectors) Sets(org.elasticsearch.common.util.set.Sets) List(java.util.List) SnapshotException(org.elasticsearch.snapshots.SnapshotException) SnapshotsInProgress(org.elasticsearch.cluster.SnapshotsInProgress) IndexNameExpressionResolver(org.elasticsearch.cluster.metadata.IndexNameExpressionResolver) Snapshot(org.elasticsearch.snapshots.Snapshot) Collections(java.util.Collections) ActionListener(org.elasticsearch.action.ActionListener) RepositoryData(org.elasticsearch.repositories.RepositoryData) IndexShardSnapshotStatus(org.elasticsearch.index.snapshots.IndexShardSnapshotStatus) ArrayList(java.util.ArrayList) ShardId(org.elasticsearch.index.shard.ShardId) SnapshotMissingException(org.elasticsearch.snapshots.SnapshotMissingException) HashSet(java.util.HashSet) SnapshotException(org.elasticsearch.snapshots.SnapshotException) RepositoryData(org.elasticsearch.repositories.RepositoryData) SnapshotId(org.elasticsearch.snapshots.SnapshotId) Snapshot(org.elasticsearch.snapshots.Snapshot) SnapshotInfo(org.elasticsearch.snapshots.SnapshotInfo) IndexShardSnapshotStatus(org.elasticsearch.index.snapshots.IndexShardSnapshotStatus) SnapshotsInProgress(org.elasticsearch.cluster.SnapshotsInProgress) IndexShardSnapshotStatus(org.elasticsearch.index.snapshots.IndexShardSnapshotStatus) HashMap(java.util.HashMap) Map(java.util.Map)

Example 7 with RepositoryData

use of org.elasticsearch.repositories.RepositoryData 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 8 with RepositoryData

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

the class SnapshotsService method createSnapshot.

/**
     * Initializes the snapshotting process.
     * <p>
     * This method is used by clients to start snapshot. It makes sure that there is no snapshots are currently running and
     * creates a snapshot record in cluster state metadata.
     *
     * @param request  snapshot request
     * @param listener snapshot creation listener
     */
public void createSnapshot(final SnapshotRequest request, final CreateSnapshotListener listener) {
    final String repositoryName = request.repositoryName;
    final String snapshotName = request.snapshotName;
    validate(repositoryName, snapshotName);
    // new UUID for the snapshot
    final SnapshotId snapshotId = new SnapshotId(snapshotName, UUIDs.randomBase64UUID());
    final RepositoryData repositoryData = repositoriesService.repository(repositoryName).getRepositoryData();
    clusterService.submitStateUpdateTask(request.cause(), new ClusterStateUpdateTask() {

        private SnapshotsInProgress.Entry newSnapshot = null;

        @Override
        public ClusterState execute(ClusterState currentState) {
            validate(request, currentState);
            SnapshotDeletionsInProgress deletionsInProgress = currentState.custom(SnapshotDeletionsInProgress.TYPE);
            if (deletionsInProgress != null && deletionsInProgress.hasDeletionsInProgress()) {
                throw new ConcurrentSnapshotExecutionException(repositoryName, snapshotName, "cannot snapshot while a snapshot deletion is in-progress");
            }
            SnapshotsInProgress snapshots = currentState.custom(SnapshotsInProgress.TYPE);
            if (snapshots == null || snapshots.entries().isEmpty()) {
                // Store newSnapshot here to be processed in clusterStateProcessed
                List<String> indices = Arrays.asList(indexNameExpressionResolver.concreteIndexNames(currentState, request.indicesOptions(), request.indices()));
                logger.trace("[{}][{}] creating snapshot for indices [{}]", repositoryName, snapshotName, indices);
                List<IndexId> snapshotIndices = repositoryData.resolveNewIndices(indices);
                newSnapshot = new SnapshotsInProgress.Entry(new Snapshot(repositoryName, snapshotId), request.includeGlobalState(), request.partial(), State.INIT, snapshotIndices, System.currentTimeMillis(), repositoryData.getGenId(), null);
                snapshots = new SnapshotsInProgress(newSnapshot);
            } else {
                throw new ConcurrentSnapshotExecutionException(repositoryName, snapshotName, "a snapshot is already running");
            }
            return ClusterState.builder(currentState).putCustom(SnapshotsInProgress.TYPE, snapshots).build();
        }

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

        @Override
        public void clusterStateProcessed(String source, ClusterState oldState, final ClusterState newState) {
            if (newSnapshot != null) {
                threadPool.executor(ThreadPool.Names.SNAPSHOT).execute(() -> beginSnapshot(newState, newSnapshot, request.partial(), listener));
            }
        }

        @Override
        public TimeValue timeout() {
            return request.masterNodeTimeout();
        }
    });
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) ClusterStateUpdateTask(org.elasticsearch.cluster.ClusterStateUpdateTask) RepositoryMissingException(org.elasticsearch.repositories.RepositoryMissingException) IOException(java.io.IOException) RepositoryData(org.elasticsearch.repositories.RepositoryData) SnapshotDeletionsInProgress(org.elasticsearch.cluster.SnapshotDeletionsInProgress) SnapshotsInProgress(org.elasticsearch.cluster.SnapshotsInProgress) List(java.util.List) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) Supplier(org.apache.logging.log4j.util.Supplier) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) TimeValue(org.elasticsearch.common.unit.TimeValue)

Example 9 with RepositoryData

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

the class BlobStoreRepository method deleteSnapshot.

@Override
public void deleteSnapshot(SnapshotId snapshotId, long repositoryStateId) {
    if (isReadOnly()) {
        throw new RepositoryException(metadata.name(), "cannot delete snapshot from a readonly repository");
    }
    final RepositoryData repositoryData = getRepositoryData();
    List<String> indices = Collections.emptyList();
    SnapshotInfo snapshot = null;
    try {
        snapshot = getSnapshotInfo(snapshotId);
        indices = snapshot.indices();
    } catch (SnapshotMissingException ex) {
        throw ex;
    } catch (IllegalStateException | SnapshotException | ElasticsearchParseException ex) {
        logger.warn((Supplier<?>) () -> new ParameterizedMessage("cannot read snapshot file [{}]", snapshotId), ex);
    }
    MetaData metaData = null;
    try {
        if (snapshot != null) {
            metaData = readSnapshotMetaData(snapshotId, snapshot.version(), repositoryData.resolveIndices(indices), true);
        } else {
            metaData = readSnapshotMetaData(snapshotId, null, repositoryData.resolveIndices(indices), true);
        }
    } catch (IOException | SnapshotException ex) {
        logger.warn((Supplier<?>) () -> new ParameterizedMessage("cannot read metadata for snapshot [{}]", snapshotId), ex);
    }
    try {
        // Delete snapshot from the index file, since it is the maintainer of truth of active snapshots
        final RepositoryData updatedRepositoryData = repositoryData.removeSnapshot(snapshotId);
        writeIndexGen(updatedRepositoryData, repositoryStateId);
        // delete the snapshot file
        safeSnapshotBlobDelete(snapshot, snapshotId.getUUID());
        // delete the global metadata file
        safeGlobalMetaDataBlobDelete(snapshot, snapshotId.getUUID());
        // Now delete all indices
        for (String index : indices) {
            final IndexId indexId = repositoryData.resolveIndexId(index);
            BlobPath indexPath = basePath().add("indices").add(indexId.getId());
            BlobContainer indexMetaDataBlobContainer = blobStore().blobContainer(indexPath);
            try {
                indexMetaDataFormat.delete(indexMetaDataBlobContainer, snapshotId.getUUID());
            } catch (IOException ex) {
                logger.warn((Supplier<?>) () -> new ParameterizedMessage("[{}] failed to delete metadata for index [{}]", snapshotId, index), ex);
            }
            if (metaData != null) {
                IndexMetaData indexMetaData = metaData.index(index);
                if (indexMetaData != null) {
                    for (int shardId = 0; shardId < indexMetaData.getNumberOfShards(); shardId++) {
                        try {
                            delete(snapshotId, snapshot.version(), indexId, new ShardId(indexMetaData.getIndex(), shardId));
                        } catch (SnapshotException ex) {
                            final int finalShardId = shardId;
                            logger.warn((Supplier<?>) () -> new ParameterizedMessage("[{}] failed to delete shard data for shard [{}][{}]", snapshotId, index, finalShardId), ex);
                        }
                    }
                }
            }
        }
        // cleanup indices that are no longer part of the repository
        final Collection<IndexId> indicesToCleanUp = Sets.newHashSet(repositoryData.getIndices().values());
        indicesToCleanUp.removeAll(updatedRepositoryData.getIndices().values());
        final BlobContainer indicesBlobContainer = blobStore().blobContainer(basePath().add("indices"));
        for (final IndexId indexId : indicesToCleanUp) {
            try {
                indicesBlobContainer.deleteBlob(indexId.getId());
            } catch (DirectoryNotEmptyException dnee) {
                // if the directory isn't empty for some reason, it will fail to clean up;
                // we'll ignore that and accept that cleanup didn't fully succeed.
                // since we are using UUIDs for path names, this won't be an issue for
                // snapshotting indices of the same name
                logger.debug((Supplier<?>) () -> new ParameterizedMessage("[{}] index [{}] no longer part of any snapshots in the repository, but failed to clean up " + "its index folder due to the directory not being empty.", metadata.name(), indexId), dnee);
            } catch (IOException ioe) {
                // a different IOException occurred while trying to delete - will just log the issue for now
                logger.debug((Supplier<?>) () -> new ParameterizedMessage("[{}] index [{}] no longer part of any snapshots in the repository, but failed to clean up " + "its index folder.", metadata.name(), indexId), ioe);
            }
        }
    } catch (IOException ex) {
        throw new RepositoryException(metadata.name(), "failed to update snapshot in repository", ex);
    }
}
Also used : IndexId(org.elasticsearch.repositories.IndexId) BlobPath(org.elasticsearch.common.blobstore.BlobPath) RepositoryException(org.elasticsearch.repositories.RepositoryException) DirectoryNotEmptyException(java.nio.file.DirectoryNotEmptyException) IOException(java.io.IOException) SnapshotException(org.elasticsearch.snapshots.SnapshotException) IndexShardSnapshotException(org.elasticsearch.index.snapshots.IndexShardSnapshotException) RepositoryData(org.elasticsearch.repositories.RepositoryData) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) ShardId(org.elasticsearch.index.shard.ShardId) SnapshotInfo(org.elasticsearch.snapshots.SnapshotInfo) SnapshotMissingException(org.elasticsearch.snapshots.SnapshotMissingException) MetaData(org.elasticsearch.cluster.metadata.MetaData) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) StoreFileMetaData(org.elasticsearch.index.store.StoreFileMetaData) BlobMetaData(org.elasticsearch.common.blobstore.BlobMetaData) RepositoryMetaData(org.elasticsearch.cluster.metadata.RepositoryMetaData) ElasticsearchParseException(org.elasticsearch.ElasticsearchParseException) BlobContainer(org.elasticsearch.common.blobstore.BlobContainer) Supplier(org.apache.logging.log4j.util.Supplier) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage)

Example 10 with RepositoryData

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

the class BlobStoreRepository method finalizeSnapshot.

/**
     * {@inheritDoc}
     */
@Override
public SnapshotInfo finalizeSnapshot(final SnapshotId snapshotId, final List<IndexId> indices, final long startTime, final String failure, final int totalShards, final List<SnapshotShardFailure> shardFailures, final long repositoryStateId) {
    try {
        SnapshotInfo blobStoreSnapshot = new SnapshotInfo(snapshotId, indices.stream().map(IndexId::getName).collect(Collectors.toList()), startTime, failure, System.currentTimeMillis(), totalShards, shardFailures);
        snapshotFormat.write(blobStoreSnapshot, snapshotsBlobContainer, snapshotId.getUUID());
        final RepositoryData repositoryData = getRepositoryData();
        List<SnapshotId> snapshotIds = repositoryData.getSnapshotIds();
        if (!snapshotIds.contains(snapshotId)) {
            writeIndexGen(repositoryData.addSnapshot(snapshotId, indices), repositoryStateId);
        }
        return blobStoreSnapshot;
    } catch (IOException ex) {
        throw new RepositoryException(metadata.name(), "failed to update snapshot in repository", ex);
    }
}
Also used : IndexId(org.elasticsearch.repositories.IndexId) SnapshotId(org.elasticsearch.snapshots.SnapshotId) SnapshotInfo(org.elasticsearch.snapshots.SnapshotInfo) RepositoryException(org.elasticsearch.repositories.RepositoryException) IOException(java.io.IOException) RepositoryData(org.elasticsearch.repositories.RepositoryData)

Aggregations

RepositoryData (org.elasticsearch.repositories.RepositoryData)15 IOException (java.io.IOException)7 IndexId (org.elasticsearch.repositories.IndexId)7 ArrayList (java.util.ArrayList)6 ShardId (org.elasticsearch.index.shard.ShardId)6 List (java.util.List)5 IndexMetaData (org.elasticsearch.cluster.metadata.IndexMetaData)5 RepositoryException (org.elasticsearch.repositories.RepositoryException)5 HashMap (java.util.HashMap)4 ParameterizedMessage (org.apache.logging.log4j.message.ParameterizedMessage)4 Supplier (org.apache.logging.log4j.util.Supplier)4 ClusterState (org.elasticsearch.cluster.ClusterState)4 RepositoriesService (org.elasticsearch.repositories.RepositoriesService)4 ObjectCursor (com.carrotsearch.hppc.cursors.ObjectCursor)3 ObjectObjectCursor (com.carrotsearch.hppc.cursors.ObjectObjectCursor)3 Collections (java.util.Collections)3 HashSet (java.util.HashSet)3 Map (java.util.Map)3 Set (java.util.Set)3 Collectors (java.util.stream.Collectors)3