Search in sources :

Example 1 with ClusterStateResponse

use of org.elasticsearch.action.admin.cluster.state.ClusterStateResponse in project elasticsearch by elastic.

the class RestClusterGetSettingsAction method prepareRequest.

@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
    ClusterStateRequest clusterStateRequest = Requests.clusterStateRequest().routingTable(false).nodes(false);
    final boolean renderDefaults = request.paramAsBoolean("include_defaults", false);
    clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local()));
    return channel -> client.admin().cluster().state(clusterStateRequest, new RestBuilderListener<ClusterStateResponse>(channel) {

        @Override
        public RestResponse buildResponse(ClusterStateResponse response, XContentBuilder builder) throws Exception {
            return new BytesRestResponse(RestStatus.OK, renderResponse(response.getState(), renderDefaults, builder, request));
        }
    });
}
Also used : BaseRestHandler(org.elasticsearch.rest.BaseRestHandler) SettingsFilter(org.elasticsearch.common.settings.SettingsFilter) RestResponse(org.elasticsearch.rest.RestResponse) RestBuilderListener(org.elasticsearch.rest.action.RestBuilderListener) ToXContent(org.elasticsearch.common.xcontent.ToXContent) Set(java.util.Set) IOException(java.io.IOException) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) RestController(org.elasticsearch.rest.RestController) ClusterStateResponse(org.elasticsearch.action.admin.cluster.state.ClusterStateResponse) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) ClusterState(org.elasticsearch.cluster.ClusterState) ClusterSettings(org.elasticsearch.common.settings.ClusterSettings) Settings(org.elasticsearch.common.settings.Settings) RestStatus(org.elasticsearch.rest.RestStatus) RestRequest(org.elasticsearch.rest.RestRequest) ClusterStateRequest(org.elasticsearch.action.admin.cluster.state.ClusterStateRequest) NodeClient(org.elasticsearch.client.node.NodeClient) Requests(org.elasticsearch.client.Requests) ClusterStateResponse(org.elasticsearch.action.admin.cluster.state.ClusterStateResponse) RestResponse(org.elasticsearch.rest.RestResponse) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) ClusterStateRequest(org.elasticsearch.action.admin.cluster.state.ClusterStateRequest) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) IOException(java.io.IOException)

Example 2 with ClusterStateResponse

use of org.elasticsearch.action.admin.cluster.state.ClusterStateResponse in project elasticsearch by elastic.

the class RestClusterStateAction method prepareRequest.

