Search in sources :

Example 1 with DeleteSnapshotRequest

use of org.opensearch.action.admin.cluster.snapshots.delete.DeleteSnapshotRequest in project OpenSearch by opensearch-project.

the class SnapshotRequestConverters method deleteSnapshot.

static Request deleteSnapshot(DeleteSnapshotRequest deleteSnapshotRequest) {
    String endpoint = new RequestConverters.EndpointBuilder().addPathPartAsIs("_snapshot").addPathPart(deleteSnapshotRequest.repository()).addCommaSeparatedPathParts(deleteSnapshotRequest.snapshots()).build();
    Request request = new Request(HttpDelete.METHOD_NAME, endpoint);
    RequestConverters.Params parameters = new RequestConverters.Params();
    parameters.withMasterTimeout(deleteSnapshotRequest.masterNodeTimeout());
    request.addParameters(parameters.asMap());
    return request;
}
Also used : CleanupRepositoryRequest(org.opensearch.action.admin.cluster.repositories.cleanup.CleanupRepositoryRequest) DeleteRepositoryRequest(org.opensearch.action.admin.cluster.repositories.delete.DeleteRepositoryRequest) VerifyRepositoryRequest(org.opensearch.action.admin.cluster.repositories.verify.VerifyRepositoryRequest) CloneSnapshotRequest(org.opensearch.action.admin.cluster.snapshots.clone.CloneSnapshotRequest) DeleteSnapshotRequest(org.opensearch.action.admin.cluster.snapshots.delete.DeleteSnapshotRequest) GetRepositoriesRequest(org.opensearch.action.admin.cluster.repositories.get.GetRepositoriesRequest) RestoreSnapshotRequest(org.opensearch.action.admin.cluster.snapshots.restore.RestoreSnapshotRequest) PutRepositoryRequest(org.opensearch.action.admin.cluster.repositories.put.PutRepositoryRequest) CreateSnapshotRequest(org.opensearch.action.admin.cluster.snapshots.create.CreateSnapshotRequest) GetSnapshotsRequest(org.opensearch.action.admin.cluster.snapshots.get.GetSnapshotsRequest) SnapshotsStatusRequest(org.opensearch.action.admin.cluster.snapshots.status.SnapshotsStatusRequest)

Example 2 with DeleteSnapshotRequest

use of org.opensearch.action.admin.cluster.snapshots.delete.DeleteSnapshotRequest in project OpenSearch by opensearch-project.

the class SnapshotRequestConvertersTests method testDeleteSnapshot.

public void testDeleteSnapshot() {
    Map<String, String> expectedParams = new HashMap<>();
    String repository = RequestConvertersTests.randomIndicesNames(1, 1)[0];
    String snapshot = "snapshot-" + randomAlphaOfLengthBetween(2, 5).toLowerCase(Locale.ROOT);
    String endpoint = String.format(Locale.ROOT, "/_snapshot/%s/%s", repository, snapshot);
    DeleteSnapshotRequest deleteSnapshotRequest = new DeleteSnapshotRequest();
    deleteSnapshotRequest.repository(repository);
    deleteSnapshotRequest.snapshots(snapshot);
    RequestConvertersTests.setRandomMasterTimeout(deleteSnapshotRequest, expectedParams);
    Request request = SnapshotRequestConverters.deleteSnapshot(deleteSnapshotRequest);
    assertThat(request.getEndpoint(), equalTo(endpoint));
    assertThat(request.getMethod(), equalTo(HttpDelete.METHOD_NAME));
    assertThat(request.getParameters(), equalTo(expectedParams));
    assertNull(request.getEntity());
}
Also used : HashMap(java.util.HashMap) VerifyRepositoryRequest(org.opensearch.action.admin.cluster.repositories.verify.VerifyRepositoryRequest) RestoreSnapshotRequest(org.opensearch.action.admin.cluster.snapshots.restore.RestoreSnapshotRequest) SnapshotsStatusRequest(org.opensearch.action.admin.cluster.snapshots.status.SnapshotsStatusRequest) DeleteRepositoryRequest(org.opensearch.action.admin.cluster.repositories.delete.DeleteRepositoryRequest) AcknowledgedRequest(org.opensearch.action.support.master.AcknowledgedRequest) DeleteSnapshotRequest(org.opensearch.action.admin.cluster.snapshots.delete.DeleteSnapshotRequest) GetRepositoriesRequest(org.opensearch.action.admin.cluster.repositories.get.GetRepositoriesRequest) PutRepositoryRequest(org.opensearch.action.admin.cluster.repositories.put.PutRepositoryRequest) CreateSnapshotRequest(org.opensearch.action.admin.cluster.snapshots.create.CreateSnapshotRequest) GetSnapshotsRequest(org.opensearch.action.admin.cluster.snapshots.get.GetSnapshotsRequest) DeleteSnapshotRequest(org.opensearch.action.admin.cluster.snapshots.delete.DeleteSnapshotRequest)

