Search in sources :

Example 1 with GetSnapshotsResponse

use of org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsResponse in project elasticsearch by elastic.

the class RestoreBackwardsCompatIT method testOldSnapshot.

private void testOldSnapshot(String version, String repo, String snapshot) throws IOException {
    logger.info("--> get snapshot and check its version");
    GetSnapshotsResponse getSnapshotsResponse = client().admin().cluster().prepareGetSnapshots(repo).setSnapshots(snapshot).get();
    assertThat(getSnapshotsResponse.getSnapshots().size(), equalTo(1));
    SnapshotInfo snapshotInfo = getSnapshotsResponse.getSnapshots().get(0);
    assertThat(snapshotInfo.version().toString(), equalTo(version));
    logger.info("--> restoring snapshot");
    RestoreSnapshotResponse response = client().admin().cluster().prepareRestoreSnapshot(repo, snapshot).setRestoreGlobalState(true).setWaitForCompletion(true).get();
    assertThat(response.status(), equalTo(RestStatus.OK));
    RestoreInfo restoreInfo = response.getRestoreInfo();
    assertThat(restoreInfo.successfulShards(), greaterThan(0));
    assertThat(restoreInfo.successfulShards(), equalTo(restoreInfo.totalShards()));
    assertThat(restoreInfo.failedShards(), equalTo(0));
    String index = restoreInfo.indices().get(0);
    logger.info("--> check search");
    SearchResponse searchResponse = client().prepareSearch(index).get();
    assertThat(searchResponse.getHits().getTotalHits(), greaterThan(1L));
    logger.info("--> check settings");
    ClusterState clusterState = client().admin().cluster().prepareState().get().getState();
    assertThat(clusterState.metaData().persistentSettings().get(FilterAllocationDecider.CLUSTER_ROUTING_EXCLUDE_GROUP_SETTING.getKey() + "version_attr"), equalTo(version));
    logger.info("--> check templates");
    IndexTemplateMetaData template = clusterState.getMetaData().templates().get("template_" + version.toLowerCase(Locale.ROOT));
    assertThat(template, notNullValue());
    assertThat(template.patterns(), equalTo(Collections.singletonList("te*")));
    assertThat(template.settings().getAsInt(IndexMetaData.SETTING_NUMBER_OF_SHARDS, -1), equalTo(1));
    assertThat(template.mappings().size(), equalTo(1));
    assertThat(template.mappings().get("type1").string(), anyOf(equalTo("{\"type1\":{\"_source\":{\"enabled\":false}}}"), equalTo("{\"type1\":{\"_source\":{\"enabled\":\"false\"}}}"), equalTo("{\"type1\":{\"_source\":{\"enabled\":\"0\"}}}"), equalTo("{\"type1\":{\"_source\":{\"enabled\":0}}}"), equalTo("{\"type1\":{\"_source\":{\"enabled\":\"off\"}}}"), equalTo("{\"type1\":{\"_source\":{\"enabled\":\"no\"}}}")));
    assertThat(template.aliases().size(), equalTo(3));
    assertThat(template.aliases().get("alias1"), notNullValue());
    assertThat(template.aliases().get("alias2").filter().string(), containsString(version));
    assertThat(template.aliases().get("alias2").indexRouting(), equalTo("kimchy"));
    assertThat(template.aliases().get("{index}-alias"), notNullValue());
    logger.info("--> cleanup");
    cluster().wipeIndices(restoreInfo.indices().toArray(new String[restoreInfo.indices().size()]));
    cluster().wipeTemplates();
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) GetSnapshotsResponse(org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsResponse) SnapshotInfo(org.elasticsearch.snapshots.SnapshotInfo) RestoreInfo(org.elasticsearch.snapshots.RestoreInfo) IndexTemplateMetaData(org.elasticsearch.cluster.metadata.IndexTemplateMetaData) Matchers.containsString(org.hamcrest.Matchers.containsString) RestoreSnapshotResponse(org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotResponse) SearchResponse(org.elasticsearch.action.search.SearchResponse)

Example 2 with GetSnapshotsResponse

use of org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsResponse in project elasticsearch by elastic.

the class SharedClusterSnapshotRestoreIT method testGetSnapshotsRequest.