@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
    final ClusterStateRequest clusterStateRequest = Requests.clusterStateRequest();
    clusterStateRequest.indicesOptions(IndicesOptions.fromRequest(request, clusterStateRequest.indicesOptions()));
    clusterStateRequest.local(request.paramAsBoolean("local", clusterStateRequest.local()));
    clusterStateRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterStateRequest.masterNodeTimeout()));
    final String[] indices = Strings.splitStringByCommaToArray(request.param("indices", "_all"));
    boolean isAllIndicesOnly = indices.length == 1 && "_all".equals(indices[0]);
    if (!isAllIndicesOnly) {
        clusterStateRequest.indices(indices);
    }
    if (request.hasParam("metric")) {
        EnumSet<ClusterState.Metric> metrics = ClusterState.Metric.parseString(request.param("metric"), true);
        // do not ask for what we do not need.
        clusterStateRequest.nodes(metrics.contains(ClusterState.Metric.NODES) || metrics.contains(ClusterState.Metric.MASTER_NODE));
        /*
             * there is no distinction in Java api between routing_table and routing_nodes, it's the same info set over the wire, one single
             * flag to ask for it
             */
        clusterStateRequest.routingTable(metrics.contains(ClusterState.Metric.ROUTING_TABLE) || metrics.contains(ClusterState.Metric.ROUTING_NODES));
        clusterStateRequest.metaData(metrics.contains(ClusterState.Metric.METADATA));
        clusterStateRequest.blocks(metrics.contains(ClusterState.Metric.BLOCKS));
        clusterStateRequest.customs(metrics.contains(ClusterState.Metric.CUSTOMS));
    }
    settingsFilter.addFilterSettingParams(request);
    return channel -> client.admin().cluster().state(clusterStateRequest, new RestBuilderListener<ClusterStateResponse>(channel) {

        @Override
        public RestResponse buildResponse(ClusterStateResponse response, XContentBuilder builder) throws Exception {
            builder.startObject();
            builder.field(Fields.CLUSTER_NAME, response.getClusterName().value());
            builder.byteSizeField(Fields.CLUSTER_STATE_SIZE_IN_BYTES, Fields.CLUSTER_STATE_SIZE, response.getTotalCompressedSize());
            response.getState().toXContent(builder, request);
            builder.endObject();
            return new BytesRestResponse(RestStatus.OK, builder);
        }
    });
}
Also used : BaseRestHandler(org.elasticsearch.rest.BaseRestHandler) SettingsFilter(org.elasticsearch.common.settings.SettingsFilter) RestResponse(org.elasticsearch.rest.RestResponse) RestBuilderListener(org.elasticsearch.rest.action.RestBuilderListener) Set(java.util.Set) IOException(java.io.IOException) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) RestController(org.elasticsearch.rest.RestController) Strings(org.elasticsearch.common.Strings) ClusterStateResponse(org.elasticsearch.action.admin.cluster.state.ClusterStateResponse) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) HashSet(java.util.HashSet) ClusterState(org.elasticsearch.cluster.ClusterState) Settings(org.elasticsearch.common.settings.Settings) RestStatus(org.elasticsearch.rest.RestStatus) IndicesOptions(org.elasticsearch.action.support.IndicesOptions) RestRequest(org.elasticsearch.rest.RestRequest) ClusterStateRequest(org.elasticsearch.action.admin.cluster.state.ClusterStateRequest) NodeClient(org.elasticsearch.client.node.NodeClient) Requests(org.elasticsearch.client.Requests) Collections(java.util.Collections) EnumSet(java.util.EnumSet) ClusterStateResponse(org.elasticsearch.action.admin.cluster.state.ClusterStateResponse) RestResponse(org.elasticsearch.rest.RestResponse) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) ClusterStateRequest(org.elasticsearch.action.admin.cluster.state.ClusterStateRequest) IOException(java.io.IOException) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder)

Example 3 with ClusterStateResponse

use of org.elasticsearch.action.admin.cluster.state.ClusterStateResponse in project elasticsearch by elastic.

the class CreateIndexIT method testCreationDateGenerated.

public void testCreationDateGenerated() {
    long timeBeforeRequest = System.currentTimeMillis();
    prepareCreate("test").get();
    long timeAfterRequest = System.currentTimeMillis();
    ClusterStateResponse response = client().admin().cluster().prepareState().get();
    ClusterState state = response.getState();
    assertThat(state, notNullValue());
    MetaData metadata = state.getMetaData();
    assertThat(metadata, notNullValue());
    ImmutableOpenMap<String, IndexMetaData> indices = metadata.getIndices();
    assertThat(indices, notNullValue());
    assertThat(indices.size(), equalTo(1));
    IndexMetaData index = indices.get("test");
    assertThat(index, notNullValue());
    assertThat(index.getCreationDate(), allOf(lessThanOrEqualTo(timeAfterRequest), greaterThanOrEqualTo(timeBeforeRequest)));
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) ClusterStateResponse(org.elasticsearch.action.admin.cluster.state.ClusterStateResponse) MetaData(org.elasticsearch.cluster.metadata.MetaData) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) Matchers.containsString(org.hamcrest.Matchers.containsString) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData)

Example 4 with ClusterStateResponse

use of org.elasticsearch.action.admin.cluster.state.ClusterStateResponse in project elasticsearch by elastic.

the class ShrinkIndexIT method testCreateShrinkIndexFails.

/**
     * Tests that we can manually recover from a failed allocation due to shards being moved away etc.
     */
