Search in sources :

Example 11 with ClusterState

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

the class GeoShapeIntegrationIT method findNodeName.

private String findNodeName(String index) {
    ClusterState state = client().admin().cluster().prepareState().get().getState();
    IndexShardRoutingTable shard = state.getRoutingTable().index(index).shard(0);
    String nodeId = shard.assignedShards().get(0).currentNodeId();
    return state.getNodes().get(nodeId).getName();
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) IndexShardRoutingTable(org.elasticsearch.cluster.routing.IndexShardRoutingTable)

Example 12 with ClusterState

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

the class SearchStatsIT method nodeIdsWithIndex.

private Set<String> nodeIdsWithIndex(String... indices) {
    ClusterState state = client().admin().cluster().prepareState().execute().actionGet().getState();
    GroupShardsIterator allAssignedShardsGrouped = state.routingTable().allAssignedShardsGrouped(indices, true);
    Set<String> nodes = new HashSet<>();
    for (ShardIterator shardIterator : allAssignedShardsGrouped) {
        for (ShardRouting routing : shardIterator.asUnordered()) {
            if (routing.active()) {
                nodes.add(routing.currentNodeId());
            }
        }
    }
    return nodes;
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) GroupShardsIterator(org.elasticsearch.cluster.routing.GroupShardsIterator) ShardIterator(org.elasticsearch.cluster.routing.ShardIterator) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) HashSet(java.util.HashSet)

Example 13 with ClusterState

use of org.elasticsearch.cluster.ClusterState 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 14 with ClusterState

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

the class DedicatedClusterSnapshotRestoreIT method testRestoreCustomMetadata.

public void testRestoreCustomMetadata() throws Exception {
    Path tempDir = randomRepoPath();
    logger.info("--> start node");
    internalCluster().startNode();
    Client client = client();
    createIndex("test-idx");
    logger.info("--> add custom persistent metadata");
    updateClusterState(new ClusterStateUpdater() {

        @Override
        public ClusterState execute(ClusterState currentState) throws Exception {
            ClusterState.Builder builder = ClusterState.builder(currentState);
            MetaData.Builder metadataBuilder = MetaData.builder(currentState.metaData());
            metadataBuilder.putCustom(SnapshottableMetadata.TYPE, new SnapshottableMetadata("before_snapshot_s"));
            metadataBuilder.putCustom(NonSnapshottableMetadata.TYPE, new NonSnapshottableMetadata("before_snapshot_ns"));
            metadataBuilder.putCustom(SnapshottableGatewayMetadata.TYPE, new SnapshottableGatewayMetadata("before_snapshot_s_gw"));
            metadataBuilder.putCustom(NonSnapshottableGatewayMetadata.TYPE, new NonSnapshottableGatewayMetadata("before_snapshot_ns_gw"));
            metadataBuilder.putCustom(SnapshotableGatewayNoApiMetadata.TYPE, new SnapshotableGatewayNoApiMetadata("before_snapshot_s_gw_noapi"));
            builder.metaData(metadataBuilder);
            return builder.build();
        }
    });
    logger.info("--> create repository");
    PutRepositoryResponse putRepositoryResponse = client.admin().cluster().preparePutRepository("test-repo").setType("fs").setSettings(Settings.builder().put("location", tempDir)).execute().actionGet();
    assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true));
    logger.info("--> start snapshot");
    CreateSnapshotResponse createSnapshotResponse = client.admin().cluster().prepareCreateSnapshot("test-repo", "test-snap").setWaitForCompletion(true).execute().actionGet();
    assertThat(createSnapshotResponse.getSnapshotInfo().totalShards(), greaterThan(0));
    assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().successfulShards()));
    assertThat(client.admin().cluster().prepareGetSnapshots("test-repo").setSnapshots("test-snap").execute().actionGet().getSnapshots().get(0).state(), equalTo(SnapshotState.SUCCESS));
    logger.info("--> change custom persistent metadata");
    updateClusterState(new ClusterStateUpdater() {

        @Override
        public ClusterState execute(ClusterState currentState) throws Exception {
            ClusterState.Builder builder = ClusterState.builder(currentState);
            MetaData.Builder metadataBuilder = MetaData.builder(currentState.metaData());
            if (randomBoolean()) {
                metadataBuilder.putCustom(SnapshottableMetadata.TYPE, new SnapshottableMetadata("after_snapshot_s"));
            } else {
                metadataBuilder.removeCustom(SnapshottableMetadata.TYPE);
            }
            metadataBuilder.putCustom(NonSnapshottableMetadata.TYPE, new NonSnapshottableMetadata("after_snapshot_ns"));
            if (randomBoolean()) {
                metadataBuilder.putCustom(SnapshottableGatewayMetadata.TYPE, new SnapshottableGatewayMetadata("after_snapshot_s_gw"));
            } else {
                metadataBuilder.removeCustom(SnapshottableGatewayMetadata.TYPE);
            }
            metadataBuilder.putCustom(NonSnapshottableGatewayMetadata.TYPE, new NonSnapshottableGatewayMetadata("after_snapshot_ns_gw"));
            metadataBuilder.removeCustom(SnapshotableGatewayNoApiMetadata.TYPE);
            builder.metaData(metadataBuilder);
            return builder.build();
        }
    });
    logger.info("--> delete repository");
    assertAcked(client.admin().cluster().prepareDeleteRepository("test-repo"));
    logger.info("--> create repository");
    putRepositoryResponse = client.admin().cluster().preparePutRepository("test-repo-2").setType("fs").setSettings(Settings.builder().put("location", tempDir)).execute().actionGet();
    assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true));
    logger.info("--> restore snapshot");
    client.admin().cluster().prepareRestoreSnapshot("test-repo-2", "test-snap").setRestoreGlobalState(true).setIndices("-*").setWaitForCompletion(true).execute().actionGet();
    logger.info("--> make sure old repository wasn't restored");
    assertThrows(client.admin().cluster().prepareGetRepositories("test-repo"), RepositoryMissingException.class);
    assertThat(client.admin().cluster().prepareGetRepositories("test-repo-2").get().repositories().size(), equalTo(1));
    logger.info("--> check that custom persistent metadata was restored");
    ClusterState clusterState = client.admin().cluster().prepareState().get().getState();
    logger.info("Cluster state: {}", clusterState);
    MetaData metaData = clusterState.getMetaData();
    assertThat(((SnapshottableMetadata) metaData.custom(SnapshottableMetadata.TYPE)).getData(), equalTo("before_snapshot_s"));
    assertThat(((NonSnapshottableMetadata) metaData.custom(NonSnapshottableMetadata.TYPE)).getData(), equalTo("after_snapshot_ns"));
    assertThat(((SnapshottableGatewayMetadata) metaData.custom(SnapshottableGatewayMetadata.TYPE)).getData(), equalTo("before_snapshot_s_gw"));
    assertThat(((NonSnapshottableGatewayMetadata) metaData.custom(NonSnapshottableGatewayMetadata.TYPE)).getData(), equalTo("after_snapshot_ns_gw"));
    logger.info("--> restart all nodes");
    internalCluster().fullRestart();
    ensureYellow();
    logger.info("--> check that gateway-persistent custom metadata survived full cluster restart");
    clusterState = client().admin().cluster().prepareState().get().getState();
    logger.info("Cluster state: {}", clusterState);
    metaData = clusterState.getMetaData();
    assertThat(metaData.custom(SnapshottableMetadata.TYPE), nullValue());
    assertThat(metaData.custom(NonSnapshottableMetadata.TYPE), nullValue());
    assertThat(((SnapshottableGatewayMetadata) metaData.custom(SnapshottableGatewayMetadata.TYPE)).getData(), equalTo("before_snapshot_s_gw"));
    assertThat(((NonSnapshottableGatewayMetadata) metaData.custom(NonSnapshottableGatewayMetadata.TYPE)).getData(), equalTo("after_snapshot_ns_gw"));
    // Shouldn't be returned as part of API response
    assertThat(metaData.custom(SnapshotableGatewayNoApiMetadata.TYPE), nullValue());
    // But should still be in state
    metaData = internalCluster().getInstance(ClusterService.class).state().metaData();
    assertThat(((SnapshotableGatewayNoApiMetadata) metaData.custom(SnapshotableGatewayNoApiMetadata.TYPE)).getData(), equalTo("before_snapshot_s_gw_noapi"));
}
Also used : Path(java.nio.file.Path) ClusterState(org.elasticsearch.cluster.ClusterState) IndexRequestBuilder(org.elasticsearch.action.index.IndexRequestBuilder) PutRepositoryResponse(org.elasticsearch.action.admin.cluster.repositories.put.PutRepositoryResponse) RepositoryMissingException(org.elasticsearch.repositories.RepositoryMissingException) IOException(java.io.IOException) ClusterService(org.elasticsearch.cluster.service.ClusterService) CreateSnapshotResponse(org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse) MetaData(org.elasticsearch.cluster.metadata.MetaData) TestCustomMetaData(org.elasticsearch.test.TestCustomMetaData) NodeClient(org.elasticsearch.client.node.NodeClient) Client(org.elasticsearch.client.Client)