public void testGetSnapshotsRequest() throws Exception {
    final String repositoryName = "test-repo";
    final String indexName = "test-idx";
    final Client client = client();
    final Path repo = randomRepoPath();
    logger.info("-->  creating repository at {}", repo.toAbsolutePath());
    assertAcked(client.admin().cluster().preparePutRepository(repositoryName).setType("mock").setSettings(Settings.builder().put("location", repo).put("compress", false).put("chunk_size", randomIntBetween(100, 1000), ByteSizeUnit.BYTES).put("wait_after_unblock", 200)));
    logger.info("--> get snapshots on an empty repository");
    expectThrows(SnapshotMissingException.class, () -> client.admin().cluster().prepareGetSnapshots(repositoryName).addSnapshots("non-existent-snapshot").get());
    // with ignore unavailable set to true, should not throw an exception
    GetSnapshotsResponse getSnapshotsResponse = client.admin().cluster().prepareGetSnapshots(repositoryName).setIgnoreUnavailable(true).addSnapshots("non-existent-snapshot").get();
    assertThat(getSnapshotsResponse.getSnapshots().size(), equalTo(0));
    logger.info("--> creating an index and indexing documents");
    // Create index on 2 nodes and make sure each node has a primary by setting no replicas
    assertAcked(prepareCreate(indexName, 1, Settings.builder().put("number_of_replicas", 0)));
    ensureGreen();
    for (int i = 0; i < 10; i++) {
        index(indexName, "doc", Integer.toString(i), "foo", "bar" + i);
    }
    refresh();
    // make sure we return only the in-progress snapshot when taking the first snapshot on a clean repository
    // take initial snapshot with a block, making sure we only get 1 in-progress snapshot returned
    // block a node so the create snapshot operation can remain in progress
    final String initialBlockedNode = blockNodeWithIndex(repositoryName, indexName);
    ListenableActionFuture<CreateSnapshotResponse> responseListener = client.admin().cluster().prepareCreateSnapshot(repositoryName, "snap-on-empty-repo").setWaitForCompletion(false).setIndices(indexName).execute();
    // wait for block to kick in
    waitForBlock(initialBlockedNode, repositoryName, TimeValue.timeValueSeconds(60));
    getSnapshotsResponse = client.admin().cluster().prepareGetSnapshots("test-repo").setSnapshots(randomFrom("_all", "_current", "snap-on-*", "*-on-empty-repo", "snap-on-empty-repo")).get();
    assertEquals(1, getSnapshotsResponse.getSnapshots().size());
    assertEquals("snap-on-empty-repo", getSnapshotsResponse.getSnapshots().get(0).snapshotId().getName());
    // unblock node
    unblockNode(repositoryName, initialBlockedNode);
    // timeout after 10 seconds
    responseListener.actionGet(TimeValue.timeValueMillis(10000L));
    client.admin().cluster().prepareDeleteSnapshot(repositoryName, "snap-on-empty-repo").get();
    final int numSnapshots = randomIntBetween(1, 3) + 1;
    logger.info("--> take {} snapshot(s)", numSnapshots - 1);
    final String[] snapshotNames = new String[numSnapshots];
    for (int i = 0; i < numSnapshots - 1; i++) {
        final String snapshotName = randomAsciiOfLength(8).toLowerCase(Locale.ROOT);
        CreateSnapshotResponse createSnapshotResponse = client.admin().cluster().prepareCreateSnapshot(repositoryName, snapshotName).setWaitForCompletion(true).setIndices(indexName).get();
        assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0));
        snapshotNames[i] = snapshotName;
    }
    logger.info("--> take another snapshot to be in-progress");
    // add documents so there are data files to block on
    for (int i = 10; i < 20; i++) {
        index(indexName, "doc", Integer.toString(i), "foo", "bar" + i);
    }
    refresh();
    final String inProgressSnapshot = randomAsciiOfLength(8).toLowerCase(Locale.ROOT);
    snapshotNames[numSnapshots - 1] = inProgressSnapshot;
    // block a node so the create snapshot operation can remain in progress
    final String blockedNode = blockNodeWithIndex(repositoryName, indexName);
    client.admin().cluster().prepareCreateSnapshot(repositoryName, inProgressSnapshot).setWaitForCompletion(false).setIndices(indexName).get();
    // wait for block to kick in
    waitForBlock(blockedNode, repositoryName, TimeValue.timeValueSeconds(60));
    logger.info("--> get all snapshots with a current in-progress");
    // with ignore unavailable set to true, should not throw an exception
    final List<String> snapshotsToGet = new ArrayList<>();
    if (randomBoolean()) {
        // use _current plus the individual names of the finished snapshots
        snapshotsToGet.add("_current");
        for (int i = 0; i < numSnapshots - 1; i++) {
            snapshotsToGet.add(snapshotNames[i]);
        }
    } else {
        snapshotsToGet.add("_all");
    }
    getSnapshotsResponse = client.admin().cluster().prepareGetSnapshots(repositoryName).setSnapshots(snapshotsToGet.toArray(Strings.EMPTY_ARRAY)).get();
    List<String> sortedNames = Arrays.asList(snapshotNames);
    Collections.sort(sortedNames);
    assertThat(getSnapshotsResponse.getSnapshots().size(), equalTo(numSnapshots));
    assertThat(getSnapshotsResponse.getSnapshots().stream().map(s -> s.snapshotId().getName()).sorted().collect(Collectors.toList()), equalTo(sortedNames));
    getSnapshotsResponse = client.admin().cluster().prepareGetSnapshots(repositoryName).addSnapshots(snapshotNames).get();
    sortedNames = Arrays.asList(snapshotNames);
    Collections.sort(sortedNames);
    assertThat(getSnapshotsResponse.getSnapshots().size(), equalTo(numSnapshots));
    assertThat(getSnapshotsResponse.getSnapshots().stream().map(s -> s.snapshotId().getName()).sorted().collect(Collectors.toList()), equalTo(sortedNames));
    logger.info("--> make sure duplicates are not returned in the response");
    String regexName = snapshotNames[randomIntBetween(0, numSnapshots - 1)];
    final int splitPos = regexName.length() / 2;
    final String firstRegex = regexName.substring(0, splitPos) + "*";
    final String secondRegex = "*" + regexName.substring(splitPos);
    getSnapshotsResponse = client.admin().cluster().prepareGetSnapshots(repositoryName).addSnapshots(snapshotNames).addSnapshots(firstRegex, secondRegex).get();
    assertThat(getSnapshotsResponse.getSnapshots().size(), equalTo(numSnapshots));
    assertThat(getSnapshotsResponse.getSnapshots().stream().map(s -> s.snapshotId().getName()).sorted().collect(Collectors.toList()), equalTo(sortedNames));
    // unblock node
    unblockNode(repositoryName, blockedNode);
    waitForCompletion(repositoryName, inProgressSnapshot, TimeValue.timeValueSeconds(60));
}
Also used : Path(java.nio.file.Path) ShardId(org.elasticsearch.index.shard.ShardId) ByteSizeUnit(org.elasticsearch.common.unit.ByteSizeUnit) Arrays(java.util.Arrays) RestoreSnapshotResponse(org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotResponse) ClusterBlocks(org.elasticsearch.cluster.block.ClusterBlocks) ClusterState(org.elasticsearch.cluster.ClusterState) ClusterStateUpdateTask(org.elasticsearch.cluster.ClusterStateUpdateTask) Matchers.nullValue(org.hamcrest.Matchers.nullValue) Path(java.nio.file.Path) Priority(org.elasticsearch.common.Priority) GetSettingsResponse(org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) TestLogging(org.elasticsearch.test.junit.annotations.TestLogging) Matchers.allOf(org.hamcrest.Matchers.allOf) DeletePipelineRequest(org.elasticsearch.action.ingest.DeletePipelineRequest) ElasticsearchAssertions.assertAliasesMissing(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAliasesMissing) Matchers.startsWith(org.hamcrest.Matchers.startsWith) ElasticsearchAssertions.assertBlocked(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertBlocked) CountDownLatch(java.util.concurrent.CountDownLatch) Stream(java.util.stream.Stream) QueryBuilders.matchQuery(org.elasticsearch.index.query.QueryBuilders.matchQuery) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) SnapshotIndexStatus(org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotIndexStatus) InvalidIndexNameException(org.elasticsearch.indices.InvalidIndexNameException) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) Matchers.is(org.hamcrest.Matchers.is) Matchers.containsString(org.hamcrest.Matchers.containsString) ShardSnapshotStatus(org.elasticsearch.cluster.SnapshotsInProgress.ShardSnapshotStatus) XContentFactory(org.elasticsearch.common.xcontent.XContentFactory) ImmutableOpenMap(org.elasticsearch.common.collect.ImmutableOpenMap) GetPipelineResponse(org.elasticsearch.action.ingest.GetPipelineResponse) ClusterService(org.elasticsearch.cluster.service.ClusterService) ArrayList(java.util.ArrayList) BytesArray(org.elasticsearch.common.bytes.BytesArray) SnapshotStatus(org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotStatus) ElasticsearchAssertions.assertIndexTemplateMissing(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertIndexTemplateMissing) Matchers.lessThan(org.hamcrest.Matchers.lessThan) IndicesService(org.elasticsearch.indices.IndicesService) FlushResponse(org.elasticsearch.action.admin.indices.flush.FlushResponse) ElasticsearchAssertions.assertThrows(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows) Files(java.nio.file.Files) SETTING_NUMBER_OF_SHARDS(org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS) Client(org.elasticsearch.client.Client) IndexService(org.elasticsearch.index.IndexService) IOUtils(org.apache.lucene.util.IOUtils) RepositoriesService(org.elasticsearch.repositories.RepositoriesService) ExecutionException(java.util.concurrent.ExecutionException) SnapshotIndexShardStage(org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotIndexShardStage) SnapshotsStatusResponse(org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotsStatusResponse) ElasticsearchAssertions.assertAcked(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked) MappingMetaData(org.elasticsearch.cluster.metadata.MappingMetaData) PutRepositoryResponse(org.elasticsearch.action.admin.cluster.repositories.put.PutRepositoryResponse) IngestTestPlugin(org.elasticsearch.ingest.IngestTestPlugin) Settings(org.elasticsearch.common.settings.Settings) Locale(java.util.Locale) SearchResponse(org.elasticsearch.action.search.SearchResponse) XContentFactory.jsonBuilder(org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder) RepositoryException(org.elasticsearch.repositories.RepositoryException) ElasticsearchAssertions.assertIndexTemplateExists(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertIndexTemplateExists) Collection(java.util.Collection) StandardOpenOption(java.nio.file.StandardOpenOption) State(org.elasticsearch.cluster.SnapshotsInProgress.State) ElasticsearchAssertions.assertHitCount(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount) GetStoredScriptResponse(org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptResponse) BytesReference(org.elasticsearch.common.bytes.BytesReference) Collectors(java.util.stream.Collectors) ActiveShardCount(org.elasticsearch.action.support.ActiveShardCount) SeekableByteChannel(java.nio.channels.SeekableByteChannel) List(java.util.List) Version(org.elasticsearch.Version) IndexRequestBuilder(org.elasticsearch.action.index.IndexRequestBuilder) IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) MockScriptEngine(org.elasticsearch.script.MockScriptEngine) Matchers.equalTo(org.hamcrest.Matchers.equalTo) ElasticsearchAssertions.assertAliasesExist(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAliasesExist) CreateSnapshotResponse(org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse) RepositoryData(org.elasticsearch.repositories.RepositoryData) XContentType(org.elasticsearch.common.xcontent.XContentType) ListenableActionFuture(org.elasticsearch.action.ListenableActionFuture) IndexId(org.elasticsearch.repositories.IndexId) Entry(org.elasticsearch.cluster.SnapshotsInProgress.Entry) Strings(org.elasticsearch.common.Strings) SETTING_NUMBER_OF_REPLICAS(org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS) SnapshotIndexShardStatus(org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotIndexShardStatus) TimeValue(org.elasticsearch.common.unit.TimeValue) GetSnapshotsResponse(org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsResponse) Plugin(org.elasticsearch.plugins.Plugin) MockRepository(org.elasticsearch.snapshots.mockstore.MockRepository) INDEX_REFRESH_INTERVAL_SETTING(org.elasticsearch.index.IndexSettings.INDEX_REFRESH_INTERVAL_SETTING) ClusterStateResponse(org.elasticsearch.action.admin.cluster.state.ClusterStateResponse) GetIndexTemplatesResponse(org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesResponse) TimeUnit(java.util.concurrent.TimeUnit) ExceptionsHelper(org.elasticsearch.ExceptionsHelper) SnapshotsInProgress(org.elasticsearch.cluster.SnapshotsInProgress) ElasticsearchAssertions.assertAllSuccessful(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAllSuccessful) StoredScriptsIT(org.elasticsearch.script.StoredScriptsIT) Collections(java.util.Collections) MetaDataIndexStateService(org.elasticsearch.cluster.metadata.MetaDataIndexStateService) ElasticsearchAssertions.assertNoFailures(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures) GetSnapshotsResponse(org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsResponse) CreateSnapshotResponse(org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse) ArrayList(java.util.ArrayList) Matchers.containsString(org.hamcrest.Matchers.containsString) Client(org.elasticsearch.client.Client)

