final WhoAmIResponse whoAmIRes = tc.execute(WhoAmIAction.INSTANCE, new WhoAmIRequest()).actionGet(); System.out.println("Connected as "+whoAmIRes.getDn()); tc.execute(ConfigUpdateAction.INSTANCE, new ConfigUpdateRequest(new String[]{"config","roles","rolesmapping","internalusers","actiongroups"})).actionGet(); final AcknowledgedResponse response = tc.admin().indices().updateSettings((new UpdateSettingsRequest(index).settings(indexSettings))).actionGet(); System.out.println("Reload config on all nodes"); System.out.println("Update number of replicas to "+(updateSettings) +" with result: "+response.isAcknowledged()); final boolean successful = tc.admin().cluster() .updateSettings(new ClusterUpdateSettingsRequest() .transientSettings(ENABLE_ALL_ALLOCATIONS_SETTINGS) .persistentSettings(ENABLE_ALL_ALLOCATIONS_SETTINGS)) final ClusterHealthRequest chrequest = new ClusterHealthRequest().timeout(TimeValue.timeValueMinutes(5)); if(!acceptRedCluster) { chrequest.waitForYellowStatus(); chr = tc.admin().cluster().health(chrequest).actionGet(); } catch (Exception e) { final boolean timedOut = chr.isTimedOut(); final NodesInfoResponse nodesInfo = tc.admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet(); ClusterHealthResponse chrsg = tc.admin().cluster().health(new ClusterHealthRequest(index)).actionGet(); if (chrsg.isTimedOut()) {
@Override public ClusterHealthStatus getClusterHealthStatus() { return getTransportClient().admin().cluster() .health(new ClusterHealthRequest().waitForStatus(ClusterHealthStatus.YELLOW).timeout(timeValueSeconds(30))) .actionGet().getStatus(); }
@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()); }
client.admin().indices() .exists(Requests.indicesExistsRequest(indexKey)).actionGet() .isExists(); if (exists && newIndex) { client.admin().indices().prepareDelete(indexKey).get(); client.admin().indices().create( new CreateIndexRequest(indexKey) .settings( .put("index.number_of_shards", numberOfShards) .put("index.number_of_replicas", numberOfReplicas) )).actionGet(); client.admin().cluster().health(new ClusterHealthRequest().waitForGreenStatus()).actionGet();
/** * Wait for yellow state of a cluster. * * @param indices * @return */ public ClusterHealthStatus ensureYellow(final String... indices) { final ClusterHealthResponse actionGet = client().admin().cluster() .health(Requests.clusterHealthRequest(indices) .waitForNoRelocatingShards(true).waitForYellowStatus() .waitForEvents(Priority.LANGUID)) .actionGet(); if (actionGet.isTimedOut()) { onFailure("ensureYellow timed out, cluster state:\n" + "\n" + client().admin().cluster().prepareState().get().getState() + "\n" + client().admin().cluster() .preparePendingClusterTasks().get(), actionGet); } return actionGet.getStatus(); }
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()); } }
final WhoAmIResponse whoAmIRes = tc.execute(WhoAmIAction.INSTANCE, new WhoAmIRequest()).actionGet(); sb.append(Strings.toString(whoAmIRes,true, true)); } catch (Exception e1) { LicenseInfoResponse res = tc.execute(LicenseInfoAction.INSTANCE, new LicenseInfoRequest()).actionGet(); sb.append(Strings.toString(res,true, true)); } catch (Exception e1) { ClusterHealthResponse nir = tc.admin().cluster().health(new ClusterHealthRequest()).actionGet(); sb.append(Strings.toString(nir,true, true)); } catch (Exception e1) { NodesInfoResponse nir = tc.admin().cluster().nodesInfo(new NodesInfoRequest()).actionGet(); sb.append(Strings.toString(nir,true, true)); } catch (Exception e1) { NodesStatsResponse nir = tc.admin().cluster().nodesStats(new NodesStatsRequest()).actionGet(); sb.append(Strings.toString(nir,true, true)); } catch (Exception e1) {
/** * 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; }
.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();
@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")); }
/** * 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; }
public static void waitForCluster(Client client, ClusterHealthStatus statusThreshold, String timeout) throws UnableToStartException { try { ClusterHealthResponse healthResponse = (ClusterHealthResponse) client .execute(ClusterHealthAction.INSTANCE, new ClusterHealthRequest().waitForStatus(statusThreshold).timeout(timeout)) .actionGet(); if (healthResponse != null && healthResponse.isTimedOut()) { throw new UnableToStartException("cluster state is " + healthResponse.getStatus().name() + " and not " + statusThreshold.name() + ", from here on, everything will fail!"); } } catch (ElasticsearchTimeoutException e) { throw new UnableToStartException( "timeout, cluster does not respond to health request, cowardly refusing to continue with operations"); } }
@Override public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException { ClusterHealthRequest clusterHealthRequest = clusterHealthRequest(Strings.splitStringByCommaToArray(request.param("index"))); clusterHealthRequest.local(request.paramAsBoolean("local", clusterHealthRequest.local())); clusterHealthRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterHealthRequest.masterNodeTimeout())); clusterHealthRequest.timeout(request.paramAsTime("timeout", clusterHealthRequest.timeout())); String waitForStatus = request.param("wait_for_status"); if (waitForStatus != null) { clusterHealthRequest.waitForStatus(ClusterHealthStatus.valueOf(waitForStatus.toUpperCase(Locale.ROOT))); } clusterHealthRequest.waitForNoRelocatingShards( request.paramAsBoolean("wait_for_no_relocating_shards", clusterHealthRequest.waitForNoRelocatingShards())); clusterHealthRequest.waitForNoInitializingShards( request.paramAsBoolean("wait_for_no_initializing_shards", clusterHealthRequest.waitForNoRelocatingShards())); if (request.hasParam("wait_for_relocating_shards")) { // wait_for_relocating_shards has been removed in favor of wait_for_no_relocating_shards throw new IllegalArgumentException("wait_for_relocating_shards has been removed, " + "use wait_for_no_relocating_shards [true/false] instead"); } String waitForActiveShards = request.param("wait_for_active_shards"); if (waitForActiveShards != null) { clusterHealthRequest.waitForActiveShards(ActiveShardCount.parseString(waitForActiveShards)); } clusterHealthRequest.waitForNodes(request.param("wait_for_nodes", clusterHealthRequest.waitForNodes())); if (request.param("wait_for_events") != null) { clusterHealthRequest.waitForEvents(Priority.valueOf(request.param("wait_for_events").toUpperCase(Locale.ROOT))); } return channel -> client.admin().cluster().health(clusterHealthRequest, new RestStatusToXContentListener<>(channel)); }
@Override public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) { ClusterHealthRequest clusterHealthRequest = clusterHealthRequest(Strings.splitStringByCommaToArray(request.param("index"))); clusterHealthRequest.local(request.paramAsBoolean("local", clusterHealthRequest.local())); clusterHealthRequest.masterNodeTimeout(request.paramAsTime("master_timeout", clusterHealthRequest.masterNodeTimeout())); clusterHealthRequest.timeout(request.paramAsTime("timeout", clusterHealthRequest.timeout())); String waitForStatus = request.param("wait_for_status"); if (waitForStatus != null) { clusterHealthRequest.waitForStatus(ClusterHealthStatus.valueOf(waitForStatus.toUpperCase(Locale.ROOT))); } clusterHealthRequest.waitForRelocatingShards(request.paramAsInt("wait_for_relocating_shards", clusterHealthRequest.waitForRelocatingShards())); clusterHealthRequest.waitForActiveShards(request.paramAsInt("wait_for_active_shards", clusterHealthRequest.waitForActiveShards())); clusterHealthRequest.waitForNodes(request.param("wait_for_nodes", clusterHealthRequest.waitForNodes())); client.admin().cluster().health(clusterHealthRequest, new RestStatusToXContentListener<ClusterHealthResponse>(channel)); }
@Override public RestChannelConsumer doCatRequest(final RestRequest request, final NodeClient client) { ClusterHealthRequest clusterHealthRequest = new ClusterHealthRequest(); return channel -> client.admin().cluster().health(clusterHealthRequest, new RestResponseListener<ClusterHealthResponse>(channel) { @Override public RestResponse buildResponse(final ClusterHealthResponse health) throws Exception { return RestTable.buildResponse(buildTable(health, request), channel); } }); }
static int prepareResponse(final ClusterHealthRequest request, final ClusterHealthResponse response, final ClusterState clusterState, final IndexNameExpressionResolver indexNameExpressionResolver) { int waitForCounter = 0; if (request.waitForStatus() != null && response.getStatus().value() <= request.waitForStatus().value()) { waitForCounter++; if (request.waitForNoRelocatingShards() && response.getRelocatingShards() == 0) { waitForCounter++; if (request.waitForNoInitializingShards() && response.getInitializingShards() == 0) { waitForCounter++; if (request.waitForActiveShards().equals(ActiveShardCount.NONE) == false) { ActiveShardCount waitForActiveShards = request.waitForActiveShards(); assert waitForActiveShards.equals(ActiveShardCount.DEFAULT) == false : "waitForActiveShards must not be DEFAULT on the request object, instead it should be NONE"; if (request.indices() != null && request.indices().length > 0) { try { indexNameExpressionResolver.concreteIndexNames(clusterState, IndicesOptions.strictExpand(), request.indices()); waitForCounter++; } catch (IndexNotFoundException e) { if (!request.waitForNodes().isEmpty()) { if (request.waitForNodes().startsWith(">=")) { int expected = Integer.parseInt(request.waitForNodes().substring(2)); } else if (request.waitForNodes().startsWith("ge(")) { int expected = Integer.parseInt(request.waitForNodes().substring(3, request.waitForNodes().length() - 1));
private void executeHealth(final ClusterHealthRequest request, final ActionListener<ClusterHealthResponse> listener) { int waitFor = 0; if (request.waitForStatus() != null) { waitFor++; if (request.waitForNoRelocatingShards()) { waitFor++; if (request.waitForNoInitializingShards()) { waitFor++; if (request.waitForActiveShards().equals(ActiveShardCount.NONE) == false) { waitFor++; if (request.waitForNodes().isEmpty() == false) { waitFor++; if (request.indices() != null && request.indices().length > 0) { // check that they actually exists in the meta data waitFor++; if (request.timeout().millis() == 0) { listener.onResponse(getResponse(request, state, waitFor, request.timeout().millis() == 0)); return; stateListener.onNewClusterState(state); } else { observer.waitForNextChange(stateListener, validationPredicate, request.timeout());
@Override public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) { final long timeoutInMillis = Math.max(0, endTimeMS - TimeValue.nsecToMSec(System.nanoTime())); final TimeValue newTimeout = TimeValue.timeValueMillis(timeoutInMillis); request.timeout(newTimeout); executeHealth(request, listener); }
static Request clusterHealth(ClusterHealthRequest healthRequest) { String[] indices = healthRequest.indices() == null ? Strings.EMPTY_ARRAY : healthRequest.indices(); String endpoint = new RequestConverters.EndpointBuilder() .addPathPartAsIs("_cluster/health") .addCommaSeparatedPathParts(indices) .build(); Request request = new Request(HttpGet.METHOD_NAME, endpoint); new RequestConverters.Params(request) .withWaitForStatus(healthRequest.waitForStatus()) .withWaitForNoRelocatingShards(healthRequest.waitForNoRelocatingShards()) .withWaitForNoInitializingShards(healthRequest.waitForNoInitializingShards()) .withWaitForActiveShards(healthRequest.waitForActiveShards(), ActiveShardCount.NONE) .withWaitForNodes(healthRequest.waitForNodes()) .withWaitForEvents(healthRequest.waitForEvents()) .withTimeout(healthRequest.timeout()) .withMasterTimeout(healthRequest.masterNodeTimeout()) .withLocal(healthRequest.local()) .withLevel(healthRequest.level()); return request; } }
@Override protected void masterOperation(Task task, final ClusterHealthRequest request, final ClusterState unusedState, final ActionListener<ClusterHealthResponse> listener) { if (request.waitForEvents() != null) { final long endTimeMS = TimeValue.nsecToMSec(System.nanoTime()) + request.timeout().millis(); if (request.local()) { clusterService.submitStateUpdateTask("cluster_health (wait_for_events [" + request.waitForEvents() + "])", new LocalClusterUpdateTask(request.waitForEvents()) { @Override public ClusterTasksResult<LocalClusterUpdateTask> execute(ClusterState currentState) { clusterService.submitStateUpdateTask("cluster_health (wait_for_events [" + request.waitForEvents() + "])", new ClusterStateUpdateTask(request.waitForEvents()) { @Override public ClusterState execute(ClusterState currentState) {