org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse类的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(14.9k)|赞(0)|评价(0)|浏览(143)

本文整理了Java中org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse类的一些代码示例,展示了ClusterHealthResponse类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ClusterHealthResponse类的具体详情如下:
包路径:org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse
类名称:ClusterHealthResponse

ClusterHealthResponse介绍

暂无

代码示例

代码示例来源:origin: floragunncom/search-guard

@Test
public void testDiscoveryWithoutInitialization() throws Exception {  
  setup(Settings.EMPTY, null, Settings.EMPTY, false);
  Assert.assertEquals(clusterInfo.numNodes, clusterHelper.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getNumberOfNodes());
  Assert.assertEquals(ClusterHealthStatus.GREEN, clusterHelper.nodeClient().admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet().getStatus());
}

代码示例来源:origin: floragunncom/search-guard

try {
  log.debug("waiting for cluster state {} and {} nodes", status.name(), expectedNodeCount);
  final ClusterHealthResponse healthResponse = client.admin().cluster().prepareHealth()
      .setWaitForStatus(status).setTimeout(timeout).setMasterNodeTimeout(timeout).setWaitForNodes("" + expectedNodeCount).execute()
      .actionGet();
  if (healthResponse.isTimedOut()) {
    throw new IOException("cluster state is " + healthResponse.getStatus().name() + " with "
        + healthResponse.getNumberOfNodes() + " nodes");
  } else {
    log.debug("... cluster state ok " + healthResponse.getStatus().name() + " with "
        + healthResponse.getNumberOfNodes() + " nodes");
  org.junit.Assert.assertEquals(expectedNodeCount, healthResponse.getNumberOfNodes());
  final NodesInfoResponse res = client.admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet();

代码示例来源:origin: floragunncom/search-guard

final WhoAmIResponse whoAmIRes = tc.execute(WhoAmIAction.INSTANCE, new WhoAmIRequest()).actionGet();
System.out.println("Connected as "+whoAmIRes.getDn());
  final AcknowledgedResponse response = tc.admin().indices().updateSettings((new UpdateSettingsRequest(index).settings(indexSettings))).actionGet();
  System.out.println("Reload config on all nodes");
  System.out.println("Auto-expand replicas "+(replicaAutoExpand?"enabled":"disabled"));
    chr = tc.admin().cluster().health(chrequest).actionGet();
  } catch (Exception e) {
final boolean timedOut = chr.isTimedOut();
System.out.println("Clustername: "+chr.getClusterName());
System.out.println("Clusterstate: "+chr.getStatus());
System.out.println("Number of nodes: "+chr.getNumberOfNodes());
System.out.println("Number of data nodes: "+chr.getNumberOfDataNodes());
final NodesInfoResponse nodesInfo = tc.admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet();
    if (chrsg.isTimedOut()) {
      System.out.println("ERR: Timed out while waiting for "+index+" index state.");
    if (chrsg.getStatus() == ClusterHealthStatus.RED) {
      System.out.println("ERR: "+index+" index state is RED.");
    if (chrsg.getStatus() == ClusterHealthStatus.YELLOW) {
      System.out.println("INFO: "+index+" index state is YELLOW, it seems you miss some replicas");

代码示例来源:origin: org.neolumin.vertexium/vertexium-elasticsearch-base

@SuppressWarnings("unused")
protected void createIndex(String indexName, boolean storeSourceData) throws IOException {
  CreateIndexResponse createResponse = client.admin().indices().prepareCreate(indexName).execute().actionGet();
  LOGGER.debug(createResponse.toString());
  ClusterHealthResponse health = client.admin().cluster().prepareHealth(indexName)
      .setWaitForGreenStatus()
      .execute().actionGet();
  LOGGER.debug("Index status: " + health.toString());
  if (health.isTimedOut()) {
    LOGGER.warn("timed out waiting for green index status, for index: " + indexName);
  }
}

代码示例来源:origin: apache/streams

@BeforeClass
public void prepareTestPersistUpdater() throws Exception {
 testConfiguration = new ComponentConfigurator<>(ElasticsearchWriterConfiguration.class).detectConfiguration("ElasticsearchPersistUpdaterIT");
 testClient = ElasticsearchClientManager.getInstance(testConfiguration).client();
 ClusterHealthRequest clusterHealthRequest = Requests.clusterHealthRequest();
 ClusterHealthResponse clusterHealthResponse = testClient.admin().cluster().health(clusterHealthRequest).actionGet();
 assertNotEquals(clusterHealthResponse.getStatus(), ClusterHealthStatus.RED);
 IndicesExistsRequest indicesExistsRequest = Requests.indicesExistsRequest(testConfiguration.getIndex());
 IndicesExistsResponse indicesExistsResponse = testClient.admin().indices().exists(indicesExistsRequest).actionGet();
 assertTrue(indicesExistsResponse.isExists());
}

代码示例来源:origin: codelibs/elasticsearch-cluster-runner

public ClusterHealthStatus waitForRelocation() {
  final ClusterHealthRequest request = Requests.clusterHealthRequest()
      .waitForNoRelocatingShards(true);
  final ClusterHealthResponse actionGet = client().admin().cluster()
      .health(request).actionGet();
  if (actionGet.isTimedOut()) {
    onFailure("waitForRelocation timed out, cluster state:\n" + "\n"
        + client().admin().cluster().prepareState().get().getState()
        + "\n" + client().admin().cluster()
            .preparePendingClusterTasks().get(),
        actionGet);
  }
  return actionGet.getStatus();
}

代码示例来源:origin: unipop-graph/unipop

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());
  }
}

代码示例来源:origin: yacy/yacy_grid_mcp

public boolean clusterReady() {
  if (clusterReadyCache) return true;
  ClusterHealthResponse chr = elasticsearchClient.admin().cluster().prepareHealth().get();
  clusterReadyCache = chr.getStatus() != ClusterHealthStatus.RED;
  return clusterReadyCache;
}

代码示例来源:origin: org.codehaus.sonar/sonar-search

@Override
public boolean isReady() {
 return node != null && node.client().admin().cluster().prepareHealth()
  .setWaitForYellowStatus()
  .setTimeout(TimeValue.timeValueSeconds(30L))
  .get()
  .getStatus() != ClusterHealthStatus.RED;
}

代码示例来源:origin: floragunncom/search-guard-ssl

@Test
public void testNodeClientSSL() throws Exception {
  final Settings settings = Settings.builder().put("searchguard.ssl.transport.enabled", true)
      .put(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_ENABLE_OPENSSL_IF_AVAILABLE, allowOpenSSL)
      .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_ENABLE_OPENSSL_IF_AVAILABLE, allowOpenSSL)
      .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_KEYSTORE_ALIAS, "node-0")
      .put("searchguard.ssl.transport.keystore_filepath", getAbsoluteFilePathFromClassPath("node-0-keystore.jks"))
      .put("searchguard.ssl.transport.truststore_filepath", getAbsoluteFilePathFromClassPath("truststore.jks"))
      .put("searchguard.ssl.transport.enforce_hostname_verification", false)
      .put("searchguard.ssl.transport.resolve_hostname", false)
      .build();
  startES(settings);      
  final Settings tcSettings = Settings.builder().put("cluster.name", clustername).put("path.home", ".")
      .put("node.name", "client_node_" + new Random().nextInt())
      .put(settings)// -----
      .build();
  try (Node node = new PluginAwareNode(tcSettings, Netty4Plugin.class, SearchGuardSSLPlugin.class).start()) {
    ClusterHealthResponse res = node.client().admin().cluster().health(new ClusterHealthRequest().waitForNodes("4").timeout(TimeValue.timeValueSeconds(5))).actionGet();
    Assert.assertFalse(res.isTimedOut());
    Assert.assertEquals(4, res.getNumberOfNodes());
    Assert.assertEquals(4, node.client().admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet().getNodes().size());
  }
  Assert.assertFalse(executeSimpleRequest("_nodes/stats?pretty").contains("\"tx_size_in_bytes\" : 0"));
  Assert.assertFalse(executeSimpleRequest("_nodes/stats?pretty").contains("\"rx_count\" : 0"));
  Assert.assertFalse(executeSimpleRequest("_nodes/stats?pretty").contains("\"rx_size_in_bytes\" : 0"));
  Assert.assertFalse(executeSimpleRequest("_nodes/stats?pretty").contains("\"tx_count\" : 0"));
}

