Search in sources :

Example 21 with RestClient

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.client.RestClient in project elasticsearch by elastic.

the class ElasticsearchHostsSnifferTests method testSniffNodes.

public void testSniffNodes() throws IOException {
    HttpHost httpHost = new HttpHost(httpServer.getAddress().getHostString(), httpServer.getAddress().getPort());
    try (RestClient restClient = RestClient.builder(httpHost).build()) {
        ElasticsearchHostsSniffer sniffer = new ElasticsearchHostsSniffer(restClient, sniffRequestTimeout, scheme);
        try {
            List<HttpHost> sniffedHosts = sniffer.sniffHosts();
            if (sniffResponse.isFailure) {
                fail("sniffNodes should have failed");
            }
            assertThat(sniffedHosts.size(), equalTo(sniffResponse.hosts.size()));
            Iterator<HttpHost> responseHostsIterator = sniffResponse.hosts.iterator();
            for (HttpHost sniffedHost : sniffedHosts) {
                assertEquals(sniffedHost, responseHostsIterator.next());
            }
        } catch (ResponseException e) {
            Response response = e.getResponse();
            if (sniffResponse.isFailure) {
                assertThat(e.getMessage(), containsString("GET " + httpHost + "/_nodes/http?timeout=" + sniffRequestTimeout + "ms"));
                assertThat(e.getMessage(), containsString(Integer.toString(sniffResponse.nodesInfoResponseCode)));
                assertThat(response.getHost(), equalTo(httpHost));
                assertThat(response.getStatusLine().getStatusCode(), equalTo(sniffResponse.nodesInfoResponseCode));
                assertThat(response.getRequestLine().toString(), equalTo("GET /_nodes/http?timeout=" + sniffRequestTimeout + "ms HTTP/1.1"));
            } else {
                fail("sniffNodes should have succeeded: " + response.getStatusLine());
            }
        }
    }
}
Also used : Response(org.elasticsearch.client.Response) ResponseException(org.elasticsearch.client.ResponseException) HttpHost(org.apache.http.HttpHost) RestClient(org.elasticsearch.client.RestClient)

Example 22 with RestClient

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.client.RestClient in project elasticsearch by elastic.

the class SniffOnFailureListenerTests method testSetSniffer.

public void testSetSniffer() throws Exception {
    SniffOnFailureListener listener = new SniffOnFailureListener();
    try {
        listener.onFailure(null);
        fail("should have failed");
    } catch (IllegalStateException e) {
        assertEquals("sniffer was not set, unable to sniff on failure", e.getMessage());
    }
    try {
        listener.setSniffer(null);
        fail("should have failed");
    } catch (NullPointerException e) {
        assertEquals("sniffer must not be null", e.getMessage());
    }
    try (RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build()) {
        try (Sniffer sniffer = Sniffer.builder(restClient).setHostsSniffer(new MockHostsSniffer()).build()) {
            listener.setSniffer(sniffer);
            try {
                listener.setSniffer(sniffer);
                fail("should have failed");
            } catch (IllegalStateException e) {
                assertEquals("sniffer can only be set once", e.getMessage());
            }
            listener.onFailure(new HttpHost("localhost", 9200));
        }
    }
}
Also used : HttpHost(org.apache.http.HttpHost) RestClient(org.elasticsearch.client.RestClient)

Example 23 with RestClient

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.client.RestClient in project elasticsearch by elastic.

the class TransportReindexAction method buildRestClient.

/**
     * Build the {@link RestClient} used for reindexing from remote clusters.
     * @param remoteInfo connection information for the remote cluster
     * @param taskId the id of the current task. This is added to the thread name for easier tracking
     * @param threadCollector a list in which we collect all the threads created by the client
     */
