Search in sources :

Example 1 with SnapshotsInProgress

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

the class SharedClusterSnapshotRestoreIT method testDeleteOrphanSnapshot.

public void testDeleteOrphanSnapshot() throws Exception {
    Client client = client();
    logger.info("-->  creating repository");
    final String repositoryName = "test-repo";
    assertAcked(client.admin().cluster().preparePutRepository(repositoryName).setType("mock").setSettings(Settings.builder().put("location", randomRepoPath()).put("compress", randomBoolean()).put("chunk_size", randomIntBetween(100, 1000), ByteSizeUnit.BYTES)));
    logger.info("--> create the index");
    final String idxName = "test-idx";
    createIndex(idxName);
    ensureGreen();
    ClusterService clusterService = internalCluster().getInstance(ClusterService.class, internalCluster().getMasterName());
    final CountDownLatch countDownLatch = new CountDownLatch(1);
    logger.info("--> snapshot");
    final String snapshotName = "test-snap";
    CreateSnapshotResponse createSnapshotResponse = client.admin().cluster().prepareCreateSnapshot(repositoryName, snapshotName).setWaitForCompletion(true).setIndices(idxName).get();
    assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0));
    assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().totalShards()));
    logger.info("--> emulate an orphan snapshot");
    RepositoriesService repositoriesService = internalCluster().getInstance(RepositoriesService.class, internalCluster().getMasterName());
    final RepositoryData repositoryData = repositoriesService.repository(repositoryName).getRepositoryData();
    final IndexId indexId = repositoryData.resolveIndexId(idxName);
    clusterService.submitStateUpdateTask("orphan snapshot test", new ClusterStateUpdateTask() {

        @Override
        public ClusterState execute(ClusterState currentState) {
            // Simulate orphan snapshot
            ImmutableOpenMap.Builder<ShardId, ShardSnapshotStatus> shards = ImmutableOpenMap.builder();
            shards.put(new ShardId(idxName, "_na_", 0), new ShardSnapshotStatus("unknown-node", State.ABORTED));
            shards.put(new ShardId(idxName, "_na_", 1), new ShardSnapshotStatus("unknown-node", State.ABORTED));
            shards.put(new ShardId(idxName, "_na_", 2), new ShardSnapshotStatus("unknown-node", State.ABORTED));
            List<Entry> entries = new ArrayList<>();
            entries.add(new Entry(new Snapshot(repositoryName, createSnapshotResponse.getSnapshotInfo().snapshotId()), true, false, State.ABORTED, Collections.singletonList(indexId), System.currentTimeMillis(), repositoryData.getGenId(), shards.build()));
            return ClusterState.builder(currentState).putCustom(SnapshotsInProgress.TYPE, new SnapshotsInProgress(Collections.unmodifiableList(entries))).build();
        }

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

        @Override
        public void clusterStateProcessed(String source, ClusterState oldState, final ClusterState newState) {
            countDownLatch.countDown();
        }
    });
    countDownLatch.await();
    logger.info("--> try deleting the orphan snapshot");
    assertAcked(client.admin().cluster().prepareDeleteSnapshot(repositoryName, snapshotName).get("10s"));
}
Also used : IndexId(org.elasticsearch.repositories.IndexId) ClusterState(org.elasticsearch.cluster.ClusterState) XContentFactory.jsonBuilder(org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder) IndexRequestBuilder(org.elasticsearch.action.index.IndexRequestBuilder) ClusterStateUpdateTask(org.elasticsearch.cluster.ClusterStateUpdateTask) Matchers.containsString(org.hamcrest.Matchers.containsString) CountDownLatch(java.util.concurrent.CountDownLatch) InvalidIndexNameException(org.elasticsearch.indices.InvalidIndexNameException) ExecutionException(java.util.concurrent.ExecutionException) RepositoryException(org.elasticsearch.repositories.RepositoryException) RepositoryData(org.elasticsearch.repositories.RepositoryData) ShardId(org.elasticsearch.index.shard.ShardId) Entry(org.elasticsearch.cluster.SnapshotsInProgress.Entry) ClusterService(org.elasticsearch.cluster.service.ClusterService) CreateSnapshotResponse(org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse) RepositoriesService(org.elasticsearch.repositories.RepositoriesService) SnapshotsInProgress(org.elasticsearch.cluster.SnapshotsInProgress) ShardSnapshotStatus(org.elasticsearch.cluster.SnapshotsInProgress.ShardSnapshotStatus) ArrayList(java.util.ArrayList) List(java.util.List) Client(org.elasticsearch.client.Client)