代码示例来源:origin: salyh/elasticsearch-imap

private void waitForCluster(final ClusterHealthStatus status, final TimeValue timeout) throws IOException {
  try {
    logger.debug("waiting for cluster state {}", status.name());
    final ClusterHealthResponse healthResponse = client.admin().cluster().prepareHealth().setWaitForStatus(status)
        .setTimeout(timeout).execute().actionGet();
    if (healthResponse.isTimedOut()) {
      throw new IOException("cluster state is " + healthResponse.getStatus().name() + " and not " + status.name()
          + ", cowardly refusing to continue with operations");
    } else {
      logger.debug("... cluster state ok");
    }
  } catch (final ElasticsearchTimeoutException e) {
    throw new IOException("timeout, cluster does not respond to health request, cowardly refusing to continue with operations");
  }
}

代码示例来源:origin: apache/usergrid

/**
 * Check health of this specific index.
 */
@Override
public Health getIndexHealth() {
  try {
    String[] indexNames = this.getIndexes();
    final ActionFuture<ClusterHealthResponse> future =  esProvider.getClient().admin().cluster().health(
      new ClusterHealthRequest( indexNames  ) );
    //only wait 2 seconds max
    ClusterHealthResponse chr = future.actionGet(2000);
    return Health.valueOf( chr.getStatus().name() );
  }
  catch ( Exception ex ) {
    logger.error( "Error connecting to ElasticSearch", ex.getMessage() );
  }
  // this is bad, red alert!
  return Health.RED;
}