static RestClient buildRestClient(RemoteInfo remoteInfo, long taskId, List<Thread> threadCollector) {
    Header[] clientHeaders = new Header[remoteInfo.getHeaders().size()];
    int i = 0;
    for (Map.Entry<String, String> header : remoteInfo.getHeaders().entrySet()) {
        clientHeaders[i] = new BasicHeader(header.getKey(), header.getValue());
    }
    return RestClient.builder(new HttpHost(remoteInfo.getHost(), remoteInfo.getPort(), remoteInfo.getScheme())).setDefaultHeaders(clientHeaders).setRequestConfigCallback(c -> {
        c.setConnectTimeout(Math.toIntExact(remoteInfo.getConnectTimeout().millis()));
        c.setSocketTimeout(Math.toIntExact(remoteInfo.getSocketTimeout().millis()));
        return c;
    }).setHttpClientConfigCallback(c -> {
        if (remoteInfo.getUsername() != null) {
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(remoteInfo.getUsername(), remoteInfo.getPassword());
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, creds);
            c.setDefaultCredentialsProvider(credentialsProvider);
        }
        AtomicInteger threads = new AtomicInteger();
        c.setThreadFactory(r -> {
            String name = "es-client-" + taskId + "-" + threads.getAndIncrement();
            Thread t = new Thread(r, name);
            threadCollector.add(t);
            return t;
        });
        c.setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(1).build());
        return c;
    }).build();
}
Also used : Versions(org.elasticsearch.common.lucene.uid.Versions) RemoteScrollableHitSource(org.elasticsearch.index.reindex.remote.RemoteScrollableHitSource) IOReactorConfig(org.apache.http.impl.nio.reactor.IOReactorConfig) Property(org.elasticsearch.common.settings.Setting.Property) BiFunction(java.util.function.BiFunction) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) Header(org.apache.http.Header) VersionType(org.elasticsearch.index.VersionType) AutoCreateIndex(org.elasticsearch.action.support.AutoCreateIndex) RemoteInfo(org.elasticsearch.index.reindex.remote.RemoteInfo) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) IndexRequest(org.elasticsearch.action.index.IndexRequest) ClusterState(org.elasticsearch.cluster.ClusterState) Operations(org.apache.lucene.util.automaton.Operations) Settings(org.elasticsearch.common.settings.Settings) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) ParentBulkByScrollTask(org.elasticsearch.action.bulk.byscroll.ParentBulkByScrollTask) ThreadPool(org.elasticsearch.threadpool.ThreadPool) Failure(org.elasticsearch.action.bulk.BulkItemResponse.Failure) Automata(org.apache.lucene.util.automaton.Automata) AbstractAsyncBulkByScrollAction(org.elasticsearch.action.bulk.byscroll.AbstractAsyncBulkByScrollAction) NamedXContentRegistry(org.elasticsearch.common.xcontent.NamedXContentRegistry) WorkingBulkByScrollTask(org.elasticsearch.action.bulk.byscroll.WorkingBulkByScrollTask) BulkByScrollResponse(org.elasticsearch.action.bulk.byscroll.BulkByScrollResponse) ActionFilters(org.elasticsearch.action.support.ActionFilters) Setting(org.elasticsearch.common.settings.Setting) Collections.synchronizedList(java.util.Collections.synchronizedList) Automaton(org.apache.lucene.util.automaton.Automaton) Collections.emptyList(java.util.Collections.emptyList) UncheckedIOException(java.io.UncheckedIOException) Objects(java.util.Objects) List(java.util.List) Logger(org.apache.logging.log4j.Logger) ActionRequestValidationException(org.elasticsearch.action.ActionRequestValidationException) CredentialsProvider(org.apache.http.client.CredentialsProvider) Task(org.elasticsearch.tasks.Task) RestClient(org.elasticsearch.client.RestClient) XContentType(org.elasticsearch.common.xcontent.XContentType) ClusterService(org.elasticsearch.cluster.service.ClusterService) SearchRequest(org.elasticsearch.action.search.SearchRequest) INTERNAL(org.elasticsearch.index.VersionType.INTERNAL) Function(java.util.function.Function) BackoffPolicy(org.elasticsearch.action.bulk.BackoffPolicy) Strings(org.elasticsearch.common.Strings) Inject(org.elasticsearch.common.inject.Inject) ArrayList(java.util.ArrayList) ScrollableHitSource(org.elasticsearch.action.bulk.byscroll.ScrollableHitSource) HandledTransportAction(org.elasticsearch.action.support.HandledTransportAction) ParentTaskAssigningClient(org.elasticsearch.client.ParentTaskAssigningClient) Objects.requireNonNull(java.util.Objects.requireNonNull) Regex(org.elasticsearch.common.regex.Regex) TransportService(org.elasticsearch.transport.TransportService) CharacterRunAutomaton(org.apache.lucene.util.automaton.CharacterRunAutomaton) Script(org.elasticsearch.script.Script) BulkByScrollParallelizationHelper(org.elasticsearch.action.bulk.byscroll.BulkByScrollParallelizationHelper) Client(org.elasticsearch.client.Client) IOException(java.io.IOException) MinimizationOperations(org.apache.lucene.util.automaton.MinimizationOperations) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) XContentParser(org.elasticsearch.common.xcontent.XContentParser) VersionFieldMapper(org.elasticsearch.index.mapper.VersionFieldMapper) AuthScope(org.apache.http.auth.AuthScope) SearchFailure(org.elasticsearch.action.bulk.byscroll.ScrollableHitSource.SearchFailure) BasicHeader(org.apache.http.message.BasicHeader) IndexNameExpressionResolver(org.elasticsearch.cluster.metadata.IndexNameExpressionResolver) HttpHost(org.apache.http.HttpHost) ScriptService(org.elasticsearch.script.ScriptService) ActionListener(org.elasticsearch.action.ActionListener) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpHost(org.apache.http.HttpHost) Map(java.util.Map) BasicHeader(org.apache.http.message.BasicHeader)

