Search in sources :

Example 46 with ClusterHealthResponse

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse in project pancm_project by xuwujing.

the class EsHighLevelCluster method catHealth.

/**
 * @return void
 * @Author pancm
 * @Description 设获取集群的健康情况
 * @Date 2020/1/2
 * @Param [index]
 */
public static void catHealth() throws IOException {
    ClusterHealthRequest request = new ClusterHealthRequest();
    ClusterHealthResponse response = client.cluster().health(request, RequestOptions.DEFAULT);
    String clusterName = response.getClusterName();
    ClusterHealthStatus status = response.getStatus();
    boolean timedOut = response.isTimedOut();
    RestStatus restStatus = response.status();
    int numberOfNodes = response.getNumberOfNodes();
    int numberOfDataNodes = response.getNumberOfDataNodes();
    int activeShards = response.getActiveShards();
    int activePrimaryShards = response.getActivePrimaryShards();
    int relocatingShards = response.getRelocatingShards();
    int initializingShards = response.getInitializingShards();
    int unassignedShards = response.getUnassignedShards();
    int delayedUnassignedShards = response.getDelayedUnassignedShards();
    double activeShardsPercent = response.getActiveShardsPercent();
    logger.info("clusterName:{},status:{},timedOut:{},restStatus:{}", clusterName, status, timedOut, restStatus.getStatus());
    List<Map<String, Object>> mapList = new ArrayList<>();
    response.getIndices().forEach((k, v) -> {
        Map<String, Object> map = new HashMap<>();
        String index = v.getIndex();
        int replicas = v.getNumberOfReplicas();
        int allShards = v.getActiveShards();
        int shards = v.getActivePrimaryShards();
        int status2 = v.getStatus().value();
        map.put("index", index);
        map.put("replicas", replicas);
        map.put("shards", shards);
        map.put("status", status2);
        System.out.println(map);
    });
}
Also used : ClusterHealthResponse(org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) ClusterHealthRequest(org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest) ClusterHealthStatus(org.elasticsearch.cluster.health.ClusterHealthStatus) RestStatus(org.elasticsearch.rest.RestStatus)

Example 47 with ClusterHealthResponse

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse in project unipop by unipop-graph.

the class LocalNode method checkHealth.

public void checkHealth() {
    final ClusterHealthRequest clusterHealthRequest = new ClusterHealthRequest().timeout(TimeValue.timeValueSeconds(10)).waitForYellowStatus();
    final ClusterHealthResponse clusterHealth = client.admin().cluster().health(clusterHealthRequest).actionGet();
    if (clusterHealth.isTimedOut()) {
        System.out.println(clusterHealth.getStatus() + " status returned from cluster '" + client.admin().cluster().toString());
    }
}
Also used : ClusterHealthResponse(org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) ClusterHealthRequest(org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest)

Example 48 with ClusterHealthResponse

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse in project bw-calendar-engine by Bedework.

the class BwIndexEsImpl method getClient.