代码示例来源:origin: codelibs/elasticsearch-taste

.admin()
    .cluster()
    .prepareHealth(index)
    .setWaitForYellowStatus()
    .setTimeout(
        params.param("timeout",
            DEFAULT_HEALTH_REQUEST_TIMEOUT)).execute()
    .actionGet();
if (healthResponse.isTimedOut()) {
  listener.onError(new OperationFailedException(
      "Failed to create index: " + index + "/" + type));
final PutMappingResponse mappingResponse = client.admin().indices()
    .preparePutMapping(index).setType(type).setSource(builder)
    .execute().actionGet();

代码示例来源:origin: org.springframework.boot/spring-boot-actuator

@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
  ClusterHealthRequest request = Requests.clusterHealthRequest(
      ObjectUtils.isEmpty(this.indices) ? ALL_INDICES : this.indices);
  ClusterHealthResponse response = this.client.admin().cluster().health(request)
      .actionGet(this.responseTimeout);
  switch (response.getStatus()) {
  case GREEN:
  case YELLOW:
    builder.up();
    break;
  case RED:
  default:
    builder.down();
    break;
  }
  builder.withDetail("clusterName", response.getClusterName());
  builder.withDetail("numberOfNodes", response.getNumberOfNodes());
  builder.withDetail("numberOfDataNodes", response.getNumberOfDataNodes());
  builder.withDetail("activePrimaryShards", response.getActivePrimaryShards());
  builder.withDetail("activeShards", response.getActiveShards());
  builder.withDetail("relocatingShards", response.getRelocatingShards());
  builder.withDetail("initializingShards", response.getInitializingShards());
  builder.withDetail("unassignedShards", response.getUnassignedShards());
}

代码示例来源:origin: loklak/loklak_server

public boolean wait_ready(long maxtimemillis, ClusterHealthStatus status) {
  // wait for yellow status
  long start = System.currentTimeMillis();
  boolean is_ready;
  do {
    // wait for yellow status
    ClusterHealthResponse health = elasticsearchClient.admin().cluster().prepareHealth().setWaitForStatus(status).execute().actionGet();
    is_ready = !health.isTimedOut();
    if (!is_ready && System.currentTimeMillis() - start > maxtimemillis) return false;
  } while (!is_ready);
  return is_ready;
}