public void testCreateShrinkIndexFails() throws Exception {
    internalCluster().ensureAtLeastNumDataNodes(2);
    prepareCreate("source").setSettings(Settings.builder().put(indexSettings()).put("number_of_shards", randomIntBetween(2, 7)).put("number_of_replicas", 0)).get();
    for (int i = 0; i < 20; i++) {
        client().prepareIndex("source", randomFrom("t1", "t2", "t3")).setSource("{\"foo\" : \"bar\", \"i\" : " + i + "}", XContentType.JSON).get();
    }
    ImmutableOpenMap<String, DiscoveryNode> dataNodes = client().admin().cluster().prepareState().get().getState().nodes().getDataNodes();
    assertTrue("at least 2 nodes but was: " + dataNodes.size(), dataNodes.size() >= 2);
    DiscoveryNode[] discoveryNodes = dataNodes.values().toArray(DiscoveryNode.class);
    String spareNode = discoveryNodes[0].getName();
    String mergeNode = discoveryNodes[1].getName();
    // ensure all shards are allocated otherwise the ensure green below might not succeed since we require the merge node
    // if we change the setting too quickly we will end up with one replica unassigned which can't be assigned anymore due
    // to the require._name below.
    ensureGreen();
    // relocate all shards to one node such that we can merge it.
    client().admin().indices().prepareUpdateSettings("source").setSettings(Settings.builder().put("index.routing.allocation.require._name", mergeNode).put("index.blocks.write", true)).get();
    ensureGreen();
    // now merge source into a single shard index
    client().admin().indices().prepareShrinkIndex("source", "target").setWaitForActiveShards(ActiveShardCount.NONE).setSettings(Settings.builder().put("index.routing.allocation.exclude._name", // we manually exclude the merge node to forcefully fuck it up
    mergeNode).put("index.number_of_replicas", 0).put("index.allocation.max_retries", 1).build()).get();
    client().admin().cluster().prepareHealth("target").setWaitForEvents(Priority.LANGUID).get();
    // now we move all shards away from the merge node
    client().admin().indices().prepareUpdateSettings("source").setSettings(Settings.builder().put("index.routing.allocation.require._name", spareNode).put("index.blocks.write", true)).get();
    ensureGreen("source");
    // erase the forcefully fuckup!
    client().admin().indices().prepareUpdateSettings("target").setSettings(Settings.builder().putNull("index.routing.allocation.exclude._name")).get();
    // wait until it fails
    assertBusy(() -> {
        ClusterStateResponse clusterStateResponse = client().admin().cluster().prepareState().get();
        RoutingTable routingTables = clusterStateResponse.getState().routingTable();
        assertTrue(routingTables.index("target").shard(0).getShards().get(0).unassigned());
        assertEquals(UnassignedInfo.Reason.ALLOCATION_FAILED, routingTables.index("target").shard(0).getShards().get(0).unassignedInfo().getReason());
        assertEquals(1, routingTables.index("target").shard(0).getShards().get(0).unassignedInfo().getNumFailedAllocations());
    });
    // now relocate them all to the right node
    client().admin().indices().prepareUpdateSettings("source").setSettings(Settings.builder().put("index.routing.allocation.require._name", mergeNode)).get();
    ensureGreen("source");
    final InternalClusterInfoService infoService = (InternalClusterInfoService) internalCluster().getInstance(ClusterInfoService.class, internalCluster().getMasterName());
    infoService.refresh();
    // kick off a retry and wait until it's done!
    ClusterRerouteResponse clusterRerouteResponse = client().admin().cluster().prepareReroute().setRetryFailed(true).get();
    long expectedShardSize = clusterRerouteResponse.getState().routingTable().index("target").shard(0).getShards().get(0).getExpectedShardSize();
    // we support the expected shard size in the allocator to sum up over the source index shards
    assertTrue("expected shard size must be set but wasn't: " + expectedShardSize, expectedShardSize > 0);
    ensureGreen();
    assertHitCount(client().prepareSearch("target").setSize(100).setQuery(new TermsQueryBuilder("foo", "bar")).get(), 20);
}
Also used : DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) RoutingTable(org.elasticsearch.cluster.routing.RoutingTable) InternalClusterInfoService(org.elasticsearch.cluster.InternalClusterInfoService) ClusterInfoService(org.elasticsearch.cluster.ClusterInfoService) ClusterStateResponse(org.elasticsearch.action.admin.cluster.state.ClusterStateResponse) InternalClusterInfoService(org.elasticsearch.cluster.InternalClusterInfoService) TermsQueryBuilder(org.elasticsearch.index.query.TermsQueryBuilder) ClusterRerouteResponse(org.elasticsearch.action.admin.cluster.reroute.ClusterRerouteResponse)