Example 24 with RestClient

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.client.RestClient in project elasticsearch by elastic.

the class HttpCompressionIT method testCompressesResponseIfRequested.

public void testCompressesResponseIfRequested() throws IOException {
    RestClient client = client();
    Response response = client.performRequest("GET", "/", new BasicHeader(HttpHeaders.ACCEPT_ENCODING, GZIP_ENCODING));
    assertEquals(200, response.getStatusLine().getStatusCode());
    assertEquals(GZIP_ENCODING, response.getHeader(HttpHeaders.CONTENT_ENCODING));
}
Also used : Response(org.elasticsearch.client.Response) RestClient(org.elasticsearch.client.RestClient) BasicHeader(org.apache.http.message.BasicHeader)

Example 25 with RestClient

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.client.RestClient in project elasticsearch by elastic.

the class IndexingIT method testIndexVersionPropagation.

public void testIndexVersionPropagation() throws Exception {
    Nodes nodes = buildNodeAndVersions();
    assumeFalse("new nodes is empty", nodes.getNewNodes().isEmpty());
    logger.info("cluster discovered: {}", nodes.toString());
    final List<String> bwcNamesList = nodes.getBWCNodes().stream().map(Node::getNodeName).collect(Collectors.toList());
    final String bwcNames = bwcNamesList.stream().collect(Collectors.joining(","));
    Settings.Builder settings = Settings.builder().put(IndexMetaData.INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), 1).put(IndexMetaData.INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), 2).put("index.routing.allocation.include._name", bwcNames);
    final String index = "test";
    final int minUpdates = 5;
    final int maxUpdates = 10;
    createIndex(index, settings.build());
    try (RestClient newNodeClient = buildClient(restClientSettings(), nodes.getNewNodes().stream().map(Node::getPublishAddress).toArray(HttpHost[]::new))) {
        int nUpdates = randomIntBetween(minUpdates, maxUpdates);
        logger.info("indexing docs with [{}] concurrent updates initially", nUpdates);
        final int finalVersionForDoc1 = indexDocWithConcurrentUpdates(index, 1, nUpdates);
        logger.info("allowing shards on all nodes");
        updateIndexSetting(index, Settings.builder().putNull("index.routing.allocation.include._name"));
        ensureGreen();
        assertOK(client().performRequest("POST", index + "/_refresh"));
        List<Shard> shards = buildShards(nodes, newNodeClient);
        for (Shard shard : shards) {
            assertVersion(index, 1, "_only_nodes:" + shard.getNode().getNodeName(), finalVersionForDoc1);
            assertCount(index, "_only_nodes:" + shard.getNode().getNodeName(), 1);
        }
        nUpdates = randomIntBetween(minUpdates, maxUpdates);
        logger.info("indexing docs with [{}] concurrent updates after allowing shards on all nodes", nUpdates);
        final int finalVersionForDoc2 = indexDocWithConcurrentUpdates(index, 2, nUpdates);
        assertOK(client().performRequest("POST", index + "/_refresh"));
        shards = buildShards(nodes, newNodeClient);
        for (Shard shard : shards) {
            assertVersion(index, 2, "_only_nodes:" + shard.getNode().getNodeName(), finalVersionForDoc2);
            assertCount(index, "_only_nodes:" + shard.getNode().getNodeName(), 2);
        }
        Shard primary = buildShards(nodes, newNodeClient).stream().filter(Shard::isPrimary).findFirst().get();
        logger.info("moving primary to new node by excluding {}", primary.getNode().getNodeName());
        updateIndexSetting(index, Settings.builder().put("index.routing.allocation.exclude._name", primary.getNode().getNodeName()));
        ensureGreen();
        nUpdates = randomIntBetween(minUpdates, maxUpdates);
        logger.info("indexing docs with [{}] concurrent updates after moving primary", nUpdates);
        final int finalVersionForDoc3 = indexDocWithConcurrentUpdates(index, 3, nUpdates);
        assertOK(client().performRequest("POST", index + "/_refresh"));
        shards = buildShards(nodes, newNodeClient);
        for (Shard shard : shards) {
            assertVersion(index, 3, "_only_nodes:" + shard.getNode().getNodeName(), finalVersionForDoc3);
            assertCount(index, "_only_nodes:" + shard.getNode().getNodeName(), 3);
        }
        logger.info("setting number of replicas to 0");
        updateIndexSetting(index, Settings.builder().put("index.number_of_replicas", 0));
        ensureGreen();
        nUpdates = randomIntBetween(minUpdates, maxUpdates);
        logger.info("indexing doc with [{}] concurrent updates after setting number of replicas to 0", nUpdates);
        final int finalVersionForDoc4 = indexDocWithConcurrentUpdates(index, 4, nUpdates);
        assertOK(client().performRequest("POST", index + "/_refresh"));
        shards = buildShards(nodes, newNodeClient);
        for (Shard shard : shards) {
            assertVersion(index, 4, "_only_nodes:" + shard.getNode().getNodeName(), finalVersionForDoc4);
            assertCount(index, "_only_nodes:" + shard.getNode().getNodeName(), 4);
        }
        logger.info("setting number of replicas to 1");
        updateIndexSetting(index, Settings.builder().put("index.number_of_replicas", 1));
        ensureGreen();
        nUpdates = randomIntBetween(minUpdates, maxUpdates);
        logger.info("indexing doc with [{}] concurrent updates after setting number of replicas to 1", nUpdates);
        final int finalVersionForDoc5 = indexDocWithConcurrentUpdates(index, 5, nUpdates);
        assertOK(client().performRequest("POST", index + "/_refresh"));
        shards = buildShards(nodes, newNodeClient);
        for (Shard shard : shards) {
            assertVersion(index, 5, "_only_nodes:" + shard.getNode().getNodeName(), finalVersionForDoc5);
            assertCount(index, "_only_nodes:" + shard.getNode().getNodeName(), 5);
        }
        // the number of documents on the primary and on the recovered replica should match the number of indexed documents
        assertCount(index, "_primary", 5);
        assertCount(index, "_replica", 5);
    }
}
Also used : HttpHost(org.apache.http.HttpHost) RestClient(org.elasticsearch.client.RestClient) Settings(org.elasticsearch.common.settings.Settings) IndexSettings(org.elasticsearch.index.IndexSettings)

Aggregations

RestClient (org.elasticsearch.client.RestClient)41 HttpHost (org.apache.http.HttpHost)21 IOException (java.io.IOException)15 Response (org.elasticsearch.client.Response)9 HttpEntity (org.apache.http.HttpEntity)6 BasicHeader (org.apache.http.message.BasicHeader)6 ResponseException (org.elasticsearch.client.ResponseException)6 Test (org.junit.jupiter.api.Test)6 RestClientBuilder (org.elasticsearch.client.RestClientBuilder)5 RestHighLevelClient (org.elasticsearch.client.RestHighLevelClient)5 Test (org.junit.Test)5 ArrayList (java.util.ArrayList)4 AuthScope (org.apache.http.auth.AuthScope)4 ClientProtocolException (org.apache.http.client.ClientProtocolException)4 SearchRequest (org.elasticsearch.action.search.SearchRequest)4 List (java.util.List)3 StringEntity (org.apache.http.entity.StringEntity)3 IndexRequest (org.elasticsearch.action.index.IndexRequest)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 TestHazelcastFactory (com.hazelcast.client.test.TestHazelcastFactory)2