private Client getClient() throws CalFacadeException {
    if (theClient != null) {
        return theClient;
    }
    synchronized (clientSyncher) {
        if (theClient != null) {
            return theClient;
        }
        if (idxpars.getEmbeddedIndexer()) {
            /* Start up a node and get a client from it.
         */
            final ImmutableSettings.Builder settings = ImmutableSettings.settingsBuilder();
            if (idxpars.getNodeName() != null) {
                settings.put("node.name", idxpars.getNodeName());
            }
            settings.put("path.data", idxpars.getDataDir());
            if (idxpars.getHttpEnabled()) {
                warn("*************************************************************");
                warn("*************************************************************");
                warn("*************************************************************");
                warn("http is enabled for the indexer. This is a security risk.    ");
                warn("Turn it off in the indexer configuration.                    ");
                warn("*************************************************************");
                warn("*************************************************************");
                warn("*************************************************************");
            }
            settings.put("http.enabled", idxpars.getHttpEnabled());
            final NodeBuilder nbld = NodeBuilder.nodeBuilder().settings(settings);
            if (idxpars.getClusterName() != null) {
                nbld.clusterName(idxpars.getClusterName());
            }
            final Node theNode = nbld.data(true).local(true).node();
            theClient = theNode.client();
        } else {
            /* Not embedded - use the URL */
            TransportClient tClient = new TransportClient();
            tClient = tClient.addTransportAddress(new InetSocketTransportAddress(host, port));
            theClient = tClient;
        }
        /* Ensure status is at least yellow */
        int tries = 0;
        int yellowTries = 0;
        for (; ; ) {
            final ClusterHealthRequestBuilder chrb = theClient.admin().cluster().prepareHealth();
            final ClusterHealthResponse chr = chrb.execute().actionGet();
            if (chr.getStatus() == ClusterHealthStatus.GREEN) {
                break;
            }
            if (chr.getStatus() == ClusterHealthStatus.YELLOW) {
                yellowTries++;
                if (yellowTries > 60) {
                    warn("Going ahead anyway on YELLOW status");
                }
                break;
            }
            tries++;
            if (tries % 5 == 0) {
                warn("Cluster status for " + chr.getClusterName() + " is still " + chr.getStatus() + " after " + tries + " tries");
            }
            try {
                Thread.sleep(1000);
            } catch (final InterruptedException ex) {
                throw new CalFacadeException("Interrupted out of getClient");
            }
        }
        return theClient;
    }
}
Also used : TransportClient(org.elasticsearch.client.transport.TransportClient) ClusterHealthResponse(org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) ClusterHealthRequestBuilder(org.elasticsearch.action.admin.cluster.health.ClusterHealthRequestBuilder) Node(org.elasticsearch.node.Node) NodeBuilder(org.elasticsearch.node.NodeBuilder) ImmutableSettings(org.elasticsearch.common.settings.ImmutableSettings) InetSocketTransportAddress(org.elasticsearch.common.transport.InetSocketTransportAddress) CalFacadeException(org.bedework.calfacade.exc.CalFacadeException)

Example 49 with ClusterHealthResponse

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse in project vertexium by visallo.

the class Elasticsearch5SearchIndex method createIndex.

@SuppressWarnings("unused")
protected void createIndex(String indexName) throws IOException {
    CreateIndexResponse createResponse = client.admin().indices().prepareCreate(indexName).setSettings(XContentFactory.jsonBuilder().startObject().startObject("analysis").startObject("normalizer").startObject(LOWERCASER_NORMALIZER_NAME).field("type", "custom").array("filter", "lowercase").endObject().endObject().endObject().field("number_of_shards", getConfig().getNumberOfShards()).field("number_of_replicas", getConfig().getNumberOfReplicas()).field("index.mapping.total_fields.limit", getConfig().getIndexMappingTotalFieldsLimit()).endObject()).execute().actionGet();
    ClusterHealthResponse health = client.admin().cluster().prepareHealth(indexName).setWaitForGreenStatus().execute().actionGet();
    LOGGER.debug("Index status: %s", health.toString());
    if (health.isTimedOut()) {
        LOGGER.warn("timed out waiting for yellow/green index status, for index: %s", indexName);
    }
}
Also used : ClusterHealthResponse(org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) CreateIndexResponse(org.elasticsearch.action.admin.indices.create.CreateIndexResponse)

Example 50 with ClusterHealthResponse

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse in project logging-log4j2 by apache.

the class LogstashIT method createClient.