Example 3 with DeleteSnapshotRequest

use of org.opensearch.action.admin.cluster.snapshots.delete.DeleteSnapshotRequest in project OpenSearch by opensearch-project.

the class SnapshotIT method testCreateSnapshot.

public void testCreateSnapshot() throws Exception {
    String repository = "test_repository";
    assertTrue(createTestRepository(repository, FsRepository.TYPE, "{\"location\": \".\"}").isAcknowledged());
    String snapshot = "test_snapshot";
    CreateSnapshotRequest request = new CreateSnapshotRequest(repository, snapshot);
    boolean waitForCompletion = randomBoolean();
    request.waitForCompletion(waitForCompletion);
    if (randomBoolean()) {
        request.userMetadata(randomUserMetadata());
    }
    request.partial(randomBoolean());
    request.includeGlobalState(randomBoolean());
    CreateSnapshotResponse response = createTestSnapshot(request);
    assertEquals(waitForCompletion ? RestStatus.OK : RestStatus.ACCEPTED, response.status());
    if (waitForCompletion == false) {
        // If we don't wait for the snapshot to complete we have to cancel it to not leak the snapshot task
        AcknowledgedResponse deleteResponse = execute(new DeleteSnapshotRequest(repository, snapshot), highLevelClient().snapshot()::delete, highLevelClient().snapshot()::deleteAsync);
        assertTrue(deleteResponse.isAcknowledged());
    }
}
Also used : CreateSnapshotResponse(org.opensearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse) CreateSnapshotRequest(org.opensearch.action.admin.cluster.snapshots.create.CreateSnapshotRequest) AcknowledgedResponse(org.opensearch.action.support.master.AcknowledgedResponse) DeleteSnapshotRequest(org.opensearch.action.admin.cluster.snapshots.delete.DeleteSnapshotRequest)

Example 4 with DeleteSnapshotRequest

use of org.opensearch.action.admin.cluster.snapshots.delete.DeleteSnapshotRequest in project OpenSearch by opensearch-project.

the class RestDeleteSnapshotAction method prepareRequest.

@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
    DeleteSnapshotRequest deleteSnapshotRequest = deleteSnapshotRequest(request.param("repository"), Strings.splitStringByCommaToArray(request.param("snapshot")));
    deleteSnapshotRequest.masterNodeTimeout(request.paramAsTime("master_timeout", deleteSnapshotRequest.masterNodeTimeout()));
    return channel -> client.admin().cluster().deleteSnapshot(deleteSnapshotRequest, new RestToXContentListener<>(channel));
}
Also used : DELETE(org.opensearch.rest.RestRequest.Method.DELETE) List(java.util.List) NodeClient(org.opensearch.client.node.NodeClient) RestToXContentListener(org.opensearch.rest.action.RestToXContentListener) RestRequest(org.opensearch.rest.RestRequest) Requests.deleteSnapshotRequest(org.opensearch.client.Requests.deleteSnapshotRequest) IOException(java.io.IOException) DeleteSnapshotRequest(org.opensearch.action.admin.cluster.snapshots.delete.DeleteSnapshotRequest) BaseRestHandler(org.opensearch.rest.BaseRestHandler) Strings(org.opensearch.common.Strings) Collections.singletonList(java.util.Collections.singletonList) DeleteSnapshotRequest(org.opensearch.action.admin.cluster.snapshots.delete.DeleteSnapshotRequest)