Example 3 with GetSnapshotsResponse

use of org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsResponse in project elasticsearch by elastic.

the class SharedClusterSnapshotRestoreIT method testSnapshotSucceedsAfterSnapshotFailure.

public void testSnapshotSucceedsAfterSnapshotFailure() throws Exception {
    logger.info("--> creating repository");
    final Path repoPath = randomRepoPath();
    final Client client = client();
    assertAcked(client.admin().cluster().preparePutRepository("test-repo").setType("mock").setVerify(false).setSettings(Settings.builder().put("location", repoPath).put("random_control_io_exception_rate", randomIntBetween(5, 20) / 100f).put("atomic_move", false).put("random", randomAsciiOfLength(10))));
    logger.info("--> indexing some data");
    assertAcked(prepareCreate("test-idx").setSettings(// that caused problems with writing subsequent snapshots if they happened to be lingering in the repository
    Settings.builder().put(SETTING_NUMBER_OF_SHARDS, 1).put(SETTING_NUMBER_OF_REPLICAS, 0)));
    ensureGreen();
    final int numDocs = randomIntBetween(1, 5);
    for (int i = 0; i < numDocs; i++) {
        index("test-idx", "doc", Integer.toString(i), "foo", "bar" + i);
    }
    refresh();
    assertThat(client.prepareSearch("test-idx").setSize(0).get().getHits().getTotalHits(), equalTo((long) numDocs));
    logger.info("--> snapshot with potential I/O failures");
    try {
        CreateSnapshotResponse createSnapshotResponse = client.admin().cluster().prepareCreateSnapshot("test-repo", "test-snap").setWaitForCompletion(true).setIndices("test-idx").get();
        if (createSnapshotResponse.getSnapshotInfo().totalShards() != createSnapshotResponse.getSnapshotInfo().successfulShards()) {
            assertThat(getFailureCount("test-repo"), greaterThan(0L));
            assertThat(createSnapshotResponse.getSnapshotInfo().shardFailures().size(), greaterThan(0));
            for (SnapshotShardFailure shardFailure : createSnapshotResponse.getSnapshotInfo().shardFailures()) {
                assertThat(shardFailure.reason(), containsString("Random IOException"));
            }
        }
    } catch (SnapshotCreationException | RepositoryException ex) {
        // sometimes, the snapshot will fail with a top level I/O exception
        assertThat(ExceptionsHelper.stackTrace(ex), containsString("Random IOException"));
    }
    logger.info("--> snapshot with no I/O failures");
    assertAcked(client.admin().cluster().preparePutRepository("test-repo-2").setType("mock").setSettings(Settings.builder().put("location", repoPath)));
    CreateSnapshotResponse createSnapshotResponse = client.admin().cluster().prepareCreateSnapshot("test-repo-2", "test-snap-2").setWaitForCompletion(true).setIndices("test-idx").get();
    assertEquals(0, createSnapshotResponse.getSnapshotInfo().failedShards());
    GetSnapshotsResponse getSnapshotsResponse = client.admin().cluster().prepareGetSnapshots("test-repo-2").addSnapshots("test-snap-2").get();
    assertEquals(SnapshotState.SUCCESS, getSnapshotsResponse.getSnapshots().get(0).state());
}
Also used : Path(java.nio.file.Path) GetSnapshotsResponse(org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsResponse) CreateSnapshotResponse(org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse) RepositoryException(org.elasticsearch.repositories.RepositoryException) Client(org.elasticsearch.client.Client)