private static RestHighLevelClient createClient() throws IOException {
    // Instantiate the client.
    LOGGER.info("instantiating the ES client");
    final HttpHost httpHost = new HttpHost(HOST_NAME, MavenHardcodedConstants.ES_PORT);
    final RestClientBuilder clientBuilder = RestClient.builder(httpHost);
    final RestHighLevelClient client = new RestHighLevelClient(clientBuilder);
    // Verify the connection.
    LOGGER.info("verifying the ES connection");
    final ClusterHealthResponse healthResponse = client.cluster().health(new ClusterHealthRequest(), RequestOptions.DEFAULT);
    Assertions.assertThat(healthResponse.getStatus()).isNotEqualTo(ClusterHealthStatus.RED);
    // Delete the index.
    LOGGER.info("deleting the ES index");
    final DeleteIndexRequest deleteRequest = new DeleteIndexRequest(MavenHardcodedConstants.ES_INDEX_NAME);
    try {
        final AcknowledgedResponse deleteResponse = client.indices().delete(deleteRequest, RequestOptions.DEFAULT);
        Assertions.assertThat(deleteResponse.isAcknowledged()).isTrue();
    } catch (ElasticsearchStatusException error) {
        Assertions.assertThat(error).satisfies(ignored -> Assertions.assertThat(error.status()).isEqualTo(RestStatus.NOT_FOUND));
    }
    return client;
}
Also used : SimpleMessage(org.apache.logging.log4j.message.SimpleMessage) Arrays(java.util.Arrays) RestClientBuilder(org.elasticsearch.client.RestClientBuilder) Level(org.apache.logging.log4j.Level) LogEvent(org.apache.logging.log4j.core.LogEvent) Duration(java.time.Duration) Map(java.util.Map) SearchResponse(org.elasticsearch.action.search.SearchResponse) RequestOptions(org.elasticsearch.client.RequestOptions) Assertions(org.assertj.core.api.Assertions) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException) Log4jLogEvent(org.apache.logging.log4j.core.impl.Log4jLogEvent) SearchHit(org.elasticsearch.search.SearchHit) ExecutionMode(org.junit.jupiter.api.parallel.ExecutionMode) Set(java.util.Set) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Test(org.junit.jupiter.api.Test) Objects(java.util.Objects) List(java.util.List) Stream(java.util.stream.Stream) ThreadLocalRecyclerFactory(org.apache.logging.log4j.layout.template.json.util.ThreadLocalRecyclerFactory) ClusterHealthRequest(org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest) GelfLayout(org.apache.logging.log4j.core.layout.GelfLayout) RestStatus(org.elasticsearch.rest.RestStatus) Layout(org.apache.logging.log4j.core.Layout) Awaitility(org.awaitility.Awaitility) RestClient(org.elasticsearch.client.RestClient) DefaultConfiguration(org.apache.logging.log4j.core.config.DefaultConfiguration) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Appender(org.apache.logging.log4j.core.Appender) SearchRequest(org.elasticsearch.action.search.SearchRequest) Function(java.util.function.Function) EventTemplateAdditionalField(org.apache.logging.log4j.layout.template.json.JsonTemplateLayout.EventTemplateAdditionalField) NetUtils(org.apache.logging.log4j.core.util.NetUtils) Charset(java.nio.charset.Charset) SocketAppender(org.apache.logging.log4j.core.appender.SocketAppender) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) PrintStream(java.io.PrintStream) DeleteIndexRequest(org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest) EcsLayout(co.elastic.logging.log4j2.EcsLayout) ClusterHealthResponse(org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) IOException(java.io.IOException) AcknowledgedResponse(org.elasticsearch.action.support.master.AcknowledgedResponse) RestHighLevelClient(org.elasticsearch.client.RestHighLevelClient) StatusLogger(org.apache.logging.log4j.status.StatusLogger) ClusterHealthStatus(org.elasticsearch.cluster.health.ClusterHealthStatus) Execution(org.junit.jupiter.api.parallel.Execution) HttpHost(org.apache.http.HttpHost) Collections(java.util.Collections) ClusterHealthResponse(org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) ClusterHealthRequest(org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest) HttpHost(org.apache.http.HttpHost) AcknowledgedResponse(org.elasticsearch.action.support.master.AcknowledgedResponse) RestClientBuilder(org.elasticsearch.client.RestClientBuilder) DeleteIndexRequest(org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest) RestHighLevelClient(org.elasticsearch.client.RestHighLevelClient) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException)

Aggregations

ClusterHealthResponse (org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse)123 Settings (org.elasticsearch.common.settings.Settings)29 Client (org.elasticsearch.client.Client)24 ClusterState (org.elasticsearch.cluster.ClusterState)16 ClusterHealthRequest (org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest)15 Test (org.junit.Test)15 IOException (java.io.IOException)13 ClusterStateResponse (org.elasticsearch.action.admin.cluster.state.ClusterStateResponse)12 SearchResponse (org.elasticsearch.action.search.SearchResponse)11 MoveAllocationCommand (org.elasticsearch.cluster.routing.allocation.command.MoveAllocationCommand)10 CloseIndexResponse (org.elasticsearch.action.admin.indices.close.CloseIndexResponse)9 OpenIndexResponse (org.elasticsearch.action.admin.indices.open.OpenIndexResponse)9 CountDownLatch (java.util.concurrent.CountDownLatch)7 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)7 IndexRequestBuilder (org.elasticsearch.action.index.IndexRequestBuilder)7 ShardRouting (org.elasticsearch.cluster.routing.ShardRouting)7 Index (org.elasticsearch.index.Index)7 MockTransportService (org.elasticsearch.test.transport.MockTransportService)6 TransportService (org.elasticsearch.transport.TransportService)6 Path (java.nio.file.Path)5