Example 5 with DeleteSnapshotRequest

use of org.opensearch.action.admin.cluster.snapshots.delete.DeleteSnapshotRequest in project OpenSearch by opensearch-project.

the class SnapshotsService method deleteSnapshots.

/**
 * Deletes snapshots from the repository. In-progress snapshots matched by the delete will be aborted before deleting them.
 *
 * @param request         delete snapshot request
 * @param listener        listener
 */
public void deleteSnapshots(final DeleteSnapshotRequest request, final ActionListener<Void> listener) {
    final String[] snapshotNames = request.snapshots();
    final String repoName = request.repository();
    logger.info(() -> new ParameterizedMessage("deleting snapshots [{}] from repository [{}]", Strings.arrayToCommaDelimitedString(snapshotNames), repoName));
    final Repository repository = repositoriesService.repository(repoName);
    repository.executeConsistentStateUpdate(repositoryData -> new ClusterStateUpdateTask(Priority.NORMAL) {

        private Snapshot runningSnapshot;

        private ClusterStateUpdateTask deleteFromRepoTask;

        private boolean abortedDuringInit = false;

        private List<SnapshotId> outstandingDeletes;

        @Override
        public ClusterState execute(ClusterState currentState) throws Exception {
            final Version minNodeVersion = currentState.nodes().getMinNodeVersion();
            if (snapshotNames.length > 1 && minNodeVersion.before(MULTI_DELETE_VERSION)) {
                throw new IllegalArgumentException("Deleting multiple snapshots in a single request is only supported in version [ " + MULTI_DELETE_VERSION + "] but cluster contained node of version [" + currentState.nodes().getMinNodeVersion() + "]");
            }
            final SnapshotsInProgress snapshots = currentState.custom(SnapshotsInProgress.TYPE, SnapshotsInProgress.EMPTY);
            final List<SnapshotsInProgress.Entry> snapshotEntries = findInProgressSnapshots(snapshots, snapshotNames, repoName);
            final List<SnapshotId> snapshotIds = matchingSnapshotIds(snapshotEntries.stream().map(e -> e.snapshot().getSnapshotId()).collect(Collectors.toList()), repositoryData, snapshotNames, repoName);
            if (snapshotEntries.isEmpty() || minNodeVersion.onOrAfter(SnapshotsService.FULL_CONCURRENCY_VERSION)) {
                deleteFromRepoTask = createDeleteStateUpdate(snapshotIds, repoName, repositoryData, Priority.NORMAL, listener);
                return deleteFromRepoTask.execute(currentState);
            }
            assert snapshotEntries.size() == 1 : "Expected just a single running snapshot but saw " + snapshotEntries;
            final SnapshotsInProgress.Entry snapshotEntry = snapshotEntries.get(0);
            runningSnapshot = snapshotEntry.snapshot();
            final ImmutableOpenMap<ShardId, ShardSnapshotStatus> shards;
            final State state = snapshotEntry.state();
            final String failure;
            outstandingDeletes = new ArrayList<>(snapshotIds);
            if (state != State.INIT) {
                // INIT state snapshots won't ever be physically written to the repository but all other states will end up in the repo
                outstandingDeletes.add(runningSnapshot.getSnapshotId());
            }
            if (state == State.INIT) {
                // snapshot is still initializing, mark it as aborted
                shards = snapshotEntry.shards();
                assert shards.isEmpty();
                failure = "Snapshot was aborted during initialization";
                abortedDuringInit = true;
            } else if (state == State.STARTED) {
                // snapshot is started - mark every non completed shard as aborted
                final SnapshotsInProgress.Entry abortedEntry = snapshotEntry.abort();
                shards = abortedEntry.shards();
                failure = abortedEntry.failure();
            } 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 but a node is gone - this is the only case
                    // where we force to finish the snapshot
                    logger.debug("trying to delete completed snapshot with no finalizing shards - can delete immediately");
                    shards = snapshotEntry.shards();
                }
                failure = snapshotEntry.failure();
            }
            return ClusterState.builder(currentState).putCustom(SnapshotsInProgress.TYPE, SnapshotsInProgress.of(snapshots.entries().stream().filter(existing -> abortedDuringInit == false || existing.equals(snapshotEntry) == false).map(existing -> {
                if (existing.equals(snapshotEntry)) {
                    return snapshotEntry.fail(shards, State.ABORTED, failure);
                }
                return existing;
            }).collect(Collectors.toList()))).build();
        }

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

        @Override
        public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
            if (deleteFromRepoTask != null) {
                assert outstandingDeletes == null : "Shouldn't have outstanding deletes after already starting delete task";
                deleteFromRepoTask.clusterStateProcessed(source, oldState, newState);
                return;
            }
            if (abortedDuringInit) {
                // BwC Path where we removed an outdated INIT state snapshot from the cluster state
                logger.info("Successfully aborted snapshot [{}]", runningSnapshot);
                if (outstandingDeletes.isEmpty()) {
                    listener.onResponse(null);
                } else {
                    clusterService.submitStateUpdateTask("delete snapshot", createDeleteStateUpdate(outstandingDeletes, repoName, repositoryData, Priority.IMMEDIATE, listener));
                }
                return;
            }
            logger.trace("adding snapshot completion listener to wait for deleted snapshot to finish");
            addListener(runningSnapshot, ActionListener.wrap(result -> {
                logger.debug("deleted snapshot completed - deleting files");
                clusterService.submitStateUpdateTask("delete snapshot", createDeleteStateUpdate(outstandingDeletes, repoName, result.v1(), Priority.IMMEDIATE, listener));
            }, e -> {
                if (ExceptionsHelper.unwrap(e, NotMasterException.class, FailedToCommitClusterStateException.class) != null) {
                    logger.warn("master failover before deleted snapshot could complete", e);
                    // Just pass the exception to the transport handler as is so it is retried on the new master
                    listener.onFailure(e);
                } else {
                    logger.warn("deleted snapshot failed", e);
                    listener.onFailure(new SnapshotMissingException(runningSnapshot.getRepository(), runningSnapshot.getSnapshotId(), e));
                }
            }));
        }

        @Override
        public TimeValue timeout() {
            return request.masterNodeTimeout();
        }
    }, "delete snapshot", listener::onFailure);
}
Also used : RepositoryMissingException(org.opensearch.repositories.RepositoryMissingException) ImmutableOpenMap(org.opensearch.common.collect.ImmutableOpenMap) Arrays(java.util.Arrays) Metadata(org.opensearch.cluster.metadata.Metadata) Collections.unmodifiableList(java.util.Collections.unmodifiableList) DataStream(org.opensearch.cluster.metadata.DataStream) Version(org.opensearch.Version) ClusterStateApplier(org.opensearch.cluster.ClusterStateApplier) Regex(org.opensearch.common.regex.Regex) Strings(org.opensearch.common.Strings) GroupedActionListener(org.opensearch.action.support.GroupedActionListener) Map(java.util.Map) ActionListener(org.opensearch.action.ActionListener) EnumSet(java.util.EnumSet) Repository(org.opensearch.repositories.Repository) TimeValue(org.opensearch.common.unit.TimeValue) Index(org.opensearch.index.Index) ExceptionsHelper(org.opensearch.ExceptionsHelper) Set(java.util.Set) ClusterStateTaskExecutor(org.opensearch.cluster.ClusterStateTaskExecutor) Settings(org.opensearch.common.settings.Settings) ObjectCursor(com.carrotsearch.hppc.cursors.ObjectCursor) TransportService(org.opensearch.transport.TransportService) FailedToCommitClusterStateException(org.opensearch.cluster.coordination.FailedToCommitClusterStateException) ActionFilters(org.opensearch.action.support.ActionFilters) AbstractLifecycleComponent(org.opensearch.common.component.AbstractLifecycleComponent) ShardState(org.opensearch.cluster.SnapshotsInProgress.ShardState) Logger(org.apache.logging.log4j.Logger) Stream(java.util.stream.Stream) ClusterStateUpdateTask(org.opensearch.cluster.ClusterStateUpdateTask) StepListener(org.opensearch.action.StepListener) State(org.opensearch.cluster.SnapshotsInProgress.State) IndexNameExpressionResolver(org.opensearch.cluster.metadata.IndexNameExpressionResolver) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) RepositoriesService(org.opensearch.repositories.RepositoriesService) ThreadPool(org.opensearch.threadpool.ThreadPool) Priority(org.opensearch.common.Priority) TransportMasterNodeAction(org.opensearch.action.support.master.TransportMasterNodeAction) ArrayList(java.util.ArrayList) ClusterState(org.opensearch.cluster.ClusterState) LegacyESVersion(org.opensearch.LegacyESVersion) ClusterStateTaskConfig(org.opensearch.cluster.ClusterStateTaskConfig) RepositoryCleanupInProgress(org.opensearch.cluster.RepositoryCleanupInProgress) RepositoriesMetadata(org.opensearch.cluster.metadata.RepositoriesMetadata) Executor(java.util.concurrent.Executor) IOException(java.io.IOException) DeleteSnapshotRequest(org.opensearch.action.admin.cluster.snapshots.delete.DeleteSnapshotRequest) ClusterService(org.opensearch.cluster.service.ClusterService) RestoreInProgress(org.opensearch.cluster.RestoreInProgress) RoutingTable(org.opensearch.cluster.routing.RoutingTable) SnapshotsInProgress.completed(org.opensearch.cluster.SnapshotsInProgress.completed) ClusterChangedEvent(org.opensearch.cluster.ClusterChangedEvent) ShardGenerations(org.opensearch.repositories.ShardGenerations) AbstractRunnable(org.opensearch.common.util.concurrent.AbstractRunnable) ObjectObjectCursor(com.carrotsearch.hppc.cursors.ObjectObjectCursor) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) IndexId(org.opensearch.repositories.IndexId) Locale(java.util.Locale) NotMasterException(org.opensearch.cluster.NotMasterException) ShardSnapshotStatus(org.opensearch.cluster.SnapshotsInProgress.ShardSnapshotStatus) RepositoryException(org.opensearch.repositories.RepositoryException) IndexShardRoutingTable(org.opensearch.cluster.routing.IndexShardRoutingTable) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ClusterBlockException(org.opensearch.cluster.block.ClusterBlockException) Collectors(java.util.stream.Collectors) Nullable(org.opensearch.common.Nullable) Tuple(org.opensearch.common.collect.Tuple) Objects(java.util.Objects) List(java.util.List) Optional(java.util.Optional) ClusterStateTaskListener(org.opensearch.cluster.ClusterStateTaskListener) DiscoveryNodes(org.opensearch.cluster.node.DiscoveryNodes) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) ActionRunnable(org.opensearch.action.ActionRunnable) SnapshotsInProgress(org.opensearch.cluster.SnapshotsInProgress) CloneSnapshotRequest(org.opensearch.action.admin.cluster.snapshots.clone.CloneSnapshotRequest) HashMap(java.util.HashMap) SnapshotDeletionsInProgress(org.opensearch.cluster.SnapshotDeletionsInProgress) Deque(java.util.Deque) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) Function(java.util.function.Function) HashSet(java.util.HashSet) IndexRoutingTable(org.opensearch.cluster.routing.IndexRoutingTable) UUIDs(org.opensearch.common.UUIDs) LinkedList(java.util.LinkedList) StreamInput(org.opensearch.common.io.stream.StreamInput) RepositoryData(org.opensearch.repositories.RepositoryData) Setting(org.opensearch.common.settings.Setting) Iterator(java.util.Iterator) Collections.emptySet(java.util.Collections.emptySet) RepositoryShardId(org.opensearch.repositories.RepositoryShardId) ShardRouting(org.opensearch.cluster.routing.ShardRouting) ShardId(org.opensearch.index.shard.ShardId) Consumer(java.util.function.Consumer) CreateSnapshotRequest(org.opensearch.action.admin.cluster.snapshots.create.CreateSnapshotRequest) LogManager(org.apache.logging.log4j.LogManager) Collections(java.util.Collections) FailedToCommitClusterStateException(org.opensearch.cluster.coordination.FailedToCommitClusterStateException) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) ImmutableOpenMap(org.opensearch.common.collect.ImmutableOpenMap) Version(org.opensearch.Version) LegacyESVersion(org.opensearch.LegacyESVersion) Collections.unmodifiableList(java.util.Collections.unmodifiableList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) List(java.util.List) LinkedList(java.util.LinkedList) NotMasterException(org.opensearch.cluster.NotMasterException) TimeValue(org.opensearch.common.unit.TimeValue) ClusterState(org.opensearch.cluster.ClusterState) ClusterStateUpdateTask(org.opensearch.cluster.ClusterStateUpdateTask) RepositoryMissingException(org.opensearch.repositories.RepositoryMissingException) FailedToCommitClusterStateException(org.opensearch.cluster.coordination.FailedToCommitClusterStateException) IOException(java.io.IOException) NotMasterException(org.opensearch.cluster.NotMasterException) RepositoryException(org.opensearch.repositories.RepositoryException) ClusterBlockException(org.opensearch.cluster.block.ClusterBlockException) Repository(org.opensearch.repositories.Repository) ShardState(org.opensearch.cluster.SnapshotsInProgress.ShardState) State(org.opensearch.cluster.SnapshotsInProgress.State) ClusterState(org.opensearch.cluster.ClusterState) SnapshotsInProgress(org.opensearch.cluster.SnapshotsInProgress) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) ShardSnapshotStatus(org.opensearch.cluster.SnapshotsInProgress.ShardSnapshotStatus)

Aggregations

DeleteSnapshotRequest (org.opensearch.action.admin.cluster.snapshots.delete.DeleteSnapshotRequest)10 CreateSnapshotResponse (org.opensearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse)5 AcknowledgedResponse (org.opensearch.action.support.master.AcknowledgedResponse)5 IOException (java.io.IOException)4 HashMap (java.util.HashMap)4 List (java.util.List)4 CreateSnapshotRequest (org.opensearch.action.admin.cluster.snapshots.create.CreateSnapshotRequest)4 Arrays (java.util.Arrays)3 Collection (java.util.Collection)3 Collections (java.util.Collections)3 Collections.emptySet (java.util.Collections.emptySet)3 HashSet (java.util.HashSet)3 Map (java.util.Map)3 Objects (java.util.Objects)3 Optional (java.util.Optional)3 Set (java.util.Set)3 Collectors (java.util.stream.Collectors)3 Stream (java.util.stream.Stream)3 LogManager (org.apache.logging.log4j.LogManager)3 Logger (org.apache.logging.log4j.Logger)3