Search in sources :

Example 76 with Client

use of org.elasticsearch.client.Client in project elasticsearch by elastic.

the class Node method close.

// During concurrent close() calls we want to make sure that all of them return after the node has completed it's shutdown cycle.
// If not, the hook that is added in Bootstrap#setup() will be useless: close() might not be executed, in case another (for example api) call
// to close() has already set some lifecycles to stopped. In this case the process will be terminated even if the first call to close() has not finished yet.
@Override
public synchronized void close() throws IOException {
    if (lifecycle.started()) {
        stop();
    }
    if (!lifecycle.moveToClosed()) {
        return;
    }
    Logger logger = Loggers.getLogger(Node.class, NODE_NAME_SETTING.get(settings));
    logger.info("closing ...");
    List<Closeable> toClose = new ArrayList<>();
    StopWatch stopWatch = new StopWatch("node_close");
    toClose.add(() -> stopWatch.start("tribe"));
    toClose.add(injector.getInstance(TribeService.class));
    toClose.add(() -> stopWatch.stop().start("node_service"));
    toClose.add(injector.getInstance(NodeService.class));
    toClose.add(() -> stopWatch.stop().start("http"));
    if (NetworkModule.HTTP_ENABLED.get(settings)) {
        toClose.add(injector.getInstance(HttpServerTransport.class));
    }
    toClose.add(() -> stopWatch.stop().start("snapshot_service"));
    toClose.add(injector.getInstance(SnapshotsService.class));
    toClose.add(injector.getInstance(SnapshotShardsService.class));
    toClose.add(() -> stopWatch.stop().start("client"));
    Releasables.close(injector.getInstance(Client.class));
    toClose.add(() -> stopWatch.stop().start("indices_cluster"));
    toClose.add(injector.getInstance(IndicesClusterStateService.class));
    toClose.add(() -> stopWatch.stop().start("indices"));
    toClose.add(injector.getInstance(IndicesService.class));
    // close filter/fielddata caches after indices
    toClose.add(injector.getInstance(IndicesStore.class));
    toClose.add(() -> stopWatch.stop().start("routing"));
    toClose.add(injector.getInstance(RoutingService.class));
    toClose.add(() -> stopWatch.stop().start("cluster"));
    toClose.add(injector.getInstance(ClusterService.class));
    toClose.add(() -> stopWatch.stop().start("node_connections_service"));
    toClose.add(injector.getInstance(NodeConnectionsService.class));
    toClose.add(() -> stopWatch.stop().start("discovery"));
    toClose.add(injector.getInstance(Discovery.class));
    toClose.add(() -> stopWatch.stop().start("monitor"));
    toClose.add(injector.getInstance(MonitorService.class));
    toClose.add(() -> stopWatch.stop().start("gateway"));
    toClose.add(injector.getInstance(GatewayService.class));
    toClose.add(() -> stopWatch.stop().start("search"));
    toClose.add(injector.getInstance(SearchService.class));
    toClose.add(() -> stopWatch.stop().start("transport"));
    toClose.add(injector.getInstance(TransportService.class));
    toClose.add(() -> stopWatch.stop().start("search_transport_service"));
    toClose.add(injector.getInstance(SearchTransportService.class));
    for (LifecycleComponent plugin : pluginLifecycleComponents) {
        toClose.add(() -> stopWatch.stop().start("plugin(" + plugin.getClass().getName() + ")"));
        toClose.add(plugin);
    }
    toClose.addAll(pluginsService.filterPlugins(Plugin.class));
    toClose.add(() -> stopWatch.stop().start("script"));
    toClose.add(injector.getInstance(ScriptService.class));
    toClose.add(() -> stopWatch.stop().start("thread_pool"));
    // TODO this should really use ThreadPool.terminate()
    toClose.add(() -> injector.getInstance(ThreadPool.class).shutdown());
    toClose.add(() -> {
        try {
            injector.getInstance(ThreadPool.class).awaitTermination(10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
        // ignore
        }
    });
    toClose.add(() -> stopWatch.stop().start("thread_pool_force_shutdown"));
    toClose.add(() -> injector.getInstance(ThreadPool.class).shutdownNow());
    toClose.add(() -> stopWatch.stop());
    toClose.add(injector.getInstance(NodeEnvironment.class));
    toClose.add(injector.getInstance(BigArrays.class));
    if (logger.isTraceEnabled()) {
        logger.trace("Close times for each service:\n{}", stopWatch.prettyPrint());
    }
    IOUtils.close(toClose);
    logger.info("closed");
}
Also used : TribeService(org.elasticsearch.tribe.TribeService) SnapshotsService(org.elasticsearch.snapshots.SnapshotsService) SnapshotShardsService(org.elasticsearch.snapshots.SnapshotShardsService) NodeConnectionsService(org.elasticsearch.cluster.NodeConnectionsService) NodeEnvironment(org.elasticsearch.env.NodeEnvironment) MonitorService(org.elasticsearch.monitor.MonitorService) Closeable(java.io.Closeable) IndicesStore(org.elasticsearch.indices.store.IndicesStore) ArrayList(java.util.ArrayList) ThreadPool(org.elasticsearch.threadpool.ThreadPool) Logger(org.apache.logging.log4j.Logger) DeprecationLogger(org.elasticsearch.common.logging.DeprecationLogger) HttpServerTransport(org.elasticsearch.http.HttpServerTransport) ScriptService(org.elasticsearch.script.ScriptService) IndicesClusterStateService(org.elasticsearch.indices.cluster.IndicesClusterStateService) LifecycleComponent(org.elasticsearch.common.component.LifecycleComponent) SearchService(org.elasticsearch.search.SearchService) SearchTransportService(org.elasticsearch.action.search.SearchTransportService) Client(org.elasticsearch.client.Client) NodeClient(org.elasticsearch.client.node.NodeClient) RoutingService(org.elasticsearch.cluster.routing.RoutingService) Discovery(org.elasticsearch.discovery.Discovery) IndicesService(org.elasticsearch.indices.IndicesService) StopWatch(org.elasticsearch.common.StopWatch) GatewayService(org.elasticsearch.gateway.GatewayService) BigArrays(org.elasticsearch.common.util.BigArrays) ClusterService(org.elasticsearch.cluster.service.ClusterService) SearchTransportService(org.elasticsearch.action.search.SearchTransportService) TransportService(org.elasticsearch.transport.TransportService) ClusterPlugin(org.elasticsearch.plugins.ClusterPlugin) SearchPlugin(org.elasticsearch.plugins.SearchPlugin) RepositoryPlugin(org.elasticsearch.plugins.RepositoryPlugin) AnalysisPlugin(org.elasticsearch.plugins.AnalysisPlugin) IngestPlugin(org.elasticsearch.plugins.IngestPlugin) ScriptPlugin(org.elasticsearch.plugins.ScriptPlugin) NetworkPlugin(org.elasticsearch.plugins.NetworkPlugin) DiscoveryPlugin(org.elasticsearch.plugins.DiscoveryPlugin) MapperPlugin(org.elasticsearch.plugins.MapperPlugin) ActionPlugin(org.elasticsearch.plugins.ActionPlugin) Plugin(org.elasticsearch.plugins.Plugin)

Example 77 with Client

use of org.elasticsearch.client.Client in project elasticsearch by elastic.

the class BlobStoreRepositoryTests method testRetrieveSnapshots.

public void testRetrieveSnapshots() throws Exception {
    final Client client = client();
    final Path location = ESIntegTestCase.randomRepoPath(node().settings());
    final String repositoryName = "test-repo";
    logger.info("-->  creating repository");
    PutRepositoryResponse putRepositoryResponse = client.admin().cluster().preparePutRepository(repositoryName).setType("fs").setSettings(Settings.builder().put(node().settings()).put("location", location)).get();
    assertThat(putRepositoryResponse.isAcknowledged(), equalTo(true));
    logger.info("--> creating an index and indexing documents");
    final String indexName = "test-idx";
    createIndex(indexName);
    ensureGreen();
    int numDocs = randomIntBetween(10, 20);
    for (int i = 0; i < numDocs; i++) {
        String id = Integer.toString(i);
        client().prepareIndex(indexName, "type1", id).setSource("text", "sometext").get();
    }
    client().admin().indices().prepareFlush(indexName).get();
    logger.info("--> create first snapshot");
    CreateSnapshotResponse createSnapshotResponse = client.admin().cluster().prepareCreateSnapshot(repositoryName, "test-snap-1").setWaitForCompletion(true).setIndices(indexName).get();
    final SnapshotId snapshotId1 = createSnapshotResponse.getSnapshotInfo().snapshotId();
    logger.info("--> create second snapshot");
    createSnapshotResponse = client.admin().cluster().prepareCreateSnapshot(repositoryName, "test-snap-2").setWaitForCompletion(true).setIndices(indexName).get();
    final SnapshotId snapshotId2 = createSnapshotResponse.getSnapshotInfo().snapshotId();
    logger.info("--> make sure the node's repository can resolve the snapshots");
    final RepositoriesService repositoriesService = getInstanceFromNode(RepositoriesService.class);
    @SuppressWarnings("unchecked") final BlobStoreRepository repository = (BlobStoreRepository) repositoriesService.repository(repositoryName);
    final List<SnapshotId> originalSnapshots = Arrays.asList(snapshotId1, snapshotId2);
    List<SnapshotId> snapshotIds = repository.getRepositoryData().getSnapshotIds().stream().sorted((s1, s2) -> s1.getName().compareTo(s2.getName())).collect(Collectors.toList());
    assertThat(snapshotIds, equalTo(originalSnapshots));
}
Also used : Path(java.nio.file.Path) RepositoryDataTests.generateRandomRepoData(org.elasticsearch.repositories.RepositoryDataTests.generateRandomRepoData) SnapshotId(org.elasticsearch.snapshots.SnapshotId) ESSingleNodeTestCase(org.elasticsearch.test.ESSingleNodeTestCase) Arrays(java.util.Arrays) Client(org.elasticsearch.client.Client) UUIDs(org.elasticsearch.common.UUIDs) IOException(java.io.IOException) RepositoriesService(org.elasticsearch.repositories.RepositoriesService) IndexId(org.elasticsearch.repositories.IndexId) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) PutRepositoryResponse(org.elasticsearch.action.admin.cluster.repositories.put.PutRepositoryResponse) List(java.util.List) Settings(org.elasticsearch.common.settings.Settings) ESIntegTestCase(org.elasticsearch.test.ESIntegTestCase) Matchers.equalTo(org.hamcrest.Matchers.equalTo) CreateSnapshotResponse(org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse) Path(java.nio.file.Path) Collections(java.util.Collections) RepositoryException(org.elasticsearch.repositories.RepositoryException) RepositoryData(org.elasticsearch.repositories.RepositoryData) SnapshotId(org.elasticsearch.snapshots.SnapshotId) CreateSnapshotResponse(org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse) RepositoriesService(org.elasticsearch.repositories.RepositoriesService) PutRepositoryResponse(org.elasticsearch.action.admin.cluster.repositories.put.PutRepositoryResponse) Client(org.elasticsearch.client.Client)