Example 5 with ClusterStateResponse

use of org.elasticsearch.action.admin.cluster.state.ClusterStateResponse in project elasticsearch by elastic.

the class SimpleIndexStateIT method testSimpleOpenClose.

public void testSimpleOpenClose() {
    logger.info("--> creating test index");
    createIndex("test");
    logger.info("--> waiting for green status");
    ensureGreen();
    NumShards numShards = getNumShards("test");
    ClusterStateResponse stateResponse = client().admin().cluster().prepareState().get();
    assertThat(stateResponse.getState().metaData().index("test").getState(), equalTo(IndexMetaData.State.OPEN));
    assertThat(stateResponse.getState().routingTable().index("test").shards().size(), equalTo(numShards.numPrimaries));
    assertEquals(stateResponse.getState().routingTable().index("test").shardsWithState(ShardRoutingState.STARTED).size(), numShards.totalNumShards);
    logger.info("--> indexing a simple document");
    client().prepareIndex("test", "type1", "1").setSource("field1", "value1").get();
    logger.info("--> closing test index...");
    CloseIndexResponse closeIndexResponse = client().admin().indices().prepareClose("test").get();
    assertThat(closeIndexResponse.isAcknowledged(), equalTo(true));
    stateResponse = client().admin().cluster().prepareState().get();
    assertThat(stateResponse.getState().metaData().index("test").getState(), equalTo(IndexMetaData.State.CLOSE));
    assertThat(stateResponse.getState().routingTable().index("test"), nullValue());
    logger.info("--> trying to index into a closed index ...");
    try {
        client().prepareIndex("test", "type1", "1").setSource("field1", "value1").get();
        fail();
    } catch (IndexClosedException e) {
    // all is well
    }
    logger.info("--> opening index...");
    OpenIndexResponse openIndexResponse = client().admin().indices().prepareOpen("test").get();
    assertThat(openIndexResponse.isAcknowledged(), equalTo(true));
    logger.info("--> waiting for green status");
    ensureGreen();
    stateResponse = client().admin().cluster().prepareState().get();
    assertThat(stateResponse.getState().metaData().index("test").getState(), equalTo(IndexMetaData.State.OPEN));
    assertThat(stateResponse.getState().routingTable().index("test").shards().size(), equalTo(numShards.numPrimaries));
    assertEquals(stateResponse.getState().routingTable().index("test").shardsWithState(ShardRoutingState.STARTED).size(), numShards.totalNumShards);
    logger.info("--> indexing a simple document");
    client().prepareIndex("test", "type1", "1").setSource("field1", "value1").get();
}
Also used : CloseIndexResponse(org.elasticsearch.action.admin.indices.close.CloseIndexResponse) IndexClosedException(org.elasticsearch.indices.IndexClosedException) ClusterStateResponse(org.elasticsearch.action.admin.cluster.state.ClusterStateResponse) OpenIndexResponse(org.elasticsearch.action.admin.indices.open.OpenIndexResponse)

Aggregations

ClusterStateResponse (org.elasticsearch.action.admin.cluster.state.ClusterStateResponse)64 Settings (org.elasticsearch.common.settings.Settings)25 ClusterStateRequest (org.elasticsearch.action.admin.cluster.state.ClusterStateRequest)21 ClusterHealthResponse (org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse)13 NodeClient (org.elasticsearch.client.node.NodeClient)12 RestController (org.elasticsearch.rest.RestController)12 RestRequest (org.elasticsearch.rest.RestRequest)12 RestResponse (org.elasticsearch.rest.RestResponse)12 IndexMetaData (org.elasticsearch.cluster.metadata.IndexMetaData)11 ClusterState (org.elasticsearch.cluster.ClusterState)10 Table (org.elasticsearch.common.Table)10 GET (org.elasticsearch.rest.RestRequest.Method.GET)10 RestResponseListener (org.elasticsearch.rest.action.RestResponseListener)10 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)9 ShardRouting (org.elasticsearch.cluster.routing.ShardRouting)8 RestActionListener (org.elasticsearch.rest.action.RestActionListener)8 Strings (org.elasticsearch.common.Strings)7 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 MetaData (org.elasticsearch.cluster.metadata.MetaData)6