代码示例来源:origin: com.strapdata.elasticsearch.test/framework

.timeout(timeout)
  .waitForStatus(clusterHealthStatus)
  .waitForEvents(Priority.LANGUID)
  .waitForNoRelocatingShards(true)
  .waitForNoInitializingShards(waitForNoInitializingShards)
  .waitForNodes(Integer.toString(cluster().size()));
ClusterHealthResponse actionGet = client().admin().cluster().health(healthRequest).actionGet();
if (actionGet.isTimedOut()) {
  logger.info("{} timed out, cluster state:\n{}\n{}",
    method,
    client().admin().cluster().prepareState().get().getState(),
    client().admin().cluster().preparePendingClusterTasks().get());
  fail("timed out waiting for " + color + " state");
assertThat("Expected at least " + clusterHealthStatus + " but got " + actionGet.getStatus(),
  actionGet.getStatus().value(), lessThanOrEqualTo(clusterHealthStatus.value()));
logger.debug("indices {} are {}", indices.length == 0 ? "[_all]" : indices, color);
return actionGet.getStatus();

代码示例来源:origin: com.scireum/sirius-search

return;
ClusterHealthResponse res = index.getClient().admin().cluster().prepareHealth().execute().actionGet();
collector.metric("es_nodes", "ES-Nodes", res.getNumberOfNodes(), null, asMetricState(res.getStatus()));
collector.metric("es_initializing_shards",
         "ES-InitializingShards",
         res.getInitializingShards(),
         null,
         res.getInitializingShards() > 0 ? MetricState.YELLOW : MetricState.GRAY);
collector.metric("es_relocating_shards",
         "ES-RelocatingShards",
         res.getRelocatingShards(),
         null,
         res.getRelocatingShards() > 0 ? MetricState.YELLOW : MetricState.GRAY);
collector.metric("es_unassigned_shards",
         "ES-UnassignedShards",
         res.getUnassignedShards(),
         null,
         res.getUnassignedShards() > 0 ? MetricState.RED : MetricState.GRAY);
collector.metric("index_delay_line",
         "index-delay-line",

代码示例来源:origin: com.strapdata.elasticsearch.test/framework

protected void ensureNodeCount(InternalTestCluster cluster) {
  assertFalse("cluster failed to form after disruption was healed", cluster.client().admin().cluster().prepareHealth()
    .setWaitForNodes(String.valueOf(cluster.size()))
    .setWaitForNoRelocatingShards(true)
    .get().isTimedOut());
}

代码示例来源:origin: apache/usergrid

/**
 * Check health of cluster.
 */
@Override
public Health getClusterHealth() {
  try {
    ClusterHealthResponse chr = esProvider.getClient().admin()
      .cluster().health(new ClusterHealthRequest()).get();
    return Health.valueOf( chr.getStatus().name() );
  }
  catch ( Exception ex ) {
    ex.printStackTrace();
    logger.error( "Error connecting to ElasticSearch", ex.getMessage() );
  }
  // this is bad, red alert!
  return Health.RED;
}

代码示例来源:origin: org.elasticsearch/elasticsearch

private Table buildTable(final ClusterHealthResponse health, final RestRequest request) {
    Table t = getTableWithHeader(request);
    t.startRow();
    t.addCell(health.getClusterName());
    t.addCell(health.getStatus().name().toLowerCase(Locale.ROOT));
    t.addCell(health.getNumberOfNodes());
    t.addCell(health.getNumberOfDataNodes());
    t.addCell(health.getActiveShards());
    t.addCell(health.getActivePrimaryShards());
    t.addCell(health.getRelocatingShards());
    t.addCell(health.getInitializingShards());
    t.addCell(health.getUnassignedShards());
    t.addCell(health.getNumberOfPendingTasks());
    t.addCell(health.getTaskMaxWaitingTime().millis() == 0 ? "-" : health.getTaskMaxWaitingTime());
    t.addCell(String.format(Locale.ROOT, "%1.1f%%", health.getActiveShardsPercent()));
    t.endRow();
    return t;
  }
}

相关文章

微信公众号

最新文章

更多