Example 78 with Client

use of org.elasticsearch.client.Client in project elasticsearch by elastic.

the class QuorumGatewayIT method testQuorumRecovery.

public void testQuorumRecovery() throws Exception {
    logger.info("--> starting 3 nodes");
    // we are shutting down nodes - make sure we don't have 2 clusters if we test network
    internalCluster().startNodes(3);
    createIndex("test");
    ensureGreen();
    final NumShards test = getNumShards("test");
    logger.info("--> indexing...");
    client().prepareIndex("test", "type1", "1").setSource(jsonBuilder().startObject().field("field", "value1").endObject()).get();
    //We don't check for failures in the flush response: if we do we might get the following:
    // FlushNotAllowedEngineException[[test][1] recovery is in progress, flush [COMMIT_TRANSLOG] is not allowed]
    flush();
    client().prepareIndex("test", "type1", "2").setSource(jsonBuilder().startObject().field("field", "value2").endObject()).get();
    refresh();
    for (int i = 0; i < 10; i++) {
        assertHitCount(client().prepareSearch().setSize(0).setQuery(matchAllQuery()).get(), 2L);
    }
    logger.info("--> restart all nodes");
    internalCluster().fullRestart(new RestartCallback() {

        @Override
        public Settings onNodeStopped(String nodeName) throws Exception {
            return null;
        }

        @Override
        public void doAfterNodes(int numNodes, final Client activeClient) throws Exception {
            if (numNodes == 1) {
                assertTrue(awaitBusy(() -> {
                    logger.info("--> running cluster_health (wait for the shards to startup)");
                    ClusterHealthResponse clusterHealth = activeClient.admin().cluster().health(clusterHealthRequest().waitForYellowStatus().waitForNodes("2").waitForActiveShards(test.numPrimaries * 2)).actionGet();
                    logger.info("--> done cluster_health, status {}", clusterHealth.getStatus());
                    return (!clusterHealth.isTimedOut()) && clusterHealth.getStatus() == ClusterHealthStatus.YELLOW;
                }, 30, TimeUnit.SECONDS));
                logger.info("--> one node is closed -- index 1 document into the remaining nodes");
                activeClient.prepareIndex("test", "type1", "3").setSource(jsonBuilder().startObject().field("field", "value3").endObject()).get();
                assertNoFailures(activeClient.admin().indices().prepareRefresh().get());
                for (int i = 0; i < 10; i++) {
                    assertHitCount(activeClient.prepareSearch().setSize(0).setQuery(matchAllQuery()).get(), 3L);
                }
            }
        }
    });
    logger.info("--> all nodes are started back, verifying we got the latest version");
    logger.info("--> running cluster_health (wait for the shards to startup)");
    ensureGreen();
    for (int i = 0; i < 10; i++) {
        assertHitCount(client().prepareSearch().setSize(0).setQuery(matchAllQuery()).get(), 3L);
    }
}
Also used : ClusterHealthResponse(org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse) RestartCallback(org.elasticsearch.test.InternalTestCluster.RestartCallback) Client(org.elasticsearch.client.Client) Settings(org.elasticsearch.common.settings.Settings)