Example 2 with SnapshotsInProgress

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

the class AbstractSnapshotIntegTestCase method waitForCompletion.

public SnapshotInfo waitForCompletion(String repository, String snapshotName, TimeValue timeout) throws InterruptedException {
    long start = System.currentTimeMillis();
    while (System.currentTimeMillis() - start < timeout.millis()) {
        List<SnapshotInfo> snapshotInfos = client().admin().cluster().prepareGetSnapshots(repository).setSnapshots(snapshotName).get().getSnapshots();
        assertThat(snapshotInfos.size(), equalTo(1));
        if (snapshotInfos.get(0).state().completed()) {
            // Make sure that snapshot clean up operations are finished
            ClusterStateResponse stateResponse = client().admin().cluster().prepareState().get();
            SnapshotsInProgress snapshotsInProgress = stateResponse.getState().custom(SnapshotsInProgress.TYPE);
            if (snapshotsInProgress == null) {
                return snapshotInfos.get(0);
            } else {
                boolean found = false;
                for (SnapshotsInProgress.Entry entry : snapshotsInProgress.entries()) {
                    final Snapshot curr = entry.snapshot();
                    if (curr.getRepository().equals(repository) && curr.getSnapshotId().getName().equals(snapshotName)) {
                        found = true;
                        break;
                    }
                }
                if (found == false) {
                    return snapshotInfos.get(0);
                }
            }
        }
        Thread.sleep(100);
    }
    fail("Timeout!!!");
    return null;
}
Also used : ClusterStateResponse(org.elasticsearch.action.admin.cluster.state.ClusterStateResponse) SnapshotsInProgress(org.elasticsearch.cluster.SnapshotsInProgress)

Example 3 with SnapshotsInProgress

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

the class SnapshotShardsService method applyClusterState.

@Override
public void applyClusterState(ClusterChangedEvent event) {
    try {
        SnapshotsInProgress prev = event.previousState().custom(SnapshotsInProgress.TYPE);
        SnapshotsInProgress curr = event.state().custom(SnapshotsInProgress.TYPE);
        if ((prev == null && curr != null) || (prev != null && prev.equals(curr) == false)) {
            processIndexShardSnapshots(event);
        }
        String masterNodeId = event.state().nodes().getMasterNodeId();
        if (masterNodeId != null && masterNodeId.equals(event.previousState().nodes().getMasterNodeId()) == false) {
            syncShardStatsOnNewMaster(event);
        }
    } catch (Exception e) {
        logger.warn("Failed to update snapshot state ", e);
    }
}
Also used : SnapshotsInProgress(org.elasticsearch.cluster.SnapshotsInProgress) IndexShardSnapshotFailedException(org.elasticsearch.index.snapshots.IndexShardSnapshotFailedException) SnapshotFailedEngineException(org.elasticsearch.index.engine.SnapshotFailedEngineException) IOException(java.io.IOException)

Example 4 with SnapshotsInProgress

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

the class SnapshotShardsService method syncShardStatsOnNewMaster.

/**
     * Checks if any shards were processed that the new master doesn't know about
     */