Example 4 with GetSnapshotsResponse

use of org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsResponse in project elasticsearch by elastic.

the class SharedClusterSnapshotRestoreIT method testReadonlyRepository.

// this fails every now and then: https://github.com/elastic/elasticsearch/issues/18121 but without
@TestLogging("_root:DEBUG")
public // more logs we cannot find out why
void testReadonlyRepository() throws Exception {
    Client client = client();
    logger.info("-->  creating repository");
    Path repositoryLocation = randomRepoPath();
    assertAcked(client.admin().cluster().preparePutRepository("test-repo").setType("fs").setSettings(Settings.builder().put("location", repositoryLocation).put("compress", randomBoolean()).put("chunk_size", randomIntBetween(100, 1000), ByteSizeUnit.BYTES)));
    createIndex("test-idx");
    ensureGreen();
    logger.info("--> indexing some data");
    for (int i = 0; i < 100; i++) {
        index("test-idx", "doc", Integer.toString(i), "foo", "bar" + i);
    }
    refresh();
    logger.info("--> snapshot");
    CreateSnapshotResponse createSnapshotResponse = client.admin().cluster().prepareCreateSnapshot("test-repo", "test-snap").setWaitForCompletion(true).setIndices("test-idx").get();
    assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0));
    assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().totalShards()));
    assertThat(client.admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test-snap").get().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS));
    logger.info("--> delete index");
    cluster().wipeIndices("test-idx");
    logger.info("--> create read-only URL repository");
    assertAcked(client.admin().cluster().preparePutRepository("readonly-repo").setType("fs").setSettings(Settings.builder().put("location", repositoryLocation).put("compress", randomBoolean()).put("readonly", true).put("chunk_size", randomIntBetween(100, 1000), ByteSizeUnit.BYTES)));
    logger.info("--> restore index after deletion");
    RestoreSnapshotResponse restoreSnapshotResponse = client.admin().cluster().prepareRestoreSnapshot("readonly-repo", "test-snap").setWaitForCompletion(true).setIndices("test-idx").execute().actionGet();
    assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), greaterThan(0));
    assertThat(client.prepareSearch("test-idx").setSize(0).get().getHits().getTotalHits(), equalTo(100L));
    logger.info("--> list available shapshots");
    GetSnapshotsResponse getSnapshotsResponse = client.admin().cluster().prepareGetSnapshots("readonly-repo").get();
    assertThat(getSnapshotsResponse.getSnapshots(), notNullValue());
    assertThat(getSnapshotsResponse.getSnapshots().size(), equalTo(1));
    logger.info("--> try deleting snapshot");
    assertThrows(client.admin().cluster().prepareDeleteSnapshot("readonly-repo", "test-snap"), RepositoryException.class, "cannot delete snapshot from a readonly repository");
    logger.info("--> try making another snapshot");
    assertThrows(client.admin().cluster().prepareCreateSnapshot("readonly-repo", "test-snap-2").setWaitForCompletion(true).setIndices("test-idx"), RepositoryException.class, "cannot create snapshot in a readonly repository");
}
Also used : Path(java.nio.file.Path) GetSnapshotsResponse(org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsResponse) CreateSnapshotResponse(org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse) Client(org.elasticsearch.client.Client) RestoreSnapshotResponse(org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotResponse) TestLogging(org.elasticsearch.test.junit.annotations.TestLogging)