Example 15 with ClusterState

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

the class TribeIT method assertCustomMetaDataUpdated.

private static void assertCustomMetaDataUpdated(InternalTestCluster cluster, TestCustomMetaData expectedCustomMetaData) throws Exception {
    assertBusy(() -> {
        ClusterState tribeState = cluster.getInstance(ClusterService.class, cluster.getNodeNames()[0]).state();
        MetaData.Custom custom = tribeState.metaData().custom(expectedCustomMetaData.getWriteableName());
        assertNotNull(custom);
        assertThat(custom, equalTo(expectedCustomMetaData));
    });
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) ClusterService(org.elasticsearch.cluster.service.ClusterService) MetaData(org.elasticsearch.cluster.metadata.MetaData) TestCustomMetaData(org.elasticsearch.test.TestCustomMetaData)

Aggregations

ClusterState (org.elasticsearch.cluster.ClusterState)564 IndexMetaData (org.elasticsearch.cluster.metadata.IndexMetaData)211 MetaData (org.elasticsearch.cluster.metadata.MetaData)179 RoutingTable (org.elasticsearch.cluster.routing.RoutingTable)150 ShardRouting (org.elasticsearch.cluster.routing.ShardRouting)123 Settings (org.elasticsearch.common.settings.Settings)100 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)85 ClusterName (org.elasticsearch.cluster.ClusterName)82 DiscoveryNodes (org.elasticsearch.cluster.node.DiscoveryNodes)75 Matchers.containsString (org.hamcrest.Matchers.containsString)72 IndexShardRoutingTable (org.elasticsearch.cluster.routing.IndexShardRoutingTable)62 ShardId (org.elasticsearch.index.shard.ShardId)61 RoutingNodes (org.elasticsearch.cluster.routing.RoutingNodes)59 ArrayList (java.util.ArrayList)57 IOException (java.io.IOException)55 Index (org.elasticsearch.index.Index)53 ClusterSettings (org.elasticsearch.common.settings.ClusterSettings)49 CountDownLatch (java.util.concurrent.CountDownLatch)47 HashSet (java.util.HashSet)45 List (java.util.List)45