Example 79 with Client

use of org.elasticsearch.client.Client in project elasticsearch by elastic.

the class RecoverAfterNodesIT method testRecoverAfterNodes.

public void testRecoverAfterNodes() throws Exception {
    logger.info("--> start node (1)");
    Client clientNode1 = startNode(Settings.builder().put("gateway.recover_after_nodes", 3), 1);
    assertThat(clientNode1.admin().cluster().prepareState().setLocal(true).execute().actionGet().getState().blocks().global(ClusterBlockLevel.METADATA_WRITE), hasItem(GatewayService.STATE_NOT_RECOVERED_BLOCK));
    logger.info("--> start node (2)");
    Client clientNode2 = startNode(Settings.builder().put("gateway.recover_after_nodes", 3), 1);
    Thread.sleep(BLOCK_WAIT_TIMEOUT.millis());
    assertThat(clientNode1.admin().cluster().prepareState().setLocal(true).execute().actionGet().getState().blocks().global(ClusterBlockLevel.METADATA_WRITE), hasItem(GatewayService.STATE_NOT_RECOVERED_BLOCK));
    assertThat(clientNode2.admin().cluster().prepareState().setLocal(true).execute().actionGet().getState().blocks().global(ClusterBlockLevel.METADATA_WRITE), hasItem(GatewayService.STATE_NOT_RECOVERED_BLOCK));
    logger.info("--> start node (3)");
    Client clientNode3 = startNode(Settings.builder().put("gateway.recover_after_nodes", 3), 1);
    assertThat(waitForNoBlocksOnNode(BLOCK_WAIT_TIMEOUT, clientNode1).isEmpty(), equalTo(true));
    assertThat(waitForNoBlocksOnNode(BLOCK_WAIT_TIMEOUT, clientNode2).isEmpty(), equalTo(true));
    assertThat(waitForNoBlocksOnNode(BLOCK_WAIT_TIMEOUT, clientNode3).isEmpty(), equalTo(true));
}
Also used : Client(org.elasticsearch.client.Client)