Example 5 with GetSnapshotsResponse

use of org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsResponse in project elasticsearch by elastic.

the class DedicatedClusterSnapshotRestoreIT method testMasterShutdownDuringSnapshot.

public void testMasterShutdownDuringSnapshot() throws Exception {
    Settings masterSettings = Settings.builder().put(Node.NODE_DATA_SETTING.getKey(), false).build();
    Settings dataSettings = Settings.builder().put(Node.NODE_MASTER_SETTING.getKey(), false).build();
    logger.info("-->  starting two master nodes and two data nodes");
    internalCluster().startNode(masterSettings);
    internalCluster().startNode(masterSettings);
    internalCluster().startNode(dataSettings);
    internalCluster().startNode(dataSettings);
    final Client client = client();
    logger.info("-->  creating repository");
    assertAcked(client.admin().cluster().preparePutRepository("test-repo").setType("fs").setSettings(Settings.builder().put("location", randomRepoPath()).put("compress", randomBoolean()).put("chunk_size", randomIntBetween(100, 1000), ByteSizeUnit.BYTES)));
    assertAcked(prepareCreate("test-idx", 0, Settings.builder().put("number_of_shards", between(1, 20)).put("number_of_replicas", 0)));
    ensureGreen();
    logger.info("--> indexing some data");
    final int numdocs = randomIntBetween(10, 100);
    IndexRequestBuilder[] builders = new IndexRequestBuilder[numdocs];
    for (int i = 0; i < builders.length; i++) {
        builders[i] = client().prepareIndex("test-idx", "type1", Integer.toString(i)).setSource("field1", "bar " + i);
    }
    indexRandom(true, builders);
    flushAndRefresh();
    final int numberOfShards = getNumShards("test-idx").numPrimaries;
    logger.info("number of shards: {}", numberOfShards);
    final ClusterService clusterService = internalCluster().clusterService(internalCluster().getMasterName());
    BlockingClusterStateListener snapshotListener = new BlockingClusterStateListener(clusterService, "update_snapshot [", "update snapshot state", Priority.HIGH);
    try {
        clusterService.addListener(snapshotListener);
        logger.info("--> snapshot");
        dataNodeClient().admin().cluster().prepareCreateSnapshot("test-repo", "test-snap").setWaitForCompletion(false).setIndices("test-idx").get();
        // Await until some updates are in pending state.
        assertBusyPendingTasks("update snapshot state", 1);
        logger.info("--> stopping master node");
        internalCluster().stopCurrentMasterNode();
        logger.info("--> unblocking snapshot execution");
        snapshotListener.unblock();
    } finally {
        clusterService.removeListener(snapshotListener);
    }
    logger.info("--> wait until the snapshot is done");
    assertBusy(new Runnable() {

        @Override
        public void run() {
            GetSnapshotsResponse snapshotsStatusResponse = client().admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test-snap").get();
            SnapshotInfo snapshotInfo = snapshotsStatusResponse.getSnapshots().get(0);
            assertTrue(snapshotInfo.state().completed());
        }
    }, 1, TimeUnit.MINUTES);
    logger.info("--> verify that snapshot was succesful");
    GetSnapshotsResponse snapshotsStatusResponse = client().admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test-snap").get();
    SnapshotInfo snapshotInfo = snapshotsStatusResponse.getSnapshots().get(0);
    assertEquals(SnapshotState.SUCCESS, snapshotInfo.state());
    assertEquals(snapshotInfo.totalShards(), snapshotInfo.successfulShards());
    assertEquals(0, snapshotInfo.failedShards());
}
Also used : IndexRequestBuilder(org.elasticsearch.action.index.IndexRequestBuilder) GetSnapshotsResponse(org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsResponse) ClusterService(org.elasticsearch.cluster.service.ClusterService) NodeClient(org.elasticsearch.client.node.NodeClient) Client(org.elasticsearch.client.Client) Settings(org.elasticsearch.common.settings.Settings)

Aggregations

GetSnapshotsResponse (org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsResponse)14 Client (org.elasticsearch.client.Client)8 CreateSnapshotResponse (org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse)7 Path (java.nio.file.Path)5 RestoreSnapshotResponse (org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotResponse)5 SnapshotStatus (org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotStatus)4 SnapshotsStatusResponse (org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotsStatusResponse)4 ArrayList (java.util.ArrayList)3 List (java.util.List)3 PutRepositoryResponse (org.elasticsearch.action.admin.cluster.repositories.put.PutRepositoryResponse)3 SnapshotIndexShardStatus (org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotIndexShardStatus)3 SnapshotIndexStatus (org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotIndexStatus)3 Settings (org.elasticsearch.common.settings.Settings)3 RepositoryException (org.elasticsearch.repositories.RepositoryException)3 Matchers.containsString (org.hamcrest.Matchers.containsString)3 ExecutionException (java.util.concurrent.ExecutionException)2 TimeUnit (java.util.concurrent.TimeUnit)2 GetSnapshotsRequest (org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsRequest)2 IndexRequestBuilder (org.elasticsearch.action.index.IndexRequestBuilder)2 SearchResponse (org.elasticsearch.action.search.SearchResponse)2