private void syncShardStatsOnNewMaster(ClusterChangedEvent event) {
    SnapshotsInProgress snapshotsInProgress = event.state().custom(SnapshotsInProgress.TYPE);
    if (snapshotsInProgress == null) {
        return;
    }
    final String localNodeId = event.state().nodes().getLocalNodeId();
    final DiscoveryNode masterNode = event.state().nodes().getMasterNode();
    for (SnapshotsInProgress.Entry snapshot : snapshotsInProgress.entries()) {
        if (snapshot.state() == State.STARTED || snapshot.state() == State.ABORTED) {
            Map<ShardId, IndexShardSnapshotStatus> localShards = currentSnapshotShards(snapshot.snapshot());
            if (localShards != null) {
                ImmutableOpenMap<ShardId, ShardSnapshotStatus> masterShards = snapshot.shards();
                for (Map.Entry<ShardId, IndexShardSnapshotStatus> localShard : localShards.entrySet()) {
                    ShardId shardId = localShard.getKey();
                    IndexShardSnapshotStatus localShardStatus = localShard.getValue();
                    ShardSnapshotStatus masterShard = masterShards.get(shardId);
                    if (masterShard != null && masterShard.state().completed() == false) {
                        // Master knows about the shard and thinks it has not completed
                        if (localShardStatus.stage() == Stage.DONE) {
                            // but we think the shard is done - we need to make new master know that the shard is done
                            logger.debug("[{}] new master thinks the shard [{}] is not completed but the shard is done locally, updating status on the master", snapshot.snapshot(), shardId);
                            updateIndexShardSnapshotStatus(snapshot.snapshot(), shardId, new ShardSnapshotStatus(localNodeId, State.SUCCESS), masterNode);
                        } else if (localShard.getValue().stage() == Stage.FAILURE) {
                            // but we think the shard failed - we need to make new master know that the shard failed
                            logger.debug("[{}] new master thinks the shard [{}] is not completed but the shard failed locally, updating status on master", snapshot.snapshot(), shardId);
                            updateIndexShardSnapshotStatus(snapshot.snapshot(), shardId, new ShardSnapshotStatus(localNodeId, State.FAILED, localShardStatus.failure()), masterNode);
                        }
                    }
                }
            }
        }
    }
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) IndexShardSnapshotStatus(org.elasticsearch.index.snapshots.IndexShardSnapshotStatus) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) SnapshotsInProgress(org.elasticsearch.cluster.SnapshotsInProgress) ShardSnapshotStatus(org.elasticsearch.cluster.SnapshotsInProgress.ShardSnapshotStatus) IndexShardSnapshotStatus(org.elasticsearch.index.snapshots.IndexShardSnapshotStatus) Map(java.util.Map) ImmutableOpenMap(org.elasticsearch.common.collect.ImmutableOpenMap) HashMap(java.util.HashMap) Collections.emptyMap(java.util.Collections.emptyMap) Collections.unmodifiableMap(java.util.Collections.unmodifiableMap)

Example 5 with SnapshotsInProgress

use of org.elasticsearch.cluster.SnapshotsInProgress 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)

Aggregations

SnapshotsInProgress (org.elasticsearch.cluster.SnapshotsInProgress)16 ShardSnapshotStatus (org.elasticsearch.cluster.SnapshotsInProgress.ShardSnapshotStatus)7 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 ClusterState (org.elasticsearch.cluster.ClusterState)6 IndexShardSnapshotStatus (org.elasticsearch.index.snapshots.IndexShardSnapshotStatus)6 ClusterStateUpdateTask (org.elasticsearch.cluster.ClusterStateUpdateTask)5 ImmutableOpenMap (org.elasticsearch.common.collect.ImmutableOpenMap)5 IndexId (org.elasticsearch.repositories.IndexId)5 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)4 ShardId (org.elasticsearch.index.shard.ShardId)4 RepositoryMissingException (org.elasticsearch.repositories.RepositoryMissingException)4 ObjectObjectCursor (com.carrotsearch.hppc.cursors.ObjectObjectCursor)3 List (java.util.List)3 ParameterizedMessage (org.apache.logging.log4j.message.ParameterizedMessage)3 Supplier (org.apache.logging.log4j.util.Supplier)3 SnapshotDeletionsInProgress (org.elasticsearch.cluster.SnapshotDeletionsInProgress)3 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)3 Collections.emptyMap (java.util.Collections.emptyMap)2 Collections.unmodifiableMap (java.util.Collections.unmodifiableMap)2