Example 80 with Client

use of org.elasticsearch.client.Client in project elasticsearch by elastic.

the class RecoverAfterNodesIT method testRecoverAfterDataNodes.

public void testRecoverAfterDataNodes() throws Exception {
    logger.info("--> start master_node (1)");
    Client master1 = startNode(Settings.builder().put("gateway.recover_after_data_nodes", 2).put(Node.NODE_DATA_SETTING.getKey(), false).put(Node.NODE_MASTER_SETTING.getKey(), true), 1);
    assertThat(master1.admin().cluster().prepareState().setLocal(true).execute().actionGet().getState().blocks().global(ClusterBlockLevel.METADATA_WRITE), hasItem(GatewayService.STATE_NOT_RECOVERED_BLOCK));
    logger.info("--> start data_node (1)");
    Client data1 = startNode(Settings.builder().put("gateway.recover_after_data_nodes", 2).put(Node.NODE_DATA_SETTING.getKey(), true).put(Node.NODE_MASTER_SETTING.getKey(), false), 1);
    assertThat(master1.admin().cluster().prepareState().setLocal(true).execute().actionGet().getState().blocks().global(ClusterBlockLevel.METADATA_WRITE), hasItem(GatewayService.STATE_NOT_RECOVERED_BLOCK));
    assertThat(data1.admin().cluster().prepareState().setLocal(true).execute().actionGet().getState().blocks().global(ClusterBlockLevel.METADATA_WRITE), hasItem(GatewayService.STATE_NOT_RECOVERED_BLOCK));
    logger.info("--> start master_node (2)");
    Client master2 = startNode(Settings.builder().put("gateway.recover_after_data_nodes", 2).put(Node.NODE_DATA_SETTING.getKey(), false).put(Node.NODE_MASTER_SETTING.getKey(), true), 1);
    assertThat(master2.admin().cluster().prepareState().setLocal(true).execute().actionGet().getState().blocks().global(ClusterBlockLevel.METADATA_WRITE), hasItem(GatewayService.STATE_NOT_RECOVERED_BLOCK));
    assertThat(data1.admin().cluster().prepareState().setLocal(true).execute().actionGet().getState().blocks().global(ClusterBlockLevel.METADATA_WRITE), hasItem(GatewayService.STATE_NOT_RECOVERED_BLOCK));
    assertThat(master2.admin().cluster().prepareState().setLocal(true).execute().actionGet().getState().blocks().global(ClusterBlockLevel.METADATA_WRITE), hasItem(GatewayService.STATE_NOT_RECOVERED_BLOCK));
    logger.info("--> start data_node (2)");
    Client data2 = startNode(Settings.builder().put("gateway.recover_after_data_nodes", 2).put(Node.NODE_DATA_SETTING.getKey(), true).put(Node.NODE_MASTER_SETTING.getKey(), false), 1);
    assertThat(waitForNoBlocksOnNode(BLOCK_WAIT_TIMEOUT, master1).isEmpty(), equalTo(true));
    assertThat(waitForNoBlocksOnNode(BLOCK_WAIT_TIMEOUT, master2).isEmpty(), equalTo(true));
    assertThat(waitForNoBlocksOnNode(BLOCK_WAIT_TIMEOUT, data1).isEmpty(), equalTo(true));
    assertThat(waitForNoBlocksOnNode(BLOCK_WAIT_TIMEOUT, data2).isEmpty(), equalTo(true));
}
Also used : Client(org.elasticsearch.client.Client)

Aggregations

Client (org.elasticsearch.client.Client)164 CreateSnapshotResponse (org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse)42 Settings (org.elasticsearch.common.settings.Settings)38 Path (java.nio.file.Path)30 RestoreSnapshotResponse (org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotResponse)28 PutRepositoryResponse (org.elasticsearch.action.admin.cluster.repositories.put.PutRepositoryResponse)24 ArrayList (java.util.ArrayList)23 ClusterHealthResponse (org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse)23 IOException (java.io.IOException)20 Matchers.containsString (org.hamcrest.Matchers.containsString)20 IndexRequestBuilder (org.elasticsearch.action.index.IndexRequestBuilder)18 ClusterState (org.elasticsearch.cluster.ClusterState)17 ExecutionException (java.util.concurrent.ExecutionException)16 SearchResponse (org.elasticsearch.action.search.SearchResponse)14 ClusterAdminClient (org.elasticsearch.client.ClusterAdminClient)13 ClusterService (org.elasticsearch.cluster.service.ClusterService)10 List (java.util.List)9 ActionRequestValidationException (org.elasticsearch.action.ActionRequestValidationException)9 CloseIndexResponse (org.elasticsearch.action.admin.indices.close.CloseIndexResponse)9 OpenIndexResponse (org.elasticsearch.action.admin.indices.open.OpenIndexResponse)9